diff --git a/code_src/rise_code/sim_pipeline.egg-info/SOURCES.txt b/code_src/rise_code/sim_pipeline.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..8ce14502e9d266d866db5e89406cfa0e1b35a868 --- /dev/null +++ b/code_src/rise_code/sim_pipeline.egg-info/SOURCES.txt @@ -0,0 +1,23 @@ +README.md +setup.py +sim_pipeline/__init__.py +sim_pipeline/reward_wrapper.py +sim_pipeline.egg-info/PKG-INFO +sim_pipeline.egg-info/SOURCES.txt +sim_pipeline.egg-info/dependency_links.txt +sim_pipeline.egg-info/top_level.txt +sim_pipeline/configs/__init__.py +sim_pipeline/configs/constants.py +sim_pipeline/configs/default.py +sim_pipeline/configs/parse_config.py +sim_pipeline/envs/__init__.py +sim_pipeline/envs/initialization_wrapper.py +sim_pipeline/envs/make_env.py +sim_pipeline/envs/reward_wrapper.py +sim_pipeline/envs/robosuite_wrapper.py +sim_pipeline/reward_functions/__init__.py +sim_pipeline/reward_functions/reward_registry.py +sim_pipeline/reward_functions/square_reward.py +sim_pipeline/success_functions/__init__.py +sim_pipeline/success_functions/square_success.py +sim_pipeline/success_functions/success_registry.py \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline.egg-info/dependency_links.txt b/code_src/rise_code/sim_pipeline.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/code_src/rise_code/sim_pipeline.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/code_src/rise_code/sim_pipeline.egg-info/top_level.txt b/code_src/rise_code/sim_pipeline.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..0ce7128248cdc2484ea1b060fb74072a90550444 --- /dev/null +++ b/code_src/rise_code/sim_pipeline.egg-info/top_level.txt @@ -0,0 +1 @@ +sim_pipeline diff --git a/code_src/rise_code/sim_pipeline/eval/rollout_policies/combined/heuristic_reset_split_policy.py b/code_src/rise_code/sim_pipeline/eval/rollout_policies/combined/heuristic_reset_split_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..8e679369f123ad698e900fed29e875d4bf79e03e --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout_policies/combined/heuristic_reset_split_policy.py @@ -0,0 +1,45 @@ +from sim_pipeline.eval.rollout_policies.rollout_policy import RolloutPolicy +from sim_pipeline.eval.rollout_policies.pd_rollout_policy import PDRolloutPolicy + +from sim_pipeline.eval.rollout_policies.composite_rollout_policy import CompositeRolloutPolicy + +class HeuristicResetSplitPolicy(CompositeRolloutPolicy): + def __init__(self, policies: list[RolloutPolicy], n_envs=1, reset_steps=400, init_run_steps=35): + assert len(policies) == 3 + assert isinstance(policies[1], PDRolloutPolicy) + super().__init__(policies=policies, init_policy_index=0, n_envs=n_envs) + self.reset_steps = reset_steps + self.init_run_steps = init_run_steps + self.steps = 0 + self.curr_policy = 0 + + def reset(self): + super().reset() + self.steps = 0 + self.curr_policy = 0 + + def predict(self, obs, *args, **kwargs): + self.steps += 1 + return super().predict(obs, *args, **kwargs) + + def switch_policy(self, obs, act, env) -> bool: + switched = False + if self.steps < self.init_run_steps: + switched = False + elif self.init_run_steps <= self.steps < self.init_run_steps + self.reset_steps: + self.env_to_policy_idx = {env: 1 for env in range(self.n_envs)} + self.n_obs_steps = self.n_obs_steps_dict[1] + self.action_chunking = self.action_chunking_dict[1] + if self.curr_policy != 1: + self.curr_policy = 1 + switched = True + elif self.steps >= self.init_run_steps + self.reset_steps: + self.env_to_policy_idx = {env: 2 for env in range(self.n_envs)} + self.n_obs_steps = self.n_obs_steps_dict[2] + self.action_chunking = self.action_chunking_dict[2] + if self.curr_policy != 2: + self.curr_policy = 2 + switched = True + else: + raise ValueError(f'Invalid state {self.steps}') + return switched \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/eval/rollout_policies/composite_rollout_policy.py b/code_src/rise_code/sim_pipeline/eval/rollout_policies/composite_rollout_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c6d27050ce4bc32b20f384d84e8a9cd2c65e780a --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout_policies/composite_rollout_policy.py @@ -0,0 +1,49 @@ +import numpy as np + +from sim_pipeline.eval.rollout_policies.rollout_policy import RolloutPolicy + +class CompositeRolloutPolicy(RolloutPolicy): + def __init__(self, policies: list[RolloutPolicy], init_policy_index: int = 0, n_envs: int = 1): + self.policies = policies + self.n_policies = len(policies) + self.n_envs = n_envs + self.init_policy_index = init_policy_index + self.env_to_policy_idx = {i: self.init_policy_index for i in range(n_envs)} + + self.action_chunking_dict = {i: policy.action_chunking for i, policy in enumerate(policies)} + self.n_obs_steps_dict = {i: policy.n_obs_steps for i, policy in enumerate(policies)} + self.action_chunking = self.action_chunking_dict[self.init_policy_index] + self.n_obs_steps = self.n_obs_steps_dict[self.init_policy_index] + self.is_composite = True + + def predict(self, obs, *args, **kwargs): + # faster for not vectorized case + if self.n_envs == 1: + return self.policies[self.env_to_policy_idx[0]].predict(obs, *args, **kwargs) + + result = [None for _ in range(self.n_envs)] + for policy_idx in self.env_to_policy_idx.values(): + envs_with_policy = np.array([env_idx for env_idx, p_idx in self.env_to_policy_idx.items() if p_idx == policy_idx]) + if isinstance(obs, dict): + obs_env = { + key: obs[key][envs_with_policy] for key in obs.keys() + } + else: + obs_env = obs[envs_with_policy] + + act_env = self.policies[policy_idx].predict(obs_env, *args, **kwargs) + + for env_idx, act in zip(envs_with_policy, act_env): + result[env_idx] = act + return np.array(result) + + def reset(self): + for policy in self.policies: + policy.reset() + self.env_to_policy_idx = {i: self.init_policy_index for i in range(self.n_envs)} + self.action_chunking = self.action_chunking_dict[self.init_policy_index] + self.n_obs_steps = self.n_obs_steps_dict[self.init_policy_index] + + def switch_policy(self, obs, act, env): + raise NotImplementedError + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/eval/rollout_policies/diffusion_rollout_policy.py b/code_src/rise_code/sim_pipeline/eval/rollout_policies/diffusion_rollout_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..cbeebf00e8e48346ad952478c78d12a8249beb78 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout_policies/diffusion_rollout_policy.py @@ -0,0 +1,57 @@ +import numpy as np +import torch + +from diffusion_policy.common.pytorch_util import dict_apply +from sim_pipeline.utils.rollout_utils import filter_obs_keys +from sim_pipeline.eval.rollout_policies.rollout_policy import RolloutPolicy + +class DiffusionRolloutPolicy(RolloutPolicy): + def __init__( + self, + policy, + action_chunking: bool = True, + n_obs_steps: int | None = 2, + obs_keys: list[str] | None = None, + lowdim: bool = False, + ): + super().__init__(policy, action_chunking=action_chunking, n_obs_steps=n_obs_steps) + self.obs_keys = obs_keys + self.lowdim = lowdim + + def reset(self): + self.policy.reset() + + def predict(self, obs, *args, **kwargs): + if not isinstance(obs, dict): + raise ValueError("Diffusion policy expects dict input") + np_obs_dict = filter_obs_keys(obs, obs_keys=self.obs_keys) + if self.lowdim: + obs = np.concatenate([ + np_obs_dict[key] for key in self.obs_keys + ], axis=-1) + np_obs_dict = {'obs': obs} + + # device transfer + obs_dict = dict_apply(np_obs_dict, + lambda x: torch.from_numpy(x).to( + device=self.policy.device)) + + with torch.no_grad(): + action_dict = self.policy.predict_action(obs_dict) + + # device_transfer + np_action_dict = dict_apply(action_dict, + lambda x: x.detach().to('cpu').numpy()) + + action = np_action_dict['action'] + if not np.all(np.isfinite(action)): + print(action) + raise RuntimeError("Nan or Inf action") + + # TODO: must enable to support abs action + # if self.abs_action: + # action = self.undo_transform_action(action) + + # shape is (n_envs, execution_horizon, action_dim) + return action + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/eval/rollout_policies/ifql_rollout_policy.py b/code_src/rise_code/sim_pipeline/eval/rollout_policies/ifql_rollout_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..877927ba80867dfa5fa9905d2516e089ac6b6f24 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout_policies/ifql_rollout_policy.py @@ -0,0 +1,141 @@ +"""IFQL as published: its own flow actor proposing N candidates, its own critic picking one (gen_q#264). + +This is column (a) of the flagship's IFQL pair. Column (b) -- the IFQL critic ranking the RISE actor's +128 chunks -- needs no rollout policy at all: it is `training.rsm_backend=ifql` in the existing best-of-N +planner (robomimic/algo/rsm_planner.IFQLCriticBackend). + +Per control step: + 1. the current frame's pooled frozen-DINOv2 state is computed exactly as the RSM scorer computes it + (robomimic/algo/rsm_scorer.PooledDinoState on agentview_image + robot0_eye_in_hand_image + proprio, + z-scored with the task cache's feat_stats.npz); + 2. `num_samples` unit normals are integrated through the behavioural flow with `flow_steps` Euler steps + and clipped to [-1, 1]; + 3. the IFQL critic scores all of them and the arg-max is executed -- one 7-d action per env step, which + is what the published agent does (its flow actor is a per-step actor, not a chunked one). + +RANDOMNESS. The candidate noise comes from a torch.Generator seeded with `exp.eval_seed`, so a cell's +action draws are reproducible and are driven by the same knob that drives the env's initial conditions, +matching the fairness rule the rest of the table follows. It is a dedicated generator, so it never +perturbs the env's own RNG stream. + +The per-step selection log has the same shape the RSM/IQL planner writes (`score_*`, `ties_at_max`, +`t_sample`, `t_score`), so eval.py's `_plan_summary` and the results-JSON `planner_time` block work +unchanged: `pop_plan_log` is exposed here and eval.py finds it through `policy.policy.policy`. +""" +import time + +import numpy as np +import torch + +from sim_pipeline.eval.rollout_policies.rollout_policy import RolloutPolicy + + +class _IFQLInner: + """What eval.py reaches as `policy.policy.policy`: holds the agent, the log and the description.""" + + algo_name = "ifql" + + def __init__(self, agent, state, ckpt, feat_stats, num_samples, eval_seed, device, + img_layout="chw"): + self.agent = agent + self._state = state + self.img_layout = img_layout + self.ckpt = ckpt + self.feat_stats = feat_stats + self.num_samples = int(num_samples) + self.eval_seed = int(eval_seed) + self.device = device + self.generator = torch.Generator(device="cpu").manual_seed(int(eval_seed)) + self._plan_log = [] + + @property + def state(self): + """The pooled-DINO state encoder, built on first use (see IFQLRolloutPolicy.__init__).""" + if self._state is None: + from robomimic.algo.rsm_scorer import PooledDinoState, CAMS, PROPRIO_KEYS + self._state = PooledDinoState(self.feat_stats, cams=CAMS, proprio_keys=PROPRIO_KEYS, + img_layout=self.img_layout).to(self.device) + return self._state + + def pop_plan_log(self): + log, self._plan_log = self._plan_log, [] + return log + + def planner_describe(self): + d = {"plan_n": self.num_samples, "plan_rule": "argmax", "rsm_backend": "ifql", + "rsm_ckpt": self.ckpt, "rsm_feat_stats": self.feat_stats, + "proposer": "ifql flow actor (its own)", "eval_seed": self.eval_seed, + "state_encoder_built": self._state is not None} + try: + d["scorer"] = self.agent.describe() + except Exception as e: # a description must never break an eval + d["scorer"] = {"error": repr(e)} + return d + + @torch.no_grad() + def act(self, obs_t): + t0 = time.time() + x = self.state(obs_t) # [B, 1545] + B, N, A = x.shape[0], self.num_samples, self.agent.action_dim + noise = torch.randn(B, N, A, generator=self.generator, device="cpu").to(self.device) + cand = self.agent.flow_candidates(x, num_samples=N, noise=noise) + t_sample = time.time() - t0 + t1 = time.time() + q = self.agent.q(x.repeat_interleave(N, 0), cand.reshape(B * N, A)).reshape(B, N) + t_score = time.time() - t1 + idx = q.argmax(1) + act = cand[torch.arange(B, device=cand.device), idx] + s = q.detach().float().cpu() + ar = torch.arange(B, device="cpu") + idx_cpu = idx.detach().to("cpu") + self._plan_log.append({ + "n": N, "rule": "argmax", "idx": idx_cpu.tolist(), "score_kind": "prob", + "score_chosen": s[ar, idx_cpu].tolist(), "score_max": s.max(1).values.tolist(), + "score_mean": s.mean(1).tolist(), "score_min": s.min(1).values.tolist(), + "score_std": s.std(1).tolist() if N > 1 else [0.0] * B, + "ties_at_max": (s >= s.max(1, keepdim=True).values - 1e-6).sum(1).tolist(), + "frac_saturated": (s >= 0.999).float().mean(1).tolist(), + "prob_chosen": s[ar, idx_cpu].tolist(), "prob_max": s.max(1).values.tolist(), + "prob_mean": s.mean(1).tolist(), + "t_sample": t_sample, "t_score": t_score, + }) + return act + + +class IFQLRolloutPolicy(RolloutPolicy): + """`predict(obs) -> [B, 7]`. `obs` is the env's processed dict (images float CHW in [0, 1]).""" + + def __init__(self, ckpt, feat_stats, device, num_samples=128, eval_seed=0, img_layout="chw"): + from robomimic.algo.ifql_torch import IFQLTorch + from robomimic.algo.rsm_scorer import CAMS, PROPRIO_KEYS + agent = IFQLTorch(ckpt, device=device) + feat_stats = feat_stats or agent.feat_stats + if not feat_stats: + raise RuntimeError("the IFQL policy needs feat_stats (the task cache's feat_stats.npz)") + # The DINO encoder is built on FIRST USE, not here. This policy is constructed inside + # eval.get_policy, i.e. BEFORE setup_eval calls initialize_obs_utils_with_obs_specs and before the + # env exists; the RSM scorer builds its own copy lazily on the first planner call and therefore + # never depended on that ordering. Matching it keeps the IFQL path independent of when ObsUtils + # is initialised. + inner = _IFQLInner(agent, None, str(ckpt), str(feat_stats), num_samples, eval_seed, device, + img_layout=img_layout) + # RolloutPolicy stores its argument as `.policy`; eval.py reads `policy.policy.policy`, so the + # inner object is nested one level deeper, the way a robomimic RolloutPolicy nests its algo. + super().__init__(type("_IFQLWrap", (), {"policy": inner})(), action_chunking=False, n_obs_steps=None) + self.inner = inner + self.device = device + self.cams = CAMS + self.proprio_keys = PROPRIO_KEYS + + def reset(self): + pass + + def predict(self, obs, *args, **kwargs): + obs_t = {} + for k in list(self.cams) + list(self.proprio_keys): + if k not in obs: + raise KeyError(f"the IFQL policy needs obs key {k!r}; env gave {sorted(obs)}") + v = obs[k] + obs_t[k] = torch.as_tensor(np.asarray(v), dtype=torch.float32, device=self.device) + act = self.inner.act(obs_t) + return act.detach().cpu().numpy() diff --git a/code_src/rise_code/sim_pipeline/eval/rollout_policies/manual_lookahead_policy.py b/code_src/rise_code/sim_pipeline/eval/rollout_policies/manual_lookahead_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..7271150ffa00c51f27fc9dbe982a9fffbd17de1d --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout_policies/manual_lookahead_policy.py @@ -0,0 +1,96 @@ +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.obs_utils as ObsUtils +import numpy as np +import torch + +from sim_pipeline.eval.rollout_policies.rollout_policy import RolloutPolicy + + +class ManualLookaheadRolloutPolicy(RolloutPolicy): + def __init__( + self, + policy, + action_chunking: bool = False, + n_obs_steps: int | None = None, + is_diffusion: bool = False + ): + super().__init__(policy, action_chunking=action_chunking, n_obs_steps=n_obs_steps) + + self.counter = 0 + + if is_diffusion and self.policy.policy.ema is not None: + self.policy.policy.ema.copy_to(self.policy.policy.nets['policy'].parameters()) + + def reset(self): + self.counter = 0 + + def predict(self, obs, *args, **kwargs): + self.counter += 1 + # we must copy robomimic.algo.algo.RolloutPolicy.__call__() here + # b/c we override _prepare_observation() to assume batch dimension + ob = self._robomimic_prepare_observations(obs) + + if 'goal' in kwargs and kwargs['goal'] is not None: + goal = self._robomimic_prepare_observations(kwargs['goal']) + else: + goal = None + + if ob['robot0_eef_pos'][0, -1, 2] < 0.835: + ac = self.policy.policy.get_action(obs_dict=ob, goal_dict=goal) + else: + # print('manual sampling') + act_min = np.array([-0.2, -0.2, -0.02, 0.0, 0.0, 0.0, -1.0]) + act_max = np.array([0.2, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0]) + + size = 30000 + + random_action_sample = np.random.uniform(act_min, act_max, size=(size, 7)) + random_action_sample = TensorUtils.to_tensor(random_action_sample) + random_action_sample = TensorUtils.to_device(random_action_sample, self.policy.policy.device) + random_action_sample = TensorUtils.to_float(random_action_sample) + + for key in ob: + ob[key] = ob[key][:, -1, :] + ob[key] = torch.tile(ob[key], (size, 1)) + pred_qs = [critic(obs_dict=ob, acts=random_action_sample, goal_dict=goal) + for critic in self.policy.policy.nets["critic"]] + pred_q1 = pred_qs[0].detach().cpu().numpy() + pred_q2 = pred_qs[1].detach().cpu().numpy() + pred_q = np.concatenate([pred_q1, pred_q2], axis=0) + + best_idx = np.argmax(pred_q) + if best_idx >= size: + best_idx -= size + ac = random_action_sample[best_idx].reshape(1, 1, -1) + # vf_pred = self.nets["vf"](obs_dict=obs, goal_dict=goal) + + # ac = self.policy.policy.get_action(obs_dict=ob, goal_dict=goal) + ac = TensorUtils.to_numpy(ac) + return ac + + def _robomimic_prepare_observations(self, ob): + """ + Prepare raw observation dict from environment for policy. + Copied from robomimic.algo.algo.RolloutPolicy._prepare_observation(). + + We override this b/c robomimic assumes that inputs do not have a batch dimension, but + we add in the batch dimension in `rollout.py` in order to standardize everything between + vectorized and non-vectorized environments. Thus, the input to robomimic rollout policies + here *must* have a batch dimension. + + Args: + ob (dict): single observation dictionary from environment (with batch dimension, + and np.array values for each key) + """ + ob = TensorUtils.to_tensor(ob) + # we just remove this line to prevent adding batch dimension twice. + # ob = TensorUtils.to_batch(ob) + ob = TensorUtils.to_device(ob, self.policy.policy.device) + ob = TensorUtils.to_float(ob) + if self.obs_normalization_stats is not None: + # ensure obs_normalization_stats are torch Tensors on proper device + obs_normalization_stats = TensorUtils.to_float(TensorUtils.to_device(TensorUtils.to_tensor(self.obs_normalization_stats), self.policy.policy.device)) + # limit normalization to obs keys being used, in case environment includes extra keys + ob = { k : ob[k] for k in self.policy.policy.global_config.all_obs_keys } + ob = ObsUtils.normalize_obs(ob, obs_normalization_stats=obs_normalization_stats) + return ob diff --git a/code_src/rise_code/sim_pipeline/eval/rollout_policies/ogbench_rollout_policy.py b/code_src/rise_code/sim_pipeline/eval/rollout_policies/ogbench_rollout_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c26c0d88f8974596d82a3ff212403c091e6a86f8 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout_policies/ogbench_rollout_policy.py @@ -0,0 +1,49 @@ +import numpy as np + +from impls.utils.evaluation import supply_rng + +from diffusion_policy.common.pytorch_util import dict_apply +from sim_pipeline.utils.rollout_utils import filter_obs_keys +from sim_pipeline.eval.rollout_policies.rollout_policy import RolloutPolicy + +class OGBenchRolloutPolicy(RolloutPolicy): + def __init__( + self, + policy, + action_chunking: bool = True, + n_obs_steps: int | None = 2, + obs_keys: list[str] | None = None, + lowdim: bool = False, + ): + import jax + + super().__init__(policy, action_chunking=action_chunking, n_obs_steps=n_obs_steps) + self.obs_keys = obs_keys + self.lowdim = lowdim + + self.actor_fn = supply_rng(self.policy.sample_actions, rng=jax.random.PRNGKey(np.random.randint(0, 2**32))) + + def reset(self): + pass + + def predict(self, obs, *args, **kwargs): + np_obs_dict = filter_obs_keys(obs, obs_keys=self.obs_keys) + if self.lowdim: + obs = np.concatenate([ + np_obs_dict[key] for key in self.obs_keys + ], axis=-1) + + # hardcoded for now + goal = np.array([1.14608096e-01, 1.52866992e-01, 8.29978946e-01, 0.0, + 0.0, 5.80254076e-01, 8.14435515e-01, 2.09027917e-03, + 4.97338057e-02, 4.99918345e-04, -7.93045580e-01, 6.07315481e-01, + -3.82225290e-02, 2.80285198e-02, + # eef + -0.11330734, 0.20262865, 0.83037664, + #quat + 9.98281814e-01, -3.44512741e-02, 4.73931190e-02, 6.49702759e-04, + 0.04, -0.04]) + goal = goal.reshape(1, -1) + action = self.actor_fn(observations=obs, goals=goal, temperature=0) + return np.array(action) + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/eval/rollout_policies/pd_rollout_policy.py b/code_src/rise_code/sim_pipeline/eval/rollout_policies/pd_rollout_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..921b65ee9b8d99a367fbe87e88aef7b15247e80f --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout_policies/pd_rollout_policy.py @@ -0,0 +1,57 @@ +import numpy as np +from scipy.spatial.transform import Rotation as R +from sim_pipeline.eval.rollout_policies.rollout_policy import RolloutPolicy + +class PDRolloutPolicy(RolloutPolicy): + def __init__( + self, + policy, + target_pos: np.ndarray, + action_chunking: bool = False, + n_obs_steps: int | None = None, + ): + super().__init__(policy, action_chunking=action_chunking, n_obs_steps=n_obs_steps) + + self.target_pos = target_pos + self.kp = 3 + self.kd = 0.1 + self.kpr = 0.1 + self.yaw_gain = 0.1 + + def reset(self): + self.prev_pos_error = np.zeros(3) + + def predict(self, obs, *args, **kwargs): + # PD controller + ee_position = obs['robot0_eef_pos'] + pos_error = self.target_pos - ee_position + + quat = obs['robot0_eef_quat'] + # switch from scalar first to scalar last + quat = np.concatenate([quat[:, 1:], quat[:, :1]], axis=1) + rot = R.from_quat(quat) + yaw = rot.as_euler('xyz', degrees=False)[:, 0] + orientation = rot.as_matrix().dot(np.array([1, 0, 0])) + rot_error = np.cross(orientation, np.array([1, 0, 0])) + + # derivative term + d_error = pos_error - self.prev_pos_error + self.prev_pos_error = pos_error + + # PD control + action_pos = self.kp * pos_error + self.kd * d_error + + # rotation + yaw + action_rot = -self.kpr * rot_error + action_rot[:, 0] = -self.yaw_gain * yaw + action_rot[:, [0, 1, 2]] = action_rot[:, [2, 1, 0]] + + # no rotation + action = np.concatenate([action_pos, action_rot], axis=1) + + # open gripper + action = np.concatenate([action, np.zeros((action.shape[0], 1), dtype=action.dtype) - 1.0], axis=1) + # clamp + action = np.clip(action, -1, 1) + + return action \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/eval/rollout_policies/robomimic_opex_rollout_policy.py b/code_src/rise_code/sim_pipeline/eval/rollout_policies/robomimic_opex_rollout_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d9db41b354f2946b944d650c1d1d076a10193ca5 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout_policies/robomimic_opex_rollout_policy.py @@ -0,0 +1,95 @@ +import torch +import numpy as np +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.obs_utils as ObsUtils + +from sim_pipeline.eval.rollout_policies.rollout_policy import RolloutPolicy + + +class RobomimicOpexRolloutPolicy(RolloutPolicy): + def __init__( + self, + policy, + action_chunking: bool = False, + n_obs_steps: int | None = None, + is_diffusion: bool = False + ): + super().__init__(policy, action_chunking=action_chunking, n_obs_steps=n_obs_steps) + + self.counter = 0 + self.grad_norms = [] + + if is_diffusion and self.policy.policy.ema is not None: + self.policy.policy.ema.copy_to(self.policy.policy.nets['policy'].parameters()) + + def reset(self): + self.counter = 0 + + def predict(self, obs, *args, **kwargs): + self.counter += 1 + # we must copy robomimic.algo.algo.RolloutPolicy.__call__() here + # b/c we override _prepare_observation() to assume batch dimension + ob = self._robomimic_prepare_observations(obs) + if 'goal' in kwargs and kwargs['goal'] is not None: + goal = self._robomimic_prepare_observations(kwargs['goal']) + else: + goal = None + ac = self.policy.policy.get_action(obs_dict=ob, goal_dict=goal) + + # if obs['robot0_eef_pos'][0, -1, 2] < 0.835: + # print('touched', self.counter) + if self.counter > 20: + print('starting') + ac = ac.detach()[:, 0, :] + for key in ob: + ob[key] = ob[key][:, -1, :] + + ac.requires_grad = True + + for i in range(10): + ac_old = ac.clone().detach() + ac = ac.detach().requires_grad_(True) + pred_qs = [critic(obs_dict=ob, acts=ac, goal_dict=goal) + for critic in self.policy.policy.nets["critic"]] + q_pred, _ = torch.cat(pred_qs, dim=1).min(dim=1, keepdim=True) + q_pred.backward() + + # self.grad_norms.append(ac.grad.norm().detach().cpu().numpy()) + # np.savez('grad_norms.npz', grad_norms=np.array(self.grad_norms)) + + eta = 0.05 + ac = ac + eta * ac.grad + ac = ac.detach() + ac[:, 2:] = ac_old[:, 2:] + + ac = torch.unsqueeze(ac, 1) + + ac = TensorUtils.to_numpy(ac) + return ac + + def _robomimic_prepare_observations(self, ob): + """ + Prepare raw observation dict from environment for policy. + Copied from robomimic.algo.algo.RolloutPolicy._prepare_observation(). + + We override this b/c robomimic assumes that inputs do not have a batch dimension, but + we add in the batch dimension in `rollout.py` in order to standardize everything between + vectorized and non-vectorized environments. Thus, the input to robomimic rollout policies + here *must* have a batch dimension. + + Args: + ob (dict): single observation dictionary from environment (with batch dimension, + and np.array values for each key) + """ + ob = TensorUtils.to_tensor(ob) + # we just remove this line to prevent adding batch dimension twice. + # ob = TensorUtils.to_batch(ob) + ob = TensorUtils.to_device(ob, self.policy.policy.device) + ob = TensorUtils.to_float(ob) + if self.obs_normalization_stats is not None: + # ensure obs_normalization_stats are torch Tensors on proper device + obs_normalization_stats = TensorUtils.to_float(TensorUtils.to_device(TensorUtils.to_tensor(self.obs_normalization_stats), self.policy.policy.device)) + # limit normalization to obs keys being used, in case environment includes extra keys + ob = { k : ob[k] for k in self.policy.policy.global_config.all_obs_keys } + ob = ObsUtils.normalize_obs(ob, obs_normalization_stats=obs_normalization_stats) + return ob diff --git a/code_src/rise_code/sim_pipeline/eval/rollout_policies/robomimic_rollout_policy.py b/code_src/rise_code/sim_pipeline/eval/rollout_policies/robomimic_rollout_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..2bd36c658c2b93caf7a666eaa2f4293829b73d72 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout_policies/robomimic_rollout_policy.py @@ -0,0 +1,60 @@ +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.obs_utils as ObsUtils +from sim_pipeline.eval.rollout_policies.rollout_policy import RolloutPolicy + + +class RobomimicRolloutPolicy(RolloutPolicy): + def __init__( + self, + policy, + action_chunking: bool = False, + n_obs_steps: int | None = None, + is_diffusion: bool = False, + action_normalization_stats: dict | None = None + ): + super().__init__(policy, action_chunking=action_chunking, n_obs_steps=n_obs_steps, action_normalization_stats=action_normalization_stats) + + if is_diffusion and self.policy.policy.ema is not None: + self.policy.policy.ema.copy_to(self.policy.policy.nets['policy'].parameters()) + + def reset(self): + pass + + def predict(self, obs, *args, **kwargs): + # we must copy robomimic.algo.algo.RolloutPolicy.__call__() here + # b/c we override _prepare_observation() to assume batch dimension + ob = self._robomimic_prepare_observations(obs) + if 'goal' in kwargs and kwargs['goal'] is not None: + goal = self._robomimic_prepare_observations(kwargs['goal']) + else: + goal = None + ac = self.policy.policy.get_action(obs_dict=ob, goal_dict=goal) + ac = TensorUtils.to_numpy(ac) + return self.unnormalize_actions(ac) + + def _robomimic_prepare_observations(self, ob): + """ + Prepare raw observation dict from environment for policy. + Copied from robomimic.algo.algo.RolloutPolicy._prepare_observation(). + + We override this b/c robomimic assumes that inputs do not have a batch dimension, but + we add in the batch dimension in `rollout.py` in order to standardize everything between + vectorized and non-vectorized environments. Thus, the input to robomimic rollout policies + here *must* have a batch dimension. + + Args: + ob (dict): single observation dictionary from environment (with batch dimension, + and np.array values for each key) + """ + ob = TensorUtils.to_tensor(ob) + # we just remove this line to prevent adding batch dimension twice. + # ob = TensorUtils.to_batch(ob) + ob = TensorUtils.to_device(ob, self.policy.policy.device) + ob = TensorUtils.to_float(ob) + if self.obs_normalization_stats is not None: + # ensure obs_normalization_stats are torch Tensors on proper device + obs_normalization_stats = TensorUtils.to_float(TensorUtils.to_device(TensorUtils.to_tensor(self.obs_normalization_stats), self.policy.policy.device)) + # limit normalization to obs keys being used, in case environment includes extra keys + ob = { k : ob[k] for k in self.policy.policy.global_config.all_obs_keys } + ob = ObsUtils.normalize_obs(ob, obs_normalization_stats=obs_normalization_stats) + return ob diff --git a/code_src/rise_code/sim_pipeline/eval/rollout_policies/robomimic_sampling_rollout_policy.py b/code_src/rise_code/sim_pipeline/eval/rollout_policies/robomimic_sampling_rollout_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..791200b8b87da74391c17c00d4808277aff979a8 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout_policies/robomimic_sampling_rollout_policy.py @@ -0,0 +1,197 @@ +import numpy as np +from scipy.spatial import cKDTree +from scipy.special import digamma + +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.obs_utils as ObsUtils + +from sim_pipeline.eval.rollout_policies.rollout_policy import RolloutPolicy +from scipy.spatial import cKDTree + +class RobomimicSamplingRolloutPolicy(RolloutPolicy): + def __init__( + self, + policy, + action_chunking: bool = False, + n_obs_steps: int | None = None, + is_diffusion: bool = False, + discriminator=None, + expert_policy=None, + action_normalization_stats: dict | None = None + ): + super().__init__(policy, action_chunking=action_chunking, n_obs_steps=n_obs_steps, action_normalization_stats=action_normalization_stats) + + self.counter = 0 + + self.all_states = [] + self.all_actions = [] + self.Q_vals = [] + + self.discriminator = discriminator + self.expert_policy = expert_policy + + if is_diffusion and self.policy.policy.ema is not None: + self.policy.policy.ema.copy_to(self.policy.policy.nets['policy'].parameters()) + + def reset(self): + self.counter = 0 + # np.savez('states_spectral_0.5.npz', states=np.array(self.all_states), actions=np.array(self.all_actions), Q_vals=np.array(self.Q_vals)) + + def entropy(self, samples, k=5): + """ + Estimate entropy of distribution given iid samples using k-nearest neighbors. + """ + N, D = samples.shape + tree = cKDTree(samples) + # Find distances to kth nearest neighbor for each point + distances, _ = tree.query(samples, k=k+1) # k+1 because first neighbor is self + knn_distances = distances[:, k] # Get distances to kth neighbor + + # Calculate entropy estimate + # H = digamma(N) - digamma(k) + D * np.mean(np.log(knn_distances)) + np.log(2) + H = -digamma(k) + digamma(N) + D * np.mean(np.log(knn_distances)) + + return H + + def predict(self, obs, *args, **kwargs): + self.counter += 1 + # we must copy robomimic.algo.algo.RolloutPolicy.__call__() here + # b/c we override _prepare_observation() to assume batch dimension + + # duplicate obs to get multiple predictions on same obs + ob = self._robomimic_prepare_observations(obs) + num_samples = 128 + if 'random_sample' in kwargs and kwargs['random_sample']: + num_samples = 512 + print('random sample') + multiplier = 1 + ob = {k: ob[k].repeat(num_samples, *([1] * (len(ob[k].shape) - 1))) for k in ob} + if 'goal' in kwargs and kwargs['goal'] is not None: + goal = self._robomimic_prepare_observations(kwargs['goal']) + else: + goal = None + + ob_unstacked = {k: ob[k].clone() for k in ob} + for key in ob_unstacked: + ob_unstacked[key] = ob_unstacked[key][:, -1, :] + + Qs = [] + all_actions = [] + all_actions_chunked = [] + for i in range(multiplier): + if 'random_sample' in kwargs and kwargs['random_sample']: + act_min = np.array([-0.2, -0.2, -0.02, 0.0, 0.0, 0.0, -1.0]) + act_max = np.array([0.2, 0.2, 0.0, 0.0, 0.0, 0.0, 1.0]) + + actions = np.random.uniform(act_min, act_max, size=(num_samples, 7)).astype(np.float32) + actions = TensorUtils.to_tensor(actions) + actions = TensorUtils.to_device(actions, self.policy.policy.device) + + all_actions.append(actions.detach().cpu().numpy()) + else: + actions = self.policy.policy.get_action(obs_dict=ob, goal_dict=goal) + all_actions_chunked.append(actions.detach().cpu().numpy()) + actions = actions[:, 0, :] + all_actions.append(actions.detach().cpu().numpy()) + + pred_qs = [critic(obs_dict=ob_unstacked, acts=actions, goal_dict=goal) + for critic in self.policy.policy.nets["critic"]] + pred_q1 = pred_qs[0].detach().cpu().numpy() + pred_q2 = pred_qs[1].detach().cpu().numpy() + + min_q = np.minimum(pred_q1, pred_q2) + Qs.append(min_q) + + Qs = np.concatenate(Qs, axis=0) + actions = np.concatenate(all_actions, axis=0) + if not ('random_sample' in kwargs and kwargs['random_sample']): + all_actions_chunked = np.concatenate(all_actions_chunked, axis=0) + # entropy = self.entropy(actions[:, :3]) + # print(entropy) + # if ob['robot0_eef_pos'][0, -1, 2] > 0.835: + # best_idx = np.argmax(min_q) + # else: + best_idx = np.argmax(Qs) + + if self.discriminator is not None: + ob2 = self._robomimic_prepare_observations(obs) + # get only the last state from each obs key + ob2 = {k: ob2[k][:, -1, ...] for k in ob2} + predict = self.discriminator.policy.nets['policy'](obs=ob2) + print(predict) + + # if ob['robot0_eef_pos'][0, -1, 2] > 0.855: + # # pass + # self.all_states.append(obs['robot0_eef_pos'][0, -1, :3]) + # self.object_state = obs['object'][0, -1, :3] + # self.all_actions.append(actions[:, :3]) + # self.Q_vals.append(Qs) + # else: + # self.all_states.append(obs['robot0_eef_pos'][0, -1, :3]) + # self.object_state = obs['object'][0, -1, :3] + # self.all_actions.append(actions[:, :3]) + # self.Q_vals.append(Qs) + + # if not ('random_sample' in kwargs and kwargs['random_sample']): + # np.savez('states_idql_two_piece_1.npz', states=np.array(self.all_states), actions=np.array(self.all_actions), Q_vals=np.array(self.Q_vals)) + + # if ob['robot0_eef_pos'][0, -1, 2] < 0.835: + # if self.counter % 10 == 0: + # self.all_states.append(obs['object'][0, -1, :2]) + # self.all_actions.append(actions[:, :2]) + # self.Q_vals.append(Qs) + + if 'random_sample' in kwargs and kwargs['random_sample']: + ac = actions[best_idx].reshape(1, 1, -1) + else: + ac = all_actions_chunked[best_idx][None, :8] + + # if self.counter > 0: + # print('bc!!!') + # ob2 = self._robomimic_prepare_observations(obs) + # ac = self.policy.policy.get_action(obs_dict=ob2, goal_dict=goal) + # print(ac[:, 0, -1]) + # if ac[:, 0, -1] > 0.0: + # import ipdb; ipdb.set_trace() + + # ob2 = self._robomimic_prepare_observations(obs) + # ob2_unstacked = {k: ob2[k].clone() for k in ob2} + # for key in ob2_unstacked: + # ob2_unstacked[key] = ob2_unstacked[key][:, -1, :] + # crit = self.policy.policy.nets["critic"][0] + # import torch + # act = torch.tensor(ac[:, 0, :]).to(self.policy.policy.device) + # import ipdb; ipdb.set_trace() + + # if self.counter > 190: + # import ipdb; ipdb.set_trace() + + ac = TensorUtils.to_numpy(ac) + return self.unnormalize_actions(ac) + + def _robomimic_prepare_observations(self, ob): + """ + Prepare raw observation dict from environment for policy. + Copied from robomimic.algo.algo.RolloutPolicy._prepare_observation(). + + We override this b/c robomimic assumes that inputs do not have a batch dimension, but + we add in the batch dimension in `rollout.py` in order to standardize everything between + vectorized and non-vectorized environments. Thus, the input to robomimic rollout policies + here *must* have a batch dimension. + + Args: + ob (dict): single observation dictionary from environment (with batch dimension, + and np.array values for each key) + """ + ob = TensorUtils.to_tensor(ob) + # we just remove this line to prevent adding batch dimension twice. + # ob = TensorUtils.to_batch(ob) + ob = TensorUtils.to_device(ob, self.policy.policy.device) + ob = TensorUtils.to_float(ob) + if self.obs_normalization_stats is not None: + # ensure obs_normalization_stats are torch Tensors on proper device + obs_normalization_stats = TensorUtils.to_float(TensorUtils.to_device(TensorUtils.to_tensor(self.obs_normalization_stats), self.policy.policy.device)) + # limit normalization to obs keys being used, in case environment includes extra keys + ob = { k : ob[k] for k in self.policy.policy.global_config.all_obs_keys } + ob = ObsUtils.normalize_obs(ob, obs_normalization_stats=obs_normalization_stats) + return ob diff --git a/code_src/rise_code/sim_pipeline/eval/rollout_policies/rollout_policy.py b/code_src/rise_code/sim_pipeline/eval/rollout_policies/rollout_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..937102b78063ba353072931dba7974cc1510dfc6 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout_policies/rollout_policy.py @@ -0,0 +1,37 @@ +class RolloutPolicy: + def __init__( + self, + policy, + action_chunking: bool = False, + n_obs_steps: int | None = None, + is_composite: bool = False, + action_normalization_stats: dict | None = None, + ): + self.policy = policy + self.action_chunking = action_chunking + self.n_obs_steps = n_obs_steps + + self.is_composite = False + self.action_normalization_stats = action_normalization_stats + + def __getattr__(self, name): + return getattr(self.policy, name) + + def reset(self): + raise NotImplementedError + + def predict(self, obs, *args, **kwargs): + raise NotImplementedError + + def unnormalize_actions(self, actions): + if self.action_normalization_stats is None: + return actions + # Actions are normalized to [-0.5, 0.5], so unnormalize by: + # 1. Add 0.5 to get [0,1] + # 2. Scale by (max-min) and add min + action_min = self.action_normalization_stats['min'] + action_max = self.action_normalization_stats['max'] + # Don't normalize the gripper dimension + actions_copy = actions.copy() + actions_copy[..., :-1] = (actions[..., :-1] + 0.5) * (action_max - action_min) + action_min + return actions_copy \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/eval/rollout_policies/sb_rollout_policy.py b/code_src/rise_code/sim_pipeline/eval/rollout_policies/sb_rollout_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..28c449d77edbea29ae9ecd82cd79f0108e320206 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout_policies/sb_rollout_policy.py @@ -0,0 +1,17 @@ +from sim_pipeline.eval.rollout_policies.rollout_policy import RolloutPolicy + +class StableBaselinesRolloutPolicy(RolloutPolicy): + def __init__( + self, + policy, + action_chunking: bool = False, + n_obs_steps: int | None = None, + ): + super().__init__(policy, action_chunking=action_chunking, n_obs_steps=n_obs_steps) + + def reset(self): + pass + + def predict(self, obs, *args, **kwargs): + act, _state = self.policy.predict(obs) + return act diff --git a/code_src/rise_code/sim_pipeline/eval/rollout_policies/wm_native_cem_rollout_policy.py b/code_src/rise_code/sim_pipeline/eval/rollout_policies/wm_native_cem_rollout_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..f92b286ec209969d882f427caf3729caed7394d4 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout_policies/wm_native_cem_rollout_policy.py @@ -0,0 +1,125 @@ +"""Roll out a world model under ITS OWN published planner (gen_q#289, worker WM_NATIVE). + +`exp.policy_mode='wm_cem'` selects this instead of `RobomimicSamplingRolloutPolicy`. There is **no +actor and no diffusion proposer** on this path: the actions come from CEM over the full open-loop +action sequence (robomimic.algo.wm_native_cem.NativeCEMPlanner), exactly as DINO-WM's +`conf/planner/mpc_cem.yaml` and LeWM's paper describe. The loaded robomimic policy is used only for +its observation pipeline; its weights never produce an action, which is why the cell's arm key starts +with `CEM` and can never pool with a shared-candidate arm. + +The planner is asked for ONE 8-frame chunk per call and re-optimises every `n_taken` calls, so the +rollout loop's action queue turns over every chunk and the planner sees a real frame at the model's +own step spacing. See NativeCEMPlanner.act for why that matters (LeWM's 3-frame context). +""" +import json + +import numpy as np +import torch + +import robomimic.utils.tensor_utils as TensorUtils +from robomimic.algo.wm_native_cem import NativeCEMPlanner, arm_key +from sim_pipeline.eval.rollout_policies.robomimic_rollout_policy import RobomimicRolloutPolicy + + +class WMNativeCEMRolloutPolicy(RobomimicRolloutPolicy): + """Single-env only (num_workers=1), which is every cell this row runs: the CEM state is per-episode.""" + + def __init__(self, policy, cfg, action_chunking=True, n_obs_steps=None, is_diffusion=False, + action_normalization_stats=None): + super().__init__(policy, action_chunking=True, n_obs_steps=n_obs_steps, + is_diffusion=is_diffusion, + action_normalization_stats=action_normalization_stats) + c = dict(cfg) + self.planner = NativeCEMPlanner( + family=c["family"], ckpt=c["ckpt"], feat_stats=c["feat_stats"], + device=str(self.policy.policy.device), + horizon=c.get("horizon"), num_samples=c.get("num_samples"), + opt_steps=c.get("opt_steps"), topk=c.get("topk"), var_scale=c.get("var_scale"), + n_taken=c.get("n_taken"), gamma=float(c.get("gamma", 0.99)), + seed=int(c.get("seed", 0)), micro=int(c.get("micro", 150)), + img_layout=c.get("img_layout", "chw"), + # both absent from every as-published spec, so those cells are unchanged. + clip=(None if c.get("clip") in (None, "") else float(c["clip"])), + warm_start=(self._proposer_prior if bool(c.get("warm", False)) else None)) + # `--warm`: how many proposer draws are averaged into the initial mu. The planner means over + # whatever this returns, and at sigma=1 the starting point barely moves the first population, + # so the count is not a tuned knob -- 8 is enough for the mean to be stable and costs ~4 ms. + self.warm_draws = int(c.get("warm_draws", 8)) + self._warm_ob = None + # `--passthrough` (`-PASS`): the PIPELINE CONTROL for an all-zero appendix row. The planner + # is still constructed and the observation pipeline is byte-for-byte the CEM cells', but the + # executed chunk is the PROPOSER'S OWN -- `super().predict`, the standard robomimic path -- + # so this arm measures what the native route's action execution can reach when the action is + # known-good. A non-zero number here is what separates "CEM fails" from "my wiring fails"; + # it is NEVER a planner result and is reported under its own `-PASS` arm. + self.passthrough = bool(c.get("passthrough", False)) + print("[wm_cem] " + json.dumps(self.planner_describe(), default=str), flush=True) + + def reset(self): + self.planner.reset() + + def _proposer_prior(self, obs_t, S): + """The OPTIONAL `-WARM` variant: seed CEM's mu from the RISE proposer (a policy prior). + + This is the published code path, not a different algorithm: DINO-WM's `planning/cem.py` + initialises `mu` from "the prior actions, zero-padded", so the prior occupies model step 0 + (the only step a real observation exists for) and steps 1..H-1 stay zero. We cannot do + better than step 0: the proposer is IMAGE-conditioned, and the world model predicts its own + latent, not renderable frames, so there is no observation to condition draw 2 on. Inventing + one would be a different method, silently. + + `obs_t` (the single current frame) is the planner's convention, but the proposer wants the + STACKED [B, To, ...] observation it was trained on, so the stack captured in `predict` is + what gets used. Returns [n_draws, H, d_act] in the SAME normalised action space the planner + searches in (`get_action` and `planner.act` both feed `unnormalize_actions`). + """ + n = max(1, self.warm_draws) + ob = {k: v.repeat(n, *([1] * (len(v.shape) - 1))) for k, v in self._warm_ob.items()} + ac = self.policy.policy.get_action(obs_dict=ob, goal_dict=None) # [n, chunk, adim] + flat = ac.reshape(n, -1) + if flat.shape[1] != self.planner.d_act: + raise RuntimeError( + f"--warm: the proposer returned a {tuple(ac.shape[1:])} chunk = {flat.shape[1]} dims, " + f"but the planner searches d_act={self.planner.d_act}. These must be the same action " + f"parameterisation or the warm start would seed mu with a reshaped-wrong vector.") + out = torch.zeros(n, self.planner.horizon, flat.shape[1], + device=flat.device, dtype=flat.dtype) + out[:, 0] = flat # zero-padded beyond step 0, as published + return out.detach().cpu().numpy() + + def predict(self, obs, *args, **kwargs): + if self.passthrough: + # The control arm: the proposer's chunk, through the BASE class's own predict, so this + # is provably the standard robomimic action path and not a second re-implementation of + # it that could differ from the shared row in some detail. CEM is never called. + return super().predict(obs, *args, **kwargs) + ob = self._robomimic_prepare_observations(obs) + self._warm_ob = ob # the stack `_proposer_prior` needs, if it is enabled + # the CURRENT frame, index To-1, the same one rsm_planner hands every shared scorer. + # EXACTLY rsm_planner.plan_get_action's convention -- `{k: v[:, -1]}` on the [B, To, ...] + # stack -- so the native route reads the same pixel/proprio the shared scorers read. A + # cleverer shape heuristic here would be a place for the two routes to silently diverge. + obs_t = {k: v[:, -1] for k, v in ob.items()} + B = next(iter(obs_t.values())).shape[0] + if B != 1: + raise RuntimeError(f"policy_mode=wm_cem is single-env (the CEM state is per-episode); " + f"got batch {B}. Run with exp.num_workers=1.") + ac = self.planner.act(obs_t) # [chunk, adim] + ac = np.asarray(ac, dtype=np.float32)[None] # [1, chunk, adim] + return self.unnormalize_actions(ac) + + def planner_describe(self): + d = self.planner.describe() + d["passthrough"] = self.passthrough + if self.passthrough: + # The arm key the launcher wrote into the cell name carries `-PASS`; the planner does + # not know about the flag, so the provenance in the JSON has to be corrected here or the + # control cell would claim the as-published arm. + d["arm"] = d["arm"] + "-PASS" + d["returns"] = "proposer_chunk (CEM not run)" + d["objective"] = "none -- pipeline control, the proposer's own action is executed" + return d + + def pop_plan_log(self): + s = self.planner.pop_stats() + return [s] if s else [] diff --git a/code_src/rise_code/sim_pipeline/eval/rollout_stats.py b/code_src/rise_code/sim_pipeline/eval/rollout_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..1ad840df6430d408462be58a6391054d3403041c --- /dev/null +++ b/code_src/rise_code/sim_pipeline/eval/rollout_stats.py @@ -0,0 +1,101 @@ +import numpy as np + + +class RolloutStats: + def __init__(self): + self.all_reward = [] + self.all_successes = [] + self.all_final_successes = [] + self.all_lengths = [] # rsm_rise: steps executed per episode + self.all_first_success = [] # rsm_rise: first step index with success (or -1) + self.num_episodes = 0 + + self.episode_returns = [] + self.episode_successes = [] + + def reset_episode(self): + self.episode_returns = [] + self.episode_successes = [] + + def add_step(self, reward: float | np.float64 | np.ndarray[np.float32], success: bool | list[bool]): + # reward is a float when not vectorized, and a np array of floats when vectorized (from sb3 VecEnv) + # success is bool when not vectorized, list of bools when vectorized + # fun fact: robomimic envs by default returns float64 for rew + self.episode_returns.append(reward) + self.episode_successes.append(success) + + def finalize_episode(self): + # shape (ep_len, num_envs) or (ep_len,) + stacked_rew: np.ndarray[np.float64 | np.float32] = np.stack(self.episode_returns) + # if vec, shape = (num_envs,) + total_reward: np.ndarray[np.float32] | np.float64 = np.sum(stacked_rew, axis=0) + + # avg over all envs, if any + self.avg_ep_reward: np.float32 | np.float64 = np.mean(total_reward) + + # avg success is proportion of envs that were successful at any point in the episode + # avg final success is proportion of envs that were successful at the end of the episode + self.avg_ep_success: np.float64 = np.mean(np.any(np.stack(self.episode_successes), axis=0)) + self.avg_ep_final_success: np.float64 = np.mean(np.stack(self.episode_successes)[-1]) + + self.all_reward.append(self.avg_ep_reward) + self.all_successes.append(self.avg_ep_success) + self.all_final_successes.append(self.avg_ep_final_success) + succ_steps = np.stack(self.episode_successes) + self.all_lengths.append(int(succ_steps.shape[0])) + first = np.where(np.any(succ_steps.reshape(succ_steps.shape[0], -1), axis=1))[0] + self.all_first_success.append(int(first[0]) if len(first) else -1) + + self.num_episodes += 1 + + self.reset_episode() + + def compute_statistics(self): + if self.num_episodes == 0: + return + + self.avg_reward = np.mean(self.all_reward) + self.avg_success = np.mean(self.all_successes) + self.avg_final_success = np.mean(self.all_final_successes) + + self.std_reward = np.std(self.all_reward) + self.std_success = np.std(self.all_successes) + self.std_final_success = np.std(self.all_final_successes) + + def get_episode_stats(self): + return { + 'reward': self.avg_ep_reward, + 'success': self.avg_ep_success, + } + + def get_overall_stats(self): + return { + 'avg_reward': self.avg_reward, + 'std_reward': self.std_reward, + 'avg_success': self.avg_success, + 'std_success': self.std_success, + } + + def get_avg_stats(self): + return { + 'avg_reward': self.avg_reward, + 'avg_success': self.avg_success, + } + + def print_stats(self, i: int, total=None): + ep_stats = self.get_episode_stats() + all_stats = self.get_overall_stats() + total_lines = 2 + len(ep_stats) + len(all_stats) + total_lines = total_lines + 1 if total is not None else total_lines + # Move cursor to the beginning of the line + print('\r', end='') + if total is not None: + print(f'progress: {i}/{total} ({i/total*100:.2f}%)') + print(f"===== Rollout {i} Stats =====") + for k, v in ep_stats.items(): + print(f"{k}: {v}") + print(f'===== Overall Stats =====') + for k, v in all_stats.items(): + print(f"{k}: {v}") + # Move cursor up to beginning of stats to override + print(f'\033[{total_lines}A', end='') \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/ilid/classify_states.py b/code_src/rise_code/sim_pipeline/ilid/classify_states.py new file mode 100644 index 0000000000000000000000000000000000000000..c39366f1cbec1ea5a92316e21bd4f3105c347dca --- /dev/null +++ b/code_src/rise_code/sim_pipeline/ilid/classify_states.py @@ -0,0 +1,100 @@ +import os +import h5py +import torch +import click +from tqdm import tqdm +import uuid +import robomimic.utils.file_utils as FileUtils +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.obs_utils as ObsUtils +from sim_pipeline.ilid.discriminator import Discriminator + + +def classify_states( + filtered_data_path: str, + suboptimal_data_path: str, + discriminator: Discriminator, + device: torch.device, + threshold: float = 0.0, +): + with h5py.File(filtered_data_path, 'w') as f: + data_grp = f.create_group('data') + + demo_counter = 0 + + with h5py.File(suboptimal_data_path, 'r') as suboptimal_data: + data = suboptimal_data['data'] + # Create progress bar for episodes + for ep_key in tqdm(data, desc="Processing episodes"): + ep = data[ep_key] + obs = ep['obs'] + expert_like_states = [] + # Create batch of observations for entire episode + obs_dict = {k: obs[k][:] for k in obs.keys()} + # reshape image keys to (C, H, W) + for k in obs_dict.keys(): + if 'image' in k: + obs_dict[k] = obs_dict[k].transpose(0, 3, 1, 2) + # scale from (0, 255) to (0, 1) + obs_dict[k] = obs_dict[k].astype(float) / 255.0 + ob = TensorUtils.to_tensor(obs_dict) + ob = TensorUtils.to_device(ob, device) + ob = TensorUtils.to_float(ob) + # Get predictions for all states at once + predictions = discriminator.policy.get_action(ob) + + # Find indices where prediction exceeds threshold + expert_like_states = [i for i, pred in enumerate(predictions) if pred > threshold] + + if expert_like_states: + last_index = expert_like_states[-1] + + # Create new trajectory up to the last expert state + new_obs = {k: obs[k][:last_index+1] for k in obs.keys()} + new_actions = ep['actions'][:last_index+1] + new_rewards = ep['rewards'][:last_index+1] + new_dones = ep['dones'][:last_index+1] + next_obs = ep['next_obs'] + new_states = ep['states'][:last_index+1] + new_next_obs = {k: next_obs[k][:last_index+1] for k in next_obs.keys()} + + # Save the new trajectory to the new dataset + ep_grp = data_grp.create_group(f'demo_{demo_counter}') + obs_grp = ep_grp.create_group('obs') + for k, v in new_obs.items(): + obs_grp.create_dataset(k, data=v) + ep_grp.create_dataset('actions', data=new_actions) + ep_grp.create_dataset('rewards', data=new_rewards) + ep_grp.create_dataset('dones', data=new_dones) + ep_grp.create_dataset('states', data=new_states) + next_obs_grp = ep_grp.create_group('next_obs') + for k, v in new_next_obs.items(): + next_obs_grp.create_dataset(k, data=v) + demo_counter += 1 + + # copy episode attributes + for key, val in ep.attrs.items(): + ep_grp.attrs[key] = val + + # copy dataset attributes + for key, val in data.attrs.items(): + if key == 'dataset_id': + data_grp.attrs[key] = str(uuid.uuid4()) + else: + data_grp.attrs[key] = val + +def load_discriminator(discriminator_path: str, device: torch.device): + policy, ckpt_dict = FileUtils.policy_from_checkpoint(ckpt_path=discriminator_path, device=device, verbose=True, discriminator=True) + return policy + +@click.command() +@click.option('--dataset', '-d', help='Datset file path') +@click.option('--output_name', '-o', help='Output file name') +@click.option('--discriminator_path', '-dp', help='Discriminator path') +@click.option('--threshold', '-t', type=float, help='Threshold for classifying states', default=0.0) +def run(dataset, output_name, discriminator_path, threshold): + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + discriminator = load_discriminator(discriminator_path, device) + output_path = os.path.join(os.path.dirname(dataset), output_name) + + classify_states(output_path, dataset, discriminator, device, threshold=threshold) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/ilid/discriminator.py b/code_src/rise_code/sim_pipeline/ilid/discriminator.py new file mode 100644 index 0000000000000000000000000000000000000000..aa8cec30472f2c286904c4116cad43577b236876 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/ilid/discriminator.py @@ -0,0 +1,132 @@ +from collections import OrderedDict + +import torch +from torch import nn +from robomimic.models.obs_nets import MIMO_MLP +from robomimic.algo import register_algo_factory_func, PolicyAlgo + +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.obs_utils as ObsUtils +import robomimic.utils.torch_utils as TorchUtils + +class Discriminator_MLP(MIMO_MLP): + def __init__(self, obs_shapes, hidden_dim=256): + # requires robomimic OBS_KEYS_TO_MODALITIES to be defined + obs_group_shapes = {'obs': obs_shapes} + obs_group_shapes = OrderedDict(obs_group_shapes) + output_shapes = OrderedDict(expert=(1)) + layer_dims = [hidden_dim, hidden_dim, 1] + super().__init__( + input_obs_group_shapes=obs_group_shapes, + output_shapes=output_shapes, + layer_dims=layer_dims, + activation=nn.ReLU, + output_activation=None, + layer_func=nn.Linear, + ) + + def forward(self, **inputs): + # import ipdb; ipdb.set_trace() + enc_outputs = self.nets["encoder"](**inputs) + mlp_outputs = self.nets["mlp"](enc_outputs) + return mlp_outputs + + +class Discriminator(PolicyAlgo): + def __init__(self, config, obs_shapes, hidden_dim=256, device='cpu'): + self.optim_params = config.algo.optim_params + self.config = config + self.device = device + + self.nets = nn.ModuleDict() + self.nets['policy'] = Discriminator_MLP(obs_shapes, hidden_dim=hidden_dim) + self.nets = self.nets.float().to(self.device) + + self._create_optimizers() + + def train_on_batch(self, batch, epoch, validate): + with TorchUtils.maybe_no_grad(no_grad=validate): + # print(f'expert_batch : {expert_batch.keys()}') + info = OrderedDict() + predictions = self._forward_training(batch) + losses = self._compute_losses(predictions, batch['labels']) + + info["losses"] = TensorUtils.detach(losses) + + if not validate: + step_info = self._train_step(losses) + info.update(step_info) + + return info + + def _forward_training(self, batch): + predictions = OrderedDict() + preds = self.nets['policy'](obs=batch['obs']) + predictions['preds'] = preds + return predictions + + + def get_action(self, obs_dict, goal_dict=None): + preds = self.nets['policy'](obs=obs_dict) + return preds + + def _compute_losses(self, preds, labels): + loss = nn.BCEWithLogitsLoss()(preds['preds'], labels) + + # Compute accuracy by comparing predicted class (>0.5 after sigmoid) with true labels + with torch.no_grad(): + predictions = torch.sigmoid(preds['preds']) > 0.5 + accuracy = (predictions == labels).float().mean() + + losses = OrderedDict() + losses["prediction_loss"] = [loss] + losses["accuracy"] = [accuracy] + return losses + + def _train_step(self, losses): + + # gradient step + info = OrderedDict() + policy_grad_norms = TorchUtils.backprop_for_loss( + net=self.nets["policy"], + optim=self.optimizers["policy"], + loss=losses["prediction_loss"][0], + ) + info["prediction_loss"] = losses["prediction_loss"][0] + info["accuracy"] = losses["accuracy"][0] + # info["policy_grad_norms"] = policy_grad_norms + return info + + def process_batch_for_training(self, batch): + input_batch = dict() + input_batch["obs"] = {k: batch["obs"][k][:, 0, :] for k in batch["obs"]} + # for k in input_batch["obs"]: + # if 'image' in k: + # # switch to channels last + # input_batch['obs'][k] = input_batch['obs'][k].permute(0, 2, 3, 1) + input_batch["labels"] = batch["rewards"][:, 0].reshape(-1, 1) + # we move to device first before float conversion because image observation modalities will be uint8 - + # this minimizes the amount of data transferred to GPU + return TensorUtils.to_float(TensorUtils.to_device(input_batch, self.device)) + + def _create_optimizers(self): + self.optimizers = dict() + self.lr_schedulers = dict() + self.optimizers["policy"] = torch.optim.Adam(self.nets["policy"].parameters(),lr=0.0001, weight_decay=1e-3) + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + log = OrderedDict() + + log["bce_loss"] = info["prediction_loss"].item() + log["accuracy"] = info["accuracy"].item() + return log \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/ilid/eval_discrminator copy.py b/code_src/rise_code/sim_pipeline/ilid/eval_discrminator copy.py new file mode 100644 index 0000000000000000000000000000000000000000..8b41b6f851f583c8fe4e0ca0d808eefb4f8f76f3 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/ilid/eval_discrminator copy.py @@ -0,0 +1,10 @@ +import torch + + +def run(): + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + ckpt_dict = torch.load('/home/kevin/ood/sim_pipeline/sim_pipeline/logs/discriminator_threading_test/20250127215826/models/test.pth') + import ipdb; ipdb.set_trace() + +if __name__ == '__main__': + run() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/ilid/eval_discrminator.py b/code_src/rise_code/sim_pipeline/ilid/eval_discrminator.py new file mode 100644 index 0000000000000000000000000000000000000000..c00e2860af86cbfde016bf1d92f3df97320305c6 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/ilid/eval_discrminator.py @@ -0,0 +1,54 @@ +import os +import h5py +import torch +import click + +import robomimic.utils.file_utils as FileUtils +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.obs_utils as ObsUtils +from sim_pipeline.ilid.discriminator import Discriminator + + +def classify_states( + data_path: str, + discriminator: Discriminator, + device: torch.device, +): + with h5py.File(data_path, 'r') as f: + data = f['data'] + for ep_key in data: + ep = data[ep_key] + obs = ep['obs'] + # Create batch of observations for entire episode + obs_dict = {k: obs[k][:] for k in obs.keys() if k in ['agentview_image', 'robot0_eye_in_hand_image', 'robot0_eef_pos', 'robot0_eef_quat', 'robot0_gripper_qpos']} + + # reshape image keys to (C, H, W) + for k in obs_dict.keys(): + if 'image' in k: + obs_dict[k] = obs_dict[k].transpose(0, 3, 1, 2) + # scale from (0, 255) to (0, 1) + obs_dict[k] = obs_dict[k].astype(float) / 255.0 + ob = TensorUtils.to_tensor(obs_dict) + ob = TensorUtils.to_device(ob, device) + ob = TensorUtils.to_float(ob) + # import ipdb; ipdb.set_trace() + # Get predictions for all states at once + predictions = discriminator.policy.get_action(ob) + + print(predictions) + +def load_discriminator(discriminator_path: str, device: torch.device): + policy, ckpt_dict = FileUtils.policy_from_checkpoint(ckpt_path=discriminator_path, device=device, verbose=True, discriminator=True) + return policy + +@click.command() +@click.option('--dataset', '-d', help='Datset file path') +@click.option('--discriminator_path', '-dp', help='Discriminator path') +def run(dataset, discriminator_path): + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + discriminator = load_discriminator(discriminator_path, device) + + classify_states(dataset, discriminator, device) + +if __name__ == '__main__': + run() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/model_manager/create_model_metadata.py b/code_src/rise_code/sim_pipeline/model_manager/create_model_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..13859672a4fff0de3fa75d32380a9117c57cca11 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/model_manager/create_model_metadata.py @@ -0,0 +1,76 @@ +import sys +import json +import uuid +import getpass +import h5py +import datetime +import git + +from omegaconf import OmegaConf, DictConfig + +from pathlib import Path +from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.utils.config_utils import convert_hydra_for_serialization + +def create_model_metadata( + name: str, + policy_type: PolicyType, + policy_identifier: str, + dataset_path: str | None, + hydra_config: DictConfig, + filepath: str | Path, + valid: bool = False, + description: str = '', +): + metadata = {} + metadata['name'] = name + metadata['policy_id'] = str(uuid.uuid4()) + metadata['policy_type'] = policy_type.value + metadata['identifier'] = policy_identifier + hydra_config = OmegaConf.to_container(hydra_config) + convert_hydra_for_serialization(hydra_config) + metadata['hydra_config'] = hydra_config + + if dataset_path is not None: + with h5py.File(dataset_path, 'r') as f: + metadata['dataset_name'] = Path(dataset_path).stem + metadata['dataset_uuid'] = f['data'].attrs['dataset_id'] + if 'description' in f['data'].attrs: + metadata['dataset_description'] = f['data'].attrs['description'] + else: + metadata['dataset_description'] = '' + + metadata['creator'] = getpass.getuser() + now = datetime.datetime.now() + metadata["date"] = "{}-{}-{}".format(now.month, now.day, now.year) + metadata["time"] = "{}:{}:{}".format(now.hour, now.minute, now.second) + + try: # rsm_rise patch: the code is not a git checkout here + repo = git.Repo(search_parent_directories=True) + sha = repo.head.object.hexsha + except Exception: + sha = 'unknown' + metadata['commit'] = sha + + args = sys.argv + command = ' '.join(args) + + metadata['command'] = command + + # by default, a policy is not considered trained until after X number + # of training steps and update_metadata_trained is called. Otherwise, + # faulty/test runs would produce valid metadata + metadata['valid'] = valid + metadata['description'] = description + + with open(filepath, 'w', encoding='utf-8') as f: + json.dump(metadata, f, indent=4) + +def update_metadata_trained(filepath: str | Path): + with open(filepath, 'r', encoding='utf-8') as f: + metadata = json.load(f) + + metadata['valid'] = True + + with open(filepath, 'w', encoding='utf-8') as f: + json.dump(metadata, f, indent=4) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/model_manager/get_model.py b/code_src/rise_code/sim_pipeline/model_manager/get_model.py new file mode 100644 index 0000000000000000000000000000000000000000..398391be085ef3bf1d64ab504b23778ab81a6cc9 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/model_manager/get_model.py @@ -0,0 +1,24 @@ +import click +from sim_pipeline.configs.constants import MODEL_DB_PATH +from sim_pipeline.model_manager.model_manager import ModelManager + +def get_model(model_name: str, model_identifier: str | None = None) -> str: + if not MODEL_DB_PATH.exists(): + raise ValueError(f'Model manager not setup. Please run `scripts/setup_model_manager.py`') + + with ModelManager(MODEL_DB_PATH) as mm: + if model_identifier is not None: + result, query, params = mm.query_models(name=model_name, model_identifier=model_identifier, return_query=True) + else: + result, query, params = mm.query_models(name=model_name, return_query=True) + + if len(result) == 0: + raise ValueError(f'No models matching name {model_name} found.') + elif len(result) > 1: + mm.visualize_query_result(query, params, add_index=True) + idx = click.prompt(f'Multiple models matching name {model_name} found. Please select one by index', type=int, default=-1, show_default=False) + else: + idx = 0 + model_dir = result[idx].path + + return model_dir \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/model_manager/model_manager.py b/code_src/rise_code/sim_pipeline/model_manager/model_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..fc27bb2b8d8a340843272f43f355efa4e3e966f9 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/model_manager/model_manager.py @@ -0,0 +1,296 @@ +import sqlite3 +import json +import tabulate + +from dvc.repo import Repo +from pathlib import Path +from importlib.resources import files +from collections import namedtuple + +from sim_pipeline.configs.constants import PolicyType, ROOT_DIR +from sim_pipeline.data_manager.data_manager import _wrap_text_to_colwidths +from sim_pipeline.utils.train_utils import get_latest_diffusion_policy, get_latest_sb_policy, get_latest_robomimic_policy + +class ModelManager: + def __init__(self, db_path): + self.db_path = db_path + self.conn = sqlite3.connect(self.db_path) + self.cursor = self.conn.cursor() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.commit() + self.close + + def commit(self): + self.conn.commit() + + def close(self): + self.conn.close() + + def create_tables(self): + """ + Create database tables based on schema. Removes all existing tables. + """ + self.empty_tables() + + with open(files('sim_pipeline.model_manager') / 'create_tables.sql', 'r') as sql_file: + sql_script = sql_file.read() + self.cursor.executescript(sql_script) + + self.populate_initial_types() + + self.conn.commit() + + def empty_tables(self): + """ + Remove all tables from database. + """ + self.cursor.execute("PRAGMA foreign_keys = OFF;") + + self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%';") + tables = self.cursor.fetchall() + + for table_name in tables: + self.cursor.execute(f"DROP TABLE IF EXISTS {table_name[0]};") + + try: + self.cursor.execute("DELETE FROM sqlite_sequence;") + except sqlite3.OperationalError: + pass + + self.cursor.execute("PRAGMA foreign_keys = ON;") + + def populate_initial_types(self): + """ + Initialize the tables with the type definitions of each enum. + """ + self.cursor.executemany( + 'INSERT INTO PolicyTypes (type) VALUES (?)', + [(status.value,) for status in PolicyType] + ) + + def parse_directories(self, directories: list[Path]): + """ + Parse directories for model metadata and add to database. + """ + for dirname in directories: + if not dirname.is_dir(): + print(f'Warning: {dirname} is not a directory.') + continue + + for path in dirname.iterdir(): + if path.is_file() and path.name == 'metadata.json': + print(f'Parsing {path}') + self.add_model_metadata(path) + elif path.is_dir(): + self.parse_directories([path]) + + def add_model_metadata(self, filepath: Path): + """ + Add model metadata to database. + """ + with open(filepath, 'r', encoding='utf-8') as f: + metadata = json.load(f) + if not metadata['valid']: + return + + path = filepath.parent + + self.insert_data( + 'Models', + { + 'id': str(metadata['policy_id']), + 'name': metadata['name'], + 'identifier': metadata['identifier'], + 'creator': metadata['creator'], + 'path': str(path), + 'description': metadata['description'], + } + ) + + policy_type_id = self.fetch_id('PolicyTypes', 'type', metadata['policy_type']) + self.insert_data( + 'ModelPolicyTypes', + { + 'model_id': metadata['policy_id'], + 'policy_type_id': policy_type_id, + } + ) + + if 'dataset_uuid' in metadata: + self.insert_data( + 'ModelDatasetAssociations', + { + 'model_id': metadata['policy_id'], + 'dataset_id': metadata['dataset_uuid'], + 'dataset_name': metadata['dataset_name'], + } + ) + + def insert_data(self, table_name, data): + columns = ', '.join(data.keys()) + values = ', '.join([f"'{v}'" for v in data.values()]) + self.cursor.execute(f"INSERT INTO {table_name} ({columns}) VALUES ({values})") + + + def fetch_id(self, table_name, matching, name, none_ok=False): + try: + return self.cursor.execute(f'SELECT id FROM {table_name} WHERE {matching} = ?', (name,)).fetchone()[0] + except TypeError: + if none_ok: + return None + raise ValueError(f'{matching} = {name} not found in {table_name} table. Likely {name} was not inserted into enum table.') + + def query_models(self, return_all=False, return_query=False, **kwargs): + if return_all: + query_t = namedtuple('query_t', ['id', 'name', 'path', 'identifier', 'creator', 'description', 'policy_type']) + query = """ + SELECT m.id, m.name, m.path, m.identifier, m.creator, m.description, pt.type + FROM Models m + LEFT JOIN ModelPolicyTypes mpt ON m.id = mpt.model_id + LEFT JOIN PolicyTypes pt ON mpt.policy_type_id = pt.id + WHERE 1=1 + """ + else: + query_t = namedtuple('query_t', ['name', 'identifier', 'path']) + query = """ + SELECT m.id, m.name, m.path + FROM Models m + WHERE 1=1 + """ + + params = [] + + def add_simple_condition(field, table, column, model_id_column='id'): + nonlocal query, params + if field in kwargs: + values = kwargs[field] if isinstance(kwargs[field], list) else [kwargs[field]] + placeholders = ','.join(['?' for _ in values]) + query += f" AND m.id IN (SELECT {model_id_column} FROM {table} WHERE {column} IN ({placeholders}))" + params.extend(values) + + def add_subset_condition(field, table, type_column, id_column): + """ + the values are a subset of the query + """ + nonlocal query, params + if field in kwargs: + values = kwargs[field] if isinstance(kwargs[field], list) else [kwargs[field]] + placeholders = ','.join(['?' for _ in values]) + query += f""" + AND NOT EXISTS ( + SELECT 1 + FROM {table} + WHERE dataset_id = d.id + AND {type_column} NOT IN ({placeholders}) + ) + AND EXISTS ( + SELECT 1 + FROM {table} + WHERE dataset_id = d.id + ) + """ + params.extend(values) + + add_simple_condition('id', 'Models', 'id') + add_simple_condition('name', 'Models', 'name') + add_simple_condition('creator', 'Models', 'creator') + add_simple_condition('identifier', 'Models', 'identifier') + + add_simple_condition('dataset_name', 'ModelDatasetAssociations', 'datatset_name', 'model_id') + + add_subset_condition('policy_type', 'ModelPolicyTypes mpt JOIN PolicyTypes pt ON mpt.policy_type_id = pt.id', 'pt.type', 'pt.id') + + self.cursor.execute(query, params) + results = self.cursor.fetchall() + + results = [query_t(*result) for result in results] + if return_query: + return results, query, params + return results + + def get_all_model_and_metadata_paths(self): + results = self.query_models(return_all=True) + paths = [Path(result.path) for result in results] + policy_types = [PolicyType(result.policy_type) for result in results] + metadata_paths = [path / 'metadata.json' for path in paths] + + all_latest_ckpt_paths = [] + for path, policy_type in zip(paths, policy_types): + match policy_type: + case PolicyType.DIFFUSION: + ckpt = get_latest_diffusion_policy(path / 'checkpoints') + case PolicyType.ROBOMIMIC: + ckpt = get_latest_robomimic_policy(path / 'models') + case PolicyType.STABLE_BASELINES: + ckpt = get_latest_sb_policy(path / 'policy' / '_step_') + case _: + pass + all_latest_ckpt_paths.append(ckpt) + all_latest_ckpt_paths.extend(metadata_paths) + return all_latest_ckpt_paths + + def dvc_add_all(self): + all_paths = self.get_all_model_and_metadata_paths() + repo = Repo(ROOT_DIR) + for path in all_paths: + repo.add(str(path)) + + def visualize_table(self, table_name, limit=None): + self.cursor.execute(f"PRAGMA table_info({table_name});") + columns = [column[1] for column in self.cursor.fetchall()] + + # Get table data + if limit: + self.cursor.execute(f"SELECT * FROM {table_name} LIMIT {limit};") + else: + self.cursor.execute(f"SELECT * FROM {table_name};") + rows = self.cursor.fetchall() + + print(f"\nContents of table '{table_name}':") + print(tabulate.tabulate(rows, headers=columns, tablefmt="grid")) + print(f"Total rows: {len(rows)}") + + def visualize_query_result(self, query, params=None, maxcolwidths=25, to_csv=False, add_index=False): + # Execute the provided query + if params: + self.cursor.execute(query, params) + else: + self.cursor.execute(query) + rows = self.cursor.fetchall() + + # Get column headers from the cursor description + columns = [column[0] for column in self.cursor.description] + if add_index: + columns = ['index'] + columns + rows = [[i] + list(row) for i, row in enumerate(rows)] + + if to_csv: + with open('all_models.csv', 'w') as f: + content = tabulate.tabulate(rows, headers=columns, tablefmt='csv') + with open('all_models.csv', 'w') as f: + f.write(content) + print(f"\nQuery result saved to all_models.csv") + else: + print(f"\nQuery result:") + print(tabulate.tabulate(rows, headers=columns, tablefmt="grid", maxcolwidths=maxcolwidths)) + print(f"Total rows: {len(rows)}") + + def visualize_all(self, to_csv=False, show_id=False): + id_str = 'm.id, ' if show_id else '' + + query = f""" + SELECT DISTINCT {id_str}m.name, m.path, m.identifier, m.creator, pt.type, m.description, mda.dataset_name, mda.dataset_id + FROM Models m + LEFT JOIN ModelPolicyTypes mpt ON m.id = mpt.model_id + LEFT JOIN PolicyTypes pt ON mpt.policy_type_id = pt.id + LEFT JOIN ModelDatasetAssociations mda ON m.id = mda.model_id + """ + maxcolwidths = [15, 35, 12, 12, 12, 30, 20, 35] + maxcolwidths = [50] + maxcolwidths if show_id else maxcolwidths + self.visualize_query_result(query, maxcolwidths=maxcolwidths, to_csv=to_csv) + +tabulate._wrap_text_to_colwidths = _wrap_text_to_colwidths diff --git a/code_src/rise_code/sim_pipeline/model_manager/model_summary.py b/code_src/rise_code/sim_pipeline/model_manager/model_summary.py new file mode 100644 index 0000000000000000000000000000000000000000..9c1af5fd6a5a507b5bcf916adae858036e68b16b --- /dev/null +++ b/code_src/rise_code/sim_pipeline/model_manager/model_summary.py @@ -0,0 +1,26 @@ +import json +from pathlib import Path +from sim_pipeline.model_manager.get_model import get_model + +def get_model_summary(name: str, model_identifier: str | None, model_dir_path: str | None): + if model_dir_path is not None: + model_dir = model_dir_path + else: + model_dir = get_model(name, model_identifier) + + model_dir = Path(model_dir) + metadata_path = model_dir / 'metadata.json' + + with open(metadata_path, 'r') as f: + metadata = json.load(f) + + print(f'Model Directory: {model_dir}') + print('==== Model Metadata ====') + print(f'Name: {metadata["name"]}') + print(f'Identifier: {metadata["identifier"]}') + print(f'Policy ID: {metadata["policy_id"]}') + print(f'Policy Type: {metadata["policy_type"]}') + print(f'Creator: {metadata["creator"]}') + print(f'Date: {metadata["date"]}') + print(f'Command: {metadata["command"]}') + print(f'Description: {metadata["description"]}') \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/reward_functions/__init__.py b/code_src/rise_code/sim_pipeline/reward_functions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e053193996456c94e12fbddaf83c1bb5c3479a12 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/reward_functions/__init__.py @@ -0,0 +1,7 @@ +from sim_pipeline.reward_functions.reward_registry import create_reward_function_enum + +from sim_pipeline.reward_functions import square_reward + +RewardFunction = create_reward_function_enum() + +__all__ = ['RewardFunction'] \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/reward_functions/reward_registry.py b/code_src/rise_code/sim_pipeline/reward_functions/reward_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..b3bdb5c5e7ed5d64087d0d52c88744d3651ff3ab --- /dev/null +++ b/code_src/rise_code/sim_pipeline/reward_functions/reward_registry.py @@ -0,0 +1,36 @@ +from enum import Enum +from typing import Callable, Dict + +MODULE_NAME_TO_FUNCTION: Dict[str, Dict[str, Callable]] = {} + +def register_reward_func(func: Callable) -> Callable: + """ + Decorator to register reward functions. + """ + global MODULE_NAME_TO_FUNCTION + module_name = func.__module__.split('.')[-1] + func_name = func.__name__ + + if module_name not in MODULE_NAME_TO_FUNCTION: + MODULE_NAME_TO_FUNCTION[module_name] = {} + + MODULE_NAME_TO_FUNCTION[module_name][func_name] = func + return func + +def create_reward_function_enum() -> type: + """ + Create and return the RewardFunction Enum class. + """ + enum_dict = {} + for module_name, funcs in MODULE_NAME_TO_FUNCTION.items(): + for func_name in funcs: + enum_name = f"{module_name.upper()}_{func_name.upper()}" + enum_value = f'{module_name}.{func_name}' + enum_dict[enum_name] = enum_value + + return Enum('RewardFunction', enum_dict, type=RewardFunctionEnum) + +class RewardFunctionEnum(Enum): + def get_function(self) -> Callable: + module_name, func_name = self.value.split('.') + return MODULE_NAME_TO_FUNCTION[module_name][func_name] diff --git a/code_src/rise_code/sim_pipeline/reward_functions/square_reward.py b/code_src/rise_code/sim_pipeline/reward_functions/square_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..13485b1db742b8d7b2e02142e7c08ffd64a741ec --- /dev/null +++ b/code_src/rise_code/sim_pipeline/reward_functions/square_reward.py @@ -0,0 +1,231 @@ +import numpy as np + +from sim_pipeline.utils.get_base_env import get_base_env +from sim_pipeline.reward_functions.reward_registry import register_reward_func +from robosuite.environments.manipulation.nut_assembly import NutAssembly + + +@register_reward_func +def reaching_reward(obs, act, env): + env = get_base_env(env, NutAssembly) + if env is None: + raise ValueError('Invalid env class. Must wrap a NutAssembly.') + + nut_name = 'SquareNut' + + gripper = env.robots[0].gripper + gripper_pos: np.ndarray = env.sim.data.get_site_xpos(gripper.important_sites['grip_site']) + object_loc_center: np.ndarray = env.sim.data.body_xpos[env.obj_body_id[nut_name]] + + dist = np.linalg.norm(gripper_pos - object_loc_center) + + return -dist + + +@register_reward_func +def pushing_reward(obs, act, env): + env = get_base_env(env, NutAssembly) + if env is None: + raise ValueError('Invalid env class. Must wrap a NutAssembly.') + + nut_name = 'SquareNut' + + # shape (3,) -> (x, y, z) + object_loc: np.ndarray = env.sim.data.body_xpos[env.obj_body_id[nut_name]] + + # avg position of ID + goal_position = np.array([-0.1125, 0.1675, 0.823]) + + dist = np.linalg.norm(object_loc - goal_position) + + return -dist + +@register_reward_func +def pushing_reward_mid(obs, act, env): + env = get_base_env(env, NutAssembly) + if env is None: + raise ValueError('Invalid env class. Must wrap a NutAssembly.') + + nut_name = 'SquareNut' + + # shape (3,) -> (x, y, z) + object_loc: np.ndarray = env.sim.data.body_xpos[env.obj_body_id[nut_name]] + + # avg position of ID + goal_position = np.array([-0.1025, -0.005, 0.823]) + + dist = np.linalg.norm(object_loc - goal_position) + + return -dist + +@register_reward_func +def pushing_reward_ll(obs, act, env): + env = get_base_env(env, NutAssembly) + if env is None: + raise ValueError('Invalid env class. Must wrap a NutAssembly.') + + nut_name = 'SquareNut' + + # shape (3,) -> (x, y, z) + object_loc: np.ndarray = env.sim.data.body_xpos[env.obj_body_id[nut_name]] + + # avg position of ID + goal_position = np.array([0.06, -0.06, 0.823]) + + dist = np.linalg.norm(object_loc - goal_position) + + return -dist + +@register_reward_func +def reach_and_push_reward(obs, act, env): + reaching_rew = reaching_reward(obs, act, env) + pushing_rew = pushing_reward(obs, act, env) + return reaching_rew + 2 * pushing_rew + +@register_reward_func +def reach_and_push_reward_mid(obs, act, env): + reaching_rew = reaching_reward(obs, act, env) + pushing_rew = pushing_reward_mid(obs, act, env) + return reaching_rew + 2 * pushing_rew + +@register_reward_func +def reach_and_push_reward_ll(obs, act, env): + reaching_rew = reaching_reward(obs, act, env) + pushing_rew = pushing_reward_ll(obs, act, env) + return reaching_rew + 2 * pushing_rew + +@register_reward_func +def stable_pushing_reward(obs, act, env): + reach_and_push_rew = reach_and_push_reward(obs, act, env) + + def rotate_vector(q, v): + """ + Rotate a 3D vector using a quaternion. + + Args: + q (numpy.array): Quaternion in the form [w, x, y, z] (scalar first) + v (numpy.array): 3D vector to rotate + + Returns: + numpy.array: Rotated 3D vector + """ + # Ensure q is a unit quaternion + q = q / np.linalg.norm(q) + + # Extract components + w, x, y, z = q + + # Compute the rotated vector + v_rotated = v + 2 * np.cross(q[1:], np.cross(q[1:], v) + w * v) + + return v_rotated + def rotational_distance(v1, v2): + """ + Calculate the rotational distance (angle) between two 3D vectors. + + Args: + v1 (numpy.array): First 3D vector + v2 (numpy.array): Second 3D vector + + Returns: + float: Angle between the vectors in radians + """ + # Normalize the vectors + v1_normalized = v1 / np.linalg.norm(v1) + v2_normalized = v2 / np.linalg.norm(v2) + + # Calculate the dot product + dot_product = np.dot(v1_normalized, v2_normalized) + + # Clamp the dot product to [-1, 1] to avoid numerical errors + dot_product = np.clip(dot_product, -1.0, 1.0) + + # Calculate the angle using arccos + angle = np.arccos(dot_product) + + return angle + + # in robosuite, yaw is x-axis, we don't care about yaw + vector = np.array([1, 0, 0]) + + # make more efficient? + obs = env._get_observations() + rotated = rotate_vector(obs['robot0_eef_quat'], vector) + + return -rotational_distance(vector, rotated) + reach_and_push_rew + + +@register_reward_func +def stable_pushing_reward_ll(obs, act, env): + reach_and_push_rew = reach_and_push_reward_ll(obs, act, env) + + def rotate_vector(q, v): + """ + Rotate a 3D vector using a quaternion. + + Args: + q (numpy.array): Quaternion in the form [w, x, y, z] (scalar first) + v (numpy.array): 3D vector to rotate + + Returns: + numpy.array: Rotated 3D vector + """ + # Ensure q is a unit quaternion + q = q / np.linalg.norm(q) + + # Extract components + w, x, y, z = q + + # Compute the rotated vector + v_rotated = v + 2 * np.cross(q[1:], np.cross(q[1:], v) + w * v) + + return v_rotated + def rotational_distance(v1, v2): + """ + Calculate the rotational distance (angle) between two 3D vectors. + + Args: + v1 (numpy.array): First 3D vector + v2 (numpy.array): Second 3D vector + + Returns: + float: Angle between the vectors in radians + """ + # Normalize the vectors + v1_normalized = v1 / np.linalg.norm(v1) + v2_normalized = v2 / np.linalg.norm(v2) + + # Calculate the dot product + dot_product = np.dot(v1_normalized, v2_normalized) + + # Clamp the dot product to [-1, 1] to avoid numerical errors + dot_product = np.clip(dot_product, -1.0, 1.0) + + # Calculate the angle using arccos + angle = np.arccos(dot_product) + + return angle + + # in robosuite, yaw is x-axis, we don't care about yaw + vector = np.array([1, 0, 0]) + + # make more efficient? + obs = env._get_observations() + rotated = rotate_vector(obs['robot0_eef_quat'], vector) + + return -rotational_distance(vector, rotated) + reach_and_push_rew + +@register_reward_func +def stable_and_smooth_pushing_reward(obs, act, env, smooth_scale=0.1): + stable_pushing_rew = stable_pushing_reward(obs, act, env) + + def smoothness_reward(env): + # penalize large actions + #return -np.linalg.norm(act)o current_eef_pos = env.sim.data.get_site_xpos(env.robots[0].gripper.important_sites['grip_site']) + gripper = env.robots[0].gripper + #eef_velocity : np.ndarray = env.sim.data.get_site_xvel(gripper.important_sites['grip_site']) + eef_velocity: np.ndarray = env.sim.data.get_body_xvelp('gripper0_eef') + + return -np.linalg.norm(eef_velocity) + + return stable_pushing_rew + smooth_scale * smoothness_reward(env) diff --git a/code_src/rise_code/sim_pipeline/reward_wrapper.py b/code_src/rise_code/sim_pipeline/reward_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..d40176a05604cdab434e48080f836c724550d64f --- /dev/null +++ b/code_src/rise_code/sim_pipeline/reward_wrapper.py @@ -0,0 +1,65 @@ +import gymnasium as gym +import mujoco +import numpy as np +from enum import Enum + +class TaskRewardType: + PICK_PLACE = 'pick_place' + PUSH = 'push' + +class RewardWrapper(gym.Wrapper): + def __init__(self, env, reward_name: TaskRewardType=None, **kwargs): + super().__init__(env) + + if reward_name == TaskRewardType.PICK_PLACE: + self.reward_fn = self.pick_place_reward + elif reward_name == TaskRewardType.PUSH: + self.reward_fn = self.push_reward + else: + self.reward_fn = self.default_reward + + def step(self, action): + obs, orig_rew, done, info = self.env.step(action) + + reward = self.reward_fn(action) + + return obs, reward + orig_rew, done, info + + def default_reward(self, action): + return 0.0 + + def pick_place_reward(self, action): + # from maniskill + reward = 0.0 + + # reaching reward + ee_pos = self.env.unwrapped._robot.get_ee_pose()[:2] + obj_pos = self.env.get_obj_pose() + dist = np.linalg.norm(ee_pos - obj_pos) + reaching_reward = 1 - np.tanh(5 * dist) + reward += reaching_reward + + # grasp reward, need to implement this somehow + # is_grasped = self.agent.check_grasp(self.obj, max_angle=30) + # if is_grasped: + # reward += 0.25 + + # if is_grasped: + obj_to_goal_dist = np.linalg.norm(np.r_[self.goal_obj_pose['x'], self.goal_obj_pose['y'], 0.0] - obj_pos) + place_reward = 1 - np.tanh(5 * obj_to_goal_dist) + reward += place_reward + + return reward + + def push_reward(self, action): + # from patrick's code + obj_pose = self.env.get_obj_pose() + ee_pos = self.env.unwrapped._robot.get_ee_pose()[:2] + goal_ee_pos = obj_pose[:2] + goal_ee_pos[0] -= 0.035 + ee_dist_to_goal = np.linalg.norm(ee_pos - goal_ee_pos) + obj_dist_to_goal = np.linalg.norm(self.goal_obj_pose['x'] - obj_pose[0]) + goal_reached = obj_dist_to_goal < .025 + obj_off_table = obj_pose[2] <= 0. + return - ee_dist_to_goal - obj_dist_to_goal + goal_reached - obj_off_table + diff --git a/code_src/rise_code/sim_pipeline/success_functions/__init__.py b/code_src/rise_code/sim_pipeline/success_functions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a46581bfa3060aeb33fee7da5e4d95692aafe5a9 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/success_functions/__init__.py @@ -0,0 +1,7 @@ +from sim_pipeline.success_functions.success_registry import create_success_function_enum + +from sim_pipeline.success_functions import square_success + +SuccessFunction = create_success_function_enum() + +__all__ = ['SuccessFunction'] \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/success_functions/square_success.py b/code_src/rise_code/sim_pipeline/success_functions/square_success.py new file mode 100644 index 0000000000000000000000000000000000000000..a36152fd9bfdf0381c6929ef08e524d6671b6a7b --- /dev/null +++ b/code_src/rise_code/sim_pipeline/success_functions/square_success.py @@ -0,0 +1,21 @@ +import numpy as np + +from sim_pipeline.utils.get_base_env import get_base_env +from sim_pipeline.success_functions.success_registry import register_success_func +from robosuite.environments.manipulation.nut_assembly import NutAssembly + + +@register_success_func +def pushing_success(obs, env): + env = get_base_env(env, NutAssembly) + if env is None: + raise ValueError('Invalid env class. Must wrap a NutAssembly.') + + nut_name = 'SquareNut' + # avg position of ID + goal_position = np.array([-0.1125, 0.1675, 0.823]) + + object_loc_center: np.ndarray = env.sim.data.body_xpos[env.obj_body_id[nut_name]] + + dist = np.linalg.norm(object_loc_center - goal_position) + return dist < 0.07 \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/success_functions/success_registry.py b/code_src/rise_code/sim_pipeline/success_functions/success_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..972c3eff599dbf5c47666c64672cda4f628249bc --- /dev/null +++ b/code_src/rise_code/sim_pipeline/success_functions/success_registry.py @@ -0,0 +1,36 @@ +from enum import Enum +from typing import Callable, Dict + +SUCCESS_MODULE_NAME_TO_FUNCTION: Dict[str, Dict[str, Callable]] = {} + +def register_success_func(func: Callable) -> Callable: + """ + Decorator to register success functions. + """ + global SUCCESS_MODULE_NAME_TO_FUNCTION + module_name = func.__module__.split('.')[-1] + func_name = func.__name__ + + if module_name not in SUCCESS_MODULE_NAME_TO_FUNCTION: + SUCCESS_MODULE_NAME_TO_FUNCTION[module_name] = {} + + SUCCESS_MODULE_NAME_TO_FUNCTION[module_name][func_name] = func + return func + +def create_success_function_enum() -> type: + """ + Create and return the SuccessFunction Enum class. + """ + enum_dict = {} + for module_name, funcs in SUCCESS_MODULE_NAME_TO_FUNCTION.items(): + for func_name in funcs: + enum_name = f"{module_name.upper()}_{func_name.upper()}" + enum_value = f'{module_name}.{func_name}' + enum_dict[enum_name] = enum_value + + return Enum('SuccessFunction', enum_dict, type=SuccessFunctionEnum) + +class SuccessFunctionEnum(Enum): + def get_function(self) -> Callable: + module_name, func_name = self.value.split('.') + return SUCCESS_MODULE_NAME_TO_FUNCTION[module_name][func_name] diff --git a/code_src/rise_code/sim_pipeline/training/custom_callback.py b/code_src/rise_code/sim_pipeline/training/custom_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..80f173e83eeaba164ab47bb6fc4f9ecd19052c75 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/training/custom_callback.py @@ -0,0 +1,49 @@ +import numpy as np +from stable_baselines3.common.callbacks import BaseCallback +from sim_pipeline.eval.rollout_env import PossibleVecEnv +from sim_pipeline.eval.rollout_policies.sb_rollout_policy import StableBaselinesRolloutPolicy +from sim_pipeline.eval.rollout import rollout +from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.eval.rollout_stats import RolloutStats + +class LoggerCallback(BaseCallback): + """ + A custom callback that derives from BaseCallback. + """ + + def __init__( + self, eval_envs, eval_interval, save_dir, save_interval, verbose=False + ): + super(LoggerCallback, self).__init__(verbose) + + self.eval_interval = eval_interval + + self.save_dir = save_dir + self.save_interval = save_interval + + self.eval_envs = PossibleVecEnv(eval_envs) + self.eval_envs.reset() + + self.rollout_stats = RolloutStats() + + self.reward_sum = 0.0 + + def _on_step(self) -> bool: + """ + This method will be called by the model after each call to `env.step()`. + """ + self.reward_sum += np.mean(self.locals["rewards"]) + + if np.all(self.locals["dones"]): + self.logger.record("eval/return", self.reward_sum) + self.reward_sum = 0 + + if (self.n_calls - 1) % self.eval_interval == 0: + rollout_model = StableBaselinesRolloutPolicy(self.model) + rollout(rollout_model, self.eval_envs, self.rollout_stats, self.logger, total_steps=200, tag="eval") + + if (self.n_calls - 1) % self.save_interval == 0: + self.model.save(self.save_dir / "_step_" / str(self.n_calls)) + # self.model.save_replay_buffer(self.save_dir / "_replay_buffer.pkl") + + return True diff --git a/code_src/rise_code/sim_pipeline/training/init_buffer.py b/code_src/rise_code/sim_pipeline/training/init_buffer.py new file mode 100644 index 0000000000000000000000000000000000000000..fcfbca3a2bd5ebf58fadbcd6ac481c4ab527ef8e --- /dev/null +++ b/code_src/rise_code/sim_pipeline/training/init_buffer.py @@ -0,0 +1,117 @@ +import h5py +import numpy as np +from stable_baselines3.common.buffers import ReplayBuffer +from stable_baselines3.common.vec_env import VecEnv +from sim_pipeline.utils.obs_dict_tools import flatten_obs_dict +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig +from sim_pipeline.envs.robosuite_wrapper import RobomimicObsWrapper + +def init_buffer(buffer: ReplayBuffer, dataset_path: str, env: RobomimicObsWrapper | VecEnv, env_config: RobomimicEnvConfig | None): + """ + Given a ReplayBuffer, loads a dataset from a given path and adds the data to the buffer. + """ + dataset = h5py.File(dataset_path, 'r') + + episode_names: list[str] = list(dataset['data'].keys()) + n_envs: int = buffer.n_envs + + # to add to sb3 buffer, needs to be in chunks of n_envs, so there will be leftovers. + # try to group together all leftovers from all episodes so that as little data is wasted as possible + leftover_obs = [] + leftover_next_obs = [] + leftover_actions = [] + leftover_rewards = [] + leftover_dones = [] + for ep_name in episode_names: + episode = dataset['data'][ep_name] + + obs_dict = episode['obs'] + next_obs_dict = episode['next_obs'] + if isinstance(env, VecEnv): + robot_prefix = env.env_method('get_prefix')[0] + else: + robot_prefix = env.get_prefix() + # Shape (ep_len, obs_dim) + obs = flatten_obs_dict(obs_dict, robot_prefix, env_config) + next_obs = flatten_obs_dict(next_obs_dict, robot_prefix, env_config) + # Shape (ep_len, act_dim) + actions = episode['actions'] + # Shape (ep_len, ) + rewards = episode['rewards'] + dones = episode['dones'] + + # convert to (n_env, dim) chunks + ep_len = obs.shape[0] + n_chunks = ep_len // n_envs + leftover = ep_len % n_envs + + if leftover > 0: + obs_chunks = np.split(obs[:-leftover], n_chunks) + next_obs_chunks = np.split(next_obs[:-leftover], n_chunks) + actions_chunks = np.split(actions[:-leftover], n_chunks) + rewards_chunks = np.split(rewards[:-leftover], n_chunks) + dones_chunks = np.split(dones[:-leftover], n_chunks) + + leftover_obs.append(obs[-leftover:]) + leftover_next_obs.append(next_obs[-leftover:]) + leftover_actions.append(actions[-leftover:]) + leftover_rewards.append(rewards[-leftover:]) + leftover_dones.append(dones[-leftover:]) + else: + obs_chunks = np.split(obs, n_chunks) + next_obs_chunks = np.split(next_obs, n_chunks) + actions_chunks = np.split(actions, n_chunks) + rewards_chunks = np.split(rewards, n_chunks) + dones_chunks = np.split(dones, n_chunks) + + infos = [{} for _ in range(n_envs)] + + for i in range(len(obs_chunks)): + buffer.add( + obs_chunks[i], + next_obs_chunks[i], + actions_chunks[i], + rewards_chunks[i], + dones_chunks[i], + infos + ) + + # Deal with leftovers + if leftover_obs: + leftover_obs = np.concatenate(leftover_obs, axis=0) + leftover_next_obs = np.concatenate(leftover_next_obs, axis=0) + leftover_actions = np.concatenate(leftover_actions, axis=0) + leftover_rewards = np.concatenate(leftover_rewards, axis=0) + leftover_dones = np.concatenate(leftover_dones, axis=0) + + num_leftover = leftover_obs.shape[0] + n_chunks = num_leftover // n_envs + leftover = num_leftover % n_envs + + if leftover > 0: + obs_chunks = np.split(leftover_obs[:-leftover], n_chunks) + next_obs_chunks = np.split(leftover_next_obs[:-leftover], n_chunks) + actions_chunks = np.split(leftover_actions[:-leftover], n_chunks) + rewards_chunks = np.split(leftover_rewards[:-leftover], n_chunks) + dones_chunks = np.split(leftover_dones[:-leftover], n_chunks) + else: + obs_chunks = np.split(leftover_obs, n_chunks) + next_obs_chunks = np.split(leftover_next_obs, n_chunks) + actions_chunks = np.split(leftover_actions, n_chunks) + rewards_chunks = np.split(leftover_rewards, n_chunks) + dones_chunks = np.split(leftover_dones, n_chunks) + + infos = [{} for _ in range(n_envs)] + + for i in range(len(obs_chunks)): + buffer.add( + obs_chunks[i], + next_obs_chunks[i], + actions_chunks[i], + rewards_chunks[i], + dones_chunks[i], + infos + ) + + print(f'Wasted {leftover} samples') + print('Wasted no samples!') \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/training/train_classifier.py b/code_src/rise_code/sim_pipeline/training/train_classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..9e096624b7919b6e6039b97f3e43577914c7ed99 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/training/train_classifier.py @@ -0,0 +1,339 @@ +import hydra +import h5py +import json +from tqdm import tqdm +import numpy as np +import os + +from pathlib import Path +from datetime import datetime +from omegaconf import OmegaConf +from sim_pipeline.configs._discriminator.robomimic_discriminator import RobomimicDiscriminatorConfig +from sim_pipeline.configs.training._imitation_learning.base_imitation import ImitationTrainingConfig +from sim_pipeline.configs.constants import PolicyType, ImitationAlgorithm +from sim_pipeline.utils.experiment import setup_experiment +from sim_pipeline.data_manager.get_dataset import get_dataset +from sim_pipeline.utils.shape_meta import get_shape_meta, update_diffusion_cfg_with_shape_meta +from sim_pipeline.utils.find_robomimic_json import find_json +from sim_pipeline.utils.diffusion_utils import get_policy_class, get_workspace +from sim_pipeline.utils.train_utils import get_latest_diffusion_policy, get_latest_robomimic_policy +from sim_pipeline.model_manager.create_model_metadata import create_model_metadata, update_metadata_trained + +import robomimic.utils.train_utils as TrainUtils +import robomimic.utils.file_utils as FileUtils +import robomimic.utils.obs_utils as ObsUtils +from robomimic.utils.log_utils import DataLogger +from robomimic.scripts.split_train_val import split_train_val_from_hdf5 +from robomimic.config import config_factory +import robomimic.macros as Macros +from robomimic.algo.discriminator import Discriminator + +import torch +from torch.utils.data import DataLoader + + +@hydra.main(version_base=None, config_path='../configs', config_name='robomimic_discriminator') +def train(config: RobomimicDiscriminatorConfig): + import traceback + import sys + try: + run(config) + except: + traceback.print_exc(file=sys.stderr) + raise + + +def run(config: RobomimicDiscriminatorConfig): + device = setup_experiment(config.exp) + + expert_dataset_path = get_dataset(config.data) + suboptimal_dataset_path = get_dataset(config.suboptimal_data) + + # Generate robomimc config for the purpose of loading dataset + expert_robomimic_config = get_robomimic_config(config, expert_dataset_path) + suboptimal_robomimic_config = get_robomimic_config(config, suboptimal_dataset_path) + + env_meta = FileUtils.get_env_metadata_from_dataset(dataset_path=expert_dataset_path) + + # print(expert_robomimic_config) + log_dir = Path(config.exp.logdir) / config.name + log_dir_rm, ckpt_dir_rm, video_dir_rm = TrainUtils.get_exp_dir(expert_robomimic_config) + dt_string = Path(log_dir_rm).parent.name + create_model_metadata( + name=config.name, + policy_type=PolicyType.ROBOMIMIC, + policy_identifier=dt_string, + dataset_path=expert_dataset_path, + hydra_config=config, + filepath=log_dir / dt_string / 'metadata.json', + ) + print(log_dir_rm) + print(ckpt_dir_rm) + print(video_dir_rm) + + # Load expert dataset + ObsUtils.initialize_obs_utils_with_config(expert_robomimic_config) + expert_shape_meta = FileUtils.get_shape_metadata_from_dataset( + dataset_path=expert_robomimic_config.train.data, + all_obs_keys=expert_robomimic_config.all_obs_keys, + verbose=True + ) + expert_trainset, expert_validset = TrainUtils.load_data_for_training( + expert_robomimic_config, obs_keys=expert_shape_meta["all_obs_keys"]) + expert_train_sampler = expert_trainset.get_dataset_sampler() + expert_train_loader = DataLoader( + dataset=expert_trainset, + sampler=expert_train_sampler, + batch_size=expert_robomimic_config.train.batch_size, + shuffle=(expert_train_sampler is None), + num_workers=expert_robomimic_config.train.num_data_workers, + generator=torch.Generator(device=device), + drop_last=True + ) + expert_obs_normalization_stats = None + if expert_robomimic_config.train.hdf5_normalize_obs: + expert_obs_normalization_stats = expert_trainset.get_obs_normalization_stats() + + if expert_robomimic_config.experiment.validate: + num_workers = min(expert_robomimic_config.train.num_data_workers, 1) + expert_valid_sampler = expert_validset.get_dataset_sampler() + expert_valid_loader = DataLoader( + dataset=expert_validset, + sampler=expert_valid_sampler, + batch_size=expert_robomimic_config.train.batch_size, + shuffle=(expert_valid_sampler is None), + num_workers=num_workers, + generator=torch.Generator(device=device), + drop_last=True + ) + + # Load suboptimal dataset + ObsUtils.initialize_obs_utils_with_config(suboptimal_robomimic_config) + suboptimal_shape_meta = FileUtils.get_shape_metadata_from_dataset( + dataset_path=suboptimal_robomimic_config.train.data, + all_obs_keys=suboptimal_robomimic_config.all_obs_keys, + verbose=True + ) + suboptimal_trainset, suboptimal_validset = TrainUtils.load_data_for_training( + suboptimal_robomimic_config, obs_keys=suboptimal_shape_meta["all_obs_keys"]) + suboptimal_train_sampler = suboptimal_trainset.get_dataset_sampler() + suboptimal_train_loader = DataLoader( + dataset=suboptimal_trainset, + sampler=suboptimal_train_sampler, + batch_size=suboptimal_robomimic_config.train.batch_size, + shuffle=(suboptimal_train_sampler is None), + num_workers=suboptimal_robomimic_config.train.num_data_workers, + generator=torch.Generator(device=device), + drop_last=True + ) + suboptimal_obs_normalization_stats = None + if suboptimal_robomimic_config.train.hdf5_normalize_obs: + suboptimal_obs_normalization_stats = suboptimal_trainset.get_obs_normalization_stats() + + if expert_robomimic_config.experiment.validate: + num_workers = min(suboptimal_robomimic_config.train.num_data_workers, 1) + suboptimal_valid_sampler = suboptimal_validset.get_dataset_sampler() + suboptimal_valid_loader = DataLoader( + dataset=suboptimal_validset, + sampler=suboptimal_valid_sampler, + batch_size=suboptimal_robomimic_config.train.batch_size, + shuffle=(suboptimal_valid_sampler is None), + num_workers=num_workers, + generator=torch.Generator(device=device), + drop_last=True + ) + + + total_obs_dim = 0 + for shape in expert_shape_meta['all_shapes'].values(): + total_obs_dim += shape[0] + + # Setup data logger + data_logger = DataLogger( + log_dir_rm, + expert_robomimic_config, + log_tb=expert_robomimic_config.experiment.logging.log_tb, + log_wandb=expert_robomimic_config.experiment.logging.log_wandb, + ) + + # Instantiate the discriminator + discriminator = Discriminator( + algo_config=expert_robomimic_config.algo, + obs_config=expert_robomimic_config.observation, + global_config=expert_robomimic_config, + obs_key_shapes=expert_shape_meta['all_shapes'], + ac_dim=1, + device=device + ) + + best_valid_loss = None + + # Train the discriminator + for epoch in range(1, expert_robomimic_config.train.num_epochs + 1): + step_log = run_discriminator_training_epoch(discriminator, expert_train_loader, suboptimal_train_loader, epoch=epoch, expert_obs_normalization_stats=expert_obs_normalization_stats, subopt_obs_normalization_stats=suboptimal_obs_normalization_stats) + discriminator.on_epoch_end(epoch) + + # setup checkpoint path + epoch_ckpt_name = "model_epoch_{}".format(epoch) + + should_save_ckpt = False + if expert_robomimic_config.experiment.save.enabled: + epoch_check = (expert_robomimic_config.experiment.save.every_n_epochs is not None) and \ + (epoch > 0) and (epoch % expert_robomimic_config.experiment.save.every_n_epochs == 0) + epoch_list_check = (epoch in expert_robomimic_config.experiment.save.epochs) + should_save_ckpt = (epoch_check or epoch_list_check) + + print("Train Epoch {}".format(epoch)) + print(json.dumps(step_log, sort_keys=True, indent=4)) + + for k, v in step_log.items(): + if k.startswith("Time_"): + data_logger.record("Timing_Stats/Train_{}".format(k[5:]), v, epoch) + else: + data_logger.record("Train/{}".format(k), v, epoch) + + + if expert_robomimic_config.experiment.validate: + with torch.no_grad(): + val_step_log = run_discriminator_training_epoch(discriminator, expert_valid_loader, suboptimal_valid_loader, epoch=epoch, validate=True, expert_obs_normalization_stats=expert_obs_normalization_stats, subopt_obs_normalization_stats=suboptimal_obs_normalization_stats) + print(json.dumps(val_step_log, sort_keys=True, indent=4)) + # discriminator.on_epoch_end(epoch, validate=True) + + for k, v in val_step_log.items(): + if k.startswith("Time_"): + data_logger.record("Timing_Stats/Valid_{}".format(k[5:]), v, epoch) + else: + data_logger.record("Valid/{}".format(k), v, epoch) + + valid_check = "Loss" in step_log + if valid_check and (best_valid_loss is None or (step_log["Loss"] <= best_valid_loss)): + best_valid_loss = step_log["Loss"] + if expert_robomimic_config.experiment.save.enabled and expert_robomimic_config.experiment.save.on_best_validation: + epoch_ckpt_name += "_best_validation_{}".format(best_valid_loss) + should_save_ckpt = True + + + if should_save_ckpt: + print(f'Saving model at epoch {epoch} to {os.path.join(ckpt_dir_rm, epoch_ckpt_name)}') + TrainUtils.save_model( + model=discriminator, + config=expert_robomimic_config, + env_meta=env_meta, + shape_meta=expert_shape_meta, + ckpt_path=os.path.join(ckpt_dir_rm, epoch_ckpt_name + ".pth"), + obs_normalization_stats=expert_obs_normalization_stats, + ) + data_logger.close() + + max_epochs_saved: int = get_latest_robomimic_policy(log_dir / dt_string / 'models', find_epoch=True) + if max_epochs_saved >= 100: + update_metadata_trained(log_dir / dt_string / 'metadata.json') + +def run_discriminator_training_epoch(discriminator, expert_loader, suboptimal_loader, epoch, validate=False, expert_obs_normalization_stats=None, subopt_obs_normalization_stats=None): + + step_log_all = [] + + num_steps = max(len(expert_loader), len(suboptimal_loader)) + for _ in tqdm(range(num_steps)): + expert_batch = next(iter(expert_loader)) + suboptimal_batch = next(iter(suboptimal_loader)) + + input_expert_batch = discriminator.process_batch_for_training(expert_batch) + input_subopt_batch = discriminator.process_batch_for_training(suboptimal_batch) + + input_expert_batch = discriminator.postprocess_batch_for_training(input_expert_batch, obs_normalization_stats=expert_obs_normalization_stats) + input_subopt_batch = discriminator.postprocess_batch_for_training(input_subopt_batch, obs_normalization_stats=subopt_obs_normalization_stats) + + info = discriminator.train_on_batch(input_expert_batch, input_subopt_batch, epoch=epoch, validate=validate) + + # print('='*50) + # print(info) + step_log = discriminator.log_info(info) + step_log_all.append(step_log) + # print(step_log) + + # print(info['losses']) + step_log_dict = {} + for i in range(len(step_log_all)): + for k in step_log_all[i]: + if k not in step_log_dict: + step_log_dict[k] = [] + step_log_dict[k].append(step_log_all[i][k]) + step_log_all = dict((k, float(np.mean(v))) for k, v in step_log_dict.items()) + + return step_log_all + + + +def get_robomimic_config(config: RobomimicDiscriminatorConfig, dataset_path: str): + train_cfg: ImitationTrainingConfig = config.training + + with h5py.File(dataset_path, 'r') as f: + add_mask = 'mask' not in f + + if add_mask: + split_train_val_from_hdf5(dataset_path, val_ratio=0.1) + + use_image = bool(train_cfg.rgb_keys) + json_path = find_json(train_cfg, config.env.env_name.get_simple_name(), use_image) + + Macros.WANDB_ENTITY = config.exp.entity + + if json_path is None: + robomimic_config = config_factory(train_cfg.algo.value) + print('No json path found') + else: + json_config = json.load(open(json_path, 'r')) + print(f'Found json path : {json_path}') + + json_config['experiment']['name'] = config.name + json_config['train']['data'] = dataset_path + json_config['train']['output_dir'] = config.exp.logdir + json_config['train']['batch_size'] = train_cfg.batch_size + json_config['train']['num_epochs'] = train_cfg.num_epochs + json_config['experiment']['epoch_every_n_steps'] = train_cfg.epoch_every_n_steps + json_config['experiment']['validate'] = not train_cfg.algo.is_offline_rl() + + json_config['experiment']['logging']['log_wandb'] = 'wandb' in config.exp.format_strings + json_config['experiment']['logging']['wandb_proj_name'] = config.exp.project + json_config['experiment']['logging']['log_tb'] = 'tensorboard' in config.exp.format_strings + + json_config['experiment']['rollout']['enabled'] = not train_cfg.algo.is_offline_rl() + json_config['experiment']['rollout']['horizon'] = train_cfg.rollout_horizon + json_config['experiment']['rollout']['rate'] = config.exp.eval_interval + json_config['experiment']['render_video'] = train_cfg.render_video + + json_config['observation']['modalities']['obs']['low_dim'] = OmegaConf.to_container(train_cfg.low_dim_keys) + json_config['observation']['modalities']['obs']['rgb'] = OmegaConf.to_container(train_cfg.rgb_keys) + json_config['observation']['modalities']['obs']['depth'] = OmegaConf.to_container(train_cfg.depth_keys) + + json_config['train']['hdf5_cache_mode'] = train_cfg.cache_mode + json_config['train']['hdf5_filter_key'] = 'train' + json_config['train']['hdf5_validation_filter_key'] = 'valid' + + if train_cfg.algo.is_offline_rl(): + json_config['algo']['optim_params']['critic']['learning_rate']['initial'] = train_cfg.learning_rate + json_config['algo']['optim_params']['vf']['learning_rate']['initial'] = train_cfg.learning_rate + json_config['algo']['target_tau'] = train_cfg.target_tau + json_config['algo']['vf_quantile'] = train_cfg.vf_quantile + json_config['algo']['critic']['layer_dims'] = OmegaConf.to_container(train_cfg.layer_dims) + json_config['algo']['adv']['beta'] = train_cfg.beta + json_config['algo']['discount'] = train_cfg.discount_rate + + if train_cfg.algo != ImitationAlgorithm.IQL_DIFFUSION: + json_config['algo']['actor']['layer_dims'] = OmegaConf.to_container(train_cfg.layer_dims) + json_config['algo']['actor']['net']['type'] = train_cfg.net_arch + json_config['algo']['actor']['net']['gmm']['num_modes'] = train_cfg.gmm_heads + json_config['algo']['optim_params']['actor']['learning_rate']['initial'] = train_cfg.learning_rate + else: + json_config['algo']['multi_step_method'] = train_cfg.multi_step_method.value + json_config['algo']['optim_params']['policy']['learning_rate']['initial'] = train_cfg.learning_rate + json_config['algo']['horizon']['observation_horizon'] = train_cfg.observation_horizon + json_config['algo']['horizon']['action_horizon'] = train_cfg.action_horizon + json_config['algo']['horizon']['prediction_horizon'] = train_cfg.prediction_horizon + + robomimic_config = config_factory(json_config['algo_name']) + with robomimic_config.values_unlocked(): + robomimic_config.update(json_config) + + return robomimic_config \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/training/train_diffusion.py b/code_src/rise_code/sim_pipeline/training/train_diffusion.py new file mode 100644 index 0000000000000000000000000000000000000000..17295c46d21cc2dc4211dce8ee8bb1367be9d69d --- /dev/null +++ b/code_src/rise_code/sim_pipeline/training/train_diffusion.py @@ -0,0 +1,146 @@ +import hydra + +from pathlib import Path +from datetime import datetime +from omegaconf import OmegaConf +from sim_pipeline.configs._diffusion.base_diffusion import DiffusionBaseConfig +from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.utils.experiment import setup_experiment +from sim_pipeline.data_manager.get_dataset import get_dataset +from sim_pipeline.utils.shape_meta import get_shape_meta, update_diffusion_cfg_with_shape_meta +from sim_pipeline.utils.diffusion_utils import get_policy_class, get_workspace +from sim_pipeline.utils.train_utils import get_latest_diffusion_policy +from sim_pipeline.model_manager.create_model_metadata import create_model_metadata, update_metadata_trained +import wandb + + +@hydra.main(version_base=None, config_path='../configs', config_name='base_diffusion') +def train(config: DiffusionBaseConfig): + import traceback + import sys + try: + run(config) + except: + traceback.print_exc(file=sys.stderr) + raise + + +def run(cfg: DiffusionBaseConfig): + # device = setup_experiment(cfg.exp) + + wandb.init( + # set the wandb project where this run will be logged + project="diffusion", + entity="kehuang", + ) + + + dataset_path = get_dataset(cfg.data) + + lowdim_keys = cfg.training.low_dim_keys + rgb_keys = cfg.training.rgb_keys + depth_keys = cfg.training.depth_keys + all_obs_keys = [] + for key in lowdim_keys + rgb_keys + depth_keys: + if key in all_obs_keys: + raise ValueError(f"Duplicate obs key {key}") + all_obs_keys.append(key) + only_lowdim = lowdim_keys and not rgb_keys and not depth_keys + + obs_shape_meta, action_shape_meta = get_shape_meta(dataset_path, all_obs_keys) + total_obs_dim = 0 + for shape in obs_shape_meta.values(): + total_obs_dim += shape[0] + + default_config_path = cfg.training.default_config_path + + default_cfg = OmegaConf.load(default_config_path) + + default_cfg.n_action_steps = cfg.training.execution_horizon + default_cfg.n_obs_steps = cfg.training.obs_horizon + + default_cfg.name = cfg.name + default_cfg.training.seed = cfg.exp.seed + default_cfg.task.env_runner.test_start_seed = cfg.exp.seed + + if 'shape_meta' in default_cfg: + shape_meta_cfg = default_cfg.shape_meta + update_diffusion_cfg_with_shape_meta(shape_meta_cfg, obs_shape_meta, action_shape_meta, rgb_keys, lowdim_keys, depth_keys) + if only_lowdim: + default_cfg.obs_dim = total_obs_dim + + policy_cfg = default_cfg.policy + + policy_cfg.n_action_steps = cfg.training.execution_horizon + policy_cfg.n_obs_steps = cfg.training.obs_horizon + policy_cfg.horizon = cfg.training.prediction_horizon + + if 'shape_meta' in policy_cfg: + policy_shape_meta_cfg = policy_cfg.shape_meta + update_diffusion_cfg_with_shape_meta(policy_shape_meta_cfg, obs_shape_meta, action_shape_meta, rgb_keys, lowdim_keys, depth_keys) + if only_lowdim: + policy_cfg.obs_dim = total_obs_dim + + policy_cls = get_policy_class(rgb_keys, lowdim_keys, depth_keys) + + env_runner_cfg = default_cfg.task.env_runner + + env_runner_cfg.n_action_steps = cfg.training.execution_horizon + env_runner_cfg.n_obs_steps = cfg.training.obs_horizon + + if only_lowdim: + default_cfg.task.obs_dim = total_obs_dim + default_cfg.task.dataset.obs_keys = tuple(all_obs_keys) + env_runner_cfg.obs_keys = tuple(all_obs_keys) + default_cfg.task.obs_keys = tuple(all_obs_keys) + + default_cfg.task.dataset.dataset_path = dataset_path + default_cfg.task.dataset_path = dataset_path + default_cfg.task.env_runner.dataset_path = dataset_path + + training_cfg = default_cfg.training + training_cfg.device = f'cuda:{cfg.exp.device_id}' + training_cfg.checkpoint_every = cfg.exp.save_interval + training_cfg.rollout_every = cfg.exp.eval_interval + training_cfg.num_epochs = cfg.training.num_epochs + + default_cfg.dataloader.batch_size = cfg.training.batch_size + default_cfg.val_dataloader.batch_size = cfg.training.batch_size + + default_cfg.logging.project = cfg.exp.project + default_cfg.logging.entity = cfg.exp.entity + default_cfg.logging.name = cfg.name + + # default_cfg.training.debug = cfg.debug + env_runner_cfg.debug = cfg.debug + if cfg.debug: + default_cfg.task.env_runner.n_envs = 1 + default_cfg.debug = True + else: + default_cfg.debug = False + + now = datetime.now() + dt_string = now.strftime("%Y%m%d%H%M%S") + log_dir = Path(cfg.exp.logdir) / cfg.name / dt_string + if not log_dir.exists(): + log_dir.mkdir(parents=True) + + create_model_metadata( + name=cfg.name, + policy_type=PolicyType.DIFFUSION, + policy_identifier=dt_string, + dataset_path=dataset_path, + hydra_config=cfg, + filepath=log_dir / 'metadata.json', + ) + + try: + OmegaConf.resolve(default_cfg) + workspace_cls = get_workspace(rgb_keys, lowdim_keys, depth_keys) + workspace = workspace_cls(default_cfg, output_dir=log_dir) + workspace.run() + finally: + max_epoch_saved: int = get_latest_diffusion_policy(log_dir / 'checkpoints', find_epoch=True) + # only consider a training run valid if we have ran for more than 1000 (hardcoded) epochs + if max_epoch_saved >= 1000: + update_metadata_trained(log_dir / 'metadata.json') diff --git a/code_src/rise_code/sim_pipeline/training/train_discriminator.py b/code_src/rise_code/sim_pipeline/training/train_discriminator.py new file mode 100644 index 0000000000000000000000000000000000000000..6577694e70496a38b4274f87bd267db0288c575b --- /dev/null +++ b/code_src/rise_code/sim_pipeline/training/train_discriminator.py @@ -0,0 +1,353 @@ +import os + +if 'DISPLAY' not in os.environ: + import glfw + glfw.ERROR_REPORTING = False + +import hydra +import json +import torch +import numpy as np +import robomimic.macros as Macros +import time +import psutil +import h5py + +import robomimic.utils.train_utils as TrainUtils +import robomimic.utils.obs_utils as ObsUtils +import robomimic.utils.env_utils as EnvUtils +import robomimic.utils.file_utils as FileUtils + +from pathlib import Path + +from omegaconf import OmegaConf +from torch.utils.data import DataLoader + +from robomimic.config import config_factory +from robomimic.scripts.split_train_val import split_train_val_from_hdf5 +from robomimic.utils.log_utils import PrintLogger, DataLogger, flush_warnings + +from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.configs._imitation_learning.robomimic_imitation_base import RobomimicImitationBaseConfig +from sim_pipeline.configs.training._imitation_learning.base_imitation import ImitationTrainingConfig +from diffusion_policy.dataset.robomimic_replay_image_dataset import RobomimicReplayImageDataset +from diffusion_policy.dataset.robomimic_replay_lowdim_dataset import RobomimicReplayLowdimDataset + +# from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.data_manager.get_dataset import get_dataset +from sim_pipeline.utils.experiment import setup_experiment +from sim_pipeline.utils.train_utils import get_latest_robomimic_policy +from sim_pipeline.model_manager.create_model_metadata import create_model_metadata, update_metadata_trained + +from sim_pipeline.ilid.discriminator import Discriminator + + +def robomimic_train(config, device, log_dir, ckpt_dir): + """ + Train a model using the algorithm. + """ + + # first set seeds + np.random.seed(config.train.seed) + torch.manual_seed(config.train.seed) + + torch.set_num_threads(2) + + print("\n============= New Training Run with Config =============") + print("") + + # read config to set up metadata for observation modalities (e.g. detecting rgb observations) + ObsUtils.initialize_obs_utils_with_config(config) + + # make sure the dataset exists + dataset_path = os.path.expanduser(config.train.data) + if not os.path.exists(dataset_path): + raise Exception("Dataset at provided path {} not found!".format(dataset_path)) + + # load basic metadata from training file + print("\n============= Loaded Environment Metadata =============") + env_meta = FileUtils.get_env_metadata_from_dataset(dataset_path=config.train.data) + shape_meta = FileUtils.get_shape_metadata_from_dataset( + dataset_path=config.train.data, + all_obs_keys=config.all_obs_keys, + verbose=True + ) + # setup for a new training run + data_logger = DataLogger( + log_dir, + config, + log_tb=config.experiment.logging.log_tb, + log_wandb=config.experiment.logging.log_wandb, + ) + + model = Discriminator( + config=config, + obs_shapes=shape_meta["all_shapes"], + device=device, + ) + + # save the config as a json file + with open(os.path.join(log_dir, '..', 'config.json'), 'w') as outfile: + json.dump(config, outfile, indent=4) + + print("\n============= Model Summary =============") + print(model) # print model summary + print("") + + # load training data + # train_sampler = trainset.get_dataset_sampler() + # print("\n============= Training Dataset =============") + # print(trainset) + # print("") + # if validset is not None: + # print("\n============= Validation Dataset =============") + # print(validset) + # print("") + + + if config.observation.modalities.obs.rgb: + with h5py.File(dataset_path, 'r') as f: + data = f['data'] + ep_keys = list(data.keys()) + ep = data[ep_keys[0]] + action_shape = ep['actions'].shape[1:] + obs_shapes = {} + for key in config.observation.modalities.obs.low_dim: + if key not in ep['obs'].keys(): + raise ValueError(f"Key {key} not found in dataset") + obs_shapes[key] = {'shape': ep['obs'][key].shape[1:]} + for key in config.observation.modalities.obs.rgb: + if key not in ep['obs'].keys(): + raise ValueError(f"Key {key} not found in dataset") + # switch to channels first + obs_shapes[key] = ep['obs'][key].shape[1:] + obs_shapes[key] = { + 'shape': (obs_shapes[key][2], obs_shapes[key][0], obs_shapes[key][1]), + 'type': 'rgb', + } + + shape_meta_dataloader = { + 'obs': obs_shapes, + 'action': { + 'shape': action_shape, + } + } + dataset = RobomimicReplayImageDataset( + shape_meta=shape_meta_dataloader, + dataset_path=dataset_path, + horizon=1, + pad_before=0, + pad_after=0, + n_obs_steps=1, + abs_action=False, + use_cache=True, + seed=config.train.seed, + val_ratio=0.0, + extra_info=True, + sample_goals=False, + squeeze=True, + ) + else: + dataset, validset = TrainUtils.load_data_for_training( + config, obs_keys=shape_meta["all_obs_keys"]) + + + obs_normalization_stats = None + + train_loader = DataLoader( + dataset=dataset, + batch_size=config.train.batch_size, + shuffle=True, + num_workers=config.train.num_data_workers, + generator=torch.Generator(device=device), + drop_last=True + ) + # train_loader = DataLoader( + # dataset=trainset, + # sampler=train_sampler, + # batch_size=config.train.batch_size, + # shuffle=(train_sampler is None), + # num_workers=config.train.num_data_workers, + # generator=torch.Generator(device=device), + # drop_last=True + # ) + + config.experiment.validate = False + # if config.experiment.validate: + # # cap num workers for validation dataset at 1 + # num_workers = min(config.train.num_data_workers, 1) + # valid_sampler = validset.get_dataset_sampler() + # valid_loader = DataLoader( + # dataset=validset, + # sampler=valid_sampler, + # batch_size=config.train.batch_size, + # shuffle=(valid_sampler is None), + # num_workers=num_workers, + # generator=torch.Generator(device=device), + # drop_last=True + # ) + # else: + valid_loader = None + + # print all warnings before training begins + print("*" * 50) + print("Warnings generated by robomimic have been duplicated here (from above) for convenience. Please check them carefully.") + flush_warnings() + print("*" * 50) + print("") + + # main training loop + best_valid_loss = None + last_ckpt_time = time.time() + + # number of learning steps per epoch (defaults to a full dataset pass) + train_num_steps = config.experiment.epoch_every_n_steps + valid_num_steps = config.experiment.validation_epoch_every_n_steps + + for epoch in range(1, config.train.num_epochs + 1): # epoch numbers start at 1 + step_log = TrainUtils.run_epoch( + model=model, + data_loader=train_loader, + epoch=epoch, + num_steps=train_num_steps, + obs_normalization_stats=obs_normalization_stats, + ) + model.on_epoch_end(epoch) + + # setup checkpoint path + epoch_ckpt_name = "model_epoch_{}".format(epoch) + + # check for recurring checkpoint saving conditions + should_save_ckpt = False + if config.experiment.save.enabled: + time_check = (config.experiment.save.every_n_seconds is not None) and \ + (time.time() - last_ckpt_time > config.experiment.save.every_n_seconds) + epoch_check = (config.experiment.save.every_n_epochs is not None) and \ + (epoch > 0) and (epoch % config.experiment.save.every_n_epochs == 0) + epoch_list_check = (epoch in config.experiment.save.epochs) + should_save_ckpt = (time_check or epoch_check or epoch_list_check) + ckpt_reason = None + if should_save_ckpt: + last_ckpt_time = time.time() + ckpt_reason = "time" + + print("Train Epoch {}".format(epoch)) + should_save_ckpt = epoch % 2 == 0 + print(f"Should save ckpt: {should_save_ckpt}, enabled: {config.experiment.save.enabled}, freq: {config.experiment.save.every_n_epochs}") + print(json.dumps(step_log, sort_keys=True, indent=4)) + for k, v in step_log.items(): + if k.startswith("Time_"): + data_logger.record("Timing_Stats/Train_{}".format(k[5:]), v, epoch) + else: + data_logger.record("Train/{}".format(k), v, epoch) + + # Evaluate the model on validation set + if config.experiment.validate: + with torch.no_grad(): + step_log = TrainUtils.run_epoch(model=model, data_loader=valid_loader, epoch=epoch, validate=True, num_steps=valid_num_steps) + for k, v in step_log.items(): + if k.startswith("Time_"): + data_logger.record("Timing_Stats/Valid_{}".format(k[5:]), v, epoch) + else: + data_logger.record("Valid/{}".format(k), v, epoch) + + print("Validation Epoch {}".format(epoch)) + print(json.dumps(step_log, sort_keys=True, indent=4)) + + # save checkpoint if achieve new best validation loss + valid_check = "Loss" in step_log + if valid_check and (best_valid_loss is None or (step_log["Loss"] <= best_valid_loss)): + best_valid_loss = step_log["Loss"] + if config.experiment.save.enabled and config.experiment.save.on_best_validation: + epoch_ckpt_name += "_best_validation_{}".format(best_valid_loss) + should_save_ckpt = True + ckpt_reason = "valid" if ckpt_reason is None else ckpt_reason + + # Save model checkpoints based on conditions (success rate, validation loss, etc) + if should_save_ckpt: + print('saving!!!!') + TrainUtils.save_model( + model=model, + config=config, + env_meta=env_meta, + shape_meta=shape_meta, + ckpt_path=os.path.join(ckpt_dir, epoch_ckpt_name + ".pth"), + obs_normalization_stats=obs_normalization_stats, + ) + + + # Finally, log memory usage in MB + process = psutil.Process(os.getpid()) + mem_usage = int(process.memory_info().rss / 1000000) + data_logger.record("System/RAM Usage (MB)", mem_usage, epoch) + print("\nEpoch {} Memory Usage: {} MB\n".format(epoch, mem_usage)) + + # terminate logging + data_logger.close() + + +@hydra.main(version_base=None, config_path='../configs', config_name='robomimic_iql_base') +def train(config: RobomimicImitationBaseConfig): + import traceback + import sys + try: + run(config) + except: + traceback.print_exc(file=sys.stderr) + raise + + +def get_robomimic_config(config: RobomimicImitationBaseConfig, dataset_path: str): + train_cfg: ImitationTrainingConfig = config.training + + with h5py.File(dataset_path, 'r') as f: + add_mask = 'mask' not in f + + if add_mask: + split_train_val_from_hdf5(dataset_path, val_ratio=0.1) + + robomimic_config = config_factory('bc') + robomimic_config.observation.modalities.obs.rgb = OmegaConf.to_container(train_cfg.rgb_keys) + robomimic_config.observation.modalities.obs.low_dim = OmegaConf.to_container(train_cfg.low_dim_keys) + + robomimic_config.train.hdf5_cache_mode = 'all' + + robomimic_config.train.data = dataset_path + robomimic_config.train.output_dir = config.exp.logdir + robomimic_config.train.batch_size = train_cfg.batch_size + robomimic_config.train.num_epochs = train_cfg.num_epochs + robomimic_config.experiment.name = config.name + + robomimic_config.experiment.logging.log_wandb = 'wandb' in config.exp.format_strings and not config.debug + robomimic_config.experiment.logging.wandb_proj_name = config.exp.project + robomimic_config.experiment.logging.log_tb = 'tensorboard' in config.exp.format_strings + + Macros.WANDB_ENTITY = config.exp.entity + + return robomimic_config + + +def run(config: RobomimicImitationBaseConfig): + device = setup_experiment(config.exp) + + dataset_path = get_dataset(config.data) + + robomimic_config = get_robomimic_config(config, dataset_path=dataset_path) + + log_dir = Path(config.exp.logdir) / config.name + log_dir_rm, ckpt_dir_rm, video_dir_rm = TrainUtils.get_exp_dir(robomimic_config) + dt_string = Path(log_dir_rm).parent.name + create_model_metadata( + name=config.name, + policy_type=PolicyType.ROBOMIMIC, + policy_identifier=dt_string, + dataset_path=dataset_path, + hydra_config=config, + filepath=log_dir / dt_string / 'metadata.json', + ) + try: + robomimic_train(robomimic_config, device, log_dir_rm, ckpt_dir_rm) + finally: + max_epochs_saved: int = get_latest_robomimic_policy(log_dir / dt_string / 'models', find_epoch=True) + if max_epochs_saved >= 1: + update_metadata_trained(log_dir / dt_string / 'metadata.json') \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/training/train_ogbench.py b/code_src/rise_code/sim_pipeline/training/train_ogbench.py new file mode 100644 index 0000000000000000000000000000000000000000..f3db4b0bb5726482dffa30185575533ba75b9360 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/training/train_ogbench.py @@ -0,0 +1,147 @@ +import hydra +import h5py +import tqdm +import torch +import wandb + +from collections import defaultdict +from pathlib import Path +from torch.utils.data import DataLoader +from omegaconf import OmegaConf + +from impls.utils.flax_utils import save_agent + +from diffusion_policy.dataset.robomimic_replay_image_dataset import RobomimicReplayImageDataset +from diffusion_policy.dataset.robomimic_replay_lowdim_dataset import RobomimicReplayLowdimDataset + +from sim_pipeline.utils.experiment import setup_experiment, setup_wandb +from sim_pipeline.data_manager.get_dataset import get_dataset +from sim_pipeline.configs._offline_rl.ogbench import OGBenchBaseConfig + +@hydra.main(version_base=None, config_path='../configs', config_name='crl') +def train(config: OGBenchBaseConfig): + device = setup_experiment(config.exp) + + if not config.debug: + setup_wandb( + config, + name=f"{config.name}", + entity=config.exp.entity, + project=config.exp.project, + ) + + log_dir = Path(config.exp.logdir) / config.name / 'checkpoints' + if not log_dir.exists(): + log_dir.mkdir(parents=True) + + dataset_path = get_dataset(config.data) + + with h5py.File(dataset_path, 'r') as f: + data = f['data'] + ep_keys = list(data.keys()) + ep = data[ep_keys[0]] + action_shape = ep['actions'].shape[1:] + obs_shapes = {} + for key in config.training.low_dim_keys: + if key not in ep['obs'].keys(): + raise ValueError(f"Key {key} not found in dataset") + obs_shapes[key] = {'shape': ep['obs'][key].shape[1:]} + for key in config.training.rgb_keys: + if key not in ep['obs'].keys(): + raise ValueError(f"Key {key} not found in dataset") + # switch to channels first + obs_shapes[key] = ep['obs'][key].shape[1:] + obs_shapes[key] = { + 'shape': (obs_shapes[key][2], obs_shapes[key][0], obs_shapes[key][1]), + 'type': 'rgb', + } + + shape_meta = { + 'obs': obs_shapes, + 'action': { + 'shape': action_shape, + } + } + + if config.training.rgb_keys: + dataset = RobomimicReplayImageDataset( + shape_meta=shape_meta, + dataset_path=dataset_path, + horizon=1, + pad_before=0, + pad_after=0, + n_obs_steps=1, + abs_action=False, + use_cache=True, + seed=config.exp.seed, + val_ratio=0.0, + extra_info=True, + sample_goals=True, + p_currgoal=config.training.p_currgoal, + squeeze=True, + ) + else: + dataset = RobomimicReplayLowdimDataset( + obs_keys=config.training.low_dim_keys, + dataset_path=dataset_path, + horizon=1, + pad_before=0, + pad_after=0, + abs_action=False, + seed=config.exp.seed, + val_ratio=0.0, + extra_info=True, + sample_goals=True, + p_currgoal=config.training.p_currgoal, + squeeze=True, + ) + + train_dataloader = DataLoader( + dataset, + batch_size=config.training.batch_size, + num_workers=0, + shuffle=True, + generator=torch.Generator(device=device), + ) + + example_batch = next(iter(train_dataloader)) + example_batch_np = { + 'observations': example_batch['obs'].numpy(), + 'actions': example_batch['action'].numpy(), + } + + agent_class = config.training.algo.get_agent() + agent = agent_class.create( + seed=config.exp.seed, + ex_observations=example_batch_np['observations'], + ex_actions=example_batch_np['actions'], + config=OmegaConf.to_container(config.training), + ) + + for epoch in range(config.training.num_epochs): + epoch_metrics = defaultdict(list) + with tqdm.tqdm(train_dataloader, desc=f'Training epoch {epoch}') as tepoch: + for batch in tepoch: + # to numpy + batch_np = { + 'observations': batch['obs'].numpy(), + 'actions': batch['action'].numpy(), + 'terminals': batch['terminals'].numpy(), + 'valids': batch['valids'].numpy(), + 'rewards': batch['rewards'].numpy(), + 'next_observations': batch['next_obs'].numpy(), + 'value_goals': batch['value_goals'].numpy(), + 'actor_goals': batch['actor_goals'].numpy(), + } + agent, update_info = agent.update(batch_np) + + for k, v in update_info.items(): + epoch_metrics[f'training/{k}'].append(v) + # avg over epoch + epoch_metrics = {k: sum(v) / len(v) for k, v in epoch_metrics.items()} + if not config.debug: + wandb.log(epoch_metrics, step=epoch) + + if epoch % config.exp.save_interval == 0: + save_agent(agent, log_dir, epoch) + save_agent(agent, log_dir, epoch) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/training/train_q_transformer.py b/code_src/rise_code/sim_pipeline/training/train_q_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..eeceef9785b41021b42ccbd6f34bf5c91aeb7efe --- /dev/null +++ b/code_src/rise_code/sim_pipeline/training/train_q_transformer.py @@ -0,0 +1,110 @@ +import hydra + +from pathlib import Path +from datetime import datetime +from omegaconf import OmegaConf +from sim_pipeline.configs._q_transformer.q_transformer import QTransformerBaseConfig +from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.utils.experiment import setup_experiment +from sim_pipeline.data_manager.get_dataset import get_dataset +from sim_pipeline.utils.shape_meta import get_shape_meta, update_diffusion_cfg_with_shape_meta +from sim_pipeline.utils.diffusion_utils import get_policy_class, get_workspace +from sim_pipeline.utils.train_utils import get_latest_diffusion_policy, get_latest_q_transformer_policy +from sim_pipeline.model_manager.create_model_metadata import create_model_metadata, update_metadata_trained + +from robomimic.utils.dataset import SequenceDataset +from q_transformer import QLearner, QRoboticTransformer + +@hydra.main(version_base=None, config_path='../configs', config_name='q_transformer') +def train(config: QTransformerBaseConfig): + import traceback + import sys + try: + run(config) + except: + traceback.print_exc(file=sys.stderr) + raise + + +def run(cfg: QTransformerBaseConfig): + # device = setup_experiment(cfg.exp) + + dataset_path = get_dataset(cfg.data) + + model = QRoboticTransformer( + vit = dict( + num_classes = 1000, + dim_conv_stem = 64, + dim = 64, + dim_head = 64, + depth = (2, 2, 5, 2), + window_size = 6, + mbconv_expansion_rate = 4, + mbconv_shrinkage_rate = 0.25, + dropout = 0.1 + ), + num_actions = 8, + depth = 1, + heads = 8, + dim_head = 64, + cond_drop_prob = 0.2, + dueling = True, + weight_tie_action_bin_embed = False, + condition_on_text=False, + num_residual_streams = 1 + ) + lowdim_keys = cfg.training.low_dim_keys + rgb_keys = cfg.training.rgb_keys + + if lowdim_keys: + raise NotImplementedError('Lowdim keys not implemented') + if not rgb_keys: + raise NotImplementedError('RGB keys needed') + + torch_dataset = SequenceDataset( + hdf5_path=dataset_path, + obs_keys=rgb_keys, + dataset_keys=['actions', 'rewards', 'dones'], + load_next_obs=True, + frame_stack=1, + seq_length=1, + pad_frame_stack=True, + pad_seq_length=True, + get_pad_mask=False, + goal_mode=None, + hdf5_cache_mode='all', + q_transformer=True, + ) + + now = datetime.now() + dt_string = now.strftime("%Y%m%d%H%M%S") + log_dir = Path(cfg.exp.logdir) / cfg.name / dt_string + if not log_dir.exists(): + log_dir.mkdir(parents=True) + + q_learner = QLearner( + model=model, + dataset=torch_dataset, + batch_size=cfg.training.batch_size, + num_train_steps=cfg.training.num_epochs, + learning_rate=cfg.training.learning_rate, + checkpoint_folder=log_dir / 'checkpoints', + checkpoint_every=500, + ) + + create_model_metadata( + name=cfg.name, + policy_type=PolicyType.QTRANSFORMER, + policy_identifier=dt_string, + dataset_path=dataset_path, + hydra_config=cfg, + filepath=log_dir / 'metadata.json', + ) + + try: + q_learner() + finally: + max_epoch_saved: int = get_latest_q_transformer_policy(log_dir / 'checkpoints', find_epoch=True) + # only consider a training run valid if we have ran for more than 1000 (hardcoded) epochs + if max_epoch_saved >= 15: + update_metadata_trained(log_dir / 'metadata.json') diff --git a/code_src/rise_code/sim_pipeline/training/train_rl.py b/code_src/rise_code/sim_pipeline/training/train_rl.py new file mode 100644 index 0000000000000000000000000000000000000000..276a6023e0290c71a6fd063ac2da6fed7f100c45 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/training/train_rl.py @@ -0,0 +1,132 @@ +import os +if 'DISPLAY' not in os.environ: + import glfw + glfw.ERROR_REPORTING = False + +import hydra +import torch +import numpy as np + +from pathlib import Path +from omegaconf import OmegaConf +from omegaconf import MissingMandatoryValue + +from stable_baselines3.common.base_class import BaseAlgorithm +from stable_baselines3.common.vec_env.base_vec_env import VecEnv + +from sim_pipeline.utils.logger import configure_logger +from sim_pipeline.utils.logger import Logger + +from sim_pipeline.configs.default import TopLevelConfig +from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.training.custom_callback import LoggerCallback +from sim_pipeline.training.init_buffer import init_buffer +from sim_pipeline.envs.make_env import make_vec_env +from sim_pipeline.utils.experiment import setup_wandb, setup_experiment +from sim_pipeline.utils.train_utils import get_latest_sb_policy +from sim_pipeline.data_manager.get_dataset import get_dataset +from sim_pipeline.model_manager.create_model_metadata import create_model_metadata, update_metadata_trained + +@hydra.main(version_base=None, config_path='../configs', config_name="default") +def train(config: TopLevelConfig): + import traceback + import sys + try: + run(config) + except: + traceback.print_exc(file=sys.stderr) + raise + +def run(config: TopLevelConfig): + device = setup_experiment(config.exp) + + log_path = config.exp.logdir + logdir = Path(log_path) / f'{config.name}' / f'{config.exp.seed}' + ckptdir = logdir / 'policy' + + if config.debug: + # no wandb + fs = list(config.exp.format_strings) + config.exp.format_strings = [i for i in fs if i != "wandb"] + + if "wandb" in config.exp.format_strings: + run = setup_wandb( + config, + name=f"{config.name}[sim][{config.exp.seed}]", + entity=config.exp.entity, + project=config.exp.project, + ) + + logger: Logger = configure_logger(str(logdir), config.exp.format_strings) + + envs: VecEnv = make_vec_env( + env_config=config.env, + num_workers=config.exp.num_workers, + seed=config.exp.seed, + device_id=config.exp.device_id, + debug=config.debug + ) + + policy_kwargs = OmegaConf.to_container(config.training.policy_kwargs) + algo = config.training.algo.get_algo() + + resuming = False + if config.training.resume and os.path.exists(ckptdir): + last_checkpoint = get_latest_sb_policy(ckptdir / '_step_') + if last_checkpoint is not None: + resuming = True + + if resuming: + model: BaseAlgorithm = algo.load(last_checkpoint, env=envs, device=device) + else: + model: BaseAlgorithm = algo( + policy=config.training.policy, + env=envs, + tensorboard_log=logdir, + policy_kwargs=policy_kwargs, + device=device + ) + + if config.training.init_buffer: + dataset_path = get_dataset(config.data) + init_buffer(model.replay_buffer, dataset_path, envs, config.env) + + eval_envs: VecEnv = make_vec_env( + env_config=config.env, + num_workers=config.exp.num_workers, + seed=config.exp.seed * 777, + device_id=config.exp.device_id, + debug=config.debug + ) + + model.set_logger(logger) + + callback = LoggerCallback( + eval_envs=eval_envs, + eval_interval=config.exp.eval_interval, + save_dir=ckptdir, + save_interval=config.exp.save_interval, + ) + + create_model_metadata( + name=config.name, + policy_type=PolicyType.DIFFUSION, + policy_identifier=config.exp.seed, + dataset_path=dataset_path, + hydra_config=config, + filepath=logdir / 'metadata.json', + ) + try: + model.learn( + total_timesteps=config.training.total_timesteps, + callback=callback, + progress_bar=not config.debug, + ) + finally: + max_epoch_saved: int = get_latest_sb_policy(ckptdir / '_step_', find_epoch=True) + if max_epoch_saved >= 2000: + update_metadata_trained(logdir / 'metadata.json') + + envs.close() + + return model diff --git a/code_src/rise_code/sim_pipeline/training/train_robomimic.py b/code_src/rise_code/sim_pipeline/training/train_robomimic.py new file mode 100644 index 0000000000000000000000000000000000000000..df20c039e5ba8e9049676037c99ccf8b5768915d --- /dev/null +++ b/code_src/rise_code/sim_pipeline/training/train_robomimic.py @@ -0,0 +1,707 @@ +import os + +if 'DISPLAY' not in os.environ: + import glfw + glfw.ERROR_REPORTING = False + +import hydra +import json +import torch +import numpy as np +import robomimic.macros as Macros +import time +import psutil +import sys +import h5py + +import robomimic.utils.train_utils as TrainUtils +import robomimic.utils.obs_utils as ObsUtils +import robomimic.utils.env_utils as EnvUtils +import robomimic.utils.file_utils as FileUtils + +from pathlib import Path +from collections import OrderedDict + +from omegaconf import OmegaConf +from omegaconf import MissingMandatoryValue +from torch.utils.data import DataLoader + +from robomimic.config import config_factory +from robomimic.algo import algo_factory, RolloutPolicy +from robomimic.scripts.split_train_val import split_train_val_from_hdf5 +from robomimic.utils.log_utils import PrintLogger, DataLogger, flush_warnings + +from sim_pipeline.configs.constants import PolicyType, ImitationAlgorithm +from sim_pipeline.configs._imitation_learning.robomimic_imitation_base import RobomimicImitationBaseConfig +from sim_pipeline.configs.training._imitation_learning.base_imitation import ImitationTrainingConfig +from sim_pipeline.envs.robosuite_wrapper import RobomimicObsWrapper +from sim_pipeline.envs.make_env import make_env +# from sim_pipeline.configs.constants import PolicyType +from sim_pipeline.data_manager.get_dataset import get_dataset +from sim_pipeline.utils.find_robomimic_json import find_json +from sim_pipeline.utils.experiment import setup_experiment +from sim_pipeline.utils.train_utils import get_latest_robomimic_policy +from sim_pipeline.model_manager.create_model_metadata import create_model_metadata, update_metadata_trained +# from sim_pipeline.eval.rollout import rollout, PossibleVecEnv, RolloutStats +# from sim_pipeline.eval.rollout import RolloutPolicy as SimPipelineRolloutPolicy + +# from robomimic.scripts.train import train as robomimic_train + + +def robomimic_train(config, env_config, exp_config, device, log_dir, ckpt_dir, video_dir): + """ + Train a model using the algorithm. + """ + + # first set seeds + np.random.seed(config.train.seed) + torch.manual_seed(config.train.seed) + + torch.set_num_threads(2) + + print("\n============= New Training Run with Config =============") + print("") + + # if config.experiment.logging.terminal_output_to_txt: + # # log stdout and stderr to a text file + # logger = PrintLogger(os.path.join(log_dir, 'log.txt')) + # sys.stdout = logger + # sys.stderr = logger + + # read config to set up metadata for observation modalities (e.g. detecting rgb observations) + ObsUtils.initialize_obs_utils_with_config(config) + + # make sure the dataset exists + dataset_path = os.path.expanduser(config.train.data) + if not os.path.exists(dataset_path): + raise Exception("Dataset at provided path {} not found!".format(dataset_path)) + + # load basic metadata from training file + print("\n============= Loaded Environment Metadata =============") + env_meta = FileUtils.get_env_metadata_from_dataset(dataset_path=config.train.data) + shape_meta = FileUtils.get_shape_metadata_from_dataset( + dataset_path=config.train.data, + all_obs_keys=config.all_obs_keys, + verbose=True + ) + + if config.experiment.env is not None: + env_meta["env_name"] = config.experiment.env + print("=" * 30 + "\n" + "Replacing Env to {}\n".format(env_meta["env_name"]) + "=" * 30) + + # create environment + envs = OrderedDict() + config.experiment.rollout.enabled = False + if config.experiment.rollout.enabled: + # create environments for validation runs + env_names = [env_meta["env_name"]] + + if config.experiment.additional_envs is not None: + for name in config.experiment.additional_envs: + env_names.append(name) + + for env_name in env_names: + # env = EnvUtils.create_env_from_metadata( + # env_meta=env_meta, + # env_name=env_name, + # render=False, + # render_offscreen=config.experiment.render_video, + # use_image_obs=shape_meta["use_images"], + # use_depth_obs=shape_meta["use_depths"], + # ) + env: RobomimicObsWrapper = make_env( + env_config=env_config, + seed=exp_config.seed, + device_id=exp_config.device_id, + flatten_obs=False, + gymnasium_api=False, + ) + + env = EnvUtils.wrap_env_from_config(env, config=config) # apply environment warpper, if applicable + envs[env.name] = env + print(envs[env.name]) + + print("") + + # setup for a new training run + data_logger = DataLogger( + log_dir, + config, + log_tb=config.experiment.logging.log_tb, + log_wandb=config.experiment.logging.log_wandb, + ) + model = algo_factory( + algo_name=config.algo_name, + config=config, + obs_key_shapes=shape_meta["all_shapes"], + ac_dim=shape_meta["ac_dim"], + device=device, + ) + + # save the config as a json file + with open(os.path.join(log_dir, '..', 'config.json'), 'w') as outfile: + json.dump(config, outfile, indent=4) + + # rsm_rise patch: resume from a checkpoint (nets + EMA; optimizer moments are not stored by robomimic's save_model) + start_epoch = 1 + resume_ckpt = os.environ.get("RSM_RESUME_CKPT") + if resume_ckpt: + import re as _re + _ck = torch.load(resume_ckpt, map_location=device, weights_only=False) + model.deserialize(_ck["model"]) + _m = _re.search(r"model_epoch_(\d+)", os.path.basename(resume_ckpt)) + start_epoch = int(_m.group(1)) + 1 if _m else 1 + print(f"[rsm_rise] resumed nets+EMA from {resume_ckpt}; continuing at epoch {start_epoch}", flush=True) + del _ck + + print("\n============= Model Summary =============") + print(model) # print model summary + print("") + + # load training data + trainset, validset = TrainUtils.load_data_for_training( + config, obs_keys=shape_meta["all_obs_keys"]) + train_sampler = trainset.get_dataset_sampler( + data_source=trainset, + generator=torch.Generator(device=device), + ) + print("\n============= Training Dataset =============") + print(trainset) + print("") + if validset is not None: + print("\n============= Validation Dataset =============") + print(validset) + print("") + + # maybe retreve statistics for normalizing observations + obs_normalization_stats = None + if config.train.hdf5_normalize_obs: + obs_normalization_stats = trainset.get_obs_normalization_stats() + + # rsm_rise patch (GPU-utilisation mitigation): num_data_workers>0 moves batch collation off the training + # process. Two things are needed for it here: the loader generator must stay on `device` (setup_experiment + # calls torch.set_default_device('cuda'), so DataLoader's internal `torch.empty(())` is a CUDA tensor and a + # CPU generator raises), and each worker must switch its default device to CPU (a forked child must never + # touch CUDA; collation then yields CPU tensors, which robomimic moves to the GPU in + # postprocess_batch_for_training exactly as upstream does). The sampler and its generator are untouched, + # so the batch order/contents are unchanged. + def _worker_init(_wid): + torch.set_default_device('cpu') + _ndw = config.train.num_data_workers + train_loader = DataLoader( + dataset=trainset, + sampler=train_sampler, + batch_size=config.train.batch_size, + shuffle=(train_sampler is None), + num_workers=_ndw, + generator=torch.Generator(device=device), + worker_init_fn=(_worker_init if _ndw > 0 else None), + persistent_workers=(_ndw > 0), + prefetch_factor=(4 if _ndw > 0 else None), + drop_last=(not config.train.augment_nearby_states), + ) + + config.experiment.validate = False + if config.experiment.validate: + # cap num workers for validation dataset at 1 + num_workers = min(config.train.num_data_workers, 1) + valid_sampler = validset.get_dataset_sampler( + data_source=validset, + generator=torch.Generator(device=device), + ) + valid_loader = DataLoader( + dataset=validset, + sampler=valid_sampler, + batch_size=config.train.batch_size, + shuffle=(valid_sampler is None), + num_workers=num_workers, + generator=torch.Generator(device=device), + drop_last=True + ) + else: + valid_loader = None + + # print all warnings before training begins + print("*" * 50) + print("Warnings generated by robomimic have been duplicated here (from above) for convenience. Please check them carefully.") + flush_warnings() + print("*" * 50) + print("") + + # main training loop + best_valid_loss = None + best_return = {k: -np.inf for k in envs} if config.experiment.rollout.enabled else None + best_success_rate = {k: -1. for k in envs} if config.experiment.rollout.enabled else None + last_ckpt_time = time.time() + + # number of learning steps per epoch (defaults to a full dataset pass) + train_num_steps = config.experiment.epoch_every_n_steps + valid_num_steps = config.experiment.validation_epoch_every_n_steps + + for epoch in range(start_epoch, config.train.num_epochs + 1): # epoch numbers start at 1 (or after the resumed checkpoint) + if config.train.augment_nearby_states: + if epoch % 2 == 0: + train_loader.sampler.set_augmented() + else: + train_loader.sampler.set_regular() + + step_log = TrainUtils.run_epoch( + model=model, + data_loader=train_loader, + epoch=epoch, + num_steps=train_num_steps, + obs_normalization_stats=obs_normalization_stats, + ) + model.on_epoch_end(epoch) + + # setup checkpoint path + epoch_ckpt_name = "model_epoch_{}".format(epoch) + + # check for recurring checkpoint saving conditions + should_save_ckpt = False + if config.experiment.save.enabled: + time_check = (config.experiment.save.every_n_seconds is not None) and \ + (time.time() - last_ckpt_time > config.experiment.save.every_n_seconds) + epoch_check = (config.experiment.save.every_n_epochs is not None) and \ + (epoch > 0) and (epoch % config.experiment.save.every_n_epochs == 0) + epoch_list_check = (epoch in config.experiment.save.epochs) + should_save_ckpt = (time_check or epoch_check or epoch_list_check) + ckpt_reason = None + if should_save_ckpt: + last_ckpt_time = time.time() + ckpt_reason = "time" + + print("Train Epoch {}".format(epoch)) + should_save_ckpt = epoch % config.experiment.save.every_n_epochs == 0 + print(f"Should save ckpt: {should_save_ckpt}, enabled: {config.experiment.save.enabled}, freq: {config.experiment.save.every_n_epochs}") + print(json.dumps(step_log, sort_keys=True, indent=4)) + for k, v in step_log.items(): + if k.startswith("Time_"): + data_logger.record("Timing_Stats/Train_{}".format(k[5:]), v, epoch) + else: + data_logger.record("Train/{}".format(k), v, epoch) + + # Evaluate the model on validation set + if config.experiment.validate: + with torch.no_grad(): + step_log = TrainUtils.run_epoch(model=model, data_loader=valid_loader, epoch=epoch, validate=True, num_steps=valid_num_steps) + for k, v in step_log.items(): + if k.startswith("Time_"): + data_logger.record("Timing_Stats/Valid_{}".format(k[5:]), v, epoch) + else: + data_logger.record("Valid/{}".format(k), v, epoch) + + print("Validation Epoch {}".format(epoch)) + print(json.dumps(step_log, sort_keys=True, indent=4)) + + # save checkpoint if achieve new best validation loss + valid_check = "Loss" in step_log + if valid_check and (best_valid_loss is None or (step_log["Loss"] <= best_valid_loss)): + best_valid_loss = step_log["Loss"] + if config.experiment.save.enabled and config.experiment.save.on_best_validation: + epoch_ckpt_name += "_best_validation_{}".format(best_valid_loss) + should_save_ckpt = True + ckpt_reason = "valid" if ckpt_reason is None else ckpt_reason + + # Evaluate the model by by running rollouts + + # do rollouts at fixed rate or if it's time to save a new ckpt + video_paths = None + rollout_check = (epoch % config.experiment.rollout.rate == 0) or (should_save_ckpt and ckpt_reason == "time") + rollout_check = False + if config.experiment.rollout.enabled and (epoch > config.experiment.rollout.warmstart) and rollout_check: + + # wrap model as a RolloutPolicy to prepare for rollouts + rollout_model = RolloutPolicy(model, obs_normalization_stats=obs_normalization_stats) + # rollout_model = SimPipelineRolloutPolicy(rollout_model, policy_type=PolicyType.ROBOMIMIC) + + # rollout_stats = RolloutStats() + # # Custom rollout ignores possibility of multiple envs (not sure why we would ever need to roll out + # # a single policy on multiple distinct envs) + # env = next(iter(envs.values())) + # _env_name = next(iter(envs.keys())) + # env = PossibleVecEnv(envs) + + # if config.experiment.render_video: + # size = (512, 512) + # fps = 20 + # video_path = os.path.join(video_dir, f'{_env_name}_epoch_{epoch}.mp4') + # video_writer = cv2.VideoWriter(video_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, size) + # else: + # video_writer = None + + + num_episodes = config.experiment.rollout.n + # for ep in range(num_episodes): + # rollout( + # policy=rollout_model, + # eval_envs=env, + # rollout_stats=rollout_stats, + # logger=None, + # steps=config.experiment.rollout.horizon, + # render_mode='rgb_array', + # log_video=config.experiment.render_video, + # video_writer=None, + # video_skip=config.experiment.get("video_skip", 5), + # render_dims=None, + # return_trajectory=False, + # ) + # rollout_stats.compute_statistics() + + all_rollout_logs, video_paths = TrainUtils.rollout_with_stats( + policy=rollout_model, + envs=envs, + horizon=config.experiment.rollout.horizon, + use_goals=config.use_goals, + num_episodes=num_episodes, + render=False, + video_dir=video_dir if config.experiment.render_video else None, + epoch=epoch, + video_skip=config.experiment.get("video_skip", 5), + terminate_on_success=config.experiment.rollout.terminate_on_success, + ) + + # summarize results from rollouts to tensorboard and terminal + for env_name in all_rollout_logs: + rollout_logs = all_rollout_logs[env_name] + for k, v in rollout_logs.items(): + if k.startswith("Time_"): + data_logger.record("Timing_Stats/Rollout_{}_{}".format(env_name, k[5:]), v, epoch) + else: + data_logger.record("Rollout/{}/{}".format(k, env_name), v, epoch, log_stats=True) + + print("\nEpoch {} Rollouts took {}s (avg) with results:".format(epoch, rollout_logs["time"])) + print('Env: {}'.format(env_name)) + print(json.dumps(rollout_logs, sort_keys=True, indent=4)) + + # checkpoint and video saving logic + updated_stats = TrainUtils.should_save_from_rollout_logs( + all_rollout_logs=all_rollout_logs, + best_return=best_return, + best_success_rate=best_success_rate, + epoch_ckpt_name=epoch_ckpt_name, + save_on_best_rollout_return=config.experiment.save.on_best_rollout_return, + save_on_best_rollout_success_rate=config.experiment.save.on_best_rollout_success_rate, + ) + best_return = updated_stats["best_return"] + best_success_rate = updated_stats["best_success_rate"] + epoch_ckpt_name = updated_stats["epoch_ckpt_name"] + should_save_ckpt = (config.experiment.save.enabled and updated_stats["should_save_ckpt"]) or should_save_ckpt + if updated_stats["ckpt_reason"] is not None: + ckpt_reason = updated_stats["ckpt_reason"] + + # Only keep saved videos if the ckpt should be saved (but not because of validation score) + should_save_video = (should_save_ckpt and (ckpt_reason != "valid")) or config.experiment.keep_all_videos + if video_paths is not None and not should_save_video: + for env_name in video_paths: + os.remove(video_paths[env_name]) + + # Save model checkpoints based on conditions (success rate, validation loss, etc) + if should_save_ckpt: + print('saving!!!!') + TrainUtils.save_model( + model=model, + config=config, + env_meta=env_meta, + shape_meta=shape_meta, + ckpt_path=os.path.join(ckpt_dir, epoch_ckpt_name + ".pth"), + obs_normalization_stats=obs_normalization_stats, + ) + + # rsm_rise: ROLLING RESUME CHECKPOINT (preemptable queue). The released cadence is one checkpoint every + # `save_interval` (500) epochs; an S0A cell needs ~2.9 h to reach epoch 500 but the preemptable queue + # evicts it every ~1-2 h, so such a cell can restart forever without ever writing a checkpoint (observed: + # two_piece_expert_play S0A seed 1, 13 h wall / 5 restarts / 0 checkpoints). RSM_ROLLING_DIR + + # RSM_ROLLING_EVERY write ONE extra checkpoint every N epochs into a separate directory, keeping only the + # newest file, so a restart resumes from at most N lost epochs. This deletes nothing from the every-500 + # series the orchestrator asked to keep (13:26), costs one checkpoint of disk per cell, and is off unless + # the runner sets the two env vars. + # rsm_rise 2026-09-19 03:20 UTC: the epoch-based trigger is NOT sufficient on its own. An epoch + # multiple of RSM_ROLLING_EVERY=100 is ~24 min of work for an S0A cell, but the wandb-429 crash loop + # (see logger.py) was restarting mug_expert_suboptimal S0A seed0 every ~13 min, so it never reached a + # multiple of 100 and wrote no rolling checkpoint at all -- 0 net epochs since 2500. Add a purely + # TIME-based trigger: write a rolling checkpoint if RSM_ROLLING_SECONDS have passed since the last + # one, whatever the epoch rate. That bounds the work lost to a restart in wall-clock terms, which is + # the quantity that actually matters, and it costs at most one checkpoint write per interval per cell. + _roll_dir = os.environ.get("RSM_ROLLING_DIR") + _roll_every = int(os.environ.get("RSM_ROLLING_EVERY", "0") or 0) + _roll_secs = int(os.environ.get("RSM_ROLLING_SECONDS", "0") or 0) + _roll_due = False + if _roll_dir and epoch > 0 and not should_save_ckpt: + if _roll_every > 0 and epoch % _roll_every == 0: + _roll_due = True + if _roll_secs > 0: + _last_roll = globals().get("_RSM_LAST_ROLL_T") + if _last_roll is None: + globals()["_RSM_LAST_ROLL_T"] = time.time() # first interval starts at process start + elif time.time() - _last_roll >= _roll_secs: + _roll_due = True + if _roll_due: + globals()["_RSM_LAST_ROLL_T"] = time.time() + try: + os.makedirs(_roll_dir, exist_ok=True) + _tmp = os.path.join(_roll_dir, "model_epoch_{}.pth.tmp".format(epoch)) + _dst = os.path.join(_roll_dir, "model_epoch_{}.pth".format(epoch)) + TrainUtils.save_model( + model=model, config=config, env_meta=env_meta, shape_meta=shape_meta, + ckpt_path=_tmp, obs_normalization_stats=obs_normalization_stats, + ) + os.replace(_tmp, _dst) # atomic: a resume never sees a half-written file + for _f in os.listdir(_roll_dir): + if _f.endswith(".pth") and _f != os.path.basename(_dst): + try: + os.remove(os.path.join(_roll_dir, _f)) + except OSError: + pass + print("[rsm_rise] rolling resume checkpoint -> {}".format(_dst), flush=True) + except Exception as _e: # never let the bookkeeping kill a training run + print("[rsm_rise] rolling checkpoint failed: {!r}".format(_e), flush=True) + + # Finally, log memory usage in MB + process = psutil.Process(os.getpid()) + mem_usage = int(process.memory_info().rss / 1000000) + data_logger.record("System/RAM Usage (MB)", mem_usage, epoch) + print("\nEpoch {} Memory Usage: {} MB\n".format(epoch, mem_usage)) + + # terminate logging + data_logger.close() + + +@hydra.main(version_base=None, config_path='../configs', config_name='robomimic_iql_base') +def train(config: RobomimicImitationBaseConfig): + import traceback + import sys + try: + run(config) + except: + traceback.print_exc(file=sys.stderr) + raise + + +def get_robomimic_config(config: RobomimicImitationBaseConfig, dataset_path: str): + train_cfg: ImitationTrainingConfig = config.training + + with h5py.File(dataset_path, 'r') as f: + add_mask = 'mask' not in f + + if add_mask: + split_train_val_from_hdf5(dataset_path, val_ratio=0.1) + + use_image = bool(train_cfg.rgb_keys) + json_path = find_json(train_cfg, config.env.env_name.get_simple_name(), use_image) + + Macros.WANDB_ENTITY = config.exp.entity + + if json_path is None: + robomimic_config = config_factory(train_cfg.algo.value) + else: + json_config = json.load(open(json_path, 'r')) + + json_config['experiment']['name'] = config.name + json_config['train']['data'] = dataset_path + json_config['train']['output_dir'] = config.exp.logdir + json_config['train']['batch_size'] = train_cfg.batch_size + json_config['train']['num_epochs'] = train_cfg.num_epochs + json_config['train']['pad_seq_length'] = train_cfg.pad_seq_length + if train_cfg.lipschitz and not train_cfg.lipschitz_slack: + json_config['train']['dataset_keys'] = json_config['train']['dataset_keys'] + ['entropy'] + json_config['experiment']['epoch_every_n_steps'] = train_cfg.epoch_every_n_steps + json_config['experiment']['validate'] = not train_cfg.algo.is_offline_rl() + + json_config['experiment']['logging']['log_wandb'] = 'wandb' in config.exp.format_strings if not config.debug else False + json_config['experiment']['logging']['wandb_proj_name'] = config.exp.project + json_config['experiment']['logging']['log_tb'] = 'tensorboard' in config.exp.format_strings + + json_config['experiment']['rollout']['enabled'] = not train_cfg.algo.is_offline_rl() + json_config['experiment']['rollout']['horizon'] = train_cfg.rollout_horizon + json_config['experiment']['rollout']['rate'] = config.exp.eval_interval + json_config['experiment']['render_video'] = train_cfg.render_video + json_config['experiment']['save']['every_n_epochs'] = config.exp.save_interval + + json_config['observation']['modalities']['obs']['low_dim'] = OmegaConf.to_container(train_cfg.low_dim_keys) + json_config['observation']['modalities']['obs']['rgb'] = OmegaConf.to_container(train_cfg.rgb_keys) + json_config['observation']['modalities']['obs']['depth'] = OmegaConf.to_container(train_cfg.depth_keys) + + json_config['train']['hdf5_cache_mode'] = train_cfg.cache_mode + json_config['train']['augment_nearby_states'] = train_cfg.action_augmentation + json_config['train']['distance_threshold'] = train_cfg.distance_threshold + json_config['train']['num_neighbors'] = train_cfg.num_neighbors + json_config['algo']['action_augmentation'] = train_cfg.action_augmentation + json_config['train']['advanced_augmentation'] = train_cfg.advanced_augmentation + json_config['train']['augment_init_cutoff_thresh'] = train_cfg.augment_init_cutoff_threshold + json_config['train']['augment_init_cutoff_thresh_expert'] = train_cfg.augment_init_cutoff_thresh_expert + json_config['train']['augment_play'] = train_cfg.augment_play + json_config['train']['gripper_key'] = train_cfg.late_fusion_key + json_config['train']['mask_augmentation'] = train_cfg.mask_augmentation + json_config['train']['proprio_keys'] = OmegaConf.to_container(train_cfg.low_dim_keys) + # rsm_rise gen_q#265: expert:play sampling mixture (None = released uniform sampling); configs that + # lack the field (non-IQL algos) fall back to None. + json_config['train']['expert_play_ratio'] = train_cfg.get('expert_play_ratio', None) + json_config['train']['done_mode_terminal_only'] = bool(train_cfg.get('done_mode_terminal_only', False)) # rsm_rise gen_q#265 wave 2 + + if train_cfg.use_dino_features: + json_config['observation']['encoder']['rgb']['core_class'] = 'DinoV2Core' + json_config['observation']['encoder']['rgb']['core_kwargs'] = { + 'backbone_name': 'dinov2_vits14', + 'frozen': True, + } + # rsm_rise CRITIC_DINO (gen_q fairness fix #1, 2026-09-25). The one-flag switch above swaps the + # ENCODER but leaves `obs_randomizer_class: CropRandomizer` (76x76 of the 84x84 frame) in place, + # so the DINO features it produces are NOT the features the RSM / DINO-WM / DF / IFQL scorers + # consume: scripts/relabel_dino.py encodes the FULL 84x84 frame (uint8 HWC -> /255 -> CHW -> + # Resize(256) -> CenterCrop(224) -> ImageNet norm -> dinov2_vits14 -> [CLS | GeM(patches)] per + # camera, 768/cam, 1536 for agentview+wrist, then 9-d proprio -> the 1545-d state). A 76-crop + # upsampled to 256 is a different field of view, i.e. different conditioning information, which + # is exactly what this experiment is controlling for. So drop the crop under DINO: the critic + # then sees byte-for-byte what cache//z.f16.npy holds. + # RSM_DINO_KEEP_CROP=1 restores the 76-crop, for the "same flag, RISE's own randomizer" variant. + if os.environ.get('RSM_DINO_KEEP_CROP', '0') != '1': + json_config['observation']['encoder']['rgb']['obs_randomizer_class'] = None + json_config['observation']['encoder']['rgb']['obs_randomizer_kwargs'] = {} + print('[rsm_rise CRITIC_DINO] use_dino_features=True -> CropRandomizer DISABLED ' + '(full 84x84 frame, matching cache// features). RSM_DINO_KEEP_CROP=1 to keep it.', + flush=True) + elif train_cfg.pretrained: + json_config['observation']['encoder']['rgb']['core_kwargs']['backbone_kwargs']['pretrained'] = True + + if train_cfg.algo.is_offline_rl(): + json_config['algo']['optim_params']['critic']['learning_rate']['initial'] = train_cfg.learning_rate + json_config['algo']['optim_params']['vf']['learning_rate']['initial'] = train_cfg.learning_rate + json_config['algo']['target_tau'] = train_cfg.target_tau + json_config['algo']['vf_quantile'] = train_cfg.vf_quantile + json_config['algo']['critic']['layer_dims'] = OmegaConf.to_container(train_cfg.layer_dims) + json_config['algo']['critic']['late_fusion_key'] = train_cfg.late_fusion_key + json_config['algo']['critic']['late_fusion_layer_index'] = train_cfg.late_fusion_layer_index + + if train_cfg.multiply_late_fusion_key and train_cfg.late_fusion_key is not None: + json_config['algo']['critic']['obs_multiplier_key'] = train_cfg.late_fusion_key + json_config['algo']['critic']['obs_multiplier'] = train_cfg.multiply_constant + + json_config['algo']['adv']['beta'] = train_cfg.beta + json_config['algo']['adv']['clip_adv_value'] = train_cfg.get('clip_adv_value', None) # rsm_rise gen_q#265 + json_config['algo']['awr_actor'] = bool(train_cfg.get('awr_actor', False)) # rsm_rise gen_q#265 + json_config['algo']['critic_on_augmented'] = bool(train_cfg.get('critic_on_augmented', False)) # rsm_rise gen_q#265 wave 2 + # rsm_rise BASE_TOPUP (gen_q#287) fast critic path, 2026-09-26 + json_config['algo']['critic_only'] = bool(train_cfg.get('critic_only', False)) + json_config['algo']['critic_skip_even_epochs'] = bool(train_cfg.get('critic_skip_even_epochs', False)) + json_config['algo']['discount'] = train_cfg.discount_rate + + json_config['algo']['optim_params']['critic']['regularization']['L2'] = train_cfg.l2_value + json_config['algo']['optim_params']['vf']['regularization']['L2'] = train_cfg.l2_value + json_config['algo']['optim_params']['policy']['regularization']['L2'] = train_cfg.l2_policy + + if not train_cfg.algo.is_diffusion(): + json_config['algo']['actor']['layer_dims'] = OmegaConf.to_container(train_cfg.layer_dims) + json_config['algo']['actor']['net']['type'] = train_cfg.net_arch + json_config['algo']['actor']['net']['gmm']['num_modes'] = train_cfg.gmm_heads + json_config['algo']['optim_params']['actor']['learning_rate']['initial'] = train_cfg.learning_rate + else: + # iql diffusion + json_config['algo']['multi_step_method'] = train_cfg.multi_step_method.value + json_config['algo']['use_bc'] = train_cfg.use_bc + if train_cfg.use_bc: + json_config['train']['hdf5_load_next_obs'] = False + json_config['algo']['unet']['down_dims'] = OmegaConf.to_container(train_cfg.down_dims) + json_config['algo']['unet']['diffusion_step_embed_dim'] = train_cfg.diffusion_step_embed_dim + json_config['algo']['optim_params']['policy']['learning_rate']['initial'] = train_cfg.learning_rate + json_config['algo']['optim_params']['policy']['freeze_until_epoch'] = train_cfg.actor_freeze_until_epoch + json_config['algo']['horizon']['observation_horizon'] = train_cfg.observation_horizon + json_config['algo']['horizon']['action_horizon'] = train_cfg.action_horizon + json_config['algo']['horizon']['prediction_horizon'] = train_cfg.prediction_horizon + json_config['train']['frame_stack'] = train_cfg.observation_horizon + json_config['train']['seq_length'] = train_cfg.prediction_horizon + + #bottleneck config + json_config['algo']['bottleneck_value'] = train_cfg.bottleneck_value + json_config['algo']['bottleneck_policy'] = train_cfg.bottleneck_policy + json_config['algo']['q_bottleneck_beta'] = train_cfg.q_bottleneck_beta + json_config['algo']['policy_bottleneck_beta'] = train_cfg.policy_bottleneck_beta + json_config['algo']['spectral_norm_value'] = train_cfg.spectral_norm_value + json_config['algo']['spectral_norm_policy'] = train_cfg.spectral_norm_policy + json_config['algo']['lipschitz'] = train_cfg.lipschitz + json_config['algo']['lipschitz_constant'] = train_cfg.lipschitz_constant + json_config['algo']['lipschitz_weight'] = train_cfg.lipschitz_weight + json_config['algo']['lipschitz_slack'] = train_cfg.lipschitz_slack + json_config['algo']['lipschitz_denoiser'] = train_cfg.lipschitz_denoiser + + # rsm_rise Stage 3 planner / RSM-advantage keys (defaults = released behaviour) + from sim_pipeline.configs.training._imitation_learning._offline_rl.iql_diffusion import planner_kwargs + for _k, _v in planner_kwargs(train_cfg).items(): + json_config['algo'][_k] = _v + + # rsm_rise patch (GPU-utilisation mitigation, 2026-09-18): robomimic's DataLoader defaults to + # num_data_workers=0, so one process alternates hdf5-cache collation (~25 % of epoch time) and the + # GPU step. RSM_NUM_DATA_WORKERS>0 moves collation to worker processes; it changes no training + # semantics (same sampler, same seed, same batch contents). Unset / 0 == released behaviour. + _ndw = os.environ.get("RSM_NUM_DATA_WORKERS") + if _ndw: + json_config['train']['num_data_workers'] = int(_ndw) + print(f"[rsm_rise] train.num_data_workers = {_ndw} (RSM_NUM_DATA_WORKERS)", flush=True) + + robomimic_config = config_factory(json_config['algo_name']) + with robomimic_config.values_unlocked(): + robomimic_config.update(json_config) + + return robomimic_config + + +def run(config: RobomimicImitationBaseConfig): + device = setup_experiment(config.exp) + + dataset_path = get_dataset(config.data) + + robomimic_config = get_robomimic_config(config, dataset_path=dataset_path) + + # SEED PLUMBING (rsm_rise 2026-09-21, gen_q#260). `setup_experiment(config.exp)` above seeds + # numpy/torch from exp.seed, but robomimic_train() re-seeds from `config.train.seed` BEFORE it + # builds the networks (lines ~57-58, algo_factory at ~133). That field was never written from + # exp.seed, so it held the robomimic default of 1 and EVERY policy and critic in this project -- + # S0A, S0B, S3H1, S0Aidql, at seeds 0/1/2, on every task -- was initialised identically and saw the + # same data order. The cross-seed spread we were reporting as replication was CUDA/dataloader + # non-determinism, not independent runs. Write exp.seed through so the re-seed is per-seed. + try: + with robomimic_config.unlocked(): + robomimic_config.train.seed = int(config.exp.seed) + except AttributeError: # not a robomimic Config object; assign directly + robomimic_config.train.seed = int(config.exp.seed) + print(f"[rsm_rise] train.seed <- exp.seed = {robomimic_config.train.seed}") + # HELD-OUT SPLIT (rsm_rise V6_IQL 2026-10-15). Default OFF: unset => train.hdf5_filter_key untouched (None in + # every existing recipe => all demos, bit-identical). RSM_HDF5_FILTER_KEY=train trains only on mask/train, so the + # v6 critics never see the TUNE/TEST episodes (mask/valid) that the junction gate scores. + _fk = os.environ.get("RSM_HDF5_FILTER_KEY", "") + if _fk: + try: + with robomimic_config.unlocked(): + robomimic_config.train.hdf5_filter_key = _fk + except AttributeError: + robomimic_config.train.hdf5_filter_key = _fk + print(f"[rsm_rise] train.hdf5_filter_key = {robomimic_config.train.hdf5_filter_key}") + + log_dir = Path(config.exp.logdir) / config.name + log_dir_rm, ckpt_dir_rm, video_dir_rm = TrainUtils.get_exp_dir(robomimic_config) + dt_string = Path(log_dir_rm).parent.name + create_model_metadata( + name=config.name, + policy_type=PolicyType.ROBOMIMIC, + policy_identifier=dt_string, + dataset_path=dataset_path, + hydra_config=config, + filepath=log_dir / dt_string / 'metadata.json', + ) + try: + robomimic_train(robomimic_config, config.env, config.exp, device, log_dir_rm, ckpt_dir_rm, video_dir_rm) + finally: + # rsm_rise 2026-09-19 03:15 UTC: this `finally` used to run bare, and get_latest_robomimic_policy() + # RAISES ValueError('No policy found in ...') when the current run's models/ dir is still empty. + # On a RESUMED run that is the normal state until it reaches its first every-500 checkpoint, so any + # crash inside robomimic_train() had its real traceback REPLACED by + # ValueError: No policy found in ...//models + # i.e. the exception that actually killed the training was destroyed by bookkeeping in its own + # cleanup path. That is what made the wandb-429 crash loop (see logger.py) hard to diagnose. + # This is pure metadata bookkeeping: it must never mask, or cause, a failure. + try: + max_epochs_saved: int = get_latest_robomimic_policy(log_dir / dt_string / 'models', find_epoch=True) + if max_epochs_saved >= 100: + update_metadata_trained(log_dir / dt_string / 'metadata.json') + except Exception as _meta_e: + print('[rsm_rise] trained-metadata bookkeeping skipped: {!r}'.format(_meta_e), flush=True) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/utils/config_utils.py b/code_src/rise_code/sim_pipeline/utils/config_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..148fa65532901c197c4ae136b7344424e538c112 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/utils/config_utils.py @@ -0,0 +1,16 @@ +from enum import Enum + +def convert_hydra_for_serialization(hydra_cfg: dict): + # convert enums into their values for json serialization + + for key, value in hydra_cfg.items(): + if isinstance(value, Enum): + hydra_cfg[key] = value.value + elif isinstance(value, dict): + convert_hydra_for_serialization(value) + elif isinstance(value, list): + for i, item in enumerate(value): + if isinstance(item, dict): + convert_hydra_for_serialization(item) + elif isinstance(item, Enum): + value[i] = item.value diff --git a/code_src/rise_code/sim_pipeline/utils/diffusion_utils.py b/code_src/rise_code/sim_pipeline/utils/diffusion_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e679150badb2efcd549531a6f3c81ae7271ceefc --- /dev/null +++ b/code_src/rise_code/sim_pipeline/utils/diffusion_utils.py @@ -0,0 +1,24 @@ +from diffusion_policy.policy.diffusion_unet_hybrid_image_policy import DiffusionUnetHybridImagePolicy +from diffusion_policy.policy.diffusion_unet_lowdim_policy import DiffusionUnetLowdimPolicy +from diffusion_policy.policy.diffusion_unet_image_policy import DiffusionUnetImagePolicy + +from diffusion_policy.workspace.train_diffusion_unet_hybrid_workspace import TrainDiffusionUnetHybridWorkspace +from diffusion_policy.workspace.train_diffusion_unet_lowdim_workspace import TrainDiffusionUnetLowdimWorkspace +from diffusion_policy.workspace.train_diffusion_unet_image_workspace import TrainDiffusionUnetImageWorkspace +from diffusion_policy.workspace.base_workspace import BaseWorkspace + +def get_policy_class(rgb_keys: list[str], lowdim_keys: list[str], depth_keys: list[str]) -> type: + if len(rgb_keys) > 0 and len(lowdim_keys) > 0: + return DiffusionUnetHybridImagePolicy + if len(rgb_keys) > 0: + return DiffusionUnetImagePolicy + if len(lowdim_keys) > 0: + return DiffusionUnetLowdimPolicy + +def get_workspace(rgb_keys: list[str], lowdim_keys: list[str], depth_keys: list[str]) -> type[BaseWorkspace]: + if len(rgb_keys) > 0 and len(lowdim_keys) > 0: + return TrainDiffusionUnetHybridWorkspace + if len(rgb_keys) > 0: + return TrainDiffusionUnetImageWorkspace + if len(lowdim_keys) > 0: + return TrainDiffusionUnetLowdimWorkspace \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/utils/experiment.py b/code_src/rise_code/sim_pipeline/utils/experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..067cf8e48c02927643531d081836bfb3770db734 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/utils/experiment.py @@ -0,0 +1,62 @@ +import wandb +import omegaconf +import random +import torch +import numpy as np + +from omegaconf import MissingMandatoryValue +from sim_pipeline.configs.exp.base import BaseExpConfig + +def setup_wandb(cfg, name, entity, project): + + run = wandb.init( + name=name, + entity=entity, + project=project, + config=omegaconf.OmegaConf.to_container( + cfg, resolve=True, throw_on_missing=True + ), + settings=wandb.Settings(start_method="thread"), + ) + + return run + +def set_random_seed(seed): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + + +def set_gpu_mode(mode, gpu_id=0): + global _GPU_ID + global _USE_GPU + global _DEVICE + _GPU_ID = gpu_id + _USE_GPU = mode + _DEVICE = torch.device(("cuda:" + str(_GPU_ID)) if _USE_GPU else "cpu") + torch.set_default_tensor_type( + torch.cuda.FloatTensor if _USE_GPU else torch.FloatTensor + ) + +def get_device() -> torch.device: + global _DEVICE + return _DEVICE + + +def setup_experiment(exp_config: BaseExpConfig, eval: bool = False) -> torch.device: + try: + seed = exp_config.seed + except MissingMandatoryValue: + exp_config['seed'] = np.random.randint(0, 1000000) + seed = exp_config.seed + + if eval: + try: + seed = exp_config.eval_seed + except MissingMandatoryValue: + exp_config['eval_seed'] = np.random.randint(0, 1000000) + seed = exp_config.eval_seed + + set_random_seed(seed) + set_gpu_mode(torch.cuda.is_available(), exp_config.device_id) + return get_device() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/utils/find_robomimic_json.py b/code_src/rise_code/sim_pipeline/utils/find_robomimic_json.py new file mode 100644 index 0000000000000000000000000000000000000000..4f034f7593def88ea5635a5d2c8573bd98789cbc --- /dev/null +++ b/code_src/rise_code/sim_pipeline/utils/find_robomimic_json.py @@ -0,0 +1,59 @@ +import os +import robomimic +import h5py +import json + +from pathlib import Path +from sim_pipeline.configs.training._imitation_learning.base_imitation import ImitationTrainingConfig +from sim_pipeline.configs.constants import ImitationAlgorithm, LOG_DIR + +def file_if_exists(filepath: Path) -> str | None: + return str(filepath) if filepath.exists() else None + +def find_json(training_config: ImitationTrainingConfig, env: str, use_image: bool) -> str | None: + algo: ImitationAlgorithm = training_config.algo + + robomimic_dir = Path(robomimic.__path__[0]) + template_dir = robomimic_dir / 'exps' / 'templates' + paper_configs_dir = robomimic_dir / 'exps' / 'paper' + + if algo not in [ImitationAlgorithm.BC, ImitationAlgorithm.BC_RNN, ImitationAlgorithm.CQL]: + return file_if_exists(Path(f'{template_dir}/{algo.value}.json')) + + if not paper_configs_dir.exists(): + generate_script = robomimic_dir / 'scripts' / 'generate_paper_configs.py' + os.system(f'python {generate_script} --output_dir {LOG_DIR}') + + obs = 'image' if use_image else 'low_dim' + json_dir = paper_configs_dir / 'core' / env / 'ph' / obs / f'{algo.value}.json' + + if not json_dir.exists(): + return file_if_exists(Path(f'{template_dir}/{algo.value}.json')) + return json_dir + + # try: + # with open(json_dir, 'r') as f: + # config = json.load(f) + # obs_modalities = config['observation']['modalities']['obs'] + # for config_obs_key in obs_modalities.values(): + # for key in config_obs_key: + # if key not in obs_keys: + # violating_key = key + # break + # else: + # # config key is in data + # continue + + # # config key is not in data + # break + # else: + # # all config keys are in data + # return str(json_dir) + + # # not all config keys are in data, invalid config + # print(f'found json config {json_dir}, but provided data is missing key {violating_key}') + # return None + + # except Exception as e: + # print(f'Error loading robomimic json config: {e}') + # return None \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/utils/get_base_env.py b/code_src/rise_code/sim_pipeline/utils/get_base_env.py new file mode 100644 index 0000000000000000000000000000000000000000..d89467ff29c0aa218e73f96f969ced8dad9ab1f6 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/utils/get_base_env.py @@ -0,0 +1,12 @@ +from typing import TypeVar + +T = TypeVar('T') + +def get_base_env(env, desired_class: type[T]) -> T | None: + if isinstance(env, desired_class): + return env + + if not hasattr(env, 'env'): + return None + + return get_base_env(env.env, desired_class) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/utils/logger.py b/code_src/rise_code/sim_pipeline/utils/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..8fc95b34976521e428e6994f9df24addaa880b06 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/utils/logger.py @@ -0,0 +1,539 @@ +import os +import sys +import warnings +from collections import defaultdict +from typing import Any, Dict, List, Optional, Sequence, TextIO, Tuple, Union + +import numpy as np +import torch +from matplotlib import pyplot as plt + +import wandb + +try: + from torch.utils.tensorboard import SummaryWriter +except ImportError: + SummaryWriter = None + +DEBUG = 10 +INFO = 20 +WARN = 30 +ERROR = 40 +DISABLED = 50 + + +class Video(object): + """ + Video data class storing the video frames and the frame per seconds + :param frames: frames to create the video from + :param fps: frames per second + """ + + def __init__(self, frames: Union[torch.Tensor, np.ndarray], fps: Union[float, int]): + self.frames = frames + self.fps = fps + + +class Figure(object): + """ + Figure data class storing a matplotlib figure and whether to close the figure after logging it + :param figure: figure to log + :param close: if true, close the figure after logging it + """ + + def __init__(self, figure: plt.figure, close: bool): + self.figure = figure + self.close = close + + +class Image(object): + """ + Image data class storing an image and data format + :param image: image to log + :param dataformats: Image data format specification of the form NCHW, NHWC, CHW, HWC, HW, WH, etc. + More info in add_image method doc at https://pytorch.org/docs/stable/tensorboard.html + Gym envs normally use 'HWC' (channel last) + """ + + def __init__(self, image: Union[torch.Tensor, np.ndarray, str], dataformats: str): + self.image = image + self.dataformats = dataformats + + +class FormatUnsupportedError(NotImplementedError): + def __init__(self, unsupported_formats: Sequence[str], value_description: str): + if len(unsupported_formats) > 1: + format_str = f"formats {', '.join(unsupported_formats)} are" + else: + format_str = f"format {unsupported_formats[0]} is" + super(FormatUnsupportedError, self).__init__( + f"The {format_str} not supported for the {value_description} value logged.\n" + f"You can exclude formats via the `exclude` parameter of the logger's `record` function." + ) + + +class KVWriter(object): + """ + Key Value writer + """ + + def write( + self, + key_values: Dict[str, Any], + key_excluded: Dict[str, Union[str, Tuple[str, ...]]], + step: int = 0, + ) -> None: + """ + Write a dictionary to file + :param key_values: + :param key_excluded: + :param step: + """ + raise NotImplementedError + + def close(self) -> None: + """ + Close owned resources + """ + raise NotImplementedError + + +class SeqWriter(object): + """ + sequence writer + """ + + def write_sequence(self, sequence: List) -> None: + """ + write_sequence an array to file + :param sequence: + """ + raise NotImplementedError + + +class HumanOutputFormat(KVWriter, SeqWriter): + """A human-readable output format producing ASCII tables of key-value pairs. + Set attribute `max_length` to change the maximum length of keys and values + to write to output (or specify it when calling `__init__`). + """ + + def __init__(self, filename_or_file: Union[str, TextIO], max_length: int = 36): + """ + log to a file, in a human readable format + :param filename_or_file: the file to write the log to + :param max_length: the maximum length of keys and values to write to output. + Outputs longer than this will be truncated. An error will be raised + if multiple keys are truncated to the same value. The maximum output + width will be ``2*max_length + 7``. The default of 36 produces output + no longer than 79 characters wide. + """ + self.max_length = max_length + if isinstance(filename_or_file, str): + self.file = open(filename_or_file, "wt") + self.own_file = True + else: + assert hasattr( + filename_or_file, "write" + ), f"Expected file or str, got {filename_or_file}" + self.file = filename_or_file + self.own_file = False + + def write(self, key_values: Dict, key_excluded: Dict, step: int = 0) -> None: + # Create strings for printing + key2str = [] + tag = None + tags = set() + for (key, value), (_, excluded) in zip( + sorted(key_values.items()), sorted(key_excluded.items()) + ): + + if excluded is not None and ("stdout" in excluded or "log" in excluded): + continue + + elif isinstance(value, Video): + raise FormatUnsupportedError(["stdout", "log"], "video") + + elif isinstance(value, Figure): + raise FormatUnsupportedError(["stdout", "log"], "figure") + + elif isinstance(value, Image): + raise FormatUnsupportedError(["stdout", "log"], "image") + + elif isinstance(value, float): + # Align left + value_str = f"{value:<8.3g}" + else: + value_str = str(value) + + # Find tag and add it to the dict + if key.find("/") > 0: + tag = key[: key.find("/") + 1] + if tag not in tags: + tags.add(tag) + key2str.append((self._truncate(tag), "")) + # Remove tag from key + if tag is not None and tag in key: + key = str(" " + key[len(tag) :]) + # Add key to the dict + key2str.append((self._truncate(key), self._truncate(value_str))) + + # Find max widths + if len(key2str) == 0: + warnings.warn("Tried to write empty key-value dict") + return + else: + keys, vals = list(zip(*key2str)) + key_width = max(map(len, keys)) + val_width = max(map(len, vals)) + + # Write out the data + dashes = "-" * (key_width + val_width + 7) + lines = [dashes] + for key, value in key2str: + key_space = " " * (key_width - len(key)) + val_space = " " * (val_width - len(value)) + lines.append(f"| {key}{key_space} | {value}{val_space} |") + lines.append(dashes) + self.file.write("\n".join(lines) + "\n") + + # Flush the output to the file + self.file.flush() + + def _truncate(self, string: str) -> str: + if len(string) > self.max_length: + string = string[: self.max_length - 3] + "..." + return string + + def write_sequence(self, sequence: List) -> None: + sequence = list(sequence) + for i, elem in enumerate(sequence): + self.file.write(elem) + if i < len(sequence) - 1: # add space unless this is the last one + self.file.write(" ") + self.file.write("\n") + self.file.flush() + + def close(self) -> None: + """ + closes the file + """ + if self.own_file: + self.file.close() + + +class TensorBoardOutputFormat(KVWriter): + def __init__(self, folder: str): + """ + Dumps key/value pairs into TensorBoard's numeric format. + :param folder: the folder to write the log to + """ + assert SummaryWriter is not None, ( + "tensorboard is not installed, you can use " + "pip install tensorboard to do so" + ) + self.writer = SummaryWriter(log_dir=folder) + + def write( + self, + key_values: Dict[str, Any], + key_excluded: Dict[str, Union[str, Tuple[str, ...]]], + step: int = 0, + ) -> None: + + for (key, value), (_, excluded) in zip( + sorted(key_values.items()), sorted(key_excluded.items()) + ): + + if excluded is not None and "tensorboard" in excluded: + continue + + if isinstance(value, np.ScalarType): + if isinstance(value, str): + # str is considered a np.ScalarType + self.writer.add_text(key, value, step) + else: + self.writer.add_scalar(key, value, step) + + if isinstance(value, torch.Tensor): + self.writer.add_histogram(key, value, step) + + if isinstance(value, Video): + self.writer.add_video(key, value.frames, step, value.fps) + + if isinstance(value, Figure): + self.writer.add_figure(key, value.figure, step, close=value.close) + + if isinstance(value, Image): + self.writer.add_image( + key, value.image, step, dataformats=value.dataformats + ) + + # Flush the output to the file + self.writer.flush() + + def close(self) -> None: + """ + closes the file + """ + if self.writer: + self.writer.close() + self.writer = None + + +class WANDBOutputFormat(KVWriter): + def __init__(self): + if wandb.run is None: + raise ValueError("WandB is not initialized") + # see the note in write(): consecutive-failure counter for the non-fatal wandb.log path + self._wandb_failures = 0 + self._wandb_max_failures = int(os.environ.get("RSM_WANDB_MAX_FAILURES", "20") or 20) + + def write( + self, + key_values: Dict[str, Any], + key_excluded: Dict[str, Union[str, Tuple[str, ...]]], + step: int = 0, + ) -> None: + + wandb_dict = {} + for (key, value), (_, excluded) in zip( + sorted(key_values.items()), sorted(key_excluded.items()) + ): + + if excluded is not None and "wandb" in excluded: + continue + + if isinstance(value, np.ScalarType): + wandb_dict[key] = value + + if isinstance(value, torch.Tensor): + wandb_dict[key] = wandb.Histogram(value) + + if isinstance(value, Video): + wandb_dict[key] = wandb.Video(value.frames, fps=value.fps, format="gif") + + # Log to wandb. + # rsm_rise 2026-09-19 03:15 UTC: W&B logging must NEVER be able to kill a 5000-epoch training. + # With ~110 concurrent runs in one project the backend starts returning + # 429 {"error":"rate limit exceeded: per_project limit on filestream requests"} + # and the wandb SDK's service connection then dies with + # ConnectionResetError('Connection lost') + # which propagates out of wandb.log() into robomimic's train loop and terminates the process. + # Measured effect before this patch: 119 job logs with the 429 and 59 with the ConnectionResetError; + # mug_expert_suboptimal S0A seed0 (job 1767499) was crash-looping every ~13 min and had made + # ZERO net progress since epoch 2500 (restart overhead alone exceeded its lifetime). + # Telemetry is strictly less important than the training itself, so swallow every wandb failure, + # and stop calling wandb.log() at all after RSM_WANDB_MAX_FAILURES consecutive failures so a dead + # backend cannot keep costing wall time. stdout + tensorboard logging are unaffected, and the + # checkpoints / eval JSONs that every downstream table is built from do not come from W&B. + if self._wandb_failures < self._wandb_max_failures: + try: + wandb.log(wandb_dict) + self._wandb_failures = 0 + except Exception as e: + self._wandb_failures += 1 + print("[rsm_rise] wandb.log failed ({}/{}), continuing training: {!r}".format( + self._wandb_failures, self._wandb_max_failures, e), flush=True) + if self._wandb_failures >= self._wandb_max_failures: + print("[rsm_rise] wandb.log disabled for the rest of this process " + "(too many consecutive failures); stdout/tensorboard logging continues", + flush=True) + + def close(self) -> None: + pass + + +def make_output_format(_format: str, log_dir: str, log_suffix: str = "") -> KVWriter: + """ + return a logger for the requested format + :param _format: the requested format to log to ('stdout', 'log', 'json' or 'csv' or 'tensorboard') + :param log_dir: the logging directory + :param log_suffix: the suffix for the log file + :return: the logger + """ + os.makedirs(log_dir, exist_ok=True) + if _format == "stdout": + return HumanOutputFormat(sys.stdout) + elif _format == "log": + return HumanOutputFormat(os.path.join(log_dir, f"log{log_suffix}.txt")) + elif _format == "tensorboard": + return TensorBoardOutputFormat(log_dir) + elif _format == "wandb": + return WANDBOutputFormat() + else: + raise ValueError(f"Unknown format specified: {_format}") + + +# ================================================================ +# Backend +# ================================================================ + + +class Logger(object): + """ + The logger class. + :param folder: the logging location + :param output_formats: the list of output formats + """ + + def __init__(self, folder: Optional[str], output_formats: List[KVWriter]): + self.name_to_value = defaultdict(float) # values this iteration + self.name_to_count = defaultdict(int) + self.name_to_excluded = defaultdict(str) + self.level = INFO + self.dir = folder + self.output_formats = output_formats + + def record( + self, + key: str, + value: Any, + exclude: Optional[Union[str, Tuple[str, ...]]] = None, + ) -> None: + """ + Log a value of some diagnostic + Call this once for each diagnostic quantity, each iteration + If called many times, last value will be used. + :param key: save to log this key + :param value: save to log this value + :param exclude: outputs to be excluded + """ + self.name_to_value[key] = value + self.name_to_excluded[key] = exclude + + def record_mean( + self, + key: str, + value: Any, + exclude: Optional[Union[str, Tuple[str, ...]]] = None, + ) -> None: + """ + The same as record(), but if called many times, values averaged. + :param key: save to log this key + :param value: save to log this value + :param exclude: outputs to be excluded + """ + if value is None: + self.name_to_value[key] = None + return + old_val, count = self.name_to_value[key], self.name_to_count[key] + self.name_to_value[key] = old_val * count / (count + 1) + value / (count + 1) + self.name_to_count[key] = count + 1 + self.name_to_excluded[key] = exclude + + def dump(self, step: int = 0) -> None: + """ + Write all of the diagnostics from the current iteration + """ + if self.level == DISABLED: + return + for _format in self.output_formats: + if isinstance(_format, KVWriter): + _format.write(self.name_to_value, self.name_to_excluded, step) + + self.name_to_value.clear() + self.name_to_count.clear() + self.name_to_excluded.clear() + + def log(self, *args, level: int = INFO) -> None: + """ + Write the sequence of args, with no separators, + to the console and output files (if you've configured an output file). + level: int. (see logger.py docs) If the global logger level is higher than + the level argument here, don't print to stdout. + :param args: log the arguments + :param level: the logging level (can be DEBUG=10, INFO=20, WARN=30, ERROR=40, DISABLED=50) + """ + if self.level <= level: + self._do_log(args) + + def debug(self, *args) -> None: + """ + Write the sequence of args, with no separators, + to the console and output files (if you've configured an output file). + Using the DEBUG level. + :param args: log the arguments + """ + self.log(*args, level=DEBUG) + + def info(self, *args) -> None: + """ + Write the sequence of args, with no separators, + to the console and output files (if you've configured an output file). + Using the INFO level. + :param args: log the arguments + """ + self.log(*args, level=INFO) + + def warn(self, *args) -> None: + """ + Write the sequence of args, with no separators, + to the console and output files (if you've configured an output file). + Using the WARN level. + :param args: log the arguments + """ + self.log(*args, level=WARN) + + def error(self, *args) -> None: + """ + Write the sequence of args, with no separators, + to the console and output files (if you've configured an output file). + Using the ERROR level. + :param args: log the arguments + """ + self.log(*args, level=ERROR) + + # Configuration + # ---------------------------------------- + def set_level(self, level: int) -> None: + """ + Set logging threshold on current logger. + :param level: the logging level (can be DEBUG=10, INFO=20, WARN=30, ERROR=40, DISABLED=50) + """ + self.level = level + + def get_dir(self) -> str: + """ + Get directory that log files are being written to. + will be None if there is no output directory (i.e., if you didn't call start) + :return: the logging directory + """ + return self.dir + + def close(self) -> None: + """ + closes the file + """ + for _format in self.output_formats: + _format.close() + + # Misc + # ---------------------------------------- + def _do_log(self, args) -> None: + """ + log to the requested format outputs + :param args: the arguments to log + """ + for _format in self.output_formats: + if isinstance(_format, SeqWriter): + _format.write_sequence(map(str, args)) + + +def configure_logger(folder: str, format_strings: List[str] = None) -> Logger: + """ + Configure the current logger. + :param folder: the save location + :param format_strings: the output logging format + :return: The logger object. + """ + assert isinstance(folder, str) + os.makedirs(folder, exist_ok=True) + + log_suffix = "" + format_strings = list(filter(None, format_strings)) + output_formats = [make_output_format(f, folder, log_suffix) for f in format_strings] + + logger = Logger(folder=folder, output_formats=output_formats) + if len(format_strings) > 0 and format_strings != ["stdout"]: + logger.log(f"Logging to {folder}") + return logger diff --git a/code_src/rise_code/sim_pipeline/utils/obs_dict_tools.py b/code_src/rise_code/sim_pipeline/utils/obs_dict_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..252d5c05bd045ba7b3f393cee8ca5922fe71debb --- /dev/null +++ b/code_src/rise_code/sim_pipeline/utils/obs_dict_tools.py @@ -0,0 +1,23 @@ +import numpy as np +from sim_pipeline.configs.env.robomimic_base import RobomimicEnvConfig + +def flatten_obs_dict(obs_dict: dict[str, np.ndarray], robot_prefix: str, env_config: RobomimicEnvConfig | None) -> np.ndarray: + if env_config is not None and hasattr(env_config, 'obs_keys'): + obs_keys: list[str] = env_config.obs_keys + for i in range(len(obs_keys)): + try: + obs_dict[obs_keys[i]] + except KeyError: + # dataset will have 'object' key, but obs returned from env will have 'object-state' + if obs_keys[i] == 'object': + obs_keys[i] = 'object-state' + elif obs_keys[i] == 'object-state': + obs_keys[i] = 'object' + else: + obs_keys[i] = f'{robot_prefix}{obs_keys[i]}' + + obs_list = [obs_dict[key] for key in obs_keys] + obs = np.concatenate(obs_list, axis=-1) + else: + obs = np.concatenate([obs_dict[f'{robot_prefix}eef_pos'], obs_dict[f'{robot_prefix}eef_quat'], obs_dict['object-state']], axis=-1) + return obs diff --git a/code_src/rise_code/sim_pipeline/utils/point_maze/point_maze_dataloader.py b/code_src/rise_code/sim_pipeline/utils/point_maze/point_maze_dataloader.py new file mode 100644 index 0000000000000000000000000000000000000000..46a071341a2c21c2176a7864f5a4fa7d993c5653 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/utils/point_maze/point_maze_dataloader.py @@ -0,0 +1,61 @@ +import h5py +import torch +from torch.utils.data import Dataset, DataLoader +import cv2 +import numpy as np + +class PointMazeDataset(Dataset): + def __init__(self, filepath): + self.file = h5py.File(filepath, 'r') + self.observations = self.file['observations'] + self.next_observations = self.file['next_observations'] + self.achieved_goals = self.file['achieved_goals'] + self.desired_goals = self.file['desired_goals'] + self.images = self.file['images'] + self.actions = self.file['actions'] + self.terminals = self.file['terminals'] + + def __len__(self): + return len(self.observations) + + def __getitem__(self, idx): + observation = torch.tensor(self.observations[idx], dtype=torch.float32) + next_observation = torch.tensor(self.next_observations[idx], dtype=torch.float32) + achieved_goal = torch.tensor(self.achieved_goals[idx], dtype=torch.float32) + desired_goal = torch.tensor(self.desired_goals[idx], dtype=torch.float32) + image = cv2.resize(self.images[idx], (160, 160), interpolation=cv2.INTER_NEAREST) + image = image.transpose(2,1,0) + image = torch.tensor(image, dtype=torch.uint8) + action = torch.tensor(self.actions[idx], dtype=torch.long) + terminal = torch.tensor(self.terminals[idx], dtype=torch.long) + + obs = torch.cat((observation, desired_goal), dim=0) + dict = {'observation': observation, 'achieved_goal': achieved_goal, 'desired_goal': desired_goal, 'obs': obs, 'image': image, 'action': action, 'next_observation': next_observation, 'terminal': terminal} + return dict + +# Example usage +if __name__ == "__main__": + maze_id = 'train_easy' + fname = 'experiments/' + maze_id + '_dataset.h5' + dataset = PointMazeDataset(fname) + dataloader = DataLoader(dataset, batch_size=64, shuffle=False) + dict = dataset[0] + observation, achieved_goal, desired_goal, image, action, obs = dict['observation'], dict['achieved_goal'], dict['desired_goal'], dict['image'], dict['action'], dict['obs'] + image = image.permute(2,1,0) + height, width, _ = image.shape + print(image.shape) + print(f"Observation: {observation.shape}, Achieved Goal: {achieved_goal.shape}, Desired Goal: {desired_goal.shape}, Image: {image.shape}, Action: {action.shape}") + + video_name = 'experiments/' + maze_id + '_dataset_video.avi' + video = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*'DIVX'), 30, (width, height)) + for i in range(len(dataset)): + obs = dataset[i] + observation, achieved_goal, desired_goal, image, action = obs['observation'], obs['achieved_goal'], obs['desired_goal'], obs['image'], obs['action'] + image = image.permute(2,1,0) + image = image.detach().numpy() + image = image[...,::-1] + video.write(image) + + print(f'Saved video to {video_name}') + video.release() + cv2.destroyAllWindows() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/utils/point_maze/point_maze_models.py b/code_src/rise_code/sim_pipeline/utils/point_maze/point_maze_models.py new file mode 100644 index 0000000000000000000000000000000000000000..02f94b400a902d874466f5ec6eb4e8b6db7fef55 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/utils/point_maze/point_maze_models.py @@ -0,0 +1,177 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.distributions as D + +from torch.optim import Adam +from torch.optim.lr_scheduler import ExponentialLR + +import numpy as np +import matplotlib.pyplot as plt + +class MLP(nn.Module): + def __init__(self, input_shape, action_dim): + super(MLP, self).__init__() + self.fc1 = nn.Linear(input_shape, 64) + self.fc2 = nn.Linear(64, 64) + self.mu = nn.Linear(64, action_dim) + self.log_std = nn.Linear(64, action_dim) + + def forward(self, x): + x = torch.relu(self.fc1(x)) + x = torch.relu(self.fc2(x)) + mu = self.mu(x) + log_std = self.log_std(x) + return mu, log_std + +class GaussianActorNetwork(nn.Module): + def __init__(self, input_shape=6, action_dim=2, fixed_std=False, init_std=0.3, mean_limits=(-1,1), std_limits=(1e-3, 1), std_activation='softplus', low_noise_eval=True): + super(GaussianActorNetwork, self).__init__() + self.net = MLP(input_shape, action_dim) + self.fixed_std = fixed_std + self.init_std = init_std + self.mean_limits = np.array(mean_limits) + self.std_limits = np.array(std_limits) + self.low_noise_eval = low_noise_eval + + def softplus_scaled(x): + out = F.softplus(x) + out - out * (self.init_std / F.softplus(torch.zeros(1).to(x.device))) + return out + + self.std_activations = { + None: lambda x: x, + 'softplus': softplus_scaled, + } + assert std_activation in self.std_activations + self.std_activation = std_activation if not self.fixed_std else None + + # with torch.no_grad(): + # for name, layer in self.net.named_children(): + # nn.init.uniform_(layer.weight, -1, 1) + # nn.init.uniform_(layer.bias, -1, 1) + + def forward_train(self, x): + mean, scale = self.net(x) + scale = scale if not self.fixed_std else torch.ones_like(scale) * self.init_std + + mean = torch.clamp(mean, min=self.mean_limits[0], max=self.mean_limits[1]) + + if self.low_noise_eval and not self.training: + scale = torch.clamp(scale, min=self.std_limits[0], max=self.std_limits[1]) + else: + scale = self.std_activations[self.std_activation](scale) + scale = torch.clamp(scale, min=self.std_limits[0], max=self.std_limits[1]) + + dists = D.Normal(loc=mean, scale=scale) + dists = D.Independent(dists, 1) + return dists + + def forward(self, obs): + dist = self.forward_train(obs) + if self.low_noise_eval and not self.training: + return dist.mean + return dist.sample() + +class GaussianCNN(nn.Module): + def __init__(self, input_shape=(3, 160, 160), action_dim=2, fixed_std=False, init_std=0.3, mean_limits=(-1,1), std_limits=(1e-3, 1), std_activation='softplus', low_noise_eval=True): + super().__init__() + feature_size = input_shape[1] + input_channels = input_shape[0] + self.conv1 = nn.Conv2d(input_channels, 32, 8, stride=4) + feature_size = (feature_size - 8) // 4 + 1 + self.conv2 = nn.Conv2d(32, 64, 4, stride=2) + feature_size = (feature_size - 4) // 2 + 1 + self.conv3 = nn.Conv2d(64, 3, 3, stride=1) + feature_size = (feature_size - 3) // 1 + 1 + self.encoding_size = 256 + + self.fc1 = nn.Linear(feature_size * feature_size * 3, self.encoding_size) + self.mu = nn.Linear(self.encoding_size, action_dim) + self.log_std = nn.Linear(self.encoding_size, action_dim) + self.fixed_std = fixed_std + self.init_std = init_std + self.mean_limits = np.array(mean_limits) + self.std_limits = np.array(std_limits) + self.low_noise_eval = low_noise_eval + + def softplus_scaled(x): + out = F.softplus(x) + out - out * (self.init_std / F.softplus(torch.zeros(1).to(x.device))) + return out + + self.std_activations = { + None: lambda x: x, + 'softplus': softplus_scaled, + } + assert std_activation in self.std_activations + self.std_activation = std_activation if not self.fixed_std else None + + # with torch.no_grad(): + # for name, layer in self.net.named_children(): + # nn.init.uniform_(layer.weight, -1, 1) + # nn.init.uniform_(layer.bias, -1, 1) + + def forward_train(self, x, return_encoding=False): + x = F.relu(self.conv1(x)) + x = F.relu(self.conv2(x)) + x = F.relu(self.conv3(x)) + x = x.view(x.size(0), -1) + x = F.relu(self.fc1(x)) + if return_encoding: + return x + mean = self.mu(x) + scale = self.log_std(x) + scale = scale if not self.fixed_std else torch.ones_like(scale) * self.init_std + + mean = torch.clamp(mean, min=self.mean_limits[0], max=self.mean_limits[1]) + + if self.low_noise_eval and not self.training: + scale = torch.clamp(scale, min=self.std_limits[0], max=self.std_limits[1]) + else: + scale = self.std_activations[self.std_activation](scale) + scale = torch.clamp(scale, min=self.std_limits[0], max=self.std_limits[1]) + + dists = D.Normal(loc=mean, scale=scale) + dists = D.Independent(dists, 1) + return dists + + def forward(self, obs): + dist = self.forward_train(obs) + if self.low_noise_eval and not self.training: + return dist.mean + return dist.sample() + +class BC_Gaussian(nn.Module): + def __init__(self, images=False, input_shape=6, action_dim=2, fixed_std=False, init_std=0.3, mean_limits=(-1,1), std_limits=(1e-3, 1), std_activation='softplus', low_noise_eval=True): + super(BC_Gaussian, self).__init__() + if images: + self.actor = GaussianCNN(input_shape, action_dim, fixed_std, init_std, mean_limits, std_limits, std_activation, low_noise_eval) + else: + self.actor = GaussianActorNetwork(input_shape, action_dim, fixed_std, init_std, mean_limits, std_limits, std_activation, low_noise_eval) + self.optimizer = Adam(self.actor.parameters(), lr=1e-3) + self.scheduler = ExponentialLR(self.optimizer, gamma=0.98) + + def forward_step(self, batch): + dist = self.actor.forward_train(batch["obs"]) + log_probs = dist.log_prob(batch["action"]) + # with torch.no_grad(): + # for name, layer in self.net.named_children(): + # nn.init.uniform_(layer.weight, -1, 1) + # nn.init.uniform_(layer.bias, -1, 1) + + return log_probs + + def train_step(self, obs, action): + self.optimizer.zero_grad() + log_probs = self.forward_step({"obs": obs, "action": action}) + loss = -log_probs.mean() + loss.backward() + self.optimizer.step() + return loss.item() + + def forward(self, obs): + return self.actor.forward(obs) + + def return_encoding(self, obs): + return self.actor.forward_train(obs, return_encoding=True) \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/utils/rollout_utils.py b/code_src/rise_code/sim_pipeline/utils/rollout_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ace12ea0b4ead27ce919fced35df43b7079fd7d7 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/utils/rollout_utils.py @@ -0,0 +1,148 @@ +import h5py +import cv2 +import numpy as np + +from collections import deque + +from sim_pipeline.eval.rollout_env import PossibleVecEnv + + +def _render_frame(env: PossibleVecEnv, render_mode: str, log_video: bool, default_camera_height: int, video_writers: list[cv2.VideoWriter] | None, dims: tuple[int, int] | None = None) -> np.ndarray: + if render_mode == 'human' and env.is_vec_env: + raise ValueError("Cannot render human mode for vectorized environments") + # for robomimic: frame is (w, h, c), 0-255 + # for sb3 VecEnv: frame is (w * num_envs, h, c) + # for gym VectorEnv, frame is (num_envs, w, h, c), where outer dim is list + if env.is_sb_vec_env or dims is None: + frame: np.ndarray[np.uint8] = env.render(mode=render_mode) + else: + frame = env.render(mode=render_mode, height=dims[0], width=dims[1]) + if render_mode == 'rgb_array' and log_video: + # each frame has shape (num_envs, w, h, c) + height = default_camera_height if dims is None else dims[0] + if env.is_gym_vec_env: + frame = np.array(frame) + elif env.is_sb_vec_env: + frame = np.array(np.split(frame, frame.shape[0] // height)) + else: + frame = np.array([frame]) + + if video_writers is not None: + num_envs = env.num_envs if env.is_vec_env else 1 + for i in range(num_envs): + video_frame = frame[i] + video_writer = video_writers[i] + video_frame = cv2.cvtColor(video_frame, cv2.COLOR_RGB2BGR) + video_writer.write(video_frame) + return frame + + +def add_trajectory_to_dataset( + ep_number: int, + trajectory: dict[str, list[np.ndarray | float | bool] | list[list[np.ndarray | float | bool]]], + dataset_file: h5py.File, + ) -> tuple[int, int]: + + ep_number_after = ep_number + 1 + added_samples = 0 + + data_grp = dataset_file['data'] + + if isinstance(trajectory['states'][0], list): + for i in range(len(trajectory['states'])): + ep_data_grp = data_grp.create_group(f"demo_{ep_number + i}") + + ep_data_grp.create_dataset('states', data=np.array(trajectory['states'][i])) + ep_data_grp.create_dataset('actions', data=np.array(trajectory['actions'][i])) + ep_data_grp.create_dataset('rewards', data=np.array(trajectory['rewards'][i])) + ep_data_grp.create_dataset('dones', data=np.array(trajectory['dones'][i])) + + ep_data_grp.attrs['num_samples'] = len(trajectory['actions'][i]) + ep_number_after = ep_number + i + 1 + added_samples += len(trajectory['actions'][i]) + else: + ep_data_grp = data_grp.create_group(f"demo_{ep_number}") + ep_data_grp.create_dataset('states', data=np.array(trajectory['states'])) + ep_data_grp.create_dataset('actions', data=np.array(trajectory['actions'])) + ep_data_grp.create_dataset('rewards', data=np.array(trajectory['rewards'])) + ep_data_grp.create_dataset('dones', data=np.array(trajectory['dones'])) + + if 'model' in trajectory['initial_state_dict']: + ep_data_grp.attrs['model_file'] = trajectory['initial_state_dict']['model'] + + n_samples = len(trajectory['actions']) + ep_data_grp.attrs['num_samples'] = n_samples + added_samples += n_samples + + return ep_number_after, added_samples + + +def add_batch_dim(obs: np.ndarray | dict[str, np.ndarray]) -> np.ndarray | dict[str, np.ndarray]: + if isinstance(obs, dict): + return {key: np.expand_dims(val, 0) for key, val in obs.items()} + return np.expand_dims(obs, 0) + + +def _get_and_pad_n_obs(all_obs: list[np.ndarray], n_obs_steps: int) -> np.ndarray: + result = np.zeros((n_obs_steps,) + all_obs[-1].shape, dtype=all_obs[-1].dtype) + + start_idx = -min(n_obs_steps, len(all_obs)) + result[start_idx:] = np.array(all_obs[start_idx:]) + + # if all_obs is not long enough to fill result + if n_obs_steps > len(all_obs): + # pad with the earliest observation + result[:start_idx] = result[start_idx] + + result = np.swapaxes(result, 0, 1) + return result + + +def stack_last_n_obs(all_obs: deque[np.ndarray | dict[str, np.ndarray]], n_obs_steps: int) -> np.ndarray | dict[str, np.ndarray]: + """ + assuming diffusion, each obs has shape (n_envs, d) + + need to stack the last n_obs_steps observations in middle dim, so we output shape (n_envs, n_obs_steps, d) + """ + if len(all_obs) == 0: + raise ValueError("observation history is empty") + + all_obs = list(all_obs) + + if isinstance(all_obs[0], dict): + keys = all_obs[0].keys() + return {key: _get_and_pad_n_obs([obs[key] for obs in all_obs], n_obs_steps) for key in keys} + + return _get_and_pad_n_obs(all_obs, n_obs_steps) + + +def filter_obs_keys(obs: dict[str, np.ndarray] | np.ndarray, obs_keys: list[str] | None) -> dict[str, np.ndarray] | np.ndarray: + if isinstance(obs, dict) and obs_keys is not None: + return {key: obs[key] for key in obs_keys} + return obs + + +def merge_obs_specs(obs_specs: list[dict[str, list[str]]]): + """Recursively merge Robomimic obs specs, concatenating values with the same keys. + + Args: + obs_specs (list[dict[str, list[str]]]): list of obs specs to merge + """ + + def merge_recursive(d1, d2): + for key, value in d2.items(): + if isinstance(value, dict): + d1[key] = merge_recursive(d1.get(key, {}), value) + elif isinstance(value, list): + if key in d1: + d1[key] = list(set(d1[key] + value)) + else: + d1[key] = value + else: + raise ValueError(f"Unexpected value type {type(value)} in dict {d2}") + return d1 + + result = {} + for d in obs_specs: + result = merge_recursive(result, d) + return result diff --git a/code_src/rise_code/sim_pipeline/utils/shape_meta.py b/code_src/rise_code/sim_pipeline/utils/shape_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..e80a0d79eddec1531cf9185a46f23d31c1b01e87 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/utils/shape_meta.py @@ -0,0 +1,54 @@ +import h5py +from omegaconf import DictConfig + +def get_shape_meta(dataset_path: str, all_obs_keys: set[str]) -> tuple[dict[str, tuple[int]], tuple[int]]: + with h5py.File(dataset_path, 'r') as f: + data = f['data'] + for ep_key in data.keys(): + ep = data[ep_key] + break + + obs = ep['obs'] + action_shape = tuple(ep['actions'].shape)[1:] + + obs_shape_meta = {} + for key in all_obs_keys: + obs_shape_meta[key] = tuple(obs[key].shape)[1:] + + return obs_shape_meta, action_shape + + +def update_diffusion_cfg_with_shape_meta( + shape_meta_cfg: DictConfig, + obs_shape_meta: dict[str, tuple[int]], + action_shape_meta: tuple[int], + rgb_keys: list[str], + lowdim_keys: list[str], + depth_keys: list[str] +): + shape_meta_cfg.action.shape = action_shape_meta + + def get_type(key: str) -> str: + if key in rgb_keys: + return 'rgb' + if key in lowdim_keys: + return 'low_dim' + if key in depth_keys: + return 'depth' + raise ValueError(f"Unknown key {key}") + + del shape_meta_cfg.obs + shape_meta_cfg.obs = {} + + shape_dict = {} + for key, shape in obs_shape_meta.items(): + # format must be c, h, w + if get_type(key) == 'rgb': + shape = (shape[2], shape[0], shape[1]) + shape_dict[key] = { + 'shape': shape, + 'type': get_type(key) + } + + shape_meta_cfg.obs = shape_dict + \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/utils/train_utils.py b/code_src/rise_code/sim_pipeline/utils/train_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..99358398cc835b4134a272937be61a0f0e056b4a --- /dev/null +++ b/code_src/rise_code/sim_pipeline/utils/train_utils.py @@ -0,0 +1,145 @@ +import os +import re +from pathlib import Path + +def get_latest_sb_policy(logdir: Path, find_epoch=False) -> str | int: + """ + Get the latest sb3 policy checkpoint from a logdir. + """ + if not logdir.exists(): + raise ValueError(f'The path {logdir} does not exist') + policy_files = list(logdir.glob('*.zip')) + if 'policy.zip' in [file.name for file in policy_files]: + latest = logdir / 'policy.zip' + else: + latest = None + if not find_epoch and latest is not None: + return latest + + pattern = re.compile('(\d+).zip') + + largest_epoch = -1 + largest_policy = None + for filename in policy_files: + match = pattern.match(filename.name) + if match is not None: + epoch = int(match.groups()[0]) + if epoch > largest_epoch: + largest_epoch = epoch + largest_policy = filename + + if largest_policy is None: + raise ValueError(f'No policy found in {logdir}') + if find_epoch: + return largest_epoch + if latest is not None: + return latest + return largest_policy + +def get_latest_robomimic_policy(logdir: Path, find_epoch=False) -> str | int: + """ + Get the latest robomimic policy checkpoint from a logdir. + """ + if not logdir.exists(): + raise ValueError(f'The path {logdir} does not exist') + policy_files = list(logdir.glob('*.pth')) + pattern = re.compile('.*model_epoch_(\d+).*\.pth') + + largest_epoch = -1 + largest_policy = None + for filename in policy_files: + match = pattern.match(filename.name) + if match is not None: + epoch = int(match.groups()[0]) + if epoch > largest_epoch: + largest_epoch = epoch + largest_policy = filename + + if largest_policy is None: + raise ValueError(f'No policy found in {logdir}') + if find_epoch: + return largest_epoch + return largest_policy + +def get_latest_diffusion_policy(logdir: Path, find_epoch=False) -> str | int: + """ + Get the latest diffusion policy checkpoint from a logdir. + """ + if not logdir.exists(): + raise ValueError(f'The path {logdir} does not exist') + policy_files = list(logdir.glob('*.ckpt')) + if 'latest.ckpt' in [file.name for file in policy_files]: + latest = logdir / 'latest.ckpt' + else: + latest = None + if not find_epoch and latest is not None: + return latest + pattern = re.compile('.*epoch=(\d+).*\.ckpt') + + largest_epoch = -1 + largest_policy = None + for filename in policy_files: + match = pattern.match(filename.name) + if match is not None: + epoch = int(match.groups()[0]) + if epoch > largest_epoch: + largest_epoch = epoch + largest_policy = filename + + if largest_policy is None: + raise ValueError(f'No policy found in {logdir}') + if find_epoch: + return largest_epoch + if latest is not None: + return latest + return largest_policy + +def get_latest_q_transformer_policy(logdir: Path, find_epoch=False) -> str | int: + """ + Get the latest qtransformer policy checkpoint from a logdir. + """ + if not logdir.exists(): + raise ValueError(f'The path {logdir} does not exist') + policy_files = list(logdir.glob('*.pt')) + pattern = re.compile('.*checkpoint-(\d+).*\.pt') + + largest_epoch = -1 + largest_policy = None + for filename in policy_files: + match = pattern.match(filename.name) + if match is not None: + epoch = int(match.groups()[0]) + if epoch > largest_epoch: + largest_epoch = epoch + largest_policy = filename + + if largest_policy is None: + raise ValueError(f'No policy found in {logdir}') + if find_epoch: + return largest_epoch + return largest_policy + +def get_latest_ogbench_policy(logdir: Path, find_epoch=False) -> str | int: + """ + Get the latest ogbench policy checkpoint from a logdir. + """ + if not logdir.exists(): + raise ValueError(f'The path {logdir} does not exist') + policy_files = list(logdir.glob('*.pkl')) + pattern = re.compile('.*params_(\d+).*\.pkl') + + largest_epoch = -1 + largest_policy = None + for filename in policy_files: + match = pattern.match(filename.name) + if match is not None: + epoch = int(match.groups()[0]) + if epoch > largest_epoch: + largest_epoch = epoch + largest_policy = filename + + if largest_policy is None: + raise ValueError(f'No policy found in {logdir}') + if find_epoch: + return largest_epoch + return largest_policy \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/utils/video_writer.py b/code_src/rise_code/sim_pipeline/utils/video_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..809370aa78d55f07648366b6c686438607c0ee82 --- /dev/null +++ b/code_src/rise_code/sim_pipeline/utils/video_writer.py @@ -0,0 +1,11 @@ +import cv2 +from contextlib import contextmanager + +@contextmanager +def video_writer_manager(video_writers: list[cv2.VideoWriter] | None): + try: + yield video_writers + finally: + if video_writers is not None: + for video_writer in video_writers: + video_writer.release() \ No newline at end of file diff --git a/code_src/rise_code/sim_pipeline/viz/dataset_visualization.py b/code_src/rise_code/sim_pipeline/viz/dataset_visualization.py new file mode 100644 index 0000000000000000000000000000000000000000..50821eda344ce35718e5522301d429b9e46f568f --- /dev/null +++ b/code_src/rise_code/sim_pipeline/viz/dataset_visualization.py @@ -0,0 +1,167 @@ +import h5py +import robomimic.utils.obs_utils as ObsUtils +import robomimic.utils.env_utils as EnvUtils +import robomimic.utils.file_utils as FileUtils + +import numpy as np + +import matplotlib.pyplot as plt +from matplotlib.colors import LogNorm +from mpl_toolkits.mplot3d import Axes3D +from matplotlib.colors import LinearSegmentedColormap +import plotly.graph_objects as go +import plotly.io as pio + +def load_dataset(dataset_name_with_full_path): + + # Not sure why, but you have to initialize the ObsUtils with a "fake" observation spec. + # Note, we don't actually perform the "regenerate observations from dataset" routine + # So we are sticking with the observations that are already in the dataset, rather than generating new ones + dummy_spec = dict( + obs=dict( + low_dim=["robot0_eef_pos"], + rgb=[], + ), + ) + ObsUtils.initialize_obs_utils_with_obs_specs(obs_modality_specs=dummy_spec) + dataset = h5py.File(dataset_name_with_full_path, "r") + + env_meta = FileUtils.get_env_metadata_from_dataset(dataset_name_with_full_path) + env = EnvUtils.create_env_from_metadata( + env_meta=env_meta, + render=True, + render_offscreen=False, + use_image_obs=False, + ) + + # == Get some information about what's inside the dataset === + + # print the environment meta data + print("\n===Environment Metadata===\n") + print(env_meta) + + # reorder and print the list of individual trajectory demonstrations + print("\n===Demos List===\n") + demos = list(dataset["data"].keys()) + idxs = np.argsort([int(elem[5:]) for elem in demos]) + demo_idxs = [demos[i] for i in idxs] + print(demo_idxs) + + + # Remind yourself what observations are available + print("\n===Available Observations:===\n") + print(dataset['data']["demo_0"]['obs'].keys()) + + + # Returns a constructed env, the meta_data for the env, a list of demo names in order, and the full dataset + return env, env_meta, demo_idxs, dataset + +def visualize_eepos_trajectories_iteratively(dataset, demo_idxs): + for demo_idx in demo_idxs: + ee_positions = dataset['data'][demo_idx]['obs']['robot0_eef_pos'] + + fig = plt.figure() + ax = fig.add_subplot(111, projection='3d') + ax.scatter3D(ee_positions[:,0], ee_positions[:,1], ee_positions[:,2], label='End Effector Trajectory') + plt.show() + +def visualize_objectpos_trajectories_iteratively(dataset, demo_idxs): + for demo_idx in demo_idxs: + # Note, the 14 dimensional object obs vector is: [world pos, world quat, ee_frame_pos, ee_frame_quat] + object_positions = dataset['data'][demo_idx]['obs']['object'][:,:3] # first 3 are world pos + + fig = plt.figure() + ax = fig.add_subplot(111, projection='3d') + ax.scatter3D(object_positions[:,0], object_positions[:,1], object_positions[:,2], label='Object Trajectory') + plt.show() + +def visualize_plotly_objectpos_trajectories_iteratively(dataset, demo_idxs): + fig = go.Figure() + + for demo_idx in demo_idxs: + # Note, the 14 dimensional object obs vector is: [world pos, world quat, ee_frame_pos, ee_frame_quat] + object_positions = dataset['data'][demo_idx]['obs']['object'][:,:3] # first 3 are world pos + fig.data = [] # Clear the existing data + fig.add_trace(go.Scatter3d( + x=object_positions[:,0], + y=object_positions[:,1], + z=object_positions[:,2], + mode='markers+lines', + marker=dict( + size=5, + color=np.arange(len(object_positions)), + colorscale='Viridis', # Choose a colorscale + opacity=0.8 + ), + hovertext=np.arange(len(object_positions)), + )) + + # Update layout details + fig.update_layout( + title=f'{demo_idx} object traj', + scene=dict( + xaxis_title='X', + yaxis_title='Y', + zaxis_title='Z' + ) + ) + + # Display the figure + pio.show(fig) + input('press enter for next') + +def visualize_eepos_trajectories_overlayed(dataset, demo_idxs, demo_idx_range=(0,10)): + fig = plt.figure() + ax = fig.add_subplot(111, projection='3d') + + for i in range(*demo_idx_range): + traj = dataset['data'][demo_idxs[i]]['obs']['robot0_eef_pos'] + + #cmap_rbg = LinearSegmentedColormap.from_list('rbg_grad', [(1,0,0), (0,0,1), (0,1,0)] , N=len(traj)) + #orp = [tuple((1/256)*e for e in t) for t in [(121,0,178), (255,0,71), (255,95,19)]] + #cmap_orp = LinearSegmentedColormap.from_list('orp_grad', orp , N=len(traj)) + + colormap_dict = { + 0: 'Blues', + 1: 'BuGn', + 2: 'BuPu', + 3: 'GnBu', + 4: 'Greens', + 5: 'Greys', + 6: 'Oranges', + 7: 'OrRd', + 8: 'PuBu', + 9: 'PuBuGn', + 10: 'PuRd', + 11: 'Purples', + 12: 'RdPu', + 13: 'Reds', + 14: 'YlGn', + 15: 'YlGnBu', + 16: 'YlOrBr', + 17: 'YlOrRd' + } + + # Use modulo operation to ensure the index is within the bounds of the colormap_dict + cmap_selected = colormap_dict.get(i % len(colormap_dict), 'viridis') + + ax.scatter3D(traj[:,0],traj[:,1],traj[:,2], c=np.arange(len(traj)), cmap=cmap_selected) + + plt.show() + +def run(): + #dataset_name = "/home/share_act/WRK/robomimic/datasets/square/ph/low_dim_v141.hdf5" + dataset_name = "/home/kevin/ood/sim_pipeline/sim_pipeline/data/combined/push_manual_combined_tl_rew.hdf5" + env, env_meta, demo_idxs, dataset = load_dataset(dataset_name) + + # Step the Env once, just for fun + test_action = np.zeros(env.action_dimension) + env.step(test_action) + + #flattened_dataset = np.concatenate([v['obs']['robot0_eef_pos'][()] for v in dataset['data'].values()]) + + #visualize_plotly_objectpos_trajectories_iteratively(dataset, demo_idxs) + visualize_eepos_trajectories_overlayed(dataset, demo_idxs, (0,10)) + +if __name__ == "__main__": + run() \ No newline at end of file diff --git a/code_src/rise_robomimic/README.md b/code_src/rise_robomimic/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bdc3556ff9439556f124d83502669aba42d621b0 --- /dev/null +++ b/code_src/rise_robomimic/README.md @@ -0,0 +1,90 @@ +# robomimic + +

+ + + + + + + + +

+ +[**[Homepage]**](https://robomimic.github.io/)   [**[Documentation]**](https://robomimic.github.io/docs/introduction/overview.html)   [**[Study Paper]**](https://arxiv.org/abs/2108.03298)   [**[Study Website]**](https://robomimic.github.io/study/)   [**[ARISE Initiative]**](https://github.com/ARISE-Initiative) + +------- +## Latest Updates +- [10/11/2023] **v0.3.1**: support for extracting, training on, and visualizing depth observations for robosuite datasets +- [07/03/2023] **v0.3.0**: BC-Transformer and IQL :brain:, support for DeepMind MuJoCo bindings :robot:, pre-trained image reps :eye:, wandb logging :chart_with_upwards_trend:, and more +- [05/23/2022] **v0.2.1**: Updated website and documentation to feature more tutorials :notebook_with_decorative_cover: +- [12/16/2021] **v0.2.0**: Modular observation modalities and encoders :wrench:, support for [MOMART](https://sites.google.com/view/il-for-mm/home) datasets :open_file_folder: [[release notes]](https://github.com/ARISE-Initiative/robomimic/releases/tag/v0.2.0) [[documentation]](https://robomimic.github.io/docs/v0.2/introduction/overview.html) +- [08/09/2021] **v0.1.0**: Initial code and paper release + +------- + +## Colab quickstart +Get started with a quick colab notebook demo of robomimic without installing anything locally. + +[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1b62r_km9pP40fKF0cBdpdTO2P_2eIbC6?usp=sharing) + + +------- + +**robomimic** is a framework for robot learning from demonstration. +It offers a broad set of demonstration datasets collected on robot manipulation domains and offline learning algorithms to learn from these datasets. +**robomimic** aims to make robot learning broadly *accessible* and *reproducible*, allowing researchers and practitioners to benchmark tasks and algorithms fairly and to develop the next generation of robot learning algorithms. + +## Core Features + +

+ +

+ + + + +## Reproducing benchmarks + +The robomimic framework also makes reproducing the results from different benchmarks and datasets easy. See the [datasets page](https://robomimic.github.io/docs/datasets/overview.html) for more information on downloading datasets and reproducing experiments. + +## Troubleshooting + +Please see the [troubleshooting](https://robomimic.github.io/docs/miscellaneous/troubleshooting.html) section for common fixes, or [submit an issue](https://github.com/ARISE-Initiative/robomimic/issues) on our github page. + +## Contributing to robomimic +This project is part of the broader [Advancing Robot Intelligence through Simulated Environments (ARISE) Initiative](https://github.com/ARISE-Initiative), with the aim of lowering the barriers of entry for cutting-edge research at the intersection of AI and Robotics. +The project originally began development in late 2018 by researchers in the [Stanford Vision and Learning Lab](http://svl.stanford.edu/) (SVL). +Now it is actively maintained and used for robotics research projects across multiple labs. +We welcome community contributions to this project. +For details please check our [contributing guidelines](https://robomimic.github.io/docs/miscellaneous/contributing.html). + +## Citation + +Please cite [this paper](https://arxiv.org/abs/2108.03298) if you use this framework in your work: + +```bibtex +@inproceedings{robomimic2021, + title={What Matters in Learning from Offline Human Demonstrations for Robot Manipulation}, + author={Ajay Mandlekar and Danfei Xu and Josiah Wong and Soroush Nasiriany and Chen Wang and Rohun Kulkarni and Li Fei-Fei and Silvio Savarese and Yuke Zhu and Roberto Mart\'{i}n-Mart\'{i}n}, + booktitle={Conference on Robot Learning (CoRL)}, + year={2021} +} +``` diff --git a/code_src/rise_robomimic/docs/conf.py b/code_src/rise_robomimic/docs/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..59eff96808884ccc986f88c7050d164c4de31cad --- /dev/null +++ b/code_src/rise_robomimic/docs/conf.py @@ -0,0 +1,173 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. + +import os +import sys +sys.path.insert(0, os.path.abspath('.')) + +import sphinx_book_theme +import robomimic + + +# -- General configuration --------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.napoleon', + 'sphinx_markdown_tables', + 'sphinx.ext.mathjax', + 'sphinx.ext.githubpages', + 'sphinx.ext.autodoc', + 'recommonmark', # use Sphinx-1.4 or newer + 'nbsphinx', +] + + +# Sphinx-apidoc variables +apidoc_module_dir = "../robomimic" +apidoc_output_dir = "reference" + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# source_parsers = { +# '.md': CommonMarkParser, +# } + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = ['.rst', '.md', '.ipynb'] + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'robomimic' +copyright = 'the robomimic core team, 2023' +author = 'the robomimic core team' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = (".").join(robomimic.__version__.split(".")[:-1]) +# The full version, including alpha/beta/rc tags. +release = (".").join(robomimic.__version__.split(".")[:-1]) + + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'sphinx_book_theme' +html_logo = "robomimic_logo.png" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# html_context = { +# 'css_files': [ +# '_static/theme_overrides.css', # override wide tables in RTD theme +# ], +# } + +# -- Options for HTMLHelp output ------------------------------------------ + +# Output file base name for HTML help builder. +htmlhelp_basename = 'robomimicdoc' + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'robomimic.tex', u'robomimic Documentation', author, 'manual'), +] + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'robomimic', u'robomimic Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'robomimic', u'robomimic Documentation', + author, 'robomimic', 'ARISE', + 'Miscellaneous'), +] diff --git a/code_src/rise_robomimic/docs/datasets/d4rl.md b/code_src/rise_robomimic/docs/datasets/d4rl.md new file mode 100644 index 0000000000000000000000000000000000000000..9e7165f588eef41f7594a01736779bc6d51411ab --- /dev/null +++ b/code_src/rise_robomimic/docs/datasets/d4rl.md @@ -0,0 +1,55 @@ +# D4RL + +## Overview +The [D4RL](https://arxiv.org/abs/2004.07219) benchmark provides a set of locomotion tasks and demonstration datasets. + +## Downloading + +Use `convert_d4rl.py` in the `scripts/conversion` folder to automatically download and postprocess the D4RL dataset in a single step. For example: + +```sh +# by default, download to robomimic/datasets +$ python convert_d4rl.py --env walker2d-medium-expert-v2 +# download to specific folder +$ python convert_d4rl.py --env walker2d-medium-expert-v2 --folder /path/to/output/folder/ +``` + +- `--env` specifies the dataset to download +- `--folder` specifies where you want to download the dataset. If no folder is provided, the `datasets` folder at the top-level of the repository will be used. + +The script will download the raw hdf5 dataset to `--folder`, and the converted one that is compatible with this repository into the `converted` subfolder. + +## Postprocessing + +No postprocessing is required, assuming the above script is run! + +## D4RL Results + +Below, we provide a table of results on common D4RL datasets using the algorithms included in the released codebase. We follow the convention in the TD3-BC paper, where we average results over the final 10 rollout evaluations, but we use 50 rollouts instead of 10 for each evaluation. All results are reported on the `-v2` environment variants. Apart from a small handful of the halfcheetah results, the results align with those presented in the [TD3_BC paper](https://arxiv.org/abs/2106.06860). We suspect the halfcheetah results are different because we used `mujoco-py` version `2.1.2.14` in our evaluations, as opposed to `1.5` in order to be consistent with the version we were using for robosuite datasets. The results below were generated with `gym` version `0.24.1` and this `d4rl` [commit](https://github.com/Farama-Foundation/D4RL/tree/305676ebb2e26582d50c6518c8df39fd52dea587). + +| | **BCQ** | **CQL** | **TD3-BC** | **IQL** | +| ----------------------------- | ------------- | ------------- | ------------- | ------------- | +| **HalfCheetah-Medium** | 46.8% (5535) | 46.7% (5516) | 47.9% (5664) | 45.6% (5379) | +| **Hopper-Medium** | 63.9% (2059) | 59.2% (1908) | 61.0% (1965) | 53.7% (1729) | +| **Walker2d-Medium** | 74.6% (3426) | 79.7% (3659) | 82.9% (3806) | 77.0% (3537) | +| **HalfCheetah-Medium-Expert** | 89.9% (10875) | 77.6% (9358) | 92.1% (11154) | 89.0% (10773) | +| **Hopper-Medium-Expert** | 79.5% (2566) | 62.9% (2027) | 89.7% (2900) | 110.1% (3564) | +| **Walker2d-Medium-Expert** | 98.7% (4535) | 109.0% (5007) | 111.1% (5103) | 109.7% (5037) | +| **HalfCheetah-Expert** | 92.9% (11249) | 67.7% (8126) | 94.6% (11469) | 93.3% (11304) | +| **Hopper-Expert** | 92.3% (2984) | 104.2% (3370) | 108.5% (3512) | 110.5% (3577) | +| **Walker2d-Expert** | 108.6% (4987) | 108.5% (4983) | 110.3% (5066) | 109.1% (5008) | + + +### Reproducing D4RL Results + +In order to reproduce the results above, first make sure that the `generate_paper_configs.py` script has been run, where the `--dataset_dir` argument is consistent with the folder where the D4RL datasets were downloaded using the `convert_d4rl.py` script. This is also the first step for reproducing results on the released robot manipulation datasets. The `--config_dir` directory used in the script (`robomimic/exps/paper` by default) will contain a `d4rl.sh` script, and a `d4rl` subdirectory that contains all the json configs. The table results above can be generated simply by running the training commands in the shell script. + +## Citation +```sh +@article{fu2020d4rl, + title={D4rl: Datasets for deep data-driven reinforcement learning}, + author={Fu, Justin and Kumar, Aviral and Nachum, Ofir and Tucker, George and Levine, Sergey}, + journal={arXiv preprint arXiv:2004.07219}, + year={2020} +} +``` diff --git a/code_src/rise_robomimic/docs/datasets/mimicgen.md b/code_src/rise_robomimic/docs/datasets/mimicgen.md new file mode 100644 index 0000000000000000000000000000000000000000..3c47d2b795a0622bd286de1adc9bcd5eea66650d --- /dev/null +++ b/code_src/rise_robomimic/docs/datasets/mimicgen.md @@ -0,0 +1,37 @@ +# MimicGen (CoRL 2023) + +## Overview + +The [MimicGen paper](https://arxiv.org/abs/2310.17596) released a large collection of task demonstrations across several different environments. + +The datasets contain over 48,000 task demonstrations across 12 tasks, grouped into the following categories: +- **source**: 120 human demonstrations across 12 tasks used to automatically generate the other datasets +- **core**: 26,000 task demonstrations across 12 tasks (26 task variants) +- **object**: 2000 task demonstrations on the Mug Cleanup task with different mugs +- **robot**: 16,000 task demonstrations across 4 different robot arms on 2 tasks (4 task variants) +- **large_interpolation**: 6000 task demonstrations across 6 tasks that pose significant challenges for modern imitation learning methods + +See [this link](https://github.com/NVlabs/mimicgen_environments#dataset-types) for more information on the datasets. + +

+ +

+ +## Downloading + +Please see [this link](https://github.com/NVlabs/mimicgen_environments#downloading-and-using-datasets) for instructions on downloading and using these datasets. + +## Postprocessing + +No postprocessing is needed for these datasets. + +## Citation + +```bibtex +@inproceedings{mandlekar2023mimicgen, + title={MimicGen: A Data Generation System for Scalable Robot Learning using Human Demonstrations}, + author={Mandlekar, Ajay and Nasiriany, Soroush and Wen, Bowen and Akinola, Iretiayo and Narang, Yashraj and Fan, Linxi and Zhu, Yuke and Fox, Dieter}, + booktitle={7th Annual Conference on Robot Learning}, + year={2023} +} +``` \ No newline at end of file diff --git a/code_src/rise_robomimic/docs/datasets/momart.md b/code_src/rise_robomimic/docs/datasets/momart.md new file mode 100644 index 0000000000000000000000000000000000000000..b76195a153588eba28693ed3a2fd76af1d915e24 --- /dev/null +++ b/code_src/rise_robomimic/docs/datasets/momart.md @@ -0,0 +1,57 @@ +# MOMART Datasets and Experiments + +## Overview +[Mobile Manipulation RoboTurk (MoMaRT)](https://sites.google.com/view/il-for-mm/home) datasets are a collection of demonstrations collected on 5 long-horizon robot mobile manipulation tasks in a realistic simulated kitchen. + +

+ + + + + + + + + + +

+ +## Downloading + + +
+

Warning!

+ +When working with these datasets, please make sure that you have installed [iGibson](http://svl.stanford.edu/igibson/) from source and are on the `momart` branch. Exact steps for installing can be found [HERE](https://sites.google.com/view/il-for-mm/datasets#h.qw0vufk0hknk). + +
+ +We provide two ways for downloading MOMART datasets: + +### Method 1: Using `download_momart_datasets.py` (Recommended) +`download_momart_datasets.py` is a python script that provides a programmatic way of installing all datasets. This is the preferred method, because this script also sets up a directory structure for the datasets that works out of the box with examples for reproducing [MOMART paper's](https://arxiv.org/abs/2112.05251) results. + +```sh +# Use --help flag to view download and options +python /robomimic/scripts/download_momart_datasets.py +``` + +### Method 2: Using Direct Download Links + +For each type of dataset, we also provide a direct download links that will download the raw HDF5 file [HERE](https://sites.google.com/view/il-for-mm/datasets#h.ko0ilbky4y5u). + +## Postprocessing + +No postprocessing is needed for these datasets! + +## Citation +```sh +@inproceedings{wong2022error, + title={Error-Aware Imitation Learning from Teleoperation Data for Mobile Manipulation}, + author={Wong, Josiah and Tung, Albert and Kurenkov, Andrey and Mandlekar, Ajay and Fei-Fei, Li and Savarese, Silvio and Mart{\'\i}n-Mart{\'\i}n, Roberto}, + booktitle={Conference on Robot Learning}, + pages={1367--1378}, + year={2022}, + organization={PMLR} +} +``` \ No newline at end of file diff --git a/code_src/rise_robomimic/docs/datasets/overview.md b/code_src/rise_robomimic/docs/datasets/overview.md new file mode 100644 index 0000000000000000000000000000000000000000..2bf39b92c864b172f31b380a52b171848335fedb --- /dev/null +++ b/code_src/rise_robomimic/docs/datasets/overview.md @@ -0,0 +1,165 @@ +# Overview + +## Dataset Pipeline + + + +Datasets capture recorded environment data and are used as inputs to a given offline RL or IL algorithm in **robomimic**. In general, you can use datasets with **robomimic** by: + +1. **Downloading** the desired dataset +2. **Postprocessing** the dataset to guarantee compatibility with robomimic +3. **Training** agent(s) in robomimic with dataset + +**robomimic** currently supports the following datasets out of the box. Click on the corresponding **(1) Downloading** link to download the dataset and the corresponding **(2) Postprocessing** link for postprocessing that dataset. + + +| **Dataset** |
**Task Types**
| **Downloading** | **Postprocessing** | +| ----------------------------- | :-------------: | :-------------: | :-------------: | +| [**robomimic v0.1**](robomimic_v0.1.html)| Sim + Real Robot Manipulation | [Link](robomimic_v0.1.html#downloading) | [Link](robomimic_v0.1.html#postprocessing) | +| [**MimicGen**](mimicgen.html) | Sim Robot Manipulation | [Link](mimicgen.html#downloading) | [Link](mimicgen.html#postprocessing) | +| [**D4RL**](d4rl.html) | Sim Locomotion | [Link](d4rl.html#downloading) | [Link](d4rl.html#postprocessing) | +| [**MOMART**](momart.html) | Sim Mobile Manipulation | [Link](momart.html#downloading) | [Link](momart.html#postprocessing) | +| [**RoboTurk Pilot**](roboturk_pilot.html) | Sim Robot Manipulation | [Link](roboturk_pilot.html#downloading) | [Link](roboturk_pilot.html#postprocessing) | + + +After downloading and postprocessing, **(3) Training** with the dataset is straightforward and unified across all datasets: + +```sh +python train.py --dataset --config +``` + +## Generating Your Own Dataset + +**robomimic** provides tutorials for collecting custom datasets for specific environment platforms. Click on any of the links below for more information for the specific environment setup: + +| **Environment Platform** | **Task Types** | +| ----------------------------- | :---------------------: | +| [**robosuite**](robosuite.html)| Robot Manipulation | + +
+

Create Your Own Environment Wrapper!

+ +If you want to generate your own dataset in a custom environment platform that is not listed above, please see [this page](../modules/environments.md#implement-an-environment-wrapper). + +
+ + +## Dataset Structure + +All postprocessed **robomimic** compatible datasets share the same data structure. A single dataset is a single HDF5 file with the following structure: + +
+ HDF5 Structure (click to expand) +

+ +- **`data`** (group) + + - **`total`** (attribute) - number of state-action samples in the dataset + + - **`env_args`** (attribute) - a json string that contains metadata on the environment and relevant arguments used for collecting data. Three keys: `env_name`, the name of the environment or task to create, `env_type`, one of robomimic's supported [environment types](https://github.com/ARISE-Initiative/robomimic/blob/master/robomimic/envs/env_base.py#L9), and `env_kwargs`, a dictionary of keyword-arguments to be passed into the environment of type `env_name`. + + - **`demo_0`** (group) - group for the first trajectory (every trajectory has a group) + + - **`num_samples`** (attribute) - the number of state-action samples in this trajectory + + - **`model_file`** (attribute) - the xml string corresponding to the MJCF MuJoCo model. Only present for robosuite datasets. + + - **`states`** (dataset) - flattened raw MuJoCo states, ordered by time. Shape (N, D) where N is the length of the trajectory, and D is the dimension of the state vector. Should be empty or have dummy values for non-robosuite datasets. + + - **`actions`** (dataset) - environment actions, ordered by time. Shape (N, A) where N is the length of the trajectory, and A is the action space dimension + + - **`rewards`** (dataset) - environment rewards, ordered by time. Shape (N,) where N is the length of the trajectory. + + - **`dones`** (dataset) - done signal, equal to 1 if playing the corresponding action in the state should terminate the episode. Shape (N,) where N is the length of the trajectory. + + - **`obs`** (group) - group for the observation keys. Each key is stored as a dataset. + + - **``** (dataset) - the first observation key. Note that the name of this dataset and shape will vary. As an example, the name could be "agentview_image", and the shape could be (N, 84, 84, 3). + + ... + + - **`next_obs`** (group) - group for the next observations. + + - **``** (dataset) - the first observation key. + + ... + + - **`demo_1`** (group) - group for the second trajectory + + ... + +- **`mask`** (group) - this group will exist in hdf5 datasets that contain filter keys + + - **``** (dataset) - the first filter key. Note that the name of this dataset and length will vary. As an example, this could be the "valid" filter key, and contain the list ["demo_0", "demo_19", "demo_35"], corresponding to 3 validation trajectories. + + ... + +

+
+ +### Data Conventions + +**robomimic**-compatible datasets expect certain values (such as images and actions) to be formatted a specific way. See the below sections for further details: + +
+ Storing images +

+

+

Warning!

+ +Dataset images should be of type `np.uint8` and be stored in channel-last `(H, W, C)` format. This is because: + +- **(1)** this is a common format that many `gym` environments and all `robosuite` environments return image observations in +- **(2)** using `np.uint8` (vs floats) saves space in dataset storage + +Note that the robosuite observation extraction script (`dataset_states_to_obs.py`) already stores images in the correct format. + +
+ +

+
+ + +
+ Storing actions +

+

+

Warning!

+ +Actions should be **normalized between -1 and 1**. This is because this range enables easier policy learning via the use of `tanh` layers). + +The `get_dataset_info.py` script can be used to sanity check stored actions, and will throw an `Exception` if there is a violation. + +
+ +

+
+ +### Filter Keys + +Filter keys enable arbitrary splitting of a dataset into sub-groups, and allow training on a specific subset of the data. + +A common use-case is to split data into train-validation splits. We provide a convenience script for doing this in the `robomimic/scripts` directory: + +```sh +$ python split_train_val.py --dataset /path/to/dataset.hdf5 --ratio 0.1 --filter_key +``` + +- `--dataset` specifies the path to the hdf5 dataset +- `--ratio` specifies the amount of validation data you would like to create. In the example above, 10% of the demonstrations will be put into the validation group. +- `--filter_key` (optional) By default, this script splits all demonstration keys in the hdf5 into 2 new hdf5 groups - one under `mask/train`, and one under `mask/valid`. If this argument is provided, the demonstration keys corresponding to this filter key (under `mask/`) will be split into 2 groups - `mask/_train` and `mask/_valid`. + +
+

Note!

+ +You can easily list the filter keys present in a dataset with the `get_dataset_info.py` script (see [this link](../tutorials/dataset_contents.html#view-dataset-structure-and-videos)), and you can even pass a `--verbose` flag to list the exact demonstrations that each filter key corresponds to. + +
+ +Using filter keys during training is easy. To use the generated train-valid split, you can set `config.experiment.validate=True` to ensure that validation will run after each training epoch, and then set `config.train.hdf5_filter_key="train"` and `config.train.hdf5_validation_filter_key="valid"` so that the demos under `mask/train` are used for training, and the demos under `mask/valid` are used for validation. + +You can also use a custom filter key for training by setting `config.train.hdf5_filter_key=`. This ensures that only the demos under `mask/` are used during training. You can also specify a custom filter key for validation by setting `config.train.hdf5_validation_filter_key`. diff --git a/code_src/rise_robomimic/docs/datasets/robomimic_v0.1.md b/code_src/rise_robomimic/docs/datasets/robomimic_v0.1.md new file mode 100644 index 0000000000000000000000000000000000000000..9fc887ba264a23b84aba92d31acdddf368b19eae --- /dev/null +++ b/code_src/rise_robomimic/docs/datasets/robomimic_v0.1.md @@ -0,0 +1,239 @@ +# robomimic v0.1 (CoRL 2021) + +## Overview +robomimic v0.1 datasets is a large-scale, diverse collection of task demonstrations spanning: + +- multiple human demonstrators of varying quality +- multiple robot manipulation tasks of varying difficulty +- both simulated and real data + +## Downloading + + +
+

Warning!

+ + +Since the release of robomimic v0.3, we recommend that users install [robosuite](https://robosuite.ai/) from source and are on the `v1.4.1` branch. The `v1.4.1` branch of robosuite uses Google DeepMind's [mujoco python bindings](https://github.com/deepmind/mujoco) which replaces the now deprecated [mujoco-py](https://github.com/openai/mujoco-py). + +Note that the CoRL 2021 datasets relied on the mujoco-py based `offline_study` branch of robosuite. In this version of robomimic we provide users with datasets based on `v1.4.1`, which we found produce similar results to the original `offline_study` datasets. However if you would like to download the `offline_study` datasets, please use the `v0.2.0` branch of robomimic and consult the [v0.2 docs](https://robomimic.github.io/docs/v0.2/datasets/robomimic_v0.1.html) for instructions. + +
+ +We provide two ways for downloading robomimic v0.1 datasets: + +### Method 1: Using `download_datasets.py` (Recommended) +`download_datasets.py` is a python script that provides a programmatic way of installing all datasets. This is the preferred method, because this script also sets up a directory structure for the datasets that works out of the box with examples for reproducing benchmark results. + +A few examples of using this script are provided below: + +```sh +# default behavior - just download lift proficient-human low-dim dataset +$ python download_datasets.py + +# download low-dim proficient-human datasets for all simulation tasks +# (do a dry run first to see which datasets would be downloaded) +$ python download_datasets.py --tasks sim --dataset_types ph --hdf5_types low_dim --dry_run +$ python download_datasets.py --tasks sim --dataset_types ph --hdf5_types low_dim + +# download all low-dim multi-human datasets for the can and square tasks +$ python download_datasets.py --tasks can square --dataset_types mh --hdf5_types low_dim + +# download the sparse reward machine-generated low-dim datasets +$ python download_datasets.py --tasks all --dataset_types mg --hdf5_types low_dim_sparse + +# download all real robot datasets +$ python download_datasets.py --tasks real + +# specify a different location for downloading the datasets +$ python download_datasets.py --download_dir /tmp/datasets +``` + +### Method 2: Using Direct Download Links + +We also provide direct download links for each hdf5 dataset (the download links for the raw datasets are also included – they allow flexibility in extracting different kinds of observations and rewards during postprocessing): + +**Proficient-Human (PH)** [**info**](robomimic_v0.1.html#proficient-human-ph) + +
+ Download Links +

+ +proficient_human + +| **Lift
(PH)** | **Can
(PH)** | **Square
(PH)** | **Transport
(PH)** | **Tool Hang
(PH)** | +| :----------------------------------------------------------: | :----------------------------------------------------------: | :----------------------------------------------------------: | :----------------------------------------------------------: | :----------------------------------------------------------: | +| ![lift](../images/lift.png) | ![can](../images/can.png) | ![square](../images/square.png) | ![transport](../images/transport.png) | ![tool_hang](../images/tool_hang.png) | +| [raw](http://downloads.cs.stanford.edu/downloads/rt_benchmark/lift/ph/demo_v141.hdf5) | [raw](http://downloads.cs.stanford.edu/downloads/rt_benchmark/can/ph/demo_v141.hdf5) | [raw](http://downloads.cs.stanford.edu/downloads/rt_benchmark/square/ph/demo_v141.hdf5) | [raw](http://downloads.cs.stanford.edu/downloads/rt_benchmark/transport/ph/demo_v141.hdf5) | [raw](http://downloads.cs.stanford.edu/downloads/rt_benchmark/tool_hang/ph/demo_v141.hdf5) | +| [low_dim](http://downloads.cs.stanford.edu/downloads/rt_benchmark/lift/ph/low_dim_v141.hdf5) | [low_dim](http://downloads.cs.stanford.edu/downloads/rt_benchmark/can/ph/low_dim_v141.hdf5) | [low_dim](http://downloads.cs.stanford.edu/downloads/rt_benchmark/square/ph/low_dim_v141.hdf5) | [low_dim](http://downloads.cs.stanford.edu/downloads/rt_benchmark/transport/ph/low_dim_v141.hdf5) | [low_dim](http://downloads.cs.stanford.edu/downloads/rt_benchmark/tool_hang/ph/low_dim_v141.hdf5) | + +| **Lift Real
(PH)** | **Can Real
(PH)** | **Tool Hang Real
(PH)** | +| :----------------------------------------------------------: | :----------------------------------------------------------: | :----------------------------------------------------------: | +| ![lift_real](../images/lift_real.jpg) | ![can_real](../images/can_real.jpg) | ![tool_hang_real](../images/tool_hang_real.jpg) | +| [image](http://downloads.cs.stanford.edu/downloads/rt_benchmark/lift_real/ph/demo.hdf5) (1.9 GB) | [image](http://downloads.cs.stanford.edu/downloads/rt_benchmark/can_real/ph/demo.hdf5) (5.3 GB) | [image](http://downloads.cs.stanford.edu/downloads/rt_benchmark/tool_hang_real/ph/demo.hdf5) (58 GB) | + +

+
+ +
+
+ +**Multi-Human (MH)** [**info**](robomimic_v0.1.html#multi-human-mh) + +
+ Download Links +

+multi_human + +| **Lift
(MH)** | **Can
(MH)** | **Square
(MH)** | **Transport
(MH)** | +| :----------------------------------------------------------: | :----------------------------------------------------------: | :----------------------------------------------------------: | :----------------------------------------------------------: | +| ![lift](../images/lift.png) | ![can](../images/can.png) | ![square](../images/square.png) | ![transport](../images/transport.png) | +| [raw](http://downloads.cs.stanford.edu/downloads/rt_benchmark/lift/mh/demo_v141.hdf5) | [raw](http://downloads.cs.stanford.edu/downloads/rt_benchmark/can/mh/demo_v141.hdf5) | [raw](http://downloads.cs.stanford.edu/downloads/rt_benchmark/square/mh/demo_v141.hdf5) | [raw](http://downloads.cs.stanford.edu/downloads/rt_benchmark/transport/mh/demo_v141.hdf5) | +| [low_dim](http://downloads.cs.stanford.edu/downloads/rt_benchmark/lift/mh/low_dim_v141.hdf5) | [low_dim](http://downloads.cs.stanford.edu/downloads/rt_benchmark/can/mh/low_dim_v141.hdf5) | [low_dim](http://downloads.cs.stanford.edu/downloads/rt_benchmark/square/mh/low_dim_v141.hdf5) | [low_dim](http://downloads.cs.stanford.edu/downloads/rt_benchmark/transport/mh/low_dim_v141.hdf5) | +

+
+ +
+
+ +**Machine-Generated (MG)** [**info**](robomimic_v0.1.html#machine-generated-mg) + +
+ Download Links +

+ +machine_generated + +| **Lift
(MG)** | **Can
(MG)** | +| :----------------------------------------------------------: | :----------------------------------------------------------: | +| ![lift](../images/lift.png) | ![can](../images/can.png) | +| [raw](http://downloads.cs.stanford.edu/downloads/rt_benchmark/lift/mg/demo_v141.hdf5) | [raw](http://downloads.cs.stanford.edu/downloads/rt_benchmark/can/mg/demo_v141.hdf5) | +| [low_dim (sparse)](http://downloads.cs.stanford.edu/downloads/rt_benchmark/lift/mg/low_dim_sparse_v141.hdf5) | [low_dim (sparse)](http://downloads.cs.stanford.edu/downloads/rt_benchmark/can/mg/low_dim_sparse_v141.hdf5) | +| [low_dim (dense)](http://downloads.cs.stanford.edu/downloads/rt_benchmark/lift/mg/low_dim_dense_v141.hdf5) | [low_dim (dense)](http://downloads.cs.stanford.edu/downloads/rt_benchmark/can/mg/low_dim_dense_v141.hdf5) | + +

+
+ +
+
+ +**Paired** [**info**](robomimic_v0.1.html#paired) + +
+ Download Links +

+ +| **Can Paired** | +| :----------------------------------------------------------: | +| can_paired | +| [raw](http://downloads.cs.stanford.edu/downloads/rt_benchmark/can/paired/demo_v141.hdf5) | +| [low_dim (sparse)](http://downloads.cs.stanford.edu/downloads/rt_benchmark/can/paired/low_dim_v141.hdf5) | + +

+
+ +## Postprocessing +If a **low_dim** or **image** dataset was downloaded, the dataset works out of the box! No postprocessing is needed. + +If a **raw** dataset was downloaded, the dataset must be postprocessed since there are no observations stored. To extract observations, please see the `extract_obs_from_raw_datasets.sh` script. + +## Info + +Below, we provide information on each dataset provided: + +### Proficient-Human (PH) + +These datasets were collected by 1 operator using the [RoboTurk](https://roboturk.stanford.edu/) platform. Each dataset consists of 200 successful trajectories. + +### Multi-Human (MH) + +These datasets were collected by 6 operators using the [RoboTurk](https://roboturk.stanford.edu/) platform. Each dataset consists of 50 trajectories provided by each operator, for a total of 300 successful trajectories. The operators were varied in proficiency -- there were 2 "worse" operators, 2 "okay" operators, and 2 "better" operators, resulting in diverse, mixed quality datasets. + +### Machine-Generated (MG) + +These datasets were generated by [training](https://github.com/ARISE-Initiative/robosuite-benchmark) an [SAC](https://arxiv.org/abs/1801.01290) agent for each task, and then using each policy checkpoint saved during training to generate a mixed quality dataset. 300 rollouts were collected for each checkpoint, with 5 checkpoints for the Lift dataset (total of 1500 trajectories), and 13 checkpoints for the Can dataset (total of 3900 trajectories). + +### Paired + +This is a diagnostic dataset to test the ability of algorithms to learn from mixed quality human data. A single experienced operator collected 2 demonstrations for each of 100 task initializations on the Can task, resulting in 200 total demonstrations. Each pair of demonstrations consists of a "good" trajectory, where the can is picked up and placed in the correct bin, and a "bad" trajectory, where the can is picked up, and tossed outside of the robot workspace. Since the task initializations are identical, and the first part of each trajectory leading up to the can grasp is similar, there is a strong expectation for algorithms that deal with suboptimal data, to be able to filter the good trajectories from the bad ones, and achieve near-perfect performance. + +## Reproduce [Study](https://robomimic.github.io/study/) Results + +### Running Experiments + +After downloading the appropriate datasets you're interested in using by running the `download_datasets.py` script, the `generate_paper_configs.py` script can be used to generate all training config json files necessary to reproduce the experiments in the [study](https://robomimic.github.io/study/). A few examples are below. + +```sh +# Assume datasets already exist in robomimic/../datasets folder. Configs will be generated under robomimic/exps/paper, and training results will be at /tmp/experiment_results when launching training runs. +$ python generate_paper_configs.py --output_dir /tmp/experiment_results + +# Alternatively, specify where datasets exist, and specify where configs should be generated. +$ python generate_paper_configs.py --config_dir /tmp/configs --dataset_dir /tmp/datasets --output_dir /tmp/experiment_results +``` + +- `--config_dir` specifies where the config json files will be generated (defaults to `robomimic/exps/paper`) +- `--dataset_dir` specifies where the released datasets can be found, and should be consistent with the `--download_dir` argument supplied to `download_datasets.py` earlier. (if omitted, both scripts default to `robomimic/../datasets`) +- `--output_dir` specifies where training results will be written (including model checkpoints, logs, and rollout videos) + +Then, to reproduce a specific set of training runs for different experiment groups, we can simply navigate to the generated config directory, and copy training commands from the generated shell script there. As an example, we can reproduce the low-dim BC and BC-RNN training results on the Lift PH dataset, by looking for the correct set of commands in `robomimic/exps/paper/core.sh` and running them. The relevant section of the shell script is reproduced below. + +```bash +# task: lift +# dataset type: ph +# hdf5 type: low_dim +python /path/to/robomimic/scripts/train.py --config /path/to/robomimic/exps/paper/core/lift/ph/low_dim/bc.json +python /path/to/robomimic/scripts/train.py --config /path/to/robomimic/exps/paper/core/lift/ph/low_dim/bc_rnn.json +``` + +
+

Want to Run Experiments on Custom Observations?

+ +We provide the raw (observation-free) `demo_v141.hdf5` datasets so that you can generate your own custom set of observations, such as additional camera viewpoints. For information, see [Extracting Observations from Datasets](robosuite.md#extracting-observations-from-mujoco-states). + +**NOTE**: To compare against how our paper's released datasets were generated, please see the `extract_obs_from_raw_datasets.sh` script. + +
+ +### Overview of Included Experiments + +Each group of experiments below has a shell script (for example `core.sh`) and a folder that is generated by the `generate_paper_configs.py` script at `--config_dir` (defaults to `robomimic/exps/paper`). The Tables and Figures below refer to the ones in this paper. + +- **core:** the main experiment results across all tasks, datasets, and observation spaces. This includes the results in Table 1, Table 3, and Table 16 + +- **subopt:** results on suboptimal data subsets of the multi-human datasets (with the exception of results on the can-paired dataset, which are actually contained in `core` above). This includes Table 2, Table 17, Table 23, and Table 24. + +- **dataset_size:** results on the 20% and 50% size subsets. This includes Figure 3, Table 27, and Table 28. + +- **obs_ablation:** results on different observation spaces from the study. This includes Figure 2a, Table 22, and Table 25. + +- **hyper_ablation:** results on the hyperparameter sensitivity study. This includes Figure 2b, Figure 2c, and Table 26. + +- **d4rl:** results on D4RL datasets (see section below) + + +### Quick Example + +Below, we show a simple example of how to reproduce one of the results from the study - the BC-RNN result on the Lift (Proficient-Human) low-dim dataset: + +```sh +# default behavior for download script - just download lift proficient-human low-dim dataset to robomimic/../datasets +$ python download_datasets.py + +# generate json configs for running all experiments at robomimic/exps/paper +$ python generate_paper_configs.py --output_dir /tmp/experiment_results + +# the training command can be found in robomimic/exps/paper/core.sh +# Training results can be viewed at /tmp/experiment_results (--output_dir when generating paper configs). +$ python train.py --config ../exps/paper/core/lift/ph/low_dim/bc_rnn.json +``` + +## Citation + +```bibtex +@inproceedings{robomimic2021, + title={What Matters in Learning from Offline Human Demonstrations for Robot Manipulation}, + author={Mandlekar, Ajay and Xu, Danfei and Wong, Josiah and Nasiriany, Soroush and Wang, Chen and Kulkarni, Rohun and Fei-Fei, Li and Savarese, Silvio and Zhu, Yuke and Mart{\'\i}n-Mart{\'\i}n, Roberto}, + booktitle={5th Annual Conference on Robot Learning}, + year={2021} +} +``` \ No newline at end of file diff --git a/code_src/rise_robomimic/docs/datasets/robosuite.md b/code_src/rise_robomimic/docs/datasets/robosuite.md new file mode 100644 index 0000000000000000000000000000000000000000..73f57b0f459e4eb3d95e73e347a686e8cc798e04 --- /dev/null +++ b/code_src/rise_robomimic/docs/datasets/robosuite.md @@ -0,0 +1,102 @@ +# robosuite Datasets + +The repository is fully compatible with datasets collected using [robosuite](https://robosuite.ai/). See [this link](https://robosuite.ai/docs/algorithms/demonstrations.html) for more information on collecting your own human demonstrations using robosuite. + +## Converting robosuite hdf5 datasets + +The raw `demo.hdf5` file generated by the `collect_human_demonstrations.py` robosuite script can easily be modified in-place to be compatible with **robomimic**: + +```sh +$ python conversion/convert_robosuite.py --dataset /path/to/demo.hdf5 +``` + +
+

Post-Processed Dataset Structure

+ +This post-processed `demo.hdf5` file in its current state is _missing_ observations (e.g.: proprioception, images, ...), rewards, and dones, which are necessary for training policies. + +However, keeping these observation-free datasets is useful because it **allows flexibility in [extracting](robosuite.md#extracting-observations-from-mujoco-states) different kinds of observations and rewards**. + +
+ Dataset Structure (click to expand) +

+ +- `data` (group) + + - `total` (attribute) - number of state-action samples in the dataset + + - `env_args` (attribute) - a json string that contains metadata on the environment and relevant arguments used for collecting data + + - `demo_0` (group) - group for the first demonstration (every demonstration has a group) + + - `num_samples` (attribute) - the number of state-action samples in this trajectory + - `model_file` (attribute) - the xml string corresponding to the MJCF MuJoCo model + - `states` (dataset) - flattened raw MuJoCo states, ordered by time + - `actions` (dataset) - environment actions, ordered by time + + - `demo_1` (group) - group for the second demonstration + + ... +

+
+ +
+ + +Next, we will extract observations from this raw dataset. + + +## Extracting Observations from MuJoCo states + +
+

Warning! Train-Validation Data Splits

+ +For robosuite datasets, if using your own [train-val splits](overview.md#filter-keys), generate these splits _before_ extracting observations. This ensures that all postprocessed hdf5s generated from the `demo.hdf5` inherits the same filter keys. + +
+ +Generating observations from a dataset is straightforward and can be done with a single command from `robomimic/scripts`: + +```sh +# For low dimensional observations only, with done on task success +$ python dataset_states_to_obs.py --dataset /path/to/demo.hdf5 --output_name low_dim.hdf5 --done_mode 2 + +# For including image observations +$ python dataset_states_to_obs.py --dataset /path/to/demo.hdf5 --output_name image.hdf5 --done_mode 2 --camera_names agentview robot0_eye_in_hand --camera_height 84 --camera_width 84 + +# For including depth observations too +python dataset_states_to_obs.py --dataset /path/to/demo.hdf5 --output_name depth.hdf5 --done_mode 2 --camera_names agentview robot0_eye_in_hand --camera_height 84 --camera_width 84 --depth + +# Using dense rewards +$ python dataset_states_to_obs.py --dataset /path/to/demo.hdf5 --output_name image_dense.hdf5 --done_mode 2 --dense --camera_names agentview robot0_eye_in_hand --camera_height 84 --camera_width 84 + +# (space saving option) extract 84x84 image observations with compression and without +# extracting next obs (not needed for pure imitation learning algos) +python dataset_states_to_obs.py --dataset /path/to/demo.hdf5 --output_name image.hdf5 \ + --done_mode 2 --camera_names agentview robot0_eye_in_hand --camera_height 84 --camera_width 84 \ + --compress --exclude-next-obs + +# Only writing done at the end of the trajectory +$ python dataset_states_to_obs.py --dataset /path/to/demo.hdf5 --output_name image_done_1.hdf5 --done_mode 1 --camera_names agentview robot0_eye_in_hand --camera_height 84 --camera_width 84 + +# For seeing descriptions of all the command-line args available +$ python dataset_states_to_obs.py --help +``` + +
+

Saving storage space

+ +Image datasets can be quite large in terms of storage, but we also offer two flags that might be useful to save on storage. First, the `--compress` flag will run lossless compression on the extracted observations, resulting in datasets that are up to 5x smaller in storage (in our testing). However, training will be marginally slower due to uncompression costs when loading batches. Second, the `--exclude-next-obs` will exclude the `next_obs` keys per trajectory, since they are not needed for imitation learning algorithms like `BC` and `BC-RNN`. + +In our testing, enabling both flags reduced the Square (PH) Image dataset size from 2.5 GB to 307 MB at the cost of increasing BC-RNN training time from 7 hours to 8.5 hours. +
+ +## Citation +```sh +@article{zhu2020robosuite, + title={robosuite: A modular simulation framework and benchmark for robot learning}, + author={Zhu, Yuke and Wong, Josiah and Mandlekar, Ajay and Mart{\'\i}n-Mart{\'\i}n, Roberto and Joshi, Abhishek and Nasiriany, Soroush and Zhu, Yifeng}, + journal={arXiv preprint arXiv:2009.12293}, + year={2020} +} +``` \ No newline at end of file diff --git a/code_src/rise_robomimic/docs/datasets/roboturk_pilot.md b/code_src/rise_robomimic/docs/datasets/roboturk_pilot.md new file mode 100644 index 0000000000000000000000000000000000000000..78e4b5d8f45c8689813e828be52b2b4a88260cb7 --- /dev/null +++ b/code_src/rise_robomimic/docs/datasets/roboturk_pilot.md @@ -0,0 +1,42 @@ +# RoboTurk Pilot + +## Overview + +The first [RoboTurk paper](https://arxiv.org/abs/1811.02790) released [large-scale pilot datasets](https://roboturk.stanford.edu/dataset_sim.html) collected with robosuite `v0.3`. These datasets consist of over 1000 task demonstrations each on several Sawyer `PickPlace` and `NutAssembly` task variants, collected by several human operators. This repository is fully compatible with these datasets. + +

+ +

+ +## Downloading + +
+

Warning!

+ +When working with these datasets, please make sure that you have installed [robosuite](https://robosuite.ai/) from source and are on the `roboturk_v1` branch. + +
+ +Download the dataset [here](http://cvgl.stanford.edu/projects/roboturk/RoboTurkPilot.zip) (~9 GB download), and unzip the file, resulting in a `RoboTurkPilot` folder. + +## Postprocessing + +First, the dataset must be updated to a format compatible with **robomimic**. Run the following script (these arguments are provided as an example): +```sh +# convert the Can demonstrations, and also create a "fastest_225" filter_key (prior work such as IRIS has trained on this subset) +$ python conversion/convert_roboturk_pilot.py --folder /path/to/RoboTurkPilot/bins-Can --n 225 +``` +Then, the dataset must be postprocessed since there are no observations stored. You must run `dataset_states_to_obs.py`. For more information, see [this page](robosuite.html#extracting-observations-from-mujoco-states). + +## Citation + +```sh +@inproceedings{mandlekar2018roboturk, + title={Roboturk: A crowdsourcing platform for robotic skill learning through imitation}, + author={Mandlekar, Ajay and Zhu, Yuke and Garg, Animesh and Booher, Jonathan and Spero, Max and Tung, Albert and Gao, Julian and Emmons, John and Gupta, Anchit and Orbay, Emre and others}, + booktitle={Conference on Robot Learning}, + pages={879--893}, + year={2018}, + organization={PMLR} +} +``` \ No newline at end of file diff --git a/code_src/rise_robomimic/docs/introduction/getting_started.md b/code_src/rise_robomimic/docs/introduction/getting_started.md new file mode 100644 index 0000000000000000000000000000000000000000..d995e3afd6d8a8aae2536a9612a589a38ffb5f1d --- /dev/null +++ b/code_src/rise_robomimic/docs/introduction/getting_started.md @@ -0,0 +1,97 @@ +# Getting Started + +## Quickstart colab notebook + +If you prefer to test the basic functionality of robomimic without installing anything locally, try the quickstart [Colab notebook](https://colab.research.google.com/drive/1b62r_km9pP40fKF0cBdpdTO2P_2eIbC6?usp=sharing). + +## Running experiments +We begin with a quick tutorial on downloading datasets and running experiments. + +Before beginning, make sure you are at the base repo path: +```sh +$ cd {/path/to/robomimic} +``` + +### Step 1: Download dataset + +Download the robosuite **Lift (PH)** dataset (see [this link](../datasets/robomimic_v0.1.html#proficient-human-ph) for more information on this dataset): +```sh +$ python robomimic/scripts/download_datasets.py --tasks lift --dataset_types ph +``` + +The dataset can be found at `datasets/lift/ph/low_dim_v141.hdf5` + +### Step 2: Launch experiment + +Now, we will run an experiment using `train.py`. In this case we would like to run behavior cloning (BC) for the lift dataset we just downloaded. + +```sh +$ python robomimic/scripts/train.py --config robomimic/exps/templates/bc.json --dataset datasets/lift/ph/low_dim_v141.hdf5 --debug +``` + +
+

Running quick sanity check experiments

+ +Make sure to add the `--debug` flag to your experiments as a sanity check that your implementation works. + +
+ +
+

Warning!

+ +This example [requires robosuite](./installation.html#install-simulators) to be installed (under the `v1.4.1` branch), but it can be run without robosuite by disabling rollouts in `robomimic/exps/templates/bc.json`: simply change the `experiment.rollout.enabled` flag to `false`. + +
+ +### Step 3: View experiment results + +After the script finishes, we can check the training outputs in the directory `bc_trained_models/test`. +Experiment outputs comprise the following: +``` +config.json # config used for this experiment +logs/ # experiment log files + log.txt # terminal output + tb/ # tensorboard logs +videos/ # videos of robot rollouts during training +models/ # saved model checkpoints +``` + +The experiment results can be viewed using tensorboard: +```sh +$ tensorboard --logdir bc_trained_models/test --bind_all +``` + +## Next steps + +Please refer to the remaining documentation sections. Some helpful suggestions on pages to view next: +- [Configuring and Launching Training Runs](../tutorials/configs.html) +- [Logging and Viewing Training Results](../tutorials/viewing_results.html) +- [Running Hyperparameter Scans](../tutorials/hyperparam_scan.html) +- [Overview of Datasets](../datasets/overview.html) +- [Dataset Contents and Visualization](../tutorials/dataset_contents.html) +- [Overview of Modules](../modules/overview.html) diff --git a/code_src/rise_robomimic/docs/introduction/implemented_algorithms.md b/code_src/rise_robomimic/docs/introduction/implemented_algorithms.md new file mode 100644 index 0000000000000000000000000000000000000000..30a26c8f5162d51f39bd4becf3721e38d063aa76 --- /dev/null +++ b/code_src/rise_robomimic/docs/introduction/implemented_algorithms.md @@ -0,0 +1,42 @@ +# Implemented Algorithms + +**robomimic** includes several high-quality implementations of offline learning algorithms, and offers tools to easily build [your own learning algorithms](../tutorials/custom_algorithms.html). +## Imitation Learning + +### BC + +- Vanilla Behavioral Cloning (see [this paper](https://papers.nips.cc/paper/1988/file/812b4ba287f5ee0bc9d43bbf5bbe87fb-Paper.pdf)), consisting of simple supervised regression from observations to actions. Implemented in the `BC` class in `algo/bc.py`, along with some variants such as `BC_GMM` (stochastic GMM policy) and `BC_VAE` (stochastic VAE policy) + +### BC-RNN + +- Behavioral Cloning with an RNN network. Implemented in the `BC_RNN` and `BC_RNN_GMM` (recurrent GMM policy) classes in `algo/bc.py`. + +### BC-Transformer + +- Behavioral Cloning with an Transformer network. Implemented in the `BC_Transformer` and `BC_Transformer_GMM` (transformer GMM policy) classes in `algo/bc.py`. + +### HBC + +- Hierarchical Behavioral Cloning - the implementation is largely based off of [this paper](https://arxiv.org/abs/2003.06085). Implemented in the `HBC` class in `algo/hbc.py`. + +## Offline Reinforcement Learning + +### IRIS + +- A recent batch offline RL algorithm from [this paper](https://arxiv.org/abs/1911.05321). Implemented in the `IRIS` class in `algo/iris.py`. + +### BCQ + +- A recent batch offline RL algorithm from [this paper](https://arxiv.org/abs/1812.02900). Implemented in the `BCQ` class in `algo/bcq.py`. + +### CQL + +- A recent batch offline RL algorithm from [this paper](https://arxiv.org/abs/2006.04779). Implemented in the `CQL` class in `algo/cql.py`. + +### IQL + +- A recent batch offline RL algorithm from [this paper](https://arxiv.org/abs/2110.06169). Implemented in the `IQL` class in `algo/iql.py`. + +### TD3-BC + +- A recent algorithm from [this paper](https://arxiv.org/abs/2106.06860). We implemented it as an example (see section below on building your own algorithm). Implemented in the `TD3_BC` class in `algo/td3_bc.py`. diff --git a/code_src/rise_robomimic/docs/introduction/installation.md b/code_src/rise_robomimic/docs/introduction/installation.md new file mode 100644 index 0000000000000000000000000000000000000000..bc7b022a087186f5759bce69c4414935cc90fc74 --- /dev/null +++ b/code_src/rise_robomimic/docs/introduction/installation.md @@ -0,0 +1,183 @@ +# Installation + +## Requirements + +- Mac OS X or Linux machine +- Python >= 3.6 (recommended 3.8.0) +- [conda](https://www.anaconda.com/products/individual) + - [virtualenv](https://virtualenv.pypa.io/en/latest/) is also an acceptable alternative, but we assume you have conda installed in our examples below + +## Install robomimic + +
+

1. Create and activate conda environment

+ +```sh +$ conda create -n robomimic_venv python=3.8.0 +$ conda activate robomimic_venv +``` + +
+ +
+

2. Install PyTorch

+ +[PyTorch](https://pytorch.org/) reference + +
+ Option 1: Mac +

+ +```sh +# Can change pytorch, torchvision versions +# We don't install cudatoolkit since Mac does not have NVIDIA GPU +$ conda install pytorch==2.0.0 torchvision==0.15.1 -c pytorch +``` + +

+
+ +
+ Option 2: Linux +

+ +```sh +# Can change pytorch, torchvision versions +$ conda install pytorch==2.0.0 torchvision==0.15.1 -c pytorch +``` + +

+
+ +
+ + +
+

3. Install robomimic

+ +
+ Option 1: Install from source (recommended) +

+ +```sh +$ cd +$ git clone https://github.com/ARISE-Initiative/robomimic.git +$ cd robomimic +$ pip install -e . +``` + +

+
+ +
+ Option 2: Install via pip +

+ +```sh +$ pip install robomimic +``` + +

+
+ +
+ +
+

Warning! Additional dependencies might be required

+ +This is all you need for using the suite of algorithms and utilities packaged with robomimic. However, to use our demonstration datasets, you may need additional dependencies. Please see the [datasets page](../datasets/overview.html) for more information on downloading datasets and reproducing experiments, and see [the simulators section below](installation.html#install-simulators). +
+ + +# Optional Installations + +## Downloading datasets and reproducing experiments + +See the [datasets page](../datasets/overview.html) for more information on downloading datasets and reproducing experiments. + +## Install simulators + +If you would like to run robomimic examples and work with released datasets, please install the following simulators: + +
+ robosuite +

+ Required for running most robomimic examples and released datasets. Compatible with robosuite v1.2+. Install via: + +```sh +# From source (recommended) +$ cd +$ git clone https://github.com/ARISE-Initiative/robosuite.git +$ cd robosuite +$ pip install -r requirements.txt +OR +# Via pip +$ pip install robosuite +``` + +**(Optional)** to use our released datasets and reproduce our experiments, switch to our `v1.4.1` branch (requires installing robosuite from source): + +```sh +git checkout v1.4.1 +``` + + + +

+
+ + +
+ D4RL +

+ +Useful for running some of our algorithms on the [D4RL](https://arxiv.org/abs/2004.07219) datasets. + +Install via the instructions [here](https://github.com/rail-berkeley/d4rl). + +

+
+ + +## Test your installation +This assumes you have installed robomimic from source. + +Run a quick debugging (dummy) training loop to make sure robomimic is installed correctly: +```sh +$ cd +$ python examples/train_bc_rnn.py --debug +``` + +Run a much more thorough test of several algorithms and scripts (**Warning: this script may take several minutes to finish!**): +```sh +$ cd /tests +$ bash test.sh +``` + +To run some easy examples, see the [Getting Started](./getting_started.html) section. + +## Install documentation dependencies + +If you plan to contribute to the repository and add new features, you must install the additional requirements required to build the documentation locally: + +```sh +$ pip install -r requirements-docs.txt +``` + +You can test generating the documentation and viewing it locally in a web browser: +```sh +$ cd /docs +$ make clean +$ make apidoc +$ make html +$ cp -r images _build/html/ +``` + +There should be a generated `_build` folder - navigate to `_build/html/` and open `index.html` in a web browser to view the documentation. \ No newline at end of file diff --git a/code_src/rise_robomimic/docs/introduction/overview.md b/code_src/rise_robomimic/docs/introduction/overview.md new file mode 100644 index 0000000000000000000000000000000000000000..f71a6aa309eb028c0ce8047b657d859aae04bfa6 --- /dev/null +++ b/code_src/rise_robomimic/docs/introduction/overview.md @@ -0,0 +1,152 @@ +# Overview + +

+ + + + + + + + +

+ +**robomimic** is a framework for robot learning from demonstration. +It offers a broad set of demonstration datasets collected on robot manipulation domains and offline learning algorithms to learn from these datasets. +**robomimic** aims to make robot learning broadly *accessible* and *reproducible*, allowing researchers and practitioners to benchmark tasks and algorithms fairly and to develop the next generation of robot learning algorithms. + +## Core Features + + + + +

+ +

+ + + + + + +## Reproducing benchmarks + +The robomimic framework also makes reproducing the results from different benchmarks and datasets easy. See the [datasets page](../datasets/overview.html) for more information on downloading datasets and reproducing experiments. + +## Troubleshooting + +Please see the [troubleshooting](../miscellaneous/troubleshooting.html) section for common fixes, or [submit an issue](https://github.com/ARISE-Initiative/robomimic/issues) on our github page. + +## Contributing to robomimic +This project is part of the broader [Advancing Robot Intelligence through Simulated Environments (ARISE) Initiative](https://github.com/ARISE-Initiative), with the aim of lowering the barriers of entry for cutting-edge research at the intersection of AI and Robotics. +The project originally began development in late 2018 by researchers in the [Stanford Vision and Learning Lab](http://svl.stanford.edu/) (SVL). +Now it is actively maintained and used for robotics research projects across multiple labs. +We welcome community contributions to this project. +For details please check our [contributing guidelines](../miscellaneous/contributing.html). + +## Citation + +Please cite [this paper](https://arxiv.org/abs/2108.03298) if you use this framework in your work: + +```bibtex +@inproceedings{robomimic2021, + title={What Matters in Learning from Offline Human Demonstrations for Robot Manipulation}, + author={Ajay Mandlekar and Danfei Xu and Josiah Wong and Soroush Nasiriany and Chen Wang and Rohun Kulkarni and Li Fei-Fei and Silvio Savarese and Yuke Zhu and Roberto Mart\'{i}n-Mart\'{i}n}, + booktitle={Conference on Robot Learning (CoRL)}, + year={2021} +} +``` diff --git a/code_src/rise_robomimic/docs/miscellaneous/acknowledgments.md b/code_src/rise_robomimic/docs/miscellaneous/acknowledgments.md new file mode 100644 index 0000000000000000000000000000000000000000..858b16e1e4c3a2b13928ed39ae1e77031c86d21c --- /dev/null +++ b/code_src/rise_robomimic/docs/miscellaneous/acknowledgments.md @@ -0,0 +1,21 @@ +# Acknowledgments + +### People + +We would like to thank members of the [Stanford PAIR Group](http://pair.stanford.edu/) for their support and feedback on this project. These people in particular have made the following contributions at different stages of this project: + +- [Rohun Kulkarni](https://www.linkedin.com/in/rohunkulkarni/) (assistance with collecting real robot datasets and running real robot experiments) +- [Albert Tung](https://www.linkedin.com/in/albert-tung3/) (assistance with collecting simulation datasets using the [RoboTurk](https://roboturk.stanford.edu/) system) +- [Fei Xia](http://fxia.me/) ([egl_probe](https://github.com/StanfordVL/egl_probe) library, which helped us run experiments on lab clusters) +- [Jim Fan](https://twitter.com/drjimfan?lang=en) (providing support for running experiments on lab clusters) + +### Codebases + +- Our Config class (see `config/config.py`) was adapted from [addict](https://github.com/mewwts/addict). +- The [BCQ](https://github.com/sfujim/BCQ), [CQL](https://github.com/aviralkumar2907/CQL), and [TD3-BC](https://github.com/sfujim/TD3_BC) author-provided implementations were used as a reference for our implementations. +- The `TanhWrappedDistribution` class in `models/distributions.py` was adapted from [rlkit](TanhWrappedDistribution). +- Support for training distributional critics (see `BCQ_Distributional` in `algos/bcq.py`) was adapted from [Acme](https://github.com/deepmind/acme). It also served as a useful reference for implementing Gaussian Mixture Model (GMM) policies. +- Our transformer implementation was adapted from the excellent [minGPT](https://github.com/karpathy/minGPT) codebase. + +We wholeheartedly welcome the community to contribute to our project through issues and pull requests. New contributors will be added to the list above. + diff --git a/code_src/rise_robomimic/docs/miscellaneous/contributing.md b/code_src/rise_robomimic/docs/miscellaneous/contributing.md new file mode 100644 index 0000000000000000000000000000000000000000..fc6915950a5315b309f4a9d086a523e7559388ba --- /dev/null +++ b/code_src/rise_robomimic/docs/miscellaneous/contributing.md @@ -0,0 +1,54 @@ +# Contributing Guidelines + +Our team wholeheartedly welcomes the community to contribute to robomimic. Contributions from members of the community will help ensure the long-term success of this project. Before you plan to make contributions, here are important resources to get started with: + +- Read the robomimic [documentation](https://robomimic.github.io/docs/introduction/overview.html) and [paper](https://arxiv.org/abs/2108.03298) +- Check our latest status from existing [issues](https://github.com/ARISE-Initiative/robomimic/issues), [pull requests](https://github.com/ARISE-Initiative/robomimic/pulls), and [branches](https://github.com/ARISE-Initiative/robomimic/branches) and avoid duplicate efforts +- Join our [ARISE Slack](https://ariseinitiative.slack.com) workspace for technical discussions. Please [email us](mailto:yukez@cs.utexas.edu) to be added to the workspace. + +We encourage the community to make four major types of contributions: + +- **Bug fixes**: Address open issues and fix bugs presented in the `master` branch. +- **Additional datasets and tasks:** Make robomimic compatible with more kinds of datasets, simulators, and tasks. +- **New algorithms:** Develop new algorithms or re-implement existing algorithms for learning from robot manipulation datasets. +- **Implement new functionalities:** Implement new features, such as training with new kinds of observations (depth images, lidar, force/torque sensors). + +Testing +------- +Before submitting your contributions, make sure that the changes do not break existing functionalities. We have a handful of tests for verifying the correctness of the code. + +You can run all the tests with the following command in the tests folder of robomimic. Make sure that it does not throw any error before you proceed to the next step. Note that the tests can take a few minutes to run. + +```sh +$ bash test.sh +``` + +Submission +---------- +Please read the coding conventions below and make sure that your code is consistent with ours. When making a contribution, make a [pull request](https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/proposing-changes-to-your-work-with-pull-requests) to robomimic with an itemized list of what you have done. When you submit a pull request, it is immensely helpful to include example script(s) that showcase the proposed changes and highlight any new APIs. We always love to see more test coverage. When it is appropriate, add a new test to the tests folder for checking the correctness of your code. + +Coding Conventions +------------------ +We value readability and adhere to the following coding conventions: +- Indent using four spaces (soft tabs) +- Always put spaces after list items and method parameters (e.g., `[1, 2, 3]` rather than `[1,2,3]`), and around operators and hash arrows (e.g., `x += 1` rather than `x+=1`) +- Use [Google Python Style](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings) for the docstrings +- For scripts such as in the `scripts` and `examples` folders, include a docstring at the top of the file that describes the high-level purpose of the script and/or instructions on how to use the scripts (if relevant). + +## Additional Coding Guidelines + +We also list additional suggested contributing guidelines that we adhered to during development. + +- When creating new networks (e.g. subclasses of `Module` in `models/base_nets.py`), always put sub-modules into a property called `self.nets`, and if there is more than one sub-module, make it a module collection (such as a `torch.nn.ModuleDict`). This is to ensure that the pattern `model.to(device)` works as expected with multiple levels of nested torch modules. As an example of nesting, see the `_create_networks` function in the `VAE` class (`models/vae_nets.py`) and the `MIMO_MLP` class (`models/obs_nets.py`). + +- Do not use default mutable arguments -- they can lead to terrible bugs and unexpected behavior (see [this link](https://florimond.dev/blog/articles/2018/08/python-mutable-defaults-are-the-source-of-all-evil/) for more information). For this reason, in functions that expect optional dictionaries and lists (for example, the `core_kwargs` argument in the `obs_encoder_factory` function, or the `layer_dims` argument in the `MLP` class constructor), we use a default argument of `core_kwargs=None` or an empty tuple (since tuples are immutable) `layer_dims=()`. + +- Prefer `torch.expand` over `torch.repeat` wherever possible, for memory efficiency. See [this link](https://discuss.pytorch.org/t/expand-vs-repeat-semantic-difference/59789) for more details. + +- When implementing new configs that specify kwargs that will be unpacked by a downstream python class (for example, the property `self.observation.encoder.rgb.core_kwargs` in the `BaseConfig` class, which is fed to the class specified by `self.observation.encoder.rgb.core_class`), the default config class should specify an empty config object (essentially an empty dictionary) for the kwargs. This is to make sure that external config jsons will be able to completely override both the class and the kwargs without worrying about existing default kwargs that could break the initialization of the class. For example, while the default `VisualCore` class takes a kwarg called `feature_dimension`, another class may not take this argument. If this kwarg already existed in the base config, the external json will just add additional kwargs. + + +We look forward to your contributions. Thanks! + +**The robomimic core team** + diff --git a/code_src/rise_robomimic/docs/miscellaneous/references.md b/code_src/rise_robomimic/docs/miscellaneous/references.md new file mode 100644 index 0000000000000000000000000000000000000000..351c34900ca7094e032fd6d3baca73e44fdddb58 --- /dev/null +++ b/code_src/rise_robomimic/docs/miscellaneous/references.md @@ -0,0 +1,50 @@ +# Projects using robomimic + +A list of projects and papers that use **robomimic**. If you would like to add your work to this list, please send the paper or project information to Ajay Mandlekar (). + +## 2023 + +- [Imitating Task and Motion Planning with Visuomotor Transformers](https://arxiv.org/abs/2305.16309). Murtaza Dalal, Ajay Mandlekar\*, Caelan Garrett\*, Ankur Handa, Ruslan Salakhutdinov, Dieter Fox +- [Data Quality in Imitation Learning](https://arxiv.org/abs/2306.02437). Suneel Belkhale, Yuchen Cui, Dorsa Sadigh +- [Coherent Soft Imitation Learning](https://arxiv.org/abs/2305.16498). Joe Watson, Sandy H. Huang, Nicolas Heess +- [Inverse Preference Learning: Preference-based RL without a Reward Function](https://arxiv.org/abs/2305.15363). Joey Hejna, Dorsa Sadigh +- [Sequence Modeling is a Robust Contender for Offline Reinforcement Learning](https://arxiv.org/abs/2305.14550). Prajjwal Bhargava, Rohan Chitnis, Alborz Geramifard, Shagun Sodhani, Amy Zhang +- [Diffusion Co-Policy for Synergistic Human-Robot Collaborative Tasks](https://arxiv.org/abs/2305.12171). Eley Ng, Ziang Liu, Monroe Kennedy III +- [Zero-shot Preference Learning for Offline RL via Optimal Transport](https://arxiv.org/abs/2306.03615). Runze Liu, Yali Du, Fengshuo Bai, Jiafei Lyu, Xiu Li +- [Seeing the Pose in the Pixels: Learning Pose-Aware Representations in Vision Transformers](https://arxiv.org/abs/2306.09331). Dominick Reilly, Aman Chadha, Srijan Das +- [Get Back Here: Robust Imitation by Return-to-Distribution Planning](https://arxiv.org/abs/2305.01400). Geoffrey Cideron, Baruch Tabanpour, Sebastian Curi, Sertan Girgin, Leonard Hussenot, Gabriel Dulac-Arnold, Matthieu Geist, Olivier Pietquin, Robert Dadashi +- [Preference Transformer: Modeling Human Preferences using Transformers for RL](https://arxiv.org/abs/2303.00957). Changyeon Kim, Jongjin Park, Jinwoo Shin, Honglak Lee, Pieter Abbeel, Kimin Lee +- [MimicPlay: Long-Horizon Imitation Learning by Watching Human Play](https://arxiv.org/abs/2302.12422). Chen Wang, Linxi Fan, Jiankai Sun, Ruohan Zhang, Li Fei-Fei, Danfei Xu, Yuke Zhu, Anima Anandkumar +- [Diffusion Policy: Visuomotor Policy Learning via Action Diffusion](https://arxiv.org/abs/2303.04137). Cheng Chi, Siyuan Feng, Yilun Du, Zhenjia Xu, Eric Cousineau, Benjamin Burchfiel, Shuran Song +- [ORBIT: A Unified Simulation Framework for Interactive Robot Learning Environments](https://arxiv.org/abs/2301.04195). Mayank Mittal, Calvin Yu, Qinxi Yu, Jingzhou Liu, Nikita Rudin, David Hoeller, Jia Lin Yuan, Pooria Poorsarvi Tehrani, Ritvik Singh, Yunrong Guo, Hammad Mazhar, Ajay Mandlekar, Buck Babich, Gavriel State, Marco Hutter, Animesh Garg +- [PLEX: Making the Most of the Available Data for Robotic Manipulation Pretraining](https://arxiv.org/abs/2303.08789). Garrett Thomas, Ching-An Cheng, Ricky Loynd, Vibhav Vineet, Mihai Jalobeanu, Andrey Kolobov +- [Behavior Retrieval: Few-Shot Imitation Learning by Querying Unlabeled Datasets](https://arxiv.org/abs/2304.08742). Maximilian Du, Suraj Nair, Dorsa Sadigh, Chelsea Finn +- [Mind the Gap: Offline Policy Optimization for Imperfect Rewards](https://arxiv.org/abs/2302.01667). Jianxiong Li, Xiao Hu, Haoran Xu, Jingjing Liu, Xianyuan Zhan, Qing-Shan Jia, Ya-Qin Zhang + +## 2022 + +- [Learning and Retrieval from Prior Data for Skill-based Imitation Learning](https://arxiv.org/abs/2210.11435). Soroush Nasiriany, Tian Gao, Ajay Mandlekar, Yuke Zhu +- [VIOLA: Imitation Learning for Vision-Based Manipulation with Object Proposal Priors](https://arxiv.org/abs/2210.11339). Yifeng Zhu, Abhishek Joshi, Peter Stone, Yuke Zhu +- [Robot Learning on the Job: Human-in-the-Loop Autonomy and Learning During Deployment](https://arxiv.org/abs/2211.08416). Huihan Liu, Soroush Nasiriany, Lance Zhang, Zhiyao Bao, Yuke Zhu +- [Data-Efficient Pipeline for Offline Reinforcement Learning with Limited Data](https://arxiv.org/abs/2210.08642). Allen Nie, Yannis Flet-Berliac, Deon R. Jordan, William Steenbergen, Emma Brunskill +- [Eliciting Compatible Demonstrations for Multi-Human Imitation Learning](https://arxiv.org/abs/2210.08073). Kanishk Gandhi, Siddharth Karamcheti, Madeline Liao, Dorsa Sadigh +- [Masked Imitation Learning: Discovering Environment-Invariant Modalities in Multimodal Demonstrations](https://arxiv.org/abs/2209.07682). Yilun Hao, Ruinan Wang, Zhangjie Cao, Zihan Wang, Yuchen Cui, Dorsa Sadigh +- [Know Your Boundaries: The Necessity of Explicit Behavioral Cloning in Offline RL](https://arxiv.org/abs/2206.00695). Wonjoon Goo, Scott Niekum +- [HEETR: Pretraining for Robotic Manipulation on Heteromodal Data](https://openreview.net/forum?id=1_XARk3k-M). Garrett Thomas, Andrey Kolobov, Ching-An Cheng, Vibhav Vineet, Mihai Jalobeanu +- [Translating Robot Skills: Learning Unsupervised Skill Correspondences Across Robots](https://proceedings.mlr.press/v162/shankar22a.html). Tanmay Shankar, Yixin Lin, Aravind Rajeswaran, Vikash Kumar, Stuart Anderson, Jean Oh +- [Active Predicting Coding: Brain-Inspired Reinforcement Learning for Sparse Reward Robotic Control Problems](https://arxiv.org/abs/2209.09174). Alexander Ororbia, Ankur Mali +- [Imitation Learning by Estimating Expertise of Demonstrators](https://arxiv.org/abs/2202.01288). Mark Beliaev, Andy Shih, Stefano Ermon, Dorsa Sadigh, Ramtin Pedarsani + +## 2021 + +- [RLDS: an Ecosystem to Generate, Share and Use Datasets in Reinforcement Learning](https://arxiv.org/abs/2111.02767). Sabela Ramos, Sertan Girgin, Léonard Hussenot, Damien Vincent, Hanna Yakubovich, Daniel Toyama, Anita Gergely, Piotr Stanczyk, Raphael Marinier, Jeremiah Harmsen, Olivier Pietquin, Nikola Momchev +- [Error-Aware Imitation Learning from Teleoperation Data for Mobile Manipulation](https://arxiv.org/abs/2112.05251). Josiah Wong, Albert Tung, Andrey Kurenkov, Ajay Mandlekar, Li Fei-Fei, Silvio Savarese, Roberto Martín-Martín +- [Generalization Through Hand-Eye Coordination: An Action Space for Learning Spatially-Invariant Visuomotor Control](https://arxiv.org/abs/2103.00375). Chen Wang, Rui Wang, Danfei Xu, Ajay Mandlekar, Li Fei-Fei, Silvio Savarese +- [Deep Affordance Foresight: Planning Through What Can Be Done in the Future](https://arxiv.org/abs/2011.08424). Danfei Xu, Ajay Mandlekar, Roberto Martín-Martín, Yuke Zhu, Silvio Savarese, Li Fei-Fei +- [Learning Multi-Arm Manipulation Through Collaborative Teleoperation](https://arxiv.org/abs/2012.06738). Albert Tung, Josiah Wong, Ajay Mandlekar, Roberto Martín-Martín, Yuke Zhu, Li Fei-Fei, Silvio Savarese +- [Learning to Generalize Across Long-Horizon Tasks from Human Demonstrations](https://arxiv.org/abs/2003.06085). Ajay Mandlekar\*, Danfei Xu\*, Roberto Martín-Martín, Silvio Savarese, Li Fei-Fei + +## 2020 + +- [Human-in-the-Loop Imitation Learning using Remote Teleoperation](https://arxiv.org/abs/2012.06733). Ajay Mandlekar, Danfei Xu, Roberto Martín-Martín, Yuke Zhu, Li Fei-Fei, Silvio Savarese +- [IRIS: Implicit Reinforcement without Interaction at Scale for Learning Control from Offline Robot Manipulation Data](https://arxiv.org/abs/1911.05321). Ajay Mandlekar, Fabio Ramos, Byron Boots, Silvio Savarese, Li Fei-Fei, Animesh Garg, Dieter Fox diff --git a/code_src/rise_robomimic/docs/miscellaneous/team.md b/code_src/rise_robomimic/docs/miscellaneous/team.md new file mode 100644 index 0000000000000000000000000000000000000000..16b784e0b88bed1339a9c91031008c0ae845c6aa --- /dev/null +++ b/code_src/rise_robomimic/docs/miscellaneous/team.md @@ -0,0 +1,22 @@ +# Team + +## Core Contributors + +These people contributed directly to the codebase and helped build it. + +- [Ajay Mandlekar](https://ai.stanford.edu/~amandlek/) +- [Danfei Xu](https://faculty.cc.gatech.edu/~danfei/) +- [Josiah Wong](https://www.jowo.me/about) +- [Soroush Nasiriany](http://snasiriany.me/) +- [Chen Wang](http://www.chenwangjeremy.net/) +- [Matthew Bronars](https://bronars.github.io/) + +## Mentors + +These people have guided the development of the framework. + +- [Roberto Martin-Martin](https://robertomartinmartin.com/) +- [Yuke Zhu](https://www.cs.utexas.edu/~yukez/) +- [Silvio Savarese](https://www.linkedin.com/in/silvio-savarese-97b76114/) +- [Fei-Fei Li](https://profiles.stanford.edu/fei-fei-li) + diff --git a/code_src/rise_robomimic/docs/miscellaneous/troubleshooting.md b/code_src/rise_robomimic/docs/miscellaneous/troubleshooting.md new file mode 100644 index 0000000000000000000000000000000000000000..189de42541181c6ec2c929705ee92db51c10b7e8 --- /dev/null +++ b/code_src/rise_robomimic/docs/miscellaneous/troubleshooting.md @@ -0,0 +1,15 @@ +# Troubleshooting + +## Common Mistakes + +This section will be populated with common mistakes and links to issues and fixes as we are made aware of them. + +If you're still having problems, please submit an issue on [the github page](https://github.com/ARISE-Initiative/robomimic/issues). + +## Known Issues + +This section contains known issues that are either minor, or that will be patched later. + +- `PrintLogger` breaks if you use `embed()` with a new-ish IPython installation. The current workaround is to use an old version. Known working version is `ipython==5.8.0` + +- On robomimic v0.2, the `test_scripts` tests will fail if `robosuite` is not on the `offline_study` branch with the following error: `No "site" with name gripper0_ee_x exists.`. This is because the test hdf5 was collected on that branch -- switching to that branch should make the test pass. \ No newline at end of file diff --git a/code_src/rise_robomimic/docs/model_zoo/robomimic_v0.1.md b/code_src/rise_robomimic/docs/model_zoo/robomimic_v0.1.md new file mode 100644 index 0000000000000000000000000000000000000000..d5ea855152595c425679e9b35a9bbfec81b88695 --- /dev/null +++ b/code_src/rise_robomimic/docs/model_zoo/robomimic_v0.1.md @@ -0,0 +1,81 @@ +# robomimic-v0.1 + +We provide links below to several pretrained models that were trained with robomimic-v0.1 for our CoRL 2021 study. All success rates listed below are approximate - they may vary. + +
+

Note: see tutorial on using these models

+ +See the ["Using Pretrained Models"](../tutorials/using_pretrained_models.html) tutorial for instructions on using these models. + +
+ +
+

Warning: use correct robomimic and robosuite versions!

+ +When using these trained models, please make sure that robosuite is on the [`offline_study` branch](https://github.com/ARISE-Initiative/robosuite/tree/offline_study), and that robomimic is on the [`v0.1` branch](https://github.com/ARISE-Initiative/robomimic/tree/v0.1). + +
+ +
+

Troubleshooting download issues

+ +Some users (eg. using Chrome) may experience issues with the dataset download links. If you are experiencing these issues, follow these steps: (1) right click on the download link, (2) select the option to copy the linked url, and (3) copy paste the link in a new tab. + +
+ +## Proficient-Human (PH) + +### Lift (PH) + +proficient_human + +#### BC-RNN + +- low-dim agent (success rate ~100%) ([download](http://downloads.cs.stanford.edu/downloads/rt_benchmark/model_zoo/lift/bc_rnn/lift_ph_low_dim_epoch_1000_succ_100.pth)) +- image agent (success rate ~100%) ([download](http://downloads.cs.stanford.edu/downloads/rt_benchmark/model_zoo/lift/bc_rnn/lift_ph_image_epoch_500_succ_100.pth)) + +### Can (PH) + +proficient_human + +#### BC-RNN + +- low-dim agent (success rate ~100%) ([download](http://downloads.cs.stanford.edu/downloads/rt_benchmark/model_zoo/can/bc_rnn/can_ph_low_dim_epoch_1150_succ_100.pth)) + +- image agent (success rate ~100%) ([download](http://downloads.cs.stanford.edu/downloads/rt_benchmark/model_zoo/can/bc_rnn/can_ph_image_epoch_300_succ_100.pth)) + + + +### Square (PH) + +proficient_human + +#### BC-RNN + +- low-dim agent (success rate ~84%) ([download](http://downloads.cs.stanford.edu/downloads/rt_benchmark/model_zoo/square/bc_rnn/square_ph_low_dim_epoch_1850_succ_84.pth)) + +- image agent (success rate ~78%) ([download](http://downloads.cs.stanford.edu/downloads/rt_benchmark/model_zoo/square/bc_rnn/square_ph_image_epoch_540_succ_78.pth)) + + + +### Transport (PH) + +proficient_human + +#### BC-RNN + +- low-dim agent (success rate ~78%) ([download](http://downloads.cs.stanford.edu/downloads/rt_benchmark/model_zoo/transport/bc_rnn/transport_ph_low_dim_epoch_1000_succ_78.pth)) + +- image agent (success rate ~70%) ([download](http://downloads.cs.stanford.edu/downloads/rt_benchmark/model_zoo/transport/bc_rnn/transport_ph_image_epoch_580_succ_70.pth)) + + + +### Tool Hang (PH) + +proficient_human + +#### BC-RNN + +- low-dim agent (success rate ~14%) ([download](http://downloads.cs.stanford.edu/downloads/rt_benchmark/model_zoo/tool_hang/bc_rnn/tool_hang_ph_low_dim_epoch_2000_succ_14.pth)) +- image agent (success rate ~ 50-74%) ([download](http://downloads.cs.stanford.edu/downloads/rt_benchmark/model_zoo/tool_hang/bc_rnn/tool_hang_ph_image_epoch_440_succ_74.pth)) + diff --git a/code_src/rise_robomimic/docs/modules/algorithms.md b/code_src/rise_robomimic/docs/modules/algorithms.md new file mode 100644 index 0000000000000000000000000000000000000000..dd0bfd4dffefc074d5eb3405844448fa983919ba --- /dev/null +++ b/code_src/rise_robomimic/docs/modules/algorithms.md @@ -0,0 +1,190 @@ +# Algorithms + +The `Algo` class is an abstraction used to make creating and training networks easy. + +### Initialization + +The standard entry point for creating `Algo` class instances is the `algo_factory` function in `algo/algo.py`. This uses a mapping from an algo name (e.g. `"bc"`) to a special `algo_config_to_class` function, that is responsible for reading an `algo_config` (`config.algo` section of the config) and returning the appropriate algo class name to instantiate, along with any additional keyword arguments needed. This is necessary because algorithms can actually have multiple subclasses with different functionality - for example, BC has the `BC_GMM` class for training GMM policies, and the `BC_RNN` class for training RNN policies. + +Therefore, every algorithm file (for example `algo/bc.py`) implements an `algo_config_to_class` function. The function should have the `register_algo_factory_func` decorator with the algo name (e.g. `"bc"`) - this registers the function into the registry used by `algo_factory`. The algo name should match the `ALGO_NAME` property in the corresponding config class for the algorithm (for BC, this is in the `BCConfig` class in `configs/bc_config.py`). The implementation from `algo/bc.py` is reproduced below. + +```python +@register_algo_factory_func("bc") +def algo_config_to_class(algo_config): + """ + Maps algo config to the BC algo class to instantiate, along with additional algo kwargs. + + Args: + algo_config (Config instance): algo config + + Returns: + algo_class: subclass of Algo + algo_kwargs (dict): dictionary of additional kwargs to pass to algorithm + """ + + # note: we need the check below because some configs import BCConfig and exclude + # some of these options + gaussian_enabled = ("gaussian" in algo_config and algo_config.gaussian.enabled) + gmm_enabled = ("gmm" in algo_config and algo_config.gmm.enabled) + vae_enabled = ("vae" in algo_config and algo_config.vae.enabled) + + if algo_config.rnn.enabled: + if gmm_enabled: + return BC_RNN_GMM, {} + return BC_RNN, {} + assert sum([gaussian_enabled, gmm_enabled, vae_enabled]) <= 1 + if gaussian_enabled: + return BC_Gaussian, {} + if gmm_enabled: + return BC_GMM, {} + if vae_enabled: + return BC_VAE, {} + return BC, {} +``` + + + +### Important Class Methods + +In this section, we outline important class methods that each `Algo` subclass needs to implement or override, categorizing them by whether they are usually called during initialization, at train time, or test time. + +- **Initialization** + - `_create_networks(self)` + - Called on class initialization - should construct networks and place them into the `self.nets` ModuleDict +- **Train** + - `process_batch_for_training(self, batch)` + - Takes a batch sampled from the data loader, and filters out the relevant portions needed for the algorithm. It should also send the batch to the correct device (cpu or gpu). + - `train_on_batch(self, batch, epoch, validate=False)` + - Takes a processed batch, and trains all networks on the batch of data, taking the epoch number and whether this is a training or validation batch into account. This is where the main logic for training happens (e.g. forward and backward passes for networks). Should return a dictionary of important training statistics (e.g. loss on the batch, gradient norms, etc.) + - `log_info(self, info)` + - Takes the output of `train_on_batch` and returns a new processed dictionary for tensorboard logging. + - `set_train(self)` + - Prepares network modules for training. By default, just calls `self.nets.train()`, but certain algorithms may always want a subset of the networks in evaluation mode (such as target networks for BCQ). In this case they should override this method. + - `on_epoch_end(self, epoch)` + - Called at the end of each training epoch. Usually consists of stepping learning rate schedulers (if they are being used). + - `serialize(self)` + - Returns the state dictionary that contains the current model parameters. This is used to produce agent checkpoints. By default, returns `self.nets.state_dict()` - usually only needs to be overriden by hierarchical algorithms like HBC and IRIS to collect state dictionaries from sub-algorithms. +- **Test** + - `set_eval(self)` + - Prepares network modules for evaluation. By default, just calls `self.nets.eval()`, but certain hierarchical algorithms like HBC and IRIS override this to call `set_eval` on their sub-algorithms. + - `deserialize(self, model_dict)` + - Inverse operation of `serialize` - load model weights. Used at test-time to restore model weights. + - `get_action(self, obs_dict, goal_dict=None)` + - The primary method that is called at test-time to return one or more actions, given observations. + - `reset(self)` + - Called at the beginning of each rollout episode to clear internal agent state before starting a rollout. As an example, `BC_RNN` resets the step counter and hidden state. + +### Train Loop + +We reproduce the stripped down version of the train loop from `examples/simple_train_loop.py` to show how methods of `Algo` instances are used during training. + +```python +# @model should be instance of Algo class to use for training +# @data_loader should be instance of torch.utils.data.DataLoader for sampling batches + +# train for 50 epochs and 100 gradient steps per epoch +num_epochs = 50 +gradient_steps_per_epoch = 100 + +# ensure model is in train mode +model.set_train() + +for epoch in range(1, num_epochs + 1): # epoch numbers start at 1 + # iterator for data_loader - it yields batches + data_loader_iter = iter(data_loader) + + # record losses + losses = [] + + for _ in range(gradient_steps_per_epoch): + + # load next batch from data loader + try: + batch = next(data_loader_iter) + except StopIteration: + # data loader ran out of batches - reset and yield first batch + data_loader_iter = iter(data_loader) + batch = next(data_loader_iter) + + # process batch for training + input_batch = model.process_batch_for_training(batch) + + # forward and backward pass + info = model.train_on_batch(batch=input_batch, epoch=epoch, validate=False) + + # record loss + step_log = model.log_info(info) + losses.append(step_log["Loss"]) + + # save model + model_params = model.serialize() + model_dict = dict(model=model.serialize()) + torch.save(model_dict, /path/to/ckpt.pth) + + # do anything model needs to after finishing epoch + model.on_epoch_end(epoch) +``` + + + +### Test Time + +We reproduce some logic from the `policy_from_checkpoint` function defined in `utils/file_utils.py` to show how `Algo` methods are used to load a model. + +```python +# load checkpoint +ckpt_dict = maybe_dict_from_checkpoint(ckpt_path=/path/to/ckpt.pth) +algo_name = ckpt_dict["algo_name"] +config, _ = config_from_checkpoint(algo_name=algo_name, ckpt_dict=ckpt_dict) + +# create Algo instance +model = algo_factory( + algo_name, + config, + obs_key_shapes=ckpt_dict["shape_metadata"]["all_shapes"], + ac_dim=ckpt_dict["shape_metadata"]["ac_dim"], + device=device, +) + +# load weights +model.deserialize(ckpt_dict["model"]) +model.set_eval() + +# rollout wrapper around model +model = RolloutPolicy(model) +``` + +We also reproduce a rollout loop to show how the `RolloutPolicy` wrapper (see `algo/algo.py`) is used to easily deploy trained models in the environment. + +```python +# @policy should be instance of RolloutPolicy +assert isinstance(policy, RolloutPolicy) + +# episode reset (calls @set_eval and @reset) +policy.start_episode() +obs = env.reset() + +horizon = 400 +total_return = 0 +for step_i in range(horizon): + # get action from policy (calls @get_action) + act = policy(obs) + # play action + next_obs, r, done = env.step(act) + total_return += r + success = env.is_success()["task"] + if done or success: + break +``` + + + +## Implemented Algorithms + +Refer [here](../introduction/implemented_algorithms.html) for the list of algorithms currently implemented in robomimic + + + +## Building your own Algorithm + +Learn how to implement your own learning algorithm [here](../tutorials/custom_algorithms.html) diff --git a/code_src/rise_robomimic/docs/modules/configs.md b/code_src/rise_robomimic/docs/modules/configs.md new file mode 100644 index 0000000000000000000000000000000000000000..b5043795f4992bc71d867ea944dba995c53e1810 --- /dev/null +++ b/code_src/rise_robomimic/docs/modules/configs.md @@ -0,0 +1,113 @@ +# Configs + +Configs are instances of the `Config` class defined in `config/config.py`. The implementation is largely based on [addict](https://github.com/mewwts/addict), which makes working with nested dictionaries convenient. At their core, configs are essentially nested dictionaries (similar to loaded json objects), with an easy way to access and set nested keys by using attributes. See the example below: + +```python +from robomimic.config import Config + +# normal way to create nested dictionaries and read values +c = dict() +c["experiment"] = dict() +c["experiment"]["save"] = dict() +c["experiment"]["save"]["enabled"] = True +print("save enabled: {}".format(c["experiment"]["save"]["enabled"])) + +# can use dot syntax instead of key lookup to create nested dictionaries +c = Config() +c.experiment.save.enabled = True + +# can also use dot syntax to access attributes +print("save enabled: {}".format(c.experiment.save.enabled)) +``` + +It's easy to go back and forth between `Config` objects and jsons as well, which is convenient when saving config objects to disk (this happens when generating new config jsons for training, and when saving the config in a model checkpoint), and loading configs from jsons. + +```python +# dump config as a json string +json_string = c.dump() + +# dump config to a json file +c.dump(filename="c.json") + +# load config from json +import json +json_dic = json.load(json_string) +c = Config(json_dic) +``` + +All algorithm config classes (one class per algorithm type) are subclasses of the `BaseConfig` class (defined in `config/base_config.py`), which is a subclass of the general `Config` class. The algorithm config classes are kept in a global registry (more details on this later). The `generate_config_templates.py` script uses the functionality demonstrated above to easily generate template config jsons for each algorithm, by instantiating the default config object per class. **This script should be run any time changes are made to default settings, or new config settings are added.** We reproduce the code snippet below. + +```python +import os +import json +import robomimic +from robomimic.config import get_all_registered_configs + +# store template config jsons in this directory +target_dir = os.path.join(robomimic.__path__[0], "exps/templates/") + +# iterate through registered algorithm config classes +all_configs = get_all_registered_configs() +for algo_name in all_configs: + # make config class for this algorithm + c = all_configs[algo_name]() + # dump to json + json_path = os.path.join(target_dir, "{}.json".format(algo_name)) + c.dump(filename=json_path) +``` + +We now go over the general structure of algorithm config classes by dicusssing the `BaseConfig` class, which has more specific functionality than the general `Config` class for use with this repository. + +## Config Factory + +The `BaseConfig` class has a property and classmethod called `ALGO_NAME` that must be filled out by all subclasses -- this should correspond to the algorithm name for each config, and should match the algorithm name that is passed to `register_algo_factory_func` at the top of each algorithm implementation file. For example, for `BCConfig`, `ALGO_NAME = "bc"`. This property is important in order to make sure that all configs that subclass `BaseConfig` get registered into the `REGISTERED_CONFIGS` global registry (`ALGO_NAME` is used as a key to register the class into the registry). This also allows the `config_factory` function to easily create the appropriate config class for an algorithm -- **this is the standard entry point for creating config objects in the codebase**. While config jsons can also be used to load configs during training (as discussed in the Quick Start section of the documentation), the `config_factory` function is still used to create an initial config object, which is then updated (see the example below). + +```python +import json +from robomimic.config import config_factory + +# base config for algorithm with default values +config = config_factory("bc") + +# update defaults with config json +with open("/path/to/config.json", "r") as f: + ext_config_json = json.load(f) +config.update(ext_config_json) +``` + +At test-time, when loading a model from a checkpoint, the config is restored by reading the json string from the checkpoint, and then using it to instantiate the config. An example is below (modified slightlyt from `config_from_checkpoint` in `utils/file_utils.py`) + +```python +import robomimic.utils.file_utils as FileUtils +ckpt_dict = FileUtils.load_dict_from_checkpoint("path/to/ckpt.pth") +config_json = ckpt_dict["config"] +config = config_factory(ckpt_dict["algo_name"], dic=json.loads(config_json)) +``` + +## Config Structure + +The `BaseConfig` class (and all subclasses) have 4 important sections that need to be filled out -- each is a method of the config class. See `config/base_config.py` (and the relevant algorithm config files like `config/bc_config.py`) for details on the specific settings under each section. + +- `experiment_config(self)` + - This function populates the `config.experiment` attribute of the config, which has several experiment settings such as the name of the training run, whether to do logging, whether to save models (and how often), whether to render videos, and whether to do rollouts (and how often). The `BaseConfig` class has a default implementation that usually doesn't need to be overriden. +- `train_config(self)` + - This function populates the `config.train` attribute of the config, which has several settings related to the training process, such as the dataset to use for training, and how the data loader should load the data. The `BaseConfig` class has a default implementation that usually doesn't need to be overriden. +- `algo_config(self)` + - This function populates the `config.algo` attribute of the config, and is given to the `Algo` subclass (see `algo/algo.py`) for each algorithm through the `algo_config` argument to the constructor. Any parameter that an algorithm needs to determine its training and test-time behavior should be populated here. This function should be implemented by every subclass. +- `observation_config(self)` + - This function populates the `config.observation` attribute of the config, and is given to the `Algo` subclass (see `algo/algo.py`) for each algorithm through the `obs_config` argument to the constructor. This portion of the config is used to specify what observation modalities should be used by the networks for training, and how the observation modalities should be encoded by the networks. While the `BaseConfig` class has a default implementation that usually doesn't need to be overriden, certain algorithm configs may choose to, in order to have seperate configs for different networks in the algorithm. + +## Config Locking + +To prevent accidental config modification, each `Config` object implements a two-level locking mechanism: _key-locked_ and _all-locked_. A `Config` object can be put into the _key-locked_ state by calling `config.lock_keys()`. Under the _key-locked_ state, a `Config` object does not allow adding new keys but only changing the values of existing keys. A `Config` object can be put into the _all-locked_ state by calling `config.lock()`. In this state, the object does not allow adding new keys nor changing existing values. + +All `Config` objects that inherit the constructor of `BaseConfig` are _key-locked_ by default. Upon finishing constructing the object, it is recommended to put the config object into the _all-locked_ state by calling `config.lock()`. `Config` objects also implement context manager functions that allow convenient and controlled config modification within a scope. + +- `value_unlocked()` + - This context scope allows values of existing keys to be modified if the `Config` object is _all-locked_. +- `unlocked()` + - This context scope allows new keys to be added as well as values of existing keys to be modified, regardless of the locking state. + +## Minimum Example + +Please see the [config tutorial](../tutorials/configs.html) for more information on how to use the Config object, and examples on how the locking mechanism works. diff --git a/code_src/rise_robomimic/docs/modules/dataset.md b/code_src/rise_robomimic/docs/modules/dataset.md new file mode 100644 index 0000000000000000000000000000000000000000..4c2510e2c3edd65c28e2efd591be4d51f69be138 --- /dev/null +++ b/code_src/rise_robomimic/docs/modules/dataset.md @@ -0,0 +1,54 @@ +# SequenceDataset + +The `robomimic.utils.dataset.SequenceDataset` class extends PyTorch's default `torch.utils.data.Dataset` to interface with our demonstration [datasets](../datasets/overview.html). The class supports accessing demonstration sub-sequences (as opposed to individual states) by index and both on-demand fetching and in-memory caching. This page walks through the key concepts of the `SequenceDataset` interface. Please refer to the official PyTorch [documentation](https://pytorch.org/docs/stable/data.html) and a short [example](https://github.com/ARISE-Initiative/robomimic/blob/master/examples/simple_train_loop.py) on how to use the `Dataset` and `DataLoader` interfaces to build a training pipeline. + + +Here is a sample dataset object: + +```python +dataset = SequenceDataset( + hdf5_path=dataset_path, + obs_keys=( # observations we want to appear in batches + "robot0_eef_pos", + "robot0_eef_quat", + "image", + "object", + ), + dataset_keys=( # can optionally specify more keys here if they should appear in batches + "actions", + "rewards", + "dones", + ), + seq_length=10, # length of sub-sequence to fetch: (s_{t}, a_{t}), (s_{t+1}, a_{t+1}), ..., (s_{t+9}, a_{t+9}) + frame_stack=1, # length of sub-sequence to prepend + pad_seq_length=True, # pad last obs per trajectory to ensure all sequences are sampled + pad_frame_stack=True, # pad first obs per trajectory to ensure all sequences are sampled + hdf5_cache_mode="all", # cache dataset in memory to avoid repeated file i/o + hdf5_normalize_obs=False, + filter_by_attribute=None, # can optionally provide a filter key here +) +``` + +- `hdf5_path` + - The absolute / relative path to the hdf5 file containing training demonstrations. See the [datasets page](../datasets/overview.html#dataset-structure) for the expected data structure. +- `obs_keys` + - A list of strings specifying which observation modalities to read from the dataset. This is typically read from the config file: our implementation pools observation keys from `config.observation.modalities.obs.low_dim` and `config.observation.modalities.obs.rgb`. +- `dataset_keys` + - Keys of non-observation data to read from a demonstration. Typically include `actions`, `rewards`, `dones`. +- `seq_length` + - Length of demonstration sub-sequence to fetch. For example, if `seq_length = 10` at time `t`, the data loader will fetch ${(s_{t}, a_{t}), (s_{t+1}, a_{t+1}), ..., (s_{t+9}, a_{t+9})}$ +- `frame_stack` + - Length of sub-sequence to stack at the beginning of fetched demonstration. For example, if `frame_stack = 10` at time `t`, the data loader will fetch ${(s_{t-1}, a_{t-1}), (s_{t-2}, a_{t-2}), ..., (s_{t-9}, a_{t-9})}$. Note that the actual length of the fetched sequence is `frame_stack - 1`. This term is useful when training a model to predict `seq_length` actions from `frame_stack` observations. If training a transformer, this should be the same as context length. +- `pad_seq_length` + - Whether to allow fetching subsequence that ends beyond the sequence. For example, given a demo of length 10 and `seq_length=10`, setting `pad_seq_length=True` allows the dataset object to access subsequence at `__get_item(index=5)__` by repeating the last frame 5 times. +- `pad_frame_stack` + - Whether to allow fetching subsequence that starts before the first time step. For example, given a demo of length 10 and `frame_stack=10`, setting `pad_frame_stack=True` allows the dataset object to access subsequence at `__get_item(index=5)__` by repeating the first frame 5 times. +- `hdf5_cache_mode` + - Optionally cache the dataset in memory for faster access. The dataset supports three caching modes: `["all", "low_dim", or None]`. + - `all`: Load the entire dataset into the RAM. This mode minimizes data loading time but incurs the largest memory footprint. Recommended if the dataset is small or when working with low-dimensional observation data. + - `low_dim`: Load only the low-dimensional observations into RAM. Always use this mode when possible as loading low-dim data incurs nontrivial overhead. Low-dim observations are specified at `config.observation.modalities.obs.low_dim`. + - `None`: Always fetch data on-demand. +- `hdf5_normalize_obs` + - If `True`, normalize observations by computing the mean observation and std of each observation (in each dimension and modality), and normalizing unit mean and variance in each dimension. +- `filter_by_attribute` + - if provided, use the provided filter key to look up a subset of demonstrations to load. See the documentation on [filter keys](../datasets/overview.html#filter-keys) for more information. diff --git a/code_src/rise_robomimic/docs/modules/environments.md b/code_src/rise_robomimic/docs/modules/environments.md new file mode 100644 index 0000000000000000000000000000000000000000..59c4808ae6c99ffdfdc8c8333f24097aca657298 --- /dev/null +++ b/code_src/rise_robomimic/docs/modules/environments.md @@ -0,0 +1,180 @@ +# Environments + +**robomimic** interfaces trained policy models with standard simulated environments such as [robosuite](https://robosuite.ai/) and [OpenAI-Gym](https://gym.openai.com/) through a standardized wrapper class. The base wrapper is located at `envs.env_base`. The standard entry point for creating an environment is through the `create_env_from_metadata` function located at `robomimic.utils.env_utils`: + +```python +def create_env_from_metadata( + env_meta, + render=False, + render_offscreen=False, + use_image_obs=False, +): + """ + Create environment. + + Args: + env_meta (dict): environment metadata, which should be loaded from demonstration + hdf5 with @FileUtils.get_env_metadata_from_dataset or from checkpoint (see + @FileUtils.env_from_checkpoint). Contains 3 keys: + + :`'env_name'`: name of environment + :`'type'`: type of environment, should be a value in EB.EnvType + :`'env_kwargs'`: dictionary of keyword arguments to pass to environment constructor + + render (bool): if True, environment supports on-screen rendering + + render_offscreen (bool): if True, environment supports off-screen rendering. This + is forced to be True if @use_image_obs is True. + + use_image_obs (bool): if True, environment is expected to render rgb image observations + on every env.step call. Set this to False for efficiency reasons, if image + observations are not required. + """ + if env_name is None: + env_name = env_meta["env_name"] + env_type = get_env_type(env_meta=env_meta) + env_kwargs = env_meta["env_kwargs"] + + env = create_env( + env_type=env_type, + env_name=env_name, + render=render, + render_offscreen=render_offscreen, + use_image_obs=use_image_obs, + **env_kwargs, + ) + return env +``` + +`env_meta` is a dictionary containing three keys: `'env_name'`, `'type'`, and `'env_kwargs'`. +- `env_name` specifies the unique identifier of the environment. For example, in `EnvGym`, `env_name` is the full environment name such as `Hopper-v2`. +- `type` is an enum defined in `robomimicenvs.env_base.EnvType` that specifies the type of environment. `type` is mainly used by the `robomimic.utils.env_utils.get_env_class()` function to look up the correct environment wrapper class. +- `env_kwargs` specifies the keyword args that are required to initialize an environment. The `env_kwargs` will be passed to the constructor of the wrapped environment as keyword arguments through the `robomimic.utils.env_utils.create_env()` helper function. + +Although it is possible to manually specify the `env_meta` dictionary, the **robomimic** training pipeline reads the `env_meta` from the hdf5 dataset as an attribute. Please refer to the [Dataset section](../datasets/overview.html#dataset-structure) for more details on where the metadata is stored, and the `robomimic.utils.file_utils.get_env_metadata_from_dataset` function to see how it is loaded from the dataset at run-time. + + +## Initialize an Environment from a Dataset +The demonstration dataset file should contain all necessary information to construct an environment. Here is standalone example for initializing a `EnvRobosuite` environment instance by reading environment metadata from the a dataset. + +```python +import robomimic.utils.env_utils as EnvUtils +import robomimic.utils.file_utils as FileUtils + +env_meta = FileUtils.get_env_metadata_from_dataset("path/to/the/dataset.hdf5") + +env = EnvUtils.create_env_from_metadata( + env_meta=env_meta, + env_name=env_name, + render=False, + render_offscreen=False, + use_image_obs=False, +) +``` + +The repo offers a simple utility tool `robomimic/scripts/get_dataset_info.py` to view the environment metadata included in a dataset. For example: +```bash +$ python robomimic/scripts/get_dataset_info.py --dataset path/to/the/dataset.hdf5 + +... + +==== Env Meta ==== +{ + "env_name": "Lift", + "type": 1, + "env_kwargs": { + "has_renderer": false, + "has_offscreen_renderer": true, + "ignore_done": true, + "use_object_obs": true, + "use_camera_obs": true, + "control_freq": 20, + "controller_configs": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [ + 0.05, + 0.05, + 0.05, + 0.5, + 0.5, + 0.5 + ], + "output_min": [ + -0.05, + -0.05, + -0.05, + -0.5, + -0.5, + -0.5 + ], + "kp": 150, + "damping": 1, + "impedance_mode": "fixed", + "kp_limits": [ + 0, + 300 + ], + "damping_limits": [ + 0, + 10 + ], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "control_delta": true, + "interpolation": null, + "ramp_ratio": 0.2 + }, + "robots": [ + "Panda" + ], + "camera_depths": false, + "camera_heights": 84, + "camera_widths": 84, + "reward_shaping": false, + "camera_names": [ + "agentview", + "robot0_eye_in_hand" + ], + "render_gpu_device_id": 0 + } +} + +... + +``` + + + +## Implement an Environment Wrapper + +While we provide wrappers for [robosuite](https://robosuite.ai/) environments and several standard [OpenAI-Gym](https://gym.openai.com/) environments, it is possible to implement your own wrapper for a new type of environment (for example, perhaps [PyBullet](https://pybullet.org/wordpress/)). This is useful if you have your own hdf5 dataset collected in this type of environment, and would like to conduct evaluation rollouts during the training process (note that no environment is needed if `config.experiment.rollout.enabled` is set to `False`). To do this, in addition to implementing a wrapper class by inheriting the `EnvBase` class, you will also need to (1) add a new environment type in the `robomimic.envs.env_base.EnvType` enum class and (2) modify `get_env_type()` and `get_env_class()` in `robomimic.utils.env_utils` to allow the environment class to be found automatically. + +Below we outline important methods that each `EnvBase` subclass needs to implement or override. The implementation mostly follows the OpenAI-Gym convention. + +- `__init__(self, ...)` + - Create the wrapped environment instance and assign it to `self.env`. For example, in `EnvGym` it simply calls `self.env = gym.make(env_name, **kwargs)`. Refer to `EnvRobosuite` as an example of handling the constructor arguments. +- `step(self, action)` + - Take a step in the environment with an input action, return `(observation, reward, done, info)`. +- `reset(self)` + - Reset the environment, return `observation` +- `render(self, mode="human", height=None, width=None, camera_name=None, **kwargs)` + - Render the environment if `mode=='human'`. Return an RGB array if `mode=='rgb_array'` +- `get_observation(self, obs=None)` + - Return the current environment observation as a dictionary, unless `obs` is not None. This function should process the raw environment observation to align with the input expected by the policy model. For example, it should cast an image observation to float with value range `0-1` and shape format `[C, H, W]`. +- `is_success(self)` + - Check if the task condition(s) is reached. Should return a dictionary { str: bool } with at least a "task" key for the overall task success, and additional optional keys corresponding to other task criteria. +- `serialize(self)` + - Aggregate and return all information needed to re-instantiate this environment in a dictionary. This is the same as @env_meta - environment metadata stored in hdf5 datasets and used in `robomimic/utils/env_utils.py`. +- `create_for_data_processing(cls, ...)` + - (Optional) A class method that initialize an environment for data-postprocessing purposes, which includes extracting observations, labeling dense / sparse rewards, and annotating dones in transitions. This function should at least designate the list of observation modalities that are image / low-dimensional observations by calling `robomimic.utils.obs_utils.initialize_obs_utils_with_obs_specs()`. +- `get_goal(self)` + - (Optional) Get goal for a goal-conditional task +- `set_goal(self, goal)` + - (optional) Set goal with external specification +- `get_state(self)` + - (Optional) This function should return the underlying state of a simulated environment. Should be compatible with `reset_to`. +- `reset_to(self, state)` + - (Optional) Reset to a specific simulator state. Useful for reproducing results. \ No newline at end of file diff --git a/code_src/rise_robomimic/docs/modules/models.md b/code_src/rise_robomimic/docs/modules/models.md new file mode 100644 index 0000000000000000000000000000000000000000..b9c18af259a56af2fa71670db930f66294b50948 --- /dev/null +++ b/code_src/rise_robomimic/docs/modules/models.md @@ -0,0 +1,216 @@ +# Models + +

+ +

+ +**robomimic** implements a suite of reusable network modules at different abstraction levels that make creating new policy models easy. + + +## Base Modules +To support automated shape resolution when dealing with multiple modalities, all basic modules such as MLP and ConvNets defined in `robomimic.models.base_nets` are a subclass of `robomimic.models.base_nets.Module`, which requires implementing the abstract method `output_shape(self, input_shape=None)`. The function resolves the output shape (excluding the batch dimension) of the module either based on an external `input_shape` or internal instance variables. To implement new base modules, simply inherit `robomimic.models.Module` or `robomimic.models.ConvBase` (if adding a ConvNet) and implement the abstract functions. Below is a sample implementation of a ResNet-18 base module. + +```python +from robomimic.models.base_nets import ConvBase + +class ResNet18Conv(ConvBase): + + ... + + def output_shape(self, input_shape): + """ + Function to compute output shape from inputs to this module. + + Args: + input_shape (iterable of int): shape of input. Does not include batch dimension. + Some modules may not need this argument, if their output does not depend + on the size of the input, or if they assume fixed size input. + + Returns: + out_shape ([int]): list of integers corresponding to output shape + """ + assert(len(input_shape) == 3) + out_h = int(math.ceil(input_shape[1] / 32.)) + out_w = int(math.ceil(input_shape[2] / 32.)) + return [512, out_h, out_w] +``` + +## EncoderCore +We create the `EncoderCore` abstract class to encapsulate any network intended to encode a specific type of observation modality (e.g.: `VisualCore` for RGB and depth observations, and `ScanCore` for range scanner observations. See below for descriptions of both!). When a new encoder class is subclassed from `EncoderCore`, it will automatically be registered internally in robomimic, allowing the user to directly refer to their custom encoder classes in their config in string form. For example, if the user specifies a custom `EncoderCore`-based class named `MyCustomRGBEncoder` to encode RGB observations, they can directly set this in their config: + +```python +config.observation.encoder.rgb.core_class = "MyCustomRGBEncoder" +config.observation.encoder.rgb.core_kwargs = ... +``` + +Any corresponding keyword arguments that should be passed to the encoder constructor should be specified in `core_kwargs` in the config. For more information on creating your own custom encoder, please see our [example script](https://github.com/ARISE-Initiative/robomimic/blob/master/examples/simple_obs_nets.py). + +Below, we provide descriptions of specific EncoderCore-based classes used to encode RGB and depth observations (`VisualCore`) and range scanner observations (`ScanCore`). + + +### VisualCore +We provide a `VisualCore` module for constructing custom vision architectures. A `VisualCore` consists of a backbone network that featurizes image input --- typically a `ConvBase` module --- and a pooling module that reduces the feature tensor into a fixed-sized vector representation. Below is a `VisualCore` built from a `ResNet18Conv` backbone and a `SpatialSoftmax` ([paper](https://rll.berkeley.edu/dsae/dsae.pdf)) pooling module. + +```python +from robomimic.models.obs_core import VisualCore +from robomimic.models.base_nets import ResNet18Conv, SpatialSoftmax + +vis_net = VisualCore( + input_shape=(3, 224, 224), + core_class="ResNet18Conv", # use ResNet18 as the visualcore backbone + core_kwargs={"pretrained": False, "input_coord_conv": False}, # kwargs for the ResNet18Conv class + pool_class="SpatialSoftmax", # use spatial softmax to regularize the model output + pool_kwargs={"num_kp": 32}, # kwargs for the SpatialSoftmax --- use 32 keypoints + flatten=True, # flatten the output of the spatial softmax layer + feature_dimension=64, # project the flattened feature into a 64-dim vector through a linear layer +) +``` + +New vision backbone and pooling classes can be added by subclassing `ConvBase`. + + +### ScanCore +We provide a `ScanCore` module for constructing custom range finder architectures. `ScanCore` consists of a 1D Convolution backbone network (`Conv1dBase`) that featurizes a high-dimensional 1D input, and a pooling module that reduces the feature tensor into a fixed-sized vector representation. Below is an example of a `ScanCore` network with a `SpatialSoftmax` ([paper](https://rll.berkeley.edu/dsae/dsae.pdf)) pooling module. + +```python +from robomimic.models.obs_core import ScanCore +from robomimic.models.base_nets import SpatialSoftmax + +vis_net = ScanCore( + input_shape=(1, 120), + conv_kwargs={ + "out_channels": [32, 64, 64], + "kernel_size": [8, 4, 2], + "stride": [4, 2, 1], + }, # kwarg settings to pass to individual Conv1d layers + conv_activation="relu", # use relu in between each Conv1d layer + pool_class="SpatialSoftmax", # use spatial softmax to regularize the model output + pool_kwargs={"num_kp": 32}, # kwargs for the SpatialSoftmax --- use 32 keypoints + flatten=True, # flatten the output of the spatial softmax layer + feature_dimension=64, # project the flattened feature into a 64-dim vector through a linear layer +) +``` + + +## Randomizers + +Randomizers are `Modules` that perturb network inputs during training, and optionally during evaluation. A `Randomizer` implements a `forward_in` and a `forward_out` function, which are intended to process the input and output of a neural network module. As an example, the `forward_in` function of a `CropRandomizer` instance perturbs an input image by taking a random crop of the image (as shown in th gif below). If the `CropRandomizer` is configured to take more than one random crop (`n_crops > 1`) of each input image, it will send all random crops through the image network and reduce the network output by average pooling the outputs along the `n_crops` dimension in the `forward_out` function. + +Image illustration of a CropRandomizer + +`Randomizer` modules are intended to be used alongside an `ObservationEncoder` --- see the next section for more details. Additional randomizer classes can be implemented by subclassing the `Randomizer` class and implementing the necessary abstract functions. + +**Visualizing randomized input:** To visualize the original and randomized image input, set `VISUALIZE_RANDOMIZER = True` in `robomimic/macros.py` + +## Observation Encoder and Decoder + `ObservationEncoder` and `ObservationDecoder` are basic building blocks for dealing with observation dictionary inputs and outputs. They are designed to take in multiple streams of observation modalities as input (e.g. a dictionary containing images and robot proprioception signals), and output a dictionary of predictions like actions and subgoals. Below is an example of how to manually create an `ObservationEncoder` instance by registering observation modalities with the `register_obs_key` function. + +```python +from robomimic.models.base_nets import MLP +from robomimic.models.obs_core import VisualCore, CropRandomizer +from robomimic.models.obs_nets import ObservationEncoder, ObservationDecoder + +obs_encoder = ObservationEncoder(feature_activation=torch.nn.ReLU) + +# There are two ways to construct the network for processing a input modality. +# Assume we are processing image input of shape (3, 224, 224). +camera1_shape = [3, 224, 224] + +image_randomizer = CropRandomizer(input_shape=camera2_shape, crop_height=200, crop_width=200) + +# We will use a reconfigurable image processing backbone VisualCore to process the input image modality +net_class = "VisualCore" # this is defined in models/base_nets.py + +# kwargs for VisualCore network +net_kwargs = { + "input_shape": camera1_shape, + "core_class": "ResNet18Conv", # use ResNet18 as the visualcore backbone + "core_kwargs": {"pretrained": False, "input_coord_conv": False}, + "pool_class": "SpatialSoftmax", # use spatial softmax to regularize the model output + "pool_kwargs": {"num_kp": 32} +} + +# register the network for processing the modality +obs_encoder.register_obs_key( + name="camera1", + shape=camera1_shape, + net_class=net_class, + net_kwargs=net_kwargs, + randomizer=image_randomizer +) + +# We could mix low-dimensional observation, e.g., proprioception signal, in the encoder +proprio_shape = [12] +net = MLP(input_dim=12, output_dim=32, layer_dims=(128,), output_activation=None) +obs_encoder.register_obs_key( + name="proprio", + shape=proprio_shape, + net=net +) +``` + +By default, each modality network should reduce an input observation stream to a fixed-size vector. The output of the `forward` function of the `ObservationEncoder` is simply the concatenation of all the vectors. The order of concatenation is deterministic and is the the same as the order that the modalities are registered. `ObservationGroupEncoder` further supports encoding nested groups of observations, e.g., `obs`, `goal`, and `subgoal`. This allows constructing goal-conditioned and / or subgoal-conditioned policy models. + +However, it can be tedious to enumerate all modalities when creating a policy model. The standard entry point to create an `ObservationEncoder` is via the `observation_encoder_factory` function in `robomimic.models.obs_nets`. It will enumerate all observation modalities and initialize all modality networks according to the configurations provided by the `config.observation` config section. + +The `ObservationDecoder` class is relatively straightforward. It's simply a single-input, multi-output-head MLP. For example, the following snippet creates an `ObservationDecoder` that takes the output of the observation encoder as input and outputs two action predictions. + +```python +obs_decoder = ObservationDecoder( + input_feat_dim=obs_encoder.output_shape()[0], + decode_shapes=OrderedDict({"action_pos": (3,), "action_orn": (4,)}) +) +``` + +See `examples/simple_obs_nets.py` for the complete example that shows additional functionalities such as weight sharing among modality networks. + + +## Multi-Input, Multi-Output (MIMO) Modules +`MIMO_MLP` and `RNN_MIMO_MLP` are highest-level wrappers that use `ObservationGroupEncoder` and `ObservationDecoder` to create multi-input, multi-output network architectures. `MIMO_MLP` optionally adds additional MLP layers before piping the encoded feature vector to the decoder. + +`RNN_MIMO_MLP` encodes each observation in an observation sequence using `ObservationGroupEncoder` and digests the feature sequence using RNN-variants such as LSTM and GRU networks. + +`MIMO_MLP` and `RNN_MIMO_MLP` serve as **the backbone for all policy and value network models** -- these models simple subclass a `MIMO_MLP` or `RNN_MIMO_MLP`, and adds specific input and output shapes. + +## Implemented Policy Networks + +These networks take an observation dictionary as input (and possibly additional conditioning, such as subgoal or goal dictionaries) and produce action predictions, samples, or distributions as outputs. Note that actions are assumed to lie in `[-1, 1]`, and most networks will have a final `tanh` activation to help ensure that outputs lie within this range. See `robomimic/models/policy_nets.py` for complete implementations. + +### ActorNetwork +- A basic policy network that predicts actions from observations. Can optionally be goal conditioned on future observations. +### PerturbationActorNetwork +- An action perturbation network - primarily used in BCQ. It takes states and actions and returns action perturbations. +### GaussianActorNetwork +- Variant of actor network that outputs a diagonal unimodal Gaussian distribution as action predictions. +### GMMActorNetwork +- Variant of actor network that outputs a multimodal Gaussian mixture distribution as action predictions. +### RNNActorNetwork +- An RNN policy network that predicts actions from a sequence of observations. +### RNNGMMActorNetwork +- An RNN policy network that outputs a multimodal Gaussian mixture distribution over actions from a sequence of observations. +### VAEActor +- A VAE that models a distribution of actions conditioned on observations. The VAE prior and decoder are used at test-time as the policy. + +## Implemented Value Networks +These networks take an observation dictionary as input (and possibly additional conditioning, such as subgoal or goal dictionaries) and produce value or action-value estimates or distributions. See `robomimic/models/value_nets.py` for complete implementations. +### ValueNetwork +- A basic value network that predicts values from observations. Can optionally be goal conditioned on future observations. +### DistributionalActionValueNetwork +- Distributional Q (action-value) network that outputs a categorical distribution over a discrete grid of value atoms. See the [paper](https://arxiv.org/abs/1707.06887) for more details. + +## Implemented VAEs +The library implements a general VAE architecture and a number of prior distributions. See `robomimic/models/vae_nets.py` for complete implementations. + +### VAE +A general Variational Autoencoder (VAE) implementation, as described in this [paper](https://arxiv.org/abs/1312.6114). + +Models a distribution p(X) or a conditional distribution p(X | Y), where each variable can consist of multiple modalities. The target variable X, whose distribution is modeled, is specified through the `input_shapes` argument, which is a map between modalities (strings) and expected shapes. In this way, a variable that consists of multiple kinds of data (e.g. image and flat-dimensional) can be modeled as well. A separate `output_shapes` argument is used to specify the expected reconstructions - this allows for asymmetric reconstruction (for example, reconstructing low-resolution images). + +This implementation supports learning conditional distributions as well (cVAE). The conditioning variable Y is specified through the `condition_shapes` argument, which is also a map between modalities (strings) and expected shapes. In this way, variables with multiple kinds of data (e.g. image and flat-dimensional) can jointly be conditioned on. By default, the decoder takes the conditioning variable Y as input. To force the decoder to reconstruct from just the latent, set `decoder_is_conditioned` to False (in this case, the prior must be conditioned). + +The implementation also supports learning expressive priors instead of using the usual N(0, 1) prior. There are three kinds of priors supported - Gaussian, Gaussian Mixture Model (GMM), and Categorical. For each prior, the parameters can be learned as independent parameters, or be learned as functions of the conditioning variable Y (by setting `prior_is_conditioned`). + +### GaussianPrior +- A class that holds functionality for learning both unimodal Gaussian priors and multimodal Gaussian Mixture Model priors for use in VAEs. Supports learnable priors, learnable / fixed mixture weights for GMM, and observation-conditioned priors, +### CategoricalPrior +- A class that holds functionality for learning categorical priors for use in VAEs. \ No newline at end of file diff --git a/code_src/rise_robomimic/docs/modules/overview.md b/code_src/rise_robomimic/docs/modules/overview.md new file mode 100644 index 0000000000000000000000000000000000000000..2342feffcf4cbc94adff2df89d7027705cba65ea --- /dev/null +++ b/code_src/rise_robomimic/docs/modules/overview.md @@ -0,0 +1,24 @@ +# Overview + +

+ +

+ +The **robomimic** framework consists of several modular components that interact to train and evaluate a policy: +- **Experiment config**: a config object defines all settings for a training run +- **Data**: an hdf5 dataset is loaded into a dataloader, which provides minibatches to the algorithm +- **Training**: an algorithm object trains a set of models (including the policy) +- **Evaluation**: the policy is evaluated in the environment by conducting a set of rollouts +- **Logging**: experiment statistics, model checkpoints, and videos are saved to disk + +These modules are encapsulated by the robomimic directory structure: + +- `examples`: examples to better understand modular components in the codebase +- [`robomimic/algo`](./algorithms.html): policy learning algorithm implementations +- [`robomimic/config`](./configs.html): default algorithm configs +- [`robomimic/envs`](./environments.html): wrappers for environments, used during evaluation rollouts +- `robomimic/exps/templates`: config templates for experiments +- [`robomimic/models`](./models.html): network implementations +- `robomimic/scripts`: main repository scripts +- `robomimic/utils`: a collection of utilities, including the [SequenceDataset](./dataset.html) class to load datasets, and [TensorUtils](../tutorials/tensor_collections.html#tensorutils) to work with nested tensor dictionaries + diff --git a/code_src/rise_robomimic/docs/tutorials/configs.md b/code_src/rise_robomimic/docs/tutorials/configs.md new file mode 100644 index 0000000000000000000000000000000000000000..519257de36226cb3a32ca003abd3b9a6f88b01eb --- /dev/null +++ b/code_src/rise_robomimic/docs/tutorials/configs.md @@ -0,0 +1,53 @@ +# Configuring and Launching Training Runs + +Robomimic uses a centralized [configuration system](../modules/configs.html) to specify (hyper)parameters at all levels. Below we walk through two ways to configure and launching training runs. + + +#### Best practices +
+

Warning! Do not modify default configs!

+ +Do not directly modify the default configs such as `config/bc_config.py`, especially if using the codebase with version control (e.g. git). Modifying these files modifies the default settings, and it’s easy to forget that these changes were made, or unintentionally commit these changes so that they become the new defaults. + +
+ + +Please see the [Config documentation](../modules/configs.html) for more information on Config objects, and the [hyperparameter scan tutorial](../tutorials/hyperparam_scan.html) for configuring hyperparameter sweeps. + +#### 1. Using a config json (preferred) + +The preferred way to specify training parameters is to pass a config json to the main training script `train.py` via the `--config` argument. The dataset can be specified by setting the `data` attribute of the `train` section of the config json, or specified via the `--dataset` argument. The example below runs a default template json for the BC algorithm. **This is the preferred way to launch training runs.** + +```sh +$ python train.py --config ../exps/templates/bc.json --dataset ../../tests/assets/test_v141.hdf5 +``` + +Please see the [hyperparameter helper tutorial](../tutorials/hyperparam_scan.html) to see how to easily generate json configs for launching training runs. + +#### 2. Constructing a config object in code + +Another way to launch a training run is to make a default config (with a line like `config = config_factory(algo_name="bc")`), modify the config in python code, and then call the train function, like in the `examples/train_bc_rnn.py` script. + +```python +import robomimic +import robomimic.utils.torch_utils as TorchUtils +from robomimic.config import config_factory +from robomimic.scripts.train import train + +# make default BC config +config = config_factory(algo_name="bc") + +# set config attributes here that you would like to update +config.experiment.name = "bc_rnn_example" +config.train.data = "/path/to/dataset.hdf5" +config.train.output_dir = "/path/to/desired/output_dir" +config.train.batch_size = 256 +config.train.num_epochs = 500 +config.algo.gmm.enabled = False + +# get torch device +device = TorchUtils.get_torch_device(try_to_use_cuda=True) + +# launch training run +train(config, device=device) +``` diff --git a/code_src/rise_robomimic/docs/tutorials/custom_algorithms.md b/code_src/rise_robomimic/docs/tutorials/custom_algorithms.md new file mode 100644 index 0000000000000000000000000000000000000000..57e64fee06d8a0ad21ad1a321182cca34e707ce3 --- /dev/null +++ b/code_src/rise_robomimic/docs/tutorials/custom_algorithms.md @@ -0,0 +1,374 @@ +# Implementing Custom Algorithms + +This tutorial provides an example of implementing a custom algorithm in robomimic. We choose to implement the recently proposed [TD3-BC](https://arxiv.org/abs/2106.06860) algorithm. + +This consists of the following steps: +1. Implement a custom `Config` class for TD3-BC. +2. Implement a custom `Algo` class for TD3-BC. + +## Implementing the Config class + +We will implement the config class in `config/td3_bc_config.py`. We implement a `TD3_BCConfig` config class that subclasses from `BaseConfig`. Importantly, we set the class variable `ALGO_NAME = "td3_bc"` to register this config under that algo name. We implement the `algo_config` function to populate `config.algo` with the keys needed for the algorithm - it is extremely similar to the `BCQConfig` implementation. Portions of the code are reproduced below. + +```python +class TD3_BCConfig(BaseConfig): + ALGO_NAME = "td3_bc" + + def algo_config(self): + # optimization parameters + self.algo.optim_params.critic.learning_rate.initial = 3e-4 # critic learning rate + self.algo.optim_params.critic.learning_rate.decay_factor = 0.1 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.critic.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.critic.regularization.L2 = 0.00 # L2 regularization strength + self.algo.optim_params.critic.start_epoch = -1 # number of epochs before starting critic training (-1 means start right away) + self.algo.optim_params.critic.end_epoch = -1 # number of epochs before ending critic training (-1 means start right away) + + self.algo.optim_params.actor.learning_rate.initial = 3e-4 # actor learning rate + self.algo.optim_params.actor.learning_rate.decay_factor = 0.1 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.actor.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.actor.regularization.L2 = 0.00 # L2 regularization strength + self.algo.optim_params.actor.start_epoch = -1 # number of epochs before starting actor training (-1 means start right away) + self.algo.optim_params.actor.end_epoch = -1 # number of epochs before ending actor training (-1 means start right away) + + # alpha value - for weighting critic loss vs. BC loss + self.algo.alpha = 2.5 + + # target network related parameters + self.algo.discount = 0.99 # discount factor to use + self.algo.n_step = 1 # for using n-step returns in TD-updates + self.algo.target_tau = 0.005 # update rate for target networks + self.algo.infinite_horizon = False # if True, scale terminal rewards by 1 / (1 - discount) to treat as infinite horizon + + # ================== Critic Network Config =================== + self.algo.critic.use_huber = False # Huber Loss instead of L2 for critic + self.algo.critic.max_gradient_norm = None # L2 gradient clipping for critic (None to use no clipping) + self.algo.critic.value_bounds = None # optional 2-tuple to ensure lower and upper bound on value estimates + + # critic ensemble parameters (TD3 trick) + self.algo.critic.ensemble.n = 2 # number of Q networks in the ensemble + self.algo.critic.ensemble.weight = 1.0 # weighting for mixing min and max for target Q value + + self.algo.critic.layer_dims = (256, 256, 256) # size of critic MLP + + # ================== Actor Network Config =================== + + # update actor and target networks every n gradients steps for each critic gradient step + self.algo.actor.update_freq = 2 + + # exploration noise used to form target action for Q-update - clipped Gaussian noise + self.algo.actor.noise_std = 0.2 # zero-mean gaussian noise with this std is applied to actions + self.algo.actor.noise_clip = 0.5 # noise is clipped in each dimension to (-noise_clip, noise_clip) + + self.algo.actor.layer_dims = (256, 256, 256) # size of actor MLP +``` + +Usually, we only need to implement the `algo_config` function to populate `config.algo` with the keys needed for the algorithm, but we also update the `experiment_config` function and `observation_config` function to make it easier to reproduce experiments on `gym` environments from the paper. See the source file for more details. + +Finally, we add the line `from robomimic.config.td3_bc_config import TD3_BCConfig` to `config/__init__.py` to make sure this `Config` subclass is registered by `robomimic`. + + +## Implementing the Algo class + +We will implement the algo class in `algo/td3_bc.py`. As described in the [Algorithm documentation](../modules/algorithms.html#initialization), we first need to implement the `algo_config_to_class` method - this is straightforward since we don't have multiple variants of this algorithm. We take special care to make sure we register this function with the same algo name that we used for defining the config (`"td3_bc"`). + +```python +@register_algo_factory_func("td3_bc") +def algo_config_to_class(algo_config): + """ + Maps algo config to the TD3_BC algo class to instantiate, along with additional algo kwargs. + + Args: + algo_config (Config instance): algo config + + Returns: + algo_class: subclass of Algo + algo_kwargs (dict): dictionary of additional kwargs to pass to algorithm + """ + # only one variant of TD3_BC for now + return TD3_BC, {} +``` + +Next, we'll describe how we implement the methods outlined in the [Algorithm documentation](../modules/algorithms.html#important-class-methods). We omit several of the methods, since their implementation is extremely similar to the `BCQ` implementation. We start by defining the class and implementing `_create_networks`. The code uses helper functions `_create_critics` and `_create_actor` to create the critic and actor networks, as in the `BCQ` implementation. + +```python +class TD3_BC(PolicyAlgo, ValueAlgo): + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + """ + self.nets = nn.ModuleDict() + + self._create_critics() + self._create_actor() + + # sync target networks at beginning of training + with torch.no_grad(): + for critic_ind in range(len(self.nets["critic"])): + TorchUtils.hard_update( + source=self.nets["critic"][critic_ind], + target=self.nets["critic_target"][critic_ind], + ) + + TorchUtils.hard_update( + source=self.nets["actor"], + target=self.nets["actor_target"], + ) + + self.nets = self.nets.float().to(self.device) + + def _create_critics(self): + critic_class = ValueNets.ActionValueNetwork + critic_args = dict( + obs_shapes=self.obs_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.critic.layer_dims, + value_bounds=self.algo_config.critic.value_bounds, + goal_shapes=self.goal_shapes, + **ObsNets.obs_encoder_args_from_config(self.obs_config.encoder), + ) + + # Q network ensemble and target ensemble + self.nets["critic"] = nn.ModuleList() + self.nets["critic_target"] = nn.ModuleList() + for _ in range(self.algo_config.critic.ensemble.n): + critic = critic_class(**critic_args) + self.nets["critic"].append(critic) + + critic_target = critic_class(**critic_args) + self.nets["critic_target"].append(critic_target) + + def _create_actor(self): + actor_class = PolicyNets.ActorNetwork + actor_args = dict( + obs_shapes=self.obs_shapes, + goal_shapes=self.goal_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.actor.layer_dims, + **ObsNets.obs_encoder_args_from_config(self.obs_config.encoder), + ) + + self.nets["actor"] = actor_class(**actor_args) + self.nets["actor_target"] = actor_class(**actor_args) +``` + +Next we describe the `train_on_batch` function, which implements the main training logic. The function trains the critic using the `_train_critic_on_batch` helper function, and then actor using the `_train_actor_on_batch` helper function (the actor is trained at a slower rate according to the `config.algo.actor.update_freq` config variable, as in the original author's implementation). Finally, the target network parameters are moved a little closer to the current network parameters, using `TorchUtils.soft_update`. + +```python + def train_on_batch(self, batch, epoch, validate=False): + """ + Training on a single batch of data. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + validate (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + with TorchUtils.maybe_no_grad(no_grad=validate): + info = PolicyAlgo.train_on_batch(self, batch, epoch, validate=validate) + + # Critic training + no_critic_backprop = validate or (not self._check_epoch(net_name="critic", epoch=epoch)) + with TorchUtils.maybe_no_grad(no_grad=no_critic_backprop): + critic_info = self._train_critic_on_batch( + batch=batch, + epoch=epoch, + no_backprop=no_critic_backprop, + ) + info.update(critic_info) + + # update actor and target networks at lower frequency + if not no_critic_backprop: + # update counter only on critic training gradient steps + self.actor_update_counter += 1 + do_actor_update = (self.actor_update_counter % self.algo_config.actor.update_freq == 0) + + # Actor training + no_actor_backprop = validate or (not self._check_epoch(net_name="actor", epoch=epoch)) + no_actor_backprop = no_actor_backprop or (not do_actor_update) + with TorchUtils.maybe_no_grad(no_grad=no_actor_backprop): + actor_info = self._train_actor_on_batch( + batch=batch, + epoch=epoch, + no_backprop=no_actor_backprop, + ) + info.update(actor_info) + + if not no_actor_backprop: + # to match original implementation, only update target networks on + # actor gradient steps + with torch.no_grad(): + # update the target critic networks + for critic_ind in range(len(self.nets["critic"])): + TorchUtils.soft_update( + source=self.nets["critic"][critic_ind], + target=self.nets["critic_target"][critic_ind], + tau=self.algo_config.target_tau, + ) + + # update target actor network + TorchUtils.soft_update( + source=self.nets["actor"], + target=self.nets["actor_target"], + tau=self.algo_config.target_tau, + ) + + return info +``` + +Below, we show the helper functions for training the critics, to be explicit in how the Bellman backup is used to construct the TD loss. The target Q values for the TD loss are obtained in the same way as [TD3](https://arxiv.org/abs/1802.09477). + +```python + def _train_critic_on_batch(self, batch, epoch, no_backprop=False): + info = OrderedDict() + + # batch variables + s_batch = batch["obs"] + a_batch = batch["actions"] + r_batch = batch["rewards"] + ns_batch = batch["next_obs"] + goal_s_batch = batch["goal_obs"] + + # 1 if not done, 0 otherwise + done_mask_batch = 1. - batch["dones"] + info["done_masks"] = done_mask_batch + + # Bellman backup for Q-targets + q_targets = self._get_target_values( + next_states=ns_batch, + goal_states=goal_s_batch, + rewards=r_batch, + dones=done_mask_batch, + ) + info["critic/q_targets"] = q_targets + + # Train all critics using this set of targets for regression + for critic_ind, critic in enumerate(self.nets["critic"]): + critic_loss = self._compute_critic_loss( + critic=critic, + states=s_batch, + actions=a_batch, + goal_states=goal_s_batch, + q_targets=q_targets, + ) + info["critic/critic{}_loss".format(critic_ind + 1)] = critic_loss + + if not no_backprop: + critic_grad_norms = TorchUtils.backprop_for_loss( + net=self.nets["critic"][critic_ind], + optim=self.optimizers["critic"][critic_ind], + loss=critic_loss, + max_grad_norm=self.algo_config.critic.max_gradient_norm, + ) + info["critic/critic{}_grad_norms".format(critic_ind + 1)] = critic_grad_norms + + return info + + def _get_target_values(self, next_states, goal_states, rewards, dones): + """ + Helper function to get target values for training Q-function with TD-loss. + """ + + with torch.no_grad(): + # get next actions via target actor and noise + next_target_actions = self.nets["actor_target"](next_states, goal_states) + noise = ( + torch.randn_like(next_target_actions) * self.algo_config.actor.noise_std + ).clamp(-self.algo_config.actor.noise_clip, self.algo_config.actor.noise_clip) + next_actions = (next_target_actions + noise).clamp(-1.0, 1.0) + + # TD3 trick to combine max and min over all Q-ensemble estimates into single target estimates + all_value_targets = self.nets["critic_target"][0](next_states, next_actions, goal_states).reshape(-1, 1) + max_value_targets = all_value_targets + min_value_targets = all_value_targets + for critic_target in self.nets["critic_target"][1:]: + all_value_targets = critic_target(next_states, next_actions, goal_states).reshape(-1, 1) + max_value_targets = torch.max(max_value_targets, all_value_targets) + min_value_targets = torch.min(min_value_targets, all_value_targets) + value_targets = self.algo_config.critic.ensemble.weight * min_value_targets + \ + (1. - self.algo_config.critic.ensemble.weight) * max_value_targets + q_targets = rewards + dones * self.discount * value_targets + + return q_targets + + def _compute_critic_loss(self, critic, states, actions, goal_states, q_targets): + """ + Helper function to compute loss between estimated Q-values and target Q-values. + """ + q_estimated = critic(states, actions, goal_states) + if self.algo_config.critic.use_huber: + critic_loss = nn.SmoothL1Loss()(q_estimated, q_targets) + else: + critic_loss = nn.MSELoss()(q_estimated, q_targets) + return critic_loss +``` + +Next we show the helper function for training the actor, which is trained through a weighted combination of the TD3 (DDPG) and BC loss. + +```python + def _train_actor_on_batch(self, batch, epoch, no_backprop=False): + info = OrderedDict() + + # Actor loss (update with mixture of DDPG loss and BC loss) + s_batch = batch["obs"] + a_batch = batch["actions"] + goal_s_batch = batch["goal_obs"] + + # lambda mixture weight is combination of hyperparameter (alpha) and Q-value normalization + actor_actions = self.nets["actor"](s_batch, goal_s_batch) + Q_values = self.nets["critic"][0](s_batch, actor_actions, goal_s_batch) + lam = self.algo_config.alpha / Q_values.abs().mean().detach() + actor_loss = -lam * Q_values.mean() + nn.MSELoss()(actor_actions, a_batch) + info["actor/loss"] = actor_loss + + if not no_backprop: + actor_grad_norms = TorchUtils.backprop_for_loss( + net=self.nets["actor"], + optim=self.optimizers["actor"], + loss=actor_loss, + ) + info["actor/grad_norms"] = actor_grad_norms + + return info +``` + +Finally, we describe the `get_action` implementation - which is used at test-time during rollouts. The implementation is extremely simple - just query the actor for an action. + +```python + def get_action(self, obs_dict, goal_dict=None): + """ + Get policy action outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + action (torch.Tensor): action tensor + """ + assert not self.nets.training + + return self.nets["actor"](obs_dict=obs_dict, goal_dict=goal_dict) +``` + +Finally, we add the line `from robomimic.algo.td3_bc import TD3_BC` to `algo/__init__.py` to make sure this `Algo` subclass is registered by `robomimic`. + +That's it! See `algo/td3_bc.py` for the complete implementation, and compare it to `algo/bcq.py` to see the similarity between the two implementations. + +We can now run the `generate_config_templates.py` script to generate the json template for our new algorithm, and then run it on our desired dataset. + +```sh +# generate ../exps/templates/td3_bc.json +$ python generate_config_templates.py + +# run training +$ python train.py --config ../exps/templates/td3_bc.json --dataset /path/to/walker2d_medium_expert.hdf5 +``` + diff --git a/code_src/rise_robomimic/docs/tutorials/dataset_contents.md b/code_src/rise_robomimic/docs/tutorials/dataset_contents.md new file mode 100644 index 0000000000000000000000000000000000000000..0cfb2584d5028d7e00895c5913125ebcb442b371 --- /dev/null +++ b/code_src/rise_robomimic/docs/tutorials/dataset_contents.md @@ -0,0 +1,60 @@ +# Dataset Contents and Visualization + +This tutorial shows how to view contents of robomimic hdf5 datasets. + +## Viewing HDF5 Dataset Structure + +
+

Note: HDF5 Dataset Structure.

+ +[This link](../datasets/overview.html#dataset-structure) shows the expected structure of each hdf5 dataset. + +
+ +The repository offers a simple utility script (`get_dataset_info.py`) to view the hdf5 dataset structure and some statistics of hdf5 datasets. The script displays the following information: + +- statistics about the trajectories (number, average length, etc.) +- the [filter keys](../datasets/overview.html#filter-keys) in the dataset +- the [environment metadata](../modules/environments.html#initialize-an-environment-from-a-dataset) in the dataset, which is used to construct the same simulator environment that the data was collected on +- the dataset structure for the first demonstration + +Pass the `--verbose` argument to print the list of demonstration keys under each filter key, and the dataset structure for all demonstrations. An example, using the small hdf5 dataset packaged with the repository in `tests/assets/test_v141.hdf5` is shown below. + +```sh +$ python get_dataset_info.py --dataset ../../tests/assets/test_v141.hdf5 +``` + +
+

Jupyter Notebook: A Deep Dive into Dataset Structure

+ +Any user wishing to write custom code that works with robomimic datasets should also look at the [jupyter notebook](https://github.com/ARISE-Initiative/robomimic/blob/master/examples/notebooks/datasets.ipynb) at `examples/notebooks/datasets.ipynb`, which showcases several useful python code snippets for working with robomimic hdf5 datasets. + +
+ +## Visualize Dataset Trajectories + +
+

Note: These examples are compatible with any robomimic dataset.

+ +The examples in this section use the small hdf5 dataset packaged with the repository in `tests/assets/test_v141.hdf5` (which requires robosuite v1.4.1), but you can run these examples with any robomimic hdf5 dataset. + +
+ +Use the `playback_dataset.py` script to easily view dataset trajectories. + +```sh +# For the first 5 trajectories, load environment simulator states one-by-one, and render "agentview" and "robot0_eye_in_hand" cameras to video at /tmp/playback_dataset.mp4 +$ python playback_dataset.py --dataset ../../tests/assets/test_v141.hdf5 --render_image_names agentview robot0_eye_in_hand --video_path /tmp/playback_dataset.mp4 --n 5 + +# Directly visualize the image observations in the dataset. This is especially useful for real robot datasets where there is no simulator to use for rendering. +$ python playback_dataset.py --dataset ../../tests/assets/test_v141.hdf5 --use-obs --render_image_names agentview_image --video_path /tmp/obs_trajectory.mp4 + +# Visualize depth observations as well. +$ python playback_dataset.py --dataset /path/to/dataset.hdf5 --use-obs --render_image_names agentview_image --render_depth_names agentview_depth --video_path /tmp/obs_trajectory.mp4 + +# Play the dataset actions in the environment to verify that the recorded actions are reasonable. +$ python playback_dataset.py --dataset ../../tests/assets/test_v141.hdf5 --use-actions --render_image_names agentview --video_path /tmp/playback_dataset_with_actions.mp4 + +# Visualize only the initial demonstration frames. +$ python playback_dataset.py --dataset ../../tests/assets/test_v141.hdf5 --first --render_image_names agentview --video_path /tmp/dataset_task_inits.mp4 +``` diff --git a/code_src/rise_robomimic/docs/tutorials/hyperparam_scan.md b/code_src/rise_robomimic/docs/tutorials/hyperparam_scan.md new file mode 100644 index 0000000000000000000000000000000000000000..1ca4b35e5963fcf3e577e290e78e2f8680371aff --- /dev/null +++ b/code_src/rise_robomimic/docs/tutorials/hyperparam_scan.md @@ -0,0 +1,300 @@ +# Running Hyperparameter Scans + +We provide the `ConfigGenerator` class under `utils/hyperparam_utils.py` to easily set and sweep over hyperparameters. +**This is the preferred way to launch multiple training runs using the repository.** +Follow the steps below for running your own hyperparameter scan: +1. [Create Base Config json](#step-1-create-base-config-json) +2. [Create Config Generator](#step-2-create-config-generator) +3. [Set Hyperparameter Values](#step-3-set-hyperparameter-values) +4. [Run Hyperparameter Helper Script](#step-4-run-hyperparameter-helper-script) + +## Step 1: Create Base Config json +The first step is to start with a base config json. A common choice is to copy one of the templates in `exps/templates` (such as `exps/templates/bc.json`) into a new folder (where additional config jsons will be generated). + +```sh +$ cp ../exps/templates/bc.json /tmp/gen_configs/base.json +``` + +
+

Relevant settings in base json file

+ +Sections of the config that are not involved in the scan and that do not differ from the default values in the template can also be omitted, if desired. + +
+ +We modify `/tmp/gen_configs/base.json`, adding a base experiment name (`"bc_rnn_hyper"`) and specified the dataset path (`"/tmp/test_v141.hdf5"`). + +```sh +$ cat /tmp/gen_configs/base.json +``` + +
+ Click to see output +

+ +```json +{ + "algo_name": "bc", + "experiment": { + "name": "bc_rnn_hyper", + "validate": true, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/tmp/test_v141.hdf5", + "output_dir": "../bc_trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "seq_length": 1, + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2 + } + } +} +``` + +

+
+ +## Step 2: Create Config Generator + +The next step is create a `ConfigGenerator` object which procedurally generates new configs (one config per unique hyperparameter combination). +We provide an example in `scripts/hyperparam_helper.py` and for the remainder of this tutorial we will follow this script step-by-step. + +First, we define a function `make_generator` that creates a `ConfigGenerator` object. +After this, our next step will be to set hyperparameter values. + +```python +import robomimic +import robomimic.utils.hyperparam_utils as HyperparamUtils + + +def make_generator(config_file, script_file): + """ + Implement this function to setup your own hyperparameter scan! + """ + generator = HyperparamUtils.ConfigGenerator( + base_config_file=config_file, script_file=script_file + ) + + # next: set and sweep over hyperparameters + generator.add_param(...) # set / sweep hp1 + generator.add_param(...) # set / sweep hp2 + generator.add_param(...) # set / sweep hp3 + ... + + return generator + +def main(args): + + # make config generator + generator = make_generator( + config_file=args.config, # base config file from step 1 + script_file=args.script # explained later in step 4 + ) + + # generate jsons and script + generator.generate() +... +``` + +## Step 3: Set Hyperparameter Values + +Next, we use the `generator.add_param` function to set hyperparameter values, which takes the following arguments: +- `key`: (string) full name of config key to sweep +- `name`: (string) shorthand name for this key +- `values`: (list) values to sweep for this key +- `value_names` (list) (optional) shorthand names associated for each value in `values` +- `group`: (integer) hp group identifier. hps with same group are swept together. hps with different groups are swept as a cartesian product + +### Set fixed values +Going back to our example, we first set hyperparameters that are fixed single values. +We could have modified our base json file directly but we opted to set it in the generator function instead. + +In this case, we would like to run the BC-RNN algorithm with an RNN horizon of 10. This requires setting `config.train.seq_length = 10` and `config.algo.rnn.enabled = True`. + +```python + # use RNN with horizon 10 + generator.add_param( + key="algo.rnn.enabled", + name="", + group=0, + values=[True], + ) + generator.add_param( + key="train.seq_length", + name="", + group=0, + values=[10], + ) + generator.add_param( + key="algo.rnn.horizon", + name="", + group=0, + values=[10], + ) +``` + +
+

Empty hyperparameter names

+ +Leaving `name=""` ensures that the experiment name is not determined by these parameter values. +Only do this if you are sweeping over a single value! + +
+ +
+

wandb logging

+ +If you would like to log and view results on wandb, enable wandb logging in the hyperparameter generator: +```python +generator.add_param( + key="experiment.logging.log_wandb", + name="", + group=-1, + values=[True], +) +``` + +
+ +### Define hyperparameter scan values +Now we define our scan - we could like to sweep the following: +- policy learning rate in [1e-3, 1e-4] +- whether to use a GMM policy or not +- whether to use an RNN dimension of 400 with an MLP of size (1024, 1024) or an RNN dimension of 1000 with an empty MLP + +Notice that the learning rate goes in `group` 1, the GMM enabled parameter goes in `group` 2, and the RNN dimension and MLP layer dims both go in `group` 3. + +
+

Sweeping hyperparameters together

+ +We set the RNN dimension and MLP layer dims in the same group to ensure that the parameters change together (RNN dimension 400 always occurs with MLP layer dims (1024, 1024), and RNN dimension 1000 always occurs with an empty MLP). + +
+ +```python + # LR - 1e-3, 1e-4 + generator.add_param( + key="algo.optim_params.policy.learning_rate.initial", + name="plr", + group=1, + values=[1e-3, 1e-4], + ) + + # GMM y / n + generator.add_param( + key="algo.gmm.enabled", + name="gmm", + group=2, + values=[True, False], + value_names=["t", "f"], + ) + + # RNN dim 400 + MLP dims (1024, 1024) vs. RNN dim 1000 + empty MLP dims () + generator.add_param( + key="algo.rnn.hidden_dim", + name="rnnd", + group=3, + values=[ + 400, + 1000, + ], + ) + generator.add_param( + key="algo.actor_layer_dims", + name="mlp", + group=3, + values=[ + [1024, 1024], + [], + ], + value_names=["1024", "0"], + ) +``` + +## Step 4: Run Hyperparameter Helper Script +Finally, we run the hyperparameter helper script (which contains the function we defined above). + +```sh +$ python hyperparam_helper.py --config /tmp/gen_configs/base.json --script /tmp/gen_configs/out.sh +``` + +All generated configs have been added to `/tmp/gen_configs`, along with a helpful bash script that can be used to launch your training runs. + +```sh +$ cat /tmp/gen_configs/out.sh + +#!/bin/bash + +python train.py --config /tmp/gen_configs/bc_rnn_hyper_plr_0.001_gmm_t_rnnd_400_mlp_1024.json +python train.py --config /tmp/gen_configs/bc_rnn_hyper_plr_0.001_gmm_t_rnnd_1000_mlp_0.json +python train.py --config /tmp/gen_configs/bc_rnn_hyper_plr_0.001_gmm_f_rnnd_400_mlp_1024.json +python train.py --config /tmp/gen_configs/bc_rnn_hyper_plr_0.001_gmm_f_rnnd_1000_mlp_0.json +python train.py --config /tmp/gen_configs/bc_rnn_hyper_plr_0.0001_gmm_t_rnnd_400_mlp_1024.json +python train.py --config /tmp/gen_configs/bc_rnn_hyper_plr_0.0001_gmm_t_rnnd_1000_mlp_0.json +python train.py --config /tmp/gen_configs/bc_rnn_hyper_plr_0.0001_gmm_f_rnnd_400_mlp_1024.json +python train.py --config /tmp/gen_configs/bc_rnn_hyper_plr_0.0001_gmm_f_rnnd_1000_mlp_0.json +``` + +
+

Meta information

+ +For each generated config file you will find a `meta` section that contains hyperparameter names, values, and other metadata information. This `meta` section is generated automatically, and you should NOT need to edit or modify it. + +
diff --git a/code_src/rise_robomimic/docs/tutorials/observations.md b/code_src/rise_robomimic/docs/tutorials/observations.md new file mode 100644 index 0000000000000000000000000000000000000000..efebd04e7f19bc49bdd303c587694ec73f1c11d3 --- /dev/null +++ b/code_src/rise_robomimic/docs/tutorials/observations.md @@ -0,0 +1,26 @@ +# Multimodal Observations + +**robomimic** natively supports multiple different observation modalities, and provides integrated support for modifying observations and adding your own custom ones. + +First, we highlight semantic distinctions when referring to different aspects of observations: + +- **Keys** are individual observations that are received from an environment / dataset. For example, `rgb_wrist`, `eef_pos`, and `joint_vel` could be keys, depending on the dataset / environment. +- **Modalities** are different observation modes. For example, low dimensional states are considered a single mode, whereas RGB observations might be another mode. **robomimic** natively supports four modalities: `low_dim`, `rgb`, `depth`, and `scan`. Each modality owns it own set of observation keys. +- **Groups** consist of potentially multiple modalities and multiple keys per modality, which are together passed to a learning model. For example, **robomimic** commonly uses three different groups: `obs`, which contains the normal observations passed to any model using these as inputs, and `goal` / `subgoal`, which means any specified modalities / keys correspond to a goal / subgoal to be learned. + +Observations are handled in the following way: +1. Each observation key is according to their modality via their `Modality` class, +2. All observations for a given modality are concatenated and passed through an `ObservationEncoder` for that modality, +3. All processed observations over all modalities are concatenated together and passed to a learning network + +## Modifying and Adding Your Own Observation Modalities + +**robomimic** natively supports the following modalities: +- `low_dim`: low-dimensional states +- `rgb`: RGB images +- `depth`: depth images +- `scan`: scan arrays + +The way each of these modalities are processed and encoded can be easily specified by modifying their respective `encoder` parameters in your `Config` class. + +You may want to specify your own custom modalities that get processed and encoded in a certain way (e.g.: semantic segmentation, optical flow, etc...). This can also easily be done, and we refer you to our [example script](https://github.com/ARISE-Initiative/robomimic/blob/master/examples/simple_obs_nets.py) which walks through the process. diff --git a/code_src/rise_robomimic/docs/tutorials/pretrained_representations.md b/code_src/rise_robomimic/docs/tutorials/pretrained_representations.md new file mode 100644 index 0000000000000000000000000000000000000000..72c66a51b71e6a10917850520dba9539c8878651 --- /dev/null +++ b/code_src/rise_robomimic/docs/tutorials/pretrained_representations.md @@ -0,0 +1,42 @@ +# Pre-trained Visual Representations + +**Robomimic** supports multiple pre-trained visual representations and offers integration for adapting observation encoders to the desired pre-trained visual representation encoders. + +## Terminology + +First, let's clarify the semantic distinctions when using different pre-trained visual representations: + +- **Backbone Classes** refer to the various pre-trained visual encoders. For instance, `R3MConv` and `MVPConv` are the backbone classes for using [R3M](https://arxiv.org/abs/2203.12601) and [MVP](https://arxiv.org/abs/2203.06173) pre-trained representations, respectively. +- **Model Classes** pertain to the different sizes of the pretrained models within each selected backbone class. For example, `R3MConv` has three model classes - `resnet18`, `resnet34`, and `resnet50`, while `MVPConv` features five model classes - `vits-mae-hoi`, `vits-mae-in`, `vits-sup-in`, `vitb-mae-egosoup`, and `vitl-256-mae-egosoup`. + +## Examples + +Using pre-trained visual representations is simple. Each pre-trained encoder is defined by its `backbone_class`, `model_class`, and whether to `freeze` representations or finetune them. Please note that you may need to refer to the original library of the pre-trained representation for installation instructions. + +If you are specifying your config with code (as in `examples/train_bc_rnn.py`), the following are example code blocks for using pre-trained representations: + +```python +# R3M +config.observation.encoder.rgb.core_kwargs.backbone_class = 'R3MConv' # R3M backbone for image observations (unused if no image observations) +config.observation.encoder.rgb.core_kwargs.backbone_kwargs.r3m_model_class = 'resnet18' # R3M model class (resnet18, resnet34, resnet50) +config.observation.encoder.rgb.core_kwargs.backbone_kwargs.freeze = True # whether to freeze network during training or allow finetuning +config.observation.encoder.rgb.core_kwargs.pool_class = None # no pooling class for pretraining model + +# MVP +config.observation.encoder.rgb.core_kwargs.backbone_class = 'MVPConv' # MVP backbone for image observations (unused if no image observations) +config.observation.encoder.rgb.core_kwargs.backbone_kwargs.mvp_model_class = 'vitb-mae-egosoup' # MVP model class (vits-mae-hoi, vits-mae-in, vits-sup-in, vitb-mae-egosoup, vitl-256-mae-egosoup) +config.observation.encoder.rgb.core_kwargs.backbone_kwargs.freeze = True # whether to freeze network during training or allow finetuning +config.observation.encoder.rgb.core_kwargs.pool_class = None # no pooling class for pretraining model + +# Set data loader attributes for image observations +config.train.num_data_workers = 2 # 2 data workers for image datasets +config.train.hdf5_cache_mode = "low_dim" # only cache non-image data + +# Ensure that you are using image observation modalities, names may depend on your dataset naming convention +config.observation.modalities.obs.rgb = [ + "agentview_image", + "robot0_eye_in_hand_image" + ] +``` + +Alternatively, if you are using a config json, you can set the appropriate keys in your json. diff --git a/code_src/rise_robomimic/docs/tutorials/reproducing_experiments.md b/code_src/rise_robomimic/docs/tutorials/reproducing_experiments.md new file mode 100644 index 0000000000000000000000000000000000000000..647c91423e9cc1d0ecdd0b0febac03509bad2676 --- /dev/null +++ b/code_src/rise_robomimic/docs/tutorials/reproducing_experiments.md @@ -0,0 +1,17 @@ +# Reproducing Published Experiments and Results + +This is a guide on how to reproduce published experiments and results for various datasets. + +
+

Note: Understand how to launch training runs and view results first!

+ +Before trying to reproduce published results, it might be useful to read the following tutorials: +- [how to launch training runs](./configs.html) +- [how to view training results](./viewing_results.html) +- [how to launch multiple training runs efficiently](./hyperparam_scan.html) + +
+ +1. Follow the steps in the [Dataset Pipeline](../datasets/overview.html#dataset-pipeline) in order to download and postprocess your dataset(s) of interest. +2. Some of the datasets provide explicit guidelines on reproducing experiments that should be followed (for example, the [CoRL 2021 robomimic datasets](../datasets/robomimic_v0.1.html#reproduce-study-results)). +3. Otherwise, you can just follow the normal steps for [launching training runs](./configs.html) and [viewing training results](./viewing_results.html). diff --git a/code_src/rise_robomimic/docs/tutorials/tensor_collections.md b/code_src/rise_robomimic/docs/tutorials/tensor_collections.md new file mode 100644 index 0000000000000000000000000000000000000000..de9df643335e5c6381b0cf267cf7ae927772de98 --- /dev/null +++ b/code_src/rise_robomimic/docs/tutorials/tensor_collections.md @@ -0,0 +1,93 @@ +# Operations over Tensor Collections + +This section highlights some important utility functions and classes used in the codebase for working with +collections of tensors. + +## TensorUtils + +Most models in **robomimic** operate on nested tensor dictionaries, both for input and training labels. We provide a suite of utilities to work with these dictionaries in `robomimic.utils.tensor_utils`. For example, given a numpy dictionary of observations: +```python +import numpy as np + +x = { + 'image': np.random.randn(3, 224, 224), + 'proprio': { + 'eef_pos': np.random.randn(3), + 'eef_rot': np.random.randn(3) + } +} +``` + +For example, we can use `robomimic.utils.tensor_utils` to convert them to pytorch tensors, add a batch dimension, and send them to GPU: + +```python +import torch +import robomimic.utils.tensor_utils as TensorUtils + +# Converts all numpy arrays in nested dictionary or list or tuple to torch tensors +x = TensorUtils.to_tensor(x) + +# add a batch dimension to all tensors in the dict +x = TensorUtils.to_batch(x) + +# send all nested tensors to GPU (if available) +x = TensorUtils.to_device(x, torch.device("cuda:0")) +``` + +The library also supports nontrivial shape operations on the nested dict. For example: + +```python +# create a new dimension at dim=1 and expand the dimension size to 10 +x = TensorUtils.unsqueeze_expand_at(x, size=10, dim=1) +# x["rgb"].shape == torch.Size([1, 10, 3, 224, 224]) + +# repeat the 0-th dimension 10 times +x = TensorUtils.repeat_by_expand_at(x, repeats=10, dim=0) +# x["rgb"].shape == torch.Size([10, 10, 3, 224, 224]) + +# gather the sequence dimension (dim=1) by some index +x = TensorUtils.gather_sequence(x_seq, indices=torch.arange(10)) +# x["rgb"].shape == torch.Size([10, 3, 224, 224]) +``` + +In addition, `map_tensor` allows applying an arbitrary function to all tensors in a nested dictionary or list of tensors and returns the same nested structure. +```python +x = TensorUtils.map_tensor(x, your_func) +``` + +The complete documentation of `robomimic.utils.tensor_utils.py` is available [here](../api/robomimic.utils.html#module-robomimic.utils.tensor_utils). + + +## ObsUtils + +`robomimic.utils.obs_utils` implements a suite of utility functions to preprocess different observation modalities such as images and functions to determine types of observations in order to create suitable encoder network architectures. Below we list the important functions. + +- **initialize_obs_utils_with_obs_specs(obs_modality_specs)** + + This function initialize a global registry of mapping between observation key names and observation modalities e.g. which ones are low-dimensional, and which ones are rgb images). For example, given an `obs_modality_specs` of the following format: + ```python + { + "obs": { + "low_dim": ["robot0_eef_pos", "robot0_eef_quat"], + "rgb": ["agentview_image", "robot0_eye_in_hand"], + } + "goal": { + "low_dim": ["robot0_eef_pos"], + "rgb": ["agentview_image"] + } + } + + ``` + The function will create a mapping between observation names such as `'agentview_image'` and observation modalities such as `'rgb'`. The registry is stored in `OBS_MODALITIES_TO_KEYS` and can be accessed globally. Utility functions such as `key_is_obs_modality()` rely on this global registry to determine observation modalities. + +- **process_obs(obs_dict)** + + Preprocess a dictionary of observations to be fed to a neural network. For example, image observations will be casted to `float` format, rescaled to `[0-1]`, and axis-transposed to `[C, H, W]` format. + +- **unprocess_obs(obs_dict)** + + Revert the preprocessing transformation applied to observations by `process_obs`. Useful for converting images back to `uint8` for efficient storage. + +- **normalize_obs(obs_dict, obs_normalization_stats)** + + Normalize observations by computing the mean observation and std of each observation (in each dimension and observation key), and normalizing unit mean and variance in each dimension. \ No newline at end of file diff --git a/code_src/rise_robomimic/docs/tutorials/training_transformers.md b/code_src/rise_robomimic/docs/tutorials/training_transformers.md new file mode 100644 index 0000000000000000000000000000000000000000..03af242a2f0d8f1bd8bd9605dbad0d3a7cb1b334 --- /dev/null +++ b/code_src/rise_robomimic/docs/tutorials/training_transformers.md @@ -0,0 +1,43 @@ +# Training Transformers + +This tutorial shows how to train a transformer policy network. + +
+

Note: Understand how to launch training runs and view results first!

+ +Before trying to train a transformer, it might be useful to read the following tutorials: +- [how to launch training runs](./configs.html) +- [how to view training results](./viewing_results.html) +- [how to launch multiple training runs efficiently](./hyperparam_scan.html) + +
+ +A template with tuned parameters for transformer based policy networks is defined in `robomimic/config/default_templates/bc_transformer.json`. + +#### 1. Using default configurations + +The easiest way to train a transformer policy network is to pass the default template json to the main training script `train.py` via the `--config` argument. The dataset can be specified by setting the `data` attribute of the `train` section of the config json, or specified via the `--dataset` argument. You may find that your data has different rollout horizon lengths, observation modalities, or other incompatibilities with the default template. In this scenario, we suggest defining custom parameters as described in (2). + +```sh +$ python train.py --config ../config/default_templates/bc_transformer.json --dataset /path/to/dataset.hdf5 +``` + +#### 2. Defining custom parameters + +If you want to modify the default transformer parameters, do not directly modify the default config (`config/bc_config.py`) or template (`config/default_templates/bc_transformer.json`). Instead, you can create a copy of `robomimic/config/default_templates/bc_transformer.json` and store it in a new directory on your computer. Set this as the base file for `scripts/hyperparam_helper.py` and define custom settings as described [here](./hyperparam_scan.html). This is particularly useful when running a sweep over hyperparameters; **it is the prefered way to launch multiple training runs**. + +Optionally, you can modify the default template in python code or directly set the appropriate keys in your copy of the config file. This code snippet below highlights useful parameters to tune for transformers. To see all transformer policy settings, refer to `config/bc_config.py`. + +```python +# make sure transformer is enabled +config.algo.transformer.enabled = True + +# useful config attributes to modify for transformers +config.algo.transformer.embed_dim = 512 # dimension for embeddings used by transformer +config.algo.transformer.num_layers = 6 # number of transformer blocks to stack +config.algo.transformer.num_heads = 8 # number of attention heads for each transformer block (should divide embed_dim evenly) +config.algo.transformer.context_length = 10 # length of (s, a) sub-seqeunces to feed to transformer +config.train.frame_stack = 10 # length of sub-sequence to observe: (s_{t-1}, a_{t-1}), (s_{t-2}, a_{t-2}), ..., (s_{t-9}, a_{t-9}) +config.train.seq_length = 1 # length of sub-seqeunce to predict: (s_{t}, a_{t}) +``` + diff --git a/code_src/rise_robomimic/docs/tutorials/using_pretrained_models.md b/code_src/rise_robomimic/docs/tutorials/using_pretrained_models.md new file mode 100644 index 0000000000000000000000000000000000000000..9f1114a88ee249ca4a2f5e2893d465c7f55fe8d3 --- /dev/null +++ b/code_src/rise_robomimic/docs/tutorials/using_pretrained_models.md @@ -0,0 +1,26 @@ +# Using Pretrained Models + +This tutorial shows how to use pretrained model checkpoints. + +
+

Jupyter Notebook: Working with Pretrained Policies

+ +The rest of this tutorial shows how to use utility scripts to load and rollout a trained policy. If you wish to do so via an interactive notebook, please refer to the [jupyter notebook](https://github.com/ARISE-Initiative/robomimic/blob/master/examples/notebooks/run_policy.ipynb) at `examples/notebooks/run_policy.ipynb`. The notebook tutorial shows how to download a checkpoint from the model zoo, load the checkpoint in pytorch, and rollout the policy. + +
+ +## Evaluating Trained Policies + +Saved policy checkpoints in the `models` directory can be evaluated using the `run_trained_agent.py` script: +```sh +# 50 rollouts with max horizon 400 and render agentview and wrist camera images to video +$ python run_trained_agent.py --agent /path/to/model.pth --n_rollouts 50 --horizon 400 --seed 0 --video_path /path/to/output.mp4 --camera_names agentview robot0_eye_in_hand + +# Write rollouts to a new dataset hdf5 +python run_trained_agent.py --agent /path/to/model.pth --n_rollouts 50 --horizon 400 --seed 0 --dataset_path /path/to/output.hdf5 --dataset_obs + +# Write rollouts without explicit observations to hdf5 +python run_trained_agent.py --agent /path/to/model.pth --n_rollouts 50 --horizon 400 --seed 0 --dataset_path /path/to/output.hdf5 +``` + +In the last case, the observations can be (later) extracted later using the `dataset_states_to_obs.py` script (see [here](../datasets/robosuite.html#extracting-observations-from-mujoco-states)). diff --git a/code_src/rise_robomimic/docs/tutorials/viewing_results.md b/code_src/rise_robomimic/docs/tutorials/viewing_results.md new file mode 100644 index 0000000000000000000000000000000000000000..64acd9ff8760c0bc3a838e10d7c575b3d29a7fea --- /dev/null +++ b/code_src/rise_robomimic/docs/tutorials/viewing_results.md @@ -0,0 +1,106 @@ +# Logging and Viewing Training Results + +In this section, we describe how to configure the logging and evaluations that occur during your training run, and how to view the results of a training run. + +## Configuring Logging + +### Saving Experiment Logs +Configured under `experiment.logging`: +``` +"logging": { + # save terminal outputs under `logs/log.txt` in experiment folder + "terminal_output_to_txt": true, + + # save tensorboard logs under `logs/tb` in experiment folder + "log_tb": true + + # save wandb logs under `logs/wandb` in experiment folder + "log_wandb": true +}, +``` + +### Saving Model Checkpoints +Configured under `experiment.save`: +``` +"save": { + # enable saving model checkpoints + "enabled": true, + + # controlling frequency of checkpoints + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + + # saving the best checkpoints + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true +}, +``` + +### Evaluating Rollouts and Saving Videos +#### Evaluating Rollouts +Configured under `experiment.rollout`: +``` +"rollout": { + "enabled": true, # enable evaluation rollouts + "n": 50, # number of rollouts per evaluation + "horizon": 400, # number of timesteps per rollout + "rate": 50, # frequency of evaluation (in epochs) + "terminate_on_success": true # terminating rollouts upon task success +} +``` + +#### Saving Videos +To save videos of the rollouts, set `experiment.render_video` to `true`. + +## Viewing Training Results + +### Contents of Training Outputs +After the script finishes, you can check the training outputs in the `//` experiment directory: +``` +config.json # config used for this experiment +logs/ # experiment log files + log.txt # terminal output + tb/ # tensorboard logs + wandb/ # wandb logs +videos/ # videos of robot rollouts during training +models/ # saved model checkpoints +``` + +
+

Loading Trained Checkpoints

+ +Please see the [Using Pretrained Models](./using_pretrained_models.html) tutorial to see how to load the trained model checkpoints in the `models` directory. + +
+ +### Viewing Tensorboard Results +The experiment results can be viewed using tensorboard: +```sh +$ tensorboard --logdir --bind_all +``` +Below is a snapshot of the tensorboard dashboard: + +

+ +

+
+ +Experiment results (y-axis) are logged across epochs (x-axis). +You may find the following logging metrics useful: +- `Rollout/`: evaluation rollout metrics, eg. success rate, rewards, etc. + - `Rollout/Success_Rate/{envname}-max`: maximum success rate over time (this is the metric the [study paper](https://arxiv.org/abs/2108.03298) uses to evaluate baselines) +- `Timing_Stats/`: time spent by the algorithm loading data, training, performing rollouts, etc. +- `Timing_Stats/`: time spent by the algorithm loading data, training, performing rollouts, etc. +- `Train/`: training stats +- `Validation/`: validation stats +- `System/RAM Usage (MB)`: system RAM used by algorithm + + +### Viewing wandb Results +You can also view results in [wandb](https://wandb.ai), similarly to tensorboard. To do so, ensure that you have set `experiment.logging.log_wandb` to True in the experiment config. + +When first logging to wandb, you will need to specify a wandb entity name, ie. the wandb account under which results will be logged. You can do so by setting `WANDB_ENTITY` to the desired wandb account name in `robomimic/macros_private.py`. Note: if this file does not exist, run `python robomimic/scripts/setup_macros.py` to setup the private macros file. + +By default all results will be logged under a wandb project labled `default`, however you can set the project name by setting `experiment.logging.wandb_proj_name` in the configs. diff --git a/code_src/rise_robomimic/docs/versions/v0.2.md b/code_src/rise_robomimic/docs/versions/v0.2.md new file mode 100644 index 0000000000000000000000000000000000000000..72e853db52c971bc9d850f937a69a978a3c1bc4f --- /dev/null +++ b/code_src/rise_robomimic/docs/versions/v0.2.md @@ -0,0 +1,18 @@ +# v0.2 + +Redirecting... + + + + + + + Page Redirection + + + + If you are not redirected automatically, follow this link. + + diff --git a/code_src/rise_robomimic/examples/add_new_modality.py b/code_src/rise_robomimic/examples/add_new_modality.py new file mode 100644 index 0000000000000000000000000000000000000000..cf7fc876e255f1f695f24f9e3b6574d4ac0169a0 --- /dev/null +++ b/code_src/rise_robomimic/examples/add_new_modality.py @@ -0,0 +1,214 @@ +""" +A simple example showing how to add custom observation modalities, and custom +observation networks (EncoderCore, ObservationRandomizer, etc.) as well. +We also show how to use your custom classes directly in a config, and link them to +your environment's observations +""" + +import numpy as np +import torch +import robomimic +from robomimic.models import EncoderCore, Randomizer +from robomimic.utils.obs_utils import Modality, ScanModality +from robomimic.config.bc_config import BCConfig +import robomimic.utils.tensor_utils as TensorUtils + + +# Let's create a new modality to handle observation modalities, which will be interpreted as +# single frame images, with raw shape (H, W) in range [0, 255] +class CustomImageModality(Modality): + # We must define the class string name to reference this modality with the @name attribute + name = "custom_image" + + # We must define two class methods: a processor and an unprocessor method. The processor + # method should map the raw observations (a numpy array OR torch tensor) into a form / shape suitable for learning, + # and the unprocess method should do the inverse operation + @classmethod + def _default_obs_processor(cls, obs): + # We add a channel dimension and normalize them to be in range [-1, 1] + return (obs / 255.0 - 0.5) * 2 + + @classmethod + def _default_obs_unprocessor(cls, obs): + # We do the reverse + return ((obs / 2) + 0.5) * 255.0 + + +# You can also modify pre-existing modalities as well. Let's say you have scan data that pads the ends with a 0, so we +# want to pre-process those scans in a different way. We can specify a custom processor / unprocessor +# method that will override the default one (assumes obs are a flat 1D array): +def custom_scan_processor(obs): + # Trim the padded ends + return obs[1:-1] + + +def custom_scan_unprocessor(obs): + # Re-add the padding + # Note: need to check type + return np.concatenate([np.zeros(1), obs, np.zeros(1)]) if isinstance(obs, np.ndarray) else \ + torch.concat([torch.zeros(1), obs, torch.zeros(1)]) + + +# Override the default functions for ScanModality +ScanModality.set_obs_processor(processor=custom_scan_processor) +ScanModality.set_obs_unprocessor(unprocessor=custom_scan_unprocessor) + + +# Let's now create a custom encoding class for the custom image modality +class CustomImageEncoderCore(EncoderCore): + # For simplicity, this will be a pass-through with some simple kwargs + def __init__( + self, + input_shape, # Required, will be inferred automatically at runtime + + # Any args below here you can specify arbitrarily + welcome_str, + ): + # Always need to run super init first and pass in input_shape + super().__init__(input_shape=input_shape) + + # Anything else should can be custom to your class + # Let's print out the welcome string + print(f"Welcome! {welcome_str}") + + # We need to always specify the output shape from this model, based on a given input_shape + def output_shape(self, input_shape=None): + # this is just a pass-through, so we return input_shape + return input_shape + + # we also need to specify the forward pass for this network + def forward(self, inputs): + # just a pass through again + return inputs + + +# Let's also create a custom randomizer class for randomizing our observations +class CustomImageRandomizer(Randomizer): + """ + A simple example of a randomizer - we make @num_rand copies of each image in the batch, + and add some small uniform noise to each. All randomized images will then get passed + through the network, resulting in outputs corresponding to each copy - we will pool + these outputs across the copies with a simple average. + """ + def __init__( + self, + input_shape, + num_rand=1, + noise_scale=0.01, + ): + """ + Args: + input_shape (tuple, list): shape of input (not including batch dimension) + num_rand (int): number of random images to create on each forward pass + noise_scale (float): magnitude of uniform noise to apply + """ + super(CustomImageRandomizer, self).__init__() + + assert len(input_shape) == 3 # (C, H, W) + + self.input_shape = input_shape + self.num_rand = num_rand + self.noise_scale = noise_scale + + def output_shape_in(self, input_shape=None): + """ + Function to compute output shape from inputs to this module. Corresponds to + the @forward_in operation, where raw inputs (usually observation modalities) + are passed in. + + Args: + input_shape (iterable of int): shape of input. Does not include batch dimension. + Some modules may not need this argument, if their output does not depend + on the size of the input, or if they assume fixed size input. + + Returns: + out_shape ([int]): list of integers corresponding to output shape + """ + + # @forward_in takes (B, C, H, W) -> (B, N, C, H, W) -> (B * N, C, H, W). + # since only the batch dimension changes, and @input_shape does not include batch + # dimension, we indicate that the non-batch dimensions don't change + return list(input_shape) + + def output_shape_out(self, input_shape=None): + """ + Function to compute output shape from inputs to this module. Corresponds to + the @forward_out operation, where processed inputs (usually encoded observation + modalities) are passed in. + + Args: + input_shape (iterable of int): shape of input. Does not include batch dimension. + Some modules may not need this argument, if their output does not depend + on the size of the input, or if they assume fixed size input. + + Returns: + out_shape ([int]): list of integers corresponding to output shape + """ + + # since the @forward_out operation splits [B * N, ...] -> [B, N, ...] + # and then pools to result in [B, ...], only the batch dimension changes, + # and so the other dimensions retain their shape. + return list(input_shape) + + def forward_in(self, inputs): + """ + Make N copies of each image, add random noise to each, and move + copies into batch dimension to ensure compatibility with rest + of network. + """ + + # note the use of @self.training to ensure no randomization at test-time + if self.training: + + # make N copies of the images [B, C, H, W] -> [B, N, C, H, W] + out = TensorUtils.unsqueeze_expand_at(inputs, size=self.num_rand, dim=1) + + # add random noise to each copy + out = out + self.noise_scale * (2. * torch.rand_like(out) - 1.) + + # reshape [B, N, C, H, W] -> [B * N, C, H, W] to ensure network forward pass is unchanged + return TensorUtils.join_dimensions(out, 0, 1) + return inputs + + def forward_out(self, inputs): + """ + Pools outputs across the copies by averaging them. It does this by splitting + the outputs from shape [B * N, ...] -> [B, N, ...] and then averaging across N + to result in shape [B, ...] to make sure the network output is consistent with + what would have happened if there were no randomization. + """ + + # note the use of @self.training to ensure no randomization at test-time + if self.training: + batch_size = (inputs.shape[0] // self.num_rand) + out = TensorUtils.reshape_dimensions(inputs, begin_axis=0, end_axis=0, + target_dims=(batch_size, self.num_rand)) + return out.mean(dim=1) + return inputs + + def __repr__(self): + """Pretty print network.""" + header = '{}'.format(str(self.__class__.__name__)) + msg = header + "(input_shape={}, num_rand={}, noise_scale={})".format( + self.input_shape, self.num_rand, self.noise_scale) + return msg + + +if __name__ == "__main__": + # Now, we can directly reference the classes in our config! + config = BCConfig() + config.observation.encoder.custom_image.core_class = "CustomImageEncoderCore" # Custom class, in string form + config.observation.encoder.custom_image.core_kwargs.welcome_str = "hi there!" # Any custom arguments, of any primitive type that is json-able + config.observation.encoder.custom_image.obs_randomizer_class = "CustomImageRandomizer" + config.observation.encoder.custom_image.obs_randomizer_kwargs.num_rand = 3 + config.observation.encoder.custom_image.obs_randomizer_kwargs.noise_scale = 0.05 + + # We can also directly use this new modality and associate dataset / observation keys with it! + config.observation.modalities.obs.custom_image = ["my_image1", "my_image2"] + config.observation.modalities.goal.custom_image = ["my_image2", "my_image3"] + + # Let's view our config + print(config) + + # That's it! Now we can pass this config into our training script, and robomimic will directly use our + # custom modality + encoder network diff --git a/code_src/rise_robomimic/examples/notebooks/datasets.ipynb b/code_src/rise_robomimic/examples/notebooks/datasets.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..32893b7ae9776be7e859334c0621c36bf5606d30 --- /dev/null +++ b/code_src/rise_robomimic/examples/notebooks/datasets.ipynb @@ -0,0 +1,388 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "d7e6ab09", + "metadata": {}, + "source": [ + "# A deep dive into robomimic datasets\n", + "\n", + "This notebook will provide examples on how to work with robomimic datasets through various python code examples. This notebook assumes that you have installed `robomimic` and `robosuite` (which should be on the `offline_study` branch)." + ] + }, + { + "cell_type": "markdown", + "id": "2a05e543", + "metadata": {}, + "source": [ + "## Download dataset\n", + "\n", + "First, let's try downloading a simple dataset - we'll use the Lift (PH) dataset. Note that there are utility scripts such as `scripts/download_datasets.py` to do this for us, but for the purposes of this example, we'll use the python API." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4e2b90e6", + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "import json\n", + "import h5py\n", + "import numpy as np\n", + "\n", + "import robomimic\n", + "import robomimic.utils.file_utils as FileUtils\n", + "\n", + "# the dataset registry can be found at robomimic/__init__.py\n", + "from robomimic import DATASET_REGISTRY\n", + "\n", + "# set download folder and make it\n", + "download_folder = \"/tmp/robomimic_ds_example\"\n", + "os.makedirs(download_folder, exist_ok=True)\n", + "\n", + "# download the dataset\n", + "task = \"lift\"\n", + "dataset_type = \"ph\"\n", + "hdf5_type = \"low_dim\"\n", + "FileUtils.download_url(\n", + " url=DATASET_REGISTRY[task][dataset_type][hdf5_type][\"url\"], \n", + " download_dir=download_folder,\n", + ")\n", + "\n", + "# enforce that the dataset exists\n", + "dataset_path = os.path.join(download_folder, \"low_dim_v141.hdf5\")\n", + "assert os.path.exists(dataset_path)" + ] + }, + { + "cell_type": "markdown", + "id": "54bdec82", + "metadata": {}, + "source": [ + "## Read quantities from dataset\n", + "\n", + "Next, let's demonstrate how to read different quantities from the dataset. There are scripts such as `scripts/get_dataset_info.py` that can help you easily understand the contents of a dataset, but in this example, we'll break down how to do this directly.\n", + "\n", + "First, let's take a look at the number of demonstrations in the file." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a35cd8e9", + "metadata": {}, + "outputs": [], + "source": [ + "# open file\n", + "f = h5py.File(dataset_path, \"r\")\n", + "\n", + "# each demonstration is a group under \"data\"\n", + "demos = list(f[\"data\"].keys())\n", + "num_demos = len(demos)\n", + "\n", + "print(\"hdf5 file {} has {} demonstrations\".format(dataset_path, num_demos))" + ] + }, + { + "cell_type": "markdown", + "id": "bdb073a0", + "metadata": {}, + "source": [ + "Next, let's list all of the demonstrations, along with the number of state-action pairs in each demonstration." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9bda3e70", + "metadata": {}, + "outputs": [], + "source": [ + "# each demonstration is named \"demo_#\" where # is a number.\n", + "# Let's put the demonstration list in increasing episode order\n", + "inds = np.argsort([int(elem[5:]) for elem in demos])\n", + "demos = [demos[i] for i in inds]\n", + "\n", + "for ep in demos:\n", + " num_actions = f[\"data/{}/actions\".format(ep)].shape[0]\n", + " print(\"{} has {} samples\".format(ep, num_actions))" + ] + }, + { + "cell_type": "markdown", + "id": "ff998d62", + "metadata": {}, + "source": [ + "Now, let's dig into a single trajectory to take a look at some of the quantities in each demonstration." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2f7b497a", + "metadata": {}, + "outputs": [], + "source": [ + "# look at first demonstration\n", + "demo_key = demos[0]\n", + "demo_grp = f[\"data/{}\".format(demo_key)]\n", + "\n", + "# Each observation is a dictionary that maps modalities to numpy arrays, and\n", + "# each action is a numpy array. Let's print the observations and actions for the \n", + "# first 5 timesteps of this trajectory.\n", + "for t in range(5):\n", + " print(\"timestep {}\".format(t))\n", + " obs_t = dict()\n", + " # each observation modality is stored as a subgroup\n", + " for k in demo_grp[\"obs\"]:\n", + " obs_t[k] = demo_grp[\"obs/{}\".format(k)][t] # numpy array\n", + " act_t = demo_grp[\"actions\"][t]\n", + " \n", + " # pretty-print observation and action using json\n", + " obs_t_pp = { k : obs_t[k].tolist() for k in obs_t }\n", + " print(\"obs\")\n", + " print(json.dumps(obs_t_pp, indent=4))\n", + " print(\"action\")\n", + " print(act_t)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "552be387", + "metadata": {}, + "outputs": [], + "source": [ + "# we can also grab multiple timesteps at once directly, or even the full trajectory at once\n", + "first_ten_actions = demo_grp[\"actions\"][:10]\n", + "print(\"shape of first ten actions {}\".format(first_ten_actions.shape))\n", + "all_actions = demo_grp[\"actions\"][:]\n", + "print(\"shape of all actions {}\".format(all_actions.shape))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "57976238", + "metadata": {}, + "outputs": [], + "source": [ + "# the trajectory also contains the next observations under \"next_obs\", \n", + "# for convenient use in a batch (offline) RL pipeline. Let's verify\n", + "# that \"next_obs\" and \"obs\" are offset by 1.\n", + "for k in demo_grp[\"obs\"]:\n", + " # obs_{t+1} == next_obs_{t}\n", + " assert(np.allclose(demo_grp[\"obs\"][k][1:], demo_grp[\"next_obs\"][k][:-1]))\n", + "print(\"success\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "51ab4a38", + "metadata": {}, + "outputs": [], + "source": [ + "# we also have \"done\" and \"reward\" information stored in each trajectory.\n", + "# In this case, we have sparse rewards that indicate task completion at\n", + "# that timestep.\n", + "dones = demo_grp[\"dones\"][:]\n", + "rewards = demo_grp[\"rewards\"][:]\n", + "print(\"dones\")\n", + "print(dones)\n", + "print(\"\")\n", + "print(\"rewards\")\n", + "print(rewards)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "360df27c", + "metadata": {}, + "outputs": [], + "source": [ + "# each demonstration also contains metadata\n", + "num_samples = demo_grp.attrs[\"num_samples\"] # number of samples in this trajectory\n", + "mujoco_xml_file = demo_grp.attrs[\"model_file\"] # mujoco XML file for this demonstration\n", + "print(mujoco_xml_file)" + ] + }, + { + "cell_type": "markdown", + "id": "5f10f98f", + "metadata": {}, + "source": [ + "Finally, let's take a look at some global metadata present in the file. The hdf5 file stores environment metadata which is a convenient way to understand which simulation environment (task) the dataset was collected on. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3b579caf", + "metadata": {}, + "outputs": [], + "source": [ + "env_meta = json.loads(f[\"data\"].attrs[\"env_args\"])\n", + "# note: we could also have used the following function:\n", + "# env_meta = FileUtils.get_env_metadata_from_dataset(dataset_path=dataset_path)\n", + "print(\"==== Env Meta ====\")\n", + "print(json.dumps(env_meta, indent=4))\n", + "print(\"\")" + ] + }, + { + "cell_type": "markdown", + "id": "b395453a", + "metadata": {}, + "source": [ + "## Visualizing demonstration trajectories\n", + "\n", + "Finally, let's play some of these demonstrations back in the simulation environment to easily visualize the data that was collected." + ] + }, + { + "cell_type": "markdown", + "id": "d613ab93", + "metadata": {}, + "source": [ + "It turns out that the environment metadata stored in the hdf5 allows us to easily create a simulation environment that is consistent with the way the dataset was collected!" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9c98068e", + "metadata": {}, + "outputs": [], + "source": [ + "import robomimic.utils.env_utils as EnvUtils\n", + "\n", + "# create simulation environment from environment metedata\n", + "env = EnvUtils.create_env_from_metadata(\n", + " env_meta=env_meta, \n", + " render=False, # no on-screen rendering\n", + " render_offscreen=True, # off-screen rendering to support rendering video frames\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "595a47d7", + "metadata": {}, + "outputs": [], + "source": [ + "import robomimic.utils.obs_utils as ObsUtils\n", + "\n", + "# We normally need to make sure robomimic knows which observations are images (for the\n", + "# data processing pipeline). This is usually inferred from your training config, but\n", + "# since we are just playing back demonstrations, we just need to initialize robomimic\n", + "# with a dummy spec.\n", + "dummy_spec = dict(\n", + " obs=dict(\n", + " low_dim=[\"robot0_eef_pos\"],\n", + " rgb=[],\n", + " ),\n", + ")\n", + "ObsUtils.initialize_obs_utils_with_obs_specs(obs_modality_specs=dummy_spec)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d997cf39", + "metadata": {}, + "outputs": [], + "source": [ + "import imageio\n", + "\n", + "# prepare to write playback trajectories to video\n", + "video_path = os.path.join(download_folder, \"playback.mp4\")\n", + "video_writer = imageio.get_writer(video_path, fps=20)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dfae1aaa", + "metadata": {}, + "outputs": [], + "source": [ + "def playback_trajectory(demo_key):\n", + " \"\"\"\n", + " Simple helper function to playback the trajectory stored under the hdf5 group @demo_key and\n", + " write frames rendered from the simulation to the active @video_writer.\n", + " \"\"\"\n", + " \n", + " # robosuite datasets store the ground-truth simulator states under the \"states\" key.\n", + " # We will use the first one, alone with the model xml, to reset the environment to\n", + " # the initial configuration before playing back actions.\n", + " init_state = f[\"data/{}/states\".format(demo_key)][0]\n", + " model_xml = f[\"data/{}\".format(demo_key)].attrs[\"model_file\"]\n", + " initial_state_dict = dict(states=init_state, model=model_xml)\n", + " \n", + " # reset to initial state\n", + " env.reset_to(initial_state_dict)\n", + " \n", + " # playback actions one by one, and render frames\n", + " actions = f[\"data/{}/actions\".format(demo_key)][:]\n", + " for t in range(actions.shape[0]):\n", + " env.step(actions[t])\n", + " video_img = env.render(mode=\"rgb_array\", height=512, width=512, camera_name=\"agentview\")\n", + " video_writer.append_data(video_img)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "926d1811", + "metadata": {}, + "outputs": [], + "source": [ + "# playback the first 5 demos\n", + "for ep in demos[:5]:\n", + " print(\"Playing back demo key: {}\".format(ep))\n", + " playback_trajectory(ep)\n", + "\n", + "# done writing video\n", + "video_writer.close()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bc89c8d8", + "metadata": {}, + "outputs": [], + "source": [ + "# view the trajectories!\n", + "from IPython.display import Video\n", + "Video(video_path, embed=True)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.12" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/code_src/rise_robomimic/examples/notebooks/run_policy.ipynb b/code_src/rise_robomimic/examples/notebooks/run_policy.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..913d74ec40c071f67a45725f11ac21b01c3b56a6 --- /dev/null +++ b/code_src/rise_robomimic/examples/notebooks/run_policy.ipynb @@ -0,0 +1,287 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "b2b15f2e", + "metadata": {}, + "source": [ + "# Run a trained policy\n", + "\n", + "This notebook will provide examples on how to run a trained policy and visualize the rollout." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "000a4ff3", + "metadata": {}, + "outputs": [], + "source": [ + "import argparse\n", + "import json\n", + "import h5py\n", + "import imageio\n", + "import numpy as np\n", + "import os\n", + "from copy import deepcopy\n", + "\n", + "import torch\n", + "\n", + "import robomimic\n", + "import robomimic.utils.file_utils as FileUtils\n", + "import robomimic.utils.torch_utils as TorchUtils\n", + "import robomimic.utils.tensor_utils as TensorUtils\n", + "import robomimic.utils.obs_utils as ObsUtils\n", + "from robomimic.envs.env_base import EnvBase\n", + "from robomimic.algo import RolloutPolicy\n", + "\n", + "import urllib.request\n" + ] + }, + { + "cell_type": "markdown", + "id": "47427159", + "metadata": {}, + "source": [ + "### Download policy checkpoint\n", + "First, let's try downloading a pretrained model from our model zoo." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9dfdfe5e", + "metadata": {}, + "outputs": [], + "source": [ + "# Get pretrained checkpooint from the model zoo\n", + "\n", + "ckpt_path = \"lift_ph_low_dim_epoch_1000_succ_100.pth\"\n", + "# Lift (Proficient Human)\n", + "urllib.request.urlretrieve(\n", + " \"http://downloads.cs.stanford.edu/downloads/rt_benchmark/model_zoo/lift/bc_rnn/lift_ph_low_dim_epoch_1000_succ_100.pth\",\n", + " filename=ckpt_path\n", + ")\n", + "\n", + "assert os.path.exists(ckpt_path)" + ] + }, + { + "cell_type": "markdown", + "id": "2c2c25c6", + "metadata": {}, + "source": [ + "### Loading trained policy\n", + "We have a convenient function called `policy_from_checkpoint` that takes care of building the correct model from the checkpoint and load the trained weights. Of course you could also load the checkpoint manually." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bf84aed6", + "metadata": {}, + "outputs": [], + "source": [ + "device = TorchUtils.get_torch_device(try_to_use_cuda=True)\n", + "\n", + "# restore policy\n", + "policy, ckpt_dict = FileUtils.policy_from_checkpoint(ckpt_path=ckpt_path, device=device, verbose=True)" + ] + }, + { + "cell_type": "markdown", + "id": "2872a3f0", + "metadata": {}, + "source": [ + "### Creating rollout envionment\n", + "The policy checkpoint also contains sufficient information to recreate the environment that it's trained with. Again, you may manually create the environment." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "12d00c2a", + "metadata": {}, + "outputs": [], + "source": [ + "# create environment from saved checkpoint\n", + "env, _ = FileUtils.env_from_checkpoint(\n", + " ckpt_dict=ckpt_dict, \n", + " render=False, # we won't do on-screen rendering in the notebook\n", + " render_offscreen=True, # render to RGB images for video\n", + " verbose=True,\n", + ")" + ] + }, + { + "cell_type": "markdown", + "id": "c7ac0e9f", + "metadata": {}, + "source": [ + "### Define the rollout loop\n", + "Now let's define the main rollout loop. The loop runs the policy to a target `horizon` and optionally writes the rollout to a video." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3dd1375e", + "metadata": {}, + "outputs": [], + "source": [ + "def rollout(policy, env, horizon, render=False, video_writer=None, video_skip=5, camera_names=None):\n", + " \"\"\"\n", + " Helper function to carry out rollouts. Supports on-screen rendering, off-screen rendering to a video, \n", + " and returns the rollout trajectory.\n", + " Args:\n", + " policy (instance of RolloutPolicy): policy loaded from a checkpoint\n", + " env (instance of EnvBase): env loaded from a checkpoint or demonstration metadata\n", + " horizon (int): maximum horizon for the rollout\n", + " render (bool): whether to render rollout on-screen\n", + " video_writer (imageio writer): if provided, use to write rollout to video\n", + " video_skip (int): how often to write video frames\n", + " camera_names (list): determines which camera(s) are used for rendering. Pass more than\n", + " one to output a video with multiple camera views concatenated horizontally.\n", + " Returns:\n", + " stats (dict): some statistics for the rollout - such as return, horizon, and task success\n", + " \"\"\"\n", + " assert isinstance(env, EnvBase)\n", + " assert isinstance(policy, RolloutPolicy)\n", + " assert not (render and (video_writer is not None))\n", + "\n", + " policy.start_episode()\n", + " obs = env.reset()\n", + " state_dict = env.get_state()\n", + "\n", + " # hack that is necessary for robosuite tasks for deterministic action playback\n", + " obs = env.reset_to(state_dict)\n", + "\n", + " results = {}\n", + " video_count = 0 # video frame counter\n", + " total_reward = 0.\n", + " try:\n", + " for step_i in range(horizon):\n", + "\n", + " # get action from policy\n", + " act = policy(ob=obs)\n", + "\n", + " # play action\n", + " next_obs, r, done, _ = env.step(act)\n", + "\n", + " # compute reward\n", + " total_reward += r\n", + " success = env.is_success()[\"task\"]\n", + "\n", + " # visualization\n", + " if render:\n", + " env.render(mode=\"human\", camera_name=camera_names[0])\n", + " if video_writer is not None:\n", + " if video_count % video_skip == 0:\n", + " video_img = []\n", + " for cam_name in camera_names:\n", + " video_img.append(env.render(mode=\"rgb_array\", height=512, width=512, camera_name=cam_name))\n", + " video_img = np.concatenate(video_img, axis=1) # concatenate horizontally\n", + " video_writer.append_data(video_img)\n", + " video_count += 1\n", + "\n", + " # break if done or if success\n", + " if done or success:\n", + " break\n", + "\n", + " # update for next iter\n", + " obs = deepcopy(next_obs)\n", + " state_dict = env.get_state()\n", + "\n", + " except env.rollout_exceptions as e:\n", + " print(\"WARNING: got rollout exception {}\".format(e))\n", + "\n", + " stats = dict(Return=total_reward, Horizon=(step_i + 1), Success_Rate=float(success))\n", + "\n", + " return stats\n" + ] + }, + { + "cell_type": "markdown", + "id": "0b43d371", + "metadata": {}, + "source": [ + "### Run the policy\n", + "Now let's rollout the policy!" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "be6e1878", + "metadata": {}, + "outputs": [], + "source": [ + "rollout_horizon = 400\n", + "np.random.seed(0)\n", + "torch.manual_seed(0)\n", + "video_path = \"rollout.mp4\"\n", + "video_writer = imageio.get_writer(video_path, fps=20)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7fa67efe", + "metadata": {}, + "outputs": [], + "source": [ + "stats = rollout(\n", + " policy=policy, \n", + " env=env, \n", + " horizon=rollout_horizon, \n", + " render=False, \n", + " video_writer=video_writer, \n", + " video_skip=5, \n", + " camera_names=[\"agentview\"]\n", + ")\n", + "print(stats)\n", + "video_writer.close()" + ] + }, + { + "cell_type": "markdown", + "id": "fe79bc19", + "metadata": {}, + "source": [ + "### Visualize the rollout" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "97472b37", + "metadata": {}, + "outputs": [], + "source": [ + "from IPython.display import Video\n", + "Video(video_path)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.12" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/code_src/rise_robomimic/examples/simple_config.py b/code_src/rise_robomimic/examples/simple_config.py new file mode 100644 index 0000000000000000000000000000000000000000..e80c6219479600f3d64b3df0b5bf32fb5f341af2 --- /dev/null +++ b/code_src/rise_robomimic/examples/simple_config.py @@ -0,0 +1,49 @@ +""" +An example for creating and using the custom Config object. +""" +from robomimic.config.base_config import Config + +if __name__ == "__main__": + + # create config + config = Config() + + config.train.batch_size = 100 + config.train.learning_rate = 1e-3 + config.algo.actor_network_size = [1000, 1000] + config.lock() # prevent accidental changes + + # access config + print("batch_size={}".format(config.train.batch_size)) + + # the config is locked --- cannot add new keys or modify existing keys + try: + config.train.optimizer = "Adam" + except RuntimeError as e: + print(e) + + # values_unlocked scope allows modifying values of existing keys, but not adding keys + with config.values_unlocked(): + config.train.batch_size = 200 + print("batch_size={}".format(config.train.batch_size)) + + # allow adding new keys to the config + with config.unlocked(): + config.test.num_eval = 10 + + assert config.is_locked + assert config.test.is_locked + + # read external config from a dict + ext_config = { + "train": { + "learning_rate": 1e-3 + }, + "algo": { + "actor_network_size": [1000, 1000] + } + } + with config.values_unlocked(): + config.update(ext_config) + + print(config) \ No newline at end of file diff --git a/code_src/rise_robomimic/examples/simple_obs_nets.py b/code_src/rise_robomimic/examples/simple_obs_nets.py new file mode 100644 index 0000000000000000000000000000000000000000..236beaa8a3f362001e69b27697c2bb49026ae710 --- /dev/null +++ b/code_src/rise_robomimic/examples/simple_obs_nets.py @@ -0,0 +1,133 @@ +""" +A simple example showing how to construct an ObservationEncoder for processing multiple input modalities. +This is purely for instructional purposes, in case others would like to make use of or extend the +functionality. +""" + +from collections import OrderedDict + +import torch +from robomimic.models.base_nets import MLP +from robomimic.models.obs_nets import ObservationEncoder, ObservationDecoder +from robomimic.models.obs_core import CropRandomizer +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.obs_utils as ObsUtils + + +def simple_obs_example(): + obs_encoder = ObservationEncoder(feature_activation=torch.nn.ReLU) + + # There are two ways to construct the network for processing a input observation. + + # 1. Construct through keyword args and class name + + # Assume we are processing image input of shape (3, 224, 224). + camera1_shape = [3, 224, 224] + + # We will use a reconfigurable image processing backbone VisualCore to process the input image observation key + net_class = "VisualCore" # this is defined in models/base_nets.py + + # kwargs for VisualCore network + net_kwargs = { + "input_shape": camera1_shape, + "backbone_class": "ResNet18Conv", # use ResNet18 as the visualcore backbone + "backbone_kwargs": {"pretrained": False, "input_coord_conv": False}, + "pool_class": "SpatialSoftmax", # use spatial softmax to regularize the model output + "pool_kwargs": {"num_kp": 32} + } + + # register the network for processing the observation key + obs_encoder.register_obs_key( + name="camera1", + shape=camera1_shape, + net_class=net_class, + net_kwargs=net_kwargs, + ) + + # 2. Alternatively, we could initialize the observation key network outside of the ObservationEncoder + + # The image doesn't have to be of the same shape + camera2_shape = [3, 160, 240] + + # We could also attach an observation randomizer to perturb the input observation key before sending to the network + image_randomizer = CropRandomizer(input_shape=camera2_shape, crop_height=140, crop_width=220) + + # the cropper will alter the input shape + net_kwargs["input_shape"] = image_randomizer.output_shape_in(camera2_shape) + net = ObsUtils.OBS_ENCODER_CORES[net_class](**net_kwargs) + + obs_encoder.register_obs_key( + name="camera2", + shape=camera2_shape, + net=net, + randomizer=image_randomizer, + ) + + # ObservationEncoder also supports weight sharing between keys + camera3_shape = [3, 224, 224] + obs_encoder.register_obs_key( + name="camera3", + shape=camera3_shape, + share_net_from="camera1", + ) + + # We could mix low-dimensional observation, e.g., proprioception signal, in the encoder + proprio_shape = [12] + net = MLP(input_dim=12, output_dim=32, layer_dims=(128,), output_activation=None) + obs_encoder.register_obs_key( + name="proprio", + shape=proprio_shape, + net=net, + ) + + # Before constructing the encoder, make sure we register all of our observation keys with corresponding modalities + # (this will determine how they are processed during training) + obs_modality_mapping = { + "low_dim": ["proprio"], + "rgb": ["camera1", "camera2", "camera3"], + } + ObsUtils.initialize_obs_modality_mapping_from_dict(modality_mapping=obs_modality_mapping) + + # Finally, construct the observation encoder + obs_encoder.make() + + # pretty-print the observation encoder + print(obs_encoder) + + # Construct fake inputs + inputs = { + "camera1": torch.randn(camera1_shape), + "camera2": torch.randn(camera2_shape), + "camera3": torch.randn(camera3_shape), + "proprio": torch.randn(proprio_shape) + } + + # Add a batch dimension + inputs = TensorUtils.to_batch(inputs) + + # Send to GPU if applicable + if torch.cuda.is_available(): + inputs = TensorUtils.to_device(inputs, torch.device("cuda:0")) + obs_encoder.cuda() + + # output from each obs key network is concatenated as a flat vector. + # The concatenation order is the same as the keys are registered + obs_feature = obs_encoder(inputs) + + print(obs_feature.shape) + + # A convenient wrapper for decoding the feature vector to named output is ObservationDecoder + obs_decoder = ObservationDecoder( + input_feat_dim=obs_encoder.output_shape()[0], + decode_shapes=OrderedDict({"action": (7,)}) + ) + + # Send to GPU if applicable + if torch.cuda.is_available(): + obs_decoder.cuda() + + print(obs_decoder(obs_feature)) + + +if __name__ == "__main__": + simple_obs_example() diff --git a/code_src/rise_robomimic/examples/simple_train_loop.py b/code_src/rise_robomimic/examples/simple_train_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..3e5c3c50209211e4efbb455c4b9e8ed6ae1622cf --- /dev/null +++ b/code_src/rise_robomimic/examples/simple_train_loop.py @@ -0,0 +1,188 @@ +""" +WARNING: This script is only for instructive purposes, and is missing several useful + components used during training such as logging and rollout evaluation. + +Example script for demonstrating how the SequenceDataset class and a training loop +can interact. This is meant to help others who would like to use our provided +datasets and dataset class in other applications. +""" +import numpy as np + +import torch +from torch.utils.data import DataLoader + +import robomimic +import robomimic.utils.obs_utils as ObsUtils +import robomimic.utils.torch_utils as TorchUtils +import robomimic.utils.test_utils as TestUtils +import robomimic.utils.file_utils as FileUtils +from robomimic.utils.dataset import SequenceDataset + +from robomimic.config import config_factory +from robomimic.algo import algo_factory + + +def get_data_loader(dataset_path): + """ + Get a data loader to sample batches of data. + + Args: + dataset_path (str): path to the dataset hdf5 + """ + dataset = SequenceDataset( + hdf5_path=dataset_path, + obs_keys=( # observations we want to appear in batches + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object", + ), + dataset_keys=( # can optionally specify more keys here if they should appear in batches + "actions", + "rewards", + "dones", + ), + load_next_obs=True, + frame_stack=1, + seq_length=10, # length-10 temporal sequences + pad_frame_stack=True, + pad_seq_length=True, # pad last obs per trajectory to ensure all sequences are sampled + get_pad_mask=False, + goal_mode=None, + hdf5_cache_mode="all", # cache dataset in memory to avoid repeated file i/o + hdf5_use_swmr=True, + hdf5_normalize_obs=False, + filter_by_attribute=None, # can optionally provide a filter key here + ) + print("\n============= Created Dataset =============") + print(dataset) + print("") + + data_loader = DataLoader( + dataset=dataset, + sampler=None, # no custom sampling logic (uniform sampling) + batch_size=100, # batches of size 100 + shuffle=True, + num_workers=0, + drop_last=True # don't provide last batch in dataset pass if it's less than 100 in size + ) + return data_loader + + +def get_example_model(dataset_path, device): + """ + Use a default config to construct a BC model. + """ + + # default BC config + config = config_factory(algo_name="bc") + + # read config to set up metadata for observation modalities (e.g. detecting rgb observations) + ObsUtils.initialize_obs_utils_with_config(config) + + # read dataset to get some metadata for constructing model + shape_meta = FileUtils.get_shape_metadata_from_dataset( + dataset_path=dataset_path, + all_obs_keys=sorted(( + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object", + )), + ) + + # make BC model + model = algo_factory( + algo_name=config.algo_name, + config=config, + obs_key_shapes=shape_meta["all_shapes"], + ac_dim=shape_meta["ac_dim"], + device=device, + ) + return model + + +def print_batch_info(batch): + print("\n============= Batch Info =============") + for k in batch: + if k in ["obs", "next_obs"]: + print("key {}".format(k)) + for obs_key in batch[k]: + print(" obs key {} with shape {}".format(obs_key, batch[k][obs_key].shape)) + else: + print("key {} with shape {}".format(k, batch[k].shape)) + print("") + + +def run_train_loop(model, data_loader): + """ + Note: this is a stripped down version of @TrainUtils.run_epoch and the train loop + in the train function in train.py. Logging and evaluation rollouts were removed. + + Args: + model (Algo instance): instance of Algo class to use for training + data_loader (torch.utils.data.DataLoader instance): torch DataLoader for + sampling batches + """ + num_epochs = 50 + gradient_steps_per_epoch = 100 + has_printed_batch_info = False + + # ensure model is in train mode + model.set_train() + + for epoch in range(1, num_epochs + 1): # epoch numbers start at 1 + + # iterator for data_loader - it yields batches + data_loader_iter = iter(data_loader) + + # record losses + losses = [] + + for _ in range(gradient_steps_per_epoch): + + # load next batch from data loader + try: + batch = next(data_loader_iter) + except StopIteration: + # data loader ran out of batches - reset and yield first batch + data_loader_iter = iter(data_loader) + batch = next(data_loader_iter) + + if not has_printed_batch_info: + has_printed_batch_info = True + print_batch_info(batch) + + # process batch for training + input_batch = model.process_batch_for_training(batch) + input_batch = model.postprocess_batch_for_training(input_batch, obs_normalization_stats=None) + + # forward and backward pass + info = model.train_on_batch(batch=input_batch, epoch=epoch, validate=False) + + # record loss + step_log = model.log_info(info) + losses.append(step_log["Loss"]) + + # do anything model needs to after finishing epoch + model.on_epoch_end(epoch) + + print("Train Epoch {}: Loss {}".format(epoch, np.mean(losses))) + + +if __name__ == "__main__": + + # small dataset with a handful of trajectories + dataset_path = TestUtils.example_dataset_path() + + # set torch device + device = TorchUtils.get_torch_device(try_to_use_cuda=True) + + # get model + model = get_example_model(dataset_path=dataset_path, device=device) + + # get dataset loader + data_loader = get_data_loader(dataset_path=dataset_path) + + # run train loop + run_train_loop(model=model, data_loader=data_loader) diff --git a/code_src/rise_robomimic/examples/train_bc_rnn.py b/code_src/rise_robomimic/examples/train_bc_rnn.py new file mode 100644 index 0000000000000000000000000000000000000000..b3ec7c510afdee2c32671dda1fa1c464b35bf20d --- /dev/null +++ b/code_src/rise_robomimic/examples/train_bc_rnn.py @@ -0,0 +1,462 @@ +""" +WARNING: This script is only for instructive purposes, to point out different portions + of the config -- the preferred way to launch training runs is still with external + jsons and scripts/train.py (and optionally using scripts/hyperparameter_helper.py + to generate several config jsons by sweeping config settings). See the online + documentation for more information about launching training. + +Example script for training a BC-RNN agent by manually setting portions of the config in +python code. + +To see a quick training run, use the following command: + + python train_bc_rnn.py --debug + +To run a full length training run on your own dataset, use the following command: + + python train_bc_rnn.py --dataset /path/to/dataset.hdf5 --output /path/to/output_dir +""" +import argparse + +import robomimic +import robomimic.utils.torch_utils as TorchUtils +import robomimic.utils.test_utils as TestUtils +import robomimic.macros as Macros +from robomimic.config import config_factory +from robomimic.scripts.train import train + + +def robosuite_hyperparameters(config): + """ + Sets robosuite-specific hyperparameters. + + Args: + config (Config): Config to modify + + Returns: + Config: Modified config + """ + ## save config - if and when to save checkpoints ## + config.experiment.save.enabled = True # whether model saving should be enabled or disabled + config.experiment.save.every_n_seconds = None # save model every n seconds (set to None to disable) + config.experiment.save.every_n_epochs = 50 # save model every n epochs (set to None to disable) + config.experiment.save.epochs = [] # save model on these specific epochs + config.experiment.save.on_best_validation = False # save models that achieve best validation score + config.experiment.save.on_best_rollout_return = False # save models that achieve best rollout return + config.experiment.save.on_best_rollout_success_rate = True # save models that achieve best success rate + + # epoch definition - if not None, set an epoch to be this many gradient steps, else the full dataset size will be used + config.experiment.epoch_every_n_steps = 100 # each epoch is 100 gradient steps + config.experiment.validation_epoch_every_n_steps = 10 # each validation epoch is 10 gradient steps + + # envs to evaluate model on (assuming rollouts are enabled), to override the metadata stored in dataset + config.experiment.env = None # no need to set this (unless you want to override) + config.experiment.additional_envs = None # additional environments that should get evaluated + + ## rendering config ## + config.experiment.render = False # render on-screen or not + config.experiment.render_video = True # render evaluation rollouts to videos + config.experiment.keep_all_videos = False # save all videos, instead of only saving those for saved model checkpoints + config.experiment.video_skip = 5 # render video frame every n environment steps during rollout + + ## evaluation rollout config ## + config.experiment.rollout.enabled = True # enable evaluation rollouts + config.experiment.rollout.n = 50 # number of rollouts per evaluation + config.experiment.rollout.horizon = 400 # set horizon based on length of demonstrations (can be obtained with scripts/get_dataset_info.py) + config.experiment.rollout.rate = 50 # do rollouts every @rate epochs + config.experiment.rollout.warmstart = 0 # number of epochs to wait before starting rollouts + config.experiment.rollout.terminate_on_success = True # end rollout early after task success + + ## dataset loader config ## + + # num workers for loading data - generally set to 0 for low-dim datasets, and 2 for image datasets + config.train.num_data_workers = 0 # assume low-dim dataset + + # One of ["all", "low_dim", or None]. Set to "all" to cache entire hdf5 in memory - this is + # by far the fastest for data loading. Set to "low_dim" to cache all non-image data. Set + # to None to use no caching - in this case, every batch sample is retrieved via file i/o. + # You should almost never set this to None, even for large image datasets. + config.train.hdf5_cache_mode = "all" + + config.train.hdf5_use_swmr = True # used for parallel data loading + + # if true, normalize observations at train and test time, using the global mean and standard deviation + # of each observation in each dimension, computed across the training set. See SequenceDataset.normalize_obs + # in utils/dataset.py for more information. + config.train.hdf5_normalize_obs = False # no obs normalization + + # if provided, demonstrations are filtered by the list of demo keys under "mask/@hdf5_filter_key" + config.train.hdf5_filter_key = "train" # by default, use "train" and "valid" filter keys corresponding to train-valid split + config.train.hdf5_validation_filter_key = "valid" + + # fetch sequences of length 10 from dataset for RNN training + config.train.seq_length = 10 + + # keys from hdf5 to load per demonstration, besides "obs" and "next_obs" + config.train.dataset_keys = ( + "actions", + "rewards", + "dones", + ) + + # one of [None, "last"] - set to "last" to include goal observations in each batch + config.train.goal_mode = None # no need for goal observations + + ## learning config ## + config.train.cuda = True # try to use GPU (if present) or not + config.train.batch_size = 100 # batch size + config.train.num_epochs = 2000 # number of training epochs + config.train.seed = 1 # seed for training + + + ### Observation Config ### + config.observation.modalities.obs.low_dim = [ # specify low-dim observations for agent + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object", + ] + config.observation.modalities.obs.rgb = [] # no image observations + config.observation.modalities.goal.low_dim = [] # no low-dim goals + config.observation.modalities.goal.rgb = [] # no image goals + + # observation encoder architecture - applies to all networks that take observation dicts as input + + config.observation.encoder.rgb.core_class = "VisualCore" + config.observation.encoder.rgb.core_kwargs.feature_dimension = 64 + config.observation.encoder.rgb.core_kwargs.backbone_class = 'ResNet18Conv' # ResNet backbone for image observations (unused if no image observations) + config.observation.encoder.rgb.core_kwargs.backbone_kwargs.pretrained = False # kwargs for visual core + config.observation.encoder.rgb.core_kwargs.backbone_kwargs.input_coord_conv = False + config.observation.encoder.rgb.core_kwargs.pool_class = "SpatialSoftmax" # Alternate options are "SpatialMeanPool" or None (no pooling) + config.observation.encoder.rgb.core_kwargs.pool_kwargs.num_kp = 32 # Default arguments for "SpatialSoftmax" + config.observation.encoder.rgb.core_kwargs.pool_kwargs.learnable_temperature = False # Default arguments for "SpatialSoftmax" + config.observation.encoder.rgb.core_kwargs.pool_kwargs.temperature = 1.0 # Default arguments for "SpatialSoftmax" + config.observation.encoder.rgb.core_kwargs.pool_kwargs.noise_std = 0.0 # Default arguments for "SpatialSoftmax" + + # if you prefer to use pre-trained visual representations, uncomment the following lines + # R3M + # config.observation.encoder.rgb.core_kwargs.backbone_class = 'R3MConv' # R3M backbone for image observations (unused if no image observations) + # config.observation.encoder.rgb.core_kwargs.backbone_kwargs.r3m_model_class = 'resnet18' # R3M model class (resnet18, resnet34, resnet50) + # config.observation.encoder.rgb.core_kwargs.backbone_kwargs.freeze = True # whether to freeze network during training or allow finetuning + # config.observation.encoder.rgb.core_kwargs.pool_class = None # no pooling class for pretraining model + # MVP + # config.observation.encoder.rgb.core_kwargs.backbone_class = 'MVPConv' # MVP backbone for image observations (unused if no image observations) + # config.observation.encoder.rgb.core_kwargs.backbone_kwargs.mvp_model_class = 'vitb-mae-egosoup' # MVP model class (vits-mae-hoi, vits-mae-in, vits-sup-in, vitb-mae-egosoup, vitl-256-mae-egosoup) + # config.observation.encoder.rgb.core_kwargs.backbone_kwargs.freeze = True # whether to freeze network during training or allow finetuning + # config.observation.encoder.rgb.core_kwargs.pool_class = None # no pooling class for pretraining model + + # observation randomizer class - set to None to use no randomization, or 'CropRandomizer' to use crop randomization + config.observation.encoder.rgb.obs_randomizer_class = None + + # kwargs for observation randomizers (for the CropRandomizer, this is size and number of crops) + config.observation.encoder.rgb.obs_randomizer_kwargs.crop_height = 76 + config.observation.encoder.rgb.obs_randomizer_kwargs.crop_width = 76 + config.observation.encoder.rgb.obs_randomizer_kwargs.num_crops = 1 + config.observation.encoder.rgb.obs_randomizer_kwargs.pos_enc = False + + ### Algo Config ### + + # optimization parameters + config.algo.optim_params.policy.learning_rate.initial = 1e-4 # policy learning rate + config.algo.optim_params.policy.learning_rate.decay_factor = 0.1 # factor to decay LR by (if epoch schedule non-empty) + config.algo.optim_params.policy.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + config.algo.optim_params.policy.regularization.L2 = 0.00 # L2 regularization strength + + # loss weights + config.algo.loss.l2_weight = 1.0 # L2 loss weight + config.algo.loss.l1_weight = 0.0 # L1 loss weight + config.algo.loss.cos_weight = 0.0 # cosine loss weight + + # MLP network architecture (layers after observation encoder and RNN, if present) + config.algo.actor_layer_dims = () # empty MLP - go from RNN layer directly to action output + + # stochastic GMM policy + config.algo.gmm.enabled = True # enable GMM policy - policy outputs GMM action distribution + config.algo.gmm.num_modes = 5 # number of GMM modes + config.algo.gmm.min_std = 0.0001 # minimum std output from network + config.algo.gmm.std_activation = "softplus" # activation to use for std output from policy net + config.algo.gmm.low_noise_eval = True # low-std at test-time + + # rnn policy config + config.algo.rnn.enabled = True # enable RNN policy + config.algo.rnn.horizon = 10 # unroll length for RNN - should usually match train.seq_length + config.algo.rnn.hidden_dim = 400 # hidden dimension size + config.algo.rnn.rnn_type = "LSTM" # rnn type - one of "LSTM" or "GRU" + config.algo.rnn.num_layers = 2 # number of RNN layers that are stacked + config.algo.rnn.open_loop = False # if True, action predictions are only based on a single observation (not sequence) + hidden state + config.algo.rnn.kwargs.bidirectional = False # rnn kwargs + + return config + + +def momart_hyperparameters(config): + """ + Sets momart-specific hyperparameters. + + Args: + config (Config): Config to modify + + Returns: + Config: Modified config + """ + ## save config - if and when to save checkpoints ## + config.experiment.save.enabled = True # whether model saving should be enabled or disabled + config.experiment.save.every_n_seconds = None # save model every n seconds (set to None to disable) + config.experiment.save.every_n_epochs = 3 # save model every n epochs (set to None to disable) + config.experiment.save.epochs = [] # save model on these specific epochs + config.experiment.save.on_best_validation = True # save models that achieve best validation score + config.experiment.save.on_best_rollout_return = False # save models that achieve best rollout return + config.experiment.save.on_best_rollout_success_rate = True # save models that achieve best success rate + + # epoch definition - if not None, set an epoch to be this many gradient steps, else the full dataset size will be used + config.experiment.epoch_every_n_steps = None # each epoch is 100 gradient steps + config.experiment.validation_epoch_every_n_steps = 10 # each validation epoch is 10 gradient steps + + # envs to evaluate model on (assuming rollouts are enabled), to override the metadata stored in dataset + config.experiment.env = None # no need to set this (unless you want to override) + config.experiment.additional_envs = None # additional environments that should get evaluated + + ## rendering config ## + config.experiment.render = False # render on-screen or not + config.experiment.render_video = True # render evaluation rollouts to videos + config.experiment.keep_all_videos = False # save all videos, instead of only saving those for saved model checkpoints + config.experiment.video_skip = 5 # render video frame every n environment steps during rollout + + ## evaluation rollout config ## + config.experiment.rollout.enabled = True # enable evaluation rollouts + config.experiment.rollout.n = 30 # number of rollouts per evaluation + config.experiment.rollout.horizon = 1500 # maximum number of env steps per rollout + config.experiment.rollout.rate = 3 # do rollouts every @rate epochs + config.experiment.rollout.warmstart = 0 # number of epochs to wait before starting rollouts + config.experiment.rollout.terminate_on_success = True # end rollout early after task success + + ## dataset loader config ## + + # num workers for loading data - generally set to 0 for low-dim datasets, and 2 for image datasets + config.train.num_data_workers = 2 # assume low-dim dataset + + # One of ["all", "low_dim", or None]. Set to "all" to cache entire hdf5 in memory - this is + # by far the fastest for data loading. Set to "low_dim" to cache all non-image data. Set + # to None to use no caching - in this case, every batch sample is retrieved via file i/o. + # You should almost never set this to None, even for large image datasets. + config.train.hdf5_cache_mode = "low_dim" + + config.train.hdf5_use_swmr = True # used for parallel data loading + + # if true, normalize observations at train and test time, using the global mean and standard deviation + # of each observation in each dimension, computed across the training set. See SequenceDataset.normalize_obs + # in utils/dataset.py for more information. + config.train.hdf5_normalize_obs = False # no obs normalization + + # if provided, demonstrations are filtered by the list of demo keys under "mask/@hdf5_filter_key" + config.train.hdf5_filter_key = "train" # by default, use "train" and "valid" filter keys corresponding to train-valid split + config.train.hdf5_validation_filter_key = "valid" + + # fetch sequences of length 10 from dataset for RNN training + config.train.seq_length = 50 + + # keys from hdf5 to load per demonstration, besides "obs" and "next_obs" + config.train.dataset_keys = ( + "actions", + "rewards", + "dones", + ) + + # one of [None, "last"] - set to "last" to include goal observations in each batch + config.train.goal_mode = "last" # no need for goal observations + + ## learning config ## + config.train.cuda = True # try to use GPU (if present) or not + config.train.batch_size = 4 # batch size + config.train.num_epochs = 31 # number of training epochs + config.train.seed = 1 # seed for training + + + ### Observation Config ### + config.observation.modalities.obs.low_dim = [ # specify low-dim observations for agent + "proprio", + ] + config.observation.modalities.obs.rgb = [ + "rgb", + "rgb_wrist", + ] + + config.observation.modalities.obs.depth = [ + "depth", + "depth_wrist", + ] + config.observation.modalities.obs.scan = [ + "scan", + ] + config.observation.modalities.goal.low_dim = [] # no low-dim goals + config.observation.modalities.goal.rgb = [] # no rgb image goals + + ### Algo Config ### + + # optimization parameters + config.algo.optim_params.policy.learning_rate.initial = 1e-4 # policy learning rate + config.algo.optim_params.policy.learning_rate.decay_factor = 0.1 # factor to decay LR by (if epoch schedule non-empty) + config.algo.optim_params.policy.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + config.algo.optim_params.policy.regularization.L2 = 0.00 # L2 regularization strength + + # loss weights + config.algo.loss.l2_weight = 1.0 # L2 loss weight + config.algo.loss.l1_weight = 0.0 # L1 loss weight + config.algo.loss.cos_weight = 0.0 # cosine loss weight + + # MLP network architecture (layers after observation encoder and RNN, if present) + config.algo.actor_layer_dims = (300, 400) # MLP layers between RNN layer and action output + + # stochastic GMM policy + config.algo.gmm.enabled = True # enable GMM policy - policy outputs GMM action distribution + config.algo.gmm.num_modes = 5 # number of GMM modes + config.algo.gmm.min_std = 0.01 # minimum std output from network + config.algo.gmm.std_activation = "softplus" # activation to use for std output from policy net + config.algo.gmm.low_noise_eval = True # low-std at test-time + + # rnn policy config + config.algo.rnn.enabled = True # enable RNN policy + config.algo.rnn.horizon = 50 # unroll length for RNN - should usually match train.seq_length + config.algo.rnn.hidden_dim = 1200 # hidden dimension size + config.algo.rnn.rnn_type = "LSTM" # rnn type - one of "LSTM" or "GRU" + config.algo.rnn.num_layers = 2 # number of RNN layers that are stacked + config.algo.rnn.open_loop = False # if True, action predictions are only based on a single observation (not sequence) + hidden state + config.algo.rnn.kwargs.bidirectional = False # rnn kwargs + + return config + + +# Valid dataset types to use +DATASET_TYPES = { + "robosuite": { + "default_dataset_func": TestUtils.example_dataset_path, + "hp": robosuite_hyperparameters, + }, + "momart": { + "default_dataset_func": TestUtils.example_momart_dataset_path, + "hp": momart_hyperparameters, + }, +} + + +def get_config(dataset_type="robosuite", dataset_path=None, output_dir=None, debug=False): + """ + Construct config for training. + + Args: + dataset_type (str): Dataset type to use. Valid options are DATASET_TYPES. Default is "robosuite" + dataset_path (str or None): path to hdf5 dataset. Pass None to use a small default dataset. + output_dir (str): path to output folder, where logs, model checkpoints, and videos + will be written. If it doesn't exist, the directory will be created. Pass + None to use a default directory in /tmp. + debug (bool): if True, shrink training and rollout times to test a full training + run quickly. + """ + assert dataset_type in DATASET_TYPES, \ + f"Invalid dataset type. Valid options are: {list(DATASET_TYPES.keys())}, got: {dataset_type}" + + # handle args + if dataset_path is None: + # small dataset with a handful of trajectories + dataset_path = DATASET_TYPES[dataset_type]["default_dataset_func"]() + + if output_dir is None: + # default output directory created in /tmp + output_dir = TestUtils.temp_model_dir_path() + + # make default BC config + config = config_factory(algo_name="bc") + + ### Experiment Config ### + config.experiment.name = f"{dataset_type}_bc_rnn_example" # name of experiment used to make log files + config.experiment.validate = True # whether to do validation or not + config.experiment.logging.terminal_output_to_txt = False # whether to log stdout to txt file + config.experiment.logging.log_tb = True # enable tensorboard logging + + ### Train Config ### + config.train.data = dataset_path # path to hdf5 dataset + + # Write all results to this directory. A new folder with the timestamp will be created + # in this directory, and it will contain three subfolders - "log", "models", and "videos". + # The "log" directory will contain tensorboard and stdout txt logs. The "models" directory + # will contain saved model checkpoints. The "videos" directory contains evaluation rollout + # videos. + config.train.output_dir = output_dir # path to output folder + + # Load default hyperparameters based on dataset type + config = DATASET_TYPES[dataset_type]["hp"](config) + + # maybe make training length small for a quick run + if debug: + + # train and validate for 3 gradient steps per epoch, and 2 total epochs + config.experiment.epoch_every_n_steps = 3 + config.experiment.validation_epoch_every_n_steps = 3 + config.train.num_epochs = 2 + + # rollout and model saving every epoch, and make rollouts short + config.experiment.save.every_n_epochs = 1 + config.experiment.rollout.rate = 1 + config.experiment.rollout.n = 2 + config.experiment.rollout.horizon = 10 + + return config + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + + # Dataset path + parser.add_argument( + "--dataset", + type=str, + default=None, + help="(optional) path to input hdf5 dataset to use in example script. If not provided, \ + a default hdf5 packaged with the repository will be used.", + ) + + # Output dir + parser.add_argument( + "--output", + type=str, + default=None, + help="(optional) path to folder to use (or create) to output logs, model checkpoints, and rollout \ + videos. If not provided, a folder in /tmp will be used.", + ) + + # debug flag for quick training run + parser.add_argument( + "--debug", + action='store_true', + help="set this flag to run a quick training run for debugging purposes" + ) + + # type + parser.add_argument( + "--dataset_type", + type=str, + default="robosuite", + choices=list(DATASET_TYPES.keys()), + help=f"Dataset type to use. This will determine the default hyperparameter settings to use for training." + f"Valid options are: {list(DATASET_TYPES.keys())}. Default is robosuite." + ) + + args = parser.parse_args() + + # Turn debug mode on possibly + if args.debug: + Macros.DEBUG = True + + # config for training + config = get_config( + dataset_type=args.dataset_type, + dataset_path=args.dataset, + output_dir=args.output, + debug=args.debug + ) + + # set torch device + device = TorchUtils.get_torch_device(try_to_use_cuda=config.train.cuda) + + # run training + train(config, device=device) diff --git a/code_src/rise_robomimic/requirements-docs.txt b/code_src/rise_robomimic/requirements-docs.txt new file mode 100644 index 0000000000000000000000000000000000000000..4b0538e24a3a648ba885ddf9d42b39c26f48087a --- /dev/null +++ b/code_src/rise_robomimic/requirements-docs.txt @@ -0,0 +1,8 @@ +# requirements for building sphinx docs +pygments==2.4.1 +sphinx +sphinx_rtd_theme +sphinx_markdown_tables +sphinx_book_theme +recommonmark +nbsphinx diff --git a/code_src/rise_robomimic/requirements.txt b/code_src/rise_robomimic/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..6f64af97e452800bd70cce9deebfa085a69f71de --- /dev/null +++ b/code_src/rise_robomimic/requirements.txt @@ -0,0 +1,13 @@ +numpy>=1.13.3 +h5py +psutil +tqdm +termcolor +tensorboard +tensorboardX +imageio +imageio-ffmpeg +matplotlib +egl_probe>=1.0.1 +torch +torchvision diff --git a/code_src/rise_robomimic/robomimic/__init__.py b/code_src/rise_robomimic/robomimic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1930630a3c7354ea8c9453aa3a4b280cebb2eceb --- /dev/null +++ b/code_src/rise_robomimic/robomimic/__init__.py @@ -0,0 +1,159 @@ +__version__ = "0.3.1" + + +# stores released dataset links and rollout horizons in global dictionary. +# Structure is given below for each type of dataset: + +# robosuite / real +# { +# task: +# dataset_type: +# hdf5_type: +# url: link +# horizon: value +# ... +# ... +# ... +# } +DATASET_REGISTRY = {} + +# momart +# { +# task: +# dataset_type: +# url: link +# size: value +# ... +# ... +# } +MOMART_DATASET_REGISTRY = {} + + +def register_dataset_link(task, dataset_type, hdf5_type, link, horizon): + """ + Helper function to register dataset link in global dictionary. + Also takes a @horizon parameter - this corresponds to the evaluation + rollout horizon that should be used during training. + + Args: + task (str): name of task for this dataset + dataset_type (str): type of dataset (usually identifies the dataset source) + hdf5_type (str): type of hdf5 - usually one of "raw", "low_dim", or "image", + to identify the kind of observations in the dataset + link (str): download link for the dataset + horizon (int): evaluation rollout horizon that should be used with this dataset + """ + if task not in DATASET_REGISTRY: + DATASET_REGISTRY[task] = {} + if dataset_type not in DATASET_REGISTRY[task]: + DATASET_REGISTRY[task][dataset_type] = {} + DATASET_REGISTRY[task][dataset_type][hdf5_type] = dict(url=link, horizon=horizon) + + +def register_all_links(): + """ + Record all dataset links in this function. + """ + + # all proficient human datasets + ph_tasks = ["lift", "can", "square", "transport", "tool_hang", "lift_real", "can_real", "tool_hang_real"] + ph_horizons = [400, 400, 400, 700, 700, 1000, 1000, 1000] + for task, horizon in zip(ph_tasks, ph_horizons): + register_dataset_link(task=task, dataset_type="ph", hdf5_type="raw", horizon=horizon, + link="http://downloads.cs.stanford.edu/downloads/rt_benchmark/{}/ph/demo{}.hdf5".format( + task, "" if "real" in task else "_v141" + ) + ) + # real world datasets only have demo.hdf5 files which already contain all observation modalities + # while sim datasets store raw low-dim mujoco states in the demo.hdf5 + if "real" not in task: + register_dataset_link(task=task, dataset_type="ph", hdf5_type="low_dim", horizon=horizon, + link="http://downloads.cs.stanford.edu/downloads/rt_benchmark/{}/ph/low_dim_v141.hdf5".format(task)) + register_dataset_link(task=task, dataset_type="ph", hdf5_type="image", horizon=horizon, + link=None) + + # all multi human datasets + mh_tasks = ["lift", "can", "square", "transport"] + mh_horizons = [500, 500, 500, 1100] + for task, horizon in zip(mh_tasks, mh_horizons): + register_dataset_link(task=task, dataset_type="mh", hdf5_type="raw", horizon=horizon, + link="http://downloads.cs.stanford.edu/downloads/rt_benchmark/{}/mh/demo_v141.hdf5".format(task)) + register_dataset_link(task=task, dataset_type="mh", hdf5_type="low_dim", horizon=horizon, + link="http://downloads.cs.stanford.edu/downloads/rt_benchmark/{}/mh/low_dim_v141.hdf5".format(task)) + register_dataset_link(task=task, dataset_type="mh", hdf5_type="image", horizon=horizon, + link=None) + + # all machine generated datasets + for task, horizon in zip(["lift", "can"], [400, 400]): + register_dataset_link(task=task, dataset_type="mg", hdf5_type="raw", horizon=horizon, + link="http://downloads.cs.stanford.edu/downloads/rt_benchmark/{}/mg/demo_v141.hdf5".format(task)) + register_dataset_link(task=task, dataset_type="mg", hdf5_type="low_dim_sparse", horizon=horizon, + link="http://downloads.cs.stanford.edu/downloads/rt_benchmark/{}/mg/low_dim_sparse_v141.hdf5".format(task)) + register_dataset_link(task=task, dataset_type="mg", hdf5_type="image_sparse", horizon=horizon, + link=None) + register_dataset_link(task=task, dataset_type="mg", hdf5_type="low_dim_dense", horizon=horizon, + link="http://downloads.cs.stanford.edu/downloads/rt_benchmark/{}/mg/low_dim_dense_v141.hdf5".format(task)) + register_dataset_link(task=task, dataset_type="mg", hdf5_type="image_dense", horizon=horizon, + link=None) + + # can-paired dataset + register_dataset_link(task="can", dataset_type="paired", hdf5_type="raw", horizon=400, + link="http://downloads.cs.stanford.edu/downloads/rt_benchmark/can/paired/demo_v141.hdf5") + register_dataset_link(task="can", dataset_type="paired", hdf5_type="low_dim", horizon=400, + link="http://downloads.cs.stanford.edu/downloads/rt_benchmark/can/paired/low_dim_v141.hdf5") + register_dataset_link(task="can", dataset_type="paired", hdf5_type="image", horizon=400, + link=None) + + +def register_momart_dataset_link(task, dataset_type, link, dataset_size): + """ + Helper function to register dataset link in global dictionary. + Also takes a @horizon parameter - this corresponds to the evaluation + rollout horizon that should be used during training. + + Args: + task (str): name of task for this dataset + dataset_type (str): type of dataset (usually identifies the dataset source) + link (str): download link for the dataset + dataset_size (float): size of the dataset, in GB + """ + if task not in MOMART_DATASET_REGISTRY: + MOMART_DATASET_REGISTRY[task] = {} + if dataset_type not in MOMART_DATASET_REGISTRY[task]: + MOMART_DATASET_REGISTRY[task][dataset_type] = {} + MOMART_DATASET_REGISTRY[task][dataset_type] = dict(url=link, size=dataset_size) + + +def register_all_momart_links(): + """ + Record all dataset links in this function. + """ + # all tasks, mapped to their [exp, sub, gen, sam] sizes + momart_tasks = { + "table_setup_from_dishwasher": [14, 14, 3.3, 0.6], + "table_setup_from_dresser": [16, 17, 3.1, 0.7], + "table_cleanup_to_dishwasher": [23, 36, 5.3, 1.1], + "table_cleanup_to_sink": [17, 28, 2.9, 0.8], + "unload_dishwasher": [21, 27, 5.4, 1.0], + } + + momart_dataset_types = [ + "expert", + "suboptimal", + "generalize", + "sample", + ] + + # Iterate over all combos and register the link + for task, dataset_sizes in momart_tasks.items(): + for dataset_type, dataset_size in zip(momart_dataset_types, dataset_sizes): + register_momart_dataset_link( + task=task, + dataset_type=dataset_type, + link=f"http://downloads.cs.stanford.edu/downloads/rt_mm/{dataset_type}/{task}_{dataset_type}.hdf5", + dataset_size=dataset_size, + ) + + +register_all_links() +register_all_momart_links() diff --git a/code_src/rise_robomimic/robomimic/algo/__init__.py b/code_src/rise_robomimic/robomimic/algo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..188465c8463c5f51dbba07307c72c76639f93744 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/__init__.py @@ -0,0 +1,15 @@ +from robomimic.algo.algo import register_algo_factory_func, algo_name_to_factory_func, algo_factory, Algo, PolicyAlgo, ValueAlgo, PlannerAlgo, HierarchicalAlgo, RolloutPolicy + +# note: these imports are needed to register these classes in the global algo registry +from robomimic.algo.bc import BC, BC_Gaussian, BC_GMM, BC_VAE, BC_RNN, BC_RNN_GMM +from robomimic.algo.bcq import BCQ, BCQ_GMM, BCQ_Distributional +from robomimic.algo.cql import CQL +from robomimic.algo.iql import IQL +from robomimic.algo.gl import GL, GL_VAE, ValuePlanner +from robomimic.algo.hbc import HBC +from robomimic.algo.iris import IRIS +from robomimic.algo.td3_bc import TD3_BC +from robomimic.algo.iql_diffusion import IQLDiffusion +from robomimic.algo.idql_qsm import IDQL_QSM +from robomimic.algo.idql import IDQL +from robomimic.algo.discriminator import Discriminator \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/algo/algo.py b/code_src/rise_robomimic/robomimic/algo/algo.py new file mode 100644 index 0000000000000000000000000000000000000000..f050c27ee7425e732056d3c7480a1d2c935e513e --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/algo.py @@ -0,0 +1,525 @@ +""" +This file contains base classes that other algorithm classes subclass. +Each algorithm file also implements a algorithm factory function that +takes in an algorithm config (`config.algo`) and returns the particular +Algo subclass that should be instantiated, along with any extra kwargs. +These factory functions are registered into a global dictionary with the +@register_algo_factory_func function decorator. This makes it easy for +@algo_factory to instantiate the correct `Algo` subclass. +""" +import textwrap +from copy import deepcopy +from collections import OrderedDict + +import torch.nn as nn + +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.torch_utils as TorchUtils +import robomimic.utils.obs_utils as ObsUtils + + +# mapping from algo name to factory functions that map algo configs to algo class names +REGISTERED_ALGO_FACTORY_FUNCS = OrderedDict() + + +def register_algo_factory_func(algo_name): + """ + Function decorator to register algo factory functions that map algo configs to algo class names. + Each algorithm implements such a function, and decorates it with this decorator. + + Args: + algo_name (str): the algorithm name to register the algorithm under + """ + def decorator(factory_func): + REGISTERED_ALGO_FACTORY_FUNCS[algo_name] = factory_func + return decorator + + +def algo_name_to_factory_func(algo_name): + """ + Uses registry to retrieve algo factory function from algo name. + + Args: + algo_name (str): the algorithm name + """ + return REGISTERED_ALGO_FACTORY_FUNCS[algo_name] + + +def algo_factory(algo_name, config, obs_key_shapes, ac_dim, device): + """ + Factory function for creating algorithms based on the algorithm name and config. + + Args: + algo_name (str): the algorithm name + + config (BaseConfig instance): config object + + obs_key_shapes (OrderedDict): dictionary that maps observation keys to shapes + + ac_dim (int): dimension of action space + + device (torch.Device): where the algo should live (i.e. cpu, gpu) + """ + + # @algo_name is included as an arg to be explicit, but make sure it matches the config + assert algo_name == config.algo_name + + # use algo factory func to get algo class and kwargs from algo config + factory_func = algo_name_to_factory_func(algo_name) + algo_cls, algo_kwargs = factory_func(config.algo) + + # create algo instance + return algo_cls( + algo_config=config.algo, + obs_config=config.observation, + global_config=config, + obs_key_shapes=obs_key_shapes, + ac_dim=ac_dim, + device=device, + **algo_kwargs + ) + + +class Algo(object): + """ + Base algorithm class that all other algorithms subclass. Defines several + functions that should be overriden by subclasses, in order to provide + a standard API to be used by training functions such as @run_epoch in + utils/train_utils.py. + """ + def __init__( + self, + algo_config, + obs_config, + global_config, + obs_key_shapes, + ac_dim, + device + ): + """ + Args: + algo_config (Config object): instance of Config corresponding to the algo section + of the config + + obs_config (Config object): instance of Config corresponding to the observation + section of the config + + global_config (Config object): global training config + + obs_key_shapes (OrderedDict): dictionary that maps observation keys to shapes + + ac_dim (int): dimension of action space + + device (torch.Device): where the algo should live (i.e. cpu, gpu) + """ + self.optim_params = deepcopy(algo_config.optim_params) + self.algo_config = algo_config + self.obs_config = obs_config + self.global_config = global_config + + self.ac_dim = ac_dim + self.device = device + self.obs_key_shapes = obs_key_shapes + self.nets = nn.ModuleDict() + self._create_shapes(obs_config.modalities, obs_key_shapes) + self._create_networks() + self._create_optimizers() + assert isinstance(self.nets, nn.ModuleDict) + + def _create_shapes(self, obs_keys, obs_key_shapes): + """ + Create obs_shapes, goal_shapes, and subgoal_shapes dictionaries, to make it + easy for this algorithm object to keep track of observation key shapes. Each dictionary + maps observation key to shape. + + Args: + obs_keys (dict): dict of required observation keys for this training run (usually + specified by the obs config), e.g., {"obs": ["rgb", "proprio"], "goal": ["proprio"]} + obs_key_shapes (dict): dict of observation key shapes, e.g., {"rgb": [3, 224, 224]} + """ + # determine shapes + self.obs_shapes = OrderedDict() + self.goal_shapes = OrderedDict() + self.subgoal_shapes = OrderedDict() + + # We check across all modality groups (obs, goal, subgoal), and see if the inputted observation key exists + # across all modalitie specified in the config. If so, we store its corresponding shape internally + for k in obs_key_shapes: + if "obs" in self.obs_config.modalities and k in [obs_key for modality in self.obs_config.modalities.obs.values() for obs_key in modality]: + self.obs_shapes[k] = obs_key_shapes[k] + if "goal" in self.obs_config.modalities and k in [obs_key for modality in self.obs_config.modalities.goal.values() for obs_key in modality]: + self.goal_shapes[k] = obs_key_shapes[k] + if "subgoal" in self.obs_config.modalities and k in [obs_key for modality in self.obs_config.modalities.subgoal.values() for obs_key in modality]: + self.subgoal_shapes[k] = obs_key_shapes[k] + + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + @self.nets should be a ModuleDict. + """ + raise NotImplementedError + + def _create_optimizers(self): + """ + Creates optimizers using @self.optim_params and places them into @self.optimizers. + """ + self.optimizers = dict() + self.lr_schedulers = dict() + + for k in self.optim_params: + # only make optimizers for networks that have been created - @optim_params may have more + # settings for unused networks + if k in self.nets: + if isinstance(self.nets[k], nn.ModuleList): + self.optimizers[k] = [ + TorchUtils.optimizer_from_optim_params(net_optim_params=self.optim_params[k], net=self.nets[k][i]) + for i in range(len(self.nets[k])) + ] + self.lr_schedulers[k] = [ + TorchUtils.lr_scheduler_from_optim_params(net_optim_params=self.optim_params[k], net=self.nets[k][i], optimizer=self.optimizers[k][i]) + for i in range(len(self.nets[k])) + ] + else: + self.optimizers[k] = TorchUtils.optimizer_from_optim_params( + net_optim_params=self.optim_params[k], net=self.nets[k]) + self.lr_schedulers[k] = TorchUtils.lr_scheduler_from_optim_params( + net_optim_params=self.optim_params[k], net=self.nets[k], optimizer=self.optimizers[k]) + + def process_batch_for_training(self, batch): + """ + Processes input batch from a data loader to filter out + relevant information and prepare the batch for training. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader + + Returns: + input_batch (dict): processed and filtered batch that + will be used for training + """ + return batch + + def postprocess_batch_for_training(self, batch, obs_normalization_stats): + """ + Does some operations (like channel swap, uint8 to float conversion, normalization) + after @process_batch_for_training is called, in order to ensure these operations + take place on GPU. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader. Assumed to be on the device where + training will occur (after @process_batch_for_training + is called) + + obs_normalization_stats (dict or None): if provided, this should map observation + keys to dicts with a "mean" and "std" of shape (1, ...) where ... is the + default shape for the observation. + + Returns: + batch (dict): postproceesed batch + """ + + # ensure obs_normalization_stats are torch Tensors on proper device + obs_normalization_stats = TensorUtils.to_float(TensorUtils.to_device(TensorUtils.to_tensor(obs_normalization_stats), self.device)) + + # we will search the nested batch dictionary for the following special batch dict keys + # and apply the processing function to their values (which correspond to observations) + obs_keys = ["obs", "next_obs", "goal_obs"] + + def recurse_helper(d): + """ + Apply process_obs_dict to values in nested dictionary d that match a key in obs_keys. + """ + for k in d: + if k in obs_keys: + # found key - stop search and process observation + if d[k] is not None: + d[k] = ObsUtils.process_obs_dict(d[k]) + if obs_normalization_stats is not None: + d[k] = ObsUtils.normalize_obs(d[k], obs_normalization_stats=obs_normalization_stats) + elif isinstance(d[k], dict): + # search down into dictionary + recurse_helper(d[k]) + + recurse_helper(batch) + return batch + + def train_on_batch(self, batch, epoch, validate=False): + """ + Training on a single batch of data. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + validate (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + assert validate or self.nets.training + return OrderedDict() + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss log (dict): name -> summary statistic + """ + log = OrderedDict() + + # record current optimizer learning rates + for k in self.optimizers: + for i, param_group in enumerate(self.optimizers[k].param_groups): + log["Optimizer/{}{}_lr".format(k, i)] = param_group["lr"] + + return log + + def on_epoch_end(self, epoch): + """ + Called at the end of each epoch. + """ + + # LR scheduling updates + for k in self.lr_schedulers: + if self.lr_schedulers[k] is not None: + self.lr_schedulers[k].step() + + def set_eval(self): + """ + Prepare networks for evaluation. + """ + self.nets.eval() + + def set_train(self): + """ + Prepare networks for training. + """ + self.nets.train() + + def serialize(self): + """ + Get dictionary of current model parameters. + """ + return self.nets.state_dict() + + def deserialize(self, model_dict): + """ + Load model from a checkpoint. + + Args: + model_dict (dict): a dictionary saved by self.serialize() that contains + the same keys as @self.network_classes + """ + self.nets.load_state_dict(model_dict) + + def __repr__(self): + """ + Pretty print algorithm and network description. + """ + return "{} (\n".format(self.__class__.__name__) + \ + textwrap.indent(self.nets.__repr__(), ' ') + "\n)" + + def reset(self): + """ + Reset algo state to prepare for environment rollouts. + """ + pass + + +class PolicyAlgo(Algo): + """ + Base class for all algorithms that can be used as policies. + """ + def get_action(self, obs_dict, goal_dict=None): + """ + Get policy action outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + action (torch.Tensor): action tensor + """ + raise NotImplementedError + + +class ValueAlgo(Algo): + """ + Base class for all algorithms that can learn a value function. + """ + def get_state_value(self, obs_dict, goal_dict=None): + """ + Get state value outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + value (torch.Tensor): value tensor + """ + raise NotImplementedError + + def get_state_action_value(self, obs_dict, actions, goal_dict=None): + """ + Get state-action value outputs. + + Args: + obs_dict (dict): current observation + actions (torch.Tensor): action + goal_dict (dict): (optional) goal + + Returns: + value (torch.Tensor): value tensor + """ + raise NotImplementedError + + +class PlannerAlgo(Algo): + """ + Base class for all algorithms that can be used for planning subgoals + conditioned on current observations and potential goal observations. + """ + def get_subgoal_predictions(self, obs_dict, goal_dict=None): + """ + Get predicted subgoal outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + subgoal prediction (dict): name -> Tensor [batch_size, ...] + """ + raise NotImplementedError + + def sample_subgoals(self, obs_dict, goal_dict, num_samples=1): + """ + For planners that rely on sampling subgoals. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + subgoals (dict): name -> Tensor [batch_size, num_samples, ...] + """ + raise NotImplementedError + + +class HierarchicalAlgo(Algo): + """ + Base class for all hierarchical algorithms that consist of (1) subgoal planning + and (2) subgoal-conditioned policy learning. + """ + def get_action(self, obs_dict, goal_dict=None): + """ + Get policy action outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + action (torch.Tensor): action tensor + """ + raise NotImplementedError + + def get_subgoal_predictions(self, obs_dict, goal_dict=None): + """ + Get subgoal predictions from high-level subgoal planner. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + subgoal (dict): predicted subgoal + """ + raise NotImplementedError + + @property + def current_subgoal(self): + """ + Get the current subgoal for conditioning the low-level policy + + Returns: + current subgoal (dict): predicted subgoal + """ + raise NotImplementedError + + +class RolloutPolicy(object): + """ + Wraps @Algo object to make it easy to run policies in a rollout loop. + """ + def __init__(self, policy, obs_normalization_stats=None): + """ + Args: + policy (Algo instance): @Algo object to wrap to prepare for rollouts + + obs_normalization_stats (dict): optionally pass a dictionary for observation + normalization. This should map observation keys to dicts + with a "mean" and "std" of shape (1, ...) where ... is the default + shape for the observation. + """ + self.policy = policy + self.obs_normalization_stats = obs_normalization_stats + + def start_episode(self): + """ + Prepare the policy to start a new rollout. + """ + self.policy.set_eval() + self.policy.reset() + + def _prepare_observation(self, ob): + """ + Prepare raw observation dict from environment for policy. + + Args: + ob (dict): single observation dictionary from environment (no batch dimension, + and np.array values for each key) + """ + ob = TensorUtils.to_tensor(ob) + ob = TensorUtils.to_batch(ob) + ob = TensorUtils.to_device(ob, self.policy.device) + ob = TensorUtils.to_float(ob) + if self.obs_normalization_stats is not None: + # ensure obs_normalization_stats are torch Tensors on proper device + obs_normalization_stats = TensorUtils.to_float(TensorUtils.to_device(TensorUtils.to_tensor(self.obs_normalization_stats), self.policy.device)) + # limit normalization to obs keys being used, in case environment includes extra keys + ob = { k : ob[k] for k in self.policy.global_config.all_obs_keys } + ob = ObsUtils.normalize_obs(ob, obs_normalization_stats=obs_normalization_stats) + return ob + + def __repr__(self): + """Pretty print network description""" + return self.policy.__repr__() + + def __call__(self, ob, goal=None): + """ + Produce action from raw observation dict (and maybe goal dict) from environment. + + Args: + ob (dict): single observation dictionary from environment (no batch dimension, + and np.array values for each key) + goal (dict): goal observation + """ + ob = self._prepare_observation(ob) + if goal is not None: + goal = self._prepare_observation(goal) + ac = self.policy.get_action(obs_dict=ob, goal_dict=goal) + return TensorUtils.to_numpy(ac[0]) diff --git a/code_src/rise_robomimic/robomimic/algo/bc.py b/code_src/rise_robomimic/robomimic/algo/bc.py new file mode 100644 index 0000000000000000000000000000000000000000..091be78e9c479f935278c592c4f4c3eac3af4bf7 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/bc.py @@ -0,0 +1,875 @@ +""" +Implementation of Behavioral Cloning (BC). +""" +from collections import OrderedDict + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.distributions as D + +import robomimic.models.base_nets as BaseNets +import robomimic.models.obs_nets as ObsNets +import robomimic.models.policy_nets as PolicyNets +import robomimic.models.vae_nets as VAENets +import robomimic.utils.loss_utils as LossUtils +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.torch_utils as TorchUtils +import robomimic.utils.obs_utils as ObsUtils + +from robomimic.algo import register_algo_factory_func, PolicyAlgo + + +@register_algo_factory_func("bc") +def algo_config_to_class(algo_config): + """ + Maps algo config to the BC algo class to instantiate, along with additional algo kwargs. + + Args: + algo_config (Config instance): algo config + + Returns: + algo_class: subclass of Algo + algo_kwargs (dict): dictionary of additional kwargs to pass to algorithm + """ + + # note: we need the check below because some configs import BCConfig and exclude + # some of these options + gaussian_enabled = ("gaussian" in algo_config and algo_config.gaussian.enabled) + gmm_enabled = ("gmm" in algo_config and algo_config.gmm.enabled) + vae_enabled = ("vae" in algo_config and algo_config.vae.enabled) + + rnn_enabled = algo_config.rnn.enabled + # support legacy configs that do not have "transformer" item + transformer_enabled = ("transformer" in algo_config) and algo_config.transformer.enabled + + if gaussian_enabled: + if rnn_enabled: + raise NotImplementedError + elif transformer_enabled: + raise NotImplementedError + else: + algo_class, algo_kwargs = BC_Gaussian, {} + elif gmm_enabled: + if rnn_enabled: + algo_class, algo_kwargs = BC_RNN_GMM, {} + elif transformer_enabled: + algo_class, algo_kwargs = BC_Transformer_GMM, {} + else: + algo_class, algo_kwargs = BC_GMM, {} + elif vae_enabled: + if rnn_enabled: + raise NotImplementedError + elif transformer_enabled: + raise NotImplementedError + else: + algo_class, algo_kwargs = BC_VAE, {} + else: + if rnn_enabled: + algo_class, algo_kwargs = BC_RNN, {} + elif transformer_enabled: + algo_class, algo_kwargs = BC_Transformer, {} + else: + algo_class, algo_kwargs = BC, {} + + return algo_class, algo_kwargs + + +class BC(PolicyAlgo): + """ + Normal BC training. + """ + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + """ + self.nets = nn.ModuleDict() + self.nets["policy"] = PolicyNets.ActorNetwork( + obs_shapes=self.obs_shapes, + goal_shapes=self.goal_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.actor_layer_dims, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + ) + self.nets = self.nets.float().to(self.device) + + def process_batch_for_training(self, batch): + """ + Processes input batch from a data loader to filter out + relevant information and prepare the batch for training. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader + + Returns: + input_batch (dict): processed and filtered batch that + will be used for training + """ + input_batch = dict() + input_batch["obs"] = {k: batch["obs"][k][:, 0, :] for k in batch["obs"]} + input_batch["goal_obs"] = batch.get("goal_obs", None) # goals may not be present + input_batch["actions"] = batch["actions"][:, 0, :] + # we move to device first before float conversion because image observation modalities will be uint8 - + # this minimizes the amount of data transferred to GPU + return TensorUtils.to_float(TensorUtils.to_device(input_batch, self.device)) + + + def train_on_batch(self, batch, epoch, validate=False): + """ + Training on a single batch of data. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + validate (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + with TorchUtils.maybe_no_grad(no_grad=validate): + info = super(BC, self).train_on_batch(batch, epoch, validate=validate) + predictions = self._forward_training(batch) + losses = self._compute_losses(predictions, batch) + + info["predictions"] = TensorUtils.detach(predictions) + info["losses"] = TensorUtils.detach(losses) + + if not validate: + step_info = self._train_step(losses) + info.update(step_info) + + return info + + def _forward_training(self, batch): + """ + Internal helper function for BC algo class. Compute forward pass + and return network outputs in @predictions dict. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + Returns: + predictions (dict): dictionary containing network outputs + """ + predictions = OrderedDict() + actions = self.nets["policy"](obs_dict=batch["obs"], goal_dict=batch["goal_obs"]) + predictions["actions"] = actions + return predictions + + def _compute_losses(self, predictions, batch): + """ + Internal helper function for BC algo class. Compute losses based on + network outputs in @predictions dict, using reference labels in @batch. + + Args: + predictions (dict): dictionary containing network outputs, from @_forward_training + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + Returns: + losses (dict): dictionary of losses computed over the batch + """ + losses = OrderedDict() + a_target = batch["actions"] + actions = predictions["actions"] + losses["l2_loss"] = nn.MSELoss()(actions, a_target) + losses["l1_loss"] = nn.SmoothL1Loss()(actions, a_target) + # cosine direction loss on eef delta position + losses["cos_loss"] = LossUtils.cosine_loss(actions[..., :3], a_target[..., :3]) + + action_losses = [ + self.algo_config.loss.l2_weight * losses["l2_loss"], + self.algo_config.loss.l1_weight * losses["l1_loss"], + self.algo_config.loss.cos_weight * losses["cos_loss"], + ] + action_loss = sum(action_losses) + losses["action_loss"] = action_loss + return losses + + def _train_step(self, losses): + """ + Internal helper function for BC algo class. Perform backpropagation on the + loss tensors in @losses to update networks. + + Args: + losses (dict): dictionary of losses computed over the batch, from @_compute_losses + """ + + # gradient step + info = OrderedDict() + policy_grad_norms = TorchUtils.backprop_for_loss( + net=self.nets["policy"], + optim=self.optimizers["policy"], + loss=losses["action_loss"], + ) + info["policy_grad_norms"] = policy_grad_norms + return info + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + log = super(BC, self).log_info(info) + log["Loss"] = info["losses"]["action_loss"].item() + if "l2_loss" in info["losses"]: + log["L2_Loss"] = info["losses"]["l2_loss"].item() + if "l1_loss" in info["losses"]: + log["L1_Loss"] = info["losses"]["l1_loss"].item() + if "cos_loss" in info["losses"]: + log["Cosine_Loss"] = info["losses"]["cos_loss"].item() + if "policy_grad_norms" in info: + log["Policy_Grad_Norms"] = info["policy_grad_norms"] + return log + + def get_action(self, obs_dict, goal_dict=None): + """ + Get policy action outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + action (torch.Tensor): action tensor + """ + assert not self.nets.training + return self.nets["policy"](obs_dict, goal_dict=goal_dict) + + +class BC_Gaussian(BC): + """ + BC training with a Gaussian policy. + """ + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + """ + assert self.algo_config.gaussian.enabled + + self.nets = nn.ModuleDict() + self.nets["policy"] = PolicyNets.GaussianActorNetwork( + obs_shapes=self.obs_shapes, + goal_shapes=self.goal_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.actor_layer_dims, + fixed_std=self.algo_config.gaussian.fixed_std, + init_std=self.algo_config.gaussian.init_std, + std_limits=(self.algo_config.gaussian.min_std, 7.5), + std_activation=self.algo_config.gaussian.std_activation, + low_noise_eval=self.algo_config.gaussian.low_noise_eval, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + ) + + self.nets = self.nets.float().to(self.device) + + def _forward_training(self, batch): + """ + Internal helper function for BC algo class. Compute forward pass + and return network outputs in @predictions dict. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + Returns: + predictions (dict): dictionary containing network outputs + """ + dists = self.nets["policy"].forward_train( + obs_dict=batch["obs"], + goal_dict=batch["goal_obs"], + ) + + # make sure that this is a batch of multivariate action distributions, so that + # the log probability computation will be correct + assert len(dists.batch_shape) == 1 + log_probs = dists.log_prob(batch["actions"]) + + predictions = OrderedDict( + log_probs=log_probs, + ) + return predictions + + def _compute_losses(self, predictions, batch): + """ + Internal helper function for BC algo class. Compute losses based on + network outputs in @predictions dict, using reference labels in @batch. + + Args: + predictions (dict): dictionary containing network outputs, from @_forward_training + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + Returns: + losses (dict): dictionary of losses computed over the batch + """ + + # loss is just negative log-likelihood of action targets + action_loss = -predictions["log_probs"].mean() + return OrderedDict( + log_probs=-action_loss, + action_loss=action_loss, + ) + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + log = PolicyAlgo.log_info(self, info) + log["Loss"] = info["losses"]["action_loss"].item() + log["Log_Likelihood"] = info["losses"]["log_probs"].item() + if "policy_grad_norms" in info: + log["Policy_Grad_Norms"] = info["policy_grad_norms"] + return log + + +class BC_GMM(BC_Gaussian): + """ + BC training with a Gaussian Mixture Model policy. + """ + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + """ + assert self.algo_config.gmm.enabled + + self.nets = nn.ModuleDict() + self.nets["policy"] = PolicyNets.GMMActorNetwork( + obs_shapes=self.obs_shapes, + goal_shapes=self.goal_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.actor_layer_dims, + num_modes=self.algo_config.gmm.num_modes, + min_std=self.algo_config.gmm.min_std, + std_activation=self.algo_config.gmm.std_activation, + low_noise_eval=self.algo_config.gmm.low_noise_eval, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + ) + + self.nets = self.nets.float().to(self.device) + + +class BC_VAE(BC): + """ + BC training with a VAE policy. + """ + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + """ + self.nets = nn.ModuleDict() + self.nets["policy"] = PolicyNets.VAEActor( + obs_shapes=self.obs_shapes, + goal_shapes=self.goal_shapes, + ac_dim=self.ac_dim, + device=self.device, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + **VAENets.vae_args_from_config(self.algo_config.vae), + ) + + self.nets = self.nets.float().to(self.device) + + def train_on_batch(self, batch, epoch, validate=False): + """ + Update from superclass to set categorical temperature, for categorical VAEs. + """ + if self.algo_config.vae.prior.use_categorical: + temperature = self.algo_config.vae.prior.categorical_init_temp - epoch * self.algo_config.vae.prior.categorical_temp_anneal_step + temperature = max(temperature, self.algo_config.vae.prior.categorical_min_temp) + self.nets["policy"].set_gumbel_temperature(temperature) + return super(BC_VAE, self).train_on_batch(batch, epoch, validate=validate) + + def _forward_training(self, batch): + """ + Internal helper function for BC algo class. Compute forward pass + and return network outputs in @predictions dict. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + Returns: + predictions (dict): dictionary containing network outputs + """ + vae_inputs = dict( + actions=batch["actions"], + obs_dict=batch["obs"], + goal_dict=batch["goal_obs"], + freeze_encoder=batch.get("freeze_encoder", False), + ) + + vae_outputs = self.nets["policy"].forward_train(**vae_inputs) + predictions = OrderedDict( + actions=vae_outputs["decoder_outputs"], + kl_loss=vae_outputs["kl_loss"], + reconstruction_loss=vae_outputs["reconstruction_loss"], + encoder_z=vae_outputs["encoder_z"], + ) + if not self.algo_config.vae.prior.use_categorical: + with torch.no_grad(): + encoder_variance = torch.exp(vae_outputs["encoder_params"]["logvar"]) + predictions["encoder_variance"] = encoder_variance + return predictions + + def _compute_losses(self, predictions, batch): + """ + Internal helper function for BC algo class. Compute losses based on + network outputs in @predictions dict, using reference labels in @batch. + + Args: + predictions (dict): dictionary containing network outputs, from @_forward_training + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + Returns: + losses (dict): dictionary of losses computed over the batch + """ + + # total loss is sum of reconstruction and KL, weighted by beta + kl_loss = predictions["kl_loss"] + recons_loss = predictions["reconstruction_loss"] + action_loss = recons_loss + self.algo_config.vae.kl_weight * kl_loss + return OrderedDict( + recons_loss=recons_loss, + kl_loss=kl_loss, + action_loss=action_loss, + ) + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + log = PolicyAlgo.log_info(self, info) + log["Loss"] = info["losses"]["action_loss"].item() + log["KL_Loss"] = info["losses"]["kl_loss"].item() + log["Reconstruction_Loss"] = info["losses"]["recons_loss"].item() + if self.algo_config.vae.prior.use_categorical: + log["Gumbel_Temperature"] = self.nets["policy"].get_gumbel_temperature() + else: + log["Encoder_Variance"] = info["predictions"]["encoder_variance"].mean().item() + if "policy_grad_norms" in info: + log["Policy_Grad_Norms"] = info["policy_grad_norms"] + return log + + +class BC_RNN(BC): + """ + BC training with an RNN policy. + """ + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + """ + self.nets = nn.ModuleDict() + self.nets["policy"] = PolicyNets.RNNActorNetwork( + obs_shapes=self.obs_shapes, + goal_shapes=self.goal_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.actor_layer_dims, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + **BaseNets.rnn_args_from_config(self.algo_config.rnn), + ) + + self._rnn_hidden_state = None + self._rnn_horizon = self.algo_config.rnn.horizon + self._rnn_counter = 0 + self._rnn_is_open_loop = self.algo_config.rnn.get("open_loop", False) + + self.nets = self.nets.float().to(self.device) + + def process_batch_for_training(self, batch): + """ + Processes input batch from a data loader to filter out + relevant information and prepare the batch for training. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader + + Returns: + input_batch (dict): processed and filtered batch that + will be used for training + """ + input_batch = dict() + input_batch["obs"] = batch["obs"] + input_batch["goal_obs"] = batch.get("goal_obs", None) # goals may not be present + input_batch["actions"] = batch["actions"] + + if self._rnn_is_open_loop: + # replace the observation sequence with one that only consists of the first observation. + # This way, all actions are predicted "open-loop" after the first observation, based + # on the rnn hidden state. + n_steps = batch["actions"].shape[1] + obs_seq_start = TensorUtils.index_at_time(batch["obs"], ind=0) + input_batch["obs"] = TensorUtils.unsqueeze_expand_at(obs_seq_start, size=n_steps, dim=1) + + # we move to device first before float conversion because image observation modalities will be uint8 - + # this minimizes the amount of data transferred to GPU + return TensorUtils.to_float(TensorUtils.to_device(input_batch, self.device)) + + def get_action(self, obs_dict, goal_dict=None): + """ + Get policy action outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + action (torch.Tensor): action tensor + """ + assert not self.nets.training + + if self._rnn_hidden_state is None or self._rnn_counter % self._rnn_horizon == 0: + batch_size = list(obs_dict.values())[0].shape[0] + self._rnn_hidden_state = self.nets["policy"].get_rnn_init_state(batch_size=batch_size, device=self.device) + + if self._rnn_is_open_loop: + # remember the initial observation, and use it instead of the current observation + # for open-loop action sequence prediction + self._open_loop_obs = TensorUtils.clone(TensorUtils.detach(obs_dict)) + + obs_to_use = obs_dict + if self._rnn_is_open_loop: + # replace current obs with last recorded obs + obs_to_use = self._open_loop_obs + + self._rnn_counter += 1 + action, self._rnn_hidden_state = self.nets["policy"].forward_step( + obs_to_use, goal_dict=goal_dict, rnn_state=self._rnn_hidden_state) + return action + + def reset(self): + """ + Reset algo state to prepare for environment rollouts. + """ + self._rnn_hidden_state = None + self._rnn_counter = 0 + + +class BC_RNN_GMM(BC_RNN): + """ + BC training with an RNN GMM policy. + """ + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + """ + assert self.algo_config.gmm.enabled + assert self.algo_config.rnn.enabled + + self.nets = nn.ModuleDict() + self.nets["policy"] = PolicyNets.RNNGMMActorNetwork( + obs_shapes=self.obs_shapes, + goal_shapes=self.goal_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.actor_layer_dims, + num_modes=self.algo_config.gmm.num_modes, + min_std=self.algo_config.gmm.min_std, + std_activation=self.algo_config.gmm.std_activation, + low_noise_eval=self.algo_config.gmm.low_noise_eval, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + **BaseNets.rnn_args_from_config(self.algo_config.rnn), + ) + + self._rnn_hidden_state = None + self._rnn_horizon = self.algo_config.rnn.horizon + self._rnn_counter = 0 + self._rnn_is_open_loop = self.algo_config.rnn.get("open_loop", False) + + self.nets = self.nets.float().to(self.device) + + def _forward_training(self, batch): + """ + Internal helper function for BC algo class. Compute forward pass + and return network outputs in @predictions dict. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + Returns: + predictions (dict): dictionary containing network outputs + """ + dists = self.nets["policy"].forward_train( + obs_dict=batch["obs"], + goal_dict=batch["goal_obs"], + ) + + # make sure that this is a batch of multivariate action distributions, so that + # the log probability computation will be correct + assert len(dists.batch_shape) == 2 # [B, T] + log_probs = dists.log_prob(batch["actions"]) + + predictions = OrderedDict( + log_probs=log_probs, + ) + return predictions + + def _compute_losses(self, predictions, batch): + """ + Internal helper function for BC algo class. Compute losses based on + network outputs in @predictions dict, using reference labels in @batch. + + Args: + predictions (dict): dictionary containing network outputs, from @_forward_training + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + Returns: + losses (dict): dictionary of losses computed over the batch + """ + + # loss is just negative log-likelihood of action targets + action_loss = -predictions["log_probs"].mean() + return OrderedDict( + log_probs=-action_loss, + action_loss=action_loss, + ) + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + log = PolicyAlgo.log_info(self, info) + log["Loss"] = info["losses"]["action_loss"].item() + log["Log_Likelihood"] = info["losses"]["log_probs"].item() + if "policy_grad_norms" in info: + log["Policy_Grad_Norms"] = info["policy_grad_norms"] + return log + + +class BC_Transformer(BC): + """ + BC training with a Transformer policy. + """ + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + """ + assert self.algo_config.transformer.enabled + + self.nets = nn.ModuleDict() + self.nets["policy"] = PolicyNets.TransformerActorNetwork( + obs_shapes=self.obs_shapes, + goal_shapes=self.goal_shapes, + ac_dim=self.ac_dim, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + **BaseNets.transformer_args_from_config(self.algo_config.transformer), + ) + self._set_params_from_config() + self.nets = self.nets.float().to(self.device) + + def _set_params_from_config(self): + """ + Read specific config variables we need for training / eval. + Called by @_create_networks method + """ + self.context_length = self.algo_config.transformer.context_length + self.supervise_all_steps = self.algo_config.transformer.supervise_all_steps + + def process_batch_for_training(self, batch): + """ + Processes input batch from a data loader to filter out + relevant information and prepare the batch for training. + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader + Returns: + input_batch (dict): processed and filtered batch that + will be used for training + """ + input_batch = dict() + h = self.context_length + input_batch["obs"] = {k: batch["obs"][k][:, :h, :] for k in batch["obs"]} + input_batch["goal_obs"] = batch.get("goal_obs", None) # goals may not be present + + if self.supervise_all_steps: + # supervision on entire sequence (instead of just current timestep) + input_batch["actions"] = batch["actions"][:, :h, :] + else: + # just use current timestep + input_batch["actions"] = batch["actions"][:, h-1, :] + + input_batch = TensorUtils.to_device(TensorUtils.to_float(input_batch), self.device) + return input_batch + + def _forward_training(self, batch, epoch=None): + """ + Internal helper function for BC_Transformer algo class. Compute forward pass + and return network outputs in @predictions dict. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + Returns: + predictions (dict): dictionary containing network outputs + """ + # ensure that transformer context length is consistent with temporal dimension of observations + TensorUtils.assert_size_at_dim( + batch["obs"], + size=(self.context_length), + dim=1, + msg="Error: expect temporal dimension of obs batch to match transformer context length {}".format(self.context_length), + ) + + predictions = OrderedDict() + predictions["actions"] = self.nets["policy"](obs_dict=batch["obs"], actions=None, goal_dict=batch["goal_obs"]) + if not self.supervise_all_steps: + # only supervise final timestep + predictions["actions"] = predictions["actions"][:, -1, :] + return predictions + + def get_action(self, obs_dict, goal_dict=None): + """ + Get policy action outputs. + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + Returns: + action (torch.Tensor): action tensor + """ + assert not self.nets.training + + return self.nets["policy"](obs_dict, actions=None, goal_dict=goal_dict)[:, -1, :] + + +class BC_Transformer_GMM(BC_Transformer): + """ + BC training with a Transformer GMM policy. + """ + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + """ + assert self.algo_config.gmm.enabled + assert self.algo_config.transformer.enabled + + self.nets = nn.ModuleDict() + self.nets["policy"] = PolicyNets.TransformerGMMActorNetwork( + obs_shapes=self.obs_shapes, + goal_shapes=self.goal_shapes, + ac_dim=self.ac_dim, + num_modes=self.algo_config.gmm.num_modes, + min_std=self.algo_config.gmm.min_std, + std_activation=self.algo_config.gmm.std_activation, + low_noise_eval=self.algo_config.gmm.low_noise_eval, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + **BaseNets.transformer_args_from_config(self.algo_config.transformer), + ) + self._set_params_from_config() + self.nets = self.nets.float().to(self.device) + + def _forward_training(self, batch, epoch=None): + """ + Modify from super class to support GMM training. + """ + # ensure that transformer context length is consistent with temporal dimension of observations + TensorUtils.assert_size_at_dim( + batch["obs"], + size=(self.context_length), + dim=1, + msg="Error: expect temporal dimension of obs batch to match transformer context length {}".format(self.context_length), + ) + + dists = self.nets["policy"].forward_train( + obs_dict=batch["obs"], + actions=None, + goal_dict=batch["goal_obs"], + low_noise_eval=False, + ) + + # make sure that this is a batch of multivariate action distributions, so that + # the log probability computation will be correct + assert len(dists.batch_shape) == 2 # [B, T] + + if not self.supervise_all_steps: + # only use final timestep prediction by making a new distribution with only final timestep. + # This essentially does `dists = dists[:, -1]` + component_distribution = D.Normal( + loc=dists.component_distribution.base_dist.loc[:, -1], + scale=dists.component_distribution.base_dist.scale[:, -1], + ) + component_distribution = D.Independent(component_distribution, 1) + mixture_distribution = D.Categorical(logits=dists.mixture_distribution.logits[:, -1]) + dists = D.MixtureSameFamily( + mixture_distribution=mixture_distribution, + component_distribution=component_distribution, + ) + + log_probs = dists.log_prob(batch["actions"]) + + predictions = OrderedDict( + log_probs=log_probs, + ) + return predictions + + def _compute_losses(self, predictions, batch): + """ + Internal helper function for BC_Transformer_GMM algo class. Compute losses based on + network outputs in @predictions dict, using reference labels in @batch. + Args: + predictions (dict): dictionary containing network outputs, from @_forward_training + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + Returns: + losses (dict): dictionary of losses computed over the batch + """ + + # loss is just negative log-likelihood of action targets + action_loss = -predictions["log_probs"].mean() + return OrderedDict( + log_probs=-action_loss, + action_loss=action_loss, + ) + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + Args: + info (dict): dictionary of info + Returns: + loss_log (dict): name -> summary statistic + """ + log = PolicyAlgo.log_info(self, info) + log["Loss"] = info["losses"]["action_loss"].item() + log["Log_Likelihood"] = info["losses"]["log_probs"].item() + if "policy_grad_norms" in info: + log["Policy_Grad_Norms"] = info["policy_grad_norms"] + return log diff --git a/code_src/rise_robomimic/robomimic/algo/bcq.py b/code_src/rise_robomimic/robomimic/algo/bcq.py new file mode 100644 index 0000000000000000000000000000000000000000..5843ccb5bd594c596a8dc138eab863bb3f5e3550 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/bcq.py @@ -0,0 +1,1022 @@ +""" +Batch-Constrained Q-Learning (BCQ), with support for more general +generative action models (the original paper uses a cVAE). +(Paper - https://arxiv.org/abs/1812.02900). +""" +from collections import OrderedDict + +import torch +import torch.nn as nn +import torch.nn.functional as F + +import robomimic.models.obs_nets as ObsNets +import robomimic.models.policy_nets as PolicyNets +import robomimic.models.value_nets as ValueNets +import robomimic.models.vae_nets as VAENets +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.torch_utils as TorchUtils +import robomimic.utils.obs_utils as ObsUtils +import robomimic.utils.loss_utils as LossUtils + +from robomimic.algo import register_algo_factory_func, PolicyAlgo, ValueAlgo + + +@register_algo_factory_func("bcq") +def algo_config_to_class(algo_config): + """ + Maps algo config to the BCQ algo class to instantiate, along with additional algo kwargs. + + Args: + algo_config (Config instance): algo config + + Returns: + algo_class: subclass of Algo + algo_kwargs (dict): dictionary of additional kwargs to pass to algorithm + """ + if algo_config.critic.distributional.enabled: + return BCQ_Distributional, {} + if algo_config.action_sampler.gmm.enabled: + return BCQ_GMM, {} + assert algo_config.action_sampler.vae.enabled + return BCQ, {} + + +class BCQ(PolicyAlgo, ValueAlgo): + """ + Default BCQ training, based on https://arxiv.org/abs/1812.02900 and + https://github.com/sfujim/BCQ + """ + def __init__(self, **kwargs): + PolicyAlgo.__init__(self, **kwargs) + + # save the discount factor - it may be overriden later + self.set_discount(self.algo_config.discount) + + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + """ + self.nets = nn.ModuleDict() + + self._create_critics() + self._create_action_sampler() + if self.algo_config.actor.enabled: + self._create_actor() + + # sync target networks at beginning of training + with torch.no_grad(): + for critic_ind in range(len(self.nets["critic"])): + TorchUtils.hard_update( + source=self.nets["critic"][critic_ind], + target=self.nets["critic_target"][critic_ind], + ) + + if self.algo_config.actor.enabled: + TorchUtils.hard_update( + source=self.nets["actor"], + target=self.nets["actor_target"], + ) + + self.nets = self.nets.float().to(self.device) + + def _create_critics(self): + """ + Called in @_create_networks to make critic networks. + """ + critic_class = ValueNets.ActionValueNetwork + critic_args = dict( + obs_shapes=self.obs_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.critic.layer_dims, + value_bounds=self.algo_config.critic.value_bounds, + goal_shapes=self.goal_shapes, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + ) + + # Q network ensemble and target ensemble + self.nets["critic"] = nn.ModuleList() + self.nets["critic_target"] = nn.ModuleList() + for _ in range(self.algo_config.critic.ensemble.n): + critic = critic_class(**critic_args) + self.nets["critic"].append(critic) + + critic_target = critic_class(**critic_args) + self.nets["critic_target"].append(critic_target) + + def _create_action_sampler(self): + """ + Called in @_create_networks to make action sampler network. + """ + + # VAE network for approximate sampling from batch dataset + assert self.algo_config.action_sampler.vae.enabled + self.nets["action_sampler"] = PolicyNets.VAEActor( + obs_shapes=self.obs_shapes, + ac_dim=self.ac_dim, + device=self.device, + goal_shapes=self.goal_shapes, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + **VAENets.vae_args_from_config(self.algo_config.action_sampler.vae), + ) + + def _create_actor(self): + """ + Called in @_create_networks to make actor network. + """ + assert self.algo_config.actor.enabled + actor_class = PolicyNets.PerturbationActorNetwork + actor_args = dict( + obs_shapes=self.obs_shapes, + goal_shapes=self.goal_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.actor.layer_dims, + perturbation_scale=self.algo_config.actor.perturbation_scale, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + ) + + self.nets["actor"] = actor_class(**actor_args) + self.nets["actor_target"] = actor_class(**actor_args) + + def _check_epoch(self, net_name, epoch): + """ + Helper function to check whether backprop should happen this epoch. + + Args: + net_name (str): name of network in @self.nets and @self.optim_params + epoch (int): epoch number + """ + epoch_start_check = (self.optim_params[net_name]["start_epoch"] == -1) or (epoch >= self.optim_params[net_name]["start_epoch"]) + epoch_end_check = (self.optim_params[net_name]["end_epoch"] == -1) or (epoch < self.optim_params[net_name]["end_epoch"]) + return (epoch_start_check and epoch_end_check) + + def set_discount(self, discount): + """ + Useful function to modify discount factor if necessary (e.g. for n-step returns). + """ + self.discount = discount + + def process_batch_for_training(self, batch): + """ + Processes input batch from a data loader to filter out + relevant information and prepare the batch for training. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader + + Returns: + input_batch (dict): processed and filtered batch that + will be used for training + """ + input_batch = dict() + + # n-step returns (default is 1) + n_step = self.algo_config.n_step + assert batch["actions"].shape[1] >= n_step + + # remove temporal batches for all + input_batch["obs"] = {k: batch["obs"][k][:, 0, :] for k in batch["obs"]} + input_batch["next_obs"] = {k: batch["next_obs"][k][:, n_step - 1, :] for k in batch["next_obs"]} + input_batch["goal_obs"] = batch.get("goal_obs", None) # goals may not be present + input_batch["actions"] = batch["actions"][:, 0, :] + + # note: ensure scalar signals (rewards, done) retain last dimension of 1 to be compatible with model outputs + + # single timestep reward is discounted sum of intermediate rewards in sequence + reward_seq = batch["rewards"][:, :n_step] + discounts = torch.pow(self.algo_config.discount, torch.arange(n_step).float()).unsqueeze(0) + input_batch["rewards"] = (reward_seq * discounts).sum(dim=1).unsqueeze(1) + + # discount rate will be gamma^N for computing n-step returns + new_discount = (self.algo_config.discount ** n_step) + self.set_discount(new_discount) + + # consider this n-step seqeunce done if any intermediate dones are present + done_seq = batch["dones"][:, :n_step] + input_batch["dones"] = (done_seq.sum(dim=1) > 0).float().unsqueeze(1) + + if self.algo_config.infinite_horizon: + # scale terminal rewards by 1 / (1 - gamma) for infinite horizon MDPs + done_inds = input_batch["dones"].round().long().nonzero(as_tuple=False)[:, 0] + if done_inds.shape[0] > 0: + input_batch["rewards"][done_inds] = input_batch["rewards"][done_inds] * (1. / (1. - self.discount)) + + # we move to device first before float conversion because image observation modalities will be uint8 - + # this minimizes the amount of data transferred to GPU + return TensorUtils.to_float(TensorUtils.to_device(input_batch, self.device)) + + def _train_action_sampler_on_batch(self, batch, epoch, no_backprop=False): + """ + A modular helper function that can be overridden in case + subclasses would like to modify training behavior for the + action sampler. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + no_backprop (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + outputs (dict): dictionary of outputs to use during critic training + (for computing target values) + """ + info = OrderedDict() + if self.algo_config.action_sampler.vae.prior.use_categorical: + temperature = self.algo_config.action_sampler.vae.prior.categorical_init_temp - epoch * self.algo_config.action_sampler.vae.prior.categorical_temp_anneal_step + temperature = max(temperature, self.algo_config.action_sampler.vae.prior.categorical_min_temp) + self.nets["action_sampler"].set_gumbel_temperature(temperature) + + vae_inputs = dict( + actions=batch["actions"], + obs_dict=batch["obs"], + goal_dict=batch["goal_obs"], + ) + + # maybe freeze encoder weights + if (self.algo_config.action_sampler.freeze_encoder_epoch != -1) and (epoch >= self.algo_config.action_sampler.freeze_encoder_epoch): + vae_inputs["freeze_encoder"] = True + + # VAE forward + vae_outputs = self.nets["action_sampler"].forward_train(**vae_inputs) + recons_loss = vae_outputs["reconstruction_loss"] + kl_loss = vae_outputs["kl_loss"] + vae_loss = recons_loss + self.algo_config.action_sampler.vae.kl_weight * kl_loss + info["action_sampler/loss"] = vae_loss + info["action_sampler/recons_loss"] = recons_loss + info["action_sampler/kl_loss"] = kl_loss + if not self.algo_config.action_sampler.vae.prior.use_categorical: + with torch.no_grad(): + encoder_variance = torch.exp(vae_outputs["encoder_params"]["logvar"]).mean() + info["action_sampler/encoder_variance"] = encoder_variance + outputs = TensorUtils.detach(vae_outputs) + + # VAE gradient step + if not no_backprop: + vae_grad_norms = TorchUtils.backprop_for_loss( + net=self.nets["action_sampler"], + optim=self.optimizers["action_sampler"], + loss=vae_loss, + ) + info["action_sampler/grad_norms"] = vae_grad_norms + return info, outputs + + def _train_critic_on_batch(self, batch, action_sampler_outputs, epoch, no_backprop=False): + """ + A modular helper function that can be overridden in case + subclasses would like to modify training behavior for the + critics. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + action_sampler_outputs (dict): dictionary of outputs from the action sampler. Used + to form target values for training the critic + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + no_backprop (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + critic_outputs (dict): dictionary of critic outputs - useful for + logging purposes + """ + info = OrderedDict() + + # batch variables + s_batch = batch["obs"] + a_batch = batch["actions"] + r_batch = batch["rewards"] + ns_batch = batch["next_obs"] + goal_s_batch = batch["goal_obs"] + + # 1 if not done, 0 otherwise + done_mask_batch = 1. - batch["dones"] + info["done_masks"] = done_mask_batch + + # Bellman backup for Q-targets + q_targets = self._get_target_values( + next_states=ns_batch, + goal_states=goal_s_batch, + rewards=r_batch, + dones=done_mask_batch, + action_sampler_outputs=action_sampler_outputs, + ) + info["critic/q_targets"] = q_targets + + # Train all critics using this set of targets for regression + critic_outputs = [] + for critic_ind, critic in enumerate(self.nets["critic"]): + critic_loss, critic_output = self._compute_critic_loss( + critic=critic, + states=s_batch, + actions=a_batch, + goal_states=goal_s_batch, + q_targets=q_targets, + ) + info["critic/critic{}_loss".format(critic_ind + 1)] = critic_loss + critic_outputs.append(critic_output) + + if not no_backprop: + critic_grad_norms = TorchUtils.backprop_for_loss( + net=self.nets["critic"][critic_ind], + optim=self.optimizers["critic"][critic_ind], + loss=critic_loss, + max_grad_norm=self.algo_config.critic.max_gradient_norm, + ) + info["critic/critic{}_grad_norms".format(critic_ind + 1)] = critic_grad_norms + + return info, critic_outputs + + def _train_actor_on_batch(self, batch, action_sampler_outputs, critic_outputs, epoch, no_backprop=False): + """ + A modular helper function that can be overridden in case + subclasses would like to modify training behavior for the + perturbation actor. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + action_sampler_outputs (dict): dictionary of outputs from the action sampler. Currently + unused, although more sophisticated models may use it. + + critic_outputs (dict): dictionary of outputs from the critic. Currently + unused, although more sophisticated models may use it. + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + no_backprop (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + assert self.algo_config.actor.enabled + + info = OrderedDict() + + # Actor loss (update with DDPG loss) + s_batch = batch["obs"] + goal_s_batch = batch["goal_obs"] + + # sample some actions from action sampler and perturb them, then improve perturbations + # where improvement is measured by the critic + sampled_actions = self.nets["action_sampler"](s_batch, goal_s_batch).detach() # don't backprop into samples + perturbed_actions = self.nets["actor"](s_batch, sampled_actions, goal_s_batch) + actor_loss = -(self.nets["critic"][0](s_batch, perturbed_actions, goal_s_batch)).mean() + info["actor/loss"] = actor_loss + + if not no_backprop: + actor_grad_norms = TorchUtils.backprop_for_loss( + net=self.nets["actor"], + optim=self.optimizers["actor"], + loss=actor_loss, + ) + info["actor/grad_norms"] = actor_grad_norms + + return info + + def _get_target_values(self, next_states, goal_states, rewards, dones, action_sampler_outputs=None): + """ + Helper function to get target values for training Q-function with TD-loss. + + Args: + next_states (dict): batch of next observations + goal_states (dict): if not None, batch of goal observations + rewards (torch.Tensor): batch of rewards - should be shape (B, 1) + dones (torch.Tensor): batch of done signals - should be shape (B, 1) + action_sampler_outputs (dict): dictionary of outputs from the action sampler. Currently + unused, although more sophisticated models may use it. + + Returns: + q_targets (torch.Tensor): target Q-values to use for TD loss + """ + + with torch.no_grad(): + # we need to stack the observations with redundancy @num_action_samples here, then decode + # to get all sampled actions. for example, if we generate 2 samples per observation and + # the batch size is 3, then ob_tiled = [ob1; ob1; ob2; ob2; ob3; ob3] + next_states_tiled = ObsUtils.repeat_and_stack_observation(next_states, n=self.algo_config.critic.num_action_samples) + goal_states_tiled = None + if len(self.goal_shapes) > 0: + goal_states_tiled = ObsUtils.repeat_and_stack_observation(goal_states, n=self.algo_config.critic.num_action_samples) + + # sample action proposals + next_sampled_actions = self._sample_actions_for_value_maximization( + states_tiled=next_states_tiled, + goal_states_tiled=goal_states_tiled, + for_target_update=True, + ) + + q_targets = self._get_target_values_from_sampled_actions( + next_states_tiled=next_states_tiled, + next_sampled_actions=next_sampled_actions, + goal_states_tiled=goal_states_tiled, + rewards=rewards, + dones=dones, + ) + + return q_targets + + def _sample_actions_for_value_maximization(self, states_tiled, goal_states_tiled, for_target_update): + """ + Helper function to sample actions for maximization (the "batch-constrained" part of + batch-constrained q-learning). + + Args: + states_tiled (dict): observations to use for sampling actions. Assumes that tiling + has already occurred - so that if the batch size is B, and N samples are + desired for each observation in the batch, the leading dimension for each + observation in the dict is B * N + + goal_states_tiled (dict): if not None, goal observations + + for_target_update (bool): if True, actions are being sampled for use in training the + critic - which means the target actor network should be used + + Returns: + sampled_actions (torch.Tensor): actions sampled from the action sampler, and maybe + perturbed by the actor network + """ + + with torch.no_grad(): + sampled_actions = self.nets["action_sampler"](states_tiled, goal_states_tiled) + if self.algo_config.actor.enabled: + actor = self.nets["actor"] + if for_target_update: + actor = self.nets["actor_target"] + # perturb the actions with the policy + sampled_actions = actor(states_tiled, sampled_actions, goal_states_tiled) + + return sampled_actions + + def _get_target_values_from_sampled_actions(self, next_states_tiled, next_sampled_actions, goal_states_tiled, rewards, dones): + """ + Helper function to get target values for training Q-function with TD-loss. The function + assumes that action candidates to maximize over have already been computed, and that + the input states have been tiled (repeated) to be compatible with the sampled actions. + + Args: + next_states_tiled (dict): next observations to use for sampling actions. Assumes that + tiling has already occurred - so that if the batch size is B, and N samples are + desired for each observation in the batch, the leading dimension for each + observation in the dict is B * N + + next_sampled_actions (torch.Tensor): actions sampled from the action sampler. This function + will maximize the critic over these action candidates (using the TD3 trick) + + goal_states_tiled (dict): if not None, goal observations + + rewards (torch.Tensor): batch of rewards - should be shape (B, 1) + + dones (torch.Tensor): batch of done signals - should be shape (B, 1) + + Returns: + q_targets (torch.Tensor): target Q-values to use for TD loss + """ + with torch.no_grad(): + # feed tiled observations and sampled actions into the critics and then + # reshape to get all Q-values in second dimension per observation in batch. + all_value_targets = self.nets["critic_target"][0](next_states_tiled, next_sampled_actions, goal_states_tiled).reshape( + -1, self.algo_config.critic.num_action_samples) + max_value_targets = all_value_targets + min_value_targets = all_value_targets + + # TD3 trick to combine max and min over all Q-ensemble estimates into single target estimates + for critic_target in self.nets["critic_target"][1:]: + all_value_targets = critic_target(next_states_tiled, next_sampled_actions, goal_states_tiled).reshape( + -1, self.algo_config.critic.num_action_samples) + max_value_targets = torch.max(max_value_targets, all_value_targets) + min_value_targets = torch.min(min_value_targets, all_value_targets) + all_value_targets = self.algo_config.critic.ensemble.weight * min_value_targets + \ + (1. - self.algo_config.critic.ensemble.weight) * max_value_targets + + # take maximum over all sampled action values per observation and compute targets + value_targets = torch.max(all_value_targets, dim=1, keepdim=True)[0] + q_targets = rewards + dones * self.discount * value_targets + + return q_targets + + def _compute_critic_loss(self, critic, states, actions, goal_states, q_targets): + """ + Helper function to compute loss between estimated Q-values and target Q-values. + It should also return outputs needed for downstream training (for training the + actor). + + Args: + critic (torch.nn.Module): critic network + states (dict): batch of observations + actions (torch.Tensor): batch of actions + goal_states (dict): if not None, batch of goal observations + q_targets (torch.Tensor): batch of target q-values for the TD loss + + Returns: + critic_loss (torch.Tensor): critic loss + critic_output (dict): additional outputs from the critic. This function + returns None, but subclasses may want to provide some information + here. + """ + q_estimated = critic(states, actions, goal_states) + if self.algo_config.critic.use_huber: + critic_loss = nn.SmoothL1Loss()(q_estimated, q_targets) + else: + critic_loss = nn.MSELoss()(q_estimated, q_targets) + return critic_loss, None + + def train_on_batch(self, batch, epoch, validate=False): + """ + Training on a single batch of data. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + validate (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + with TorchUtils.maybe_no_grad(no_grad=validate): + info = PolicyAlgo.train_on_batch(self, batch, epoch, validate=validate) + + # Action Sampler training + no_action_sampler_backprop = validate or (not self._check_epoch(net_name="action_sampler", epoch=epoch)) + with TorchUtils.maybe_no_grad(no_grad=no_action_sampler_backprop): + action_sampler_info, action_sampler_outputs = self._train_action_sampler_on_batch( + batch=batch, + epoch=epoch, + no_backprop=no_action_sampler_backprop, + ) + info.update(action_sampler_info) + + # make sure action sampler is in eval mode for models like GMM which may require low-noise + # samples when sampling actions. + self.nets["action_sampler"].eval() + + # Critic training + no_critic_backprop = validate or (not self._check_epoch(net_name="critic", epoch=epoch)) + with TorchUtils.maybe_no_grad(no_grad=no_critic_backprop): + critic_info, critic_outputs = self._train_critic_on_batch( + batch=batch, + action_sampler_outputs=action_sampler_outputs, + epoch=epoch, + no_backprop=no_critic_backprop, + ) + info.update(critic_info) + + if self.algo_config.actor.enabled: + # Actor training + no_actor_backprop = validate or (not self._check_epoch(net_name="actor", epoch=epoch)) + with TorchUtils.maybe_no_grad(no_grad=no_actor_backprop): + actor_info = self._train_actor_on_batch( + batch=batch, + action_sampler_outputs=action_sampler_outputs, + critic_outputs=critic_outputs, + epoch=epoch, + no_backprop=no_actor_backprop, + ) + info.update(actor_info) + + if not validate: + # restore to train mode if necessary + self.nets["action_sampler"].train() + + # update the target critic networks (only when critic has gradient update) + if not no_critic_backprop: + with torch.no_grad(): + for critic_ind in range(len(self.nets["critic"])): + TorchUtils.soft_update( + source=self.nets["critic"][critic_ind], + target=self.nets["critic_target"][critic_ind], + tau=self.algo_config.target_tau, + ) + + # update target actor network (only when actor has gradient update) + if self.algo_config.actor.enabled and (not no_actor_backprop): + with torch.no_grad(): + TorchUtils.soft_update( + source=self.nets["actor"], + target=self.nets["actor_target"], + tau=self.algo_config.target_tau, + ) + + return info + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + loss_log = OrderedDict() + + # record current optimizer learning rates + for k in self.optimizers: + keys = [k] + optims = [self.optimizers[k]] + if k == "critic": + # account for critic having one optimizer per ensemble member + keys = ["{}{}".format(k, critic_ind) for critic_ind in range(len(self.nets["critic"]))] + optims = self.optimizers[k] + for kp, optimizer in zip(keys, optims): + for i, param_group in enumerate(optimizer.param_groups): + loss_log["Optimizer/{}{}_lr".format(kp, i)] = param_group["lr"] + + # extract relevant logs for action sampler, critic, and actor + loss_log["Loss"] = 0. + for loss_logger in [self._log_action_sampler_info, self._log_critic_info, self._log_actor_info]: + this_log = loss_logger(info) + if "Loss" in this_log: + # manually merge total loss + loss_log["Loss"] += this_log["Loss"] + del this_log["Loss"] + loss_log.update(this_log) + + return loss_log + + def _log_action_sampler_info(self, info): + """ + Helper function to extract action sampler-relevant information for logging. + """ + loss_log = OrderedDict() + loss_log["Action_Sampler/Loss"] = info["action_sampler/loss"].item() + loss_log["Action_Sampler/Reconsruction_Loss"] = info["action_sampler/recons_loss"].item() + loss_log["Action_Sampler/KL_Loss"] = info["action_sampler/kl_loss"].item() + if self.algo_config.action_sampler.vae.prior.use_categorical: + loss_log["Action_Sampler/Gumbel_Temperature"] = self.nets["action_sampler"].get_gumbel_temperature() + else: + loss_log["Action_Sampler/Encoder_Variance"] = info["action_sampler/encoder_variance"].item() + if "action_sampler/grad_norms" in info: + loss_log["Action_Sampler/Grad_Norms"] = info["action_sampler/grad_norms"] + loss_log["Loss"] = loss_log["Action_Sampler/Loss"] + return loss_log + + def _log_critic_info(self, info): + """ + Helper function to extract critic-relevant information for logging. + """ + loss_log = OrderedDict() + if "done_masks" in info: + loss_log["Critic/Done_Mask_Percentage"] = 100. * torch.mean(info["done_masks"]).item() + if "critic/q_targets" in info: + loss_log["Critic/Q_Targets"] = info["critic/q_targets"].mean().item() + loss_log["Loss"] = 0. + for critic_ind in range(len(self.nets["critic"])): + loss_log["Critic/Critic{}_Loss".format(critic_ind + 1)] = info["critic/critic{}_loss".format(critic_ind + 1)].item() + if "critic/critic{}_grad_norms".format(critic_ind + 1) in info: + loss_log["Critic/Critic{}_Grad_Norms".format(critic_ind + 1)] = info["critic/critic{}_grad_norms".format(critic_ind + 1)] + loss_log["Loss"] += loss_log["Critic/Critic{}_Loss".format(critic_ind + 1)] + return loss_log + + def _log_actor_info(self, info): + """ + Helper function to extract actor-relevant information for logging. + """ + loss_log = OrderedDict() + if self.algo_config.actor.enabled: + loss_log["Actor/Loss"] = info["actor/loss"].item() + if "actor/grad_norms" in info: + loss_log["Actor/Grad_Norms"] = info["actor/grad_norms"] + loss_log["Loss"] = loss_log["Actor/Loss"] + return loss_log + + def set_train(self): + """ + Prepare networks for evaluation. Update from super class to make sure + target networks stay in evaluation mode all the time. + """ + self.nets.train() + + # target networks always in eval + for critic_ind in range(len(self.nets["critic_target"])): + self.nets["critic_target"][critic_ind].eval() + + if self.algo_config.actor.enabled: + self.nets["actor_target"].eval() + + def on_epoch_end(self, epoch): + """ + Called at the end of each epoch. + """ + + # LR scheduling updates + for lr_sc in self.lr_schedulers["critic"]: + if lr_sc is not None: + lr_sc.step() + + if self.lr_schedulers["action_sampler"] is not None: + self.lr_schedulers["action_sampler"].step() + + if self.algo_config.actor.enabled and self.lr_schedulers["actor"] is not None: + self.lr_schedulers["actor"].step() + + def _get_best_value(self, obs_dict, goal_dict=None): + """ + Internal helper function for getting the best value for a given state and + the corresponding best action. Meant to be used at test-time. Key differences + between this and retrieving target values at train-time are that (1) only a + single critic is used for the value estimate and (2) the critic and actor + are used instead of the target critic and target actor. + + Args: + obs_dict (dict): batch of current observations + goal_dict (dict): (optional) goal + + Returns: + best_value (torch.Tensor): best values + best_action (torch.Tensor): best actions + """ + assert not self.nets.training + + random_key = list(obs_dict.keys())[0] + batch_size = obs_dict[random_key].shape[0] + + # number of action proposals from action sampler + num_action_samples = self.algo_config.critic.num_action_samples_rollout + + # we need to stack the observations with redundancy @num_action_samples here, then decode + # to get all sampled actions. for example, if we generate 2 samples per observation and + # the batch size is 3, then ob_tiled = [ob1; ob1; ob2; ob2; ob3; ob3] + ob_tiled = ObsUtils.repeat_and_stack_observation(obs_dict, n=num_action_samples) + goal_tiled = None + if len(self.goal_shapes) > 0: + goal_tiled = ObsUtils.repeat_and_stack_observation(goal_dict, n=num_action_samples) + + sampled_actions = self._sample_actions_for_value_maximization( + states_tiled=ob_tiled, + goal_states_tiled=goal_tiled, + for_target_update=False, + ) + + # feed tiled observations and perturbed sampled actions into the critic and then + # reshape to get all Q-values in second dimension per observation in batch. + # finally, just take a maximum across that second dimension to take the best sampled action + all_critic_values = self.nets["critic"][0](ob_tiled, sampled_actions, goal_tiled).reshape(-1, num_action_samples) + best_action_index = torch.argmax(all_critic_values, dim=1) + + all_actions = sampled_actions.reshape(batch_size, num_action_samples, -1) + best_action = all_actions[torch.arange(all_actions.shape[0]), best_action_index] + best_value = all_critic_values[torch.arange(all_critic_values.shape[0]), best_action_index].unsqueeze(1) + + return best_value, best_action + + def get_action(self, obs_dict, goal_dict=None): + """ + Get policy action outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + action (torch.Tensor): action tensor + """ + assert not self.nets.training + + _, best_action = self._get_best_value(obs_dict=obs_dict, goal_dict=goal_dict) + return best_action + + def get_state_value(self, obs_dict, goal_dict=None): + """ + Get state value outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + value (torch.Tensor): value tensor + """ + assert not self.nets.training + + best_value, _ = self._get_best_value(obs_dict=obs_dict, goal_dict=goal_dict) + return best_value + + def get_state_action_value(self, obs_dict, actions, goal_dict=None): + """ + Get state-action value outputs. + + Args: + obs_dict (dict): current observation + actions (torch.Tensor): action + goal_dict (dict): (optional) goal + + Returns: + value (torch.Tensor): value tensor + """ + assert not self.nets.training + + return self.nets["critic"][0](obs_dict, actions, goal_dict) + + +class BCQ_GMM(BCQ): + """ + A simple modification to BCQ that replaces the VAE used to sample action proposals from the + batch with a GMM. + """ + def _create_action_sampler(self): + """ + Called in @_create_networks to make action sampler network. + """ + assert self.algo_config.action_sampler.gmm.enabled + + # GMM network for approximate sampling from batch dataset + self.nets["action_sampler"] = PolicyNets.GMMActorNetwork( + obs_shapes=self.obs_shapes, + goal_shapes=self.goal_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.action_sampler.actor_layer_dims, + num_modes=self.algo_config.action_sampler.gmm.num_modes, + min_std=self.algo_config.action_sampler.gmm.min_std, + std_activation=self.algo_config.action_sampler.gmm.std_activation, + low_noise_eval=self.algo_config.action_sampler.gmm.low_noise_eval, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + ) + + def _train_action_sampler_on_batch(self, batch, epoch, no_backprop=False): + """ + Modify this helper function from superclass to train GMM action sampler + with maximum likelihood. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + no_backprop (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + outputs (dict): dictionary of outputs to use during critic training + (for computing target values) + """ + info = OrderedDict() + + # GMM forward + dists = self.nets["action_sampler"].forward_train( + obs_dict=batch["obs"], + goal_dict=batch["goal_obs"], + ) + + # make sure that this is a batch of multivariate action distributions, so that + # the log probability computation will be correct + assert len(dists.batch_shape) == 1 + log_probs = dists.log_prob(batch["actions"]) + loss = -log_probs.mean() + info["action_sampler/loss"] = loss + + # GMM gradient step + if not no_backprop: + gmm_grad_norms = TorchUtils.backprop_for_loss( + net=self.nets["action_sampler"], + optim=self.optimizers["action_sampler"], + loss=loss, + ) + info["action_sampler/grad_norms"] = gmm_grad_norms + return info, None + + def _log_action_sampler_info(self, info): + """ + Update from superclass for GMM (no KL loss). + """ + loss_log = OrderedDict() + loss_log["Action_Sampler/Loss"] = info["action_sampler/loss"].item() + if "action_sampler/grad_norms" in info: + loss_log["Action_Sampler/Grad_Norms"] = info["action_sampler/grad_norms"] + loss_log["Loss"] = loss_log["Action_Sampler/Loss"] + return loss_log + + +class BCQ_Distributional(BCQ): + """ + BCQ with distributional critics. Distributional critics output categorical + distributions over a discrete set of values instead of expected returns. + Some parts of this implementation were adapted from ACME (https://github.com/deepmind/acme). + """ + def _create_critics(self): + """ + Called in @_create_networks to make critic networks. + """ + assert self.algo_config.critic.distributional.enabled + critic_class = ValueNets.DistributionalActionValueNetwork + critic_args = dict( + obs_shapes=self.obs_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.critic.layer_dims, + value_bounds=self.algo_config.critic.value_bounds, + num_atoms=self.algo_config.critic.distributional.num_atoms, + goal_shapes=self.goal_shapes, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + ) + + # Q network ensemble and target ensemble + self.nets["critic"] = nn.ModuleList() + self.nets["critic_target"] = nn.ModuleList() + + # NOTE: ensemble value in config is ignored, and only 1 critic is used. + critic = critic_class(**critic_args) + self.nets["critic"].append(critic) + + critic_target = critic_class(**critic_args) + self.nets["critic_target"].append(critic_target) + + def _get_target_values_from_sampled_actions(self, next_states_tiled, next_sampled_actions, goal_states_tiled, rewards, dones): + """ + Helper function to get target values for training Q-function with TD-loss. Update from superclass + to account for distributional value functions. + + Args: + next_states_tiled (dict): next observations to use for sampling actions. Assumes that + tiling has already occurred - so that if the batch size is B, and N samples are + desired for each observation in the batch, the leading dimension for each + observation in the dict is B * N + + next_sampled_actions (torch.Tensor): actions sampled from the action sampler. This function + will maximize the critic over these action candidates (using the TD3 trick) + + goal_states_tiled (dict): if not None, goal observations + + rewards (torch.Tensor): batch of rewards - should be shape (B, 1) + + dones (torch.Tensor): batch of done signals - should be shape (B, 1) + + Returns: + target_categorical_probabilities (torch.Tensor): target categorical probabilities + to use in the bellman backup + """ + + with torch.no_grad(): + # compute expected returns of the sampled actions and maximize to find the best action + all_vds = self.nets["critic_target"][0].forward_train(next_states_tiled, next_sampled_actions, goal_states_tiled) + expected_values = all_vds.mean().reshape(-1, self.algo_config.critic.num_action_samples) + best_action_index = torch.argmax(expected_values, dim=1) + all_actions = next_sampled_actions.reshape(-1, self.algo_config.critic.num_action_samples, self.ac_dim) + best_action = all_actions[torch.arange(all_actions.shape[0]), best_action_index] + + # get the corresponding probabilities for the categorical distributions corresponding to the best actions + all_vd_probs = all_vds.probs.reshape(-1, self.algo_config.critic.num_action_samples, self.algo_config.critic.distributional.num_atoms) + target_vd_probs = all_vd_probs[torch.arange(all_vd_probs.shape[0]), best_action_index] + + # bellman backup to get a new grid of values - then project onto the canonical atoms to obtain a + # target set of categorical probabilities over the atoms + atom_value_grid = all_vds.values + target_value_grid = rewards + dones * self.discount * atom_value_grid + target_categorical_probabilities = LossUtils.project_values_onto_atoms( + values=target_value_grid, + probabilities=target_vd_probs, + atoms=atom_value_grid, + ) + + return target_categorical_probabilities + + def _compute_critic_loss(self, critic, states, actions, goal_states, q_targets): + """ + Overrides super class to compute a distributional loss. Since values are + categorical distributions, this is just computing a cross-entropy + loss between the two distributions. + + NOTE: q_targets is expected to be a batch of normalized probability vectors that correspond to + the target categorical distributions over the value atoms. + + Args: + critic (torch.nn.Module): critic network + states (dict): batch of observations + actions (torch.Tensor): batch of actions + goal_states (dict): if not None, batch of goal observations + q_targets (torch.Tensor): batch of target q-values for the TD loss + + Returns: + critic_loss (torch.Tensor): critic loss + critic_output (dict): additional outputs from the critic. This function + returns None, but subclasses may want to provide some information + here. + """ + + # this should be the equivalent of softmax with logits from tf + vd = critic.forward_train(states, actions, goal_states) + log_probs = F.log_softmax(vd.logits, dim=-1) + critic_loss = nn.KLDivLoss(reduction='batchmean')(log_probs, q_targets) + return critic_loss, None diff --git a/code_src/rise_robomimic/robomimic/algo/cql.py b/code_src/rise_robomimic/robomimic/algo/cql.py new file mode 100644 index 0000000000000000000000000000000000000000..0c24d50abd91426a4d96e91896c958b7df1ada0a --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/cql.py @@ -0,0 +1,668 @@ +""" +Implementation of Conservative Q-Learning (CQL). +Based off of https://github.com/aviralkumar2907/CQL. +(Paper - https://arxiv.org/abs/2006.04779). +""" +import numpy as np +from collections import OrderedDict + +import torch +import torch.nn as nn +import torch.optim as optim + +import robomimic.models.base_nets as BaseNets +import robomimic.models.obs_nets as ObsNets +import robomimic.models.policy_nets as PolicyNets +import robomimic.models.value_nets as ValueNets +import robomimic.utils.obs_utils as ObsUtils +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.torch_utils as TorchUtils +from robomimic.algo import register_algo_factory_func, ValueAlgo, PolicyAlgo + + +@register_algo_factory_func("cql") +def algo_config_to_class(algo_config): + """ + Maps algo config to the CQL algo class to instantiate, along with additional algo kwargs. + + Args: + algo_config (Config instance): algo config + + Returns: + algo_class: subclass of Algo + algo_kwargs (dict): dictionary of additional kwargs to pass to algorithm + """ + return CQL, {} + + +class CQL(PolicyAlgo, ValueAlgo): + """ + CQL-extension of SAC for the off-policy, offline setting. See https://arxiv.org/abs/2006.04779 + """ + def __init__(self, **kwargs): + # Store entropy / cql settings first since the super init call requires them + self.automatic_entropy_tuning = kwargs["algo_config"].actor.target_entropy is not None + self.automatic_cql_tuning = kwargs["algo_config"].critic.target_q_gap is not None and \ + kwargs["algo_config"].critic.target_q_gap >= 0.0 + + # Run super init first + super().__init__(**kwargs) + + # Reward settings + self.n_step = self.algo_config.n_step + self.discount = self.algo_config.discount ** self.n_step + + # Now also store additional SAC- and CQL-specific stuff from the config + self._num_batch_steps = 0 + self.bc_start_steps = self.algo_config.actor.bc_start_steps + self.deterministic_backup = self.algo_config.critic.deterministic_backup + self.td_loss_fcn = nn.SmoothL1Loss() if self.algo_config.critic.use_huber else nn.MSELoss() + + # Entropy settings + self.target_entropy = -np.prod(self.ac_dim) if self.algo_config.actor.target_entropy in {None, "default"} else\ + self.algo_config.actor.target_entropy + + # CQL settings + self.min_q_weight = self.algo_config.critic.min_q_weight + self.target_q_gap = self.algo_config.critic.target_q_gap if self.automatic_cql_tuning else 0.0 + + @property + def log_entropy_weight(self): + return self.nets["log_entropy_weight"]() if self.automatic_entropy_tuning else\ + torch.zeros(1, requires_grad=False, device=self.device) + + @property + def log_cql_weight(self): + return self.nets["log_cql_weight"]() if self.automatic_cql_tuning else\ + torch.log(torch.tensor(self.algo_config.critic.cql_weight, requires_grad=False, device=self.device)) + + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + + Networks for this algo: critic (potentially ensemble), policy + """ + + # Create nets + self.nets = nn.ModuleDict() + + # Assemble args to pass to actor + actor_args = dict(self.algo_config.actor.net.common) + + # Add network-specific args and define network class + if self.algo_config.actor.net.type == "gaussian": + actor_cls = PolicyNets.GaussianActorNetwork + actor_args.update(dict(self.algo_config.actor.net.gaussian)) + else: + # Unsupported actor type! + raise ValueError(f"Unsupported actor requested. " + f"Requested: {self.algo_config.actor.net.type}, " + f"valid options are: {['gaussian']}") + + # Policy + self.nets["actor"] = actor_cls( + obs_shapes=self.obs_shapes, + goal_shapes=self.goal_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.actor.layer_dims, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + **actor_args, + ) + + # Critics + self.nets["critic"] = nn.ModuleList() + self.nets["critic_target"] = nn.ModuleList() + for _ in range(self.algo_config.critic.ensemble.n): + for net_list in (self.nets["critic"], self.nets["critic_target"]): + critic = ValueNets.ActionValueNetwork( + obs_shapes=self.obs_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.critic.layer_dims, + value_bounds=self.algo_config.critic.value_bounds, + goal_shapes=self.goal_shapes, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + ) + net_list.append(critic) + + # Entropy (if automatically tuning) + if self.automatic_entropy_tuning: + self.nets["log_entropy_weight"] = BaseNets.Parameter(torch.zeros(1)) + + # CQL (if automatically tuning) + if self.automatic_cql_tuning: + self.nets["log_cql_weight"] = BaseNets.Parameter(torch.zeros(1)) + + # Send networks to appropriate device + self.nets = self.nets.float().to(self.device) + + # sync target networks at beginning of training + with torch.no_grad(): + for critic, critic_target in zip(self.nets["critic"], self.nets["critic_target"]): + TorchUtils.hard_update( + source=critic, + target=critic_target, + ) + + def _create_optimizers(self): + """ + Creates optimizers using @self.optim_params and places them into @self.optimizers. + + Overrides base method since we might need to create aditional optimizers for the entropy + and cql weight parameters (by default, the base class only creates optimizers for all + entries in @self.nets that have corresponding entries in `self.optim_params` but these + parameters do not). + """ + + # Create actor and critic optimizers via super method + super()._create_optimizers() + + # We still need to potentially create additional optimizers based on algo settings + + # entropy (if automatically tuning) + if self.automatic_entropy_tuning: + self.optimizers["entropy"] = optim.Adam( + params=self.nets["log_entropy_weight"].parameters(), + lr=self.optim_params["actor"]["learning_rate"]["initial"], + weight_decay=0.0, + ) + + # cql (if automatically tuning) + if self.automatic_cql_tuning: + self.optimizers["cql"] = optim.Adam( + params=self.nets["log_cql_weight"].parameters(), + lr=self.optim_params["critic"]["learning_rate"]["initial"], + weight_decay=0.0, + ) + + def process_batch_for_training(self, batch): + """ + Processes input batch from a data loader to filter out relevant info and prepare the batch for training. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader + + Returns: + input_batch (dict): processed and filtered batch that + will be used for training + """ + input_batch = dict() + + # Make sure the trajectory of actions received is greater than our step horizon + assert batch["actions"].shape[1] >= self.n_step + + # remove temporal batches for all + input_batch["obs"] = {k: batch["obs"][k][:, 0, :] for k in batch["obs"]} + input_batch["next_obs"] = {k: batch["next_obs"][k][:, self.n_step - 1, :] for k in batch["next_obs"]} + input_batch["goal_obs"] = batch.get("goal_obs", None) # goals may not be present + input_batch["actions"] = batch["actions"][:, 0, :] + + # note: ensure scalar signals (rewards, done) retain last dimension of 1 to be compatible with model outputs + + # single timestep reward is discounted sum of intermediate rewards in sequence + reward_seq = batch["rewards"][:, :self.n_step] + discounts = torch.pow(self.algo_config.discount, torch.arange(self.n_step).float()).unsqueeze(0) + input_batch["rewards"] = (reward_seq * discounts).sum(dim=1).unsqueeze(1) + + # consider this n-step seqeunce done if any intermediate dones are present + done_seq = batch["dones"][:, :self.n_step] + input_batch["dones"] = (done_seq.sum(dim=1) > 0).float().unsqueeze(1) + + # we move to device first before float conversion because image observation modalities will be uint8 - + # this minimizes the amount of data transferred to GPU + return TensorUtils.to_float(TensorUtils.to_device(input_batch, self.device)) + + def train_on_batch(self, batch, epoch, validate=False): + """ + Training on a single batch of data. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + validate (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + info = OrderedDict() + + # Set the correct context for this training step + with TorchUtils.maybe_no_grad(no_grad=validate): + # Always run super call first + super_info = super().train_on_batch(batch, epoch, validate=validate) + # Train actor + actor_info = self._train_policy_on_batch(batch, epoch, validate) + # Train critic(s) + critic_info = self._train_critic_on_batch(batch, epoch, validate) + # Update info + info.update(super_info) + info.update(actor_info) + info.update(critic_info) + + # Return stats + return info + + def _train_policy_on_batch(self, batch, epoch, validate=False): + """ + Training policy on a single batch of data. + + Loss is the ExpValue over sampled states of the (weighted) logprob of a sampled action + under the current policy minus the Q value of associated with the (s, a) combo + + Intuitively, this tries to improve the odds of sampling actions with high Q values while simultaneously + penalizing high probability actions. + + Since we're in the continuous setting, we monte carlo sample. + + Concretely: + Loss = Average[ entropy_weight * logprob(f(eps; s) | s) - Q(s, f(eps; s) ] + + where we use the reparameterization trick with Gaussian function f(*) to parameterize + actions as a function of the sampled noise param eps given input state s + + Additionally, we update the (log) entropy weight parameter if we're tuning that as well. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + validate (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + info = OrderedDict() + + # Sample actions from policy and get log probs + dist = self.nets["actor"].forward_train(obs_dict=batch["obs"], goal_dict=batch["goal_obs"]) + actions, log_prob = self._get_actions_and_log_prob(dist=dist) + + # Calculate alpha + entropy_weight_loss = -(self.log_entropy_weight * (log_prob + self.target_entropy).detach()).mean() if\ + self.automatic_entropy_tuning else 0.0 + entropy_weight = self.log_entropy_weight.exp() + + # Get predicted Q-values for all state, action pairs + pred_qs = [critic(obs_dict=batch["obs"], acts=actions, goal_dict=batch["goal_obs"]) + for critic in self.nets["critic"]] + # We take the minimum for stability + pred_qs, _ = torch.cat(pred_qs, dim=1).min(dim=1, keepdim=True) + + # Use BC if we're in the beginning of training, otherwise calculate policy loss normally + baseline = dist.log_prob(batch["actions"]).unsqueeze(dim=-1) if\ + self._num_batch_steps < self.bc_start_steps else pred_qs + policy_loss = (entropy_weight * log_prob - baseline).mean() + + # Add info + info["entropy_weight"] = entropy_weight.item() + info["entropy_weight_loss"] = entropy_weight_loss.item() if \ + self.automatic_entropy_tuning else entropy_weight_loss + info["actor/loss"] = policy_loss + + # Take a training step if we're not validating + if not validate: + # Update batch step + self._num_batch_steps += 1 + if self.automatic_entropy_tuning: + # Alpha + self.optimizers["entropy"].zero_grad() + entropy_weight_loss.backward() + self.optimizers["entropy"].step() + info["entropy_grad_norms"] = self.log_entropy_weight.grad.data.norm(2).pow(2).item() + + # Policy + actor_grad_norms = TorchUtils.backprop_for_loss( + net=self.nets["actor"], + optim=self.optimizers["actor"], + loss=policy_loss, + max_grad_norm=self.algo_config.actor.max_gradient_norm, + ) + # Add info + info["actor/grad_norms"] = actor_grad_norms + + # Return stats + return info + + def _train_critic_on_batch(self, batch, epoch, validate=False): + """ + Training critic(s) on a single batch of data. + + For a given batch of (s, a, r, s') tuples and n sampled actions (a_, a'_ corresponding to actions + sampled from the learned policy at states s and s', respectively; a~ corresponding to uniformly random + sampled actions): + + Loss = CQL_loss + SAC_loss + + Since we're in the continuous setting, we monte carlo sample for all ExpValues, which become Averages instead + + SAC_loss is the standard single-step TD error, corresponding to the following: + + SAC_loss = 0.5 * Average[ (Q(s,a) - (r + Average over a'_ [ Q(s', a'_) ]))^2 ] + + The CQL_loss corresponds to a weighted secondary objective, corresponding to the (ExpValue of Q values over + sampled states and sampled actions from the LEARNED policy) minus the (ExpValue of Q values over + sampled states and sampled actions from the DATASET policy) plus a regularizer as a function + of the learned policy. + + Intuitively, this tries to penalize Q-values arbitrarily resulting from the learned policy (which may produce + out-of-distribution (s,a) pairs) while preserving (known) Q-values taken from the dataset policy. + + As we are using SAC, we choose our regularizer to correspond to the negative KL divergence between our + learned policy and a uniform distribution such that the first term in the CQL loss corresponds to the + soft maximum over all Q values at any state s. + + For stability, we importance sample actions over random actions and from the current policy at s, s'. + + Moreover, if we want to tune the cql_weight automatically, we include the threshold value target_q_gap + to penalize Q values that are overly-optimistic by the given threshold. + + In this case, the CQL_loss is as follows: + + CQL_loss = cql_weight * (Average [log (Average over a` in {a~, a_, a_'}: exp(Q(s,a`) - logprob(a`)) - Average [Q(s,a)]] - target_q_gap) + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + validate (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + info = OrderedDict() + B, A = batch["actions"].shape + N = self.algo_config.critic.num_random_actions + + # Get predicted Q-values from taken actions + q_preds = [critic(obs_dict=batch["obs"], acts=batch["actions"], goal_dict=batch["goal_obs"]) + for critic in self.nets["critic"]] + + # Sample actions at the current and next step + curr_dist = self.nets["actor"].forward_train(obs_dict=batch["obs"], goal_dict=batch["goal_obs"]) + next_dist = self.nets["actor"].forward_train(obs_dict=batch["next_obs"], goal_dict=batch["goal_obs"]) + next_actions, next_log_prob = self._get_actions_and_log_prob(dist=next_dist) + + # Don't capture gradients here, since the critic target network doesn't get trained (only soft updated) + with torch.no_grad(): + # We take the max over all samples if the number of action samples is > 1 + if self.algo_config.critic.num_action_samples > 1: + # Generate the target q values, using the backup from the next state + temp_actions = next_dist.rsample(sample_shape=(self.algo_config.critic.num_action_samples,)).permute(1, 0, 2) + target_qs = [self._get_qs_from_actions( + obs_dict=batch["next_obs"], actions=temp_actions, goal_dict=batch["goal_obs"], q_net=critic) + .max(dim=1, keepdim=True)[0] for critic in self.nets["critic_target"]] + else: + target_qs = [critic(obs_dict=batch["next_obs"], acts=next_actions, goal_dict=batch["goal_obs"]) + for critic in self.nets["critic_target"]] + # Take the minimum over all critics + target_qs, _ = torch.cat(target_qs, dim=1).min(dim=1, keepdim=True) + # If only sampled once from each critic and not using a deterministic backup, subtract the logprob as well + if self.algo_config.critic.num_action_samples == 1 and not self.deterministic_backup: + target_qs = target_qs - self.log_entropy_weight.exp() * next_log_prob + + # Calculate the q target values + done_mask_batch = 1. - batch["dones"] + info["done_masks"] = done_mask_batch + q_target = batch["rewards"] + done_mask_batch * self.discount * target_qs + + # Calculate CQL stuff + cql_random_actions = torch.FloatTensor(N, B, A).uniform_(-1., 1.).to(self.device) # shape (N, B, A) + cql_random_log_prob = np.log(0.5 ** A) + cql_curr_actions, cql_curr_log_prob = self._get_actions_and_log_prob(dist=curr_dist, sample_shape=(N,)) # shape (N, B, A) and (N, B, 1) + cql_next_actions, cql_next_log_prob = self._get_actions_and_log_prob(dist=next_dist, sample_shape=(N,)) # shape (N, B, A) and (N, B, 1) + cql_curr_log_prob = cql_curr_log_prob.squeeze(dim=-1).permute(1, 0).detach() # shape (B, N) + cql_next_log_prob = cql_next_log_prob.squeeze(dim=-1).permute(1, 0).detach() # shape (B, N) + q_cats = [] # Each entry shape will be (B, N) + + for critic, q_pred in zip(self.nets["critic"], q_preds): + # Compose Q values over all sampled actions (importance sampled) + q_rand = self._get_qs_from_actions(obs_dict=batch["obs"], actions=cql_random_actions.permute(1, 0, 2), goal_dict=batch["goal_obs"], q_net=critic) + q_curr = self._get_qs_from_actions(obs_dict=batch["obs"], actions=cql_curr_actions.permute(1, 0, 2), goal_dict=batch["goal_obs"], q_net=critic) + q_next = self._get_qs_from_actions(obs_dict=batch["obs"], actions=cql_next_actions.permute(1, 0, 2), goal_dict=batch["goal_obs"], q_net=critic) + q_cat = torch.cat([ + q_rand - cql_random_log_prob, + q_next - cql_next_log_prob, + q_curr - cql_curr_log_prob, + ], dim=1) # shape (B, 3 * N) + q_cats.append(q_cat) + + # Calculate the losses for all critics + cql_losses = [] + critic_losses = [] + cql_weight = torch.clamp(self.log_cql_weight.exp(), min=0.0, max=1000000.0) + info["critic/cql_weight"] = cql_weight.item() + for i, (q_pred, q_cat) in enumerate(zip(q_preds, q_cats)): + # Calculate td error loss + td_loss = self.td_loss_fcn(q_pred, q_target) + # Calculate cql loss + cql_loss = cql_weight * (self.min_q_weight * (torch.logsumexp(q_cat, dim=1).mean() - q_pred.mean()) - + self.target_q_gap) + cql_losses.append(cql_loss) + # Calculate total loss + loss = td_loss + cql_loss + critic_losses.append(loss) + info[f"critic/critic{i+1}_loss"] = loss + + # Run gradient descent if we're not validating + if not validate: + # Train CQL weight if tuning automatically + if self.automatic_cql_tuning: + cql_weight_loss = -torch.stack(cql_losses).mean() + info[ + "critic/cql_weight_loss"] = cql_weight_loss.item() # Make sure to not store computation graph since we retain graph after backward() call + self.optimizers["cql"].zero_grad() + cql_weight_loss.backward(retain_graph=True) + self.optimizers["cql"].step() + info["critic/cql_grad_norms"] = self.log_cql_weight.grad.data.norm(2).pow(2).item() + + # Train critics + for i, (critic_loss, critic, critic_target, optimizer) in enumerate(zip( + critic_losses, self.nets["critic"], self.nets["critic_target"], self.optimizers["critic"] + )): + retain_graph = (i < (len(critic_losses) - 1)) + critic_grad_norms = TorchUtils.backprop_for_loss( + net=critic, + optim=optimizer, + loss=critic_loss, + max_grad_norm=self.algo_config.critic.max_gradient_norm, + retain_graph=retain_graph, + ) + info[f"critic/critic{i+1}_grad_norms"] = critic_grad_norms + with torch.no_grad(): + TorchUtils.soft_update(source=critic, target=critic_target, tau=self.algo_config.target_tau) + + # Return stats + return info + + def _get_actions_and_log_prob(self, dist, sample_shape=torch.Size()): + """ + Helper method to sample actions and compute corresponding log probabilities + + Args: + dist (Distribution): Distribution to sample from + sample_shape (torch.Size or tuple): Shape of output when sampling (number of samples) + + Returns: + 2-tuple: + - (tensor) sampled actions (..., B, ..., A) + - (tensor) corresponding log probabilities (..., B, ..., 1) + """ + # Process networks with tanh differently than normal distributions + if self.algo_config.actor.net.common.use_tanh: + actions, actions_pre_tanh = dist.rsample(sample_shape=sample_shape, return_pretanh_value=True) + log_prob = dist.log_prob(actions, pre_tanh_value=actions_pre_tanh).unsqueeze(dim=-1) + else: + actions = dist.rsample(sample_shape=sample_shape) + log_prob = dist.log_prob(actions) + + return actions, log_prob + + @staticmethod + def _get_qs_from_actions(obs_dict, actions, goal_dict, q_net): + """ + Helper function for grabbing Q values given a single state and multiple (N) sampled actions. + + Args: + obs_dict (dict): Observation dict from batch + actions (tensor): Torch tensor, with dim1 assumed to be the extra sampled dimension + goal_dict (dict): Goal dict from batch + q_net (nn.Module): Q net to pass the observations and actions + + Returns: + tensor: (B, N) corresponding Q values + """ + # Get the number of sampled actions + B, N, D = actions.shape + + # Repeat obs and goals in the batch dimension + obs_dict_stacked = ObsUtils.repeat_and_stack_observation(obs_dict, N) + goal_dict_stacked = ObsUtils.repeat_and_stack_observation(goal_dict, N) + + # Pass the obs and (flattened) actions through to get the Q values + qs = q_net(obs_dict=obs_dict_stacked, acts=actions.reshape(-1, D), goal_dict=goal_dict_stacked) + + # Unflatten output + qs = qs.reshape(B, N) + + return qs + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + loss_log = OrderedDict() + + # record current optimizer learning rates + for k in self.optimizers: + keys = [k] + optims = [self.optimizers[k]] + if k == "critic": + # account for critic having one optimizer per ensemble member + keys = ["{}{}".format(k, critic_ind) for critic_ind in range(len(self.nets["critic"]))] + optims = self.optimizers[k] + for kp, optimizer in zip(keys, optims): + for i, param_group in enumerate(optimizer.param_groups): + loss_log["Optimizer/{}{}_lr".format(kp, i)] = param_group["lr"] + + # extract relevant logs for critic, and actor + loss_log["Loss"] = 0. + for loss_logger in [self._log_critic_info, self._log_actor_info]: + this_log = loss_logger(info) + if "Loss" in this_log: + # manually merge total loss + loss_log["Loss"] += this_log["Loss"] + del this_log["Loss"] + loss_log.update(this_log) + + return loss_log + + def _log_critic_info(self, info): + """ + Helper function to extract critic-relevant information for logging. + """ + loss_log = OrderedDict() + if "done_masks" in info: + loss_log["Critic/Done_Mask_Percentage"] = 100. * torch.mean(info["done_masks"]).item() + if "critic/q_targets" in info: + loss_log["Critic/Q_Targets"] = info["critic/q_targets"].mean().item() + loss_log["Loss"] = 0. + for critic_ind in range(len(self.nets["critic"])): + loss_log["Critic/Critic{}_Loss".format(critic_ind + 1)] = info["critic/critic{}_loss".format(critic_ind + 1)].item() + if "critic/critic{}_grad_norms".format(critic_ind + 1) in info: + loss_log["Critic/Critic{}_Grad_Norms".format(critic_ind + 1)] = info["critic/critic{}_grad_norms".format(critic_ind + 1)] + loss_log["Loss"] += loss_log["Critic/Critic{}_Loss".format(critic_ind + 1)] + if "critic/cql_weight_loss" in info: + loss_log["Critic/CQL_Weight"] = info["critic/cql_weight"] + loss_log["Critic/CQL_Weight_Loss"] = info["critic/cql_weight_loss"] + loss_log["Critic/CQL_Grad_Norms"] = info["critic/cql_grad_norms"] + return loss_log + + def _log_actor_info(self, info): + """ + Helper function to extract actor-relevant information for logging. + """ + loss_log = OrderedDict() + loss_log["Actor/Loss"] = info["actor/loss"].item() + if "actor/grad_norms" in info: + loss_log["Actor/Grad_Norms"] = info["actor/grad_norms"] + loss_log["Loss"] = loss_log["Actor/Loss"] + loss_log["Entropy_Weight_Loss"] = info["entropy_weight_loss"] + loss_log["Entropy_Weight"] = info["entropy_weight"] + if "entropy_grad_norms" in info: + loss_log["Entropy_Grad_Norms"] = info["entropy_grad_norms"] + return loss_log + + def set_train(self): + """ + Prepare networks for evaluation. Update from super class to make sure + target networks stay in evaluation mode all the time. + """ + self.nets.train() + + # target networks always in eval + for critic in self.nets["critic_target"]: + critic.eval() + + def on_epoch_end(self, epoch): + """ + Called at the end of each epoch. + """ + + # LR scheduling updates + for lr_sc in self.lr_schedulers["critic"]: + if lr_sc is not None: + lr_sc.step() + + if self.lr_schedulers["actor"] is not None: + self.lr_schedulers["actor"].step() + + def get_action(self, obs_dict, goal_dict=None): + """ + Get policy action outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + action (torch.Tensor): action tensor + """ + assert not self.nets.training + + return self.nets["actor"](obs_dict=obs_dict, goal_dict=goal_dict) + + def get_state_action_value(self, obs_dict, actions, goal_dict=None): + """ + Get state-action value outputs. + + Args: + obs_dict (dict): current observation + actions (torch.Tensor): action + goal_dict (dict): (optional) goal + + Returns: + value (torch.Tensor): value tensor + """ + assert not self.nets.training + + return self.nets["critic"][0](obs_dict, actions, goal_dict) diff --git a/code_src/rise_robomimic/robomimic/algo/diffusion_policy.py b/code_src/rise_robomimic/robomimic/algo/diffusion_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..2d2b20d9366d56852e3af5686a4848d7b3d5629d --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/diffusion_policy.py @@ -0,0 +1,697 @@ +""" +Implementation of Diffusion Policy https://diffusion-policy.cs.columbia.edu/ by Cheng Chi +""" +from typing import Callable, Union +import math +from collections import OrderedDict, deque +from packaging.version import parse as parse_version +import random +import torch +import torch.nn as nn +import torch.nn.functional as F +# requires diffusers==0.11.1 +from diffusers.schedulers.scheduling_ddpm import DDPMScheduler +from diffusers.schedulers.scheduling_ddim import DDIMScheduler +from diffusers.training_utils import EMAModel + +import robomimic.models.obs_nets as ObsNets +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.torch_utils as TorchUtils +import robomimic.utils.obs_utils as ObsUtils + +from robomimic.algo import register_algo_factory_func, PolicyAlgo + +import random +import robomimic.utils.torch_utils as TorchUtils +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.obs_utils as ObsUtils + +@register_algo_factory_func("diffusion_policy") +def algo_config_to_class(algo_config): + """ + Maps algo config to the BC algo class to instantiate, along with additional algo kwargs. + + Args: + algo_config (Config instance): algo config + + Returns: + algo_class: subclass of Algo + algo_kwargs (dict): dictionary of additional kwargs to pass to algorithm + """ + + if algo_config.unet.enabled: + return DiffusionPolicyUNet, {} + elif algo_config.transformer.enabled: + raise NotImplementedError() + else: + raise RuntimeError() + +class DiffusionPolicyUNet(PolicyAlgo): + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + """ + # set up different observation groups for @MIMO_MLP + observation_group_shapes = OrderedDict() + observation_group_shapes["obs"] = OrderedDict(self.obs_shapes) + encoder_kwargs = ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder) + + obs_encoder = ObsNets.ObservationGroupEncoder( + observation_group_shapes=observation_group_shapes, + encoder_kwargs=encoder_kwargs, + ) + # IMPORTANT! + # replace all BatchNorm with GroupNorm to work with EMA + # performance will tank if you forget to do this! + obs_encoder = replace_bn_with_gn(obs_encoder) + + obs_dim = obs_encoder.output_shape()[0] + + # create network object + noise_pred_net = ConditionalUnet1D( + input_dim=self.ac_dim, + global_cond_dim=obs_dim*self.algo_config.horizon.observation_horizon + ) + + # the final arch has 2 parts + nets = nn.ModuleDict({ + 'policy': nn.ModuleDict({ + 'obs_encoder': obs_encoder, + 'noise_pred_net': noise_pred_net + }) + }) + + nets = nets.float().to(self.device) + + # setup noise scheduler + noise_scheduler = None + if self.algo_config.ddpm.enabled: + noise_scheduler = DDPMScheduler( + num_train_timesteps=self.algo_config.ddpm.num_train_timesteps, + beta_schedule=self.algo_config.ddpm.beta_schedule, + clip_sample=self.algo_config.ddpm.clip_sample, + prediction_type=self.algo_config.ddpm.prediction_type + ) + elif self.algo_config.ddim.enabled: + noise_scheduler = DDIMScheduler( + num_train_timesteps=self.algo_config.ddim.num_train_timesteps, + beta_schedule=self.algo_config.ddim.beta_schedule, + clip_sample=self.algo_config.ddim.clip_sample, + set_alpha_to_one=self.algo_config.ddim.set_alpha_to_one, + steps_offset=self.algo_config.ddim.steps_offset, + prediction_type=self.algo_config.ddim.prediction_type + ) + else: + raise RuntimeError() + + # setup EMA + ema = None + if self.algo_config.ema.enabled: + ema = EMAModel(model=nets, power=self.algo_config.ema.power) + + # set attrs + self.nets = nets + self.noise_scheduler = noise_scheduler + self.ema = ema + self.action_check_done = False + self.obs_queue = None + self.action_queue = None + + def process_batch_for_training(self, batch): + """ + Processes input batch from a data loader to filter out + relevant information and prepare the batch for training. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader + + Returns: + input_batch (dict): processed and filtered batch that + will be used for training + """ + To = self.algo_config.horizon.observation_horizon + Ta = self.algo_config.horizon.action_horizon + Tp = self.algo_config.horizon.prediction_horizon + + input_batch = dict() + input_batch["obs"] = {k: batch["obs"][k][:, :To, :] for k in batch["obs"]} + input_batch["goal_obs"] = batch.get("goal_obs", None) # goals may not be present + input_batch["actions"] = batch["actions"][:, :Tp, :] + + # check if actions are normalized to [-1,1] + if not self.action_check_done: + actions = input_batch["actions"] + in_range = (-1 <= actions) & (actions <= 1) + all_in_range = torch.all(in_range).item() + if not all_in_range: + raise ValueError('"actions" must be in range [-1,1] for Diffusion Policy! Check if hdf5_normalize_action is enabled.') + self.action_check_done = True + + return TensorUtils.to_device(TensorUtils.to_float(input_batch), self.device) + + def train_on_batch(self, batch, epoch, validate=False): + """ + Training on a single batch of data. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + validate (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + To = self.algo_config.horizon.observation_horizon + Ta = self.algo_config.horizon.action_horizon + Tp = self.algo_config.horizon.prediction_horizon + action_dim = self.ac_dim + B = batch['actions'].shape[0] + + + with TorchUtils.maybe_no_grad(no_grad=validate): + info = super(DiffusionPolicyUNet, self).train_on_batch(batch, epoch, validate=validate) + actions = batch['actions'] + + # encode obs + inputs = { + 'obs': batch["obs"], + 'goal': batch["goal_obs"] + } + for k in self.obs_shapes: + # first two dimensions should be [B, T] for inputs + assert inputs['obs'][k].ndim - 2 == len(self.obs_shapes[k]) + + obs_features = TensorUtils.time_distributed(inputs, self.nets['policy']['obs_encoder'], inputs_as_kwargs=True) + assert obs_features.ndim == 3 # [B, T, D] + + obs_cond = obs_features.flatten(start_dim=1) + + # sample noise to add to actions + noise = torch.randn(actions.shape, device=self.device) + + # sample a diffusion iteration for each data point + timesteps = torch.randint( + 0, self.noise_scheduler.config.num_train_timesteps, + (B,), device=self.device + ).long() + + # add noise to the clean actions according to the noise magnitude at each diffusion iteration + # (this is the forward diffusion process) + noisy_actions = self.noise_scheduler.add_noise( + actions, noise, timesteps) + + # predict the noise residual + noise_pred = self.nets['policy']['noise_pred_net']( + noisy_actions, timesteps, global_cond=obs_cond) + + # L2 loss + loss = F.mse_loss(noise_pred, noise) + + # logging + losses = { + 'l2_loss': loss + } + info["losses"] = TensorUtils.detach(losses) + + if not validate: + # gradient step + policy_grad_norms = TorchUtils.backprop_for_loss( + net=self.nets, + optim=self.optimizers["policy"], + loss=loss, + ) + + # update Exponential Moving Average of the model weights + if self.ema is not None: + self.ema.step(self.nets) + + step_info = { + 'policy_grad_norms': policy_grad_norms + } + info.update(step_info) + + return info + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + log = super(DiffusionPolicyUNet, self).log_info(info) + log["Loss"] = info["losses"]["l2_loss"].item() + if "policy_grad_norms" in info: + log["Policy_Grad_Norms"] = info["policy_grad_norms"] + return log + + def reset(self): + """ + Reset algo state to prepare for environment rollouts. + """ + # setup inference queues + To = self.algo_config.horizon.observation_horizon + Ta = self.algo_config.horizon.action_horizon + obs_queue = deque(maxlen=To) + action_queue = deque(maxlen=Ta) + self.obs_queue = obs_queue + self.action_queue = action_queue + + def get_action(self, obs_dict, goal_dict=None): + """ + Get policy action outputs. + + Args: + obs_dict (dict): current observation [1, Do] + goal_dict (dict): (optional) goal + + Returns: + action (torch.Tensor): action tensor [1, Da] + """ + # obs_dict: key: [1,D] + To = self.algo_config.horizon.observation_horizon + Ta = self.algo_config.horizon.action_horizon + + # TODO: obs_queue already handled by frame_stack + # make sure we have at least To observations in obs_queue + # if not enough, repeat + # if already full, append one to the obs_queue + # n_repeats = max(To - len(self.obs_queue), 1) + # self.obs_queue.extend([obs_dict] * n_repeats) + + if len(self.action_queue) == 0: + # no actions left, run inference + # turn obs_queue into dict of tensors (concat at T dim) + # import pdb; pdb.set_trace() + # obs_dict_list = TensorUtils.list_of_flat_dict_to_dict_of_list(list(self.obs_queue)) + # obs_dict_tensor = dict((k, torch.cat(v, dim=0).unsqueeze(0)) for k,v in obs_dict_list.items()) + + # run inference + # [1,T,Da] + action_sequence = self._get_action_trajectory(obs_dict=obs_dict) + + # put actions into the queue + self.action_queue.extend(action_sequence[0]) + + # has action, execute from left to right + # [Da] + action = self.action_queue.popleft() + + # [1,Da] + action = action.unsqueeze(0) + return action + + def _get_action_trajectory(self, obs_dict, goal_dict=None): + assert not self.nets.training + To = self.algo_config.horizon.observation_horizon + Ta = self.algo_config.horizon.action_horizon + Tp = self.algo_config.horizon.prediction_horizon + action_dim = self.ac_dim + if self.algo_config.ddpm.enabled is True: + num_inference_timesteps = self.algo_config.ddpm.num_inference_timesteps + elif self.algo_config.ddim.enabled is True: + num_inference_timesteps = self.algo_config.ddim.num_inference_timesteps + else: + raise ValueError + + # select network + nets = self.nets + if self.ema is not None: + nets = self.ema.averaged_model + + # encode obs + inputs = { + 'obs': obs_dict, + 'goal': goal_dict + } + for k in self.obs_shapes: + # first two dimensions should be [B, T] for inputs + assert inputs['obs'][k].ndim - 2 == len(self.obs_shapes[k]) + obs_features = TensorUtils.time_distributed(inputs, self.nets['policy']['obs_encoder'], inputs_as_kwargs=True) + assert obs_features.ndim == 3 # [B, T, D] + B = obs_features.shape[0] + + # reshape observation to (B,obs_horizon*obs_dim) + obs_cond = obs_features.flatten(start_dim=1) + + # initialize action from Guassian noise + noisy_action = torch.randn( + (B, Tp, action_dim), device=self.device) + naction = noisy_action + + # init scheduler + self.noise_scheduler.set_timesteps(num_inference_timesteps) + + for k in self.noise_scheduler.timesteps: + # predict noise + noise_pred = nets['policy']['noise_pred_net']( + sample=naction, + timestep=k, + global_cond=obs_cond + ) + + # inverse diffusion step (remove noise) + naction = self.noise_scheduler.step( + model_output=noise_pred, + timestep=k, + sample=naction + ).prev_sample + + # process action using Ta + start = To - 1 + end = start + Ta + action = naction[:,start:end] + return action + + def serialize(self): + """ + Get dictionary of current model parameters. + """ + return { + "nets": self.nets.state_dict(), + "ema": self.ema.averaged_model.state_dict() if self.ema is not None else None, + } + + def deserialize(self, model_dict): + """ + Load model from a checkpoint. + + Args: + model_dict (dict): a dictionary saved by self.serialize() that contains + the same keys as @self.network_classes + """ + self.nets.load_state_dict(model_dict["nets"]) + if model_dict.get("ema", None) is not None: + self.ema.averaged_model.load_state_dict(model_dict["ema"]) + + + + + +# =================== Vision Encoder Utils ===================== +def replace_submodules( + root_module: nn.Module, + predicate: Callable[[nn.Module], bool], + func: Callable[[nn.Module], nn.Module]) -> nn.Module: + """ + Replace all submodules selected by the predicate with + the output of func. + + predicate: Return true if the module is to be replaced. + func: Return new module to use. + """ + if predicate(root_module): + return func(root_module) + + if parse_version(torch.__version__) < parse_version('1.9.0'): + raise ImportError('This function requires pytorch >= 1.9.0') + + bn_list = [k.split('.') for k, m + in root_module.named_modules(remove_duplicate=True) + if predicate(m)] + for *parent, k in bn_list: + parent_module = root_module + if len(parent) > 0: + parent_module = root_module.get_submodule('.'.join(parent)) + if isinstance(parent_module, nn.Sequential): + src_module = parent_module[int(k)] + else: + src_module = getattr(parent_module, k) + tgt_module = func(src_module) + if isinstance(parent_module, nn.Sequential): + parent_module[int(k)] = tgt_module + else: + setattr(parent_module, k, tgt_module) + # verify that all modules are replaced + bn_list = [k.split('.') for k, m + in root_module.named_modules(remove_duplicate=True) + if predicate(m)] + assert len(bn_list) == 0 + return root_module + +def replace_bn_with_gn( + root_module: nn.Module, + features_per_group: int=16) -> nn.Module: + """ + Relace all BatchNorm layers with GroupNorm. + """ + replace_submodules( + root_module=root_module, + predicate=lambda x: isinstance(x, nn.BatchNorm2d), + func=lambda x: nn.GroupNorm( + num_groups=x.num_features//features_per_group, + num_channels=x.num_features) + ) + return root_module + +# =================== UNet for Diffusion ============== + +class SinusoidalPosEmb(nn.Module): + def __init__(self, dim): + super().__init__() + self.dim = dim + + def forward(self, x): + device = x.device + half_dim = self.dim // 2 + emb = math.log(10000) / (half_dim - 1) + emb = torch.exp(torch.arange(half_dim, device=device) * -emb) + emb = x[:, None] * emb[None, :] + emb = torch.cat((emb.sin(), emb.cos()), dim=-1) + return emb + + +class Downsample1d(nn.Module): + def __init__(self, dim): + super().__init__() + self.conv = nn.Conv1d(dim, dim, 3, 2, 1) + + def forward(self, x): + return self.conv(x) + +class Upsample1d(nn.Module): + def __init__(self, dim): + super().__init__() + self.conv = nn.ConvTranspose1d(dim, dim, 4, 2, 1) + + def forward(self, x): + return self.conv(x) + + +class Conv1dBlock(nn.Module): + ''' + Conv1d --> GroupNorm --> Mish + ''' + + def __init__(self, inp_channels, out_channels, kernel_size, n_groups=8): + super().__init__() + + self.block = nn.Sequential( + nn.Conv1d(inp_channels, out_channels, kernel_size, padding=kernel_size // 2), + nn.GroupNorm(n_groups, out_channels), + nn.Mish(), + ) + + def forward(self, x): + return self.block(x) + + +class ConditionalResidualBlock1D(nn.Module): + def __init__(self, + in_channels, + out_channels, + cond_dim, + kernel_size=3, + n_groups=8): + super().__init__() + + self.blocks = nn.ModuleList([ + Conv1dBlock(in_channels, out_channels, kernel_size, n_groups=n_groups), + Conv1dBlock(out_channels, out_channels, kernel_size, n_groups=n_groups), + ]) + + # FiLM modulation https://arxiv.org/abs/1709.07871 + # predicts per-channel scale and bias + cond_channels = out_channels * 2 + self.out_channels = out_channels + self.cond_encoder = nn.Sequential( + nn.Mish(), + nn.Linear(cond_dim, cond_channels), + nn.Unflatten(-1, (-1, 1)) + ) + + # make sure dimensions compatible + self.residual_conv = nn.Conv1d(in_channels, out_channels, 1) \ + if in_channels != out_channels else nn.Identity() + + def forward(self, x, cond): + ''' + x : [ batch_size x in_channels x horizon ] + cond : [ batch_size x cond_dim] + + returns: + out : [ batch_size x out_channels x horizon ] + ''' + out = self.blocks[0](x) + embed = self.cond_encoder(cond) + + embed = embed.reshape( + embed.shape[0], 2, self.out_channels, 1) + scale = embed[:,0,...] + bias = embed[:,1,...] + out = scale * out + bias + + out = self.blocks[1](out) + out = out + self.residual_conv(x) + return out + + +class ConditionalUnet1D(nn.Module): + def __init__(self, + input_dim, + global_cond_dim, + diffusion_step_embed_dim=256, + down_dims=[256,512,1024], + kernel_size=5, + n_groups=8 + ): + """ + input_dim: Dim of actions. + global_cond_dim: Dim of global conditioning applied with FiLM + in addition to diffusion step embedding. This is usually obs_horizon * obs_dim + diffusion_step_embed_dim: Size of positional encoding for diffusion iteration k + down_dims: Channel size for each UNet level. + The length of this array determines numebr of levels. + kernel_size: Conv kernel size + n_groups: Number of groups for GroupNorm + """ + + super().__init__() + all_dims = [input_dim] + list(down_dims) + start_dim = down_dims[0] + + dsed = diffusion_step_embed_dim + diffusion_step_encoder = nn.Sequential( + SinusoidalPosEmb(dsed), + nn.Linear(dsed, dsed * 4), + nn.Mish(), + nn.Linear(dsed * 4, dsed), + ) + cond_dim = dsed + global_cond_dim + + in_out = list(zip(all_dims[:-1], all_dims[1:])) + mid_dim = all_dims[-1] + self.mid_modules = nn.ModuleList([ + ConditionalResidualBlock1D( + mid_dim, mid_dim, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups + ), + ConditionalResidualBlock1D( + mid_dim, mid_dim, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups + ), + ]) + + down_modules = nn.ModuleList([]) + for ind, (dim_in, dim_out) in enumerate(in_out): + is_last = ind >= (len(in_out) - 1) + down_modules.append(nn.ModuleList([ + ConditionalResidualBlock1D( + dim_in, dim_out, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups), + ConditionalResidualBlock1D( + dim_out, dim_out, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups), + Downsample1d(dim_out) if not is_last else nn.Identity() + ])) + + up_modules = nn.ModuleList([]) + for ind, (dim_in, dim_out) in enumerate(reversed(in_out[1:])): + is_last = ind >= (len(in_out) - 1) + up_modules.append(nn.ModuleList([ + ConditionalResidualBlock1D( + dim_out*2, dim_in, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups), + ConditionalResidualBlock1D( + dim_in, dim_in, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups), + Upsample1d(dim_in) if not is_last else nn.Identity() + ])) + + final_conv = nn.Sequential( + Conv1dBlock(start_dim, start_dim, kernel_size=kernel_size), + nn.Conv1d(start_dim, input_dim, 1), + ) + + self.diffusion_step_encoder = diffusion_step_encoder + self.up_modules = up_modules + self.down_modules = down_modules + self.final_conv = final_conv + + print("number of parameters: {:e}".format( + sum(p.numel() for p in self.parameters())) + ) + + def forward(self, + sample: torch.Tensor, + timestep: Union[torch.Tensor, float, int], + global_cond=None): + """ + x: (B,T,input_dim) + timestep: (B,) or int, diffusion step + global_cond: (B,global_cond_dim) + output: (B,T,input_dim) + """ + # (B,T,C) + sample = sample.moveaxis(-1,-2) + # (B,C,T) + + # 1. time + timesteps = timestep + if not torch.is_tensor(timesteps): + timesteps = torch.tensor([timesteps], dtype=torch.long, device=sample.device) + elif torch.is_tensor(timesteps) and len(timesteps.shape) == 0: + timesteps = timesteps[None].to(sample.device) + # broadcast to batch dimension in a way that's compatible with ONNX/Core ML + timesteps = timesteps.expand(sample.shape[0]) + + global_feature = self.diffusion_step_encoder(timesteps) + + if global_cond is not None: + global_feature = torch.cat([ + global_feature, global_cond + ], axis=-1) + + x = sample + h = [] + for idx, (resnet, resnet2, downsample) in enumerate(self.down_modules): + x = resnet(x, global_feature) + x = resnet2(x, global_feature) + h.append(x) + x = downsample(x) + + for mid_module in self.mid_modules: + x = mid_module(x, global_feature) + + for idx, (resnet, resnet2, upsample) in enumerate(self.up_modules): + x = torch.cat((x, h.pop()), dim=1) + x = resnet(x, global_feature) + x = resnet2(x, global_feature) + x = upsample(x) + + x = self.final_conv(x) + + # (B,C,T) + x = x.moveaxis(-1,-2) + # (B,T,C) + return x diff --git a/code_src/rise_robomimic/robomimic/algo/discriminator.py b/code_src/rise_robomimic/robomimic/algo/discriminator.py new file mode 100644 index 0000000000000000000000000000000000000000..e512a69425d0b7843e05bdd3277be082774ac9bb --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/discriminator.py @@ -0,0 +1,201 @@ +""" +Implementation of Behavioral Cloning (BC). +""" +from collections import OrderedDict + +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.distributions as D + +import robomimic.models.base_nets as BaseNets +import robomimic.models.obs_nets as ObsNets +import robomimic.models.policy_nets as PolicyNets +import robomimic.models.vae_nets as VAENets +import robomimic.utils.loss_utils as LossUtils +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.torch_utils as TorchUtils +import robomimic.utils.obs_utils as ObsUtils + +from robomimic.algo import register_algo_factory_func, PolicyAlgo + + +@register_algo_factory_func("discriminator") +def algo_config_to_class(algo_config): + """ + Maps algo config to the Discriminator algo class to instantiate, along with additional algo kwargs. + + Args: + algo_config (Config instance): algo config + + Returns: + algo_class: subclass of Algo + algo_kwargs (dict): dictionary of additional kwargs to pass to algorithm + """ + + algo_class, algo_kwargs = Discriminator, {} + + return algo_class, algo_kwargs + + +class Discriminator(PolicyAlgo): + """ + Normal BC training. + """ + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + """ + self.nets = nn.ModuleDict() + self.nets['policy'] = PolicyNets.Discriminator_MLP( + obs_shapes=self.obs_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.discriminator_layer_dims + ) + self.nets = self.nets.float().to(self.device) + + def process_batch_for_training(self, batch): + """ + Processes input batch from a data loader to filter out + relevant information and prepare the batch for training. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader + + Returns: + input_batch (dict): processed and filtered batch that + will be used for training + """ + input_batch = dict() + input_batch["obs"] = {k: batch["obs"][k][:, 0, :] for k in batch["obs"]} + input_batch["goal_obs"] = batch.get("goal_obs", None) # goals may not be present + input_batch["actions"] = batch["actions"][:, 0, :] + # we move to device first before float conversion because image observation modalities will be uint8 - + # this minimizes the amount of data transferred to GPU + return TensorUtils.to_float(TensorUtils.to_device(input_batch, self.device)) + + + def train_on_batch(self, expert_batch, subopt_batch, epoch, validate): + with TorchUtils.maybe_no_grad(no_grad=validate): + # print(f'expert_batch : {expert_batch.keys()}') + info = OrderedDict() + prediction_on_expert = self._forward_training(expert_batch) + prediction_on_subopt = self._forward_training(subopt_batch) + losses = self._compute_losses(preds_on_expert=prediction_on_expert, preds_on_subopt=prediction_on_subopt) + + info['preds_on_expert'] = TensorUtils.detach(prediction_on_expert) + info['preds_on_subopt'] = TensorUtils.detach(prediction_on_subopt) + + + tp = (info['preds_on_expert']['preds'] > 0.5).float().mean() + fp = (info['preds_on_subopt']['preds'] > 0.5).float().mean() + tn = (info['preds_on_subopt']['preds'] < 0.5).float().mean() + fn = (info['preds_on_expert']['preds'] < 0.5).float().mean() + + info['tp'] = tp.item() + info['fp'] = fp.item() + info['tn'] = tn.item() + info['fn'] = fn.item() + + info["losses"] = TensorUtils.detach(losses) + + if not validate: + step_info = self._train_step(losses) + info.update(step_info) + + return info + + def _forward_training(self, batch): + """ + Internal helper function for BC algo class. Compute forward pass + and return network outputs in @predictions dict. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + Returns: + predictions (dict): dictionary containing network outputs + """ + predictions = OrderedDict() + preds = self.nets['policy'](obs=batch['obs'], goal_dict=batch['goal_obs']) + predictions['preds'] = preds + return predictions + + def _compute_losses(self, preds_on_expert, preds_on_subopt): + """ + Internal helper function for BC algo class. Compute losses based on + network outputs in @predictions dict, using reference labels in @batch. + + Args: + predictions (dict): dictionary containing network outputs, from @_forward_training + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + Returns: + losses (dict): dictionary of losses computed over the batch + """ + expert_target = torch.ones_like(preds_on_expert['preds']).to(self.device) + subopt_target = torch.zeros_like(preds_on_subopt['preds']).to(self.device) + + expert_loss = nn.BCELoss()(preds_on_expert['preds'], expert_target) + subopt_loss = nn.BCELoss()(preds_on_subopt['preds'], subopt_target) + + losses = OrderedDict() + losses["prediction_loss"] = expert_loss + subopt_loss + losses["expert_prediction_loss"] = expert_loss + losses["subopt_prediction_loss"] = subopt_loss + return losses + + def _train_step(self, losses): + """ + Internal helper function for BC algo class. Perform backpropagation on the + loss tensors in @losses to update networks. + + Args: + losses (dict): dictionary of losses computed over the batch, from @_compute_losses + """ + + # gradient step + info = OrderedDict() + policy_grad_norms = TorchUtils.backprop_for_loss( + net=self.nets["policy"], + optim=self.optimizers["policy"], + loss=losses["prediction_loss"], + ) + info["policy_grad_norms"] = policy_grad_norms + return info + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + log = super().log_info(info) + log["Loss"] = info["losses"]["prediction_loss"].item() + log["TP"] = info["tp"] + log["FP"] = info["fp"] + log["TN"] = info["tn"] + log["FN"] = info["fn"] + return log + + def get_action(self, obs_dict, goal_dict=None): + """ + Get policy action outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + action (torch.Tensor): action tensor + """ + assert not self.nets.training + return self.nets["policy"](obs_dict, goal_dict=goal_dict) \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/algo/gl.py b/code_src/rise_robomimic/robomimic/algo/gl.py new file mode 100644 index 0000000000000000000000000000000000000000..24ae800892ee0866f9b4df3d94ff49eb1cd8d112 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/gl.py @@ -0,0 +1,775 @@ +""" +Subgoal prediction models, used in HBC / IRIS. +""" +import numpy as np +from collections import OrderedDict +from copy import deepcopy + +import torch +import torch.nn as nn + +import robomimic.models.obs_nets as ObsNets +import robomimic.models.vae_nets as VAENets +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.torch_utils as TorchUtils +import robomimic.utils.obs_utils as ObsUtils + +from robomimic.algo import register_algo_factory_func, PlannerAlgo, ValueAlgo + + +@register_algo_factory_func("gl") +def algo_config_to_class(algo_config): + """ + Maps algo config to the GL algo class to instantiate, along with additional algo kwargs. + + Args: + algo_config (Config instance): algo config + + Returns: + algo_class: subclass of Algo + algo_kwargs (dict): dictionary of additional kwargs to pass to algorithm + """ + if algo_config.vae.enabled: + return GL_VAE, {} + return GL, {} + + +class GL(PlannerAlgo): + """ + Implements goal prediction component for HBC and IRIS. + """ + def __init__( + self, + algo_config, + obs_config, + global_config, + obs_key_shapes, + ac_dim, + device + ): + """ + Args: + algo_config (Config object): instance of Config corresponding to the algo section + of the config + + obs_config (Config object): instance of Config corresponding to the observation + section of the config + + global_config (Config object): global training config + + obs_key_shapes (OrderedDict): dictionary that maps observation keys to shapes + + ac_dim (int): dimension of action space + + device (torch.Device): where the algo should live (i.e. cpu, gpu) + """ + + self._subgoal_horizon = algo_config.subgoal_horizon + super(GL, self).__init__( + algo_config=algo_config, + obs_config=obs_config, + global_config=global_config, + obs_key_shapes=obs_key_shapes, + ac_dim=ac_dim, + device=device + ) + + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + """ + self.nets = nn.ModuleDict() + + obs_group_shapes = OrderedDict() + obs_group_shapes["obs"] = OrderedDict(self.obs_shapes) + if len(self.goal_shapes) > 0: + obs_group_shapes["goal"] = OrderedDict(self.goal_shapes) + + # deterministic goal prediction network + self.nets["goal_network"] = ObsNets.MIMO_MLP( + input_obs_group_shapes=obs_group_shapes, + output_shapes=self.subgoal_shapes, + layer_dims=self.algo_config.ae.planner_layer_dims, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + ) + + self.nets = self.nets.float().to(self.device) + + def process_batch_for_training(self, batch): + """ + Processes input batch from a data loader to filter out + relevant information and prepare the batch for training. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader + + Returns: + input_batch (dict): processed and filtered batch that + will be used for training + """ + input_batch = dict() + + # remove temporal batches for all except scalar signals (to be compatible with model outputs) + input_batch["obs"] = { k: batch["obs"][k][:, 0, :] for k in batch["obs"] } + # extract multi-horizon subgoal target + input_batch["subgoals"] = {k: batch["next_obs"][k][:, self._subgoal_horizon - 1, :] for k in batch["next_obs"]} + input_batch["target_subgoals"] = input_batch["subgoals"] + input_batch["goal_obs"] = batch.get("goal_obs", None) # goals may not be present + + # we move to device first before float conversion because image observation modalities will be uint8 - + # this minimizes the amount of data transferred to GPU + return TensorUtils.to_float(TensorUtils.to_device(input_batch, self.device)) + + def get_actor_goal_for_training_from_processed_batch(self, processed_batch, **kwargs): + """ + Retrieve subgoals from processed batch to use for training the actor. Subclasses + can modify this function to change the subgoals. + + Args: + processed_batch (dict): processed batch from @process_batch_for_training + + Returns: + actor_subgoals (dict): subgoal observations to condition actor on + """ + return processed_batch["target_subgoals"] + + def train_on_batch(self, batch, epoch, validate=False): + """ + Training on a single batch of data. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + validate (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + with TorchUtils.maybe_no_grad(no_grad=validate): + info = super(GL, self).train_on_batch(batch, epoch, validate=validate) + + # predict subgoal observations with goal network + pred_subgoals = self.nets["goal_network"](obs=batch["obs"], goal=batch["goal_obs"]) + + # compute loss as L2 error for each observation key + losses = OrderedDict() + target_subgoals = batch["target_subgoals"] # targets for network prediction + goal_loss = 0. + for k in pred_subgoals: + assert pred_subgoals[k].shape == target_subgoals[k].shape, "mismatch in predicted and target subgoals!" + mode_loss = nn.MSELoss()(pred_subgoals[k], target_subgoals[k]) + goal_loss += mode_loss + losses["goal_{}_loss".format(k)] = mode_loss + losses["goal_loss"] = goal_loss + info.update(TensorUtils.detach(losses)) + + if not validate: + # gradient step + goal_grad_norms = TorchUtils.backprop_for_loss( + net=self.nets["goal_network"], + optim=self.optimizers["goal_network"], + loss=losses["goal_loss"], + ) + info["goal_grad_norms"] = goal_grad_norms + + return info + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + loss_log = super(GL, self).log_info(info) + + loss_log["Loss"] = info["goal_loss"].item() + for k in info: + if k.endswith("_loss"): + loss_log[k] = info[k].item() + if "goal_grad_norms" in info: + loss_log["Grad_Norms"] = info["goal_grad_norms"] + + return loss_log + + def get_subgoal_predictions(self, obs_dict, goal_dict=None): + """ + Takes a batch of observations and predicts a batch of subgoals. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + subgoal prediction (dict): name -> Tensor [batch_size, ...] + """ + return self.nets["goal_network"](obs=obs_dict, goal=goal_dict) + + def sample_subgoals(self, obs_dict, goal_dict=None, num_samples=1): + """ + Sample @num_samples subgoals from the network per observation. + Since this class implements a deterministic subgoal prediction, + this function returns identical subgoals for each input observation. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + subgoals (dict): name -> Tensor [batch_size, num_samples, ...] + """ + + # stack observations to get all samples in one forward pass + obs_tiled = ObsUtils.repeat_and_stack_observation(obs_dict, n=num_samples) + goal_tiled = None + if goal_dict is not None: + goal_tiled = ObsUtils.repeat_and_stack_observation(goal_dict, n=num_samples) + + # [batch_size * num_samples, ...] + goals = self.get_subgoal_predictions(obs_dict=obs_tiled, goal_dict=goal_tiled) + # reshape to [batch_size, num_samples, ...] + return TensorUtils.reshape_dimensions(goals, begin_axis=0, end_axis=0, target_dims=(-1, num_samples)) + + def get_action(self, obs_dict, goal_dict=None): + """ + Get policy action outputs. Assumes one input observation (first dimension should be 1). + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + action (torch.Tensor): action tensor + """ + raise Exception("Rollouts are not supported by GL") + + +class GL_VAE(GL): + """ + Implements goal prediction via VAE. + """ + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + """ + self.nets = nn.ModuleDict() + + self.nets["goal_network"] = VAENets.VAE( + input_shapes=self.subgoal_shapes, + output_shapes=self.subgoal_shapes, + condition_shapes=self.obs_shapes, + goal_shapes=self.goal_shapes, + device=self.device, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + **VAENets.vae_args_from_config(self.algo_config.vae), + ) + + self.nets = self.nets.float().to(self.device) + + def get_actor_goal_for_training_from_processed_batch( + self, + processed_batch, + use_latent_subgoals=False, + use_prior_correction=False, + num_prior_samples=100, + **kwargs, + ): + """ + Modify from superclass to support a @use_latent_subgoals option. + The VAE can optionally return latent subgoals by passing the subgoal + observations in the batch through the encoder. + + Args: + processed_batch (dict): processed batch from @process_batch_for_training + + use_latent_subgoals (bool): if True, condition the actor on latent subgoals + by using the VAE encoder to encode subgoal observations at train-time, + and using the VAE prior to generate latent subgoals at test-time + + use_prior_correction (bool): if True, use a "prior correction" trick to + choose a latent subgoal sampled from the prior that is close to the + latent from the VAE encoder (posterior). This can help with issues at + test-time where the encoder latent distribution might not match + the prior latent distribution. + + num_prior_samples (int): number of VAE prior samples to take and choose among, + if @use_prior_correction is true + + Returns: + actor_subgoals (dict): subgoal observations to condition actor on + """ + + if not use_latent_subgoals: + return processed_batch["target_subgoals"] + + # batch variables + obs = processed_batch["obs"] + subgoals = processed_batch["subgoals"] # full subgoal observations + target_subgoals = processed_batch["target_subgoals"] # targets for network prediction + goal_obs = processed_batch["goal_obs"] + + with torch.no_grad(): + # run VAE forward pass to get samples from posterior for the current observation and subgoal + vae_outputs = self.nets["goal_network"]( + inputs=subgoals, # encoder takes full subgoals + outputs=target_subgoals, # reconstruct target subgoals + goals=goal_obs, + conditions=obs, # condition on observations + ) + posterior_z = vae_outputs["encoder_z"] + latent_subgoals = posterior_z + + if use_prior_correction: + # instead of treating posterior samples as latent subgoals, sample latents from + # the prior and choose the closest one as the latent subgoal + + random_key = list(obs.keys())[0] + batch_size = obs[random_key].shape[0] + + # for each batch member, get @num_prior_samples samples from the prior + obs_tiled = ObsUtils.repeat_and_stack_observation(obs, n=num_prior_samples) + goal_tiled = None + if len(self.goal_shapes) > 0: + goal_tiled = ObsUtils.repeat_and_stack_observation(goal_obs, n=num_prior_samples) + + prior_z_samples = self.nets["goal_network"].sample_prior( + conditions=obs_tiled, + goals=goal_tiled, + ) + + # choose prior samples that are closest to the sampled posterior latents + # note: every posterior sample in the batch has @num_prior_samples corresponding prior samples + + # reshape prior samples to (batch_size, num_samples, latent_dim) + prior_z_samples = prior_z_samples.reshape(batch_size, num_prior_samples, -1) + + # reshape posterior latents to (batch_size, 1, latent_dim) + posterior_z_expanded = posterior_z.unsqueeze(1) + + # compute distances with broadcasting so that each posterior sample + # has distances to all of its prior samples + distances = (prior_z_samples - posterior_z_expanded).pow(2).sum(dim=2) + + # then gather the closest prior sample for each posterior sample + neighbors = torch.argmin(distances, dim=1) + latent_subgoals = prior_z_samples[torch.arange(batch_size).long(), neighbors] + + return { "latent_subgoal" : latent_subgoals } + + def train_on_batch(self, batch, epoch, validate=False): + """ + Training on a single batch of data. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + validate (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + with TorchUtils.maybe_no_grad(no_grad=validate): + info = super(GL, self).train_on_batch(batch, epoch, validate=validate) + + if self.algo_config.vae.prior.use_categorical: + temperature = self.algo_config.vae.prior.categorical_init_temp - epoch * self.algo_config.vae.prior.categorical_temp_anneal_step + temperature = max(temperature, self.algo_config.vae.prior.categorical_min_temp) + self.nets["goal_network"].set_gumbel_temperature(temperature) + + # batch variables + obs = batch["obs"] + subgoals = batch["subgoals"] # full subgoal observations + target_subgoals = batch["target_subgoals"] # targets for network prediction + goal_obs = batch["goal_obs"] + + vae_outputs = self.nets["goal_network"]( + inputs=subgoals, # encoder takes full subgoals + outputs=target_subgoals, # reconstruct target subgoals + goals=goal_obs, + conditions=obs, # condition on observations + ) + recons_loss = vae_outputs["reconstruction_loss"] + kl_loss = vae_outputs["kl_loss"] + goal_loss = recons_loss + self.algo_config.vae.kl_weight * kl_loss + info["recons_loss"] = recons_loss + info["kl_loss"] = kl_loss + info["goal_loss"] = goal_loss + + if not self.algo_config.vae.prior.use_categorical: + with torch.no_grad(): + info["encoder_variance"] = torch.exp(vae_outputs["encoder_params"]["logvar"]) + + # VAE gradient step + if not validate: + goal_grad_norms = TorchUtils.backprop_for_loss( + net=self.nets["goal_network"], + optim=self.optimizers["goal_network"], + loss=goal_loss, + ) + info["goal_grad_norms"] = goal_grad_norms + + return info + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + loss_log = super(GL_VAE, self).log_info(info) + loss_log["Reconstruction_Loss"] = info["recons_loss"].item() + loss_log["KL_Loss"] = info["kl_loss"].item() + if self.algo_config.vae.prior.use_categorical: + loss_log["Gumbel_Temperature"] = self.nets["goal_network"].get_gumbel_temperature() + else: + loss_log["Encoder_Variance"] = info["encoder_variance"].mean().item() + return loss_log + + def get_subgoal_predictions(self, obs_dict, goal_dict=None): + """ + Takes a batch of observations and predicts a batch of subgoals. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + subgoal prediction (dict): name -> Tensor [batch_size, ...] + """ + + if self.global_config.algo.latent_subgoal.enabled: + # latent subgoals from sampling prior + latent_subgoals = self.nets["goal_network"].sample_prior( + conditions=obs_dict, + goals=goal_dict, + ) + + return OrderedDict(latent_subgoal=latent_subgoals) + + # sample a single goal from the VAE + goals = self.sample_subgoals(obs_dict=obs_dict, goal_dict=goal_dict, num_samples=1) + return { k : goals[k][:, 0, ...] for k in goals } + + def sample_subgoals(self, obs_dict, goal_dict=None, num_samples=1): + """ + Sample @num_samples subgoals from the VAE per observation. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + subgoals (dict): name -> Tensor [batch_size, num_samples, ...] + """ + + # stack observations to get all samples in one forward pass + obs_tiled = ObsUtils.repeat_and_stack_observation(obs_dict, n=num_samples) + goal_tiled = None + if goal_dict is not None: + goal_tiled = ObsUtils.repeat_and_stack_observation(goal_dict, n=num_samples) + + # VAE decode expects number of samples explicitly + mod = list(obs_tiled.keys())[0] + n = obs_tiled[mod].shape[0] + # [batch_size * num_samples, ...] + goals = self.nets["goal_network"].decode(n=n, conditions=obs_tiled, goals=goal_tiled) + # reshape to [batch_size, num_samples, ...] + return TensorUtils.reshape_dimensions(goals, begin_axis=0, end_axis=0, target_dims=(-1, num_samples)) + + +class ValuePlanner(PlannerAlgo, ValueAlgo): + """ + Base class for all algorithms that are used for planning subgoals + based on (1) a @PlannerAlgo that is used to sample candidate subgoals + and (2) a @ValueAlgo that is used to select one of the subgoals. + """ + def __init__( + self, + planner_algo_class, + value_algo_class, + algo_config, + obs_config, + global_config, + obs_key_shapes, + ac_dim, + device, + + ): + """ + Args: + planner_algo_class (Algo class): algo class for the planner + + value_algo_class (Algo class): algo class for the value network + + algo_config (Config object): instance of Config corresponding to the algo section + of the config + + obs_config (Config object): instance of Config corresponding to the observation + section of the config + + global_config (Config object); global config + + obs_key_shapes (OrderedDict): dictionary that maps input/output observation keys to shapes + + ac_dim (int): action dimension + + device: torch device + """ + self.algo_config = algo_config + self.obs_config = obs_config + self.global_config = global_config + + self.ac_dim = ac_dim + self.device = device + + self.planner = planner_algo_class( + algo_config=algo_config.planner, + obs_config=obs_config.planner, + global_config=global_config, + obs_key_shapes=obs_key_shapes, + ac_dim=ac_dim, + device=device + ) + + self.value_net = value_algo_class( + algo_config=algo_config.value, + obs_config=obs_config.value, + global_config=global_config, + obs_key_shapes=obs_key_shapes, + ac_dim=ac_dim, + device=device + ) + + self.subgoal_shapes = self.planner.subgoal_shapes + + def process_batch_for_training(self, batch): + """ + Processes input batch from a data loader to filter out + relevant information and prepare the batch for training. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader + + Returns: + input_batch (dict): processed and filtered batch that + will be used for training + """ + input_batch = dict() + + input_batch["planner"] = self.planner.process_batch_for_training(batch) + input_batch["value_net"] = self.value_net.process_batch_for_training(batch) + + # we move to device first before float conversion because image observation modalities will be uint8 - + # this minimizes the amount of data transferred to GPU + return TensorUtils.to_float(TensorUtils.to_device(input_batch, self.device)) + + def train_on_batch(self, batch, epoch, validate=False): + """ + Training on a single batch of data. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + validate (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + if validate: + assert not self.planner.nets.training + assert not self.value_net.nets.training + + info = dict(planner=dict(), value_net=dict()) + + # train planner + info["planner"].update(self.planner.train_on_batch(batch["planner"], epoch, validate=validate)) + + # train value network + info["value_net"].update(self.value_net.train_on_batch(batch["value_net"], epoch, validate=validate)) + + return info + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + loss = 0. + + # planner + planner_log = self.planner.log_info(info["planner"]) + planner_log = dict(("Planner/" + k, v) for k, v in planner_log.items()) + loss += planner_log["Planner/Loss"] + + # value network + value_net_log = self.value_net.log_info(info["value_net"]) + value_net_log = dict(("ValueNetwork/" + k, v) for k, v in value_net_log.items()) + loss += value_net_log["ValueNetwork/Loss"] + planner_log.update(value_net_log) + + planner_log["Loss"] = loss + return planner_log + + def on_epoch_end(self, epoch): + """ + Called at the end of each epoch. + """ + self.planner.on_epoch_end(epoch) + self.value_net.on_epoch_end(epoch) + + def set_eval(self): + """ + Prepare networks for evaluation. + """ + self.planner.set_eval() + self.value_net.set_eval() + + def set_train(self): + """ + Prepare networks for training. + """ + self.planner.set_train() + self.value_net.set_train() + + def serialize(self): + """ + Get dictionary of current model parameters. + """ + return dict( + planner=self.planner.serialize(), + value_net=self.value_net.serialize(), + ) + + def deserialize(self, model_dict): + """ + Load model from a checkpoint. + + Args: + model_dict (dict): a dictionary saved by self.serialize() that contains + the same keys as @self.network_classes + """ + self.planner.deserialize(model_dict["planner"]) + self.value_net.deserialize(model_dict["value_net"]) + + def reset(self): + """ + Reset algo state to prepare for environment rollouts. + """ + self.planner.reset() + self.value_net.reset() + + def __repr__(self): + """ + Pretty print algorithm and network description. + """ + msg = str(self.__class__.__name__) + import textwrap + return msg + "Planner:\n" + textwrap.indent(self.planner.__repr__(), ' ') + \ + "\n\nValue Network:\n" + textwrap.indent(self.value_net.__repr__(), ' ') + + def get_subgoal_predictions(self, obs_dict, goal_dict=None): + """ + Takes a batch of observations and predicts a batch of subgoals. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + subgoal prediction (dict): name -> Tensor [batch_size, ...] + """ + + num_samples = self.algo_config.num_samples + + # sample subgoals from the planner (shape: [batch_size, num_samples, ...]) + subgoals = self.sample_subgoals(obs_dict=obs_dict, goal_dict=goal_dict, num_samples=num_samples) + + # stack subgoals to get all values in one forward pass (shape [batch_size * num_samples, ...]) + k = list(obs_dict.keys())[0] + bsize = obs_dict[k].shape[0] + subgoals_tiled = TensorUtils.reshape_dimensions(subgoals, begin_axis=0, end_axis=1, target_dims=(bsize * num_samples,)) + + # also repeat goals if necessary + goal_tiled = None + if len(self.planner.goal_shapes) > 0: + goal_tiled = ObsUtils.repeat_and_stack_observation(goal_dict, n=num_samples) + + # evaluate the value of each subgoal + subgoal_values = self.value_net.get_state_value(obs_dict=subgoals_tiled, goal_dict=goal_tiled).reshape(-1, num_samples) + + # pick the best subgoal + best_index = torch.argmax(subgoal_values, dim=1) + best_subgoal = {k: subgoals[k][torch.arange(bsize), best_index] for k in subgoals} + return best_subgoal + + def sample_subgoals(self, obs_dict, goal_dict, num_samples=1): + """ + Sample @num_samples subgoals from the planner algo per observation. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + subgoals (dict): name -> Tensor [batch_size, num_samples, ...] + """ + return self.planner.sample_subgoals(obs_dict=obs_dict, goal_dict=goal_dict, num_samples=num_samples) + + def get_state_value(self, obs_dict, goal_dict=None): + """ + Get state value outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + value (torch.Tensor): value tensor + """ + return self.value_net.get_state_value(obs_dict=obs_dict, goal_dict=goal_dict) + + def get_state_action_value(self, obs_dict, actions, goal_dict=None): + """ + Get state-action value outputs. + + Args: + obs_dict (dict): current observation + actions (torch.Tensor): action + goal_dict (dict): (optional) goal + + Returns: + value (torch.Tensor): value tensor + """ + return self.value_net.get_state_action_value(obs_dict=obs_dict, actions=actions, goal_dict=goal_dict) diff --git a/code_src/rise_robomimic/robomimic/algo/hbc.py b/code_src/rise_robomimic/robomimic/algo/hbc.py new file mode 100644 index 0000000000000000000000000000000000000000..543b1fbcf4ced11b9628d506b1972f1123a357b6 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/hbc.py @@ -0,0 +1,344 @@ +""" +Implementation of Hierarchical Behavioral Cloning, where +a planner model outputs subgoals (future observations), and +an actor model is conditioned on the subgoals to try and +reach them. Largely based on the Generalization Through Imitation (GTI) +paper (see https://arxiv.org/abs/2003.06085). +""" +import textwrap +import numpy as np +from collections import OrderedDict +from copy import deepcopy + +import torch + +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.obs_utils as ObsUtils +from robomimic.config.config import Config +from robomimic.algo import register_algo_factory_func, algo_name_to_factory_func, HierarchicalAlgo, GL_VAE + + +@register_algo_factory_func("hbc") +def algo_config_to_class(algo_config): + """ + Maps algo config to the HBC algo class to instantiate, along with additional algo kwargs. + + Args: + algo_config (Config instance): algo config + + Returns: + algo_class: subclass of Algo + algo_kwargs (dict): dictionary of additional kwargs to pass to algorithm + """ + pol_cls, _ = algo_name_to_factory_func("bc")(algo_config.actor) + plan_cls, _ = algo_name_to_factory_func("gl")(algo_config.planner) + return HBC, dict(policy_algo_class=pol_cls, planner_algo_class=plan_cls) + + +class HBC(HierarchicalAlgo): + """ + Default HBC training, largely based on https://arxiv.org/abs/2003.06085 + """ + def __init__( + self, + planner_algo_class, + policy_algo_class, + algo_config, + obs_config, + global_config, + obs_key_shapes, + ac_dim, + device, + ): + """ + Args: + planner_algo_class (Algo class): algo class for the planner + + policy_algo_class (Algo class): algo class for the policy + + algo_config (Config object): instance of Config corresponding to the algo section + of the config + + obs_config (Config object): instance of Config corresponding to the observation + section of the config + + global_config (Config object): global training config + + obs_key_shapes (dict): dictionary that maps input/output observation keys to shapes + + ac_dim (int): action dimension + + device: torch device + """ + self.algo_config = algo_config + self.obs_config = obs_config + self.global_config = global_config + + self.ac_dim = ac_dim + self.device = device + + self._subgoal_step_count = 0 # current step count for deciding when to update subgoal + self._current_subgoal = None # latest subgoal + self._subgoal_update_interval = self.algo_config.subgoal_update_interval # subgoal update frequency + self._subgoal_horizon = self.algo_config.planner.subgoal_horizon + self._actor_horizon = self.algo_config.actor.rnn.horizon + + self._algo_mode = self.algo_config.mode + assert self._algo_mode in ["separate", "cascade"] + + self.planner = planner_algo_class( + algo_config=algo_config.planner, + obs_config=obs_config.planner, + global_config=global_config, + obs_key_shapes=obs_key_shapes, + ac_dim=ac_dim, + device=device + ) + + # goal-conditional actor follows goals set by the planner + self.actor_goal_shapes = self.planner.subgoal_shapes + if self.algo_config.latent_subgoal.enabled: + assert planner_algo_class == GL_VAE # only VAE supported for now + self.actor_goal_shapes = OrderedDict(latent_subgoal=(self.planner.algo_config.vae.latent_dim,)) + + # only for the actor: override goal modalities and shapes to match the subgoal set by the planner + actor_obs_key_shapes = deepcopy(obs_key_shapes) + # make sure we are not modifying existing observation key shapes + for k in self.actor_goal_shapes: + if k in actor_obs_key_shapes: + assert actor_obs_key_shapes[k] == self.actor_goal_shapes[k] + actor_obs_key_shapes.update(self.actor_goal_shapes) + + goal_obs_keys = {obs_modality: [] for obs_modality in ObsUtils.OBS_MODALITY_CLASSES.keys()} + for k in self.actor_goal_shapes.keys(): + goal_obs_keys[ObsUtils.OBS_KEYS_TO_MODALITIES[k]].append(k) + + actor_obs_config = deepcopy(obs_config.actor) + with actor_obs_config.unlocked(): + actor_obs_config["goal"] = Config(**goal_obs_keys) + + self.actor = policy_algo_class( + algo_config=algo_config.actor, + obs_config=actor_obs_config, + global_config=global_config, + obs_key_shapes=actor_obs_key_shapes, + ac_dim=ac_dim, + device=device, + ) + + def process_batch_for_training(self, batch): + """ + Processes input batch from a data loader to filter out + relevant information and prepare the batch for training. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader + + Returns: + input_batch (dict): processed and filtered batch that + will be used for training + """ + input_batch = dict() + + input_batch["planner"] = self.planner.process_batch_for_training(batch) + input_batch["actor"] = self.actor.process_batch_for_training(batch) + + if self.algo_config.actor_use_random_subgoals: + # optionally use randomly sampled step between [1, seq_length] as policy goal + policy_subgoal_indices = torch.randint( + low=0, high=self.global_config.train.seq_length, size=(batch["actions"].shape[0],)) + goal_obs = TensorUtils.gather_sequence(batch["next_obs"], policy_subgoal_indices) + goal_obs = TensorUtils.to_float(TensorUtils.to_device(goal_obs, self.device)) + input_batch["actor"]["goal_obs"] = \ + self.planner.get_actor_goal_for_training_from_processed_batch( + goal_obs, + use_latent_subgoals=self.algo_config.latent_subgoal.enabled, + use_prior_correction=self.algo_config.latent_subgoal.prior_correction.enabled, + num_prior_samples=self.algo_config.latent_subgoal.prior_correction.num_samples, + ) + else: + # otherwise, use planner subgoal target as goal for the policy + input_batch["actor"]["goal_obs"] = \ + self.planner.get_actor_goal_for_training_from_processed_batch( + input_batch["planner"], + use_latent_subgoals=self.algo_config.latent_subgoal.enabled, + use_prior_correction=self.algo_config.latent_subgoal.prior_correction.enabled, + num_prior_samples=self.algo_config.latent_subgoal.prior_correction.num_samples, + ) + + # we move to device first before float conversion because image observation modalities will be uint8 - + # this minimizes the amount of data transferred to GPU + return TensorUtils.to_float(TensorUtils.to_device(input_batch, self.device)) + + def train_on_batch(self, batch, epoch, validate=False): + """ + Training on a single batch of data. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + validate (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + info = dict(planner=dict(), actor=dict()) + # train planner + info["planner"].update(self.planner.train_on_batch(batch["planner"], epoch, validate=validate)) + + # train actor + if self._algo_mode == "separate": + # train low-level actor by getting subgoals from the dataset + info["actor"].update(self.actor.train_on_batch(batch["actor"], epoch, validate=validate)) + + elif self._algo_mode == "cascade": + # get predictions from the planner + with torch.no_grad(): + batch["actor"]["goal_obs"] = self.planner.get_subgoal_predictions( + obs_dict=batch["planner"]["obs"], goal_dict=batch["planner"]["goal_obs"]) + + # train actor with the predicted goal + info["actor"].update(self.actor.train_on_batch(batch["actor"], epoch, validate=validate)) + + else: + raise NotImplementedError("algo mode {} is not implemented".format(self._algo_mode)) + + return info + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + planner_log = dict() + actor_log = dict() + loss = 0. + + planner_log = self.planner.log_info(info["planner"]) + planner_log = dict(("Planner/" + k, v) for k, v in planner_log.items()) + loss += planner_log["Planner/Loss"] + + actor_log = self.actor.log_info(info["actor"]) + actor_log = dict(("Actor/" + k, v) for k, v in actor_log.items()) + loss += actor_log["Actor/Loss"] + + planner_log.update(actor_log) + planner_log["Loss"] = loss + return planner_log + + def on_epoch_end(self, epoch): + """ + Called at the end of each epoch. + """ + self.planner.on_epoch_end(epoch) + self.actor.on_epoch_end(epoch) + + def set_eval(self): + """ + Prepare networks for evaluation. + """ + self.planner.set_eval() + self.actor.set_eval() + + def set_train(self): + """ + Prepare networks for training. + """ + self.planner.set_train() + self.actor.set_train() + + def serialize(self): + """ + Get dictionary of current model parameters. + """ + return dict( + planner=self.planner.serialize(), + actor=self.actor.serialize(), + ) + + def deserialize(self, model_dict): + """ + Load model from a checkpoint. + + Args: + model_dict (dict): a dictionary saved by self.serialize() that contains + the same keys as @self.network_classes + """ + self.actor.deserialize(model_dict["actor"]) + self.planner.deserialize(model_dict["planner"]) + + @property + def current_subgoal(self): + """ + Return the current subgoal (at rollout time) with shape (batch, ...) + """ + return { k : self._current_subgoal[k].clone() for k in self._current_subgoal } + + @current_subgoal.setter + def current_subgoal(self, sg): + """ + Sets the current subgoal being used by the actor. + """ + for k, v in sg.items(): + if not self.algo_config.latent_subgoal.enabled: + # subgoal should only match subgoal shapes if not using latent subgoals + assert list(v.shape[1:]) == list(self.planner.subgoal_shapes[k]) + # subgoal shapes should always match actor goal shapes + assert list(v.shape[1:]) == list(self.actor_goal_shapes[k]) + self._current_subgoal = { k : sg[k].clone() for k in sg } + + def get_action(self, obs_dict, goal_dict=None): + """ + Get policy action outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + action (torch.Tensor): action tensor + """ + if self._current_subgoal is None or self._subgoal_step_count % self._subgoal_update_interval == 0: + # update current subgoal + self.current_subgoal = self.planner.get_subgoal_predictions(obs_dict=obs_dict, goal_dict=goal_dict) + + action = self.actor.get_action(obs_dict=obs_dict, goal_dict=self.current_subgoal) + self._subgoal_step_count += 1 + return action + + def reset(self): + """ + Reset algo state to prepare for environment rollouts. + """ + self._current_subgoal = None + self._subgoal_step_count = 0 + self.planner.reset() + self.actor.reset() + + def __repr__(self): + """ + Pretty print algorithm and network description. + """ + msg = str(self.__class__.__name__) + msg += "(subgoal_horizon={}, actor_horizon={}, subgoal_update_interval={}, mode={}, " \ + "actor_use_random_subgoals={})\n".format( + self._subgoal_horizon, + self._actor_horizon, + self._subgoal_update_interval, + self._algo_mode, + self.algo_config.actor_use_random_subgoals + ) + return msg + "Planner:\n" + textwrap.indent(self.planner.__repr__(), ' ') + \ + "\n\nPolicy:\n" + textwrap.indent(self.actor.__repr__(), ' ') diff --git a/code_src/rise_robomimic/robomimic/algo/idql.py b/code_src/rise_robomimic/robomimic/algo/idql.py new file mode 100644 index 0000000000000000000000000000000000000000..d98d10bde34cf5fd96ae90819fb15873b66febef --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/idql.py @@ -0,0 +1,1214 @@ +""" +Implementation of Implicit Q-Learning (IQL). +Based off of https://github.com/rail-berkeley/rlkit/blob/master/rlkit/torch/sac/iql_trainer.py. +(Paper - https://arxiv.org/abs/2110.06169). +""" +import numpy as np +import copy +from collections import OrderedDict + +import math +import torch +import torch.nn as nn +import torch.nn.functional as F + +import robomimic.models.policy_nets as PolicyNets +import robomimic.models.value_nets as ValueNets +import robomimic.utils.obs_utils as ObsUtils +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.torch_utils as TorchUtils +import robomimic.models.obs_nets as ObsNets + +from typing import Callable, Union +from packaging.version import parse as parse_version +from enum import Enum +from diffusers.schedulers.scheduling_ddpm import DDPMScheduler +from diffusers.schedulers.scheduling_ddim import DDIMScheduler +from diffusers.training_utils import EMAModel + +from robomimic.algo import register_algo_factory_func, ValueAlgo, PolicyAlgo +from robomimic.algo.rsm_planner import RSMPlannerMixin + +from diffusion_policy.model.diffusion.mask_generator import LowdimMaskGenerator + + +class MultiStepMethod(Enum): + REPEAT = 'repeat' + ONE_STEP = 'one_step' + MULTI_STEP = 'multi_step' + +@register_algo_factory_func("idql") +def algo_config_to_class(algo_config): + """ + Maps algo config to the IQL algo class to instantiate, along with additional algo kwargs. + + Args: + algo_config (Config instance): algo config + + Returns: + algo_class: subclass of Algo + algo_kwargs (dict): dictionary of additional kwargs to pass to algorithm + """ + return IDQL, {} + + +class IDQL(RSMPlannerMixin, PolicyAlgo, ValueAlgo): + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + + Networks for this algo: critic (potentially ensemble), actor, value function + """ + try: + self.multi_step_method = MultiStepMethod(self.algo_config.multi_step_method) + except RuntimeError: + self.multi_step_method = MultiStepMethod.ONE_STEP + + # Create nets + self.nets = nn.ModuleDict() + + observation_group_shapes = OrderedDict() + observation_group_shapes["obs"] = OrderedDict(self.obs_shapes) + encoder_kwargs = ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder) + + try: + lipschitz = self.algo_config.lipschitz + except: + lipschitz = False + obs_encoder = ObsNets.ObservationGroupEncoder( + observation_group_shapes=observation_group_shapes, + encoder_kwargs=encoder_kwargs, + stochastic=self.algo_config.bottleneck_policy, + spectral_norm=self.algo_config.spectral_norm_policy or lipschitz, + ) + # IMPORTANT! + # replace all BatchNorm with GroupNorm to work with EMA + # performance will tank if you forget to do this! + obs_encoder = replace_bn_with_gn(obs_encoder) + + obs_dim = obs_encoder.output_shape()[0] + + # create network object + noise_pred_net = ConditionalUnet1D( + input_dim=self.ac_dim, + down_dims=self.algo_config.unet.down_dims, + diffusion_step_embed_dim=self.algo_config.unet.diffusion_step_embed_dim, + global_cond_dim=obs_dim*self.algo_config.horizon.observation_horizon + ) + + # the final arch has 2 parts + self.nets = nn.ModuleDict({ + 'policy': nn.ModuleDict({ + 'obs_encoder': obs_encoder, + 'noise_pred_net': noise_pred_net + }) + }) + + try: + self.action_augmentation = self.algo_config.action_augmentation + except RuntimeError: + self.action_augmentation = False + + # self.mask_generator = LowdimMaskGenerator( + # action_dim=self.ac_dim, + # obs_dim=0 if (obs_as_cond) else obs_feature_dim, + # max_n_obs_steps=self.algo_config.horizon.observation_horizon, + # fix_obs_steps=True, + # action_visible=False + # ) + + # setup noise scheduler + noise_scheduler = None + if self.algo_config.ddpm.enabled: + noise_scheduler = DDPMScheduler( + num_train_timesteps=self.algo_config.ddpm.num_train_timesteps, + beta_schedule=self.algo_config.ddpm.beta_schedule, + clip_sample=self.algo_config.ddpm.clip_sample, + prediction_type=self.algo_config.ddpm.prediction_type + ) + elif self.algo_config.ddim.enabled: + noise_scheduler = DDIMScheduler( + num_train_timesteps=self.algo_config.ddim.num_train_timesteps, + beta_schedule=self.algo_config.ddim.beta_schedule, + clip_sample=self.algo_config.ddim.clip_sample, + set_alpha_to_one=self.algo_config.ddim.set_alpha_to_one, + steps_offset=self.algo_config.ddim.steps_offset, + prediction_type=self.algo_config.ddim.prediction_type + ) + else: + raise RuntimeError() + + try: + late_fusion_key = self.algo_config.critic.late_fusion_key + except: + late_fusion_key = None + try: + late_fusion_layer_index = self.algo_config.critic.late_fusion_layer_index + except: + late_fusion_layer_index = 1 + try: + obs_multiplier_key = self.algo_config.critic.obs_multiplier_key + except: + obs_multiplier_key = None + try: + obs_multiplier = self.algo_config.critic.obs_multiplier + except: + obs_multiplier = 1 + + # Critics + self.nets["critic"] = nn.ModuleList() + self.nets["critic_target"] = nn.ModuleList() + for _ in range(self.algo_config.critic.ensemble.n): + for net_list in (self.nets["critic"], self.nets["critic_target"]): + critic = ValueNets.ActionValueNetwork( + obs_shapes=self.obs_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.critic.layer_dims, + goal_shapes=self.goal_shapes, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + stochastic_encoder=self.algo_config.bottleneck_value, + spectral_norm=self.algo_config.spectral_norm_value, + late_fusion_key=late_fusion_key, + late_fusion_layer_index=late_fusion_layer_index, + obs_multiplier_key=obs_multiplier_key, + obs_multiplier=obs_multiplier, + ) + net_list.append(critic) + + # Value function network + self.nets["vf"] = ValueNets.ValueNetwork( + obs_shapes=self.obs_shapes, + mlp_layer_dims=self.algo_config.critic.layer_dims, + goal_shapes=self.goal_shapes, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + stochastic_encoder=False, + spectral_norm=False, + late_fusion_key=late_fusion_key, + late_fusion_layer_index=late_fusion_layer_index, + obs_multiplier_key=obs_multiplier_key, + obs_multiplier=obs_multiplier, + ) + + try: + if self.algo_config.lipschitz_slack: + self.nets['policy']['slack_var_net'] = ValueNets.ActionValueNetwork = ValueNets.ActionValueNetwork( + obs_shapes=self.obs_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.critic.layer_dims, + goal_shapes=self.goal_shapes, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + stochastic_encoder=False, + spectral_norm=False, + ) + except: + pass + + # Send networks to appropriate device + self.nets = self.nets.float().to(self.device) + + # setup EMA + ema = None + if self.algo_config.ema.enabled: + ema = EMAModel(parameters=self.nets.parameters(), power=self.algo_config.ema.power, use_ema_warmup=True) + + self.noise_scheduler = noise_scheduler + self.ema = ema + self.action_check_done = False + + # sync target networks at beginning of training + with torch.no_grad(): + for critic, critic_target in zip(self.nets["critic"], self.nets["critic_target"]): + TorchUtils.hard_update( + source=critic, + target=critic_target, + ) + + def _flag(self, name, default=False): + """rsm_rise gen_q#265: read an opt-in algo flag that older checkpoints' (locked) configs do not carry. + robomimic's Config raises RuntimeError, not AttributeError, for a missing key on a locked config.""" + try: + return self.algo_config[name] if name in self.algo_config else default + except Exception: + return default + + def process_batch_for_training(self, batch): + """ + Processes input batch from a data loader to filter out relevant info and prepare the batch for training. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader + + Returns: + input_batch (dict): processed and filtered batch that + will be used for training + """ + + input_batch = dict() + + To = self.algo_config.horizon.observation_horizon + Tp = self.algo_config.horizon.prediction_horizon + + input_batch["obs"] = {k: batch["obs"][k][:, :(To + Tp - 1), :] for k in batch["obs"]} + # TODO: check this + if not self.algo_config.use_bc: + input_batch["next_obs"] = {k: batch["next_obs"][k][:, :(To + Tp - 1), :] for k in batch["next_obs"]} + input_batch["goal_obs"] = batch.get("goal_obs", None) # goals may not be present + input_batch["actions"] = batch["actions"][:, (To - 1):(Tp + To - 1), :] + input_batch["dones"] = batch["dones"][:, (To - 1):(Tp + To - 1)] + input_batch["rewards"] = batch["rewards"][:, (To - 1):(Tp + To - 1)] + if self.algo_config.lipschitz and not self.algo_config.lipschitz_slack: + input_batch["entropy"] = batch["entropy"][:, (To - 1):(Tp + To - 1)] + + return TensorUtils.to_device(TensorUtils.to_float(input_batch), self.device) + + def train_on_batch(self, batch, epoch, validate=False): + """ + Training on a single batch of data. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + validate (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + Tp = self.algo_config.horizon.prediction_horizon + info = OrderedDict() + + actor_freeze_until_epoch = self.algo_config.optim_params.policy.freeze_until_epoch + if actor_freeze_until_epoch is None: + actor_freeze_until_epoch = -1 + using_augmented = self.action_augmentation and epoch % 2 == 0 + # rsm_rise gen_q#265 wave 2 (opt-in, default False = released): `algo.critic_on_augmented` lets Q and V + # train on the kNN-augmented rows too. An augmented row is (s_play, a_expert_nn, r_expert, done_expert, + # next_obs = the PLAY frame's own next state). ASSUMPTION: within the augmentation radius + # (train.distance_threshold) the play frame's next state stands in for where the expert action would + # have led, so the one-step target r_expert + gamma * V(s'_play) is a valid (if slightly biased) + # bootstrap. This is the ONLY source of action-contrastive pairs under a per-file provenance reward + # (same state, expert vs play action, different reward); without it Q(s,a) collapses to V(s) + # (status/critic_diag_*.json: within-state Q spread 0.02-0.35 vs 2-40 across states). + critic_skip = using_augmented and not self._flag("critic_on_augmented") + # rsm_rise BASE_TOPUP (gen_q#287) FAST CRITIC PATH, 2026-09-26. See idql_config.py for why these + # two flags exist. `critic_skip_even_epochs` reproduces the released critic SCHEDULE (updates on + # odd epochs only, because the released aug-ON recipe skips the augmented even epochs) on a run + # whose augmentation is off, so a precomputed-feature run makes the SAME number of critic updates + # (250k) instead of twice as many. `critic_only` removes the diffusion actor from the step. + if self._flag("critic_skip_even_epochs") and epoch % 2 == 0: + critic_skip = True + critic_only = self._flag("critic_only") + + # Set the correct context for this training step + with TorchUtils.maybe_no_grad(no_grad=validate): + # Always run super call first + info = super().train_on_batch(batch, epoch, validate=validate) + + # if self.multi_step_method == MultiStepMethod.REPEAT: + # q_preds = [] + # v_preds = [] + # for i in range(Tp): + # # Compute loss for critic(s) + # if not self.algo_config.use_bc: + # critic_losses, vf_loss, critic_info = self._compute_critic_loss(batch, i) + # q_preds.append(critic_info["vf/q_pred"]) + # v_preds.append(critic_info["vf/v_pred"]) + + # if not validate: + # # Critic update + # self._update_critic(critic_losses, vf_loss) + + # # Compute loss for actor + # actor_loss, actor_info = self._compute_actor_loss(batch, q_preds, v_preds) + + # if not validate and epoch >= actor_freeze_until_epoch: + # # Actor update + # self._update_actor(actor_loss) + if self.multi_step_method == MultiStepMethod.ONE_STEP: + + # don't update critic if using augmented data b/c the next obs is wrong + + # Compute loss for critic(s) + if not self.algo_config.use_bc and not critic_skip: + critic_losses, vf_loss, critic_info = self._compute_critic_loss(batch) + q_pred = critic_info["vf/q_pred"] + v_pred = critic_info["vf/v_pred"] + else: + q_pred = None + v_pred = None + + # Compute loss for actor + if critic_only: + actor_loss, actor_info = None, OrderedDict() + else: + actor_loss, actor_info = self._compute_actor_loss(batch, q_pred, v_pred) + + if not validate: + # Critic update + if not self.algo_config.use_bc and not critic_skip: + self._update_critic(critic_losses, vf_loss) + + # Actor update + if not critic_only and epoch >= actor_freeze_until_epoch: + self._update_actor(actor_loss) + actor_info["actor/policy_grad_norm"] = torch.tensor(self._last_policy_grad_norm) + # rsm_rise: advantage stats (the released actor loss is NOT advantage-weighted; logged for monitoring only) + if q_pred is not None and v_pred is not None: + actor_info["actor/adv"] = (q_pred - v_pred).detach() + else: + raise NotImplementedError + + # Update info + info.update(actor_info) + if not self.algo_config.use_bc and not critic_skip: + info.update(critic_info) + + # Return stats + return info + + def compute_updated_actions(self, batch): + To = self.algo_config.horizon.observation_horizon + Tp = self.algo_config.horizon.prediction_horizon + B = batch['actions'].shape[0] + + raise NotImplementedError + + def _compute_critic_loss(self, batch, i=0): + """ + Helper function for computing Q and V losses. Called by @train_on_batch + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + i (int): timestep + + Returns: + critic_losses (list): list of critic (Q function) losses + vf_loss (torch.Tensor): value function loss + info (dict): dictionary of Q / V predictions and losses + """ + info = OrderedDict() + To = self.algo_config.horizon.observation_horizon + Tp = self.algo_config.horizon.prediction_horizon + + # get batch values + obs = {k: batch["obs"][k][:, To - 1 + i, :] for k in batch["obs"]} + actions = batch["actions"][:, i, :] + next_obs = {k: batch["next_obs"][k][:, To - 1 + i, :] for k in batch["next_obs"]} + goal_obs = batch["goal_obs"] + rewards = torch.unsqueeze(batch["rewards"][:, i], 1) + dones = torch.unsqueeze(batch["dones"][:, i], 1) + + # Q predictions + pred_qs = [critic(obs_dict=obs, acts=actions, goal_dict=goal_obs) + for critic in self.nets["critic"]] + + info["critic/critic1_pred"] = pred_qs[0].mean() + + # Q target values + target_vf_pred = self.nets["vf"](obs_dict=next_obs, goal_dict=goal_obs).detach() + q_target = rewards + (1. - dones) * self.algo_config.discount * target_vf_pred + q_target = q_target.detach() + + # Q losses + critic_losses = [] + td_loss_fcn = nn.SmoothL1Loss() if self.algo_config.critic.use_huber else nn.MSELoss() + for (i, q_pred) in enumerate(pred_qs): + # Calculate td error loss + td_loss = td_loss_fcn(q_pred, q_target) + info[f"critic/critic{i+1}_loss"] = td_loss + + if self.algo_config.bottleneck_value: + # compute KL divergence between encoder distribution and standard normal + mean = self.nets["critic"][i].nets["encoder"].nets['obs'].computed_mean + logvar = self.nets["critic"][i].nets["encoder"].nets['obs'].computed_logvar + + # KL divergence between N(mean, std) and N(0, 1) + kl_div = -0.5 * torch.sum(1 + logvar - mean.pow(2) - logvar.exp(), dim=1).mean() + + # add KL term to critic loss with weight + td_loss = td_loss + self.algo_config.q_bottleneck_beta * kl_div + info[f"critic/critic{i+1}_kl_div"] = kl_div + elif self.algo_config.spectral_norm_value: + spectral_norm = self.nets["critic"][i].nets["encoder"].nets['obs'].spectral_norm + td_loss = td_loss + self.algo_config.q_bottleneck_beta * spectral_norm + info[f"critic/critic{i+1}_spectral_norm"] = spectral_norm + + critic_losses.append(td_loss) + + # V predictions + pred_qs = [critic(obs_dict=obs, acts=actions, goal_dict=goal_obs) + for critic in self.nets["critic_target"]] + q_pred, _ = torch.cat(pred_qs, dim=1).min(dim=1, keepdim=True) + q_pred = q_pred.detach() + vf_pred = self.nets["vf"](obs_dict=obs, goal_dict=goal_obs) + + # V losses: expectile regression. see section 4.1 in https://arxiv.org/pdf/2110.06169.pdf + vf_err = vf_pred - q_pred + vf_sign = (vf_err > 0).float() + vf_weight = (1 - vf_sign) * self.algo_config.vf_quantile + vf_sign * (1 - self.algo_config.vf_quantile) + vf_loss = (vf_weight * (vf_err ** 2)).mean() + + # update logs for V loss + info["vf/q_pred"] = q_pred + info["vf/v_pred"] = vf_pred + info["vf/v_loss"] = vf_loss + + # Return stats + return critic_losses, vf_loss, info + + def _update_critic(self, critic_losses, vf_loss): + """ + Helper function for updating critic and vf networks. Called by @train_on_batch + + Args: + critic_losses (list): list of critic (Q function) losses + vf_loss (torch.Tensor): value function loss + """ + + # update ensemble of critics + for (critic_loss, critic, critic_target, optimizer) in zip( + critic_losses, self.nets["critic"], self.nets["critic_target"], self.optimizers["critic"] + ): + TorchUtils.backprop_for_loss( + net=critic, + optim=optimizer, + loss=critic_loss, + max_grad_norm=self.algo_config.critic.max_gradient_norm, + retain_graph=False, + ) + + # update target network + with torch.no_grad(): + TorchUtils.soft_update(source=critic, target=critic_target, tau=self.algo_config.target_tau) + + # update V function network + TorchUtils.backprop_for_loss( + net=self.nets["vf"], + optim=self.optimizers["vf"], + loss=vf_loss, + max_grad_norm=self.algo_config.critic.max_gradient_norm, + retain_graph=False, + ) + + def _compute_actor_loss(self, batch, q_pred, v_pred): + """ + Helper function for computing actor loss. Called by @train_on_batch + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + critic_info (dict): dictionary containing Q and V function predictions, + to be used for computing advantage estimates + + Returns: + actor_loss (torch.Tensor): actor loss + info (dict): dictionary of actor losses, log_probs, advantages, and weights + """ + B = batch['actions'].shape[0] + + info = OrderedDict() + actions = batch['actions'] + + To = self.algo_config.horizon.observation_horizon + + # encode obs + inputs = { + 'obs': {k: batch["obs"][k][:, :To, :] for k in batch["obs"]}, + 'goal': batch["goal_obs"] + } + + for k in self.obs_shapes: + # first two dimensions should be [B, T] for inputs + assert inputs['obs'][k].ndim - 2 == len(self.obs_shapes[k]) + + obs_features = TensorUtils.time_distributed(inputs, self.nets['policy']['obs_encoder'], inputs_as_kwargs=True) + assert obs_features.ndim == 3 # [B, T, D] + + obs_cond = obs_features.flatten(start_dim=1) + + # sample noise to add to actions + noise = torch.randn(actions.shape, device=self.device) + + # sample a diffusion iteration for each data point + timesteps = torch.randint( + 0, self.noise_scheduler.config.num_train_timesteps, + (B,), device=self.device + ).long() + + # add noise to the clean actions according to the noise magnitude at each diffusion iteration + # (this is the forward diffusion process) + noisy_actions = self.noise_scheduler.add_noise( + actions, noise, timesteps) + + # # apply conditioning + # noisy_actions[condition_mask] = actions[condition_mask] + # predict the noise residual + noise_pred = self.nets['policy']['noise_pred_net']( + noisy_actions, timesteps, global_cond=obs_cond) + + # L2 loss + bc_loss = F.mse_loss(noise_pred, noise) + + self.ema.step(self.nets['policy'].parameters()) + + info["actor/bc_loss"] = bc_loss.mean() + + # rsm_rise gen_q#265: OPT-IN advantage-weighted regression. The released IDQL actor loss is plain + # diffusion BC (the adv.beta / _get_adv_weights machinery below is never called), so `algo.awr_actor` + # (default False = released behaviour) multiplies the per-sample BC loss by exp((Q-V)/adv.beta) + # (clip_adv_value, final clip at 100, as in _get_adv_weights). Q/V are only available on the + # non-augmented (odd) epochs -- train_on_batch passes None on augmented ones -- so those batches + # fall back to unweighted BC. + if self._flag("awr_actor") and q_pred is not None and v_pred is not None: + adv = (q_pred - v_pred).detach() + weights = self._get_adv_weights(adv.reshape(adv.shape[0], -1)[:, :1]) # (B,) + # bc_loss above is F.mse_loss's batch mean; weight the PER-SAMPLE mean squared noise error + bc_per_sample = F.mse_loss(noise_pred, noise, reduction='none').reshape(noise.shape[0], -1).mean(dim=1) + actor_loss = (bc_per_sample * weights.detach()).mean() + info["adv/adv_weight"] = weights.detach() + else: + actor_loss = (bc_loss).mean() + if self.algo_config.bottleneck_policy: + # compute KL divergence between encoder distribution and standard normal + mean = self.nets['policy']['obs_encoder'].nets['obs'].computed_mean + logvar = self.nets['policy']['obs_encoder'].nets['obs'].computed_logvar + + # KL divergence between N(mean, std) and N(0, 1) + kl_div = -0.5 * torch.sum(1 + logvar - mean.pow(2) - logvar.exp(), dim=1).mean() + + # add KL term to actor loss with weight + actor_loss = actor_loss + self.algo_config.policy_bottleneck_beta * kl_div + info["actor/kl_div"] = kl_div + elif self.algo_config.spectral_norm_policy: + spectral_norm = self.nets['policy']['obs_encoder'].nets['obs'].spectral_norm + actor_loss = actor_loss + self.algo_config.policy_bottleneck_beta * spectral_norm + if self.algo_config.lipschitz: + slack = self.nets['policy']['slack_var_net'](obs_dict=obs_cond, acts=noisy_actions) + weights = torch.nn.Sigmoid()(slack) + avg_slack_size = slack.mean() + actor_loss = weights * actor_loss - self.algo_config.lipschitz_weight * avg_slack_size + info["actor/slack_size"] = avg_slack_size + info["actor/spectral_norm"] = spectral_norm + # elif self.algo_config.lipschitz_denoiser: + # n_samples = 5 + + # obs_cond_extended = torch.repeat_interleave(obs_cond, n_samples, dim=0) + # noisy_actions_extended = torch.repeat_interleave(noisy_actions, n_samples, dim=0) + # obs_cond_noise = torch.randn_like(obs_cond_extended, device=self.device) + # timesteps_extended = torch.randint( + # 0, self.noise_scheduler.config.num_train_timesteps, + # (B*n_samples,), device=self.device + # ).long() + # # enforce lipschitz on the first action only if action chunking + # noise_pred_extended = torch.repeat_interleave(noise_pred, n_samples, dim=0)[:, 0] + # noise_pred_noise = self.nets['policy']['noise_pred_net']( + # noisy_actions_extended, timesteps_extended, global_cond=obs_cond_noise)[:, 0] + # output_diff = torch.linalg.norm(noise_pred_noise - noise_pred_extended, dim=-1) + # noise_magnitude = torch.linalg.norm(obs_cond_noise, dim=-1) + # lipschitz_penalty = torch.relu(output_diff - self.algo_config.lipschitz_constant * noise_magnitude) + # # reshape lipschitz penalty from (B*n_samples, D1, D2, ...) to (B, n_samples, D1, D2, ...) + # lipschitz_penalty = lipschitz_penalty.reshape(B, n_samples, *lipschitz_penalty.shape[1:]) + # # take mean over n_samples dimension + # lipschitz_penalty = lipschitz_penalty.mean(dim=1) + # obs_dict = {k: batch["obs"][k][:, To - 1, :] for k in batch["obs"]} + # actions = batch['actions'][:, 0, :] + # slack = self.nets['policy']['slack_var_net'](obs_dict=obs_dict, acts=actions)[:, 0] + # lipschitz_penalty = slack * lipschitz_penalty + 1 - torch.exp(-0.1 * torch.abs(slack).mean()) + # lipschitz_penalty = self.algo_config.lipschitz_weight * lipschitz_penalty.mean() + + # actor_loss = actor_loss + lipschitz_penalty + + # info["actor/lipschitz_penalty"] = lipschitz_penalty + elif self.algo_config.lipschitz: + n_samples = 5 + + try: + lipschitz_denoiser = self.algo_config.lipschitz_denoiser + except: + lipschitz_denoiser = False + + if lipschitz_denoiser: + obs_cond_extended = torch.repeat_interleave(obs_cond, n_samples, dim=0) + noisy_actions_extended = torch.repeat_interleave(noisy_actions, n_samples, dim=0) + obs_cond_noise = torch.randn_like(obs_cond_extended, device=self.device) + timesteps_extended = torch.randint( + 0, self.noise_scheduler.config.num_train_timesteps, + (B*n_samples,), device=self.device + ).long() + # enforce lipschitz on the first action only if action chunking + noise_pred_extended = torch.repeat_interleave(noise_pred, n_samples, dim=0)[:, 0] + noise_pred_noise = self.nets['policy']['noise_pred_net']( + noisy_actions_extended, timesteps_extended, global_cond=obs_cond_noise)[:, 0] + output_diff = torch.linalg.norm(noise_pred_noise - noise_pred_extended, dim=-1) + noise_magnitude = torch.linalg.norm(obs_cond_noise, dim=-1) + else: + inputs_extended = {k: torch.repeat_interleave(batch["obs"][k][:, To - 1, :], n_samples, dim=0) for k in batch["obs"]} + delta_inputs = {k: torch.randn_like(inputs_extended[k], device=self.device) for k in inputs_extended} + + inputs_noisy = {k: inputs_extended[k] + delta_inputs[k] for k in inputs_extended} + + # shape (n_samples * B, D) + obs_features_noisy = self.nets['policy']['obs_encoder'](obs=inputs_noisy, goal=None) + obs_features_extended = torch.repeat_interleave(obs_features[:, -1, :], n_samples, dim=0) + + # shape (n_samples * B) + output_diff = torch.linalg.norm(obs_features_noisy - obs_features_extended, dim=-1) + noise_magnitude = torch.linalg.norm(torch.concatenate([delta_inputs[k] for k in delta_inputs], dim=-1), dim=-1) + + lipschitz_penalty = output_diff / noise_magnitude + # lipschitz_penalty = torch.relu(output_diff - self.algo_config.lipschitz_constant * noise_magnitude) + # reshape lipschitz penalty from (B*n_samples, D1, D2, ...) to (B, n_samples, D1, D2, ...) + lipschitz_penalty = lipschitz_penalty.reshape(B, n_samples, *lipschitz_penalty.shape[1:]) + + # take mean over n_samples dimension -> shape (B,) + lipschitz_penalty = lipschitz_penalty.mean(dim=1) + + if self.algo_config.lipschitz_slack: + obs_dict = {k: batch["obs"][k][:, To - 1, :] for k in batch["obs"]} + actions = batch['actions'][:, 0, :] + + slack = self.nets['policy']['slack_var_net'](obs_dict=obs_dict, acts=actions) + lipschitz_penalty = slack * lipschitz_penalty + 1 - torch.exp(-0.1 * torch.abs(slack).mean()) + lipschitz_penalty = self.algo_config.lipschitz_weight * lipschitz_penalty.mean() + else: + entropies = batch['entropy'][:, 0] + # sigmoid + entropy_weight = 1 / (1 + torch.exp(-5 * (entropies - 0.5))) + lipschitz_penalty = (self.algo_config.lipschitz_weight * lipschitz_penalty * entropy_weight).mean() + + actor_loss = actor_loss + lipschitz_penalty + + info["actor/lipschitz_penalty"] = lipschitz_penalty + + info["actor/loss"] = actor_loss + + # Return stats + return actor_loss, info + + def _update_actor(self, actor_loss): + """ + Helper function for updating actor network. Called by @train_on_batch + + Args: + actor_loss (torch.Tensor): actor loss + """ + + gn_sq = TorchUtils.backprop_for_loss( + net=self.nets['policy'], + optim=self.optimizers['policy'], + loss=actor_loss, + ) + # rsm_rise: policy gradient norm (backprop_for_loss returns the sum of squared per-parameter norms) + self._last_policy_grad_norm = float(gn_sq) ** 0.5 + + def _get_adv_weights(self, adv): + """ + Helper function for computing advantage weights. Called by @_compute_actor_loss + + Args: + adv (torch.Tensor): raw advantage estimates + + Returns: + weights (torch.Tensor): weights computed based on advantage estimates, + in shape (B,) where B is batch size + """ + + # clip raw advantage values + if self.algo_config.adv.clip_adv_value is not None: + adv = adv.clamp(max=self.algo_config.adv.clip_adv_value) + + # compute weights based on advantage values + beta = self.algo_config.adv.beta # temprature factor + weights = torch.exp(adv / beta) + # clip final weights + if self.algo_config.adv.use_final_clip is True: + weights = weights.clamp(-100.0, 100.0) + + # reshape from (B, 1) to (B,) + return weights[:, 0] + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + log = OrderedDict() + + # rsm_rise BASE_TOPUP (gen_q#287): under algo.critic_only the actor loss is never computed, so + # these keys are absent. Guarded rather than faked so a MISSING actor loss can never be read as 0. + if "actor/bc_loss" in info: + log["actor/bc_loss"] = info["actor/bc_loss"].item() + if "actor/loss" in info: + log["actor/loss"] = info["actor/loss"].item() + # rsm_rise: extra monitoring keys + if "actor/policy_grad_norm" in info: + log["actor/policy_grad_norm"] = info["actor/policy_grad_norm"].item() + if "actor/adv" in info: + self._log_data_attributes(log, info, "actor/adv") + if "actor/spectral_norm" in info: + log["actor/spectral_norm"] = info["actor/spectral_norm"].item() + + if not self.algo_config.use_bc: + if 'critic/critic1_pred' in info: + log["critic/critic1_pred"] = info["critic/critic1_pred"].item() + log["critic/critic1_loss"] = info["critic/critic1_loss"].item() + + log["vf/v_loss"] = info["vf/v_loss"].item() + + + self._log_data_attributes(log, info, "vf/q_pred") + self._log_data_attributes(log, info, "vf/v_pred") + + try: + if self.algo_config.bottleneck_value: + self._log_data_attributes(log, info, "critic/critic1_kl_div") + if self.algo_config.bottleneck_policy: + self._log_data_attributes(log, info, "actor/kl_div") + if self.algo_config.spectral_norm_value: + self._log_data_attributes(log, info, "critic/critic1_spectral_norm") + if self.algo_config.spectral_norm_policy: + self._log_data_attributes(log, info, "actor/spectral_norm") + if self.algo_config.lipschitz: + self._log_data_attributes(log, info, "actor/lipschitz_penalty") + except KeyError: + pass + + return log + + def _log_data_attributes(self, log, info, key): + """ + Helper function for logging statistics. Moodifies log in-place + + Args: + log (dict): existing log dictionary + log (dict): existing dictionary of tensors containing raw stats + key (str): key to log + """ + log[key + "/max"] = info[key].max().item() + log[key + "/min"] = info[key].min().item() + log[key + "/mean"] = info[key].mean().item() + log[key + "/std"] = info[key].std().item() + + def on_epoch_end(self, epoch): + """ + Called at the end of each epoch. + """ + + # LR scheduling updates + for lr_sc in self.lr_schedulers["critic"]: + if lr_sc is not None: + lr_sc.step() + + if self.lr_schedulers["vf"] is not None: + self.lr_schedulers["vf"].step() + + if self.lr_schedulers["policy"] is not None: + self.lr_schedulers["policy"].step() + + def get_action(self, obs_dict, goal_dict=None): + """ + Get policy action outputs. plan_n <= 1 (default) is the released path: one diffusion sample, + the Ta-step executed window. plan_n > 1: best-of-N over the sampler with the RSM scorer + (robomimic/algo/rsm_planner.py, rsm_rise E1). + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + action (torch.Tensor): action tensor + """ + assert not self.nets.training + return self.plan_get_action(obs_dict, goal_dict) + + def _sample_action_chunks(self, obs_dict, goal_dict=None): + """The released sampler, unchanged: one DDPM/DDIM chain per batch row -> naction [B, Tp, ac].""" + To = self.algo_config.horizon.observation_horizon + Ta = self.algo_config.horizon.action_horizon + Tp = self.algo_config.horizon.prediction_horizon + action_dim = self.ac_dim + if self.algo_config.ddpm.enabled is True: + num_inference_timesteps = self.algo_config.ddpm.num_inference_timesteps + elif self.algo_config.ddim.enabled is True: + num_inference_timesteps = self.algo_config.ddim.num_inference_timesteps + else: + raise ValueError + + # select network + nets = self.nets + # if self.ema is not None: + # nets = self.ema_model + + # encode obs + inputs = { + 'obs': obs_dict, + 'goal': goal_dict + } + + for k in self.obs_shapes: + # first two dimensions should be [B, T] for inputs + assert inputs['obs'][k].ndim - 2 == len(self.obs_shapes[k]) + obs_features = TensorUtils.time_distributed(inputs, self.nets['policy']['obs_encoder'], inputs_as_kwargs=True) + assert obs_features.ndim == 3 # [B, T, D] + B = obs_features.shape[0] + + # reshape observation to (B,obs_horizon*obs_dim) + obs_cond = obs_features.flatten(start_dim=1) + + # initialize action from Guassian noise + noisy_action = torch.randn( + (B, Tp, action_dim), device=self.device) + naction = noisy_action + + # init scheduler + self.noise_scheduler.set_timesteps(num_inference_timesteps) + + for k in self.noise_scheduler.timesteps: + # predict noise + noise_pred = nets['policy']['noise_pred_net']( + sample=naction, + timestep=k, + global_cond=obs_cond + ) + + # inverse diffusion step (remove noise) + naction = self.noise_scheduler.step( + model_output=noise_pred, + timestep=k, + sample=naction + ).prev_sample + + return naction + + def serialize(self): + nets_state_dict = super().serialize() + if self.ema is not None: + ema_state_dict = self.ema.state_dict() + + return { + 'nets': nets_state_dict, + 'ema': ema_state_dict + } + + def deserialize(self, model_dict): + try: + nets_dict = model_dict['nets'] + ema_dict = model_dict['ema'] + except KeyError: + super().deserialize(model_dict) + return + super().deserialize(nets_dict) + if ema_dict: + self.ema.load_state_dict(ema_dict) + +# =================== Vision Encoder Utils ===================== +def replace_submodules( + root_module: nn.Module, + predicate: Callable[[nn.Module], bool], + func: Callable[[nn.Module], nn.Module]) -> nn.Module: + """ + Replace all submodules selected by the predicate with + the output of func. + + predicate: Return true if the module is to be replaced. + func: Return new module to use. + """ + if predicate(root_module): + return func(root_module) + + if parse_version(torch.__version__) < parse_version('1.9.0'): + raise ImportError('This function requires pytorch >= 1.9.0') + + bn_list = [k.split('.') for k, m + in root_module.named_modules(remove_duplicate=True) + if predicate(m)] + for *parent, k in bn_list: + parent_module = root_module + if len(parent) > 0: + parent_module = root_module.get_submodule('.'.join(parent)) + if isinstance(parent_module, nn.Sequential): + src_module = parent_module[int(k)] + else: + src_module = getattr(parent_module, k) + tgt_module = func(src_module) + if isinstance(parent_module, nn.Sequential): + parent_module[int(k)] = tgt_module + else: + setattr(parent_module, k, tgt_module) + # verify that all modules are replaced + bn_list = [k.split('.') for k, m + in root_module.named_modules(remove_duplicate=True) + if predicate(m)] + assert len(bn_list) == 0 + return root_module + +def replace_bn_with_gn( + root_module: nn.Module, + features_per_group: int=16) -> nn.Module: + """ + Relace all BatchNorm layers with GroupNorm. + """ + replace_submodules( + root_module=root_module, + predicate=lambda x: isinstance(x, nn.BatchNorm2d), + func=lambda x: nn.GroupNorm( + num_groups=x.num_features//features_per_group, + num_channels=x.num_features) + ) + return root_module + +# =================== UNet for Diffusion ============== + +class SinusoidalPosEmb(nn.Module): + def __init__(self, dim): + super().__init__() + self.dim = dim + + def forward(self, x): + device = x.device + half_dim = self.dim // 2 + emb = math.log(10000) / (half_dim - 1) + emb = torch.exp(torch.arange(half_dim, device=device) * -emb) + emb = x[:, None] * emb[None, :] + emb = torch.cat((emb.sin(), emb.cos()), dim=-1) + return emb + + +class Downsample1d(nn.Module): + def __init__(self, dim): + super().__init__() + self.conv = nn.Conv1d(dim, dim, 3, 2, 1) + + def forward(self, x): + return self.conv(x) + +class Upsample1d(nn.Module): + def __init__(self, dim): + super().__init__() + self.conv = nn.ConvTranspose1d(dim, dim, 4, 2, 1) + + def forward(self, x): + return self.conv(x) + + +class Conv1dBlock(nn.Module): + ''' + Conv1d --> GroupNorm --> Mish + ''' + + def __init__(self, inp_channels, out_channels, kernel_size, n_groups=8): + super().__init__() + + self.block = nn.Sequential( + nn.Conv1d(inp_channels, out_channels, kernel_size, padding=kernel_size // 2), + nn.GroupNorm(n_groups, out_channels), + nn.Mish(), + ) + + def forward(self, x): + return self.block(x) + + +class ConditionalResidualBlock1D(nn.Module): + def __init__(self, + in_channels, + out_channels, + cond_dim, + kernel_size=3, + n_groups=8): + super().__init__() + + self.blocks = nn.ModuleList([ + Conv1dBlock(in_channels, out_channels, kernel_size, n_groups=n_groups), + Conv1dBlock(out_channels, out_channels, kernel_size, n_groups=n_groups), + ]) + + # FiLM modulation https://arxiv.org/abs/1709.07871 + # predicts per-channel scale and bias + cond_channels = out_channels * 2 + self.out_channels = out_channels + self.cond_encoder = nn.Sequential( + nn.Mish(), + nn.Linear(cond_dim, cond_channels), + nn.Unflatten(-1, (-1, 1)) + ) + + # make sure dimensions compatible + self.residual_conv = nn.Conv1d(in_channels, out_channels, 1) \ + if in_channels != out_channels else nn.Identity() + + def forward(self, x, cond): + ''' + x : [ batch_size x in_channels x horizon ] + cond : [ batch_size x cond_dim] + + returns: + out : [ batch_size x out_channels x horizon ] + ''' + out = self.blocks[0](x) + embed = self.cond_encoder(cond) + + embed = embed.reshape( + embed.shape[0], 2, self.out_channels, 1) + scale = embed[:,0,...] + bias = embed[:,1,...] + out = scale * out + bias + + out = self.blocks[1](out) + out = out + self.residual_conv(x) + return out + + +class ConditionalUnet1D(nn.Module): + def __init__(self, + input_dim, + global_cond_dim, + diffusion_step_embed_dim=256, + down_dims=[256,512,1024], + kernel_size=5, + n_groups=8 + ): + """ + input_dim: Dim of actions. + global_cond_dim: Dim of global conditioning applied with FiLM + in addition to diffusion step embedding. This is usually obs_horizon * obs_dim + diffusion_step_embed_dim: Size of positional encoding for diffusion iteration k + down_dims: Channel size for each UNet level. + The length of this array determines numebr of levels. + kernel_size: Conv kernel size + n_groups: Number of groups for GroupNorm + """ + + super().__init__() + all_dims = [input_dim] + list(down_dims) + start_dim = down_dims[0] + + dsed = diffusion_step_embed_dim + diffusion_step_encoder = nn.Sequential( + SinusoidalPosEmb(dsed), + nn.Linear(dsed, dsed * 4), + nn.Mish(), + nn.Linear(dsed * 4, dsed), + ) + cond_dim = dsed + global_cond_dim + + in_out = list(zip(all_dims[:-1], all_dims[1:])) + mid_dim = all_dims[-1] + self.mid_modules = nn.ModuleList([ + ConditionalResidualBlock1D( + mid_dim, mid_dim, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups + ), + ConditionalResidualBlock1D( + mid_dim, mid_dim, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups + ), + ]) + + down_modules = nn.ModuleList([]) + for ind, (dim_in, dim_out) in enumerate(in_out): + is_last = ind >= (len(in_out) - 1) + down_modules.append(nn.ModuleList([ + ConditionalResidualBlock1D( + dim_in, dim_out, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups), + ConditionalResidualBlock1D( + dim_out, dim_out, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups), + Downsample1d(dim_out) if not is_last else nn.Identity() + ])) + + up_modules = nn.ModuleList([]) + for ind, (dim_in, dim_out) in enumerate(reversed(in_out[1:])): + is_last = ind >= (len(in_out) - 1) + up_modules.append(nn.ModuleList([ + ConditionalResidualBlock1D( + dim_out*2, dim_in, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups), + ConditionalResidualBlock1D( + dim_in, dim_in, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups), + Upsample1d(dim_in) if not is_last else nn.Identity() + ])) + + final_conv = nn.Sequential( + Conv1dBlock(start_dim, start_dim, kernel_size=kernel_size), + nn.Conv1d(start_dim, input_dim, 1), + ) + + self.diffusion_step_encoder = diffusion_step_encoder + self.up_modules = up_modules + self.down_modules = down_modules + self.final_conv = final_conv + + print("number of parameters: {:e}".format( + sum(p.numel() for p in self.parameters())) + ) + + def forward(self, + sample: torch.Tensor, + timestep: Union[torch.Tensor, float, int], + global_cond=None): + """ + x: (B,T,input_dim) + timestep: (B,) or int, diffusion step + global_cond: (B,global_cond_dim) + out + put: (B,T,input_dim) + """ + # (B,T,C) + sample = sample.moveaxis(-1,-2) + # (B,C,T) + + # 1. time + timesteps = timestep + if not torch.is_tensor(timesteps): + timesteps = torch.tensor([timesteps], dtype=torch.long, device=sample.device) + elif torch.is_tensor(timesteps) and len(timesteps.shape) == 0: + timesteps = timesteps[None].to(sample.device) + # broadcast to batch dimension in a way that's compatible with ONNX/Core ML + timesteps = timesteps.expand(sample.shape[0]) + + global_feature = self.diffusion_step_encoder(timesteps) + + if global_cond is not None: + global_feature = torch.cat([ + global_feature, global_cond + ], axis=-1) + + x = sample + h = [] + for idx, (resnet, resnet2, downsample) in enumerate(self.down_modules): + x = resnet(x, global_feature) + x = resnet2(x, global_feature) + h.append(x) + x = downsample(x) + + for mid_module in self.mid_modules: + x = mid_module(x, global_feature) + + for idx, (resnet, resnet2, upsample) in enumerate(self.up_modules): + x = torch.cat((x, h.pop()), dim=1) + x = resnet(x, global_feature) + x = resnet2(x, global_feature) + x = upsample(x) + + x = self.final_conv(x) + + # (B,C,T) + x = x.moveaxis(-1,-2) + # (B,T,C) + return x diff --git a/code_src/rise_robomimic/robomimic/algo/idql_qsm.py b/code_src/rise_robomimic/robomimic/algo/idql_qsm.py new file mode 100644 index 0000000000000000000000000000000000000000..835ed7d90aa3e0d6ff0ccfc0d79989731a2694ab --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/idql_qsm.py @@ -0,0 +1,967 @@ +""" +Implementation of Implicit Q-Learning (IQL). +Based off of https://github.com/rail-berkeley/rlkit/blob/master/rlkit/torch/sac/iql_trainer.py. +(Paper - https://arxiv.org/abs/2110.06169). +""" +import numpy as np +import copy +from collections import OrderedDict +from torch.autograd.functional import jacobian + +import math +import torch +import torch.nn as nn +import torch.nn.functional as F + +import robomimic.models.policy_nets as PolicyNets +import robomimic.models.value_nets as ValueNets +import robomimic.utils.obs_utils as ObsUtils +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.torch_utils as TorchUtils +import robomimic.models.obs_nets as ObsNets + +from typing import Callable, Union +from packaging.version import parse as parse_version +from enum import Enum +from diffusers.schedulers.scheduling_ddpm import DDPMScheduler +from diffusers.schedulers.scheduling_ddim import DDIMScheduler +from diffusers.training_utils import EMAModel + +from robomimic.algo import register_algo_factory_func, ValueAlgo, PolicyAlgo + +from diffusion_policy.model.diffusion.mask_generator import LowdimMaskGenerator + + +class MultiStepMethod(Enum): + REPEAT = 'repeat' + ONE_STEP = 'one_step' + MULTI_STEP = 'multi_step' + +@register_algo_factory_func("idql_qsm") +def algo_config_to_class(algo_config): + """ + Maps algo config to the IQL algo class to instantiate, along with additional algo kwargs. + + Args: + algo_config (Config instance): algo config + + Returns: + algo_class: subclass of Algo + algo_kwargs (dict): dictionary of additional kwargs to pass to algorithm + """ + return IDQL_QSM, {} + + +class IDQL_QSM(PolicyAlgo, ValueAlgo): + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + + Networks for this algo: critic (potentially ensemble), actor, value function + """ + try: + self.multi_step_method = MultiStepMethod(self.algo_config.multi_step_method) + except RuntimeError: + self.multi_step_method = MultiStepMethod.ONE_STEP + + # Create nets + self.nets = nn.ModuleDict() + + observation_group_shapes = OrderedDict() + observation_group_shapes["obs"] = OrderedDict(self.obs_shapes) + encoder_kwargs = ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder) + + obs_encoder = ObsNets.ObservationGroupEncoder( + observation_group_shapes=observation_group_shapes, + encoder_kwargs=encoder_kwargs, + ) + # IMPORTANT! + # replace all BatchNorm with GroupNorm to work with EMA + # performance will tank if you forget to do this! + obs_encoder = replace_bn_with_gn(obs_encoder) + + obs_dim = obs_encoder.output_shape()[0] + + # create network object + noise_pred_net = ConditionalUnet1D( + input_dim=self.ac_dim, + down_dims=self.algo_config.unet.down_dims, + diffusion_step_embed_dim=self.algo_config.unet.diffusion_step_embed_dim, + global_cond_dim=obs_dim*self.algo_config.horizon.observation_horizon, + no_chunking=self.algo_config.horizon.prediction_horizon==1, + ) + + # the final arch has 2 parts + self.nets = nn.ModuleDict({ + 'policy': nn.ModuleDict({ + 'obs_encoder': obs_encoder, + 'noise_pred_net': noise_pred_net + }) + }) + + + # self.mask_generator = LowdimMaskGenerator( + # action_dim=self.ac_dim, + # obs_dim=0 if (obs_as_cond) else obs_feature_dim, + # max_n_obs_steps=self.algo_config.horizon.observation_horizon, + # fix_obs_steps=True, + # action_visible=False + # ) + + # setup noise scheduler + noise_scheduler = None + if self.algo_config.ddpm.enabled: + noise_scheduler = DDPMScheduler( + num_train_timesteps=self.algo_config.ddpm.num_train_timesteps, + beta_schedule=self.algo_config.ddpm.beta_schedule, + clip_sample=self.algo_config.ddpm.clip_sample, + prediction_type=self.algo_config.ddpm.prediction_type + ) + elif self.algo_config.ddim.enabled: + noise_scheduler = DDIMScheduler( + num_train_timesteps=self.algo_config.ddim.num_train_timesteps, + beta_schedule=self.algo_config.ddim.beta_schedule, + clip_sample=self.algo_config.ddim.clip_sample, + set_alpha_to_one=self.algo_config.ddim.set_alpha_to_one, + steps_offset=self.algo_config.ddim.steps_offset, + prediction_type=self.algo_config.ddim.prediction_type + ) + else: + raise RuntimeError() + + # Critics + self.nets["critic"] = nn.ModuleList() + self.nets["critic_target"] = nn.ModuleList() + for _ in range(self.algo_config.critic.ensemble.n): + for net_list in (self.nets["critic"], self.nets["critic_target"]): + critic = ValueNets.ActionValueNetwork( + obs_shapes=self.obs_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.critic.layer_dims, + goal_shapes=self.goal_shapes, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + ) + net_list.append(critic) + + # Value function network + self.nets["vf"] = ValueNets.ValueNetwork( + obs_shapes=self.obs_shapes, + mlp_layer_dims=self.algo_config.critic.layer_dims, + goal_shapes=self.goal_shapes, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + ) + + # Send networks to appropriate device + self.nets = self.nets.float().to(self.device) + + # setup EMA + ema = None + if self.algo_config.ema.enabled: + ema = EMAModel(parameters=self.nets.parameters(), power=self.algo_config.ema.power, use_ema_warmup=True) + + self.noise_scheduler = noise_scheduler + self.ema = ema + self.action_check_done = False + + # sync target networks at beginning of training + with torch.no_grad(): + for critic, critic_target in zip(self.nets["critic"], self.nets["critic_target"]): + TorchUtils.hard_update( + source=critic, + target=critic_target, + ) + + def process_batch_for_training(self, batch): + """ + Processes input batch from a data loader to filter out relevant info and prepare the batch for training. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader + + Returns: + input_batch (dict): processed and filtered batch that + will be used for training + """ + + input_batch = dict() + + To = self.algo_config.horizon.observation_horizon + Tp = self.algo_config.horizon.prediction_horizon + + input_batch["obs"] = {k: batch["obs"][k][:, :(To + Tp - 1), :] for k in batch["obs"]} + # TODO: check this + if not self.algo_config.use_bc: + input_batch["next_obs"] = {k: batch["next_obs"][k][:, :(To + Tp - 1), :] for k in batch["next_obs"]} + input_batch["goal_obs"] = batch.get("goal_obs", None) # goals may not be present + input_batch["actions"] = batch["actions"][:, (To - 1):(Tp + To - 1), :] + input_batch["dones"] = batch["dones"][:, (To - 1):(Tp + To - 1)] + input_batch["rewards"] = batch["rewards"][:, (To - 1):(Tp + To - 1)] + + return TensorUtils.to_device(TensorUtils.to_float(input_batch), self.device) + + def train_on_batch(self, batch, epoch, validate=False): + """ + Training on a single batch of data. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + validate (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + Tp = self.algo_config.horizon.prediction_horizon + info = OrderedDict() + + actor_freeze_until_epoch = self.algo_config.optim_params.policy.freeze_until_epoch + if actor_freeze_until_epoch is None: + actor_freeze_until_epoch = -1 + + # Set the correct context for this training step + with TorchUtils.maybe_no_grad(no_grad=validate): + # Always run super call first + info = super().train_on_batch(batch, epoch, validate=validate) + + if self.multi_step_method == MultiStepMethod.REPEAT: + q_preds = [] + v_preds = [] + for i in range(Tp): + # Compute loss for critic(s) + if not self.algo_config.use_bc: + critic_losses, vf_loss, critic_info = self._compute_critic_loss(batch, i) + q_preds.append(critic_info["vf/q_pred"]) + v_preds.append(critic_info["vf/v_pred"]) + + if not validate: + # Critic update + self._update_critic(critic_losses, vf_loss) + + # Compute loss for actor + actor_loss, actor_info = self._compute_actor_loss(batch, q_preds, v_preds) + + if not validate and epoch >= actor_freeze_until_epoch: + # Actor update + self._update_actor(actor_loss) + elif self.multi_step_method == MultiStepMethod.ONE_STEP: + # Compute loss for critic(s) + if not self.algo_config.use_bc: + critic_losses, vf_loss, critic_info = self._compute_critic_loss(batch) + q_pred = critic_info["vf/q_pred"] + v_pred = critic_info["vf/v_pred"] + else: + q_pred = None + v_pred = None + # Compute loss for actor + actor_loss, actor_info = self._compute_actor_loss(batch, q_pred, v_pred) + + if not validate: + # Critic update + if not self.algo_config.use_bc: + self._update_critic(critic_losses, vf_loss) + + # Actor update + if epoch >= actor_freeze_until_epoch: + self._update_actor(actor_loss) + else: + raise NotImplementedError + + # Update info + info.update(actor_info) + if not self.algo_config.use_bc: + info.update(critic_info) + + # Return stats + return info + + def _compute_critic_loss(self, batch, i=0): + """ + Helper function for computing Q and V losses. Called by @train_on_batch + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + i (int): timestep + + Returns: + critic_losses (list): list of critic (Q function) losses + vf_loss (torch.Tensor): value function loss + info (dict): dictionary of Q / V predictions and losses + """ + info = OrderedDict() + To = self.algo_config.horizon.observation_horizon + Tp = self.algo_config.horizon.prediction_horizon + + # get batch values + obs = {k: batch["obs"][k][:, To - 1 + i, :] for k in batch["obs"]} + actions = batch["actions"][:, i, :] + next_obs = {k: batch["next_obs"][k][:, To - 1 + i, :] for k in batch["next_obs"]} + goal_obs = batch["goal_obs"] + rewards = torch.unsqueeze(batch["rewards"][:, i], 1) + dones = torch.unsqueeze(batch["dones"][:, i], 1) + + # Q predictions + pred_qs = [critic(obs_dict=obs, acts=actions, goal_dict=goal_obs) + for critic in self.nets["critic"]] + + info["critic/critic1_pred"] = pred_qs[0].mean() + + # Q target values + target_vf_pred = self.nets["vf"](obs_dict=next_obs, goal_dict=goal_obs).detach() + q_target = rewards + (1. - dones) * self.algo_config.discount * target_vf_pred + q_target = q_target.detach() + + # Q losses + critic_losses = [] + td_loss_fcn = nn.SmoothL1Loss() if self.algo_config.critic.use_huber else nn.MSELoss() + for (i, q_pred) in enumerate(pred_qs): + # Calculate td error loss + td_loss = td_loss_fcn(q_pred, q_target) + info[f"critic/critic{i+1}_loss"] = td_loss + critic_losses.append(td_loss) + + # V predictions + pred_qs = [critic(obs_dict=obs, acts=actions, goal_dict=goal_obs) + for critic in self.nets["critic_target"]] + q_pred, _ = torch.cat(pred_qs, dim=1).min(dim=1, keepdim=True) + q_pred = q_pred.detach() + vf_pred = self.nets["vf"](obs_dict=obs, goal_dict=goal_obs) + + # V losses: expectile regression. see section 4.1 in https://arxiv.org/pdf/2110.06169.pdf + vf_err = vf_pred - q_pred + vf_sign = (vf_err > 0).float() + vf_weight = (1 - vf_sign) * self.algo_config.vf_quantile + vf_sign * (1 - self.algo_config.vf_quantile) + vf_loss = (vf_weight * (vf_err ** 2)).mean() + + # update logs for V loss + info["vf/q_pred"] = q_pred + info["vf/v_pred"] = vf_pred + info["vf/v_loss"] = vf_loss + + # Return stats + return critic_losses, vf_loss, info + + def _update_critic(self, critic_losses, vf_loss): + """ + Helper function for updating critic and vf networks. Called by @train_on_batch + + Args: + critic_losses (list): list of critic (Q function) losses + vf_loss (torch.Tensor): value function loss + """ + + # update ensemble of critics + for (critic_loss, critic, critic_target, optimizer) in zip( + critic_losses, self.nets["critic"], self.nets["critic_target"], self.optimizers["critic"] + ): + TorchUtils.backprop_for_loss( + net=critic, + optim=optimizer, + loss=critic_loss, + max_grad_norm=self.algo_config.critic.max_gradient_norm, + retain_graph=False, + ) + + # update target network + with torch.no_grad(): + TorchUtils.soft_update(source=critic, target=critic_target, tau=self.algo_config.target_tau) + + # update V function network + TorchUtils.backprop_for_loss( + net=self.nets["vf"], + optim=self.optimizers["vf"], + loss=vf_loss, + max_grad_norm=self.algo_config.critic.max_gradient_norm, + retain_graph=False, + ) + + def _compute_actor_loss(self, batch, q_pred, v_pred): + """ + Helper function for computing actor loss. Called by @train_on_batch + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + critic_info (dict): dictionary containing Q and V function predictions, + to be used for computing advantage estimates + + Returns: + actor_loss (torch.Tensor): actor loss + info (dict): dictionary of actor losses, log_probs, advantages, and weights + """ + B = batch['actions'].shape[0] + + info = OrderedDict() + actions = batch['actions'] + + To = self.algo_config.horizon.observation_horizon + + # encode obs + inputs = { + 'obs': {k: batch["obs"][k][:, :To, :] for k in batch["obs"]}, + 'goal': batch["goal_obs"] + } + for k in self.obs_shapes: + # first two dimensions should be [B, T] for inputs + assert inputs['obs'][k].ndim - 2 == len(self.obs_shapes[k]) + + obs_features = TensorUtils.time_distributed(inputs, self.nets['policy']['obs_encoder'], inputs_as_kwargs=True) + assert obs_features.ndim == 3 # [B, T, D] + + obs_cond = obs_features.flatten(start_dim=1) + + # inpainting mask + # condition_mask = self.mask_generator(actions.shape) + + # sample noise to add to actions + noise = torch.randn(actions.shape, device=self.device) + + # sample a diffusion iteration for each data point + timesteps = torch.randint( + 0, self.noise_scheduler.config.num_train_timesteps, + (B,), device=self.device + ).long() + + # add noise to the clean actions according to the noise magnitude at each diffusion iteration + # (this is the forward diffusion process) + noisy_actions = self.noise_scheduler.add_noise( + actions, noise, timesteps) + + obs = {k: batch["obs"][k][:, To - 1, :] for k in batch["obs"]} + goal_obs = batch["goal_obs"] + noisy_actions.requires_grad = True + + jacobians = [] + single_noisy_action = noisy_actions[:, 0, :] + def filter_dict_by_inx(d, inx): + return {k: v[inx].unsqueeze(0) for k, v in d.items()} + for i in range(single_noisy_action.shape[0]): + jac = jacobian( + lambda x: self.nets["critic"][0]( + obs_dict=filter_dict_by_inx(obs, i), + acts=x.unsqueeze(0), + goal_dict=filter_dict_by_inx(goal_obs, i) if goal_obs is not None else None + ), single_noisy_action[i]) + jacobians.append(jac) + # shape (B, A) + jacobians = torch.cat(jacobians, dim=0).squeeze().detach() + + # # apply conditioning + # noisy_actions[condition_mask] = actions[condition_mask] + # predict the noise residual + noise_pred = self.nets['policy']['noise_pred_net']( + noisy_actions, timesteps, global_cond=obs_cond) + + # L2 loss + score_matching_loss = F.mse_loss(noise_pred, -self.algo_config.alpha_q * jacobians) + + self.ema.step(self.nets['policy'].parameters()) + + info["actor/bc_loss"] = score_matching_loss.mean() + + actor_loss = (score_matching_loss).mean() + + info["actor/loss"] = actor_loss + + # Return stats + return actor_loss, info + + def _update_actor(self, actor_loss): + """ + Helper function for updating actor network. Called by @train_on_batch + + Args: + actor_loss (torch.Tensor): actor loss + """ + + TorchUtils.backprop_for_loss( + net=self.nets['policy'], + optim=self.optimizers['policy'], + loss=actor_loss, + ) + + def _get_adv_weights(self, adv): + """ + Helper function for computing advantage weights. Called by @_compute_actor_loss + + Args: + adv (torch.Tensor): raw advantage estimates + + Returns: + weights (torch.Tensor): weights computed based on advantage estimates, + in shape (B,) where B is batch size + """ + + # clip raw advantage values + if self.algo_config.adv.clip_adv_value is not None: + adv = adv.clamp(max=self.algo_config.adv.clip_adv_value) + + # compute weights based on advantage values + beta = self.algo_config.adv.beta # temprature factor + weights = torch.exp(adv / beta) + # clip final weights + if self.algo_config.adv.use_final_clip is True: + weights = weights.clamp(-100.0, 100.0) + + # reshape from (B, 1) to (B,) + return weights[:, 0] + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + log = OrderedDict() + + log["actor/bc_loss"] = info["actor/bc_loss"].item() + log["actor/loss"] = info["actor/loss"].item() + + if not self.algo_config.use_bc: + log["critic/critic1_pred"] = info["critic/critic1_pred"].item() + log["critic/critic1_loss"] = info["critic/critic1_loss"].item() + + log["vf/v_loss"] = info["vf/v_loss"].item() + + self._log_data_attributes(log, info, "vf/q_pred") + self._log_data_attributes(log, info, "vf/v_pred") + + return log + + def _log_data_attributes(self, log, info, key): + """ + Helper function for logging statistics. Moodifies log in-place + + Args: + log (dict): existing log dictionary + log (dict): existing dictionary of tensors containing raw stats + key (str): key to log + """ + log[key + "/max"] = info[key].max().item() + log[key + "/min"] = info[key].min().item() + log[key + "/mean"] = info[key].mean().item() + log[key + "/std"] = info[key].std().item() + + def on_epoch_end(self, epoch): + """ + Called at the end of each epoch. + """ + + # LR scheduling updates + for lr_sc in self.lr_schedulers["critic"]: + if lr_sc is not None: + lr_sc.step() + + if self.lr_schedulers["vf"] is not None: + self.lr_schedulers["vf"].step() + + if self.lr_schedulers["policy"] is not None: + self.lr_schedulers["policy"].step() + + def get_action(self, obs_dict, goal_dict=None): + """ + Get policy action outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + action (torch.Tensor): action tensor + """ + + To = self.algo_config.horizon.observation_horizon + Ta = self.algo_config.horizon.action_horizon + Tp = self.algo_config.horizon.prediction_horizon + action_dim = self.ac_dim + if self.algo_config.ddpm.enabled is True: + num_inference_timesteps = self.algo_config.ddpm.num_inference_timesteps + elif self.algo_config.ddim.enabled is True: + num_inference_timesteps = self.algo_config.ddim.num_inference_timesteps + else: + raise ValueError + + # select network + nets = self.nets + # if self.ema is not None: + # nets = self.ema_model + + # encode obs + inputs = { + 'obs': obs_dict, + 'goal': goal_dict + } + + for k in self.obs_shapes: + # first two dimensions should be [B, T] for inputs + assert inputs['obs'][k].ndim - 2 == len(self.obs_shapes[k]) + obs_features = TensorUtils.time_distributed(inputs, self.nets['policy']['obs_encoder'], inputs_as_kwargs=True) + assert obs_features.ndim == 3 # [B, T, D] + B = obs_features.shape[0] + + # reshape observation to (B,obs_horizon*obs_dim) + obs_cond = obs_features.flatten(start_dim=1) + + # initialize action from Guassian noise + noisy_action = torch.randn( + (B, Tp, action_dim), device=self.device) + naction = noisy_action + + # init scheduler + self.noise_scheduler.set_timesteps(num_inference_timesteps) + + for k in self.noise_scheduler.timesteps: + # predict noise + noise_pred = nets['policy']['noise_pred_net']( + sample=naction, + timestep=k, + global_cond=obs_cond + ) + + # inverse diffusion step (remove noise) + naction = self.noise_scheduler.step( + model_output=noise_pred, + timestep=k, + sample=naction + ).prev_sample + + # process action using Ta + start = To - 1 + # for action chunk = 1 (no action chunking) + if Tp == 1: + start -= 1 + end = start + Ta + action = naction[:,start:end] + return action + + def serialize(self): + nets_state_dict = super().serialize() + if self.ema is not None: + ema_state_dict = self.ema.state_dict() + + return { + 'nets': nets_state_dict, + 'ema': ema_state_dict + } + + def deserialize(self, model_dict): + try: + nets_dict = model_dict['nets'] + ema_dict = model_dict['ema'] + except KeyError: + super().deserialize(model_dict) + return + super().deserialize(nets_dict) + if ema_dict: + self.ema.load_state_dict(ema_dict) + +# =================== Vision Encoder Utils ===================== +def replace_submodules( + root_module: nn.Module, + predicate: Callable[[nn.Module], bool], + func: Callable[[nn.Module], nn.Module]) -> nn.Module: + """ + Replace all submodules selected by the predicate with + the output of func. + + predicate: Return true if the module is to be replaced. + func: Return new module to use. + """ + if predicate(root_module): + return func(root_module) + + if parse_version(torch.__version__) < parse_version('1.9.0'): + raise ImportError('This function requires pytorch >= 1.9.0') + + bn_list = [k.split('.') for k, m + in root_module.named_modules(remove_duplicate=True) + if predicate(m)] + for *parent, k in bn_list: + parent_module = root_module + if len(parent) > 0: + parent_module = root_module.get_submodule('.'.join(parent)) + if isinstance(parent_module, nn.Sequential): + src_module = parent_module[int(k)] + else: + src_module = getattr(parent_module, k) + tgt_module = func(src_module) + if isinstance(parent_module, nn.Sequential): + parent_module[int(k)] = tgt_module + else: + setattr(parent_module, k, tgt_module) + # verify that all modules are replaced + bn_list = [k.split('.') for k, m + in root_module.named_modules(remove_duplicate=True) + if predicate(m)] + assert len(bn_list) == 0 + return root_module + +def replace_bn_with_gn( + root_module: nn.Module, + features_per_group: int=16) -> nn.Module: + """ + Relace all BatchNorm layers with GroupNorm. + """ + replace_submodules( + root_module=root_module, + predicate=lambda x: isinstance(x, nn.BatchNorm2d), + func=lambda x: nn.GroupNorm( + num_groups=x.num_features//features_per_group, + num_channels=x.num_features) + ) + return root_module + +# =================== UNet for Diffusion ============== + +class SinusoidalPosEmb(nn.Module): + def __init__(self, dim): + super().__init__() + self.dim = dim + + def forward(self, x): + device = x.device + half_dim = self.dim // 2 + emb = math.log(10000) / (half_dim - 1) + emb = torch.exp(torch.arange(half_dim, device=device) * -emb) + emb = x[:, None] * emb[None, :] + emb = torch.cat((emb.sin(), emb.cos()), dim=-1) + return emb + + +class Downsample1d(nn.Module): + def __init__(self, dim): + super().__init__() + self.conv = nn.Conv1d(dim, dim, 3, 2, 1) + + def forward(self, x): + return self.conv(x) + +class Upsample1d(nn.Module): + def __init__(self, dim): + super().__init__() + self.conv = nn.ConvTranspose1d(dim, dim, 4, 2, 1) + + def forward(self, x): + return self.conv(x) + + +class Conv1dBlock(nn.Module): + ''' + Conv1d --> GroupNorm --> Mish + ''' + + def __init__(self, inp_channels, out_channels, kernel_size, n_groups=8): + super().__init__() + + self.block = nn.Sequential( + nn.Conv1d(inp_channels, out_channels, kernel_size, padding=kernel_size // 2), + nn.GroupNorm(n_groups, out_channels), + nn.Mish(), + ) + + def forward(self, x): + return self.block(x) + + +class ConditionalResidualBlock1D(nn.Module): + def __init__(self, + in_channels, + out_channels, + cond_dim, + kernel_size=3, + n_groups=8): + super().__init__() + + self.blocks = nn.ModuleList([ + Conv1dBlock(in_channels, out_channels, kernel_size, n_groups=n_groups), + Conv1dBlock(out_channels, out_channels, kernel_size, n_groups=n_groups), + ]) + + # FiLM modulation https://arxiv.org/abs/1709.07871 + # predicts per-channel scale and bias + cond_channels = out_channels * 2 + self.out_channels = out_channels + self.cond_encoder = nn.Sequential( + nn.Mish(), + nn.Linear(cond_dim, cond_channels), + nn.Unflatten(-1, (-1, 1)) + ) + + # make sure dimensions compatible + self.residual_conv = nn.Conv1d(in_channels, out_channels, 1) \ + if in_channels != out_channels else nn.Identity() + + def forward(self, x, cond): + ''' + x : [ batch_size x in_channels x horizon ] + cond : [ batch_size x cond_dim] + + returns: + out : [ batch_size x out_channels x horizon ] + ''' + out = self.blocks[0](x) + embed = self.cond_encoder(cond) + + embed = embed.reshape( + embed.shape[0], 2, self.out_channels, 1) + scale = embed[:,0,...] + bias = embed[:,1,...] + out = scale * out + bias + + out = self.blocks[1](out) + out = out + self.residual_conv(x) + return out + + +class ConditionalUnet1D(nn.Module): + def __init__(self, + input_dim, + global_cond_dim, + diffusion_step_embed_dim=256, + down_dims=[256,512,1024], + kernel_size=5, + n_groups=8, + no_chunking=False, + ): + """ + input_dim: Dim of actions. + global_cond_dim: Dim of global conditioning applied with FiLM + in addition to diffusion step embedding. This is usually obs_horizon * obs_dim + diffusion_step_embed_dim: Size of positional encoding for diffusion iteration k + down_dims: Channel size for each UNet level. + The length of this array determines numebr of levels. + kernel_size: Conv kernel size + n_groups: Number of groups for GroupNorm + """ + + super().__init__() + all_dims = [input_dim] + list(down_dims) + start_dim = down_dims[0] + + dsed = diffusion_step_embed_dim + diffusion_step_encoder = nn.Sequential( + SinusoidalPosEmb(dsed), + nn.Linear(dsed, dsed * 4), + nn.Mish(), + nn.Linear(dsed * 4, dsed), + ) + cond_dim = dsed + global_cond_dim + + in_out = list(zip(all_dims[:-1], all_dims[1:])) + mid_dim = all_dims[-1] + self.mid_modules = nn.ModuleList([ + ConditionalResidualBlock1D( + mid_dim, mid_dim, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups + ), + ConditionalResidualBlock1D( + mid_dim, mid_dim, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups + ), + ]) + + down_modules = nn.ModuleList([]) + for ind, (dim_in, dim_out) in enumerate(in_out): + is_last = ind >= (len(in_out) - 1) + down_modules.append(nn.ModuleList([ + ConditionalResidualBlock1D( + dim_in, dim_out, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups), + ConditionalResidualBlock1D( + dim_out, dim_out, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups), + Downsample1d(dim_out) if (not is_last and not no_chunking) else nn.Identity() + ])) + + up_modules = nn.ModuleList([]) + for ind, (dim_in, dim_out) in enumerate(reversed(in_out[1:])): + is_last = ind >= (len(in_out) - 1) + up_modules.append(nn.ModuleList([ + ConditionalResidualBlock1D( + dim_out*2, dim_in, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups), + ConditionalResidualBlock1D( + dim_in, dim_in, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups), + Upsample1d(dim_in) if (not is_last and not no_chunking) else nn.Identity() + ])) + + final_conv = nn.Sequential( + Conv1dBlock(start_dim, start_dim, kernel_size=kernel_size), + nn.Conv1d(start_dim, input_dim, 1), + ) + + self.diffusion_step_encoder = diffusion_step_encoder + self.up_modules = up_modules + self.down_modules = down_modules + self.final_conv = final_conv + + print("number of parameters: {:e}".format( + sum(p.numel() for p in self.parameters())) + ) + + def forward(self, + sample: torch.Tensor, + timestep: Union[torch.Tensor, float, int], + global_cond=None): + """ + x: (B,T,input_dim) + timestep: (B,) or int, diffusion step + global_cond: (B,global_cond_dim) + out + put: (B,T,input_dim) + """ + sample = sample.moveaxis(-1,-2) + # (B,C,T) + + # 1. time + timesteps = timestep + if not torch.is_tensor(timesteps): + timesteps = torch.tensor([timesteps], dtype=torch.long, device=sample.device) + elif torch.is_tensor(timesteps) and len(timesteps.shape) == 0: + timesteps = timesteps[None].to(sample.device) + # broadcast to batch dimension in a way that's compatible with ONNX/Core ML + timesteps = timesteps.expand(sample.shape[0]) + + global_feature = self.diffusion_step_encoder(timesteps) + + if global_cond is not None: + global_feature = torch.cat([ + global_feature, global_cond + ], axis=-1) + + x = sample + h = [] + for idx, (resnet, resnet2, downsample) in enumerate(self.down_modules): + x = resnet(x, global_feature) + x = resnet2(x, global_feature) + h.append(x) + x = downsample(x) + + for mid_module in self.mid_modules: + x = mid_module(x, global_feature) + + for idx, (resnet, resnet2, upsample) in enumerate(self.up_modules): + x = torch.cat((x, h.pop()), dim=1) + x = resnet(x, global_feature) + x = resnet2(x, global_feature) + x = upsample(x) + + x = self.final_conv(x) + + # (B,C,T) + x = x.moveaxis(-1,-2) + # (B,T,C) + return x diff --git a/code_src/rise_robomimic/robomimic/algo/ifql_torch.py b/code_src/rise_robomimic/robomimic/algo/ifql_torch.py new file mode 100644 index 0000000000000000000000000000000000000000..587dc8d9fb6acc504a5fcaa265d1377e4752fdb8 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/ifql_torch.py @@ -0,0 +1,233 @@ +"""Torch re-implementation of the IFQL critic and flow actor, reading a JAX/flax training bundle. + +gen_q#264. IFQL (implicit flow Q-learning, the flow variant of IDQL) is trained in JAX by +rsm_rise/code/ifql/train_ifql.py, which exports every flax parameter as a plain numpy array into +`ifql_bundle.pt`. Eval happens inside the RISE robomimic/MuJoCo process, whose python (rsm_rise/env, +3.10) has no JAX at all, so the two things eval needs -- Q(s, a) for ranking candidates, and the flow +actor for the "IFQL as published" column -- are re-implemented here in torch and fed those arrays. + +What is replicated, exactly (upstream files vendored under rsm_rise/code/ifql/impls): + * utils/networks.ResidualMLP / ResidualMLPBlock: Dense -> gelu -> LayerNorm entry projection, then + `len(hidden_dims)` blocks of (Dense, gelu, LayerNorm, Dense, +residual, gelu, LayerNorm), then a + Dense to the output width. flax's nn.gelu is the TANH approximation and flax's nn.LayerNorm uses + epsilon 1e-6, both of which torch has to be told explicitly. + * utils/networks.CategoricalValue: [obs (| action)] -> num_bins logits; `num_ensembles` > 1 is flax + nn.vmap with the parameter axis leading, i.e. kernels are [E, d_in, d_out] and every member sees the + same input. + * utils/loss_utils.hl_gauss_from_logits: softmax over 101 bins whose centres tile [0, 1], dotted with + those centres -- so a Q is already on the "discounted average provenance label" scale (see + train_ifql.py's VALUE SCALE note). + * utils/networks.ActorVectorField: [obs | action | time embedding] -> action-dim velocity, where the + time embedding is [t, cos(2 pi t k), sin(2 pi t k)] for k = 1..32. + * agents/ifql.IFQLAgent.sample_actions: `num_samples` unit normals, `flow_steps` Euler steps at + t = i / flow_steps, clip to [-1, 1], then arg-max of the `q_agg` aggregation of the critic ensemble. + +Parity against the JAX original is asserted by rsm_rise/scripts/ifql_parity.py (max abs difference over +random states/actions; the tolerance it enforces is 1e-4 on Q and on the sampled action). +""" +from __future__ import annotations + +import numpy as np +import torch +import torch.nn.functional as F + +LN_EPS = 1e-6 # flax.linen.LayerNorm default epsilon (torch's default is 1e-5) + + +def _gelu(x): + """flax.linen.gelu == jax.nn.gelu(approximate=True) == torch's tanh approximation.""" + return F.gelu(x, approximate="tanh") + + +def hl_gauss_from_logits(logits, lo=0.0, hi=1.0): + """[..., B] logits -> scalar value, the HL-Gauss two-hot read-out over bins tiling [lo, hi].""" + nb = logits.shape[-1] + edges = torch.linspace(lo, hi, nb + 1, device=logits.device, dtype=logits.dtype) + centres = (edges[:-1] + edges[1:]) / 2 + return (torch.softmax(logits, dim=-1) * centres).sum(-1) + + +class _Params: + """Flat {'a/b/c': tensor} bundle with dotted access helpers.""" + + def __init__(self, params, device, dtype=torch.float32): + self.p = {k: torch.as_tensor(np.asarray(v), dtype=dtype, device=device) if not torch.is_tensor(v) + else v.to(device=device, dtype=dtype) for k, v in params.items()} + + def has(self, key): + return key in self.p + + def __getitem__(self, key): + if key not in self.p: + raise KeyError(f"{key} not in the IFQL bundle; have e.g. {sorted(self.p)[:6]}") + return self.p[key] + + +def _dense(P, prefix, x, ens): + """flax nn.Dense. ens: None (plain) or the ensemble size (kernel [E, d_in, d_out], x [E, ..., d_in]).""" + k, b = P[f"{prefix}/kernel"], P[f"{prefix}/bias"] + if ens is None: + return x @ k + b + return torch.einsum("e...i,eio->e...o", x, k) + b.reshape(ens, *([1] * (x.dim() - 2)), -1) + + +def _layer_norm(P, prefix, x, ens): + s, b = P[f"{prefix}/scale"], P[f"{prefix}/bias"] + y = (x - x.mean(-1, keepdim=True)) / torch.sqrt(x.var(-1, unbiased=False, keepdim=True) + LN_EPS) + if ens is None: + return y * s + b + shape = (ens, *([1] * (x.dim() - 2)), -1) + return y * s.reshape(shape) + b.reshape(shape) + + +def _residual_mlp(P, prefix, x, n_blocks, layer_norm, ens): + """utils/networks.ResidualMLP forward (hidden widths are constant, so n_blocks is all we need).""" + x = _dense(P, f"{prefix}/Dense_0", x, ens) + x = _gelu(x) + if layer_norm: + x = _layer_norm(P, f"{prefix}/LayerNorm_0", x, ens) + for i in range(n_blocks): + bp = f"{prefix}/ResidualMLPBlock_{i}" + res = x + x = _dense(P, f"{bp}/Dense_0", x, ens) + x = _gelu(x) + if layer_norm: + x = _layer_norm(P, f"{bp}/LayerNorm_0", x, ens) + x = _dense(P, f"{bp}/Dense_1", x, ens) + x = res + x + x = _gelu(x) + if layer_norm: + x = _layer_norm(P, f"{bp}/LayerNorm_1", x, ens) + return _dense(P, f"{prefix}/Dense_1", x, ens) + + +def _plain_mlp(P, prefix, x, n_hidden, layer_norm, ens): + """utils/networks.MLP forward with hidden_dims = (*hidden, out) and activate_final=False.""" + n = n_hidden + 1 + for i in range(n): + x = _dense(P, f"{prefix}/Dense_{i}", x, ens) + if i + 1 < n: + x = _gelu(x) + if layer_norm: + x = _layer_norm(P, f"{prefix}/LayerNorm_{i}", x, ens) + return x + + +def _embed_times(t, n_freq=32): + """utils/networks.ActorVectorField._embed_times: [t, cos(2 pi t k), sin(2 pi t k)] for k = 1..n_freq.""" + freqs = torch.arange(1, n_freq + 1, device=t.device, dtype=t.dtype) + ang = 2 * np.pi * t * freqs + return torch.cat([t, torch.cos(ang), torch.sin(ang)], dim=-1) + + +class IFQLTorch: + """One trained IFQL agent, in torch. `q(obs, actions)` and `sample_actions(obs, generator)`.""" + + def __init__(self, bundle, device="cpu"): + if isinstance(bundle, (str, bytes)) or hasattr(bundle, "__fspath__"): + self.path = str(bundle) + bundle = torch.load(bundle, map_location="cpu", weights_only=False) + else: + self.path = bundle.get("path", "") + if bundle.get("kind") != "ifql_bundle_v1": + raise RuntimeError(f"not an IFQL bundle: kind={bundle.get('kind')!r}") + self.device = torch.device(device) + self.P = _Params(bundle["params"], self.device) + c = dict(bundle["config"]) + self.cfg = c + self.feat_stats = bundle.get("feat_stats", "") + self.task = bundle.get("task", "") + self.seed = int(bundle.get("seed", -1)) + self.step = int(bundle.get("step", -1)) + self.obs_mode = bundle.get("obs_mode", "dino") + if c.get("encoder"): + raise NotImplementedError("the torch port covers the vector-observation variant (encoder=None); " + f"this bundle was trained with encoder={c['encoder']!r}") + self.mlp_class = c.get("mlp_class", "resmlp") + self.layer_norm = bool(c.get("layer_norm", True)) + self.actor_layer_norm = bool(c.get("actor_layer_norm", True)) + self.action_dim = int(c["action_dim"]) + self.num_samples = int(c.get("num_samples", 128)) + self.flow_steps = int(c.get("flow_steps", 10)) + self.q_agg = c.get("q_agg", "mean") + self.n_value_blocks = len(c["value_hidden_dims"]) + self.n_actor_blocks = len(c["actor_hidden_dims"]) + # critic ensemble size, read off the parameter shapes rather than assumed + k = self.P["modules_critic/value_net/Dense_0/kernel"] + self.n_critics = int(k.shape[0]) if k.dim() == 3 else None + + # ---- read-outs --------------------------------------------------------- + def _value_net(self, prefix, x, ens): + if self.mlp_class == "resmlp": + return _residual_mlp(self.P, prefix, x, self.n_value_blocks, self.layer_norm, ens) + return _plain_mlp(self.P, prefix, x, self.n_value_blocks, self.layer_norm, ens) + + @torch.no_grad() + def q(self, obs, actions, aggregate=True): + """obs [B, d], actions [B, adim] -> Q [B] (aggregated with q_agg) or [E, B].""" + obs = torch.as_tensor(obs, dtype=torch.float32, device=self.device) + actions = torch.as_tensor(actions, dtype=torch.float32, device=self.device) + inp = torch.cat([obs, actions], -1) + ens = self.n_critics + if ens is not None: + inp = inp.unsqueeze(0).expand(ens, *inp.shape) + logits = self._value_net("modules_critic/value_net", inp, ens) + qs = hl_gauss_from_logits(logits) + if ens is None or not aggregate: + return qs + return qs.min(dim=0).values if self.q_agg == "min" else qs.mean(dim=0) + + @torch.no_grad() + def v(self, obs): + """obs [B, d] -> V [B] (the expectile value head; num_ensembles=1, so no ensemble axis).""" + obs = torch.as_tensor(obs, dtype=torch.float32, device=self.device) + return hl_gauss_from_logits(self._value_net("modules_value/value_net", obs, None)) + + @torch.no_grad() + def flow_velocity(self, obs, actions, t): + inp = torch.cat([obs, actions, _embed_times(t)], -1) + if self.mlp_class == "resmlp": + return _residual_mlp(self.P, "modules_actor_flow/mlp", inp, self.n_actor_blocks, + self.actor_layer_norm, None) + return _plain_mlp(self.P, "modules_actor_flow/mlp", inp, self.n_actor_blocks, + self.actor_layer_norm, None) + + @torch.no_grad() + def flow_candidates(self, obs, num_samples=None, generator=None, noise=None): + """obs [B, d] -> candidate actions [B, N, adim]: N unit normals pushed through `flow_steps` Euler + steps of the behavioural flow, clipped to [-1, 1] (agents/ifql.py sample_actions, verbatim).""" + obs = torch.as_tensor(obs, dtype=torch.float32, device=self.device) + B = obs.shape[0] + N = int(num_samples if num_samples is not None else self.num_samples) + if noise is None: + # A torch.Generator is bound to one device, and callers seed a CPU one (it is the eval seed, + # which must give the same draws wherever the job lands), so draw on the generator's own + # device and move. Passing a CPU generator with device="cuda" is a hard error. + dev = self.device if generator is None else torch.device(getattr(generator, "device", "cpu")) + noise = torch.randn(B, N, self.action_dim, generator=generator, device=dev) + a = noise.to(device=self.device, dtype=torch.float32).reshape(B, N, self.action_dim) + o = obs.unsqueeze(1).expand(B, N, obs.shape[-1]) + for i in range(self.flow_steps): + t = torch.full((B, N, 1), i / self.flow_steps, device=self.device, dtype=torch.float32) + a = a + self.flow_velocity(o, a, t) / self.flow_steps + return torch.clamp(a, -1.0, 1.0) + + @torch.no_grad() + def sample_actions(self, obs, num_samples=None, generator=None, noise=None, return_all=False): + """IFQL's action: arg-max Q over `num_samples` flow samples. obs [B, d] -> [B, adim].""" + cand = self.flow_candidates(obs, num_samples=num_samples, generator=generator, noise=noise) + B, N, A = cand.shape + q = self.q(obs.repeat_interleave(N, 0) if torch.is_tensor(obs) else + torch.as_tensor(obs, dtype=torch.float32, device=self.device).repeat_interleave(N, 0), + cand.reshape(B * N, A)).reshape(B, N) + idx = q.argmax(1) + act = cand[torch.arange(B, device=cand.device), idx] + return (act, cand, q, idx) if return_all else act + + def describe(self): + return {"backend": "ifql", "ckpt": self.path, "task": self.task, "seed": self.seed, + "train_step": self.step, "obs_mode": self.obs_mode, "n_critics": self.n_critics, + "q_agg": self.q_agg, "num_samples": self.num_samples, "flow_steps": self.flow_steps, + "mlp_class": self.mlp_class, "action_dim": self.action_dim, + "feat_stats": self.feat_stats, + "scored": "first action of the chunk, HL-Gauss Q, mean over the critic ensemble"} diff --git a/code_src/rise_robomimic/robomimic/algo/iql.py b/code_src/rise_robomimic/robomimic/algo/iql.py new file mode 100644 index 0000000000000000000000000000000000000000..6ef93f9b5ab9500ab4a1775579b9845f71409f5a --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/iql.py @@ -0,0 +1,426 @@ +""" +Implementation of Implicit Q-Learning (IQL). +Based off of https://github.com/rail-berkeley/rlkit/blob/master/rlkit/torch/sac/iql_trainer.py. +(Paper - https://arxiv.org/abs/2110.06169). +""" +import numpy as np +from collections import OrderedDict + +import torch +import torch.nn as nn +import torch.nn.functional as F + +import robomimic.models.policy_nets as PolicyNets +import robomimic.models.value_nets as ValueNets +import robomimic.utils.obs_utils as ObsUtils +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.torch_utils as TorchUtils +from robomimic.algo import register_algo_factory_func, ValueAlgo, PolicyAlgo + + +@register_algo_factory_func("iql") +def algo_config_to_class(algo_config): + """ + Maps algo config to the IQL algo class to instantiate, along with additional algo kwargs. + + Args: + algo_config (Config instance): algo config + + Returns: + algo_class: subclass of Algo + algo_kwargs (dict): dictionary of additional kwargs to pass to algorithm + """ + return IQL, {} + + +class IQL(PolicyAlgo, ValueAlgo): + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + + Networks for this algo: critic (potentially ensemble), actor, value function + """ + + # Create nets + self.nets = nn.ModuleDict() + + # Assemble args to pass to actor + actor_args = dict(self.algo_config.actor.net.common) + + # Add network-specific args and define network class + if self.algo_config.actor.net.type == "gaussian": + actor_cls = PolicyNets.GaussianActorNetwork + actor_args.update(dict(self.algo_config.actor.net.gaussian)) + elif self.algo_config.actor.net.type == "gmm": + actor_cls = PolicyNets.GMMActorNetwork + actor_args.update(dict(self.algo_config.actor.net.gmm)) + else: + # Unsupported actor type! + raise ValueError(f"Unsupported actor requested. " + f"Requested: {self.algo_config.actor.net.type}, " + f"valid options are: {['gaussian', 'gmm']}") + + # Actor + self.nets["actor"] = actor_cls( + obs_shapes=self.obs_shapes, + goal_shapes=self.goal_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.actor.layer_dims, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + **actor_args, + ) + + # Critics + self.nets["critic"] = nn.ModuleList() + self.nets["critic_target"] = nn.ModuleList() + for _ in range(self.algo_config.critic.ensemble.n): + for net_list in (self.nets["critic"], self.nets["critic_target"]): + critic = ValueNets.ActionValueNetwork( + obs_shapes=self.obs_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.critic.layer_dims, + goal_shapes=self.goal_shapes, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + ) + net_list.append(critic) + + # Value function network + self.nets["vf"] = ValueNets.ValueNetwork( + obs_shapes=self.obs_shapes, + mlp_layer_dims=self.algo_config.critic.layer_dims, + goal_shapes=self.goal_shapes, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + ) + + # Send networks to appropriate device + self.nets = self.nets.float().to(self.device) + + # sync target networks at beginning of training + with torch.no_grad(): + for critic, critic_target in zip(self.nets["critic"], self.nets["critic_target"]): + TorchUtils.hard_update( + source=critic, + target=critic_target, + ) + + def process_batch_for_training(self, batch): + """ + Processes input batch from a data loader to filter out relevant info and prepare the batch for training. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader + + Returns: + input_batch (dict): processed and filtered batch that + will be used for training + """ + + input_batch = dict() + # remove temporal batches for all + input_batch["obs"] = {k: batch["obs"][k][:, 0, :] for k in batch["obs"]} + input_batch["next_obs"] = {k: batch["next_obs"][k][:, 0, :] for k in batch["next_obs"]} + input_batch["goal_obs"] = batch.get("goal_obs", None) # goals may not be present + input_batch["actions"] = batch["actions"][:, 0, :] + input_batch["dones"] = batch["dones"][:, 0] + input_batch["rewards"] = batch["rewards"][:, 0] + + return TensorUtils.to_device(TensorUtils.to_float(input_batch), self.device) + + def train_on_batch(self, batch, epoch, validate=False): + """ + Training on a single batch of data. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + validate (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + info = OrderedDict() + + # Set the correct context for this training step + with TorchUtils.maybe_no_grad(no_grad=validate): + # Always run super call first + info = super().train_on_batch(batch, epoch, validate=validate) + + # Compute loss for critic(s) + critic_losses, vf_loss, critic_info = self._compute_critic_loss(batch) + # Compute loss for actor + actor_loss, actor_info = self._compute_actor_loss(batch, critic_info) + + if not validate: + # Critic update + self._update_critic(critic_losses, vf_loss) + + # Actor update + self._update_actor(actor_loss) + + # Update info + info.update(actor_info) + info.update(critic_info) + + # Return stats + return info + + def _compute_critic_loss(self, batch): + """ + Helper function for computing Q and V losses. Called by @train_on_batch + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + Returns: + critic_losses (list): list of critic (Q function) losses + vf_loss (torch.Tensor): value function loss + info (dict): dictionary of Q / V predictions and losses + """ + info = OrderedDict() + + # get batch values + obs = batch["obs"] + actions = batch["actions"] + next_obs = batch["next_obs"] + goal_obs = batch["goal_obs"] + rewards = torch.unsqueeze(batch["rewards"], 1) + dones = torch.unsqueeze(batch["dones"], 1) + + # Q predictions + pred_qs = [critic(obs_dict=obs, acts=actions, goal_dict=goal_obs) + for critic in self.nets["critic"]] + + info["critic/critic1_pred"] = pred_qs[0].mean() + + # Q target values + target_vf_pred = self.nets["vf"](obs_dict=next_obs, goal_dict=goal_obs).detach() + q_target = rewards + (1. - dones) * self.algo_config.discount * target_vf_pred + q_target = q_target.detach() + + # Q losses + critic_losses = [] + td_loss_fcn = nn.SmoothL1Loss() if self.algo_config.critic.use_huber else nn.MSELoss() + for (i, q_pred) in enumerate(pred_qs): + # Calculate td error loss + td_loss = td_loss_fcn(q_pred, q_target) + info[f"critic/critic{i+1}_loss"] = td_loss + critic_losses.append(td_loss) + + # V predictions + pred_qs = [critic(obs_dict=obs, acts=actions, goal_dict=goal_obs) + for critic in self.nets["critic_target"]] + q_pred, _ = torch.cat(pred_qs, dim=1).min(dim=1, keepdim=True) + q_pred = q_pred.detach() + vf_pred = self.nets["vf"](obs_dict=obs, goal_dict=goal_obs) + + # V losses: expectile regression. see section 4.1 in https://arxiv.org/pdf/2110.06169.pdf + vf_err = vf_pred - q_pred + vf_sign = (vf_err > 0).float() + vf_weight = (1 - vf_sign) * self.algo_config.vf_quantile + vf_sign * (1 - self.algo_config.vf_quantile) + vf_loss = (vf_weight * (vf_err ** 2)).mean() + + # update logs for V loss + info["vf/q_pred"] = q_pred + info["vf/v_pred"] = vf_pred + info["vf/v_loss"] = vf_loss + + # Return stats + return critic_losses, vf_loss, info + + def _update_critic(self, critic_losses, vf_loss): + """ + Helper function for updating critic and vf networks. Called by @train_on_batch + + Args: + critic_losses (list): list of critic (Q function) losses + vf_loss (torch.Tensor): value function loss + """ + + # update ensemble of critics + for (critic_loss, critic, critic_target, optimizer) in zip( + critic_losses, self.nets["critic"], self.nets["critic_target"], self.optimizers["critic"] + ): + TorchUtils.backprop_for_loss( + net=critic, + optim=optimizer, + loss=critic_loss, + max_grad_norm=self.algo_config.critic.max_gradient_norm, + retain_graph=False, + ) + + # update target network + with torch.no_grad(): + TorchUtils.soft_update(source=critic, target=critic_target, tau=self.algo_config.target_tau) + + # update V function network + TorchUtils.backprop_for_loss( + net=self.nets["vf"], + optim=self.optimizers["vf"], + loss=vf_loss, + max_grad_norm=self.algo_config.critic.max_gradient_norm, + retain_graph=False, + ) + + def _compute_actor_loss(self, batch, critic_info): + """ + Helper function for computing actor loss. Called by @train_on_batch + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + critic_info (dict): dictionary containing Q and V function predictions, + to be used for computing advantage estimates + + Returns: + actor_loss (torch.Tensor): actor loss + info (dict): dictionary of actor losses, log_probs, advantages, and weights + """ + info = OrderedDict() + + # compute log probability of batch actions + dist = self.nets["actor"].forward_train(obs_dict=batch["obs"], goal_dict=batch["goal_obs"]) + log_prob = dist.log_prob(batch["actions"]) + + info["actor/log_prob"] = log_prob.mean() + + # compute advantage estimate + q_pred = critic_info["vf/q_pred"] + v_pred = critic_info["vf/v_pred"] + adv = q_pred - v_pred + + # compute weights + weights = self._get_adv_weights(adv) + + # compute advantage weighted actor loss. disable gradients through weights + actor_loss = (-log_prob * weights.detach()).mean() + + info["actor/loss"] = actor_loss + + # log adv-related values + info["adv/adv"] = adv + info["adv/adv_weight"] = weights + + # Return stats + return actor_loss, info + + def _update_actor(self, actor_loss): + """ + Helper function for updating actor network. Called by @train_on_batch + + Args: + actor_loss (torch.Tensor): actor loss + """ + + TorchUtils.backprop_for_loss( + net=self.nets["actor"], + optim=self.optimizers["actor"], + loss=actor_loss, + max_grad_norm=self.algo_config.actor.max_gradient_norm, + ) + + def _get_adv_weights(self, adv): + """ + Helper function for computing advantage weights. Called by @_compute_actor_loss + + Args: + adv (torch.Tensor): raw advantage estimates + + Returns: + weights (torch.Tensor): weights computed based on advantage estimates, + in shape (B,) where B is batch size + """ + + # clip raw advantage values + if self.algo_config.adv.clip_adv_value is not None: + adv = adv.clamp(max=self.algo_config.adv.clip_adv_value) + + # compute weights based on advantage values + beta = self.algo_config.adv.beta # temprature factor + weights = torch.exp(adv / beta) + # clip final weights + if self.algo_config.adv.use_final_clip is True: + weights = weights.clamp(-100.0, 100.0) + + # reshape from (B, 1) to (B,) + return weights[:, 0] + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + log = OrderedDict() + + log["actor/log_prob"] = info["actor/log_prob"].item() + log["actor/loss"] = info["actor/loss"].item() + + log["critic/critic1_pred"] = info["critic/critic1_pred"].item() + log["critic/critic1_loss"] = info["critic/critic1_loss"].item() + + log["vf/v_loss"] = info["vf/v_loss"].item() + + self._log_data_attributes(log, info, "vf/q_pred") + self._log_data_attributes(log, info, "vf/v_pred") + self._log_data_attributes(log, info, "adv/adv") + self._log_data_attributes(log, info, "adv/adv_weight") + + return log + + def _log_data_attributes(self, log, info, key): + """ + Helper function for logging statistics. Moodifies log in-place + + Args: + log (dict): existing log dictionary + log (dict): existing dictionary of tensors containing raw stats + key (str): key to log + """ + log[key + "/max"] = info[key].max().item() + log[key + "/min"] = info[key].min().item() + log[key + "/mean"] = info[key].mean().item() + log[key + "/std"] = info[key].std().item() + + def on_epoch_end(self, epoch): + """ + Called at the end of each epoch. + """ + + # LR scheduling updates + for lr_sc in self.lr_schedulers["critic"]: + if lr_sc is not None: + lr_sc.step() + + if self.lr_schedulers["vf"] is not None: + self.lr_schedulers["vf"].step() + + if self.lr_schedulers["actor"] is not None: + self.lr_schedulers["actor"].step() + + def get_action(self, obs_dict, goal_dict=None): + """ + Get policy action outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + action (torch.Tensor): action tensor + """ + assert not self.nets.training + + return self.nets["actor"](obs_dict=obs_dict, goal_dict=goal_dict) \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/algo/iql_diffusion.py b/code_src/rise_robomimic/robomimic/algo/iql_diffusion.py new file mode 100644 index 0000000000000000000000000000000000000000..f3da25dc42e6d48dc600a0898834fda59ff6e5c5 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/iql_diffusion.py @@ -0,0 +1,1145 @@ +""" +Implementation of Implicit Q-Learning (IQL). +Based off of https://github.com/rail-berkeley/rlkit/blob/master/rlkit/torch/sac/iql_trainer.py. +(Paper - https://arxiv.org/abs/2110.06169). +""" +import numpy as np +import copy +from collections import OrderedDict + +import math +import torch +import torch.nn as nn +import torch.nn.functional as F + +import robomimic.models.policy_nets as PolicyNets +import robomimic.models.value_nets as ValueNets +import robomimic.utils.obs_utils as ObsUtils +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.torch_utils as TorchUtils +import robomimic.models.obs_nets as ObsNets + +from typing import Callable, Union +from packaging.version import parse as parse_version +from enum import Enum +from diffusers.schedulers.scheduling_ddpm import DDPMScheduler +from diffusers.schedulers.scheduling_ddim import DDIMScheduler +from diffusers.training_utils import EMAModel + +from robomimic.algo import register_algo_factory_func, ValueAlgo, PolicyAlgo +from robomimic.algo.rsm_planner import RSMPlannerMixin + +from diffusion_policy.model.diffusion.mask_generator import LowdimMaskGenerator + + +class MultiStepMethod(Enum): + REPEAT = 'repeat' + ONE_STEP = 'one_step' + MULTI_STEP = 'multi_step' + +@register_algo_factory_func("iql_diffusion") +def algo_config_to_class(algo_config): + """ + Maps algo config to the IQL algo class to instantiate, along with additional algo kwargs. + + Args: + algo_config (Config instance): algo config + + Returns: + algo_class: subclass of Algo + algo_kwargs (dict): dictionary of additional kwargs to pass to algorithm + """ + return IQLDiffusion, {} + + +class IQLDiffusion(RSMPlannerMixin, PolicyAlgo, ValueAlgo): + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + + Networks for this algo: critic (potentially ensemble), actor, value function + """ + try: + self.multi_step_method = MultiStepMethod(self.algo_config.multi_step_method) + except RuntimeError: + self.multi_step_method = MultiStepMethod.ONE_STEP + + # Create nets + self.nets = nn.ModuleDict() + + observation_group_shapes = OrderedDict() + observation_group_shapes["obs"] = OrderedDict(self.obs_shapes) + encoder_kwargs = ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder) + + try: + stochastic = self.algo_config.bottleneck_policy + except RuntimeError: + stochastic = False + try: + spectral_norm = self.algo_config.spectral_norm_policy + except RuntimeError: + spectral_norm = False + obs_encoder = ObsNets.ObservationGroupEncoder( + observation_group_shapes=observation_group_shapes, + encoder_kwargs=encoder_kwargs, + stochastic=stochastic, + spectral_norm=spectral_norm, + ) + # IMPORTANT! + # replace all BatchNorm with GroupNorm to work with EMA + # performance will tank if you forget to do this! + obs_encoder = replace_bn_with_gn(obs_encoder) + + obs_dim = obs_encoder.output_shape()[0] + + # create network object + noise_pred_net = ConditionalUnet1D( + input_dim=self.ac_dim, + down_dims=self.algo_config.unet.down_dims, + diffusion_step_embed_dim=self.algo_config.unet.diffusion_step_embed_dim, + global_cond_dim=obs_dim*self.algo_config.horizon.observation_horizon, + no_chunking=self.algo_config.horizon.prediction_horizon==1, + ) + + # the final arch has 2 parts + self.nets = nn.ModuleDict({ + 'policy': nn.ModuleDict({ + 'obs_encoder': obs_encoder, + 'noise_pred_net': noise_pred_net + }) + }) + + + # self.mask_generator = LowdimMaskGenerator( + # action_dim=self.ac_dim, + # obs_dim=0 if (obs_as_cond) else obs_feature_dim, + # max_n_obs_steps=self.algo_config.horizon.observation_horizon, + # fix_obs_steps=True, + # action_visible=False + # ) + + # setup noise scheduler + noise_scheduler = None + if self.algo_config.ddpm.enabled: + noise_scheduler = DDPMScheduler( + num_train_timesteps=self.algo_config.ddpm.num_train_timesteps, + beta_schedule=self.algo_config.ddpm.beta_schedule, + clip_sample=self.algo_config.ddpm.clip_sample, + prediction_type=self.algo_config.ddpm.prediction_type + ) + elif self.algo_config.ddim.enabled: + noise_scheduler = DDIMScheduler( + num_train_timesteps=self.algo_config.ddim.num_train_timesteps, + beta_schedule=self.algo_config.ddim.beta_schedule, + clip_sample=self.algo_config.ddim.clip_sample, + set_alpha_to_one=self.algo_config.ddim.set_alpha_to_one, + steps_offset=self.algo_config.ddim.steps_offset, + prediction_type=self.algo_config.ddim.prediction_type + ) + else: + raise RuntimeError() + + # rsm_rise E2: an RSM checkpoint replaces the IQL critic/vf as the advantage source + # (robomimic/algo/rsm_scorer.py). No critic/vf nets are built or updated in that case. + try: + rsm_ckpt = self.algo_config.rsm_ckpt + except RuntimeError: + rsm_ckpt = "" + self.rsm_adv_enabled = bool(rsm_ckpt) and not self.algo_config.use_bc + self._planner_scorer = None + + # Critics + self.nets["critic"] = nn.ModuleList() + self.nets["critic_target"] = nn.ModuleList() + try: + stochastic = self.algo_config.bottleneck_value + except RuntimeError: + stochastic = False + try: + spectral_norm = self.algo_config.spectral_norm_value + except RuntimeError: + spectral_norm = False + n_critics = 0 if self.rsm_adv_enabled else self.algo_config.critic.ensemble.n + for _ in range(n_critics): + for net_list in (self.nets["critic"], self.nets["critic_target"]): + critic = ValueNets.ActionValueNetwork( + obs_shapes=self.obs_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.critic.layer_dims, + goal_shapes=self.goal_shapes, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + stochastic_encoder=stochastic, + spectral_norm=spectral_norm, + ) + net_list.append(critic) + + # Value function network + if not self.rsm_adv_enabled: + self.nets["vf"] = ValueNets.ValueNetwork( + obs_shapes=self.obs_shapes, + mlp_layer_dims=self.algo_config.critic.layer_dims, + goal_shapes=self.goal_shapes, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + stochastic_encoder=False, + spectral_norm=False, + ) + + try: + if self.algo_config.lipschitz: + self.nets['policy']['slack_var_net'] = ValueNets.ActionValueNetwork = ValueNets.ActionValueNetwork( + obs_shapes=self.obs_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.critic.layer_dims, + goal_shapes=self.goal_shapes, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + stochastic_encoder=False, + spectral_norm=False, + ) + except: + pass + + # Send networks to appropriate device + self.nets = self.nets.float().to(self.device) + + # setup EMA + ema = None + if self.algo_config.ema.enabled: + ema = EMAModel(parameters=self.nets.parameters(), power=self.algo_config.ema.power, use_ema_warmup=True) + + self.noise_scheduler = noise_scheduler + self.ema = ema + self.action_check_done = False + + # sync target networks at beginning of training + with torch.no_grad(): + for critic, critic_target in zip(self.nets["critic"], self.nets["critic_target"]): + TorchUtils.hard_update( + source=critic, + target=critic_target, + ) + + def process_batch_for_training(self, batch): + """ + Processes input batch from a data loader to filter out relevant info and prepare the batch for training. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader + + Returns: + input_batch (dict): processed and filtered batch that + will be used for training + """ + + input_batch = dict() + + To = self.algo_config.horizon.observation_horizon + Tp = self.algo_config.horizon.prediction_horizon + + input_batch["obs"] = {k: batch["obs"][k][:, :(To + Tp - 1), :] for k in batch["obs"]} + # TODO: check this + if not self.algo_config.use_bc: + input_batch["next_obs"] = {k: batch["next_obs"][k][:, :(To + Tp - 1), :] for k in batch["next_obs"]} + input_batch["goal_obs"] = batch.get("goal_obs", None) # goals may not be present + input_batch["actions"] = batch["actions"][:, (To - 1):(Tp + To - 1), :] + input_batch["dones"] = batch["dones"][:, (To - 1):(Tp + To - 1)] + input_batch["rewards"] = batch["rewards"][:, (To - 1):(Tp + To - 1)] + + return TensorUtils.to_device(TensorUtils.to_float(input_batch), self.device) + + def train_on_batch(self, batch, epoch, validate=False): + """ + Training on a single batch of data. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + validate (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + Tp = self.algo_config.horizon.prediction_horizon + info = OrderedDict() + + actor_freeze_until_epoch = self.algo_config.optim_params.policy.freeze_until_epoch + if actor_freeze_until_epoch is None: + actor_freeze_until_epoch = -1 + + # Set the correct context for this training step + with TorchUtils.maybe_no_grad(no_grad=validate): + # Always run super call first + info = super().train_on_batch(batch, epoch, validate=validate) + + if self.multi_step_method == MultiStepMethod.REPEAT: + q_preds = [] + v_preds = [] + for i in range(Tp): + # Compute loss for critic(s) + if not self.algo_config.use_bc: + critic_losses, vf_loss, critic_info = self._compute_critic_loss(batch, i) + q_preds.append(critic_info["vf/q_pred"]) + v_preds.append(critic_info["vf/v_pred"]) + + if not validate: + # Critic update + self._update_critic(critic_losses, vf_loss) + + # Compute loss for actor + actor_loss, actor_info = self._compute_actor_loss(batch, q_preds, v_preds) + + if not validate and epoch >= actor_freeze_until_epoch: + # Actor update + self._update_actor(actor_loss) + elif self.multi_step_method == MultiStepMethod.ONE_STEP: + # Compute loss for critic(s) + if self.rsm_adv_enabled: + # rsm_rise E2: frozen successor model supplies Q̄ / V̄ for this exact batch + critic_info = self._rsm_advantage(batch) + q_pred = critic_info["vf/q_pred"] + v_pred = critic_info["vf/v_pred"] + elif not self.algo_config.use_bc: + critic_losses, vf_loss, critic_info = self._compute_critic_loss(batch) + q_pred = critic_info["vf/q_pred"] + v_pred = critic_info["vf/v_pred"] + else: + q_pred = None + v_pred = None + # Compute loss for actor + actor_loss, actor_info = self._compute_actor_loss(batch, q_pred, v_pred) + + if not validate: + # Critic update + if not self.algo_config.use_bc and not self.rsm_adv_enabled: + self._update_critic(critic_losses, vf_loss) + + # Actor update + if epoch >= actor_freeze_until_epoch: + self._update_actor(actor_loss) + else: + raise NotImplementedError + + # Update info + info.update(actor_info) + if not self.algo_config.use_bc: + info.update(critic_info) + + # Return stats + return info + + def _rsm_advantage(self, batch): + """ + rsm_rise E2: Q̄(x_t, A_t) and V̄_τ(x_t) from the frozen successor model at the batch's current + frame (To-1) for the first plan_chunk actions of the (kNN-swapped) chunk, computed per batch, + nothing cached. Returns critic_info with "vf/q_pred" / "vf/v_pred" [B,1] so _compute_actor_loss + and _get_adv_weights run unchanged. + rsm_adv_scale = td : Q̄/(1-γ), V̄/(1-γ) (advantage on the discounted-return scale) + rsm_adv_scale = std: (adv - mean)/std, v = 0 (batch-standardised advantage) + rsm_adv_permute : S3H6 control, the (q, v) pairs are permuted within the batch. + """ + cfg = self.planner_cfg() + scorer = self._get_scorer() + To = self.algo_config.horizon.observation_horizon + obs_t = {k: batch["obs"][k][:, To - 1] for k in batch["obs"]} + A = batch["actions"][:, :int(cfg["plan_chunk"])] + with torch.no_grad(): + st = scorer.state_from_obs(obs_t) + q, v, qm = scorer.advantage(st, A, v_samples=int(cfg["rsm_adv_v_samples"]), + v_expectile=float(cfg["rsm_adv_v_expectile"]), + seed=None if int(cfg["plan_seed"]) < 0 else int(cfg["plan_seed"])) + info = OrderedDict() + info["rsm/qbar"] = q.detach() + info["rsm/vbar"] = v.detach() + info["rsm/qbar_hop_std"] = qm.std(1).detach() + scale = str(cfg["rsm_adv_scale"]) + if scale == "td": + gamma = float(self.algo_config.discount) + q_pred, v_pred = q / (1.0 - gamma), v / (1.0 - gamma) + elif scale == "std": + adv = q - v + q_pred = (adv - adv.mean()) / (adv.std() + 1e-6) + v_pred = torch.zeros_like(q_pred) + else: + raise ValueError(f"rsm_adv_scale={scale}; use td or std") + if bool(cfg["rsm_adv_permute"]): + perm = torch.randperm(q_pred.shape[0], device=q_pred.device) + q_pred, v_pred = q_pred[perm], v_pred[perm] + info["vf/q_pred"] = q_pred.detach()[:, None] + info["vf/v_pred"] = v_pred.detach()[:, None] + return info + + def _compute_critic_loss(self, batch, i=0): + """ + Helper function for computing Q and V losses. Called by @train_on_batch + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + i (int): timestep + + Returns: + critic_losses (list): list of critic (Q function) losses + vf_loss (torch.Tensor): value function loss + info (dict): dictionary of Q / V predictions and losses + """ + info = OrderedDict() + To = self.algo_config.horizon.observation_horizon + Tp = self.algo_config.horizon.prediction_horizon + + # get batch values + obs = {k: batch["obs"][k][:, To - 1 + i, :] for k in batch["obs"]} + actions = batch["actions"][:, i, :] + next_obs = {k: batch["next_obs"][k][:, To - 1 + i, :] for k in batch["next_obs"]} + goal_obs = batch["goal_obs"] + rewards = torch.unsqueeze(batch["rewards"][:, i], 1) + dones = torch.unsqueeze(batch["dones"][:, i], 1) + + # Q predictions + pred_qs = [critic(obs_dict=obs, acts=actions, goal_dict=goal_obs) + for critic in self.nets["critic"]] + + info["critic/critic1_pred"] = pred_qs[0].mean() + + # Q target values + target_vf_pred = self.nets["vf"](obs_dict=next_obs, goal_dict=goal_obs).detach() + q_target = rewards + (1. - dones) * self.algo_config.discount * target_vf_pred + q_target = q_target.detach() + + # Q losses + critic_losses = [] + td_loss_fcn = nn.SmoothL1Loss() if self.algo_config.critic.use_huber else nn.MSELoss() + for (i, q_pred) in enumerate(pred_qs): + # Calculate td error loss + td_loss = td_loss_fcn(q_pred, q_target) + info[f"critic/critic{i+1}_loss"] = td_loss + + # add KL divergence loss if bottleneck is enabled + if self.algo_config.bottleneck_value: + # compute KL divergence between encoder distribution and standard normal + mean = self.nets["critic"][i].nets["encoder"].nets['obs'].computed_mean + logvar = self.nets["critic"][i].nets["encoder"].nets['obs'].computed_logvar + + # KL divergence between N(mean, std) and N(0, 1) + kl_div = -0.5 * torch.sum(1 + logvar - mean.pow(2) - logvar.exp(), dim=1).mean() + + # add KL term to critic loss with weight + td_loss = td_loss + self.algo_config.q_bottleneck_beta * kl_div + info[f"critic/critic{i+1}_kl_div"] = kl_div + elif self.algo_config.spectral_norm_value: + spectral_norm = self.nets["critic"][i].nets["encoder"].nets['obs'].spectral_norm + td_loss = td_loss + self.algo_config.q_bottleneck_beta * spectral_norm + info[f"critic/critic{i+1}_spectral_norm"] = spectral_norm + + critic_losses.append(td_loss) + + # V predictions + pred_qs = [critic(obs_dict=obs, acts=actions, goal_dict=goal_obs) + for critic in self.nets["critic_target"]] + q_pred, _ = torch.cat(pred_qs, dim=1).min(dim=1, keepdim=True) + q_pred = q_pred.detach() + vf_pred = self.nets["vf"](obs_dict=obs, goal_dict=goal_obs) + + # V losses: expectile regression. see section 4.1 in https://arxiv.org/pdf/2110.06169.pdf + vf_err = vf_pred - q_pred + vf_sign = (vf_err > 0).float() + vf_weight = (1 - vf_sign) * self.algo_config.vf_quantile + vf_sign * (1 - self.algo_config.vf_quantile) + vf_loss = (vf_weight * (vf_err ** 2)).mean() + + # update logs for V loss + info["vf/q_pred"] = q_pred + info["vf/v_pred"] = vf_pred + info["vf/v_loss"] = vf_loss + + # Return stats + return critic_losses, vf_loss, info + + def _update_critic(self, critic_losses, vf_loss): + """ + Helper function for updating critic and vf networks. Called by @train_on_batch + + Args: + critic_losses (list): list of critic (Q function) losses + vf_loss (torch.Tensor): value function loss + """ + + # update ensemble of critics + for (critic_loss, critic, critic_target, optimizer) in zip( + critic_losses, self.nets["critic"], self.nets["critic_target"], self.optimizers["critic"] + ): + TorchUtils.backprop_for_loss( + net=critic, + optim=optimizer, + loss=critic_loss, + max_grad_norm=self.algo_config.critic.max_gradient_norm, + retain_graph=False, + ) + + # update target network + with torch.no_grad(): + TorchUtils.soft_update(source=critic, target=critic_target, tau=self.algo_config.target_tau) + + # update V function network + TorchUtils.backprop_for_loss( + net=self.nets["vf"], + optim=self.optimizers["vf"], + loss=vf_loss, + max_grad_norm=self.algo_config.critic.max_gradient_norm, + retain_graph=False, + ) + + def _compute_actor_loss(self, batch, q_pred, v_pred): + """ + Helper function for computing actor loss. Called by @train_on_batch + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + critic_info (dict): dictionary containing Q and V function predictions, + to be used for computing advantage estimates + + Returns: + actor_loss (torch.Tensor): actor loss + info (dict): dictionary of actor losses, log_probs, advantages, and weights + """ + B = batch['actions'].shape[0] + + info = OrderedDict() + actions = batch['actions'] + + To = self.algo_config.horizon.observation_horizon + + # encode obs + inputs = { + 'obs': {k: batch["obs"][k][:, :To, :] for k in batch["obs"]}, + 'goal': batch["goal_obs"] + } + + for k in self.obs_shapes: + # first two dimensions should be [B, T] for inputs + assert inputs['obs'][k].ndim - 2 == len(self.obs_shapes[k]) + + obs_features = TensorUtils.time_distributed(inputs, self.nets['policy']['obs_encoder'], inputs_as_kwargs=True) + assert obs_features.ndim == 3 # [B, T, D] + + obs_cond = obs_features.flatten(start_dim=1) + + # inpainting mask + # condition_mask = self.mask_generator(actions.shape) + + # sample noise to add to actions + noise = torch.randn(actions.shape, device=self.device) + + # sample a diffusion iteration for each data point + timesteps = torch.randint( + 0, self.noise_scheduler.config.num_train_timesteps, + (B,), device=self.device + ).long() + + # add noise to the clean actions according to the noise magnitude at each diffusion iteration + # (this is the forward diffusion process) + noisy_actions = self.noise_scheduler.add_noise( + actions, noise, timesteps) + + # # compute loss mask + # loss_mask = ~condition_mask + + # # apply conditioning + # noisy_actions[condition_mask] = actions[condition_mask] + # predict the noise residual + noise_pred = self.nets['policy']['noise_pred_net']( + noisy_actions, timesteps, global_cond=obs_cond) + + # L2 loss + bc_loss = F.mse_loss(noise_pred, noise) + + self.ema.step(self.nets['policy'].parameters()) + + info["actor/bc_loss"] = bc_loss.mean() + + if not self.algo_config.use_bc: + # compute advantage estimate + if self.multi_step_method == MultiStepMethod.REPEAT: + q_pred = torch.stack(q_pred) + v_pred = torch.stack(v_pred) + discounts = self.algo_config.discount ** torch.arange(len(q_pred), dtype=torch.float32, device=self.device).reshape(len(q_pred), 1, 1) + adv = torch.sum(discounts * (q_pred - v_pred), dim=0) + elif self.multi_step_method == MultiStepMethod.ONE_STEP: + adv = q_pred - v_pred + + # compute weights + weights = self._get_adv_weights(adv) + + if self.algo_config.use_bc: + actor_loss = (bc_loss).mean() + else: + # compute advantage weighted actor loss. disable gradients through weights + actor_loss = (bc_loss * weights.detach()).mean() + + if self.algo_config.bottleneck_policy: + # add information bottleneck KL divergence loss + # compute KL divergence between encoder distribution and standard normal + mean = self.nets['policy']['obs_encoder'].nets['obs'].computed_mean + logvar = self.nets['policy']['obs_encoder'].nets['obs'].computed_logvar + + # KL divergence between N(mean, std) and N(0, 1) + kl_div = -0.5 * torch.sum(1 + logvar - mean.pow(2) - logvar.exp(), dim=1).mean() + + # add KL term to actor loss with weight + actor_loss = actor_loss + self.algo_config.policy_bottleneck_beta * kl_div + info["actor/kl_div"] = kl_div + elif self.algo_config.spectral_norm_policy: + spectral_norm = self.nets['policy']['obs_encoder'].nets['obs'].spectral_norm + actor_loss = actor_loss + self.algo_config.policy_bottleneck_beta * spectral_norm + info["actor/spectral_norm"] = spectral_norm + elif self.algo_config.lipschitz: + n_samples = 5 + + obs_cond_extended = torch.repeat_interleave(obs_cond, n_samples, dim=0) + noisy_actions_extended = torch.repeat_interleave(noisy_actions, n_samples, dim=0) + obs_cond_noise = torch.randn_like(obs_cond_extended, device=self.device) + timesteps_extended = torch.randint( + 0, self.noise_scheduler.config.num_train_timesteps, + (B*n_samples,), device=self.device + ).long() + # enforce lipschitz on the first action only if action chunking + noise_pred_extended = torch.repeat_interleave(noise_pred, n_samples, dim=0)[:, 0] + noise_pred_noise = self.nets['policy']['noise_pred_net']( + noisy_actions_extended, timesteps_extended, global_cond=obs_cond_noise)[:, 0] + output_diff = torch.linalg.norm(noise_pred_noise - noise_pred_extended, dim=-1) + noise_magnitude = torch.linalg.norm(obs_cond_noise, dim=-1) + lipschitz_penalty = torch.relu(output_diff - self.algo_config.lipschitz_constant * noise_magnitude) + # reshape lipschitz penalty from (B*n_samples, D1, D2, ...) to (B, n_samples, D1, D2, ...) + lipschitz_penalty = lipschitz_penalty.reshape(B, n_samples, *lipschitz_penalty.shape[1:]) + # take mean over n_samples dimension + lipschitz_penalty = lipschitz_penalty.mean(dim=1) + obs_dict = {k: batch["obs"][k][:, To - 1, :] for k in batch["obs"]} + actions = batch['actions'][:, 0, :] + slack = self.nets['policy']['slack_var_net'](obs_dict=obs_dict, acts=actions)[:, 0] + lipschitz_penalty = slack * lipschitz_penalty + 1 - torch.exp(-0.1 * torch.abs(slack).mean()) + lipschitz_penalty = self.algo_config.lipschitz_weight * lipschitz_penalty.mean() + + actor_loss = actor_loss + lipschitz_penalty + + info["actor/lipschitz_penalty"] = lipschitz_penalty + + info["actor/loss"] = actor_loss + + if not self.algo_config.use_bc: + # log adv-related values + info["adv/adv"] = adv + info["adv/adv_weight"] = weights + + # Return stats + return actor_loss, info + + def _update_actor(self, actor_loss): + """ + Helper function for updating actor network. Called by @train_on_batch + + Args: + actor_loss (torch.Tensor): actor loss + """ + + TorchUtils.backprop_for_loss( + net=self.nets['policy'], + optim=self.optimizers['policy'], + loss=actor_loss, + ) + + def _get_adv_weights(self, adv): + """ + Helper function for computing advantage weights. Called by @_compute_actor_loss + + Args: + adv (torch.Tensor): raw advantage estimates + + Returns: + weights (torch.Tensor): weights computed based on advantage estimates, + in shape (B,) where B is batch size + """ + + # clip raw advantage values + if self.algo_config.adv.clip_adv_value is not None: + adv = adv.clamp(max=self.algo_config.adv.clip_adv_value) + + # compute weights based on advantage values + beta = self.algo_config.adv.beta # temprature factor + weights = torch.exp(adv / beta) + # clip final weights + if self.algo_config.adv.use_final_clip is True: + weights = weights.clamp(-100.0, 100.0) + + # reshape from (B, 1) to (B,) + return weights[:, 0] + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + log = OrderedDict() + + log["actor/bc_loss"] = info["actor/bc_loss"].item() + log["actor/loss"] = info["actor/loss"].item() + + if not self.algo_config.use_bc: + if "critic/critic1_pred" in info: + log["critic/critic1_pred"] = info["critic/critic1_pred"].item() + log["critic/critic1_loss"] = info["critic/critic1_loss"].item() + log["vf/v_loss"] = info["vf/v_loss"].item() + for k in ("rsm/qbar", "rsm/vbar", "rsm/qbar_hop_std"): + if k in info: + self._log_data_attributes(log, info, k) + + self._log_data_attributes(log, info, "vf/q_pred") + self._log_data_attributes(log, info, "vf/v_pred") + self._log_data_attributes(log, info, "adv/adv") + self._log_data_attributes(log, info, "adv/adv_weight") + + if self.algo_config.bottleneck_policy: + self._log_data_attributes(log, info, "actor/kl_div") + if self.algo_config.bottleneck_value: + self._log_data_attributes(log, info, "critic/critic1_kl_div") + if self.algo_config.spectral_norm_value: + self._log_data_attributes(log, info, "critic/critic1_spectral_norm") + if self.algo_config.spectral_norm_policy: + self._log_data_attributes(log, info, "actor/spectral_norm") + if self.algo_config.lipschitz: + self._log_data_attributes(log, info, "actor/lipschitz_penalty") + return log + + def _log_data_attributes(self, log, info, key): + """ + Helper function for logging statistics. Moodifies log in-place + + Args: + log (dict): existing log dictionary + log (dict): existing dictionary of tensors containing raw stats + key (str): key to log + """ + log[key + "/max"] = info[key].max().item() + log[key + "/min"] = info[key].min().item() + log[key + "/mean"] = info[key].mean().item() + log[key + "/std"] = info[key].std().item() + + def on_epoch_end(self, epoch): + """ + Called at the end of each epoch. + """ + + # LR scheduling updates + for lr_sc in self.lr_schedulers.get("critic", []): + if lr_sc is not None: + lr_sc.step() + + if self.lr_schedulers.get("vf", None) is not None: + self.lr_schedulers["vf"].step() + + if self.lr_schedulers["policy"] is not None: + self.lr_schedulers["policy"].step() + + def get_action(self, obs_dict, goal_dict=None): + """ + Get policy action outputs. plan_n <= 1 (default) is the released path: one diffusion sample, + the Ta-step executed window. plan_n > 1: best-of-N over the sampler with the RSM scorer + (robomimic/algo/rsm_planner.py, rsm_rise E1). + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + action (torch.Tensor): action tensor + """ + return self.plan_get_action(obs_dict, goal_dict) + + def _sample_action_chunks(self, obs_dict, goal_dict=None): + """The released sampler, unchanged: one DDPM/DDIM chain per batch row -> naction [B, Tp, ac].""" + To = self.algo_config.horizon.observation_horizon + Ta = self.algo_config.horizon.action_horizon + Tp = self.algo_config.horizon.prediction_horizon + action_dim = self.ac_dim + if self.algo_config.ddpm.enabled is True: + num_inference_timesteps = self.algo_config.ddpm.num_inference_timesteps + elif self.algo_config.ddim.enabled is True: + num_inference_timesteps = self.algo_config.ddim.num_inference_timesteps + else: + raise ValueError + + # select network + nets = self.nets + # if self.ema is not None: + # nets = self.ema_model + + # encode obs + inputs = { + 'obs': obs_dict, + 'goal': goal_dict + } + + for k in self.obs_shapes: + # first two dimensions should be [B, T] for inputs + assert inputs['obs'][k].ndim - 2 == len(self.obs_shapes[k]) + obs_features = TensorUtils.time_distributed(inputs, self.nets['policy']['obs_encoder'], inputs_as_kwargs=True) + assert obs_features.ndim == 3 # [B, T, D] + B = obs_features.shape[0] + + # reshape observation to (B,obs_horizon*obs_dim) + obs_cond = obs_features.flatten(start_dim=1) + + # initialize action from Guassian noise + noisy_action = torch.randn( + (B, Tp, action_dim), device=self.device) + naction = noisy_action + + # init scheduler + self.noise_scheduler.set_timesteps(num_inference_timesteps) + + for k in self.noise_scheduler.timesteps: + # predict noise + noise_pred = nets['policy']['noise_pred_net']( + sample=naction, + timestep=k, + global_cond=obs_cond + ) + + # inverse diffusion step (remove noise) + naction = self.noise_scheduler.step( + model_output=noise_pred, + timestep=k, + sample=naction + ).prev_sample + + return naction + + def serialize(self): + nets_state_dict = super().serialize() + if self.ema is not None: + ema_state_dict = self.ema.state_dict() + + return { + 'nets': nets_state_dict, + 'ema': ema_state_dict + } + + def deserialize(self, model_dict): + try: + nets_dict = model_dict['nets'] + ema_dict = model_dict['ema'] + except KeyError: + super().deserialize(model_dict) + return + super().deserialize(nets_dict) + if ema_dict: + self.ema.load_state_dict(ema_dict) + +# =================== Vision Encoder Utils ===================== +def replace_submodules( + root_module: nn.Module, + predicate: Callable[[nn.Module], bool], + func: Callable[[nn.Module], nn.Module]) -> nn.Module: + """ + Replace all submodules selected by the predicate with + the output of func. + + predicate: Return true if the module is to be replaced. + func: Return new module to use. + """ + if predicate(root_module): + return func(root_module) + + if parse_version(torch.__version__) < parse_version('1.9.0'): + raise ImportError('This function requires pytorch >= 1.9.0') + + bn_list = [k.split('.') for k, m + in root_module.named_modules(remove_duplicate=True) + if predicate(m)] + for *parent, k in bn_list: + parent_module = root_module + if len(parent) > 0: + parent_module = root_module.get_submodule('.'.join(parent)) + if isinstance(parent_module, nn.Sequential): + src_module = parent_module[int(k)] + else: + src_module = getattr(parent_module, k) + tgt_module = func(src_module) + if isinstance(parent_module, nn.Sequential): + parent_module[int(k)] = tgt_module + else: + setattr(parent_module, k, tgt_module) + # verify that all modules are replaced + bn_list = [k.split('.') for k, m + in root_module.named_modules(remove_duplicate=True) + if predicate(m)] + assert len(bn_list) == 0 + return root_module + +def replace_bn_with_gn( + root_module: nn.Module, + features_per_group: int=16) -> nn.Module: + """ + Relace all BatchNorm layers with GroupNorm. + """ + replace_submodules( + root_module=root_module, + predicate=lambda x: isinstance(x, nn.BatchNorm2d), + func=lambda x: nn.GroupNorm( + num_groups=x.num_features//features_per_group, + num_channels=x.num_features) + ) + return root_module + +# =================== UNet for Diffusion ============== + +class SinusoidalPosEmb(nn.Module): + def __init__(self, dim): + super().__init__() + self.dim = dim + + def forward(self, x): + device = x.device + half_dim = self.dim // 2 + emb = math.log(10000) / (half_dim - 1) + emb = torch.exp(torch.arange(half_dim, device=device) * -emb) + emb = x[:, None] * emb[None, :] + emb = torch.cat((emb.sin(), emb.cos()), dim=-1) + return emb + + +class Downsample1d(nn.Module): + def __init__(self, dim): + super().__init__() + self.conv = nn.Conv1d(dim, dim, 3, 2, 1) + + def forward(self, x): + return self.conv(x) + +class Upsample1d(nn.Module): + def __init__(self, dim): + super().__init__() + self.conv = nn.ConvTranspose1d(dim, dim, 4, 2, 1) + + def forward(self, x): + return self.conv(x) + + +class Conv1dBlock(nn.Module): + ''' + Conv1d --> GroupNorm --> Mish + ''' + + def __init__(self, inp_channels, out_channels, kernel_size, n_groups=8): + super().__init__() + + self.block = nn.Sequential( + nn.Conv1d(inp_channels, out_channels, kernel_size, padding=kernel_size // 2), + nn.GroupNorm(n_groups, out_channels), + nn.Mish(), + ) + + def forward(self, x): + return self.block(x) + + +class ConditionalResidualBlock1D(nn.Module): + def __init__(self, + in_channels, + out_channels, + cond_dim, + kernel_size=3, + n_groups=8): + super().__init__() + + self.blocks = nn.ModuleList([ + Conv1dBlock(in_channels, out_channels, kernel_size, n_groups=n_groups), + Conv1dBlock(out_channels, out_channels, kernel_size, n_groups=n_groups), + ]) + + # FiLM modulation https://arxiv.org/abs/1709.07871 + # predicts per-channel scale and bias + cond_channels = out_channels * 2 + self.out_channels = out_channels + self.cond_encoder = nn.Sequential( + nn.Mish(), + nn.Linear(cond_dim, cond_channels), + nn.Unflatten(-1, (-1, 1)) + ) + + # make sure dimensions compatible + self.residual_conv = nn.Conv1d(in_channels, out_channels, 1) \ + if in_channels != out_channels else nn.Identity() + + def forward(self, x, cond): + ''' + x : [ batch_size x in_channels x horizon ] + cond : [ batch_size x cond_dim] + + returns: + out : [ batch_size x out_channels x horizon ] + ''' + out = self.blocks[0](x) + embed = self.cond_encoder(cond) + + embed = embed.reshape( + embed.shape[0], 2, self.out_channels, 1) + scale = embed[:,0,...] + bias = embed[:,1,...] + out = scale * out + bias + + out = self.blocks[1](out) + out = out + self.residual_conv(x) + return out + + +class ConditionalUnet1D(nn.Module): + def __init__(self, + input_dim, + global_cond_dim, + diffusion_step_embed_dim=256, + down_dims=[256,512,1024], + kernel_size=5, + n_groups=8, + no_chunking=False, + ): + """ + input_dim: Dim of actions. + global_cond_dim: Dim of global conditioning applied with FiLM + in addition to diffusion step embedding. This is usually obs_horizon * obs_dim + diffusion_step_embed_dim: Size of positional encoding for diffusion iteration k + down_dims: Channel size for each UNet level. + The length of this array determines numebr of levels. + kernel_size: Conv kernel size + n_groups: Number of groups for GroupNorm + """ + + super().__init__() + all_dims = [input_dim] + list(down_dims) + start_dim = down_dims[0] + + dsed = diffusion_step_embed_dim + diffusion_step_encoder = nn.Sequential( + SinusoidalPosEmb(dsed), + nn.Linear(dsed, dsed * 4), + nn.Mish(), + nn.Linear(dsed * 4, dsed), + ) + cond_dim = dsed + global_cond_dim + + in_out = list(zip(all_dims[:-1], all_dims[1:])) + mid_dim = all_dims[-1] + self.mid_modules = nn.ModuleList([ + ConditionalResidualBlock1D( + mid_dim, mid_dim, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups + ), + ConditionalResidualBlock1D( + mid_dim, mid_dim, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups + ), + ]) + + down_modules = nn.ModuleList([]) + for ind, (dim_in, dim_out) in enumerate(in_out): + is_last = ind >= (len(in_out) - 1) + down_modules.append(nn.ModuleList([ + ConditionalResidualBlock1D( + dim_in, dim_out, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups), + ConditionalResidualBlock1D( + dim_out, dim_out, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups), + Downsample1d(dim_out) if (not is_last and not no_chunking) else nn.Identity() + ])) + + up_modules = nn.ModuleList([]) + for ind, (dim_in, dim_out) in enumerate(reversed(in_out[1:])): + is_last = ind >= (len(in_out) - 1) + up_modules.append(nn.ModuleList([ + ConditionalResidualBlock1D( + dim_out*2, dim_in, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups), + ConditionalResidualBlock1D( + dim_in, dim_in, cond_dim=cond_dim, + kernel_size=kernel_size, n_groups=n_groups), + Upsample1d(dim_in) if (not is_last and not no_chunking) else nn.Identity() + ])) + + final_conv = nn.Sequential( + Conv1dBlock(start_dim, start_dim, kernel_size=kernel_size), + nn.Conv1d(start_dim, input_dim, 1), + ) + + self.diffusion_step_encoder = diffusion_step_encoder + self.up_modules = up_modules + self.down_modules = down_modules + self.final_conv = final_conv + + print("number of parameters: {:e}".format( + sum(p.numel() for p in self.parameters())) + ) + + def forward(self, + sample: torch.Tensor, + timestep: Union[torch.Tensor, float, int], + global_cond=None): + """ + x: (B,T,input_dim) + timestep: (B,) or int, diffusion step + global_cond: (B,global_cond_dim) + out + put: (B,T,input_dim) + """ + sample = sample.moveaxis(-1,-2) + # (B,C,T) + + # 1. time + timesteps = timestep + if not torch.is_tensor(timesteps): + timesteps = torch.tensor([timesteps], dtype=torch.long, device=sample.device) + elif torch.is_tensor(timesteps) and len(timesteps.shape) == 0: + timesteps = timesteps[None].to(sample.device) + # broadcast to batch dimension in a way that's compatible with ONNX/Core ML + timesteps = timesteps.expand(sample.shape[0]) + + global_feature = self.diffusion_step_encoder(timesteps) + + if global_cond is not None: + global_feature = torch.cat([ + global_feature, global_cond + ], axis=-1) + + x = sample + h = [] + for idx, (resnet, resnet2, downsample) in enumerate(self.down_modules): + x = resnet(x, global_feature) + x = resnet2(x, global_feature) + h.append(x) + x = downsample(x) + + for mid_module in self.mid_modules: + x = mid_module(x, global_feature) + + for idx, (resnet, resnet2, upsample) in enumerate(self.up_modules): + x = torch.cat((x, h.pop()), dim=1) + x = resnet(x, global_feature) + x = resnet2(x, global_feature) + x = upsample(x) + + x = self.final_conv(x) + + # (B,C,T) + x = x.moveaxis(-1,-2) + # (B,T,C) + return x diff --git a/code_src/rise_robomimic/robomimic/algo/iris.py b/code_src/rise_robomimic/robomimic/algo/iris.py new file mode 100644 index 0000000000000000000000000000000000000000..7b441470c796749f92682ecf2b38a48e0bb3ada5 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/iris.py @@ -0,0 +1,183 @@ +""" +Implementation of IRIS (https://arxiv.org/abs/1911.05321). +""" +import numpy as np +from collections import OrderedDict +from copy import deepcopy + +import torch + +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.obs_utils as ObsUtils +from robomimic.config.config import Config +from robomimic.algo import register_algo_factory_func, algo_name_to_factory_func, HBC, ValuePlanner, ValueAlgo, GL_VAE + + +@register_algo_factory_func("iris") +def algo_config_to_class(algo_config): + """ + Maps algo config to the IRIS algo class to instantiate, along with additional algo kwargs. + + Args: + algo_config (Config instance): algo config + + Returns: + algo_class: subclass of Algo + algo_kwargs (dict): dictionary of additional kwargs to pass to algorithm + """ + pol_cls, _ = algo_name_to_factory_func("bc")(algo_config.actor) + plan_cls, _ = algo_name_to_factory_func("gl")(algo_config.value_planner.planner) + value_cls, _ = algo_name_to_factory_func("bcq")(algo_config.value_planner.value) + return IRIS, dict(policy_algo_class=pol_cls, planner_algo_class=plan_cls, value_algo_class=value_cls) + + +class IRIS(HBC, ValueAlgo): + """ + Implementation of IRIS (https://arxiv.org/abs/1911.05321). + """ + def __init__( + self, + planner_algo_class, + value_algo_class, + policy_algo_class, + algo_config, + obs_config, + global_config, + obs_key_shapes, + ac_dim, + device, + ): + """ + Args: + planner_algo_class (Algo class): algo class for the planner + + policy_algo_class (Algo class): algo class for the policy + + algo_config (Config object): instance of Config corresponding to the algo section + of the config + + obs_config (Config object): instance of Config corresponding to the observation + section of the config + + global_config (Config object): global training config + + obs_key_shapes (OrderedDict): dictionary that maps input/output observation keys to shapes + + ac_dim (int): action dimension + + device: torch device + """ + self.algo_config = algo_config + self.obs_config = obs_config + self.global_config = global_config + + self.ac_dim = ac_dim + self.device = device + + self._subgoal_step_count = 0 # current step count for deciding when to update subgoal + self._current_subgoal = None # latest subgoal + self._subgoal_update_interval = self.algo_config.subgoal_update_interval # subgoal update frequency + self._subgoal_horizon = self.algo_config.value_planner.planner.subgoal_horizon + self._actor_horizon = self.algo_config.actor.rnn.horizon + + self._algo_mode = self.algo_config.mode + assert self._algo_mode in ["separate", "cascade"] + + self.planner = ValuePlanner( + planner_algo_class=planner_algo_class, + value_algo_class=value_algo_class, + algo_config=algo_config.value_planner, + obs_config=obs_config.value_planner, + global_config=global_config, + obs_key_shapes=obs_key_shapes, + ac_dim=ac_dim, + device=device + ) + + self.actor_goal_shapes = self.planner.subgoal_shapes + assert not algo_config.latent_subgoal.enabled, "IRIS does not support latent subgoals" + + # only for the actor: override goal modalities and shapes to match the subgoal set by the planner + actor_obs_key_shapes = deepcopy(obs_key_shapes) + # make sure we are not modifying existing observation key shapes + for k in self.actor_goal_shapes: + if k in actor_obs_key_shapes: + assert actor_obs_key_shapes[k] == self.actor_goal_shapes[k] + actor_obs_key_shapes.update(self.actor_goal_shapes) + + goal_modalities = {obs_modality: [] for obs_modality in ObsUtils.OBS_MODALITY_CLASSES.keys()} + for k in self.actor_goal_shapes.keys(): + goal_modalities[ObsUtils.OBS_KEYS_TO_MODALITIES[k]].append(k) + + actor_obs_config = deepcopy(obs_config.actor) + with actor_obs_config.unlocked(): + actor_obs_config["goal"] = Config(**goal_modalities) + + self.actor = policy_algo_class( + algo_config=algo_config.actor, + obs_config=actor_obs_config, + global_config=global_config, + obs_key_shapes=actor_obs_key_shapes, + ac_dim=ac_dim, + device=device + ) + + def process_batch_for_training(self, batch): + """ + Processes input batch from a data loader to filter out + relevant information and prepare the batch for training. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader + + Returns: + input_batch (dict): processed and filtered batch that + will be used for training + """ + input_batch = dict() + + input_batch["planner"] = self.planner.process_batch_for_training(batch) + input_batch["actor"] = self.actor.process_batch_for_training(batch) + + if self.algo_config.actor_use_random_subgoals: + # optionally use randomly sampled step between [1, seq_length] as policy goal + policy_subgoal_indices = torch.randint( + low=0, high=self.global_config.train.seq_length, size=(batch["actions"].shape[0],)) + goal_obs = TensorUtils.gather_sequence(batch["next_obs"], policy_subgoal_indices) + goal_obs = TensorUtils.to_float(TensorUtils.to_device(goal_obs, self.device)) + input_batch["actor"]["goal_obs"] = goal_obs + else: + # otherwise, use planner subgoal target as goal for the policy + input_batch["actor"]["goal_obs"] = input_batch["planner"]["planner"]["target_subgoals"] + + # we move to device first before float conversion because image observation modalities will be uint8 - + # this minimizes the amount of data transferred to GPU + return TensorUtils.to_float(TensorUtils.to_device(input_batch, self.device)) + + def get_state_value(self, obs_dict, goal_dict=None): + """ + Get state value outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + value (torch.Tensor): value tensor + """ + return self.planner.get_state_value(obs_dict=obs_dict, goal_dict=goal_dict) + + def get_state_action_value(self, obs_dict, actions, goal_dict=None): + """ + Get state-action value outputs. + + Args: + obs_dict (dict): current observation + actions (torch.Tensor): action + goal_dict (dict): (optional) goal + + Returns: + value (torch.Tensor): value tensor + """ + return self.planner.get_state_action_value(obs_dict=obs_dict, actions=actions, goal_dict=goal_dict) diff --git a/code_src/rise_robomimic/robomimic/algo/rsm_beam.py b/code_src/rise_robomimic/robomimic/algo/rsm_beam.py new file mode 100644 index 0000000000000000000000000000000000000000..68262b4ff7828cf1ea4621f123cb715adc2be2bf --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/rsm_beam.py @@ -0,0 +1,305 @@ +"""Beam search over behavioural action chunks with the RSM as the value (rsm_rise BEAM_RISE, 2026-11-09). + +Port of gen_q `robomimic_genq/beam.py` (williamd4112/gen_q #97/#103/#112/#118, branch +issue-97-myopic-transition @ ce8f010d) to the RISE sim planner. Selected by `training.plan_mode=beam`; +every other plan_mode never reaches this file. + +What differs from gen_q, and why +-------------------------------- +* gen_q advanced a node with an action-conditioned 1-chunk WORLD MODEL (+ optionally an action-free occupancy + jump). The RISE successor model is itself ACTION-CONDITIONED (train_rsm.sample_future(flow, z, a, beta)), + so the transition is ONE RSM draw at a myopic beta_t: z' ~ m_{beta_t}( . | z, a). It is the "WM step + + jump" of gen_q #118 in one call (mean offset 1/(1-beta_t) frames). +* gen_q's heuristic was one occupancy jump at beta = gamma. Here it is the paper's own read-out, the + coin-terminated beta chain (rsm_scorer._q_chain_logit, plan_beta, plan_gamma), so depth 1 of the beam + scores EXACTLY what best-of-N scores (same chain, same hop head, same K particles). +* Root proposals are the RISE diffusion policy's chunks (the same N=plan_n draws best-of-N ranks); deeper + proposals come from the hop head (the 1545-d DINO-state BC policy the chain read-out already uses), since + the image policy cannot be run on a predicted state. +* Scores are kept in LOG space (log of the success-probability scale), because on Square the membership + logits sit near -57 and every probability underflows to a tie. + +Path value (gen_q's g + Gamma * h, normalised so it stays a probability): + v = g + Gamma * sigmoid(lg_leaf) per particle + on a transition z -> z' (k ~ Geom(1-beta_t) frames): g += Gamma * (1 - jk) * r(z'); Gamma *= jk, + jk = E[gamma^k] = gamma (1-beta_t) / (1 - gamma beta_t) (gen_q beam.py "discount bookkeeping") +The reward over the k frames is proxied by r at the arrival state (gen_q's approximation, not unbiased). + +Aggregation over particles (plan_beam_agg): "logmean" = log mean_j v_j (the `prob` ranking), "meanlog" = +mean_j log v_j (~ the `logit` ranking when v << 1, i.e. Square). Default follows plan_score. + +Algorithm per decision (one env): + L1: score all N root chunks at the real state (chain read, K particles); keep top `root_keep`. + L2..d: each kept entry (state particles z [P], chunk a) is advanced on all P particles to z'; the hop head + proposes `branch` chunks at z' (round-robin over particles); every child is scored with the chain + read from each particle (K // P chains per particle) and the global top `width` are kept. + End: the final beam's leaf reads are redrawn with fresh noise (winner's-curse control, gen_q #103) and the + argmax entry's ROOT chunk is executed (replan every Ta steps, as best-of-N). +""" +from __future__ import annotations + +import math +import time + +import torch + + +BEAM_DEFAULTS = dict( + plan_beam_width=8, # B: entries kept per level (levels >= 2) + plan_beam_branch=8, # N: hop-head proposals per entry + plan_beam_depth=2, # d: levels (1 == best-of-N with the beam's own score) + plan_beam_root_keep=8, # root chunks that enter level 2 (0 = all plan_n) + plan_beam_nwm=4, # P: successor particles per node + plan_beam_beta_t=0.95, # transition beta (myopic successor) + plan_beam_tail_k=0, # chain particles per candidate at levels >= 2 (0 = plan_particles) + plan_beam_agg="", # logmean | meanlog | "" (follow plan_score: logit -> meanlog, else logmean) + plan_beam_rescore=1, # 1: fresh-noise re-read of the final beam + plan_beam_reward=1, # 1: collect r(z') along the path (gen_q g); 0: leaf heuristic only + plan_beam_select="max", # max: root of the best final entry | rootmean: root whose final-level children (all + # of them, before pruning) have the best aggregated value (variance / winner's curse) + # | quantile | lcb (gen_q #115, run 6; see _select / _lcb) + plan_beam_select_q=1.0, # quantile: nearest-rank q-quantile of the SURVIVING (pruned, rescored) final beam; + # 1.0 == argmax exactly. Pruning is untouched (as gen_q). + plan_beam_lcb_lambda=0.0, # lcb: score = mean_p(u) - L * sd_p(u) over the P successor particles (u = per-particle + # value), used for top-k pruning at levels >= 2 AND the final pick (as gen_q); + # L == 0 returns the plain score object itself (== max, bit-for-bit). +) + + +def _logsig(x): + return torch.nn.functional.logsigmoid(x) + + +class ChainReader: + """Per-chain membership logits of the coin-terminated beta chain, from latent rows z [R, D] and flat chunks + a [R, da]. Same law, same CRN contract (noise per (level, chain index) shared across rows) and the same + draw ORDER as rsm_scorer._q_chain_logit's sampled path when given the same generator, so + sigmoid(logits).mean(1) reproduces its q (unit-tested in scripts/beam/test_beam_cpu.py).""" + + def __init__(self, backend, beta, gamma, cap, flow_steps, temperature): + from robomimic.algo import rsm_scorer as S + _, train_rsm, _ = S._rsm_modules() + self.sample_future = train_rsm.sample_future + self.b = backend + self.beta, self.gamma = float(beta), float(gamma) + self.p = S.chain_continuation_p(self.beta, self.gamma) + self.L = int(cap) if cap else int(S.chain_cap(self.beta, self.gamma)) + self.flow_steps = int(flow_steps) + self.T = float(temperature) if temperature else 1.0 + + @torch.no_grad() + def logits(self, z, a, n, generator=None): + """z [R, D], a [R, da] -> raw membership logits [R, n] (one read at each chain's frozen node).""" + b, dev = self.b, z.device + R, D = z.shape + L, n = self.L, int(n) + rnd = lambda *s: torch.randn(*s, device=dev, generator=generator) + x0s = [rnd(n, D) for _ in range(L + 1)] + epss = [rnd(n, int(b.hop.d_act)) for _ in range(L)] if L >= 1 else [] + coins = torch.rand(L, n, device=dev, generator=generator) if L >= 1 else None + zz = z.repeat_interleave(n, 0) + aa = a.repeat_interleave(n, 0) + tk = torch.zeros(R * n, dtype=torch.long, device=dev) + bq = torch.full((R * n,), self.beta, device=dev) + pid = torch.arange(n, device=dev).repeat(R) + alive = torch.ones(R * n, dtype=torch.bool, device=dev) + for k in range(L): + alive = alive & (coins[k][pid] < self.p) + idx = alive.nonzero(as_tuple=True)[0] + if idx.numel() == 0: + break + sub = pid[idx] + z_new = self.sample_future(b.flow, zz[idx], aa[idx], tk[idx], bq[idx], b.rms, self.flow_steps, + n=1, x0=x0s[k][sub]) + a_new = b.hop.sample_eps(z_new, tk[idx], epss[k][sub]) + zz = zz.index_copy(0, idx, z_new) + aa = aa.index_copy(0, idx, a_new) + zz = self.sample_future(b.flow, zz, aa, tk, bq, b.rms, self.flow_steps, n=1, x0=x0s[L][pid]) + lg = b.rew(zz, tk).float() / self.T + return torch.nan_to_num(lg, nan=-100.0).view(R, n) + + +class BeamSearch: + def __init__(self, scorer, cfg): + self.sc = scorer + b = scorer.backend + if getattr(b, "hop", None) is None: + raise RuntimeError("plan_mode=beam needs a hop head (rsm_hop_ckpt): it proposes chunks at predicted states") + self.b = b + g = lambda k: cfg.get(k, BEAM_DEFAULTS[k]) if cfg.get(k, None) is not None else BEAM_DEFAULTS[k] + self.width = int(g("plan_beam_width")) + self.branch = int(g("plan_beam_branch")) + self.depth = int(g("plan_beam_depth")) + self.root_keep = int(g("plan_beam_root_keep")) + self.nwm = int(g("plan_beam_nwm")) + self.beta_t = float(g("plan_beam_beta_t")) + self.K = int(g("plan_beam_tail_k") or cfg["plan_particles"]) + self.K_root = int(cfg["plan_particles"]) + agg = str(g("plan_beam_agg") or "") + self.agg = agg or ("meanlog" if cfg.get("plan_score") == "logit" else "logmean") + assert self.agg in ("logmean", "meanlog"), self.agg + self.rescore = bool(int(g("plan_beam_rescore"))) + self.use_reward = bool(int(g("plan_beam_reward"))) + self.select = str(g("plan_beam_select") or "max") + assert self.select in ("max", "rootmean", "quantile", "lcb"), self.select + self.sel_q = float(g("plan_beam_select_q")) + self.lcb_L = float(g("plan_beam_lcb_lambda")) + assert 0.0 <= self.sel_q <= 1.0, self.sel_q + self.gamma = float(cfg["plan_gamma"]) + self.flow_steps = int(cfg["plan_flow_steps"]) + T = scorer.effective_temperature() + self.reader = ChainReader(b, cfg["plan_beta"], self.gamma, int(cfg.get("plan_chain_cap", 0) or 0), + self.flow_steps, T) + self.T = float(T) if T else 1.0 + bt, gm = self.beta_t, self.gamma + self.jk = gm * (1.0 - bt) / (1.0 - gm * bt) # E[gamma^k], k ~ Geom(1 - beta_t), k >= 1 + self.log_jk = math.log(self.jk) + self.log_1mjk = math.log1p(-self.jk) + if self.K % self.nwm: + raise ValueError(f"plan_beam_tail_k={self.K} must be a multiple of plan_beam_nwm={self.nwm}") + + def describe(self): + return {"width": self.width, "branch": self.branch, "depth": self.depth, "root_keep": self.root_keep, + "nwm": self.nwm, "beta_t": self.beta_t, "tail_k": self.K, "root_k": self.K_root, "agg": self.agg, + "rescore": self.rescore, "reward": self.use_reward, "jk": self.jk, + **({"select": self.select} if self.select != "max" else {}), + **({"select_q": self.sel_q} if self.select == "quantile" else {}), + **({"lcb_lambda": self.lcb_L, "lcb_space": ("log" if self.agg == "meanlog" else "prob")} + if self.select == "lcb" else {}), + "heuristic": {"beta": self.reader.beta, "gamma": self.gamma, "cap": self.reader.L, + "p_cont": self.reader.p}} + + # ---- scoring ------------------------------------------------------------------------------------ + def _agg(self, logv): + """logv [M, J] per-chain log path values -> [M].""" + if self.agg == "meanlog": + return logv.mean(1) + return torch.logsumexp(logv, 1) - math.log(logv.shape[1]) + + def _read(self, z, a, logg, logG, per, pp=False): + """Entries: z [M, P, D] state particles, a [M, da] chunk, logg/logG [M, P]. `per` chains per particle. + Returns f [M] (aggregated log path value); with pp=True also u [M, P], the same agg per particle.""" + M, P, D = z.shape + lg = self.reader.logits(z.reshape(M * P, D), a.repeat_interleave(P, 0), per) # [M*P, per] + lv = _logsig(lg).view(M, P, per) + if self.use_reward: + lv = torch.logaddexp(logg.unsqueeze(-1), logG.unsqueeze(-1) + lv) + else: + lv = logG.unsqueeze(-1) + lv + f = self._agg(lv.reshape(M, P * per)) + if pp: + return f, self._agg(lv.reshape(M * P, per)).view(M, P) + return f + + def _lcb(self, f, u): + """gen_q #115 LCB: mean_p(u) - L * sd_p(u) over the P particles (population sd, as jnp.std). meanlog: in log + space (mean_p u == f). logmean: in probability space (mean_p exp(u) == exp(f)), returned as a log; an + LCB <= 0 floors at 1e-30 of the entry's best particle. L == 0 returns f itself (bit-identical to max).""" + if self.lcb_L == 0.0: + return f + if self.agg == "meanlog": + return u.mean(1) - self.lcb_L * u.std(1, unbiased=False) + c = u.max(1).values + w = torch.exp(u - c.unsqueeze(1)) + val = w.mean(1) - self.lcb_L * w.std(1, unbiased=False) + return c + torch.log(val.clamp_min(1e-30)) + + def _select(self, s): + """Final pick over the surviving beam scores s [M] -> (index, rank from top).""" + if self.select == "quantile" and self.sel_q < 1.0: + n = s.numel() + r = n - 1 - int(round(self.sel_q * (n - 1))) # gen_q nearest rank: ranks skipped from the top + order = torch.argsort(s, descending=True) + return int(order[r]), r + return int(s.argmax()), 0 + + def _advance(self, z, a, logg, logG): + """One transition on every particle: z [M, P, D] -> z' [M, P, D], with the reward bookkeeping.""" + M, P, D = z.shape + rows = M * P + tk = torch.zeros(rows, dtype=torch.long, device=z.device) + bq = torch.full((rows,), self.beta_t, device=z.device) + zn = self.reader.sample_future(self.b.flow, z.reshape(rows, D), a.repeat_interleave(P, 0), tk, bq, + self.b.rms, self.flow_steps, n=1) + zn = zn.view(M, P, D) + if self.use_reward: + lr = _logsig(self.b.rew(zn.reshape(rows, D), tk).float() / self.T).view(M, P) + logg = torch.logaddexp(logg, logG + self.log_1mjk + lr) + logG = logG + self.log_jk + return zn, logg, logG + + def _propose(self, zn): + """zn [M, P, D] -> chunks [M*branch, da] (proposal j of entry m conditioned on particle j % P).""" + M, P, D = zn.shape + rr = torch.arange(self.branch, device=zn.device) % P + zc = zn[:, rr, :].reshape(M * self.branch, D) + tk = torch.zeros(zc.shape[0], dtype=torch.long, device=zn.device) + eps = torch.randn(zc.shape[0], int(self.b.hop.d_act), device=zn.device) + return self.b.hop.sample_eps(zc, tk, eps) + + # ---- the search ----------------------------------------------------------------------------------- + @torch.no_grad() + def plan(self, z0, A): + """z0 [D] latent of the real current state; A [N, da] flat root chunks. + -> (root index, info dict).""" + dev = z0.device + N, P = A.shape[0], self.nwm + stats = {"levels": []} + # L1: the real state, K_root chains (== best-of-N's own read-out) + zr = z0.view(1, 1, -1).expand(N, 1, -1).contiguous() + zero = torch.zeros(N, 1, device=dev) + f1 = self._read(zr, A, torch.full_like(zero, -float("inf")), zero, self.K_root) + root = torch.arange(N, device=dev) + stats["levels"].append({"n": int(N), "f_max": float(f1.max()), "f_mean": float(f1.mean())}) + if self.depth <= 1: + return int(f1.argmax()), {"f1": f1, "f": f1, "root": root, **stats} + keep = N if self.root_keep <= 0 else min(self.root_keep, N) + top = torch.topk(f1, keep).indices + z = z0.view(1, 1, -1).expand(keep, P, -1).contiguous() + a = A[top] + root = top + logg = torch.full((keep, P), -float("inf"), device=dev) + logG = torch.zeros(keep, P, device=dev) + f = f1[top] + for lvl in range(2, self.depth + 1): + zn, logg, logG = self._advance(z, a, logg, logG) # [M, P, D] + M = zn.shape[0] + a = self._propose(zn) # [M*br, da] + z = zn.repeat_interleave(self.branch, 0) + logg = logg.repeat_interleave(self.branch, 0) + logG = logG.repeat_interleave(self.branch, 0) + root = root.repeat_interleave(self.branch, 0) + if self.select == "lcb": + f, u = self._read(z, a, logg, logG, self.K // P, pp=True) + fs = self._lcb(f, u) + else: + f = self._read(z, a, logg, logG, self.K // P) + fs = f + stats["levels"].append({"n": int(f.numel()), "f_max": float(f.max()), "f_mean": float(f.mean())}) + if self.select == "rootmean" and lvl == self.depth: + # aggregate every final-level child per root (same agg as particles), pick the best root + ur, inv = torch.unique(root, return_inverse=True) + cnt = torch.zeros(ur.numel(), device=dev).index_add_(0, inv, torch.ones_like(f)) + if self.agg == "meanlog": + fr = torch.zeros(ur.numel(), device=dev).index_add_(0, inv, f) / cnt + else: + mx = float(f.max()) + fr = torch.log(torch.zeros(ur.numel(), device=dev).index_add_(0, inv, torch.exp(f - mx)) / cnt) + mx + j = int(fr.argmax()) + return int(ur[j]), {"f1": f1, "f": fr, "root": ur, **stats} + if f.numel() > self.width: + k = torch.topk(fs, self.width).indices + z, a, logg, logG, root, f, fs = z[k], a[k], logg[k], logG[k], root[k], f[k], fs[k] + stats["levels"][-1]["n_roots"] = int(torch.unique(root).numel()) # log only: distinct roots in the final beam + if self.rescore: + if self.select == "lcb": + f, u = self._read(z, a, logg, logG, self.K // P, pp=True) + fs = self._lcb(f, u) + else: + f = self._read(z, a, logg, logG, self.K // P) + fs = f + if self.select in ("quantile", "lcb"): + j, r = self._select(fs) + return int(root[j]), {"f1": f1, "f": f, "fs": fs, "root": root, "sel_rank": r, **stats} + j = int(f.argmax()) + return int(root[j]), {"f1": f1, "f": f, "root": root, **stats} diff --git a/code_src/rise_robomimic/robomimic/algo/rsm_mpc_ctx.py b/code_src/rise_robomimic/robomimic/algo/rsm_mpc_ctx.py new file mode 100644 index 0000000000000000000000000000000000000000..3789eeeb9dcfc22599da58949a8599c5063d4db9 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/rsm_mpc_ctx.py @@ -0,0 +1,51 @@ +"""Per-decision-step context the MPC read-outs of gen_q#273 need and the scorer interface cannot carry. + +WHY THIS EXISTS. `RSMScorer.score(state, A)` hands a read-out exactly ONE action chunk per candidate -- +the `plan_chunk` (8) actions that would actually run. A true MPC read-out rolls the world model open-loop +for H frames, so for H > 8 it needs MORE of the candidate's action sequence than the scorer's signature +can express. RISE's diffusion actor emits Tp = 16 actions per sample and the planner throws away +everything past `start + plan_chunk`; those discarded actions are the PROPOSER'S OWN CONTINUATION of the +candidate it is scoring, which is the honest extension of the rollout and costs nothing to keep. + +Rather than widen `rsm_scorer.RSMScorer.score` / `DWMBackend.q` (owned by another work stream) this module +is a one-slot store that `rsm_planner.plan_get_action` fills immediately before it scores and the MPC +read-out reads. It is WRITE-ONLY for every existing backend: nothing outside `dinowm_mpc_readout` / +`lewm_mpc_readout` ever calls `get_tail()`, so storing the tensor changes no number in any cell on disk. + +Row order: the tail is [B*N, Ttail, ac] in the SAME row order as the `A` the scorer receives (both are +slices of the one `naction` tensor), and `RSMScorer.score` passes all rows to the backend in one call. +A read-out must still check `tail.shape[0] == rows` and fall back if it does not -- see `tail_for`. +""" +from __future__ import annotations + +_TAIL = None # [B*N, Ttail, ac] or None +_STAMP = 0 # increments on every set; lets a read-out detect a stale tail + + +def set_tail(t): + """Called by rsm_planner once per decision step with naction[:, start+chunk:].""" + global _TAIL, _STAMP + _TAIL = t + _STAMP += 1 + + +def clear(): + global _TAIL + _TAIL = None + + +def get_tail(): + return _TAIL + + +def stamp(): + return _STAMP + + +def tail_for(rows): + """The stored tail if it belongs to `rows` candidates, else None (the caller then falls back to the + hop policy for every chunk past the first, and must say so in its rollout provenance).""" + t = _TAIL + if t is None or getattr(t, "ndim", 0) != 3 or t.shape[0] != int(rows): + return None + return t diff --git a/code_src/rise_robomimic/robomimic/algo/rsm_planner.py b/code_src/rise_robomimic/robomimic/algo/rsm_planner.py new file mode 100644 index 0000000000000000000000000000000000000000..7068dd9b981fc00e06e49c96401f8e632086446e --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/rsm_planner.py @@ -0,0 +1,684 @@ +"""Best-of-N planning over RISE's diffusion policy with a successor-model scorer (rsm_rise E1). + +Mixed into IDQL (robomimic/algo/idql.py, the class RISE's `-cn iql_diffusion +training=` recipe +actually trains: `IQLDiffusionTrainingConfig.algo` defaults to `idql`) and IQLDiffusion +(iql_diffusion.py, the advantage-weighted class, E2). Both classes expose +`_sample_action_chunks(obs_dict, goal_dict) -> naction [B, Tp, ac]` (their released DDPM/DDIM sampler, +unchanged) and route `get_action` through `plan_get_action` below. + +Per control step with plan_n = N > 1: + 1. the obs dict ([B, To, ...]) is repeated N times (candidate n of env b sits at row b*N + n); + 2. the sampler runs ONCE on the B*N batch -> N 16-step chunks per env; + 3. the scorer gets the CURRENT frame (index To-1 == -1 of the obs stack) and the first `plan_chunk` + actions of the executed window naction[:, To-1 : To-1+plan_chunk] (the 8 actions that would run); + 4. a rule picks one candidate per env; its executed window naction[:, To-1 : To-1+Ta] goes to the + rollout loop's action queue exactly as the released path's single sample does. +plan_n = 1 (or None) is the released behaviour, bit for bit. + +Rules: argmax | softmax (temperature plan_temp on Q̄) | topk_uniform (uniform among the plan_topk best) +| random (S3H2: ignores Q̄) | permuted (S3H3: Q̄ shuffled across candidates, then argmax) | argmin +| first (#282: ignores Q̄, always candidate 0 -- the index-prior control for tie-saturated scores). + +Backends: mlp / dwm / mc (rsm_scorer.RSMScorer on the pooled DINO state), ifql (gen_q#264: an IFQL +critic -- the flow variant of IDQL -- trained by rsm_rise/code/ifql/train_ifql.py on the same provenance +reward and the same pooled DINO state, read through the torch port robomimic/algo/ifql_torch.py) and iql (S3H4: the fork's own +IQL critic nets, min over the ensemble, on the first action of the chunk, as +sim_pipeline.eval.rollout_policies.robomimic_sampling_rollout_policy does at N=128). With backend iql, +`rsm_ckpt` may be an S0A robomimic .pth whose critics are used, or "" for the loaded policy's own. + +Config keys (algo config, all with released-behaviour defaults; hydra: training.=): + plan_n, plan_rule, plan_temp, plan_topk, plan_chunk, plan_particles, plan_mode {d1,fold,recursive}, + plan_depth, plan_beta, plan_gamma, plan_flow_steps, plan_seed (-1: no reseed; >=0: CRN seed reused at + every step, i.e. the same particle noise at every state), rsm_backend {mlp,dwm,mc,iql}, rsm_ckpt, + rsm_hop_ckpt, rsm_feat_stats, rsm_img_layout {chw,rise_t}, rsm_dwm_module, rsm_backend also accepts + `ifql` (rsm_ckpt = an ifql_bundle.pt, rsm_feat_stats = the task's cache feat_stats.npz), + plan_score {prob,logit,prob_log,conformal_lcb} (prob: rank by mean σ = released; logit: rank by the mean + raw logit over particles; prob_log: rank by the SAME quantity as prob, folded in the log-complement domain + so it does not tie ~half the candidates at exactly 1.0 when σ saturates (mlp backend, d1/fold only); + conformal_lcb: rank by the plan_lcb_quantile quantile over particles of the per-particle + success probability — a pessimistic read-out that prefers candidates whose future is reliably good), + plan_rescore_top / plan_particles_rescore (both > 0: two-stage screening, the top-K candidates of the + ranking array are rescored with M particles), plan_temperature (0: the checkpoint's calib.json T if present + else 1; > 0 overrides; enters the sigmoid only, the logit ranking is T-free). +The per-step log records the ranking array (`score_*`, `ties_at_max`) and every read-out the backend produced +(`prob_*`, `logit_*`, `prob_log_*`, `lcb_*`). +""" +from __future__ import annotations + +import math +import time +from robomimic.algo import rsm_mpc_ctx as _mpc_ctx +from collections import OrderedDict + +import numpy as np +import torch + +PLANNER_DEFAULTS = OrderedDict( + plan_n=None, + plan_rule="argmax", + plan_temp=0.2, + plan_topk=8, + plan_chunk=8, + plan_particles=16, + plan_mode="fold", + plan_depth=2, + plan_beta=0.95, + plan_gamma=0.99, + plan_flow_steps=8, + plan_seed=-1, + rsm_backend="mlp", # mlp | dwm | mc | iql | ifql + rsm_ckpt="", + rsm_hop_ckpt="", + rsm_feat_stats="", + rsm_img_layout="chw", + rsm_dwm_module="dwm_readout", + plan_score="prob", # prob | logit | prob_log | conformal_lcb + plan_rescore_top=0, # two-stage screening: rescore the top-K (0 = off) + plan_particles_rescore=0, # ... with M particles (0 = off) + plan_temperature=0.0, # 0: checkpoint's calib.json T (else 1.0); > 0 overrides + plan_lcb_quantile=0.1, # plan_score=conformal_lcb: the particle quantile that ranks (0.1 = 10th pct) + plan_max_rows=0, # >0: override the scorer row-slice width (rsm_scorer.MAX_ROWS, 65536). + plan_mpc_horizon=0, # gen_q#273: world-model MPC horizon H in FRAMES (H = 1/(1-plan_gamma)); + # 0 = off. Read only by plan_mode in {mpc, mpc_disc}. + plan_chain_cap=0, # coin chain (gen_q#267): 0 = compute the cap from the 1e-3 tail + plan_chain_tail_eps=1e-3, # P(walk longer than cap) <= this; the cap is a guard, not a tuning knob + plan_chain_seed=-1, # <0 = follow the cell's eval seed + # Candidates x particles per read-out slice. The CRN noise is drawn + # once up front and indexed by particle, so the estimate is invariant + # to this -- it is purely a memory knob, unlike plan_sample_batch. + # 65536 is 8x what the grid ever hit (128 cand x 64 part = 8192) and + # OOMs an 80 GB card at plan_n=2048 in _q_fold_logit. + plan_sample_batch=0, # >0: run the DDPM sampler over at most this many candidate rows at a + # time and concatenate. 0 = off (one call, released behaviour, bit for + # bit). The sampler is what caps N: at plan_n=2048 the released path + # builds a [B*N, Tp, ac] denoising batch and OOMs an 80 GB card (75 GB + # allocated) in idql._sample_action_chunks, long before the RSM scorer + # is reached. Chunking changes how much noise the sampler draws per + # call, so it is OFF by default: every existing cell stays identical. +) +# E2 (training-time advantage) keys, IQLDiffusion only +ADV_DEFAULTS = OrderedDict( + rsm_adv_v_expectile=0.5, + rsm_adv_v_samples=16, + rsm_adv_scale="td", # td: Q̄/(1-γ), V̄/(1-γ); std: batch-standardised advantage + rsm_adv_permute=False, # S3H6: permute the advantage within each batch +) +RULES = ("argmax", "softmax", "topk_uniform", "random", "permuted", "argmin", "first") + + +def _cfg_get(algo_config, key, default): + try: + v = algo_config[key] + except (KeyError, RuntimeError, AttributeError): + return default + if v is None: + return default if key != "plan_n" else None + return v + + +def select(scores, rule, temp=0.2, topk=8, generator=None): + """scores [B, N] (cpu float) -> chosen index [B] (long, cpu) under `rule`. + Every tensor is created with an explicit device: sim_pipeline's setup_experiment sets the default tensor + type to CUDA, so a bare torch.arange / randint would land on the GPU and break the cpu indexing.""" + B, N = scores.shape + # float64 in -> float64 through: plan_score=prob_log ranks by log(1 - Q̄), whose values sit near + # -depth * logit (~ -490 at depth 4 on threading). A .float() here would have quietly undone the + # whole point of that read-out by putting the comparison back at 6e-5 resolution. Every other + # read-out arrives as float32 and is unaffected. + scores = scores.detach().cpu() + scores = scores.double() if scores.dtype == torch.float64 else scores.float() + if rule == "argmax": + return scores.argmax(1) + if rule == "argmin": + return scores.argmin(1) + if rule == "random": + return torch.randint(0, N, (B,), generator=generator, device="cpu") + if rule == "first": + # DF_VALUE / gen_q#282: the INDEX-PRIOR control. Ignores the scores entirely and always takes + # candidate 0 of the N the proposer drew. It exists because this file asserts (at the + # `ties_at_max` log line below) that "argmax picks the first of them = uniform over the tied set + # since candidates are exchangeable" -- an ASSUMPTION, never measured. A DF arm whose value ties + # ~86 of 128 candidates takes candidate 0 on ~68 % of steps, so if the 128 proposer draws are NOT + # exchangeable in index, its success rate is the index prior and not the value. `first` measures + # that prior directly on the identical candidates; `random` (uniform over N) is its null. + return torch.zeros(B, dtype=torch.long, device="cpu") + if rule == "permuted": + perm = torch.stack([torch.randperm(N, generator=generator, device="cpu") for _ in range(B)]) + return torch.gather(scores, 1, perm).argmax(1) + if rule == "softmax": + p = torch.softmax(scores / max(float(temp), 1e-6), dim=1) + return torch.multinomial(p, 1, generator=generator)[:, 0] + if rule == "topk_uniform": + k = min(int(topk), N) + top = scores.topk(k, dim=1).indices # [B, k] + pick = torch.randint(0, k, (B,), generator=generator, device="cpu") + return top[torch.arange(B, device="cpu"), pick] + raise ValueError(f"unknown plan_rule {rule}; choose from {RULES}") + + +class IQLCriticBackend: + """S3H4: score candidates with RISE's own IQL critic ensemble (min over critics) on the first + action, on the current (unstacked) obs dict, like RobomimicSamplingRolloutPolicy.""" + + def __init__(self, critics, own=True, ckpt="", state=None, feat_stats=""): + self.critics = critics + self.own = own + self.ckpt = ckpt + # PRECOMPUTED-FEATURE CRITICS (BASE_TOPUP run 11, gen_q#287, 2026-09-26). A path-(D)/(Dq) critic was + # trained with NO image encoder: its observation is the single low_dim key `dino_state`, the 1545-d + # z-scored [pooled DINOv2 | proprio] state from data/derived/_dinostate.hdf5 (= cache//). + # The env hands the planner pixels, so that key has to be BUILT here -- with exactly the module that + # produces every published RSM / IFQL / DINO-WM state (rsm_scorer.PooledDinoState on the same + # feat_stats.npz), or the critic would be fed a different representation at eval than at train time. + # `state=None` (every pixel critic, i.e. every published RISE cell) leaves this class byte-identical. + self.state = state + self.feat_stats = feat_stats + + @property + def needs_dino_state(self): + return self.state is not None + + @torch.no_grad() + def state_from_obs(self, obs_t): + """obs_t: B current-frame observations -> [B, 1545] z-scored pooled DINO state.""" + return self.state(obs_t) + + @classmethod + def from_checkpoint(cls, ckpt_path, device, feat_stats=""): + import robomimic.utils.file_utils as FileUtils + # GLOBAL OBS-SPEC CLOBBER (BASE_TOPUP run 12, gen_q#287, 2026-09-26). `policy_from_checkpoint` + # calls `ObsUtils.initialize_obs_utils_with_config`, which REPLACES the process-global + # `OBS_KEYS_TO_MODALITIES` / `OBS_MODALITIES_TO_KEYS`. `EnvRobosuite.get_observation` + # (env_robosuite.py:217) only returns a camera image when its key is in that global dict -- so + # loading a path-(D)/(Dq) critic, whose obs spec is the single low_dim key `dino_state` and has + # NO rgb keys, silently made the env stop returning `agentview_image` from the next step on, and + # every (Dq) cell died with `KeyError: 'agentview_image'` in `stack_last_n_obs` (job 1923672). + # The pixel critics never showed it because their spec contains the image keys already. + # Snapshot before, and after the load restore the snapshot UNIONed with whatever keys the critic + # spec added (so `dino_state` stays registered for the critic without evicting the env's images). + # The union is a no-op for every pixel critic, so all published cells are byte-identical. + import robomimic.utils.obs_utils as _ObsUtils + from copy import deepcopy as _deepcopy + _snap_k2m = _deepcopy(_ObsUtils.OBS_KEYS_TO_MODALITIES) + _snap_m2k = _deepcopy(_ObsUtils.OBS_MODALITIES_TO_KEYS) + policy, ckpt_dict = FileUtils.policy_from_checkpoint(ckpt_path=ckpt_path, device=device, verbose=False) + if _snap_k2m is not None: + _crit_k2m = _ObsUtils.OBS_KEYS_TO_MODALITIES or {} + _merged_k2m, _merged_m2k = _snap_k2m, (_snap_m2k if _snap_m2k is not None else {}) + for _k, _m in dict(_crit_k2m).items(): + if _k not in _merged_k2m: + _merged_k2m[_k] = _m + _merged_m2k.setdefault(_m, []) + if _k not in _merged_m2k[_m]: + _merged_m2k[_m].append(_k) + _ObsUtils.OBS_KEYS_TO_MODALITIES = _merged_k2m + _ObsUtils.OBS_MODALITIES_TO_KEYS = _merged_m2k + algo = policy.policy + # Does this critic read `dino_state`? Read it off the CHECKPOINT'S OWN obs spec, not off the + # path/family name, so nothing can be mis-detected by a directory that happens to contain "dino". + _low_dim = [] + try: + import json as _json + _cfg = _json.loads(ckpt_dict["config"]) + _low_dim = list(((_cfg.get("observation") or {}).get("modalities") or {}).get("obs", {}).get("low_dim") or []) + except Exception: + _low_dim = [] + _state = None + if "dino_state" in _low_dim: + if not feat_stats: + raise RuntimeError( + "rsm_backend=iql: the critic %s was trained on the precomputed `dino_state` " + "(path (D)/(Dq)) and needs rsm_feat_stats=//feat_stats.npz to rebuild that " + "state from the env observation" % ckpt_path) + from robomimic.algo.rsm_scorer import PooledDinoState, CAMS, PROPRIO_KEYS + _state = PooledDinoState(feat_stats, cams=CAMS, proprio_keys=PROPRIO_KEYS).to(device) + # RISE's own eval (sim_pipeline/eval/rollout_policies/robomimic_sampling_rollout_policy.py:96) scores with + # nets["critic"], the ONLINE ensemble, not the target copy. Default to that; RSM_IQL_TARGET=1 restores the + # old behaviour so the two can be compared. + import os as _os + _want_target = _os.environ.get("RSM_IQL_TARGET", "0") == "1" + if _want_target and "critic_target" in algo.nets: + critics = algo.nets["critic_target"] + else: + critics = algo.nets["critic"] if "critic" in algo.nets else algo.nets["critic_target"] + return cls(list(critics), own=False, ckpt=ckpt_path, state=_state, feat_stats=feat_stats) + + @torch.no_grad() + def score(self, obs_t, chunks, goal_dict=None): + a0 = chunks[:, 0] + qs = [critic(obs_dict=obs_t, acts=a0, goal_dict=goal_dict) for critic in self.critics] + return torch.cat(qs, 1).min(dim=1).values + + def describe(self): + d = {"backend": "iql", "n_critics": len(self.critics), "own_critic": self.own, "ckpt": self.ckpt, + "scored": "first action, min over ensemble"} + if self.state is not None: + d.update({"obs": "dino_state(precomputed pooled DINOv2 + proprio, z-scored)", + "feat_stats": self.feat_stats, "state_dim": int(self.state.d)}) + return d + + +class IFQLCriticBackend: + """gen_q#264: score candidates with an IFQL critic -- the flagship's second value-function baseline. + + IFQL (implicit flow Q-learning, the flow variant of IDQL) is trained by rsm_rise/code/ifql/train_ifql.py + on the SAME binary data-provenance reward every other column uses, over the SAME observation the RSM + scorer sees (the pooled frozen-DINOv2 state of the current frame, z-scored with the Stage-1 cache's + feat_stats.npz). Its critic is an HL-Gauss two-hot Q, so a score is already on the [0, 1] + "discounted average provenance label" scale. + + Like the `iql` backend, and for the same reason, the Q is read on the FIRST action of the candidate + chunk (an IFQL critic is a single-step Q over (s, a), so the chunk beyond a_0 is not part of its input) + and the ensemble is aggregated the way IFQL itself aggregates it at action time (`q_agg`, mean by + default -- min for the RISE/IQL critic is that method's own convention, not ours to impose here). + + Configured through the usual planner keys: `rsm_backend=ifql`, `rsm_ckpt=<...>/ifql_bundle.pt`, + `rsm_feat_stats=/feat_stats.npz`. The successor-model knobs (plan_beta, plan_depth, + plan_particles, plan_score, ...) are carried by the launcher but never read, exactly as for `iql`. + """ + + def __init__(self, ckpt, feat_stats, device, img_layout="chw", cams=None, proprio_keys=None): + from robomimic.algo.ifql_torch import IFQLTorch + from robomimic.algo.rsm_scorer import PooledDinoState, CAMS, PROPRIO_KEYS + self.ckpt = ckpt + self.agent = IFQLTorch(ckpt, device=device) + if not feat_stats: + feat_stats = self.agent.feat_stats + if not feat_stats: + raise RuntimeError("rsm_backend=ifql needs rsm_feat_stats (or a bundle that records one)") + self.state = PooledDinoState(feat_stats, cams=cams or CAMS, + proprio_keys=proprio_keys or PROPRIO_KEYS, + img_layout=img_layout).to(device) + self.feat_stats = feat_stats + + @torch.no_grad() + def state_from_obs(self, obs_t): + return self.state(obs_t) + + @torch.no_grad() + def score(self, x, chunks, goal_dict=None): + """x [B*N, d] z-scored DINO states, chunks [B*N, chunk, adim] -> Q [B*N].""" + return self.agent.q(x, chunks[:, 0]) + + def describe(self): + d = self.agent.describe() + d.update({"feat_stats": self.feat_stats, "state_dim": int(self.state.d)}) + return d + + +def RSMScorerState(st): + """BEAM_RISE: RSMScorer.as_state, imported lazily (rsm_scorer pulls in rsm_libero).""" + from robomimic.algo.rsm_scorer import RSMScorer + return RSMScorer.as_state(st) + + +class RSMPlannerMixin: + """See module docstring. Requires `self.algo_config`, `self.nets`, `self.device`, `self.ac_dim` + and `_sample_action_chunks` on the host class.""" + + # ---- configuration ----------------------------------------------------- + def configure_planner(self, **kw): + """Override planner keys at run time (the eval config, not the checkpoint, decides the planner).""" + from robomimic.algo.rsm_beam import BEAM_DEFAULTS as _BEAM_DEFAULTS # BEAM_RISE 2026-11-09 (additive) + unknown = set(kw) - set(PLANNER_DEFAULTS) - set(ADV_DEFAULTS) - set(_BEAM_DEFAULTS) + if unknown: + raise KeyError(f"unknown planner keys {sorted(unknown)}") + ov = getattr(self, "_planner_overrides", None) or {} + ov.update(kw) + self._planner_overrides = ov + self._planner_scorer = None + self._planner_cfg_cache = None + + def planner_cfg(self): + cache = getattr(self, "_planner_cfg_cache", None) + if cache is not None: + return cache + cfg = {} + for k, d in list(PLANNER_DEFAULTS.items()) + list(ADV_DEFAULTS.items()): + cfg[k] = _cfg_get(self.algo_config, k, d) + cfg.update(getattr(self, "_planner_overrides", None) or {}) + if cfg["plan_n"] is not None: + cfg["plan_n"] = int(cfg["plan_n"]) + cfg["plan_sample_batch"] = int(cfg["plan_sample_batch"] or 0) + cfg["plan_max_rows"] = int(cfg["plan_max_rows"] or 0) + if cfg["plan_rule"] not in RULES: + raise ValueError(f"plan_rule={cfg['plan_rule']} not in {RULES}") + self._planner_cfg_cache = cfg + return cfg + + @property + def planning_enabled(self): + n = self.planner_cfg()["plan_n"] + return n is not None and n > 1 + + def _get_scorer(self): + sc = getattr(self, "_planner_scorer", None) + if sc is not None: + return sc + cfg = self.planner_cfg() + if cfg["rsm_backend"] == "iql": + if cfg["rsm_ckpt"]: + sc = IQLCriticBackend.from_checkpoint(cfg["rsm_ckpt"], self.device, + feat_stats=cfg["rsm_feat_stats"]) + else: + if "critic" not in self.nets or len(self.nets["critic"]) == 0: + raise RuntimeError("rsm_backend=iql needs a checkpoint with critic nets") + sc = IQLCriticBackend(list(self.nets["critic"]), own=True) + elif cfg["rsm_backend"] == "ifql": + if not cfg["rsm_ckpt"]: + raise RuntimeError("rsm_backend=ifql needs rsm_ckpt (an ifql_bundle.pt)") + sc = IFQLCriticBackend(cfg["rsm_ckpt"], cfg["rsm_feat_stats"], self.device, + img_layout=cfg["rsm_img_layout"]) + else: + from robomimic.algo.rsm_scorer import RSMScorer, MAX_ROWS as _SCORER_MAX_ROWS + if not cfg["rsm_ckpt"] or not cfg["rsm_feat_stats"]: + raise RuntimeError("rsm_backend=%s needs rsm_ckpt and rsm_feat_stats" % cfg["rsm_backend"]) + # TAIL ALARM (2026-09-21): one hop is a Geom(1-beta) draw of mean 1/(1-beta) frames, discounted by + # gamma**(1/(1-beta)); after plan_depth hops the fold DROPS gamma**(depth/(1-beta)) of the gamma-mass. + # Nothing ever checked it (depth was swept and picked by success); say so loudly when most of the + # mass is dropped, so the read-out is understood as a short-horizon predictor, not a gamma-value. + # The TAIL ALARM measures the DETERMINISTIC fold's dropped gamma-mass. The coin chain drops + # nothing by construction (its cap is set so P(truncation) <= 1e-3), so firing it there would be + # a false alarm; the chain prints its own banner from RSMScorer.__init__ and its own CAP ALARM. + # gen_q#273: the MPC read-outs take their horizon FROM gamma by construction (K chunks = + # ceil(H/hop_frames), H = 1/(1-gamma)), so the fold's dropped-mass alarm does not apply + # and would fire on every MPC cell. + _tail = (0.0 if cfg["plan_mode"] in ("chain", "chain_rb", "mpc", "mpc_disc", "beam") else + float(cfg["plan_gamma"]) ** (int(cfg["plan_depth"]) / (1.0 - float(cfg["plan_beta"])))) + if _tail > 0.5: + import sys as _sys + print(f"[rsm_planner] TAIL ALARM: depth={cfg['plan_depth']} beta={cfg['plan_beta']} gamma={cfg['plan_gamma']} " + f"drops {_tail:.0%} of the gamma-mass -- the read-out covers ~{int(cfg['plan_depth'])/(1-float(cfg['plan_beta'])):.0f} frames", file=_sys.stderr) + sc = RSMScorer(backend=cfg["rsm_backend"], ckpt=cfg["rsm_ckpt"], hop_ckpt=cfg["rsm_hop_ckpt"], + feat_stats=cfg["rsm_feat_stats"], + # BEAM_RISE 2026-11-09: plan_mode=beam scores its nodes with the chain read-out + mode=("chain" if cfg["plan_mode"] == "beam" else cfg["plan_mode"]), + depth=cfg["plan_depth"], + beta=cfg["plan_beta"], gamma=cfg["plan_gamma"], n_particles=cfg["plan_particles"], + flow_steps=cfg["plan_flow_steps"], device=self.device, + img_layout=cfg["rsm_img_layout"], dwm_module=cfg["rsm_dwm_module"], + score_kind=cfg["plan_score"], lcb_quantile=cfg["plan_lcb_quantile"], + rescore_top=cfg["plan_rescore_top"], + n_particles_rescore=cfg["plan_particles_rescore"], + temperature=cfg["plan_temperature"], + max_rows=cfg["plan_max_rows"] or _SCORER_MAX_ROWS, + chain_cap=int(cfg.get("plan_chain_cap", 0) or 0), + chain_tail_eps=float(cfg.get("plan_chain_tail_eps", 1e-3) or 1e-3), + chain_seed=(None if int(cfg.get("plan_chain_seed", -1) or -1) < 0 + else int(cfg["plan_chain_seed"])), + mpc_horizon=int(cfg.get("plan_mpc_horizon", 0) or 0)) + if sc.chunk != int(cfg["plan_chunk"]): + raise RuntimeError(f"plan_chunk={cfg['plan_chunk']} but the RSM was trained on chunk {sc.chunk}") + self._planner_scorer = sc + return sc + + def planner_describe(self): + cfg = dict(self.planner_cfg()) + if self.planning_enabled or cfg["rsm_ckpt"]: + try: + cfg["scorer"] = self._get_scorer().describe() + if cfg["plan_mode"] == "beam": # BEAM_RISE 2026-11-09 (additive) + cfg["beam"] = self._get_beam().describe() + except Exception as e: # description must never break an eval + cfg["scorer"] = {"error": repr(e)} + return cfg + + # ---- logging ----------------------------------------------------------- + def pop_plan_log(self): + log = getattr(self, "_plan_log", None) or [] + self._plan_log = [] + return log + + # ---- the action -------------------------------------------------------- + def _executed_window(self, naction): + To = self.algo_config.horizon.observation_horizon + Ta = self.algo_config.horizon.action_horizon + Tp = self.algo_config.horizon.prediction_horizon + start = To - 1 + if Tp == 1: # IQLDiffusion's no-chunking quirk + start -= 1 + return naction[:, start:start + Ta], start + + def _sample_chunked(self, rep, rep_goal, sample_batch): + """`_sample_action_chunks` over at most `sample_batch` rows at a time, concatenated. + + sample_batch <= 0 is the released path: a single call on the whole [B*N, ...] batch. The split is + purely a memory measure -- rows are independent under the sampler -- but it does change the order in + which the DDPM chain consumes the RNG, so it is opt-in via `training.plan_sample_batch`.""" + rows = rep[next(iter(rep))].shape[0] + if sample_batch <= 0 or rows <= sample_batch: + return self._sample_action_chunks(rep, rep_goal) + out = [] + for lo in range(0, rows, sample_batch): + hi = min(lo + sample_batch, rows) + sl = {k: v[lo:hi] for k, v in rep.items()} + sl_goal = None if rep_goal is None else {k: v[lo:hi] for k, v in rep_goal.items()} + out.append(self._sample_action_chunks(sl, sl_goal)) + return torch.cat(out, dim=0) + + # ---- BEAM_RISE 2026-11-09: plan_mode=beam (robomimic/algo/rsm_beam.py) ------------------------ + def _get_beam(self): + bs = getattr(self, "_planner_beam", None) + if bs is not None and bs.sc is self._get_scorer(): + return bs + from robomimic.algo.rsm_beam import BeamSearch + cfg = self.planner_cfg() + if cfg["rsm_backend"] != "mlp": + raise ValueError("plan_mode=beam is implemented on the mlp backend (got %s)" % cfg["rsm_backend"]) + if cfg["plan_rule"] != "argmax": + raise ValueError("plan_mode=beam selects by argmax of the path value (got plan_rule=%s)" % cfg["plan_rule"]) + bs = self._planner_beam = BeamSearch(self._get_scorer(), cfg) + return bs + + @torch.no_grad() + def _beam_get_action(self, obs_dict, naction, cand, B, N, t0, t_sample): + import json as _json, os as _os + scorer = self._get_scorer() + beam = self._get_beam() + t1 = time.time() + obs_t = {k: v[:, -1] for k, v in obs_dict.items()} + st = scorer.state_from_obs(obs_t) + z0 = scorer._inputs(RSMScorerState(st)) # [B, D] latent + A = scorer._flat_chunk(cand) # [B*N, da] + idx, f_rows, extra = [], [], [] + for b in range(B): + j, info = beam.plan(z0[b], A[b * N:(b + 1) * N]) + idx.append(j) + f1 = info["f1"].float().cpu() + f = info["f"].float().cpu() + rank1 = int((f1 > f1[j]).sum()) # 0 == the chosen root is best-of-N's own pick + f_rows.append(f1) + extra.append({"rank_l1": rank1, "f_fin_max": float(f.max()), "f1_chosen": float(f1[j]), + "f1_max": float(f1.max()), "levels": info["levels"], + **({"sel_rank": info["sel_rank"]} if "sel_rank" in info else {})}) + t_score = time.time() - t1 + idx_t = torch.tensor(idx, dtype=torch.long, device="cpu") # eval sets default tensor type to cuda + chosen = naction.view(B, N, *naction.shape[1:])[torch.arange(B, device=naction.device), + idx_t.to(naction.device)] + action, _ = self._executed_window(chosen) + s = torch.stack(f_rows) # [B, N] level-1 scores + ar = torch.arange(B, device="cpu") + log = getattr(self, "_plan_log", None) + if log is None: + log = self._plan_log = [] + log.append({ + "n": N, "rule": "beam", "idx": idx, "score_kind": "beam_" + beam.agg, + # score_* = the LEVEL-1 (best-of-N) log path value of the root chunks; score_chosen is the + # level-1 value of the root the beam executed, so score_max - score_chosen > 0 means the + # beam overrode best-of-N's pick. + "score_chosen": s[ar, idx_t].tolist(), "score_max": s.max(1).values.tolist(), + "score_mean": s.mean(1).tolist(), "score_std": s.std(1).tolist() if N > 1 else [0.0] * B, + "score_min": s.min(1).values.tolist(), + "ties_at_max": (s >= s.max(1, keepdim=True).values - 1e-6).sum(1).tolist(), + "t_sample": t_sample, "t_score": t_score, + }) + _p = _os.environ.get("RR_BEAM_LOG", "") + if _p: + try: + with open(_p, "a") as fh: + fh.write(_json.dumps({"t_sample": t_sample, "t_score": t_score, "idx": idx, "beam": extra}) + "\n") + except Exception: + pass + return action + + @torch.no_grad() # the rollout path has NO no_grad anywhere (sim_pipeline/eval/rollout.py + # -> robomimic_rollout_policy.predict -> get_action), so the released + # DDPM sampler retained an autograd graph across all 100 inference + # timesteps: ~75 GB of live activations at plan_n=2048, which is what + # actually capped the candidate-count ladder. Forward numerics and RNG + # draws are identical under no_grad, so every cell already on disk is + # unchanged; this only stops the graph being built. + def plan_get_action(self, obs_dict, goal_dict=None): + cfg = self.planner_cfg() + N = cfg["plan_n"] or 1 + if N <= 1: + naction = self._sample_action_chunks(obs_dict, goal_dict) + action, _ = self._executed_window(naction) + return action + + t0 = time.time() + keys = list(obs_dict.keys()) + B = obs_dict[keys[0]].shape[0] + rep = {k: v.repeat_interleave(N, 0) for k, v in obs_dict.items()} + rep_goal = None if goal_dict is None else {k: v.repeat_interleave(N, 0) for k, v in goal_dict.items()} + naction = self._sample_chunked(rep, rep_goal, cfg["plan_sample_batch"]) # [B*N, Tp, ac] + t_sample = time.time() - t0 + + _, start = self._executed_window(naction) + chunk = int(cfg["plan_chunk"]) + cand = naction[:, start:start + chunk] # [B*N, chunk, ac] + if cfg["plan_mode"] == "beam": # BEAM_RISE 2026-11-09: additive, no other mode enters + return self._beam_get_action(obs_dict, naction, cand, B, N, t0, t_sample) + # gen_q#273: keep the actions the released path discards. `naction` is [B*N, Tp=16, ac] and only + # the first `chunk` (8) of the executed window is scored; the rest is the PROPOSER'S OWN + # CONTINUATION of that same candidate and is what an MPC read-out should roll the world model over + # past frame 8. Write-only for every existing backend (rsm_mpc_ctx docstring), so no cell moves. + _mpc_ctx.set_tail(naction[:, start + chunk:]) # [B*N, Tp-start-chunk, ac] + obs_t = {k: v[:, -1] for k, v in obs_dict.items()} # current frame (To-1) + + t1 = time.time() + rule = cfg["plan_rule"] + scorer = None + q_prob = q_logit = q_lcb = q_problog = None # every read-out of the RSM scorer (for the log) + if rule in ("random", "first"): + # Both controls ignore the scores by construction, so the scorer is never built. The + # CANDIDATES are identical either way -- they come from the proposer, not the scorer -- which + # is what makes `first` a control on the same 128 draws at a fraction of the cost. + scores = torch.zeros(B * N, device=naction.device) + else: + scorer = self._get_scorer() + if isinstance(scorer, IQLCriticBackend): + obs_rep_t = {k: v[:, -1] for k, v in rep.items()} + if scorer.needs_dino_state: + # Encode the B CURRENT frames once and repeat across the N candidates -- the same + # thing the IFQL and RSM branches do. Encoding `rep` instead would run the frozen + # ViT B*N=128x too often for an identical result. + obs_rep_t["dino_state"] = scorer.state_from_obs(obs_t).repeat_interleave(N, 0) + scores = scorer.score(obs_rep_t, cand, goal_dict=rep_goal) + elif isinstance(scorer, IFQLCriticBackend): + # DINO is the expensive part, so encode the B current frames ONCE and repeat the state + # across the N candidates (the same thing the RSM path does below). + x = scorer.state_from_obs(obs_t).repeat_interleave(N, 0) + scores = scorer.score(x, cand) + else: + st = scorer.state_from_obs(obs_t) # B states + # The SCORER repeats its own state (gen_q#268). This line used to rebuild the + # namespace here as (x, tok, pr) and dropped the pixel backends' `img`: + # state_from_obs built LeWM's frames and the next line threw them away, so _inputs + # saw img=None and _rows died on `None.shape[0]` -- which is why no LeWM eval cell + # ever landed. A field list maintained in the caller goes stale; RSMScorer.repeat_state + # repeats whatever the state carries. + st_rep = scorer.repeat_state(st, N) + seed = cfg["plan_seed"] + scores = scorer.score(st_rep, cand, seed=None if seed is None or int(seed) < 0 else int(seed)) + q_prob = getattr(scorer, "last_q", None) + q_logit = getattr(scorer, "last_q_logit", None) + q_lcb = getattr(scorer, "last_q_lcb", None) + q_problog = getattr(scorer, "last_q_problog", None) + t_score = time.time() - t1 + + # plan_score=prob_log hands back a float64 array whose values sit near -depth * logit (about -490 at + # depth 4 on threading, where the reward logits are ~121). float32's spacing at that magnitude is + # 6e-5, which is still far below the O(1) gaps between candidates, but casting down would put the + # ranking back in the regime of "distinct candidates collapse to one float" that this read-out + # exists to leave -- and would make the 1e-6 tie tolerance below narrower than one ULP. So keep + # float64 when that is what the scorer produced; every other read-out is float32 exactly as before. + _sc = scores.detach().cpu() + s = (_sc.double() if _sc.dtype == torch.float64 else _sc.float()).view(B, N) + p = s if q_prob is None else q_prob.detach().float().cpu().view(B, N) + lg = None if q_logit is None else q_logit.detach().float().cpu().view(B, N) + lc = None if q_lcb is None else q_lcb.detach().float().cpu().view(B, N) + pl = None if q_problog is None else q_problog.detach().double().cpu().view(B, N) + gen = getattr(self, "_plan_generator", None) + if gen is None and cfg["plan_seed"] is not None and int(cfg["plan_seed"]) >= 0: + gen = torch.Generator().manual_seed(int(cfg["plan_seed"])) + self._plan_generator = gen + idx = select(s, rule, temp=cfg["plan_temp"], topk=cfg["plan_topk"], generator=gen) + + ar_dev = torch.arange(B, device=naction.device) + chosen = naction.view(B, N, *naction.shape[1:])[ar_dev, idx.to(naction.device)] + ar = torch.arange(B, device="cpu") + action, _ = self._executed_window(chosen) + + log = getattr(self, "_plan_log", None) + if log is None: + log = self._plan_log = [] + entry = { + "n": N, "rule": rule, "idx": idx.tolist(), + "score_kind": cfg["plan_score"] if q_prob is not None else ("none" if rule in ("random", "first") else "prob"), + # the RANKING array (Q̄ or Q̄_logit per plan_score; the IQL critic's Q for backend iql) + "score_chosen": s[ar, idx].tolist(), + "score_max": s.max(1).values.tolist(), "score_mean": s.mean(1).tolist(), + "score_std": s.std(1).tolist() if N > 1 else [0.0] * B, + "score_min": s.min(1).values.tolist(), + # ties at the max of the ranking array (argmax picks the first of them; that is uniform over the tied + # set ONLY IF candidates are exchangeable in index, which is an assumption -- plan_rule=first is the + # control that measures it, see select() and gen_q#282) and saturation of the probability read-out (Q̄ >= 0.999): both are 1 when + # the ranking carries nothing + "ties_at_max": (s >= s.max(1, keepdim=True).values - 1e-6).sum(1).tolist(), + "frac_saturated": (p >= 0.999).float().mean(1).tolist(), + # both read-outs of the RSM scorer, whichever one ranks + "prob_chosen": p[ar, idx].tolist(), "prob_max": p.max(1).values.tolist(), "prob_mean": p.mean(1).tolist(), + # gen_q#266: ties of the PROBABILITY array itself, regardless of which array ranks. `ties_at_max` + # above is the ranking array's, so under plan_score=prob_log it is prob_log's (~1) and says + # nothing about prob. This one makes "prob would have tied ~60 of 128 here, prob_log ties 1" a + # WITHIN-CELL comparison on the same states, instead of a comparison across two sweeps. + # (With a backend that has no probability read-out, p is the ranking array and this equals + # `ties_at_max` by construction.) + "prob_ties_at_max": (p >= p.max(1, keepdim=True).values - 1e-6).sum(1).tolist(), + "prob_ties_at_max_exact": (p == p.max(1, keepdim=True).values).sum(1).tolist(), + "prob_distinct": [int(torch.unique(p[b]).numel()) for b in range(B)], + "t_sample": t_sample, "t_score": t_score, + } + if lc is not None: + entry.update({"lcb_chosen": lc[ar, idx].tolist(), "lcb_max": lc.max(1).values.tolist(), + "lcb_mean": lc.mean(1).tolist(), + "lcb_std": lc.std(1).tolist() if N > 1 else [0.0] * B, + "lcb_quantile": float(getattr(scorer, "lcb_quantile", float("nan"))), + "lcb_ties_at_max": (lc >= lc.max(1, keepdim=True).values - 1e-6).sum(1).tolist()}) + if pl is not None: + # gen_q#266: prob_log is `prob` folded in the log-complement domain, so its tie count is the + # health number that makes the "prob ties ~60 of 128, prob_log ties 1" claim checkable from the + # eval JSON alone -- no re-scoring. Recorded beside `ties_at_max` / `logit_ties_at_max` and + # with the same 1e-6 absolute tolerance, on the float64 array (see the dtype note above). + entry.update({"prob_log_chosen": pl[ar, idx].tolist(), "prob_log_max": pl.max(1).values.tolist(), + "prob_log_mean": pl.mean(1).tolist(), + "prob_log_std": pl.std(1).tolist() if N > 1 else [0.0] * B, + "prob_log_ties_at_max": (pl >= pl.max(1, keepdim=True).values - 1e-6).sum(1).tolist(), + # The 1e-6 ABSOLUTE tolerance above is the convention the other read-outs use, + # but it is not a tie count for this one: prob_log = -log(1 - Q̄) ranges over 40+ + # orders of magnitude (about 124 where every candidate succeeds, about 1e-44 in a + # hopeless state where every logit is -100), so in the hopeless regime 1e-6 + # swallows the whole candidate set and reports 128 ties where the float64 values + # are in fact distinct. These two are tolerance-free and are what the ordering + # claim should be read off: exact bitwise equality, and the count of DISTINCT + # values in the array. + "prob_log_ties_at_max_exact": (pl == pl.max(1, keepdim=True).values).sum(1).tolist(), + "prob_log_distinct": [int(torch.unique(pl[b]).numel()) for b in range(B)]}) + if lg is not None: + entry.update({"logit_chosen": lg[ar, idx].tolist(), "logit_max": lg.max(1).values.tolist(), + "logit_mean": lg.mean(1).tolist(), + "logit_std": lg.std(1).tolist() if N > 1 else [0.0] * B, + "logit_ties_at_max": (lg >= lg.max(1, keepdim=True).values - 1e-6).sum(1).tolist()}) + log.append(entry) + return action diff --git a/code_src/rise_robomimic/robomimic/algo/rsm_scorer.py b/code_src/rise_robomimic/robomimic/algo/rsm_scorer.py new file mode 100644 index 0000000000000000000000000000000000000000..d228ec64f1faf7fdd108b4c3431f289bd0363339 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/rsm_scorer.py @@ -0,0 +1,1876 @@ +"""RSM (successor-model) scorer for RISE policy extraction (rsm_rise Stage 3). + +One object, two jobs: + + score(state, A) -> Q̄[N] E1: rank N candidate 8-step chunks at one state (common random + numbers across the N rows: particle i of every candidate uses the + same flow noise / hop-head noise / restart coin, so the arg-max is a + paired comparison). + advantage(state, A) -> Q̄, V̄_τ E2: Q̄ of the logged (kNN-swapped) chunk and the τ-expectile of Q̄ + over M hop-head chunks at the same state. + +State = the pooled DINO vector RISE's `DinoV2Core(concatenate=True)` produces for the CURRENT frame: +[agentview CLS|GeM (768) | wrist CLS|GeM (768) | eef_pos(3) eef_quat(4) gripper_qpos(2)] = 1545, z-scored +with the Stage-1 cache's feat_stats.npz (mu/sd over all frames, sd floored at 1e-3). Images arrive in the +policy's format (float CHW in [0,1], robomimic ObsUtils.process_frame), which is exactly what +scripts/relabel_dino.py fed DINO when it built the cache (NOT the H/W-transposed layout of RISE's +offline relabel_dino_features.py; `img_layout="rise_t"` reproduces that one if a cache ever needs it). + +Backends + mlp the rsm_libero MLP flow (train_rsm.py blob: enc/rew/flow/rms/config/d_act/enc_kind/d_in), + read-outs d1 / fold / recursive via is_ope.q_fold / q_recursive (crn=True). + dwm the token successor model (stream C): `dwm_readout.load_critic_dwm(path, device)` (module name + `rsm_dwm_module`, default `dwm_readout`), scoring RAW [B,514,384] tokens + RAW proprio; d1 / fold. + mc MC return-to-go MLP on [x | A] (S3H5 control), blob {"net", "config":{"d_in","d_act","width","depth"}}. +The IQL-critic backend (S3H4) lives in rsm_planner.py because it scores the raw obs dict with the +fork's own critic nets, not a DINO state. + +All read-outs return Q̄ on the success-probability scale ([0,1] for d1/fold; recursive is rescaled by +(1-γ) from is_ope's Q/(1-γ)). The E2 caller rescales (1/(1-γ) "td" or batch-standardised "std"). + +Logit read-out (stream E, orchestrator 13:05): d1 / fold also expose Q̄_logit = mean over particles of the +reward head's RAW logit at the last hop state (the DWM read-out's `q_logit` convention), which does not +saturate / tie at 1.0 the way mean-sigmoid does. `score_kind="logit"` ranks by it; `.last_q` / `.last_q_logit` +hold both arrays after every score() call. Temperature T (calib.json next to the checkpoint, or an explicit +override) enters only the sigmoid: q = mean_i σ(logit_i / T); the logit ranking is T-free. Two-stage screening +(rescore_top=K, n_particles_rescore=M): every candidate is scored with n_particles, the top-K by the ranking +array are rescored with M particles and written back (DWM: inside dwm_readout; MLP: here, second draw of the +seeded stream). Log-complement read-out (gen_q#266): `score_kind="prob_log"` ranks by the SAME quantity as "prob" -- the whole +product fold, averaged over particles -- but folded as log(1 - Q) so it never rounds to 1.0. `prob`'s ties are +numerical, not structural: threading cells record reward logits near +121, where σ is exactly 1.0 in float64 +and Q collapses to exactly 1.0 for ~60 of 128 candidates, so the arg-max there is a uniform draw inside the +tied set. `prob_log` is a strictly monotone transform of `prob`'s infinite-precision value, so it keeps the +fold (unlike "logit", which reports only the LAST hop's logit and discards hops 0..L-2) and still totally +orders the candidates. It needs the per-hop reward logits, so it is mlp-backend / d1-fold only, and +`.last_q_problog` holds it after every score() call. Rows of the MLP read-out are processed in slices of at most `max_rows` (65536) with the CRN +noise drawn ONCE for all particles, so plan_particles up to 32768 at N=128 fits and results do not depend on +the slicing. +""" +from __future__ import annotations + +import contextlib +import math +import importlib +import os +import sys +from types import SimpleNamespace + +import numpy as np +import torch +import torch.nn as nn + +RSM_LIBERO_DIR = os.environ.get( + "RSM_LIBERO_DIR", "/proj/dmfexp/zwhong/rsm_rise/code/gen_q/rsm_libero") + +CAMS = ("agentview_image", "robot0_eye_in_hand_image") +PROPRIO_KEYS = ("robot0_eef_pos", "robot0_eef_quat", "robot0_gripper_qpos") +D_TOK, N_PATCH = 384, 256 +STATE_DIM = 2 * 2 * D_TOK + 9 # 1545 + +# "chain"/"chain_rb" (gen_q#267): the coin-terminated beta chain, the ogbench_genq/rsm.py read-out. +# ADDED, never substituted -- d1/fold/recursive are byte-for-byte the code they were. +# gen_q#273: "mpc" / "mpc_disc" are the WORLD-MODEL MPC read-outs (dwm / dinowm / lewm backends only). +# The roll-out is the same open-loop one the fold performs; only the combination of the per-chunk +# reward-head values differs -- terminal latent, or the gamma-discounted sum over the roll-out. +_MODES = ("d1", "fold", "recursive", "chain", "chain_rb", "mpc", "mpc_disc") +_MPC_MODES = ("mpc", "mpc_disc") +# Backends whose state is the RAW token frame + raw proprio rather than the pooled 1545-d vector, and +# whose q() takes the dwm read-out's kwargs (crn_seed, internal two-stage rescore). gen_q#268 adds +# `dinowm`: the same token state and the same read-out interface, with DINO-WM's deterministic latent +# dynamics in place of the occupancy flow (rsm_libero/dinowm_readout.py). +TOKEN_BACKENDS = ("dwm", "dinowm") +# Default read-out module per backend; `rsm_dwm_module` overrides it (that is how stream C injects an +# alternative DWM read-out). Keyed by backend so `rsm_backend=dinowm` needs no extra hydra override +# and the eval JSON records WHICH scorer ran in `rsm_backend` itself -- which is what +# scripts/verdict_table.py classifies the arm on. +READOUT_MODULE = {"dwm": "dwm_readout", "dinowm": "dinowm_readout"} +_SCORE_KINDS = ("prob", "logit", "prob_log", "conformal_lcb") +MAX_ROWS = 65536 # rows (candidates x particles) per slice of the MLP read-out +# coin-terminated beta chain: the cap is chosen so P(walk longer than cap) <= this. The reference +# (ogbench_genq/rsm.py:76) documents exactly this rule -- its REC_MAX_DEPTH = 10 is the ~1e-3 tail at +# beta = 0.98. Never hard-code a cap; call chain_cap(beta, gamma). +CHAIN_TAIL_EPS = 1e-3 + + +def read_calib_temperature(ckpt): + """calib.json next to a checkpoint (rsm_libero/calib_dwm.py: {"T": ...}) -> T, or None if absent/unreadable.""" + try: + cj = os.path.join(os.path.dirname(os.path.abspath(ckpt)), "calib.json") + if os.path.exists(cj): + import json + return float(json.load(open(cj))["T"]) + except Exception as e: # a broken calib file must not break the scorer; T = 1 + print(f"[rsm_scorer] calib.json next to {ckpt} unreadable ({e}); T=1", flush=True) + return None + + +def _rsm_modules(): + """Import rsm_libero's model / train_rsm / is_ope lazily (they are plain top-level modules).""" + if RSM_LIBERO_DIR not in sys.path: + sys.path.insert(0, RSM_LIBERO_DIR) + model = importlib.import_module("model") + train_rsm = importlib.import_module("train_rsm") + is_ope = importlib.import_module("is_ope") + return model, train_rsm, is_ope + + +@contextlib.contextmanager +def seeded(seed, device=None): + """Fork the RNG state and seed it, so a scorer call is reproducible without disturbing the + caller's stream (the diffusion sampler's noise must stay independent of the scorer's).""" + if seed is None or int(seed) < 0: + yield + return + devices = [] + if device is not None and torch.device(device).type == "cuda" and torch.cuda.is_available(): + devices = [torch.device(device)] + with torch.random.fork_rng(devices=devices): + torch.manual_seed(int(seed)) + yield + + +def gem_pool(patch_tokens): + """DinoV2Core's GeM: [B,256,384] -> [B,384] (clamp 1e-6, pow 4, mean over the 16x16 grid, pow 1/4).""" + B = patch_tokens.shape[0] + pd = int(np.sqrt(patch_tokens.shape[-2])) + p = patch_tokens.reshape(B, pd, pd, -1).clamp(min=1e-6).permute(0, 3, 1, 2) + return nn.functional.avg_pool2d(p.pow(4), (pd, pd)).pow(1 / 4).reshape(B, -1) + + +def pooled_from_tokens(tok): + """[B,514,384] (agentview CLS, 256 patches, wrist CLS, 256 patches) -> [B,1536] = z.f16.npy layout.""" + out = [] + for c in range(2): + cls = tok[:, c * (1 + N_PATCH)] + pt = tok[:, c * (1 + N_PATCH) + 1:(c + 1) * (1 + N_PATCH)] + out.append(torch.cat([cls, gem_pool(pt)], -1)) + return torch.cat(out, -1) + + +def expectile(q, tau, iters=50): + """tau-expectile of each row of q [B,M] (tau=0.5 is exactly the mean). + Fixed-point iteration of the asymmetric-least-squares stationarity condition.""" + tau = float(tau) + v = q.mean(1, keepdim=True) + if abs(tau - 0.5) < 1e-12: + return v[:, 0] + for _ in range(iters): + w = torch.where(q > v, torch.full_like(q, tau), torch.full_like(q, 1.0 - tau)) + v_new = (w * q).sum(1, keepdim=True) / w.sum(1, keepdim=True) + if torch.allclose(v_new, v, atol=1e-7, rtol=0): + v = v_new + break + v = v_new + return v[:, 0] + + +# --------------------------------------------------------------------------- # +# state: pooled DINO vector / tokens from the policy's obs dict +# --------------------------------------------------------------------------- # +class PooledDinoState(nn.Module): + """obs dict at ONE time step (values [B, ...], images float CHW in [0,1]) -> z-scored 1545-d state. + + `dino` may be any module with `.backbone_model` (a dinov2 hub model) and `.transform`; by default + RISE's DinoV2Core (frozen, concatenate=True) is instantiated, which is what the cache used.""" + + def __init__(self, feat_stats, cams=CAMS, proprio_keys=PROPRIO_KEYS, backbone="dinov2_vits14", + img_layout="chw", dino=None): + super().__init__() + self.cams = tuple(cams) + self.proprio_keys = tuple(proprio_keys) + self.img_layout = img_layout + if dino is None: + from robomimic.models.obs_core import DinoV2Core + dino = DinoV2Core(input_shape=(3, 84, 84), backbone_name=backbone, frozen=True, concatenate=True) + self.dino = dino.eval() + for p in self.dino.parameters(): + p.requires_grad_(False) + # STATE DEFINITION (Stage 1, final): x = clip((feat - mu) / max(sd, sd_floor), -z_clip, z_clip). + # sd_floor / z_clip come from feat_stats.npz (relabel_dino.py writes them), else PACK.json next + # to it, else the defaults 0.01 / 10 -- identical to rsm_libero data.py._feat. + st = np.load(feat_stats) + mu = np.asarray(st["mu"], np.float32) + sd = np.asarray(st["sd"], np.float32) + sd_floor, z_clip = None, None + if "sd_floor" in st.files: + sd_floor = float(st["sd_floor"]) + if "z_clip" in st.files: + z_clip = float(st["z_clip"]) + pack = os.path.join(os.path.dirname(os.path.abspath(feat_stats)), "PACK.json") + if (sd_floor is None or z_clip is None) and os.path.exists(pack): + import json + pk = json.load(open(pack)) + sd_floor = float(pk.get("sd_floor", 0.01)) if sd_floor is None else sd_floor + z_clip = float(pk.get("z_clip", 10.0)) if z_clip is None else z_clip + self.sd_floor = 0.01 if sd_floor is None else sd_floor + self.z_clip = 10.0 if z_clip is None else z_clip + sd = np.maximum(sd, self.sd_floor).astype(np.float32) + self.register_buffer("mu", torch.as_tensor(mu)) + self.register_buffer("sd", torch.as_tensor(sd)) + self.d = int(mu.shape[0]) + + def normalize(self, feat): + """[B, d] raw [z | proprio] -> the trainer's state (z-score with floored sd, then clip).""" + x = (feat - self.mu) / self.sd + if self.z_clip and self.z_clip > 0: + x = x.clamp(-self.z_clip, self.z_clip) + return x + + def _images(self, obs_t): + ims = [] + for c in self.cams: + im = obs_t[c].float() + if im.dim() == 3: + im = im[None] + if self.img_layout == "rise_t": # RISE's offline relabel: (N,H,W,C)->(N,C,W,H) + im = im.transpose(-1, -2) + ims.append(im) + return ims + + def _proprio(self, obs_t, B): + pr = [obs_t[k].float().reshape(B, -1) for k in self.proprio_keys] + return torch.cat(pr, -1) + + @torch.no_grad() + def forward(self, obs_t): + ims = self._images(obs_t) + feats = [self.dino(im) for im in ims] # each [B, 768] + B = feats[0].shape[0] + x = torch.cat(feats + [self._proprio(obs_t, B)], -1) + if x.shape[1] != self.d: + raise RuntimeError(f"pooled state is {x.shape[1]}-d but feat_stats has {self.d} dims") + return self.normalize(x) + + @torch.no_grad() + def raw_features(self, obs_t): + """Un-normalised [z(1536) | proprio(9)] -- what the cache stores (z as fp16).""" + ims = self._images(obs_t) + feats = [self.dino(im) for im in ims] + B = feats[0].shape[0] + return torch.cat(feats + [self._proprio(obs_t, B)], -1) + + @torch.no_grad() + def tokens(self, obs_t): + """[B,514,384] raw (un-normalised) DINO tokens in the cache's token order, plus the pooled state.""" + ims = self._images(obs_t) + toks, pooled = [], [] + for im in ims: + f = self.dino.backbone_model.forward_features(self.dino.transform(im)) + cls, pt = f["x_norm_clstoken"], f["x_norm_patchtokens"] + toks.append(torch.cat([cls[:, None], pt], 1)) + pooled.append(torch.cat([cls, gem_pool(pt)], -1)) + B = toks[0].shape[0] + tok = torch.cat(toks, 1) + x = torch.cat(pooled + [self._proprio(obs_t, B)], -1) + return tok, self.normalize(x) + + +# --------------------------------------------------------------------------- # +# hop head (Stage 2, bc_arm.py policy_r1.pt) +# --------------------------------------------------------------------------- # +class HopPolicy(nn.Module): + """Wraps a bc_arm.py policy so q_fold / q_recursive can call sample_eps(z, task, eps) on the + z-scored state. bc_arm's `--policy-features raw --feat-scale center` rescales the input by + sd / mean(sd) over the visual block (RawFeat); `zscore` is the identity.""" + + def __init__(self, pol, scale): + super().__init__() + self.pol = pol + self.d_act = int(pol.d_act) if hasattr(pol, "d_act") else int(pol.mu.out_features) + self.register_buffer("scale", torch.as_tensor(scale, dtype=torch.float32)) + + def sample_eps(self, z, task, eps): + z = z * self.scale + if hasattr(self.pol, "sample_eps"): # BCHead, ConcatFlowPolicy + return self.pol.sample_eps(z, task, eps) + # FlowPolicy: its Euler loop started from the supplied noise (CRN) + a = eps + steps = int(getattr(self.pol, "steps", 8)) + for s in range(steps): + k = torch.full((z.shape[0],), 1.0 - s / steps, device=z.device) + a = a + self.pol.velocity(z, task, a, k) / steps + return a + + def sample(self, z, task): + return self.pol.sample(z * self.scale, task) + + +def load_hop_head(path, d_z, n_task, device, feat_sd=None): + model, _, _ = _rsm_modules() + ck = torch.load(path, map_location=device, weights_only=False) + c = ck["config"] + sd_ = ck["pol"] + fam = c.get("policy_family", "concat") + if c.get("policy_features", "raw") != "raw": + raise RuntimeError("hop head must read raw (z-scored) features; got policy_features=" + f"{c.get('policy_features')}") + if fam == "gauss": + d_act = sd_["mu.weight"].shape[0] + pol = model.BCHead(d_z, d_act, n_task) + elif fam == "flow": + d_act = sd_["out.weight"].shape[0] + pol = model.FlowPolicy(d_z, d_act, n_task) + else: + last = max(int(k.split(".")[1]) for k in sd_ if k.startswith("net.") and k.endswith(".weight")) + d_act = sd_[f"net.{last}.weight"].shape[0] + pol = model.ConcatFlowPolicy(d_z, d_act, n_task, width=int(c.get("pol_width", 1024) or 1024), + depth=int(c.get("pol_depth", 4) or 4)) + pol.load_state_dict(sd_) + pol = pol.to(device).eval() + for p in pol.parameters(): + p.requires_grad_(False) + scale = np.ones(d_z, np.float32) + if c.get("feat_scale", "zscore") == "center": + if feat_sd is None: + raise RuntimeError("hop head trained with --feat-scale center needs feat_stats sd") + n_z = d_z - 9 + scale[:n_z] = feat_sd[:n_z] / max(float(feat_sd[:n_z].mean()), 1e-6) + return HopPolicy(pol, scale).to(device), int(c.get("chunk", 8)) + + +def _particle_quantile(qp, p): + """p-quantile over the particle axis of a [B, n] per-particle score matrix (the conformal read-out's + lower confidence bound). torch.quantile caps its input at 2**24 elements, so it is applied row-blockwise.""" + qp = qp.float() + p = float(p) + if not 0.0 < p < 1.0: + raise ValueError(f"plan_lcb_quantile must be in (0, 1), got {p}") + n = qp.shape[1] + if n < 2: + return qp[:, 0].clone() + rows = max(1, (2 ** 24) // n) + if rows >= qp.shape[0]: + return torch.quantile(qp, p, dim=1) + return torch.cat([torch.quantile(qp[i:i + rows], p, dim=1) for i in range(0, qp.shape[0], rows)], 0) + + +# --------------------------------------------------------------------------- # +# MLP read-out with the raw logit (is_ope.q_fold re-implemented; is_ope.py belongs to another stream) +# --------------------------------------------------------------------------- # +@torch.no_grad() +def _q_fold_logit(enc_z, a_chunk, task, *, rew, flow, rms, pol, beta, gamma, depth=1, n_particles=16, + flow_steps=8, temperature=1.0, max_rows=MAX_ROWS, return_particles=False, + return_problog=False, return_trace=False, openloop=False, + sample_clip=0.0): + """is_ope.q_fold (crn=True) with the reward head's RAW logit collected at the read-out states. + + Returns (q_mean [B], logit_mean [B]): q_mean = the product fold Q_k = c_k + (1 - c_k) γ^h Q_{k+1} with + c_k = σ(R(z_k) / T), Monte-Carlo mean over particles (== q_fold's first output when T = 1); logit_mean = + mean over particles of R(z_L) at the LAST hop (the DWM read-out's q_logit convention; at depth 1 it is the + logit of the d1 read-out). CRN exactly as q_fold: the noise for hop k (x0 [n, D]) and the hop-head noise + (eps [n, d_act]) are drawn from the current torch stream in q_fold's order and tiled over the candidates + (row b*n + i = candidate b, particle i). All of it is drawn ONCE up front, then the B*n rows are processed + in slices of at most `max_rows` rows (whole candidates; particles are sliced too when one candidate alone + exceeds max_rows), so the estimate does not depend on the slicing. + + return_particles=True appends the per-particle fold values q [B, n] (whose mean over dim 1 is q_mean); the + conformal read-out ranks by a low quantile of that row instead of its mean. + + return_trace=True appends a VISUALISATION-ONLY dict of the intermediate quantities the fold already + computes and throws away (gen_q#270, the successor-stitching figure): per hop k in 0..depth-1 the + successor SAMPLES z_k [depth, B, n, D] (fp16), the raw reward logits lg [depth, B, n], the membership + c_k = sigmoid(lg/T) [depth, B, n], the hop-head action chunk that PRODUCED each z_k [depth, B, n, d_act] + (fp16; hop 0's is the candidate itself), and the backward fold's partial values q_k [depth+1, B, n] with + q_k[depth] = 0 and q_k[0] == the per-particle q that q_mean averages. It draws NOTHING extra from the + RNG and writes into preallocated buffers after each existing computation, so q_mean / logit_mean / + prob_log are bit-identical with the flag on and off (tests/test_rsm_trace.py asserts exactly that). + + return_problog=True appends the `prob_log` ranking array [B] (higher is better): the SAME quantity as + q_mean, computed in the log-complement domain so it does not collapse when σ saturates. Derivation + (gen_q#266) -- with G = γ^h, q_L = 0 and q_k = c_k + (1 - c_k) G q_{k+1}: + + 1 - q_k = (1 - c_k) (1 - G q_{k+1}) (exact) + u_k := log(1 - q_k) = logσ(-lg_k / T) + log1p(G expm1(u_{k+1})), u_L = 0 (*) + + using 1 - G q_{k+1} = 1 - G(1 - e^{u_{k+1}}) = 1 + G expm1(u_{k+1}), so the recursion is closed in the + log domain and never reads the float32 q (which is a DENORMAL in a hopeless state and corrupted the + ranking at depth >= 2 when it was used; see the comment in the loop). + + NOTE this is a one-step RECURSION, not a sum over hops. The issue's summed form + `u_0 = Σ_k [log(1-c_k) + log(1 - G q_{k+1})]` double-counts, because log(1 - G q_{k+1}) is not + log(1 - q_{k+1}) unless G = 1, so each term is short a -log(1 - q_{k+1}). Counterexample: L = 2, + c = (0.5, 0.5), G = 0.5 -> q_0 = 0.625, u_0 = -0.98083, while the sum gives -1.67398 (1 - q_0 = 0.1875 + instead of 0.375). (*) is what is implemented, and the test asserts it against a float64 loop. + + Both terms of (*) are well conditioned where the probability form is not: logσ(-lg/T) returns about -121 + for lg/T = 121 instead of log(0) = -inf, and q_{k+1} in [0, 1] with G < 1 gives 1 - G q_{k+1} >= 1 - G + (0.182 at beta=0.95, gamma=0.99), so reusing the fold's own float q_{k+1} there costs only a relative + O(eps) error. The per-particle mean is taken in the SAME domain, so the order is exactly the order of + the infinite-precision q_mean: since mean_i q_i = 1 - mean_i (1 - q_i), ranking by mean_i q_i descending + is ranking by log(mean_i exp(u_i)) ascending, and the array returned is its negation. That mean is + taken as m + log1p(mean_i expm1(u_i - m)) with m = max_i u_i, NOT as logsumexp_i(u_i) - log n; see the + comment at the return for why the logsumexp form collapses in the hopeless regime.""" + _, train_rsm, _ = _rsm_modules() + sample_future = train_rsm.sample_future + dev = enc_z.device + B, D = enc_z.shape + n, depth = int(n_particles), int(depth) + if depth >= 2 and pol is None: + raise RuntimeError(f"fold at depth {depth} needs a hop head (rsm_hop_ckpt)") + beta, gamma = float(beta), float(gamma) + h = 1.0 / (1.0 - beta) + T = float(temperature) if temperature else 1.0 + x0s, epss = [], [] + for k in range(depth): # same draw order as q_fold(crn=True) + x0s.append(torch.randn(n, D, device=dev)) + if k < depth - 1: + epss.append(torch.randn(n, int(pol.d_act), device=dev)) + max_rows = max(int(max_rows), 1) + cand_per = max(1, max_rows // n) + part_per = n if n <= max_rows else max_rows + q_out = torch.empty(B, n, device=dev, dtype=torch.float32) + lg_out = torch.empty(B, n, device=dev, dtype=torch.float32) + # log(1 - q) per particle, accumulated in float64: the saturated values sit near -121 * depth, where + # float32's absolute resolution (1e-5 at that magnitude) is still far below the O(0.1) logit gaps we + # need to order, but float64 costs one [B, n] buffer and removes the question. + lq_out = torch.empty(B, n, device=dev, dtype=torch.float64) if return_problog else None + # visualisation-only buffers (gen_q#270); None unless return_trace + tr = None + if return_trace: + tr = {"z": torch.empty(depth, B, n, D, device=dev, dtype=torch.float16), + "a": torch.empty(depth, B, n, a_chunk.shape[1], device=dev, dtype=torch.float16), + "lg": torch.empty(depth, B, n, device=dev, dtype=torch.float32), + "c": torch.empty(depth, B, n, device=dev, dtype=torch.float32), + "q": torch.zeros(depth + 1, B, n, device=dev, dtype=torch.float32)} + G = gamma ** h + # G capped strictly below 1 for the log-domain fold only: at G == 1 (gamma == 1) the term + # log1p(G * expm1(u)) would be log(0) = -inf for a fully saturated hop. q_out's fold keeps the + # uncapped G, so `prob` and `logit` stay bit-identical. + G_l = min(G, 1.0 - 1e-12) + for b0 in range(0, B, cand_per): + b1 = min(B, b0 + cand_per); nb = b1 - b0 + for p0 in range(0, n, part_per): + p1 = min(n, p0 + part_per); npp = p1 - p0 + z = enc_z[b0:b1].repeat_interleave(npp, 0) + a = a_chunk[b0:b1].repeat_interleave(npp, 0) + tk = task[b0:b1].repeat_interleave(npp, 0) + bq = torch.full((z.shape[0],), beta, device=dev) + cs, lcs, lg = [], [], None + for k in range(depth): + x0 = x0s[k][p0:p1].repeat(nb, 1) + if tr is not None: + tr["a"][k, b0:b1, p0:p1] = a.detach().view(nb, npp, -1).half() + z = sample_future(flow, z, a, tk, bq, rms, flow_steps, n=1, x0=x0) + # gen_q#271. The label's own rollout (stitch_decompose.py) clamps the sampled + # latent to the trainer's `sample_clip` after EVERY hop; the fold never has. At + # depth 1 that is invisible (R is read at the sampled z either way, and the + # clamp only ever binds on the tail), but at depth >= 2 an unclamped z is fed + # back into the flow and the two rollouts drift apart. Default 0.0 == off == + # the historic fold, so every archived cell is bit-identical. + if sample_clip > 0: + z = z.clamp(-sample_clip, sample_clip) + lg = rew(z, tk).float() + cs.append(torch.sigmoid(lg / T)) + if tr is not None: + tr["z"][k, b0:b1, p0:p1] = z.detach().view(nb, npp, -1).half() + tr["lg"][k, b0:b1, p0:p1] = lg.detach().view(nb, npp) + tr["c"][k, b0:b1, p0:p1] = cs[-1].detach().view(nb, npp) + if return_problog: + # log(1 - c_k) = log σ(-lg_k / T), exact for large positive logits + lcs.append(nn.functional.logsigmoid(-(lg.double() / T))) + if k == depth - 1: + break + # gen_q#271. CLOSED LOOP (default, unchanged): the action for the next hop is + # RE-SAMPLED from the hop head, so Q estimates "apply this candidate once, then + # follow the hop policy". OPEN LOOP (openloop=True): the candidate action chunk + # is REPEATED at every hop, which is the generating process of the stitching + # diagnostic's own GOAL/FAIL label (stitch_decompose.py never reassigns `act` + # inside its hop loop). The eps draws above are kept either way, so the flow + # noise x0s is bit-identical between the two settings and the only thing that + # differs is which action is applied. + if not openloop: + a = pol.sample_eps(z, tk, epss[k][p0:p1].repeat(nb, 1)) + q = torch.zeros_like(cs[-1]) + lq = None if not return_problog else torch.zeros_like(lcs[-1]) # u_L = log(1 - q_L) = 0 + for k in range(depth - 1, -1, -1): # backward fold + c = cs[k] + if return_problog: + # u_k = log(1 - c_k) + log(1 - G q_{k+1}), with the second term written WITHOUT q: + # 1 - G q_{k+1} = 1 - G(1 - e^{u_{k+1}}) = 1 + G expm1(u_{k+1}). + # Using the fold's own float32 q_{k+1} here was wrong at the bottom of the range and a + # 90-digit reference caught it: in a hopeless state c_k = sigmoid(-100) = 3.7e-44 is a + # float32 DENORMAL with 2-3 bits of mantissa, and log1p(-G q) is then the same + # magnitude as log(1 - c_k) itself, so the quantisation corrupted the ranking at every + # depth >= 2 (depth 1 was unaffected, which is why the preflight cell looked fine). + # This form is closed in float64: expm1 is exact for tiny u, log1p for tiny arguments, + # and the saturated end is unchanged (u -> -inf gives log1p(-G) = log(1 - G)). + lq = lcs[k] + torch.log1p(G_l * torch.expm1(lq)) + q = c + (1.0 - c) * G * q + if tr is not None: + tr["q"][k, b0:b1, p0:p1] = q.detach().view(nb, npp) + q_out[b0:b1, p0:p1] = torch.nan_to_num(q, nan=0.0).clamp(0.0, 1.0).view(nb, npp) + lg_out[b0:b1, p0:p1] = torch.nan_to_num(lg, nan=0.0).view(nb, npp) + if return_problog: + # nan -> 0.0 is the SAME fallback as q's (q = 0 <-> log(1 - q) = 0), and clamp_max(0) + # mirrors q.clamp(0, 1)'s upper end (q >= 0 <-> u <= 0). + lq_out[b0:b1, p0:p1] = torch.nan_to_num(lq, nan=0.0).clamp(max=0.0).view(nb, npp) + out = [q_out.mean(1), lg_out.mean(1)] + if return_particles: + out.append(q_out) + if return_problog: + # rank = -log(mean_i (1 - q_i)) = -log(mean_i exp(u_i)): monotone in the exact q_mean, higher better. + # + # NOT `logsumexp_i(u_i) - log n`. That form is algebraically right and numerically WRONG at the + # bottom of the range, and it cost a preflight to find out. In a hopeless state every reward logit + # is about -100, so u_i = logsigmoid(-lg_i/T) is about -3.7e-44: distinct per candidate and + # perfectly representable, but `logsumexp` returns m + log(sum exp(u - m)) = m + log n, and adding + # -3.7e-44 to log 16 = 2.7726 loses it completely. Subtracting log n then gives EXACTLY -0.0 for + # all 128 candidates -- measured: 1 distinct value out of 128, i.e. a total collapse, and strictly + # WORSE than `prob` itself (24-95 distinct there). It is the same failure as `prob`'s, mirrored to + # the other end of the range. + # + # So the mean is taken as m + log1p(mean_i expm1(u_i - m)), m = max_i u_i: exactly the same + # quantity, but every step is conditioned for small arguments. expm1 is exact for tiny u_i - m + # (where `exp` would return 1.0 and drop the difference), log1p is exact for tiny means, and log n + # never appears, so nothing is added to an O(1) constant and cancelled back out. Behaviour at the + # saturated-high end is unchanged: there u_i - m spans O(10) and every term is O(1). + m = lq_out.max(dim=1, keepdim=True).values # <= 0 + rel = torch.expm1(lq_out - m).mean(dim=1) # in (-1, 0] + out.append(-(m[:, 0] + torch.log1p(rel.clamp(min=-1.0 + 1e-300)))) + if return_trace: + out.append(tr) + return tuple(out) + + +# --------------------------------------------------------------------------- # +# coin-terminated beta chain (gen_q#267; the reference read-out) +# --------------------------------------------------------------------------- # +# Reference: ogbench_genq/rsm.py (worktree agent-a0467d92d2631bf34) +# rsm.py:113 rec_p = (GAMMA - rec_beta) / (GAMMA * (1 - rec_beta)) +# rsm.py:76 REC_MAX_DEPTH = 10 # "P(depth > 10) ~ 1e-3 at beta = 0.98" +# rsm.py:532 chain_prob(): each level, ALIVE rows flip the coin at rec_p, sample ONE beta-horizon +# midpoint and re-decide the action there; dead rows freeze. After the scan, ONE goal +# read at each row's frozen node. Expectation form -- no max, no per-hop accumulation. +# +# WHY THIS COIN AND NOT gamma**h. A single beta-occupancy draw lands at a frame offset ~ Geom(1-beta) +# (PGF G(z) = (1-beta)/(1-beta z)). The walk composes M = N+1 of them with N ~ Geom(1-p) +# (PGF H(u) = u(1-p)/(1-p u)). Then +# H(G(z)) = (1-beta)(1-p) / (1 - p(1-beta) - beta z), +# a geometric with ratio beta / (1 - p(1-beta)). Demanding that ratio == gamma gives +# p = (gamma - beta) / (gamma (1 - beta)) [rsm.py:113] +# and the normaliser then collapses to exactly (1-gamma). So the composed frame offset is EXACTLY +# Geom(1-gamma): "sampling at beta" reproduces "sampling at gamma" in distribution, not approximately. +# gamma**h with h = 1/(1-beta) is a DIFFERENT number (0.6050 vs 0.5051 at beta=0.98, gamma=0.99) and does +# not satisfy the identity; it also fails the reference's own sanity comment, since 0.6050**10 = 7.0e-3 +# while 0.5051**10 = 1.08e-3 -- the "~1e-3" the reference documents. +# +# HOW IT DIFFERS FROM `_q_fold_logit` (the defect this fixes). The fold computes the ABSORBING hitting +# probability q_k = c_k + (1-c_k) gamma**h q_{k+1}, i.e. "did membership fire anywhere inside a +# gamma**h-geometric window". The chain computes the DISCOUNTED OCCUPANCY read +# Q_gamma = E[ c at a Geom(1-gamma) offset ]. These are different functionals: for constant c the fold +# returns c / (1 - gamma**h (1-c)) and the chain returns c -- a factor ~1/(1-gamma**h) apart (5.5x at +# beta=0.95). They are NOT expected to agree, and the chain is not verified against the fold; it is +# verified against its own exact Rao-Blackwellised form (`chain_rb` below), which is a true identity. + +def chain_continuation_p(beta, gamma): + """The reference's coin (rsm.py:113). Requires beta <= gamma; at beta == gamma the chain degenerates + to a single read (p = 0), which is correct -- one beta-draw already has the gamma horizon.""" + beta, gamma = float(beta), float(gamma) + if not (0.0 <= beta <= gamma < 1.0): + raise ValueError(f"coin chain needs 0 <= beta <= gamma < 1, got beta={beta}, gamma={gamma}") + return (gamma - beta) / (gamma * (1.0 - beta)) + + +def chain_cap(beta, gamma, tail_eps=CHAIN_TAIL_EPS): + """Smallest L with P(N > L) = p**L <= tail_eps. The cap is a TRUNCATION GUARD, not a tuning knob: + the reference's 10 is exactly this rule at beta=0.98 with tail ~1e-3. Never hard-code it.""" + p = chain_continuation_p(beta, gamma) + if p <= 0.0: + return 0 + return int(math.ceil(math.log(float(tail_eps)) / math.log(p))) + + +# alias: RSMScorer has an ATTRIBUTE named chain_cap (the override), so the function needs a +# non-colliding name at the call site inside the class. +chain_cap_fn = chain_cap + + +def _q_chain_logit(enc_z, a_chunk, task, *, rew, flow, rms, pol, beta, gamma, cap=None, + n_particles=16, flow_steps=8, temperature=1.0, max_rows=MAX_ROWS, + tail_eps=CHAIN_TAIL_EPS, rb=False, return_particles=False, seed=None, return_trace=False): + """Coin-terminated beta chain, the rsm.py read-out. Returns (q_mean [B], lg_mean [B], + [q_particles [B,n] if return_particles], stats dict). + + Per particle: walk N hops, each gated by an independent Bernoulli(p) coin; at a hop, sample ONE + beta-horizon successor with the trained flow and let the hop head re-decide the action there (the + reference's `occ_bits` + actor re-decide). When the coin fails -- or the cap binds -- the row freezes + and takes ONE more beta-occupancy draw as its goal read, exactly as rsm.py takes one `gl` at the frozen + node. The estimate is the mean over particles of the membership at that read. N+1 beta-draws compose + to a Geom(1-gamma) frame offset (see the module comment). + + Dead rows are PRUNED from the network call, so the expected cost is 1/(1-p) levels of work per row + rather than `cap` levels -- the chain is cheaper than a deterministic depth-L fold whenever + 1/(1-p) < L. CRN: the flow noise for level k and the hop-head noise for level k are drawn ONCE per + particle index and shared across candidates, exactly as `_q_fold_logit` does, so candidate comparisons + stay paired. The coins are likewise shared across candidates per (particle, level), so every candidate + is scored on the SAME set of walk lengths -- otherwise the coin noise alone would reorder candidates. + + rb=True replaces the coin with its exact conditional expectation (Rao-Blackwell): the full depth-(cap+1) + trajectory is run and read k is weighted by the coin's own law, w_k = (1-p) p**k for k < cap and + p**cap for k == cap. E[chain] == chain_rb exactly, so chain_rb is the analytic target the sampled + chain is verified against. It costs `cap+1` levels (no pruning), so it is a TEST path, not the + read-out.""" + _, train_rsm, _ = _rsm_modules() # same lazy import as _q_fold_logit (rsm_libero is not a package) + sample_future = train_rsm.sample_future + dev = enc_z.device + B, D = enc_z.shape + n = int(n_particles) + beta, gamma = float(beta), float(gamma) + p_cont = chain_continuation_p(beta, gamma) + # gen_q#270 VISUALISATION ONLY. The sampled chain prunes frozen rows, so there is no full-depth + # tensor to hand back -- which is why tracing was refused here. When return_trace is on we keep a + # per-level copy of every row's latent and read the reward classifier at EVERY level, purely for + # colour-coding. The value still uses ONE read at the frozen node; nothing below changes q_out. + tr_z, tr_c, tr_alive = ([], [], []) if return_trace else (None, None, None) + L = int(chain_cap(beta, gamma, tail_eps) if cap is None else cap) + if L >= 1 and pol is None: + raise RuntimeError(f"coin chain at cap {L} needs a hop head (rsm_hop_ckpt)") + T = float(temperature) if temperature else 1.0 + g = None + if seed is not None: # reproducible coins/noise without touching global RNG + g = torch.Generator(device=dev); g.manual_seed(int(seed)) + rnd = lambda *s: torch.randn(*s, device=dev, generator=g) + # CRN draws, per particle index, shared across candidates -- same contract as _q_fold_logit + x0s = [rnd(n, D) for _ in range(L + 1)] # flow noise per level + epss = [rnd(n, int(pol.d_act)) for _ in range(L)] if L >= 1 else [] # hop-head noise per level + coins = torch.rand(L, n, device=dev, generator=g) if L >= 1 else None # the coin, per (level, particle) + + max_rows = max(int(max_rows), 1) + cand_per = max(1, max_rows // n) + part_per = n if n <= max_rows else max_rows + q_out = torch.empty(B, n, device=dev, dtype=torch.float32) + lg_out = torch.empty(B, n, device=dev, dtype=torch.float32) + hops_out = torch.zeros(B, n, device=dev, dtype=torch.int32) + capped_out = torch.zeros(B, n, device=dev, dtype=torch.bool) + levels_run = 0 # measured network levels, for the cost claim + + for b0 in range(0, B, cand_per): + b1 = min(B, b0 + cand_per); nb = b1 - b0 + for p0 in range(0, n, part_per): + p1 = min(n, p0 + part_per); npp = p1 - p0 + R = nb * npp + z = enc_z[b0:b1].repeat_interleave(npp, 0) + a = a_chunk[b0:b1].repeat_interleave(npp, 0) + tk = task[b0:b1].repeat_interleave(npp, 0) + bq = torch.full((R,), beta, device=dev) + # particle index of each row, so the per-particle CRN draws line up after pruning + pid = torch.arange(p0, p1, device=dev).repeat(nb) + + if rb: + # ---- analytic path: full trajectory, coin replaced by its law ----------------- + w = torch.tensor([(1.0 - p_cont) * p_cont ** k for k in range(L)] + [p_cont ** L], + device=dev, dtype=torch.float64) + q = torch.zeros(R, device=dev, dtype=torch.float64) + lg = None + for k in range(L + 1): + z = sample_future(flow, z, a, tk, bq, rms, flow_steps, n=1, x0=x0s[k][pid]) + lg = rew(z, tk).float() + q = q + w[k] * torch.sigmoid(lg / T).double() + levels_run += R + if k < L: + a = pol.sample_eps(z, tk, epss[k][pid]) + q_out[b0:b1, p0:p1] = torch.nan_to_num(q.float(), nan=0.0).clamp(0.0, 1.0).view(nb, npp) + lg_out[b0:b1, p0:p1] = torch.nan_to_num(lg, nan=0.0).view(nb, npp) + hops_out[b0:b1, p0:p1] = L + continue + + # ---- sampled path: coin-terminated walk with row pruning ------------------------- + alive = torch.ones(R, dtype=torch.bool, device=dev) + hops = torch.zeros(R, dtype=torch.int32, device=dev) + for k in range(L): + cont = alive & (coins[k][pid] < p_cont) + idx = cont.nonzero(as_tuple=True)[0] + alive = cont + if idx.numel() == 0: + break + sub = pid[idx] + z_new = sample_future(flow, z[idx], a[idx], tk[idx], bq[idx], rms, flow_steps, + n=1, x0=x0s[k][sub]) + a_new = pol.sample_eps(z_new, tk[idx], epss[k][sub]) + z = z.index_copy(0, idx, z_new) + a = a.index_copy(0, idx, a_new) + hops = hops.index_add(0, idx, torch.ones_like(idx, dtype=torch.int32)) + levels_run += idx.numel() + if return_trace: + tr_z.append(z.detach().to(torch.float16).cpu()) + tr_c.append(torch.sigmoid(rew(z, tk).float() / T).detach().cpu()) + tr_alive.append(alive.detach().cpu()) + # ONE goal read at each row's frozen node (rsm.py:559-561), for EVERY row + z = sample_future(flow, z, a, tk, bq, rms, flow_steps, n=1, x0=x0s[L][pid]) + lg = rew(z, tk).float() + levels_run += R + if return_trace: + tr_z.append(z.detach().to(torch.float16).cpu()) + tr_c.append(torch.sigmoid(lg / T).detach().cpu()) + tr_alive.append(torch.zeros_like(alive).cpu()) # terminal level: nothing continues + # same NaN fallback and clamp as _q_fold_logit's q_out, so the two read-outs degrade + # identically on a pathological state instead of one of them emitting NaN into the ranking + q_out[b0:b1, p0:p1] = torch.nan_to_num(torch.sigmoid(lg / T), + nan=0.0).clamp(0.0, 1.0).view(nb, npp) + lg_out[b0:b1, p0:p1] = torch.nan_to_num(lg, nan=0.0).view(nb, npp) + hops_out[b0:b1, p0:p1] = hops.view(nb, npp) + capped_out[b0:b1, p0:p1] = alive.view(nb, npp) # still alive after L levels == capped + + hf = hops_out.float() + capped_frac = float(capped_out.float().mean()) + exp_hops = hf[~capped_out].mean() if (~capped_out).any() else torch.tensor(float("nan")) + if return_trace: + # [levels, R] / [levels, R, D] with R = B*n rows in (candidate, particle) order. hops_out gives + # each row's stop level, so a reader can slice each chain at its OWN length -- that ragged + # structure IS the figure: chains stagger, and rows sharing a particle index stop together + # because the coin is drawn per (level, particle) and shared across candidates. + import numpy as _np + _tr = { + "z": _np.stack([t.numpy() for t in tr_z]) if tr_z else None, + "c": _np.stack([t.numpy() for t in tr_c]) if tr_c else None, + "alive": _np.stack([t.numpy() for t in tr_alive]) if tr_alive else None, + "hops": hops_out.cpu().numpy(), # [B, n] stop level per (candidate, particle) + "capped": capped_out.cpu().numpy(), + "p_cont": float(p_cont), "cap": int(L), "beta": float(beta), "gamma": float(gamma), + "note": "value uses ONE read at the frozen node; c at earlier levels is colour only", + } + stats = { + "mode": "chain_rb" if rb else "chain", + "beta": beta, "gamma": gamma, "p_cont": p_cont, "cap": L, "tail_eps": float(tail_eps), + "tail_prob_at_cap": p_cont ** L, "n_particles": n, + # reference values the measurement must reproduce + "E_hops_expected": p_cont / (1.0 - p_cont) if p_cont < 1.0 else float("inf"), + "E_beta_reads_expected": 1.0 / (1.0 - p_cont) if p_cont < 1.0 else float("inf"), + "L_star_tab_discounts": (1.0 - beta) / (1.0 - gamma), + "frame_offset_mean_expected": gamma / (1.0 - gamma), + # measured + "hops_mean": float(hf.mean()), "hops_median": float(hf.median()), + "hops_p90": float(hf.flatten().quantile(0.90)), + "hops_mean_expired": float(exp_hops), + "capped_frac": capped_frac, + # the reference chain has NO absorbing event: membership is READ once at the frozen node and never + # terminates the walk (that is the OLD fold's behaviour). Recorded explicitly so the share is not + # mistaken for "not measured". + "absorbed_frac": 0.0, "expired_frac": 1.0 - capped_frac, + "absorbed_note": "reference chain has no absorbing event; termination is the coin or the cap", + "levels_run": int(levels_run), "levels_per_row": levels_run / max(B * n, 1), + # chain_rb runs the full cap-length trajectory BY CONSTRUCTION (it replaces the coin with its + # law, so there is nothing to terminate); its hops_mean is always the cap and the alarm would be a + # guaranteed false positive. The alarm is a property of the SAMPLED chain only. + # PER-CALL alarm, and it must NOT use the aggregate 1e-2 rule directly: one decision scores + # `n` particles, so its capped fraction is QUANTISED to multiples of 1/n and the smallest + # nonzero value at n=16 is 0.0625 > 1e-2. With P(cap) = p^L <= 1e-3 per particle, ~1.4 % of + # decisions legitimately cap one particle, so the aggregate rule applied per call fires on a + # perfectly healthy cell (~28 times in the first mug cell -- exactly the 1.4 % predicted). + # Per call the real signal is TWO or more particles capping, or a mean walk length near the + # cap; the cell-level verdict is computed from the pooled fractions in chain_hop_summary(). + "cap_binding": (False if rb else + bool(capped_frac * n >= 2.0 or float(hf.mean()) > 0.9 * max(L, 1))), + } + if stats["cap_binding"]: + sys.stderr.write( + f"[CAP ALARM] chain cap is BINDING: beta={beta} gamma={gamma} cap={L} " + f"capped_frac={capped_frac:.4f} hops_mean={stats['hops_mean']:.3f} " + f"(alarm if capped_frac > 1e-2 or hops_mean > 0.9*cap) -- this cell is TRUNCATED and must not " + f"be quoted as a chain number without the flag\n") + sys.stderr.flush() + out = [q_out.mean(1), lg_out.mean(1)] + if return_particles: + out.append(q_out) + out.append(stats) + if return_trace: + out.append(_tr) # gen_q#270, LAST element; absent unless the caller asked for it + return tuple(out) + +# --------------------------------------------------------------------------- # +# backends +# --------------------------------------------------------------------------- # +class MLPBackend: + """rsm_libero MLP successor (train_rsm.py). Uses is_ope.load_critic (identity or MLP encoder).""" + + def __init__(self, ckpt, device, d_in=STATE_DIM, hop_ckpt="", feat_sd=None, max_rows=MAX_ROWS): + model, train_rsm, is_ope = _rsm_modules() + self.is_ope = is_ope + self.device = device + self.max_rows = int(max_rows) + self.temperature = read_calib_temperature(ckpt) or 1.0 # calib.json next to the blob, else 1 + self.enc, self.rew, self.flow, self.rms, self.cfg = is_ope.load_critic( + ckpt, d_in, 1, device, data=None) + ck = torch.load(ckpt, map_location="cpu", weights_only=False) + self.n_task = max(1, len(ck.get("tasks", ["task"]))) + self.d_act = int(ck["d_act"]) + self.q_action_winrate = ck.get("q_action_winrate", None) + self.step = ck.get("step", None) + self.chunk = int(self.cfg.get("chunk", 8)) + self.adim = self.d_act // self.chunk + self.d_z = int(self.cfg["d_z"]) + self.hop, self.hop_chunk = None, None + if hop_ckpt: + self.hop, self.hop_chunk = load_hop_head(hop_ckpt, self.d_z, self.n_task, device, feat_sd=feat_sd) + if self.hop.d_act != self.d_act: + raise RuntimeError(f"hop head emits {self.hop.d_act}-d chunks, RSM expects {self.d_act}") + + def latent(self, x): + return self.enc(x) + + def q(self, z, a, *, mode, depth, beta, gamma, n_particles, flow_steps, return_logit=False, + temperature=None, return_lcb=None, return_problog=False, return_trace=False): + """Q̄ [B] (return_logit=False, the historic contract) or (Q̄, Q̄_logit) [B] each; with return_lcb=

+ a third array, the p-quantile over particles of the per-particle Q (the conformal read-out), and with + return_problog=True a further array, the `prob_log` ranking (Q̄ itself, computed in the log-complement + domain so it does not tie when σ saturates). The returned tuple is + (Q̄, Q̄_logit [, LCB if return_lcb] [, prob_log if return_problog]). d1 / fold go through + `_q_fold_logit` (== is_ope.q_fold(crn=True) at T=1, plus the raw logit, row-sliced); recursive keeps + is_ope.q_recursive and has neither a logit nor a prob_log (it has no per-hop c_k). + temperature=None -> the checkpoint's calib.json T (or 1).""" + task = torch.zeros(z.shape[0], dtype=torch.long, device=z.device) + if mode == "d1": + depth = 1 + if depth >= 2 and self.hop is None: + raise RuntimeError(f"read-out {mode} at depth {depth} needs a hop head (rsm_hop_ckpt)") + T = self.temperature if temperature is None else float(temperature) + if mode in ("chain", "chain_rb"): + # coin-terminated beta chain (gen_q#267). ADDITIVE: no existing mode reaches this branch, so + # d1/fold/recursive stay bit-identical. `depth` is IGNORED here on purpose -- the chain's only + # length parameter is the truncation cap, computed from (beta, gamma) by chain_cap(); a caller + # may override it with chain_cap_override for the cap sweep, never to tune success. + out = list(_q_chain_logit(z, a, task, rew=self.rew, flow=self.flow, rms=self.rms, pol=self.hop, + beta=beta, gamma=gamma, + cap=getattr(self, "chain_cap_override", None), + n_particles=n_particles, flow_steps=flow_steps, temperature=T, + max_rows=self.max_rows, + tail_eps=getattr(self, "chain_tail_eps", CHAIN_TAIL_EPS), + rb=(mode == "chain_rb"), return_trace=return_trace, + return_particles=return_lcb is not None, + seed=getattr(self, "chain_seed", None))) + q, ql = out.pop(0), out.pop(0) + res = [q, ql] + if return_lcb is not None: + res.append(_particle_quantile(out.pop(0), return_lcb)) + # hop accounting rides on the instance, so the tuple contract above is untouched + self.last_chain_stats = out.pop(0) + if return_problog: + raise RuntimeError("plan_score=prob_log is a fold-only ranking (it folds per-hop c_k in the " + "log-complement domain); the chain reads membership ONCE at the frozen " + "node, so use plan_score=prob") + # gen_q#270: the chain now traces. _q_chain_logit appends the trace dict after the stats, + # so it is the last element; the caller gets ragged chains plus each row's stop level and + # slices at the true length. The returned q/ql are untouched. + if return_trace: + res.append(out.pop(0) if out else None) + if len(res) > 2: + return tuple(res) + return (q, ql) if return_logit else q + if mode in ("d1", "fold"): + out = list(_q_fold_logit(z, a, task, rew=self.rew, flow=self.flow, rms=self.rms, pol=self.hop, + beta=beta, gamma=gamma, depth=depth, n_particles=n_particles, + flow_steps=flow_steps, temperature=T, max_rows=self.max_rows, + return_particles=return_lcb is not None, + return_problog=bool(return_problog), + return_trace=bool(return_trace), + openloop=bool(getattr(self, "fold_openloop", False)), + sample_clip=float(getattr(self, "fold_sample_clip", 0.0)))) + q, ql = out.pop(0), out.pop(0) + res = [q, ql] + if return_lcb is not None: + res.append(_particle_quantile(out.pop(0), return_lcb)) + if return_problog: + res.append(out.pop(0)) + if return_trace: # always LAST, so no existing position moves (gen_q#270) + res.append(out.pop(0)) + if len(res) > 2: + return tuple(res) + return (q, ql) if return_logit else q + if mode == "recursive": + q, _ess = self.is_ope.q_recursive(z, a, task, rew=self.rew, flow=self.flow, rms=self.rms, + pol=self.hop, wend=None, beta=beta, gamma=gamma, depth=depth, + n_particles=n_particles, flow_steps=flow_steps, + use_is=False, crn=True) + q = q * (1.0 - gamma) # back to the success-probability scale + if return_lcb is not None: + raise RuntimeError("plan_score=conformal_lcb needs the d1 / fold read-out (recursive has no " + "per-particle success probability)") + if return_problog: + raise RuntimeError("plan_score=prob_log needs the d1 / fold read-out (recursive has no " + "per-hop reward logits to fold in the log-complement domain)") + if return_trace: + raise RuntimeError("return_trace needs the d1 / fold read-out (recursive's stochastic stop " + "keeps no per-hop c_k to trace)") + return (q, None) if return_logit else q + raise ValueError(mode) + + def q_fold_reference(self, z, a, *, depth, beta, gamma, n_particles, flow_steps): + """is_ope.q_fold itself (crn=True), for tests against `_q_fold_logit`.""" + task = torch.zeros(z.shape[0], dtype=torch.long, device=z.device) + q, _ = self.is_ope.q_fold(z, a, task, rew=self.rew, flow=self.flow, rms=self.rms, pol=self.hop, + beta=beta, gamma=gamma, depth=depth, n_particles=n_particles, + flow_steps=flow_steps, crn=True) + return q + + def hop_sample(self, z, eps): + task = torch.zeros(z.shape[0], dtype=torch.long, device=z.device) + return self.hop.sample_eps(z, task, eps) + + +class DWMBackend: + """Token successor model, stream C's shipped interface (rsm_libero/dwm_readout.py, status/C_dwm.md): + crit = load_critic_dwm(path, device); crit.q(x_tokens RAW [B,514,384], a_chunk [B,56], beta, + n_particles, crn_seed, depth, mode in {d1, fold}, proprio RAW [B,9], + hop_policy(pooled_raw [R,1545], eps [R,d_act]) -> [R,56], gamma, flow_steps) -> Q̄ [B] + The critic normalises tokens/proprio itself (cache//tokens/tok_stats.npz). The hop head runs on the + z-scored pooled state, so the callable applies our feat_stats rule (`normalize`) to pooled_raw first. + `q()` takes inp = (tokens_raw, proprio_raw). mode "recursive" is not offered by the DWM read-out.""" + + def __init__(self, ckpt, device, module="dwm_readout", hop_ckpt="", feat_sd=None, d_in=STATE_DIM, + normalize=None): + _rsm_modules() + try: + mod = importlib.import_module(module) + except ImportError as e: + raise RuntimeError(f"DWM backend needs module '{module}' with load_critic_dwm (stream C): {e}") + self.core = mod.load_critic_dwm(ckpt, device=device) + self.d_act = int(self.core.d_act) + self.chunk = int(self.core.config.get("chunk", 8)) + self.adim = self.d_act // self.chunk + self.d_z = d_in + self.normalize = normalize if normalize is not None else (lambda x: x) + self.q_action_winrate = getattr(self.core, "q_action_winrate", None) + self.step = getattr(self.core, "step", None) + self.hop = None + if hop_ckpt: + self.hop, _ = load_hop_head(hop_ckpt, d_in, 1, device, feat_sd=feat_sd) + + def _hop_callable(self): + if self.hop is None: + return None + hop, norm = self.hop, self.normalize + + class _Hop: + d_act = hop.d_act + + def __call__(self, pooled_raw, eps): + x = norm(pooled_raw.float()) + task = torch.zeros(x.shape[0], dtype=torch.long, device=x.device) + return hop.sample_eps(x, task, eps) + return _Hop() + + @property + def temperature(self): + return float(getattr(self.core, "temperature", 1.0)) + + def q(self, inp, a, *, mode, depth, beta, gamma, n_particles, flow_steps, crn_seed=None, + return_logit=False, temperature=None, rescore_top=0, n_particles_rescore=0, return_lcb=None): + """Q̄ [B] or (Q̄, Q̄_logit) with return_logit=True; temperature=None -> the critic's own (calib.json); + rescore_top=K / n_particles_rescore=M -> dwm_readout's two-stage screening (top-K by q_logit). + + return_lcb=

additionally returns the p-quantile over particles of the per-particle Q. dwm_readout + returns only the MEAN, so the per-particle values are rebuilt from its `return_hops=True` output (the + per-hop c_k [B, n], folded exactly as _q_once does). Those hops belong to the STAGE-1 pass, so the + conformal read-out is incompatible with the internal two-stage screening and raises instead of + silently ranking rescored candidates by their stage-1 spread.""" + tok, pr = inp + if mode == "recursive": + raise RuntimeError("the DWM read-out offers d1 / fold only (rsm_libero/dwm_readout.py)") + if mode == "d1": + depth = 1 + if crn_seed is None: # fresh CRN draw per call, shared by all rows + crn_seed = int(torch.randint(0, 2 ** 31 - 1, (1,), device="cpu")) + kw = {} + if temperature is not None: + kw["temperature"] = float(temperature) + if rescore_top and n_particles_rescore: + kw["rescore_top"] = int(rescore_top) + kw["n_particles_rescore"] = int(n_particles_rescore) + if return_lcb is None: + return self.core.q(tok, a, float(beta), n_particles=int(n_particles), crn_seed=int(crn_seed), + depth=int(depth), mode=mode, proprio=pr, hop_policy=self._hop_callable(), + gamma=float(gamma), flow_steps=int(flow_steps), + return_logit=bool(return_logit), **kw) + if "rescore_top" in kw: + raise RuntimeError("plan_score=conformal_lcb cannot be combined with the DWM two-stage screening " + "(plan_rescore_top / plan_particles_rescore): dwm_readout only exposes the " + "stage-1 per-particle values") + (q, ql), cs = self.core.q(tok, a, float(beta), n_particles=int(n_particles), crn_seed=int(crn_seed), + depth=int(depth), mode=mode, proprio=pr, hop_policy=self._hop_callable(), + gamma=float(gamma), flow_steps=int(flow_steps), return_logit=True, + return_hops=True, **kw) + if mode in ("mpc", "mpc_disc"): + raise RuntimeError("plan_score=conformal_lcb is not defined for the MPC read-outs: the\n" + "per-particle rebuild below is the FOLD recursion, and using it under\n" + "mpc would rank candidates by a quantity the cell did not run.") + qp = torch.zeros_like(cs[-1]) # per-particle fold, same recursion as dwm_readout + if mode == "d1" or len(cs) == 1: + qp = cs[0] + else: + h = 1.0 / (1.0 - float(beta)) + for c in reversed(cs): + qp = c + (1.0 - c) * (float(gamma) ** h) * qp + qp = torch.nan_to_num(qp, nan=0.0).clamp(0.0, 1.0) + return q, ql, _particle_quantile(qp, return_lcb) + + def hop_sample(self, x, eps): + task = torch.zeros(x.shape[0], dtype=torch.long, device=x.device) + return self.hop.sample_eps(x, task, eps) + + +class LeWMBackend: + """LeWM (gen_q#268): rsm_libero/lewm_readout.py, a JEPA world model with a membership probe. + + crit = load_critic_lewm(path, device) + crit.q(inp = (frames [B,6,84,84] uint8-or-float, proprio (ignored)), a_chunk [B,56], + depth=L, mode in {d1, fold}, gamma) -> Q [B] + + Its state is PIXELS -- the two RISE cameras stacked as 6 channels -- because LeWM predicts its + OWN encoder's embeddings; feeding it frozen DINO features would make it DINO-WM. The scorer + therefore hands it the planner's frames and still computes the pooled DINO state alongside, so + the hop head and every other consumer are unaffected and DINO still runs once per frame. + Deterministic, so there is no particle dimension: it is the cheapest scorer in the table. + """ + + def __init__(self, ckpt, device, module="lewm_readout", hop_ckpt="", feat_sd=None, + d_in=STATE_DIM, normalize=None): + _rsm_modules() + try: + mod = importlib.import_module(module) + except ImportError as e: + raise RuntimeError(f"LeWM backend needs module '{module}' with load_critic_lewm: {e}") + self.core = mod.load_critic_lewm(ckpt, device=device) + self.d_act = int(self.core.d_act) + self.chunk = int(self.core.chunk) + self.adim = self.d_act // self.chunk + self.d_z = d_in + self.res, self.in_ch = int(self.core.res), int(self.core.in_ch) + self.cams = tuple(self.core.cams) + self.normalize = normalize if normalize is not None else (lambda x: x) + self.q_action_winrate = getattr(self.core, "q_action_winrate", None) + self.step = getattr(self.core, "step", None) + # HOP HEAD (gen_q#288). It used to be pinned to None on the claim that LeWM "rolls the SAME + # candidate chunk", which made every LeWM MPC cell a single deterministic roll-out even though + # all 630 of them requested 16 particles. Owner, 2026-09-25: "should definitely be M different + # chains for DINOWM and LeWM with stochastic continuations just like RSM." So LeWM now chains + # with the SAME hop head DWM/DINO-WM do -- see lewm_readout's deviation 2 for the one thing that + # differs (the head is conditioned on the CURRENT observation's pooled DINO state, because a + # rolled LeWM embedding has no pooled DINO vector). Without --hop the old zero-order hold at + # one particle still runs, byte-identical, so the published M=1 arms stay reproducible. + self.hop = None + if hop_ckpt: + self.hop, _ = load_hop_head(hop_ckpt, d_in, 1, device, feat_sd=feat_sd) + + def _hop_callable(self): + """Same object DWMBackend._hop_callable builds -- identical weights, identical z-scoring rule -- + so "the same continuation actor as RSM" is literally the same code path, not a re-implementation.""" + if self.hop is None: + return None + hop, norm = self.hop, self.normalize + + class _Hop: + d_act = hop.d_act + + def __call__(self, pooled_raw, eps): + x = norm(pooled_raw.float()) + task = torch.zeros(x.shape[0], dtype=torch.long, device=x.device) + return hop.sample_eps(x, task, eps) + return _Hop() + + @property + def temperature(self): + return float(getattr(self.core, "temperature", 1.0)) + + def q(self, inp, a, *, mode, depth, beta, gamma, n_particles, flow_steps, crn_seed=None, + return_logit=False, temperature=None, rescore_top=0, n_particles_rescore=0, + return_lcb=None): + return self.core.q(inp, a, beta=beta, n_particles=int(n_particles), crn_seed=crn_seed, + depth=depth, mode=mode, gamma=gamma, flow_steps=flow_steps, + hop_policy=self._hop_callable(), + return_logit=return_logit, temperature=temperature, + return_lcb=return_lcb) + + def hop_sample(self, x, eps): + if self.hop is None: + return self.core.hop_sample(x, eps) + task = torch.zeros(x.shape[0], dtype=torch.long, device=x.device) + return self.hop.sample_eps(x, task, eps) + + +class DFBackend: + """Diffusion Forcing as a VALUE estimator (gen_q#274 / #282): rsm_libero/df_readout.py. + + crit = load_critic_df(path, device) + crit.q(inp = pooled state [B, 1545], a_chunk [B, 56], depth=K, mode in {mpc, mpc_disc}, + gamma, n_particles=M) -> Q [B] + + Its state is the SAME pooled 1545-d DINO state every mlp/RSM scorer reads, so `state_from_obs` + needs no branch for it: `df_data.obs_rows` applies literally the same z-score-and-clip that + PooledDinoState.forward does. Stochastic, so the particle axis is real (M = n_particles, the + analogue of RSM's P) and is NOT forced to 1 the way DINO-WM's is. + """ + + def __init__(self, ckpt, device, module="df_readout", hop_ckpt="", feat_sd=None, + d_in=STATE_DIM): + _rsm_modules() + try: + mod = importlib.import_module(module) + except ImportError as e: + raise RuntimeError(f"DF backend needs module '{module}' with load_critic_df: {e}") + self.core = mod.load_critic_df(ckpt, device=device) + self.d_act = int(self.core.d_act) + self.chunk = int(self.core.chunk) + self.adim = self.d_act // self.chunk + self.d_z = d_in + # No hop head: the continuation past the candidate chunk is the model's own sampled action + # channel, so a policy over DINO states would never be called. None rather than loaded, so + # an advantage() call fails loudly instead of silently scoring something else. + self.hop = None + + @property + def temperature(self): + return float(getattr(self.core, "temperature", 1.0)) + + def q(self, inp, a, *, mode, depth, beta, gamma, n_particles, flow_steps, crn_seed=None, + return_logit=False, temperature=None, rescore_top=0, n_particles_rescore=0, + return_lcb=None): + return self.core.q(inp, a, beta=beta, n_particles=n_particles, crn_seed=crn_seed, + depth=depth, mode=mode, gamma=gamma, flow_steps=flow_steps, + return_logit=return_logit, temperature=temperature, + return_lcb=return_lcb) + + def hop_sample(self, x, eps): + return self.core.hop_sample(x, eps) + + +class MCBackend: + """MC return-to-go critic on the pooled state (S3H5). blob: {"net": state_dict, + "config": {"d_in": 1545, "d_act": 56, "width": 1024, "depth": 3, "scale": 1.0}}, net = MLP([x|A]) -> R.""" + + def __init__(self, ckpt, device, hop_ckpt="", feat_sd=None): + ck = torch.load(ckpt, map_location=device, weights_only=False) + c = ck["config"] + self.d_act, self.chunk = int(c["d_act"]), int(c.get("chunk", 8)) + self.adim = self.d_act // self.chunk + self.d_z = int(c["d_in"]) + w, dp = int(c.get("width", 1024)), int(c.get("depth", 3)) + layers, ind = [], self.d_z + self.d_act + for i in range(dp): + layers += [nn.Linear(ind if i == 0 else w, w), nn.SiLU()] + layers += [nn.Linear(w, 1)] + self.net = nn.Sequential(*layers).to(device) + self.net.load_state_dict(ck["net"]) + self.net.eval() + self.scale = float(c.get("scale", 1.0)) + self.hop = None + if hop_ckpt: + self.hop, _ = load_hop_head(hop_ckpt, self.d_z, 1, device, feat_sd=feat_sd) + + def q(self, x, a, return_logit=False, **_): + with torch.no_grad(): + q = self.net(torch.cat([x, a], -1))[:, 0] * self.scale + return (q, None) if return_logit else q # a return-to-go has no logit + + def hop_sample(self, x, eps): + task = torch.zeros(x.shape[0], dtype=torch.long, device=x.device) + return self.hop.sample_eps(x, task, eps) + + +# --------------------------------------------------------------------------- # +# the scorer +# --------------------------------------------------------------------------- # +class RSMScorer: + """score(state, A[N,chunk,adim]) -> Q̄[N]; advantage(state, A[B,...]) -> (Q̄[B], V̄[B], Qm[B,M]).""" + + def __init__(self, backend="mlp", ckpt="", hop_ckpt="", feat_stats="", mode="fold", depth=2, + beta=0.95, gamma=0.99, n_particles=16, flow_steps=8, device="cpu", state=None, + img_layout="chw", cams=CAMS, proprio_keys=PROPRIO_KEYS, dwm_module="dwm_readout", + dino=None, score_kind="prob", rescore_top=0, n_particles_rescore=0, temperature=0.0, + max_rows=MAX_ROWS, lcb_quantile=0.1, chain_cap=0, chain_tail_eps=CHAIN_TAIL_EPS, + chain_seed=None, mpc_horizon=0, fold_openloop=False, fold_sample_clip=0.0): + """score_kind: "prob" (mean σ, the historic ranking) | "logit" (mean raw logit, d1/fold only) | + "prob_log" (gen_q#266: the SAME quantity as "prob" -- the whole product fold, mean over particles -- + but folded in the log-complement domain, so it is a strictly monotone transform of prob's + infinite-precision value and gives a total order over the candidates where prob ties ~half of them + at exactly 1.0; mlp backend, d1/fold only, since it needs the per-hop reward logits) | + "conformal_lcb" (the `lcb_quantile` quantile — 0.1 by default — over particles of the per-particle + success probability instead of its mean: a pessimistic read-out that prefers candidates whose future + is reliably good over candidates with one lucky particle). + rescore_top=K, n_particles_rescore=M (both > 0 to enable): two-stage particle screening in score(). + temperature: 0 -> the checkpoint's calib.json T if present else 1.0; > 0 overrides.""" + assert mode in _MODES, mode + assert score_kind in _SCORE_KINDS, score_kind + self.backend_name = backend + self.mode, self.depth = mode, int(depth) + self.beta, self.gamma = float(beta), float(gamma) + self.n_particles, self.flow_steps = int(n_particles), int(flow_steps) + self.score_kind = score_kind + self.rescore_top = int(rescore_top or 0) + self.n_particles_rescore = int(n_particles_rescore or 0) + self.temperature = float(temperature or 0.0) + self.lcb_quantile = float(lcb_quantile) + self.last_q = self.last_q_logit = self.last_q_lcb = self.last_q_problog = None + # coin chain (gen_q#267). chain_cap=0 means "compute it from (beta, gamma) and the 1e-3 tail", + # which is the ONLY legitimate way to set it; a non-zero override exists solely so the cap can be + # SWEPT as a truncation guard (and so the reference's own 10 can be reproduced), never to tune + # success. Recorded in describe() either way so every cell says which cap it ran. + self.chain_cap = int(chain_cap or 0) + self.chain_tail_eps = float(chain_tail_eps) + self.chain_seed = chain_seed + # gen_q#271: repeat the candidate action at every fold hop instead of re-sampling the hop + # head. Default False == the historic closed-loop fold, so every archived cell is + # bit-identical. mlp / (d1, fold) only -- at depth 1 it is a no-op by construction. + self.fold_openloop = bool(fold_openloop) + # gen_q#271: clamp the sampled latent between hops, as the label's rollout does. + # 0.0 == off == the historic fold; the trainer's own value for this corpus is 10.0. + self.fold_sample_clip = float(fold_sample_clip or 0.0) + self.chain_hop_acc = None + # gen_q#273 -- MPC. The horizon is given in FRAMES and comes from the discount: + # H = 1/(1-gamma). The number of open-loop chunks is ceil(H / hop_frames) and is computed + # AFTER the backend is built, from the model's own chunk length, so the launcher never has to + # hard-code 8. mpc_horizon=0 leaves `depth` exactly as the caller passed it. + self.mpc_horizon = int(mpc_horizon or 0) + # gen_q#282 (stream DF_VALUE): `df` is the third world-model column -- same H, same + # candidates, same provenance reward as dinowm/lewm, and the horizon is generated JOINTLY + # instead of autoregressively. It is MPC-only by construction: df_readout refuses d1/fold + # because DF has no per-hop hazard to fold. + if mode in _MPC_MODES and backend not in TOKEN_BACKENDS + ("lewm", "df"): + raise ValueError(f"plan_mode={mode} is a WORLD-MODEL read-out: it rolls a latent dynamics\n" + f"model open-loop and scores the result. Backends: dwm, dinowm, lewm, df " + f"(got backend={backend}).") + if mode in ("chain", "chain_rb"): + if backend != "mlp": + raise ValueError(f"the coin chain is implemented on the mlp backend (got backend={backend}); " + f"the token read-outs have no per-row freeze") + # fail loudly at construction, not 400 decisions in + _p = chain_continuation_p(self.beta, self.gamma) + _cap = self.chain_cap or chain_cap_fn(self.beta, self.gamma, self.chain_tail_eps) + # P(N > cap) = p**cap, except that Python's 0**0 is 1: at beta == gamma the coin never + # continues, so a cap of 0 truncates nothing and the tail is 0, not 1. + _tail = 0.0 if _p == 0.0 else _p ** _cap + sys.stderr.write( + f"[rsm_scorer] COIN CHAIN: beta={self.beta} gamma={self.gamma} p={_p:.6f} cap={_cap} " + f"tail=P(N>cap)={_tail:.2e} E[hops]={_p / (1 - _p):.3f} " + f"E[beta-reads]={1 / (1 - _p):.3f} (L*=(1-beta)/(1-gamma)={(1 - self.beta) / (1 - self.gamma):.1f})\n") + sys.stderr.flush() + if score_kind in ("logit", "conformal_lcb", "prob_log") and (mode == "recursive" or backend == "mc"): + raise ValueError(f"plan_score={score_kind} needs the d1 / fold read-out of the mlp / dwm / dinowm backend " + f"(got backend={backend}, mode={mode})") + # prob_log folds log(1 - c_k) = logσ(-lg_k/T) hop by hop, so it needs the per-hop reward LOGITS. + # The token read-outs (dwm / dinowm) expose only the per-hop c_k (return_hops), already through the + # sigmoid -- a saturated c_k = 1.0 there gives log(0) = -inf and the read-out would silently lose + # exactly the resolution it exists to recover. So it is restricted to the mlp backend, which owns + # `_q_fold_logit` and has the raw logits in hand. LeWM has no per-hop logit interface either. + if score_kind == "prob_log" and backend != "mlp": + raise ValueError(f"plan_score=prob_log needs the per-hop reward logits of the mlp backend's fold " + f"(got backend={backend}); the token read-outs expose only the post-sigmoid c_k") + if self.fold_sample_clip > 0: + if backend != "mlp" or mode not in ("d1", "fold"): + raise ValueError(f"fold_sample_clip is an mlp d1/fold option (got backend={backend}, " + f"mode={mode})") + sys.stderr.write(f"[rsm_scorer] FOLD SAMPLE CLIP: z clamped to +-{self.fold_sample_clip} " + f"after every hop (mode={mode} depth={depth})\n") + sys.stderr.flush() + if self.fold_openloop: + if backend != "mlp" or mode not in ("d1", "fold"): + raise ValueError(f"fold_openloop is an mlp d1/fold option (got backend={backend}, " + f"mode={mode})") + sys.stderr.write(f"[rsm_scorer] FOLD OPEN LOOP: the candidate action chunk is REPEATED at " + f"every hop (mode={mode} depth={depth}); the hop head is not sampled\n") + sys.stderr.flush() + if score_kind == "conformal_lcb" and not 0.0 < self.lcb_quantile < 1.0: + raise ValueError(f"plan_lcb_quantile must be in (0, 1), got {self.lcb_quantile}") + self.device = torch.device(device) + self.state = state + if self.state is None and feat_stats: + self.state = PooledDinoState(feat_stats, cams=cams, proprio_keys=proprio_keys, + img_layout=img_layout, dino=dino).to(self.device) + feat_sd = None if self.state is None else self.state.sd.cpu().numpy() + d_in = STATE_DIM if self.state is None else self.state.d + if backend == "mlp": + self.backend = MLPBackend(ckpt, self.device, d_in=d_in, hop_ckpt=hop_ckpt, feat_sd=feat_sd, + max_rows=max_rows) + elif backend in TOKEN_BACKENDS: + # `dwm_module` defaults to "dwm_readout", so only override it when the caller left it at + # that default: an explicit --rsm_dwm_module still wins. + _mod = dwm_module if dwm_module not in (None, "", "dwm_readout") \ + else READOUT_MODULE[backend] + self.backend = DWMBackend(ckpt, self.device, module=_mod, hop_ckpt=hop_ckpt, + feat_sd=feat_sd, d_in=d_in, + normalize=None if self.state is None else self.state.normalize) + elif backend == "lewm": + self.backend = LeWMBackend(ckpt, self.device, hop_ckpt=hop_ckpt, feat_sd=feat_sd, + d_in=d_in, + normalize=None if self.state is None else self.state.normalize) + elif backend == "df": + self.backend = DFBackend(ckpt, self.device, hop_ckpt=hop_ckpt, feat_sd=feat_sd, + d_in=d_in) + elif backend == "mc": + self.backend = MCBackend(ckpt, self.device, hop_ckpt=hop_ckpt, feat_sd=feat_sd) + else: + raise ValueError(f"unknown backend {backend}") + self.chunk, self.adim, self.d_act = self.backend.chunk, self.backend.adim, self.backend.d_act + # gen_q#273: H frames -> K = ceil(H / hop_frames) chunks of open-loop roll-out. hop_frames is + # the model's OWN step, read off the loaded critic, so the cell name (H in frames) and the run + # can never disagree. + # + # ASK THE BACKEND, NEVER ASSUME. Two different critics live behind `backend == "dwm"`, and + # they do NOT share a hop (measured receipt: status/q273/hop_receipt.json, LSF 1874174): + # DWMCritic (dwm_readout.py, the RSM/DWM occupancy flow, `--model DWM=...:dwm`) + # : _step IS a draw from the beta-discounted successor, so its hop is + # _hop_frames(beta) = 1/(1-beta) frames and beta sets the roll granularity. + # DINOWMCritic (dinowm_readout.py, `--model DINOWM=...:dinowm`, which is what every DINO-WM + # cell in this table uses) : SUBCLASSES DWMCritic but OVERRIDES BOTH. _step is a + # deterministic one-chunk latent step with beta forced to zero + # (dinowm_readout.py:65-86, `bz = torch.zeros(...)`), and _hop_frames returns the + # constant self.hop_frames (:89-90) = ck["hop_frames"] or config chunk = 8. + # beta is therefore INERT on DINO-WM: _hop_frames is 8.0 at every beta in + # {0.90, 0.95, 0.98, 0.99, 0.995}, measured. + # LeWMCritic (lewm_readout.py) : step_emb advances the context by ONE action chunk, so + # hop_frames = chunk = 8 is genuinely true and beta is inert there too. + # A 2026-09-23 note in this file claimed DINO-WM's hop was 1/(1-beta); that read DWMCritic's + # base methods and missed the subclass overrides. It is retracted -- see status/DWM_MPC_DONE. + # The lookup order below is kept because it is the honest one (a backend that DOES vary its hop + # with beta gets asked), and the banner prints the source so a fallback can never be silent. + _core = getattr(self.backend, "core", None) + _hf = getattr(_core, "_hop_frames", None) + if callable(_hf): + self.mpc_hop_frames = float(_hf(self.beta)) + else: + self.mpc_hop_frames = float(getattr(_core, "hop_frames", self.chunk)) + if self.mode in _MPC_MODES: + if self.mpc_horizon <= 0: + raise ValueError(f"plan_mode={self.mode} needs plan_mpc_horizon > 0 (H in FRAMES, " + f"H = 1/(1-gamma)); got {self.mpc_horizon}") + self.depth = int(math.ceil(self.mpc_horizon / self.mpc_hop_frames)) + _gh = 1.0 / (1.0 - self.gamma) + # The continuation past the first chunk is NOT the same object on the two world models, and + # the banner has to say which one ran: DINO-WM re-queries the hop head on the rolled latent, + # LeWM cannot (no hop head -- its latent is its own encoder's) and repeats the candidate. + # gen_q#288: LeWM DOES chain with the hop head now, on the current observation's pooled + # DINO state (its own latent has none). With no --hop it still repeats the candidate. + _cont = (("hop head on the CURRENT observation's pooled state, " + f"M={self.effective_particles()} roll-outs" + if self.backend.hop is not None else + "zero-order hold of the candidate chunk (no hop head loaded)") + if self.backend_name == "lewm" else + "the model's OWN sampled action channel past the chunk (DF, D2: free tail)" + if self.backend_name == "df" else "hop head on the rolled latent") + _src = "backend._hop_frames(beta)" if callable( + getattr(getattr(self.backend, "core", None), "_hop_frames", None)) else ( + "backend.hop_frames" if hasattr(getattr(self.backend, "core", None), "hop_frames") + else "action chunk (fallback)") + sys.stderr.write( + f"[rsm_scorer] MPC: mode={self.mode} H={self.mpc_horizon} frames " + f"(gamma={self.gamma} -> 1/(1-gamma)={_gh:.1f}) hop_frames={self.mpc_hop_frames:.1f} " + f"[from {_src}, beta={self.beta}] " + f"-> K={self.depth} open-loop hops = {self.depth * self.mpc_hop_frames:.0f} frames " + f"rolled; continuation past chunk 1 = {_cont}\n") + sys.stderr.flush() + # the coin chain's knobs live on the BACKEND (that is where _q_chain_logit reads them). Set + # unconditionally so a backend can never carry a stale value from a previous scorer. + self.backend.chain_cap_override = self.chain_cap or None + self.backend.chain_tail_eps = self.chain_tail_eps + self.backend.chain_seed = self.chain_seed + self.backend.fold_openloop = self.fold_openloop + self.backend.fold_sample_clip = self.fold_sample_clip + self.backend.last_chain_stats = None + + # ---- state ------------------------------------------------------------ + @torch.no_grad() + def state_from_obs(self, obs_t): + """obs dict at the current frame -> SimpleNamespace(x [B,1545], tok [B,514,384] or None).""" + if self.state is None: + raise RuntimeError("scorer built without feat_stats; pass states directly") + if self.backend_name in TOKEN_BACKENDS: + tok, x = self.state.tokens(obs_t) + pr = self.state._proprio(obs_t, tok.shape[0]) + return SimpleNamespace(x=x, tok=tok, pr=pr) + if self.backend_name == "lewm": + # PIXELS, through the SAME transform train_lewm.py used (lewm_data.frames_from_obs), plus + # the pooled DINO state so nothing else in the planner changes. + _rsm_modules() + img = importlib.import_module("lewm_data").frames_from_obs( + obs_t, cams=self.backend.cams, res=self.backend.res).to(self.device) + pr = self.state._proprio(obs_t, img.shape[0]) + # DINO runs here ONLY when a hop head is loaded (gen_q#288). LeWM itself scores from + # pixels and never reads the pooled state, and the flagship discloses each scorer's search + # cost -- charging LeWM for a DINOv2 forward it does not use would overstate that cost, so + # a no-hop cell keeps x=None and the pre-#288 cost exactly. With a hop head the + # continuation actor IS a policy over the pooled 1545-d state, so the forward is genuinely + # part of this scorer's cost and is paid once per decision (not per candidate). + if self.backend.hop is None: + return SimpleNamespace(x=None, tok=None, pr=pr, img=img) + _tok, x = self.state.tokens(obs_t) + return SimpleNamespace(x=x, tok=None, pr=pr, img=img) + return SimpleNamespace(x=self.state(obs_t), tok=None, pr=None) + + @staticmethod + def as_state(s): + if isinstance(s, torch.Tensor): + return SimpleNamespace(x=s, tok=None, pr=None) + if not hasattr(s, "pr"): + s.pr = None + return s + + @staticmethod + def repeat_state(s, N): + """B states -> B*N states, repeat_interleave'd, for one state per candidate chunk. + + Lives here, not in the caller, because the SCORER decides which fields its backend reads: + rsm_planner used to rebuild the namespace itself as (x, tok, pr) and silently dropped the + pixel backends' `img` (gen_q#268), so every LeWM eval cell died in _rows on a None input. + Repeating whatever vars(s) holds cannot go stale when a backend adds a field.""" + s = RSMScorer.as_state(s) + if int(N) == 1: + return s + return type(s)(**{k: (v.repeat_interleave(int(N), 0) if torch.is_tensor(v) else v) + for k, v in vars(s).items()}) + + def _flat_chunk(self, A): + A = torch.as_tensor(A, dtype=torch.float32, device=self.device) + if A.dim() == 3: + if A.shape[1] < self.chunk: + raise RuntimeError(f"need {self.chunk} actions per chunk, got {A.shape[1]}") + A = A[:, :self.chunk].reshape(A.shape[0], -1) + if A.shape[1] != self.d_act: + raise RuntimeError(f"chunk is {A.shape[1]}-d, RSM expects {self.d_act}") + return A + + def _inputs(self, s): + # Every branch names the field it needs and raises if the caller did not carry it. A missing + # field used to surface as `'NoneType' object has no attribute 'shape'` from _rows, three + # frames away from the caller that dropped it (gen_q#268: rsm_planner's st_rep rebuilt the + # namespace from a hardcoded (x, tok, pr) list and lost `img`), which is exactly the kind of + # silent degradation this pipeline keeps paying for. + if self.backend_name in TOKEN_BACKENDS: + return (self._need(s, "tok"), s.pr) + if self.backend_name == "lewm": + # gen_q#288: 3-tuple (frames, proprio, pooled_raw) when a hop head is loaded, so + # lewm_readout can sample the continuation actor; the historic 2-tuple otherwise, which is + # what lewm_readout._pooled_of reads as "no hop head on this cell". + if self.backend.hop is not None: + return (self._need(s, "img"), s.pr, self._need(s, "x")) + return (self._need(s, "img"), s.pr) + return self.backend.latent(self._need(s, "x")) if hasattr(self.backend, "latent") \ + else self._need(s, "x") + + def _need(self, s, field): + """The state field this backend scores from, or a RuntimeError naming backend AND field.""" + v = getattr(s, field, None) + if v is None: + have = sorted(k for k, t in vars(s).items() if t is not None) if hasattr(s, "__dict__") else [] + raise RuntimeError( + f"backend={self.backend_name} scores from state field '{field}', but it is None " + f"(state carries {have or 'nothing'}). The caller built the state without it -- see " + f"rsm_planner.plan_get_action's st_rep, which must repeat every field of " + f"RSMScorer.state_from_obs's output.") + return v + + @staticmethod + def _rows(inp): + return inp[0].shape[0] if isinstance(inp, tuple) else inp.shape[0] + + @staticmethod + def _expand(inp, N): + if isinstance(inp, tuple): + return tuple(None if t is None else t.expand(N, *t.shape[1:]) for t in inp) + return inp.expand(N, *inp.shape[1:]) + + @staticmethod + def _repeat(inp, M): + if isinstance(inp, tuple): + return tuple(None if t is None else t.repeat_interleave(M, 0) for t in inp) + return inp.repeat_interleave(M, 0) + + @staticmethod + def _cat(a, b): + if isinstance(a, tuple): + return tuple(None if x is None else torch.cat([x, y], 0) for x, y in zip(a, b)) + return torch.cat([a, b], 0) + + @staticmethod + def _index(inp, idx): + if isinstance(inp, tuple): + return tuple(None if t is None else t[idx] for t in inp) + return inp[idx] + + def effective_temperature(self): + """The T the sigmoid uses: the override if > 0, else the checkpoint's (calib.json or 1.0).""" + if self.temperature > 0: + return self.temperature + return float(getattr(self.backend, "temperature", 1.0)) + + # ---- E1 ---------------------------------------------------------------- + @torch.no_grad() + # ---- hop accounting for the coin chain (gen_q#267) --------------------------------------- + # The cheapest proof the chain does what the maths says: the number of hops the walk ACTUALLY takes + # must match E[N] = p/(1-p) = the same quantity tab:discounts calls L* = (1-beta)/(1-gamma). Summed + # over every decision of a cell, then written into the eval JSON by the planner. + def _accum_chain_stats(self): + st = getattr(self.backend, "last_chain_stats", None) + if st is None: + return + self.backend.last_chain_stats = None # consume, so a fold decision cannot inherit it + a = getattr(self, "chain_hop_acc", None) + if a is None: + a = self.chain_hop_acc = {"decisions": 0, "hops_sum": 0.0, "hops_sq_sum": 0.0, + "capped_sum": 0.0, "expired_sum": 0.0, "levels_run": 0, + "cap_binding_decisions": 0, "hops_p90_sum": 0.0, + "levels_per_row_sum": 0.0, + "hops_median_sum": 0.0, "hops_mean_expired_sum": 0.0, + "hops_mean_expired_n": 0} + for k in ("mode", "beta", "gamma", "p_cont", "cap", "tail_eps", "tail_prob_at_cap", + "n_particles", "E_hops_expected", "E_beta_reads_expected", + "L_star_tab_discounts", "frame_offset_mean_expected", "absorbed_note"): + a[k] = st[k] + a["decisions"] += 1 + a["hops_sum"] += st["hops_mean"] + a["hops_sq_sum"] += st["hops_mean"] ** 2 + a["hops_median_sum"] += st["hops_median"] + a["hops_p90_sum"] += st["hops_p90"] + a["capped_sum"] += st["capped_frac"] + a["expired_sum"] += st["expired_frac"] + a["levels_run"] += st["levels_run"] + a["levels_per_row_sum"] += st["levels_per_row"] + a["cap_binding_decisions"] += int(st["cap_binding"]) + if st["hops_mean_expired"] == st["hops_mean_expired"]: # not NaN + a["hops_mean_expired_sum"] += st["hops_mean_expired"] + a["hops_mean_expired_n"] += 1 + + def chain_hop_summary(self): + """Per-cell hop accounting, or None if no chain decision was scored. Goes into the eval JSON.""" + a = getattr(self, "chain_hop_acc", None) + if not a or not a["decisions"]: + return None + d = float(a["decisions"]) + s = {k: a[k] for k in ("mode", "beta", "gamma", "p_cont", "cap", "tail_eps", + "tail_prob_at_cap", "n_particles", "E_hops_expected", + "E_beta_reads_expected", "L_star_tab_discounts", + "frame_offset_mean_expected", "absorbed_note")} + s.update({ + "decisions": int(a["decisions"]), + "hops_mean": a["hops_sum"] / d, + "hops_median": a["hops_median_sum"] / d, + "hops_p90": a["hops_p90_sum"] / d, + "hops_mean_expired": (a["hops_mean_expired_sum"] / a["hops_mean_expired_n"] + if a["hops_mean_expired_n"] else None), + "capped_frac": a["capped_sum"] / d, + "expired_frac": a["expired_sum"] / d, + "absorbed_frac": 0.0, + # Averaged from the PER-CALL value, which divides by rows = candidates x particles. The + # cell-level version used to divide the summed level count by decisions x particles only, + # dropping the 128 candidates, so it read ~670 ("levels per row") where the walk runs ~5: + # cells written before 2026-09-22 18:30Z carry that inflated value -- divide by 128. + "levels_per_row": a["levels_per_row_sum"] / d, + "levels_per_row_legacy_denominator": a["levels_run"] / max(a["decisions"] * a["n_particles"], 1), + "cap_binding_decisions": int(a["cap_binding_decisions"]), + # THE FLAG the loader reads: a cell whose cap binds is truncated and must not be quoted + # as a chain number without it. + # THE CELL-LEVEL RULE IS THE AGGREGATE ONE ONLY. It used to also fire on + # `cap_binding_decisions > 0`, i.e. on a single decision in which one particle of 16 + # reached the cap -- which happens on ~1.4 % of decisions BY DESIGN at a 1e-3 per-particle + # tail, so every healthy chain cell was flagged as truncated. A flag that is always on + # carries no information and would have put a truncation warning on every row. The + # per-decision count is kept as a diagnostic beside it. + "cap_binding": bool(a["capped_sum"] / d > 1e-2 + or a["hops_sum"] / d > 0.9 * max(a["cap"], 1)), + }) + # the hop-accounting check itself: mean hops among EXPIRED particles must match E[N]. The + # OVERALL mean is the same number here (the reference chain has no absorbing event), so a + # mismatch is a real defect, not a membership-density artefact. + e = s["E_hops_expected"] + s["hops_rel_err"] = abs(s["hops_mean"] - e) / max(e, 1e-9) + return s + + def score(self, state, A, seed=None, mode=None, depth=None, beta=None, rescore_top=None, + n_particles_rescore=None): + """Ranking array [N]: Q̄ for score_kind="prob", Q̄_logit for "logit", the per-particle + `lcb_quantile` quantile of Q for "conformal_lcb". All three are kept in `.last_q` / `.last_q_logit` / + `.last_q_lcb` (the logit is None for recursive / mc, the LCB None unless conformal). Two-stage + screening: every candidate with n_particles, then the top-K of the RANKING array rescored with M + particles and written back.""" + s = self.as_state(state) + A = self._flat_chunk(A) + N = A.shape[0] + inp = self._inputs(s) + R = self._rows(inp) + if R == 1 and N > 1: + inp = self._expand(inp, N) + elif R != N: + raise RuntimeError(f"{R} states for {N} chunks") + mode = mode or self.mode + depth = depth or self.depth + beta = self.beta if beta is None else beta + K = self.rescore_top if rescore_top is None else int(rescore_top or 0) + M = self.n_particles_rescore if n_particles_rescore is None else int(n_particles_rescore or 0) + two_stage = bool(K and M and K < N) + conformal = self.score_kind == "conformal_lcb" + problog = self.score_kind == "prob_log" + kw = dict(mode=mode, depth=depth, beta=beta, gamma=self.gamma, flow_steps=self.flow_steps, + return_logit=True) + if conformal: + kw["return_lcb"] = self.lcb_quantile + if problog: + kw["return_problog"] = True + if self.backend_name != "mc": + kw["temperature"] = self.temperature if self.temperature > 0 else None + if self.backend_name in TOKEN_BACKENDS: + kw["crn_seed"] = None if (seed is None or int(seed) < 0) else int(seed) + if two_stage: # dwm_readout screens internally (top-K by q_logit) + kw["rescore_top"], kw["n_particles_rescore"] = K, M + def _unpack(out): + """(Q̄, Q̄_logit [, LCB] [, prob_log]) -> (q, ql, lcb, plg) with the absent ones None.""" + o = list(out) if isinstance(out, tuple) else [out] + q_, ql_ = o.pop(0), (o.pop(0) if o else None) + lcb_ = o.pop(0) if (conformal and o) else None + plg_ = o.pop(0) if (problog and o) else None + return q_, ql_, lcb_, plg_ + + with seeded(seed, self.device): + q, ql, lcb, plg = _unpack(self.backend.q(inp, A, n_particles=self.n_particles, **kw)) + q = q.float() + ql = None if ql is None else ql.float() + lcb = None if lcb is None else lcb.float() + plg = None if plg is None else plg.double() + rank = self._rank_of(q, ql, lcb, plg) + if two_stage and self.backend_name not in TOKEN_BACKENDS: + top = torch.topk(rank, K).indices + q2, ql2, lcb2, plg2 = _unpack( + self.backend.q(self._index(inp, top), A[top], n_particles=M, **kw)) + q = q.clone(); q[top] = q2.float() + if ql is not None and ql2 is not None: + ql = ql.clone(); ql[top] = ql2.float() + if lcb is not None and lcb2 is not None: + lcb = lcb.clone(); lcb[top] = lcb2.float() + if plg is not None and plg2 is not None: + plg = plg.clone(); plg[top] = plg2.double() + rank = self._rank_of(q, ql, lcb, plg) + self.last_q, self.last_q_logit, self.last_q_lcb = q, ql, lcb + self.last_q_problog = plg + self._accum_chain_stats() + return rank + + @torch.no_grad() + def score_trace(self, state, A, seed=None, mode=None, depth=None, beta=None): + """VISUALISATION ONLY (gen_q#270). Same call as `score()` for the mlp backend's d1/fold read-out, + but returns (rank [N], trace) where trace exposes what the fold already computes internally and + normally discards: + + trace["z"] [L, N, P, D] fp16 the successor SAMPLES at each hop (z-scored state space) + trace["a"] [L, N, P, d_act] the chunk that produced each z (hop 0 = the candidate itself) + trace["lg"] [L, N, P] raw reward logits R(z) + trace["c"] [L, N, P] c_k = sigmoid(R(z)/T) -- the GREEN/RED membership + trace["q"] [L+1, N, P] the backward fold's partials; q[0].mean(1) == .last_q + + It does NOT go through the two-stage rescreening path (rescore_top is ignored) so that the trace and + the returned rank describe ONE pass with `n_particles` particles; for the flagship cells + rescore_top=0 anyway, and `score()` itself is untouched. Every RNG draw is the fold's own, so with + the same `seed` the q values here equal `score()`'s bit for bit (tests/test_rsm_trace.py).""" + if self.backend_name != "mlp": + raise RuntimeError(f"score_trace needs the mlp backend (got {self.backend_name})") + s_ = self.as_state(state) + A = self._flat_chunk(A) + N = A.shape[0] + inp = self._inputs(s_) + R = self._rows(inp) + if R == 1 and N > 1: + inp = self._expand(inp, N) + elif R != N: + raise RuntimeError(f"{R} states for {N} chunks") + mode = mode or self.mode + depth = depth or self.depth + beta = self.beta if beta is None else beta + conformal = self.score_kind == "conformal_lcb" + problog = self.score_kind == "prob_log" + kw = dict(mode=mode, depth=depth, beta=beta, gamma=self.gamma, flow_steps=self.flow_steps, + return_logit=True, return_trace=True, + temperature=self.temperature if self.temperature > 0 else None) + if conformal: + kw["return_lcb"] = self.lcb_quantile + if problog: + kw["return_problog"] = True + with seeded(seed, self.device): + out = list(self.backend.q(inp, A, n_particles=self.n_particles, **kw)) + trace = out.pop() + q, ql = out.pop(0).float(), (out.pop(0) if out else None) + ql = None if ql is None else ql.float() + lcb = out.pop(0).float() if (conformal and out) else None + plg = out.pop(0).double() if (problog and out) else None + self.last_q, self.last_q_logit, self.last_q_lcb, self.last_q_problog = q, ql, lcb, plg + return self._rank_of(q, ql, lcb, plg), trace + + def _rank_of(self, q, ql, lcb, plg=None): + """the array the selection rule sees, per score_kind (falling back to Q̄ when a backend has none).""" + if self.score_kind == "logit" and ql is not None: + return ql + if self.score_kind == "conformal_lcb" and lcb is not None: + return lcb + if self.score_kind == "prob_log" and plg is not None: + return plg + return q + + # ---- E2 ---------------------------------------------------------------- + @torch.no_grad() + def advantage(self, state, A, v_samples=16, v_expectile=0.5, seed=None): + """Q̄(x, A) and V̄_τ(x) = τ-expectile over M hop-head chunks of Q̄(x, a^(m)); all B×(1+M) rows are + scored in ONE batched call so the CRN noise is shared across the logged chunk and its baselines.""" + s = self.as_state(state) + A = self._flat_chunk(A) + B, M = A.shape[0], int(v_samples) + if self.backend.hop is None: + raise RuntimeError("advantage needs a hop head (rsm_hop_ckpt) to draw baseline chunks") + inp = self._inputs(s) + if self._rows(inp) != B: + raise RuntimeError(f"{self._rows(inp)} states for {B} chunks") + kw = {} + if self.backend_name in TOKEN_BACKENDS: + kw["crn_seed"] = None if (seed is None or int(seed) < 0) else int(seed) + with seeded(seed, self.device): + eps = torch.randn(M, self.d_act, device=self.device).repeat(B, 1) # CRN over rows + x_rep = s.x.repeat_interleave(M, 0) + a_hop = self.backend.hop_sample(x_rep, eps) # [B*M, d_act] + a_all = torch.cat([A, a_hop], 0) + inp_all = self._cat(inp, self._repeat(inp, M)) + q_all = self.backend.q(inp_all, a_all, mode=self.mode, depth=self.depth, beta=self.beta, + gamma=self.gamma, n_particles=self.n_particles, flow_steps=self.flow_steps, **kw) + q = q_all[:B].float() + qm = q_all[B:].float().view(B, M) + v = expectile(qm, v_expectile) + return q, v, qm + + def effective_horizon(self): + _, _, is_ope = _rsm_modules() + if self.mode == "recursive" and self.backend_name not in TOKEN_BACKENDS: + return is_ope.effective_horizon(self.beta, self.gamma, self.depth) + L = 1 if self.mode == "d1" else self.depth + if self.mode in _MPC_MODES: + hf = float(getattr(self, "mpc_hop_frames", self.chunk)) + return {"mean_hops": float(L), "effective_frames": L * hf, "gamma_nominal": self.gamma, + "hop_frames": hf, "mpc_horizon_frames": self.mpc_horizon, + "mpc_horizon_from_gamma": 1.0 / (1.0 - self.gamma)} + # A DINO-WM hop is ONE ACTION CHUNK (the step it was trained on), not 1/(1-beta) frames: it + # has no beta. Reporting the beta horizon for it would overstate its reach by ~2.5x at + # beta=0.95 and is exactly the kind of mismatch the flagship table has to get right. + if self.backend_name in ("dinowm", "lewm"): + hf = float(getattr(getattr(self.backend, "core", None), "hop_frames", self.chunk)) + return {"mean_hops": float(L), "effective_frames": L * hf, "gamma_nominal": self.gamma, + "hop_frames": hf} + return {"mean_hops": float(L), "effective_frames": L / (1.0 - self.beta), "gamma_nominal": self.gamma} + + def _hop_varies_with_beta(self): + """Probe the backend's own hop at two betas. A critic that ignores beta (DINO-WM's + deterministic latent step, LeWM's fixed action chunk) returns the same number twice.""" + hf = getattr(getattr(self.backend, "core", None), "_hop_frames", None) + if not callable(hf): + return False + try: + return abs(float(hf(0.90)) - float(hf(0.995))) > 1e-9 + except Exception: + return False + + def effective_particles(self): + """How many DISTINCT roll-outs this cell's Q average is over, asked of the BACKEND'S CORE. + + A backend whose core does not answer is taken at its word (mlp, dwm, df, mc all average exactly + `n_particles` chains). dinowm / lewm answer 1 at depth 1 -- no continuation to sample, so the + roll really is deterministic there -- and `n_particles` above it (gen_q#288).""" + core = getattr(self.backend, "core", None) + f = getattr(core, "n_eff_particles", None) + if f is None: + return int(self.n_particles) + if self.backend_name == "lewm": + return int(f(self.n_particles, self.depth, self.mode, + None if self.backend.hop is None else True)) + return int(f(self.n_particles, self.depth, self.mode)) + + def describe(self): + state = None + if self.state is not None: + state = {"dim": self.state.d, "sd_floor": self.state.sd_floor, "z_clip": self.state.z_clip, + "img_layout": self.state.img_layout, "cams": list(self.state.cams), + "proprio_keys": list(self.state.proprio_keys)} + return {"backend": self.backend_name, "mode": self.mode, "depth": self.depth, "beta": self.beta, + "state": state, + "gamma": self.gamma, "n_particles": self.n_particles, + # gen_q#288 -- THE MEASURED PARTICLE COUNT, not the requested one. dinowm / lewm used + # to collapse any request to a single roll-out, so 855 + 630 published cells recorded + # `n_particles: 16` and averaged ONE chain. verdict_table's arm key reads this field + # (absent => M1, which is what those cells were), so a repaired cell cannot pool with + # them. Same self-verifying trick as the `temperature` field above. + "effective_particles": self.effective_particles(), + "flow_steps": self.flow_steps, + "chunk": self.chunk, "adim": self.adim, "hop": self.backend.hop is not None, + "score_kind": self.score_kind, "fold_openloop": self.fold_openloop, + "fold_sample_clip": self.fold_sample_clip, + "rescore_top": self.rescore_top, + "n_particles_rescore": self.n_particles_rescore, "temperature_override": self.temperature, + "lcb_quantile": self.lcb_quantile if self.score_kind == "conformal_lcb" else None, + "temperature": self.effective_temperature(), + "horizon": self.effective_horizon(), + # coin chain (gen_q#267): None for every non-chain cell, so an archived describe() is + # unchanged and the loader can tell a chain cell from a fold cell by this key alone. + "chain": (None if self.mode not in ("chain", "chain_rb") else { + "p_cont": chain_continuation_p(self.beta, self.gamma), + "cap": self.chain_cap or chain_cap_fn(self.beta, self.gamma, self.chain_tail_eps), + "cap_source": "override" if self.chain_cap else "computed from the 1e-3 tail", + "tail_eps": self.chain_tail_eps, + "E_hops_expected": (lambda p: p / (1 - p))(chain_continuation_p(self.beta, self.gamma)), + "reference": "ogbench_genq/rsm.py:113 rec_p=(gamma-beta)/(gamma*(1-beta)); :532 chain_prob"}), + # gen_q#273: None for every non-MPC cell, so an archived describe() is unchanged. + "mpc": (None if self.mode not in _MPC_MODES else { + "horizon_frames": self.mpc_horizon, + "horizon_from_gamma": 1.0 / (1.0 - self.gamma), + "hop_frames": self.mpc_hop_frames, + "chunks_rolled": self.depth, + "frames_rolled": self.depth * self.mpc_hop_frames, + "readout": ("terminal latent" if self.mode == "mpc" else + "gamma-discounted sum over the roll-out, normalised by sum_k gamma**(h k)"), + # gen_q#288. Both world models now chain with the SAME stochastic hop head; what + # differs is the STATE it is conditioned on (DINO-WM: the rolled latent's pooled + # vector; LeWM: the current observation's, because a LeWM embedding has no pooled + # DINO vector). describe() must never claim a hop head ran when none is loaded. + "continuation": ("zero-order hold of the candidate chunk (no hop head loaded)" + if self.backend.hop is None and self.backend_name == "lewm" else + "hop head (runs//hop/gauss/policy_r1.pt) past chunk 1"), + "continuation_state": ("rolled latent" if self.backend_name != "lewm" else + "current observation (LeWM's latent has no pooled DINO " + "vector; see lewm_readout deviation 2)"), + "particles": self.effective_particles(), + # measured, not assumed: does this critic's own hop move with beta at all? + # False on DINO-WM and LeWM (constant 8), True on the RSM/DWM occupancy flow. + "beta_affects_hop": self._hop_varies_with_beta()}), + "chain_hops": self.chain_hop_summary()} + + +# --------------------------------------------------------------------------- # +# test helpers: random checkpoints in the real blob formats +# --------------------------------------------------------------------------- # +def save_random_rsm_ckpt(path, d_in=STATE_DIM, chunk=8, adim=7, flow_width=64, flow_depth=2, seed=0): + """Randomly initialised identity-encoder MLP successor in train_rsm.py's blob format.""" + model, _, _ = _rsm_modules() + torch.manual_seed(seed) + d_act = chunk * adim + enc = model.IdentityEncoder(d_in) + rew = model.RewardHead(d_in, 1) + flow = model.OccFlow(d_in, d_act, 1, width=flow_width, depth=flow_depth) + blob = {"enc": enc.state_dict(), "enc_t": enc.state_dict(), "rew": rew.state_dict(), + "flow": flow.state_dict(), "rms": torch.ones(d_in), "n_pr": 0, "tasks": ["task"], + "d_act": d_act, "step": 0, "enc_kind": "identity", "d_in": d_in, "d_lat": d_in, + "config": {"enc": "identity", "d_z": d_in, "enc_width": 1024, "flow_width": flow_width, + "flow_depth": flow_depth, "chunk": chunk, "beta_lo": 0.9, "beta_hi": 0.995}} + torch.save(blob, path) + return path + + +def save_random_hop_ckpt(path, d_in=STATE_DIM, chunk=8, adim=7, family="gauss", seed=0): + model, _, _ = _rsm_modules() + torch.manual_seed(seed) + d_act = chunk * adim + if family == "gauss": + pol = model.BCHead(d_in, d_act, 1) + elif family == "flow": + pol = model.FlowPolicy(d_in, d_act, 1) + else: + pol = model.ConcatFlowPolicy(d_in, d_act, 1, width=64, depth=2) + torch.save({"pol": pol.state_dict(), "round": 1, + "config": {"policy_family": family, "chunk": chunk, "policy_features": "raw", + "feat_scale": "zscore", "pol_width": 64, "pol_depth": 2}}, path) + return path + + +def save_feat_stats(path, d=STATE_DIM, seed=0): + rng = np.random.default_rng(seed) + np.savez(path, mu=rng.normal(size=d).astype(np.float32), + sd=np.maximum(rng.uniform(0.5, 2.0, size=d), 1e-3).astype(np.float32), dim=d, n=1000) + return path diff --git a/code_src/rise_robomimic/robomimic/algo/td3_bc.py b/code_src/rise_robomimic/robomimic/algo/td3_bc.py new file mode 100644 index 0000000000000000000000000000000000000000..e324c54a1614c1c01b3efdb1def9c8f6f11b2c70 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/td3_bc.py @@ -0,0 +1,567 @@ +""" +Implementation of TD3-BC. +Based on https://github.com/sfujim/TD3_BC +(Paper - https://arxiv.org/abs/1812.02900). + +Note that several parts are exactly the same as the BCQ implementation, +such as @_create_critics, @process_batch_for_training, and +@_train_critic_on_batch. They are replicated here (instead of subclassing +from the BCQ algo class) to be explicit and have implementation details +self-contained in this file. +""" +from collections import OrderedDict + +import torch +import torch.nn as nn +import torch.nn.functional as F + +import robomimic.models.obs_nets as ObsNets +import robomimic.models.policy_nets as PolicyNets +import robomimic.models.value_nets as ValueNets +import robomimic.models.vae_nets as VAENets +import robomimic.utils.tensor_utils as TensorUtils +import robomimic.utils.torch_utils as TorchUtils +import robomimic.utils.obs_utils as ObsUtils +import robomimic.utils.loss_utils as LossUtils + +from robomimic.algo import register_algo_factory_func, PolicyAlgo, ValueAlgo + + +@register_algo_factory_func("td3_bc") +def algo_config_to_class(algo_config): + """ + Maps algo config to the TD3_BC algo class to instantiate, along with additional algo kwargs. + + Args: + algo_config (Config instance): algo config + + Returns: + algo_class: subclass of Algo + algo_kwargs (dict): dictionary of additional kwargs to pass to algorithm + """ + # only one variant of TD3_BC for now + return TD3_BC, {} + + +class TD3_BC(PolicyAlgo, ValueAlgo): + """ + Default TD3_BC training, based on https://arxiv.org/abs/2106.06860 and + https://github.com/sfujim/TD3_BC. + """ + def __init__(self, **kwargs): + PolicyAlgo.__init__(self, **kwargs) + + # save the discount factor - it may be overriden later + self.set_discount(self.algo_config.discount) + + # initialize actor update counter. This is used to train the actor at a lower freq than critic + self.actor_update_counter = 0 + + def _create_networks(self): + """ + Creates networks and places them into @self.nets. + """ + self.nets = nn.ModuleDict() + + self._create_critics() + self._create_actor() + + # sync target networks at beginning of training + with torch.no_grad(): + for critic_ind in range(len(self.nets["critic"])): + TorchUtils.hard_update( + source=self.nets["critic"][critic_ind], + target=self.nets["critic_target"][critic_ind], + ) + + TorchUtils.hard_update( + source=self.nets["actor"], + target=self.nets["actor_target"], + ) + + self.nets = self.nets.float().to(self.device) + + def _create_critics(self): + """ + Called in @_create_networks to make critic networks. + + Exactly the same as BCQ. + """ + critic_class = ValueNets.ActionValueNetwork + critic_args = dict( + obs_shapes=self.obs_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.critic.layer_dims, + value_bounds=self.algo_config.critic.value_bounds, + goal_shapes=self.goal_shapes, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + ) + + # Q network ensemble and target ensemble + self.nets["critic"] = nn.ModuleList() + self.nets["critic_target"] = nn.ModuleList() + for _ in range(self.algo_config.critic.ensemble.n): + critic = critic_class(**critic_args) + self.nets["critic"].append(critic) + + critic_target = critic_class(**critic_args) + self.nets["critic_target"].append(critic_target) + + def _create_actor(self): + """ + Called in @_create_networks to make actor network. + """ + actor_class = PolicyNets.ActorNetwork + actor_args = dict( + obs_shapes=self.obs_shapes, + goal_shapes=self.goal_shapes, + ac_dim=self.ac_dim, + mlp_layer_dims=self.algo_config.actor.layer_dims, + encoder_kwargs=ObsUtils.obs_encoder_kwargs_from_config(self.obs_config.encoder), + ) + + self.nets["actor"] = actor_class(**actor_args) + self.nets["actor_target"] = actor_class(**actor_args) + + def _check_epoch(self, net_name, epoch): + """ + Helper function to check whether backprop should happen this epoch. + + Args: + net_name (str): name of network in @self.nets and @self.optim_params + epoch (int): epoch number + """ + epoch_start_check = (self.optim_params[net_name]["start_epoch"] == -1) or (epoch >= self.optim_params[net_name]["start_epoch"]) + epoch_end_check = (self.optim_params[net_name]["end_epoch"] == -1) or (epoch < self.optim_params[net_name]["end_epoch"]) + return (epoch_start_check and epoch_end_check) + + def set_discount(self, discount): + """ + Useful function to modify discount factor if necessary (e.g. for n-step returns). + """ + self.discount = discount + + def process_batch_for_training(self, batch): + """ + Processes input batch from a data loader to filter out + relevant information and prepare the batch for training. + + Exactly the same as BCQ. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader + + Returns: + input_batch (dict): processed and filtered batch that + will be used for training + """ + input_batch = dict() + + # n-step returns (default is 1) + n_step = self.algo_config.n_step + assert batch["actions"].shape[1] >= n_step + + # remove temporal batches for all + input_batch["obs"] = {k: batch["obs"][k][:, 0, :] for k in batch["obs"]} + input_batch["next_obs"] = {k: batch["next_obs"][k][:, n_step - 1, :] for k in batch["next_obs"]} + input_batch["goal_obs"] = batch.get("goal_obs", None) # goals may not be present + input_batch["actions"] = batch["actions"][:, 0, :] + + # note: ensure scalar signals (rewards, done) retain last dimension of 1 to be compatible with model outputs + + # single timestep reward is discounted sum of intermediate rewards in sequence + reward_seq = batch["rewards"][:, :n_step] + discounts = torch.pow(self.algo_config.discount, torch.arange(n_step).float()).unsqueeze(0) + input_batch["rewards"] = (reward_seq * discounts).sum(dim=1).unsqueeze(1) + + # discount rate will be gamma^N for computing n-step returns + new_discount = (self.algo_config.discount ** n_step) + self.set_discount(new_discount) + + # consider this n-step seqeunce done if any intermediate dones are present + done_seq = batch["dones"][:, :n_step] + input_batch["dones"] = (done_seq.sum(dim=1) > 0).float().unsqueeze(1) + + if self.algo_config.infinite_horizon: + # scale terminal rewards by 1 / (1 - gamma) for infinite horizon MDPs + done_inds = input_batch["dones"].round().long().nonzero(as_tuple=False)[:, 0] + if done_inds.shape[0] > 0: + input_batch["rewards"][done_inds] = input_batch["rewards"][done_inds] * (1. / (1. - self.discount)) + + # we move to device first before float conversion because image observation modalities will be uint8 - + # this minimizes the amount of data transferred to GPU + return TensorUtils.to_float(TensorUtils.to_device(input_batch, self.device)) + + def _train_critic_on_batch(self, batch, epoch, no_backprop=False): + """ + A modular helper function that can be overridden in case + subclasses would like to modify training behavior for the + critics. + + Exactly the same as BCQ (except for removal of @action_sampler_outputs and @critic_outputs) + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + no_backprop (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + info = OrderedDict() + + # batch variables + s_batch = batch["obs"] + a_batch = batch["actions"] + r_batch = batch["rewards"] + ns_batch = batch["next_obs"] + goal_s_batch = batch["goal_obs"] + + # 1 if not done, 0 otherwise + done_mask_batch = 1. - batch["dones"] + info["done_masks"] = done_mask_batch + + # Bellman backup for Q-targets + q_targets = self._get_target_values( + next_states=ns_batch, + goal_states=goal_s_batch, + rewards=r_batch, + dones=done_mask_batch, + ) + info["critic/q_targets"] = q_targets + + # Train all critics using this set of targets for regression + for critic_ind, critic in enumerate(self.nets["critic"]): + critic_loss = self._compute_critic_loss( + critic=critic, + states=s_batch, + actions=a_batch, + goal_states=goal_s_batch, + q_targets=q_targets, + ) + info["critic/critic{}_loss".format(critic_ind + 1)] = critic_loss + + if not no_backprop: + critic_grad_norms = TorchUtils.backprop_for_loss( + net=self.nets["critic"][critic_ind], + optim=self.optimizers["critic"][critic_ind], + loss=critic_loss, + max_grad_norm=self.algo_config.critic.max_gradient_norm, + ) + info["critic/critic{}_grad_norms".format(critic_ind + 1)] = critic_grad_norms + + return info + + def _train_actor_on_batch(self, batch, epoch, no_backprop=False): + """ + A modular helper function that can be overridden in case + subclasses would like to modify training behavior for the + actor. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + no_backprop (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + info = OrderedDict() + + # Actor loss (update with mixture of DDPG loss and BC loss) + s_batch = batch["obs"] + a_batch = batch["actions"] + goal_s_batch = batch["goal_obs"] + + # lambda mixture weight is combination of hyperparameter (alpha) and Q-value normalization + actor_actions = self.nets["actor"](s_batch, goal_s_batch) + Q_values = self.nets["critic"][0](s_batch, actor_actions, goal_s_batch) + lam = self.algo_config.alpha / Q_values.abs().mean().detach() + actor_loss = -lam * Q_values.mean() + nn.MSELoss()(actor_actions, a_batch) + info["actor/loss"] = actor_loss + + if not no_backprop: + actor_grad_norms = TorchUtils.backprop_for_loss( + net=self.nets["actor"], + optim=self.optimizers["actor"], + loss=actor_loss, + ) + info["actor/grad_norms"] = actor_grad_norms + + return info + + def _get_target_values(self, next_states, goal_states, rewards, dones): + """ + Helper function to get target values for training Q-function with TD-loss. + + Args: + next_states (dict): batch of next observations + goal_states (dict): if not None, batch of goal observations + rewards (torch.Tensor): batch of rewards - should be shape (B, 1) + dones (torch.Tensor): batch of done signals - should be shape (B, 1) + + Returns: + q_targets (torch.Tensor): target Q-values to use for TD loss + """ + + with torch.no_grad(): + # get next actions via target actor and noise + next_target_actions = self.nets["actor_target"](next_states, goal_states) + noise = ( + torch.randn_like(next_target_actions) * self.algo_config.actor.noise_std + ).clamp(-self.algo_config.actor.noise_clip, self.algo_config.actor.noise_clip) + next_actions = (next_target_actions + noise).clamp(-1.0, 1.0) + + # TD3 trick to combine max and min over all Q-ensemble estimates into single target estimates + all_value_targets = self.nets["critic_target"][0](next_states, next_actions, goal_states).reshape(-1, 1) + max_value_targets = all_value_targets + min_value_targets = all_value_targets + for critic_target in self.nets["critic_target"][1:]: + all_value_targets = critic_target(next_states, next_actions, goal_states).reshape(-1, 1) + max_value_targets = torch.max(max_value_targets, all_value_targets) + min_value_targets = torch.min(min_value_targets, all_value_targets) + value_targets = self.algo_config.critic.ensemble.weight * min_value_targets + \ + (1. - self.algo_config.critic.ensemble.weight) * max_value_targets + q_targets = rewards + dones * self.discount * value_targets + + return q_targets + + def _compute_critic_loss(self, critic, states, actions, goal_states, q_targets): + """ + Helper function to compute loss between estimated Q-values and target Q-values. + + Nearly the same as BCQ (return type slightly different). + + Args: + critic (torch.nn.Module): critic network + states (dict): batch of observations + actions (torch.Tensor): batch of actions + goal_states (dict): if not None, batch of goal observations + q_targets (torch.Tensor): batch of target q-values for the TD loss + + Returns: + critic_loss (torch.Tensor): critic loss + """ + q_estimated = critic(states, actions, goal_states) + if self.algo_config.critic.use_huber: + critic_loss = nn.SmoothL1Loss()(q_estimated, q_targets) + else: + critic_loss = nn.MSELoss()(q_estimated, q_targets) + return critic_loss + + def train_on_batch(self, batch, epoch, validate=False): + """ + Training on a single batch of data. + + Args: + batch (dict): dictionary with torch.Tensors sampled + from a data loader and filtered by @process_batch_for_training + + epoch (int): epoch number - required by some Algos that need + to perform staged training and early stopping + + validate (bool): if True, don't perform any learning updates. + + Returns: + info (dict): dictionary of relevant inputs, outputs, and losses + that might be relevant for logging + """ + with TorchUtils.maybe_no_grad(no_grad=validate): + info = PolicyAlgo.train_on_batch(self, batch, epoch, validate=validate) + + # Critic training + no_critic_backprop = validate or (not self._check_epoch(net_name="critic", epoch=epoch)) + with TorchUtils.maybe_no_grad(no_grad=no_critic_backprop): + critic_info = self._train_critic_on_batch( + batch=batch, + epoch=epoch, + no_backprop=no_critic_backprop, + ) + info.update(critic_info) + + # update actor and target networks at lower frequency + if not no_critic_backprop: + # update counter only on critic training gradient steps + self.actor_update_counter += 1 + do_actor_update = (self.actor_update_counter % self.algo_config.actor.update_freq == 0) + + # Actor training + no_actor_backprop = validate or (not self._check_epoch(net_name="actor", epoch=epoch)) + no_actor_backprop = no_actor_backprop or (not do_actor_update) + with TorchUtils.maybe_no_grad(no_grad=no_actor_backprop): + actor_info = self._train_actor_on_batch( + batch=batch, + epoch=epoch, + no_backprop=no_actor_backprop, + ) + info.update(actor_info) + + if not no_actor_backprop: + # to match original implementation, only update target networks on + # actor gradient steps + with torch.no_grad(): + # update the target critic networks + for critic_ind in range(len(self.nets["critic"])): + TorchUtils.soft_update( + source=self.nets["critic"][critic_ind], + target=self.nets["critic_target"][critic_ind], + tau=self.algo_config.target_tau, + ) + + # update target actor network + TorchUtils.soft_update( + source=self.nets["actor"], + target=self.nets["actor_target"], + tau=self.algo_config.target_tau, + ) + + return info + + def log_info(self, info): + """ + Process info dictionary from @train_on_batch to summarize + information to pass to tensorboard for logging. + + Args: + info (dict): dictionary of info + + Returns: + loss_log (dict): name -> summary statistic + """ + loss_log = OrderedDict() + + # record current optimizer learning rates + for k in self.optimizers: + keys = [k] + optims = [self.optimizers[k]] + if k == "critic": + # account for critic having one optimizer per ensemble member + keys = ["{}{}".format(k, critic_ind) for critic_ind in range(len(self.nets["critic"]))] + optims = self.optimizers[k] + for kp, optimizer in zip(keys, optims): + for i, param_group in enumerate(optimizer.param_groups): + loss_log["Optimizer/{}{}_lr".format(kp, i)] = param_group["lr"] + + # extract relevant logs for critic, and actor + loss_log["Loss"] = 0. + for loss_logger in [self._log_critic_info, self._log_actor_info]: + this_log = loss_logger(info) + if "Loss" in this_log: + # manually merge total loss + loss_log["Loss"] += this_log["Loss"] + del this_log["Loss"] + loss_log.update(this_log) + + return loss_log + + def _log_critic_info(self, info): + """ + Helper function to extract critic-relevant information for logging. + """ + loss_log = OrderedDict() + if "done_masks" in info: + loss_log["Critic/Done_Mask_Percentage"] = 100. * torch.mean(info["done_masks"]).item() + if "critic/q_targets" in info: + loss_log["Critic/Q_Targets"] = info["critic/q_targets"].mean().item() + loss_log["Loss"] = 0. + for critic_ind in range(len(self.nets["critic"])): + loss_log["Critic/Critic{}_Loss".format(critic_ind + 1)] = info["critic/critic{}_loss".format(critic_ind + 1)].item() + if "critic/critic{}_grad_norms".format(critic_ind + 1) in info: + loss_log["Critic/Critic{}_Grad_Norms".format(critic_ind + 1)] = info["critic/critic{}_grad_norms".format(critic_ind + 1)] + loss_log["Loss"] += loss_log["Critic/Critic{}_Loss".format(critic_ind + 1)] + return loss_log + + def _log_actor_info(self, info): + """ + Helper function to extract actor-relevant information for logging. + """ + loss_log = OrderedDict() + loss_log["Actor/Loss"] = info["actor/loss"].item() + if "actor/grad_norms" in info: + loss_log["Actor/Grad_Norms"] = info["actor/grad_norms"] + loss_log["Loss"] = loss_log["Actor/Loss"] + return loss_log + + def set_train(self): + """ + Prepare networks for evaluation. Update from super class to make sure + target networks stay in evaluation mode all the time. + """ + self.nets.train() + + # target networks always in eval + for critic_ind in range(len(self.nets["critic_target"])): + self.nets["critic_target"][critic_ind].eval() + + self.nets["actor_target"].eval() + + def on_epoch_end(self, epoch): + """ + Called at the end of each epoch. + """ + + # LR scheduling updates + for lr_sc in self.lr_schedulers["critic"]: + if lr_sc is not None: + lr_sc.step() + + if self.lr_schedulers["actor"] is not None: + self.lr_schedulers["actor"].step() + + def get_action(self, obs_dict, goal_dict=None): + """ + Get policy action outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + action (torch.Tensor): action tensor + """ + assert not self.nets.training + + return self.nets["actor"](obs_dict=obs_dict, goal_dict=goal_dict) + + def get_state_value(self, obs_dict, goal_dict=None): + """ + Get state value outputs. + + Args: + obs_dict (dict): current observation + goal_dict (dict): (optional) goal + + Returns: + value (torch.Tensor): value tensor + """ + assert not self.nets.training + + actions = self.nets["actor"](obs_dict=obs_dict, goal_dict=goal_dict) + return self.nets["critic"][0](obs_dict, actions, goal_dict) + + def get_state_action_value(self, obs_dict, actions, goal_dict=None): + """ + Get state-action value outputs. + + Args: + obs_dict (dict): current observation + actions (torch.Tensor): action + goal_dict (dict): (optional) goal + + Returns: + value (torch.Tensor): value tensor + """ + assert not self.nets.training + + return self.nets["critic"][0](obs_dict, actions, goal_dict) diff --git a/code_src/rise_robomimic/robomimic/algo/wm_native_cem.py b/code_src/rise_robomimic/robomimic/algo/wm_native_cem.py new file mode 100644 index 0000000000000000000000000000000000000000..9ad113726f7c8a642deb3f1d03a8f45b9ea7f9c0 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/algo/wm_native_cem.py @@ -0,0 +1,392 @@ +"""DINO-WM / LeWM with their OWN published planner: CEM over the full open-loop action sequence. + +gen_q#289 (worker WM_NATIVE), the appendix row that answers "you didn't run the world models the way +their authors did". This file is **additive and self-contained**: it imports `rsm_scorer.RSMScorer` +READ-ONLY (only to build the observation state exactly the way every other column builds it) and +touches nothing in `rsm_planner.py` / `rsm_scorer.py`. The shared-candidate protocol of the main +table -- N=128 proposer draws, ranked -- is unreachable from here, and so is every cell on disk. + +WHAT THE PUBLISHED PLANNERS DO (verified at source 2026-09-25, not from memory; neither repo is +vendored in this tree, so the settings were read off the upstream repo and the paper) +--------------------------------------------------------------------------------------------------- +DINO-WM gaoyuezhou/dino_wm@main:conf/planner/mpc_cem.yaml + horizon 5 | num_samples 300 | topk 30 | var_scale 1 | opt_steps 30 | n_taken_actions 5 + planning/cem.py: mu <- zeros (or the prior actions, zero-padded); sigma <- var_scale * ones; + per iteration mu = elites.mean(0), sigma = elites.std(0); NO momentum, NO smoothing, NO action + clipping; the planner returns the FINAL MU, not the best sample. +LeWM arXiv 2603.19312, planning section, quoted: + horizon "5 steps, which corresponds to 25 environment timesteps due to the use of a frame skip of + 5" | "300 candidate action sequences" | "30 iterations in PushT and 10 iterations in the other + environments" | "top 30 trajectories are retained" | "initial sampling variance is set to 1" | + "entire optimized action sequence is executed before replanning". +Both: deterministic predictor, ONE roll-out per sampled sequence, terminal goal-matching cost. + +WHAT WE CHANGE, AND WHY -- three items, all declared on #289 +--------------------------------------------------------------------------------------------------- +1. THE COST. RISE has no goal images, so the terminal goal distance is replaced by our learned reward + head, objective = the gamma-discounted sum of r_hat over the planned roll-out, normalised by the + weight sum so it stays a probability in [0, 1]. That is bit-for-bit the `mpc_disc` read-out the + flagship world-model columns already use (dwm_readout._q_once), so the native row and the shared + row differ in the SEARCH and not in the read-out. (Owner ruling: summing rewards over the + trajectory is standard.) +2. THE ACTION GRANULARITY, and the LOOKAHEAD it does NOT buy equally. One model step here is one + 8-frame action CHUNK -- that is the action granularity both checkpoints were trained to step over + -- so a 5-step plan COMMITS 40 environment frames for both families (n_taken=5 chunks) and the CEM + search space is 5 x 8 x 7 = 280-d against ~10-20-d in the published tasks at the same 300 samples. + A far sparser search relative to dimension; stated, not hidden. + The PREDICTOR's advance per model step, however, is family-dependent, and an earlier version of + this comment wrongly claimed 40 frames of lookahead for both (corrected 2026-09-26, run 33, after + the finding was confirmed from the trainers by gen_q#288): + * DINO-WM: trained on (t -> t+chunk) targets (train_rsm_dwm._onestep_future: fut = t + d.chunk), so + `_score_dinowm`'s 5 steps DO look 40 frames ahead -- exactly the window it commits. Correct. + * LeWM: trained NEXT-FRAME (lewm_model.N_PREDS = 1; train_lewm.py:174 `tgt = emb[:, N_PREDS:]` over + CONSECUTIVE rows, lewm_data.sample: `fr[j] = buf[e][j0:j0+T]`), so `_score_lewm`'s 5 `step_emb` + calls look only 5 FRAMES ahead while the same 40 are committed, and the inherited gamma^(8k) + weights (self.w, from the shared read-out) discount 8 frames per step where 1 elapses. + This is NOT why the row reads 0%: CEM reaches its objective's ceiling (J_cem = 1.0000 pooled) and + the same rollout policy with CEM OFF (`-PASS`) scores 1.3-44.7% by task. It IS a real caveat on + the LeWM half and it is now stated in the appendix prose (scripts/wm_native_text.py) too. + NOT FIXED HERE ON PURPOSE: raising LeWM's horizon or changing self.w would re-define an arm that is + already measured and published (21 CEM decisions, 84 magnitude states, 6300 episodes). The arm key + carries H, so a deeper LeWM cell would be a NEW arm, not a correction of this one. +3. HISTORY, and it is ASYMMETRIC because our two checkpoints differ. + * LeWM was trained with CTX = 3 (lewm_model.py:40) and the SHARED scorer had to fill its context by + repeating the single current frame (lewm_readout.py:109, its declared deviation 1), because + rsm_planner hands a scorer one frame. The native route owns its own ring buffer, so **LeWM + finally gets three REAL frames**. This is the one thing the native row can do that the shared + row structurally cannot. CAVEAT (measured, not assumed): those three frames are CHUNK-SPACED, + 8 apart, while LeWM's training rows are consecutive (see 2 above); our own n=252 probe found + 8-apart to be the worst of the three constructions (median L2 1.28 vs consecutive 1.03 and + repeat-current 1.14). So "real history" here means real frames, not the trained spacing. + * DINO-WM CANNOT: dwm_model.DWM.forward(tok_now, pr_now, a, ...) takes ONE frame. Our predictor + was trained history-1; three frames would need a fresh 100k-step training. So the DINO-WM native + row is history 1, declared, and the brief's "3 frames for both models" is not achievable here. + +NOT IMPLEMENTED ON PURPOSE: a stochastic / multi-continuation evaluation of a shared candidate set. +That is sibling stream WM_MCBUNDLE (gen_q#288) and this file must never grow into it. +""" +from __future__ import annotations + +import json as _json +import math +import os +import time +from types import SimpleNamespace + +import numpy as np +import torch + +from robomimic.algo.rsm_scorer import RSMScorer + +# The published defaults, keyed by family. `opt_steps` is the ONLY one that differs between them +# (LeWM uses 30 in PushT and 10 elsewhere; our tasks are "elsewhere"). +PUBLISHED = { + "dinowm": dict(horizon=5, num_samples=300, topk=30, var_scale=1.0, opt_steps=30, n_taken=5), + "lewm": dict(horizon=5, num_samples=300, topk=30, var_scale=1.0, opt_steps=10, n_taken=5), +} + + +def arm_key(family, horizon, num_samples, opt_steps, topk, n_taken, warm=False, clip=None, + passthrough=False): + """The cell's arm key. It STARTS WITH `CEM` so it can never pool with a shared-candidate arm, and + it carries every setting that changes the search, so two different searches cannot collide.""" + k = f"CEM-H{int(horizon)}-S{int(num_samples)}-I{int(opt_steps)}-T{int(topk)}-X{int(n_taken)}" + if clip is not None: + # `C05` = clipped to +-0.5. A DIFFERENT ARM, never folded into the as-published one: both + # papers explicitly do not clip (dino_wm/planning/cem.py), so a clipped cell is a variant. + k += "-C" + f"{float(clip):g}".replace(".", "p") # 0.5 -> "C0p5" + k += "-WARM" if warm else "" + # `-PASS`: the PIPELINE CONTROL, not a planner at all. The proposer's own chunk is executed + # through this exact rollout policy and CEM never runs, so a non-zero success rate here proves + # the native route can execute a good action sequence and an all-zero appendix row is the + # planner's result rather than my wiring. The `CEM` prefix is kept ONLY so the key still cannot + # pool with a shared-candidate arm; the suffix is what a reader must go by. + return k + ("-PASS" if passthrough else "") + + +class NativeCEMPlanner: + """CEM over the full open-loop action sequence, with the model's own deterministic roll-out. + + plan(obs_t) -> actions [n_taken * chunk, adim] (numpy, one env). The caller executes ALL of them + and calls plan() again -- the published receding-horizon protocol (`n_taken_actions: 5`). + """ + + def __init__(self, family, ckpt, feat_stats, device="cuda", *, horizon=None, num_samples=None, + opt_steps=None, topk=None, var_scale=None, n_taken=None, gamma=0.99, seed=0, + micro=150, img_layout="chw", warm_start=None, clip=None): + if family not in PUBLISHED: + raise ValueError(f"family must be one of {sorted(PUBLISHED)}, got {family!r}") + d = dict(PUBLISHED[family]) + self.family = family + self.horizon = int(horizon if horizon is not None else d["horizon"]) + self.num_samples = int(num_samples if num_samples is not None else d["num_samples"]) + self.opt_steps = int(opt_steps if opt_steps is not None else d["opt_steps"]) + self.topk = int(topk if topk is not None else d["topk"]) + self.var_scale = float(var_scale if var_scale is not None else d["var_scale"]) + self.n_taken = int(n_taken if n_taken is not None else d["n_taken"]) + if not 1 <= self.n_taken <= self.horizon: + raise ValueError(f"n_taken must be in [1, horizon={self.horizon}], got {self.n_taken}") + if not 1 <= self.topk <= self.num_samples: + raise ValueError(f"topk must be in [1, num_samples], got {self.topk}") + self.gamma = float(gamma) + self.micro = int(micro) + self.device = torch.device(device) + self.warm_start = warm_start # optional callable(obs_t, S) -> [S, H, d_act] + # OPTIONAL VARIANT, off by default so the as-published cell is bit-identical to run 2's. + # `clip=0.5` bounds the search to the DATA'S OWN ACTION RANGE: robomimic normalises actions + # min-max to [-0.5, 0.5] (rollout_policy.unnormalize_actions:29), so the published var_scale=1 + # puts ~96% of every sampled dimension outside the range any demonstration ever used, and the + # run-3 diagnostic measured returned |mu|_inf up to 9.0 = 18x the data range. Clipping is + # the ONE knob our action parameterisation forces; it is its own arm (`-C0p5`), never the + # as-published row. + self.clip = None if clip is None else float(clip) + + # RSMScorer is used ONLY as the observation encoder, so the native route sees exactly the + # state every other column sees. `mode`/`depth`/`beta` are never consulted: we never call + # scorer.score(), only scorer.state_from_obs(). Built with mode='d1' so nothing in its + # constructor takes an MPC or chain code path. + backend = "dinowm" if family == "dinowm" else "lewm" + self.scorer = RSMScorer(backend=backend, ckpt=ckpt, feat_stats=feat_stats, mode="d1", + depth=1, device=str(self.device), img_layout=img_layout, + dwm_module="dinowm_readout") + self.core = self.scorer.backend.core + # Ask the SCORER, not the core: `chunk` lives on the backend for the dwm/dinowm family + # (DWMBackend reads it off core.config) and on the core for LeWM, so core.chunk exists on + # exactly one of the two. RSMScorer.{chunk,adim,d_act} is the one place both are resolved, + # and it is the same triple every shared-candidate column uses -- so the native route cannot + # disagree with the shared route about what one model step is. + self.d_act = int(self.scorer.d_act) # chunk * adim = 56 + self.chunk = int(self.scorer.chunk) # 8 frames + self.adim = int(self.scorer.adim) # 7 + # likewise mpc_hop_frames is the scorer's own `_hop_frames(beta)`-or-`hop_frames` lookup, + # which prints its source in the MPC banner. Both world models here answer 8. + self.hop_frames = float(self.scorer.mpc_hop_frames) + self.T = float(getattr(self.core, "temperature", 1.0) or 1.0) + # the mpc_disc weights, computed ONCE: gamma ** (hop_frames * k), normalised. + w = torch.tensor([self.gamma ** (self.hop_frames * k) for k in range(self.horizon)], + dtype=torch.float32, device=self.device) + self.w = w / w.sum() + + self.g = torch.Generator(device=self.device) + self.seed = int(seed) + self.stats = [] + # DIAGNOSTIC ONLY (run 3, gen_q#289). `WMNAT_DIAG=` instruments the FIRST k decisions of + # every episode: the per-iteration J trace, ||mu||, and the J of the all-zero sequence for + # scale. Off unless the env var is set, and it only PRINTS -- no cell's numbers, JSON or + # control flow change, so it is safe to have on disk while the production wave runs. + self.diag_n = int(os.environ.get("WMNAT_DIAG", "0") or 0) + self._diag_left = 0 + self.reset() + + # -- episode state ------------------------------------------------------------------------ + def reset(self): + """New episode: reseed CEM and drop the frame/action history. + + The generator is reseeded PER EPISODE rather than per decision so the 300x30 draws of one + episode are one stream (a per-decision reseed would make every decision of every episode use + the identical noise, which is not what either paper does).""" + self.g.manual_seed(self.seed) + self._queue = [] # chunks of the current plan still to execute + self._last_executed = None # the chunk that produced the frame now entering the history + self._frames = None # LeWM: [ctx, C, H, W] uint8 ring buffer of REAL frames + self._acts = None # LeWM: [ctx-1, d_act] the chunks actually executed at those frames + self.stats = [] + self._diag_left = int(self.diag_n) + + # -- the roll-out ------------------------------------------------------------------------- + @torch.no_grad() + def _score_dinowm(self, st, seq): + """seq [S, H, d_act] -> J [S]. Deterministic latent roll-out, one roll-out per sequence. + + Everything stays in the normaliser's space, which is where both _step and the reward head + live (dwm_readout.DWMCritic._prep / _q_once), so this is the same arithmetic the mpc_disc + cells run -- only the actions differ per step instead of coming from a hop head.""" + c = self.core + S = seq.shape[0] + tz = c.norm.tok(torch.as_tensor(st.tok).to(self.device)) + pz = (c.norm.pr(torch.as_tensor(st.pr).to(self.device).float().view(1, c.n_pr)) + if c.n_pr else torch.zeros(1, 0, device=self.device)) + tzr = tz.expand(S, *tz.shape[1:]).contiguous() + pzr = pz.expand(S, *pz.shape[1:]).contiguous() + bq = torch.zeros(S, device=self.device) # inert on DINO-WM (dinowm_readout._step) + J = torch.zeros(S, device=self.device) + for k in range(self.horizon): + ar = seq[:, k].contiguous() + tzr, pzr = c._step(tzr, pzr, ar, bq, S, 1, None, 8, self.micro) + with c.autocast(): + lg = c.rew(tzr, pzr).float() + J = J + self.w[k] * torch.sigmoid(lg / self.T) + return torch.nan_to_num(J, nan=0.0) + + @torch.no_grad() + def _score_lewm(self, st, seq): + """seq [S, H, d_act] -> J [S], with LeWM's REAL 3-frame history. + + `self._frames` holds the last `ctx` frames actually observed and `self._acts` the chunks + actually executed at the first ctx-1 of them; the action at the LAST context slot is the + candidate's first chunk, which is what `LeWM.step_emb(emb[:, :ctx], act[:, :ctx])` was + trained on (lewm_model.py:192). After each model step the predicted embedding and the next + candidate chunk are appended, so the roll-out is open-loop in the model's own latent.""" + c = self.core + S = seq.shape[0] + ctx = int(c.ctx) + with c.autocast(): + z_hist = c.model.embed(self._frames.unsqueeze(0)) # [1, ctx, D] + z_hist = z_hist.float().expand(S, *z_hist.shape[1:]).contiguous() + a_hist = torch.cat([self._acts.unsqueeze(0).expand(S, ctx - 1, self.d_act), + seq[:, 0:1]], 1).contiguous() # [S, ctx, d_act] + J = torch.zeros(S, device=self.device) + for k in range(self.horizon): + with c.autocast(): + z = c.model.step_emb(z_hist, a_hist) + lg = c.probe(z).float() + J = J + self.w[k] * torch.sigmoid(lg / self.T) + if k == self.horizon - 1: + break + z_hist = torch.cat([z_hist[:, 1:], z.float().unsqueeze(1)], 1) + a_hist = torch.cat([a_hist[:, 1:], seq[:, k + 1:k + 2]], 1) + return torch.nan_to_num(J, nan=0.0) + + def _score(self, st, seq): + """Micro-batched over samples: 300 x 514 tokens is the same memory problem the shared scorer + has, and `micro` is purely a memory knob -- rows are independent and the CEM draws are made + once, up front, so the returned J is invariant to it.""" + out = [] + m = max(int(self.micro), 1) + fn = self._score_dinowm if self.family == "dinowm" else self._score_lewm + for i in range(0, seq.shape[0], m): + out.append(fn(st, seq[i:i + m])) + return torch.cat(out, 0) + + # -- the planner -------------------------------------------------------------------------- + @torch.no_grad() + def act(self, obs_t): + """obs_t: the CURRENT frame as a dict of [1, ...] tensors -> the next chunk [chunk, adim]. + + Called ONCE PER 8-FRAME CHUNK, and re-optimises only every `n_taken` calls -- the published + receding-horizon protocol (`n_taken_actions: 5` = execute the whole optimised sequence, then + replan), with the plan's remaining chunks served from a queue in between. + + Why not return all `n_taken * chunk` actions in one call and let the rollout loop queue them: + because then this object would only SEE a frame every 40 environment frames, so the context + would be 40 apart instead of one chunk (8 frames) apart -- a silently different model input. + Being called every chunk costs nothing (the CEM runs on 1 call in `n_taken`) and keeps the + history at the chunk spacing the arm is defined at. NOTE (corrected run 33): 8-apart is NOT + LeWM's trained spacing -- train_lewm targets emb[:, 1:] over CONSECUTIVE rows -- so this + buys real frames at the chunk spacing, not at the spacing the predictor was fit on. + """ + st = self.scorer.state_from_obs(obs_t) + if self.family == "lewm": + self._push_frame(st.img) + if not self._queue: + self._queue = list(self._cem(st, obs_t)) + a = self._queue.pop(0) + self._last_executed = a + return a.reshape(self.chunk, self.adim).float().cpu().numpy() + + @torch.no_grad() + def _cem(self, st, obs_t): + """One CEM optimisation at state `st` -> the first `n_taken` chunks of the final mu.""" + t0 = time.time() + H, S, A = self.horizon, self.num_samples, self.d_act + mu = torch.zeros(H, A, device=self.device) + sigma = torch.full((H, A), self.var_scale, device=self.device) + if self.warm_start is not None: + # the OPTIONAL second variant (#289): a TD-MPC2-style policy prior. Published DINO-WM + # supports exactly this -- cem.py seeds mu from supplied prior actions -- so it is the + # same code path with a non-zero mu, never a different algorithm. + prior = torch.as_tensor(self.warm_start(obs_t, S)).to(self.device).float() + mu = prior.reshape(-1, H, A).mean(0) + + diag = self._diag_left > 0 + trace = [] + j_best = float("nan") + for it in range(self.opt_steps): + eps = torch.randn(S, H, A, device=self.device, generator=self.g) + seq = mu.unsqueeze(0) + sigma.unsqueeze(0) * eps # NO clipping (as published) + if self.clip is not None: + seq = seq.clamp(-self.clip, self.clip) # the `-C0p5` variant only + J = self._score(st, seq) + idx = torch.topk(J, self.topk).indices + elites = seq[idx] + if diag: + # iteration 0 is the UNOPTIMISED N(0, var_scale) draw, so trace[0] IS the random + # baseline and the last entry is what CEM actually bought over it. No extra scoring. + trace.append(dict(it=it, j_max=float(J.max()), j_mean=float(J.mean()), + j_std=float(J.std()), j_elite=float(J[idx].mean()), + mu_absmax=float(mu.abs().max()), sig_mean=float(sigma.mean()))) + mu = elites.mean(0) + sigma = elites.std(0) + j_best = float(J.max().item()) + if self.clip is not None: + # the elite MEAN of clipped samples is inside the box already, but clamp the returned + # point too so the executed action can never leave the range the arm claims. + mu = mu.clamp(-self.clip, self.clip) + if diag: + self._diag_left -= 1 + # J of the returned point (the final mu) and of the all-zero sequence -- 2 extra rows. + j_mu = float(self._score(st, mu.unsqueeze(0))[0]) + j_zero = float(self._score(st, torch.zeros(1, H, A, device=self.device))[0]) + print("[wm_cem_diag] " + _json.dumps(dict( + family=self.family, j_random_max=trace[0]["j_max"], j_random_mean=trace[0]["j_mean"], + j_final_max=trace[-1]["j_max"], j_final_mean=trace[-1]["j_mean"], + j_of_returned_mu=j_mu, j_of_zero_action=j_zero, + mu_absmax=float(mu.abs().max()), mu_l2=float(mu.norm()), + sigma_mean_final=float(sigma.mean()), trace=trace), default=float), flush=True) + self.stats.append(dict(t_plan_s=time.time() - t0, j_best=j_best, + sigma_mean=float(sigma.mean().item()))) + return [mu[k] for k in range(self.n_taken)] + + # -- LeWM's real history ------------------------------------------------------------------ + def _push_frame(self, img): + """img [1, C, res, res] from RSMScorer.state_from_obs (lewm_data.frames_from_obs). + + At the first decision of an episode there is no history: the buffer is filled by repeating + the first frame with ZERO past actions. That is the same cold-start every receding-horizon + controller has, it lasts one decision, and it is stated rather than hidden.""" + c = self.core + ctx = int(c.ctx) + f = torch.as_tensor(img).to(self.device)[0] + if f.dtype.is_floating_point: + # the SAME transform lewm_readout._prep applies: the planner's frames are float in [0,1] + # and LeWM.embed was trained on uint8. Doing it here (once per frame) rather than at + # score time keeps the ring buffer in the model's own input dtype. + f = (f.clamp(0, 1) * 255.0).round().to(torch.uint8) + if self._frames is None: + self._frames = f.unsqueeze(0).repeat(ctx, *([1] * f.dim())) + self._acts = torch.zeros(ctx - 1, self.d_act, device=self.device) + return + self._frames = torch.cat([self._frames[1:], f.unsqueeze(0)], 0) + # the chunk executed at the frame that just left the "current" slot + last = self._last_executed + a = last if last is not None else torch.zeros(self.d_act, device=self.device) + self._acts = torch.cat([self._acts[1:], a.unsqueeze(0)], 0) + + # -- provenance --------------------------------------------------------------------------- + def describe(self): + d = dict(planner="native_cem", family=self.family, horizon=self.horizon, + num_samples=self.num_samples, opt_steps=self.opt_steps, topk=self.topk, + var_scale=self.var_scale, n_taken=self.n_taken, gamma=self.gamma, + hop_frames=self.hop_frames, chunk=self.chunk, adim=self.adim, d_act=self.d_act, + frames_per_plan=self.n_taken * self.chunk, frames_per_call=self.chunk, seed=self.seed, + temperature=self.T, clipping=self.clip, returns="final_mu", + objective="mpc_disc: sum_k gamma**(hop_frames*k) sigmoid(R(z_k)) / sum_k w_k", + warm_start=self.warm_start is not None, + arm=arm_key(self.family, self.horizon, self.num_samples, self.opt_steps, + self.topk, self.n_taken, self.warm_start is not None, self.clip)) + d["history"] = int(getattr(self.core, "ctx", 1)) + d["history_real"] = (self.family == "lewm") + try: + d["scorer"] = self.scorer.describe() + except Exception as e: # a description must never break an eval + d["scorer"] = {"error": repr(e)} + return d + + def pop_stats(self): + s, self.stats = self.stats, [] + if not s: + return {} + return dict(decisions=len(s), + t_plan_s=float(sum(x["t_plan_s"] for x in s)), + j_best_mean=float(np.mean([x["j_best"] for x in s])), + sigma_mean=float(np.mean([x["sigma_mean"] for x in s]))) diff --git a/code_src/rise_robomimic/robomimic/config/__init__.py b/code_src/rise_robomimic/robomimic/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eca0f01bcf18384c03273cefb3a3c6e993617ae3 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/config/__init__.py @@ -0,0 +1,16 @@ +from robomimic.config.config import Config +from robomimic.config.base_config import config_factory, get_all_registered_configs + +# note: these imports are needed to register these classes in the global config registry +from robomimic.config.bc_config import BCConfig +from robomimic.config.bcq_config import BCQConfig +from robomimic.config.cql_config import CQLConfig +from robomimic.config.iql_config import IQLConfig +from robomimic.config.gl_config import GLConfig +from robomimic.config.hbc_config import HBCConfig +from robomimic.config.iris_config import IRISConfig +from robomimic.config.td3_bc_config import TD3_BCConfig +from robomimic.config.idql_config import IDQLConfig +from robomimic.config.idql_qsm_config import IDQL_QSMConfig +from robomimic.config.iql_diffusion_config import IQLDiffusionConfig +from robomimic.config.discriminator_config import DiscriminatorConfig \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/config/base_config.py b/code_src/rise_robomimic/robomimic/config/base_config.py new file mode 100644 index 0000000000000000000000000000000000000000..5992146aacdb48bd35bee237981e8f8c7a6473c0 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/config/base_config.py @@ -0,0 +1,329 @@ +""" +The base config class that is used for all algorithm configs in this repository. +Subclasses get registered into a global dictionary, making it easy to instantiate +the correct config class given the algorithm name. +""" + +import six # preserve metaclass compatibility between python 2 and 3 +from copy import deepcopy + +import robomimic +from robomimic.config.config import Config + +# global dictionary for remembering name - class mappings +REGISTERED_CONFIGS = {} + + +def get_all_registered_configs(): + """ + Give access to dictionary of all registered configs for external use. + """ + return deepcopy(REGISTERED_CONFIGS) + + +def config_factory(algo_name, dic=None): + """ + Creates an instance of a config from the algo name. Optionally pass + a dictionary to instantiate the config from the dictionary. + """ + if algo_name not in REGISTERED_CONFIGS: + raise Exception("Config for algo name {} not found. Make sure it is a registered config among: {}".format( + algo_name, ', '.join(REGISTERED_CONFIGS))) + return REGISTERED_CONFIGS[algo_name](dict_to_load=dic) + + +class ConfigMeta(type): + """ + Define a metaclass for constructing a config class. + It registers configs into the global registry. + """ + def __new__(meta, name, bases, class_dict): + cls = super(ConfigMeta, meta).__new__(meta, name, bases, class_dict) + if cls.__name__ != "BaseConfig": + REGISTERED_CONFIGS[cls.ALGO_NAME] = cls + return cls + + +@six.add_metaclass(ConfigMeta) +class BaseConfig(Config): + def __init__(self, dict_to_load=None): + if dict_to_load is not None: + super(BaseConfig, self).__init__(dict_to_load) + return + + super(BaseConfig, self).__init__() + + # store algo name class property in the config (must be implemented by subclasses) + self.algo_name = type(self).ALGO_NAME + + self.experiment_config() + self.train_config() + self.algo_config() + self.observation_config() + self.meta_config() + + # After Config init, new keys cannot be added to the config, except under nested + # attributes that have called @do_not_lock_keys + self.lock_keys() + + @property + @classmethod + def ALGO_NAME(cls): + # must be specified by subclasses + raise NotImplementedError + + def experiment_config(self): + """ + This function populates the `config.experiment` attribute of the config, + which has several experiment settings such as the name of the training run, + whether to do logging, whether to save models (and how often), whether to render + videos, and whether to do rollouts (and how often). This class has a default + implementation that usually doesn't need to be overriden. + """ + + self.experiment.name = "test" # name of experiment used to make log files + self.experiment.validate = False # whether to do validation or not + self.experiment.logging.terminal_output_to_txt = True # whether to log stdout to txt file + self.experiment.logging.log_tb = True # enable tensorboard logging + self.experiment.logging.log_wandb = False # enable wandb logging + self.experiment.logging.wandb_proj_name = "debug" # project name if using wandb + + + ## save config - if and when to save model checkpoints ## + self.experiment.save.enabled = True # whether model saving should be enabled or disabled + self.experiment.save.every_n_seconds = None # save model every n seconds (set to None to disable) + self.experiment.save.every_n_epochs = 50 # save model every n epochs (set to None to disable) + self.experiment.save.epochs = [] # save model on these specific epochs + self.experiment.save.on_best_validation = False # save models that achieve best validation score + self.experiment.save.on_best_rollout_return = False # save models that achieve best rollout return + self.experiment.save.on_best_rollout_success_rate = True # save models that achieve best success rate + + # epoch definitions - if not None, set an epoch to be this many gradient steps, else the full dataset size will be used + self.experiment.epoch_every_n_steps = 100 # number of gradient steps in train epoch (None for full dataset pass) + self.experiment.validation_epoch_every_n_steps = 10 # number of gradient steps in valid epoch (None for full dataset pass) + + # envs to evaluate model on (assuming rollouts are enabled), to override the metadata stored in dataset + self.experiment.env = None # no need to set this (unless you want to override) + self.experiment.additional_envs = None # additional environments that should get evaluated + + + ## rendering config ## + self.experiment.render = False # render on-screen or not + self.experiment.render_video = True # render evaluation rollouts to videos + self.experiment.keep_all_videos = False # save all videos, instead of only saving those for saved model checkpoints + self.experiment.video_skip = 5 # render video frame every n environment steps during rollout + + + ## evaluation rollout config ## + self.experiment.rollout.enabled = True # enable evaluation rollouts + self.experiment.rollout.n = 50 # number of rollouts per evaluation + self.experiment.rollout.horizon = 400 # maximum number of env steps per rollout + self.experiment.rollout.rate = 50 # do rollouts every @rate epochs + self.experiment.rollout.warmstart = 0 # number of epochs to wait before starting rollouts + self.experiment.rollout.terminate_on_success = True # end rollout early after task success + + def train_config(self): + """ + This function populates the `config.train` attribute of the config, which + has several settings related to the training process, such as the dataset + to use for training, and how the data loader should load the data. This + class has a default implementation that usually doesn't need to be overriden. + """ + + # Path to hdf5 dataset to use for training + self.train.data = None + + # Write all results to this directory. A new folder with the timestamp will be created + # in this directory, and it will contain three subfolders - "log", "models", and "videos". + # The "log" directory will contain tensorboard and stdout txt logs. The "models" directory + # will contain saved model checkpoints. The "videos" directory contains evaluation rollout + # videos. + self.train.output_dir = "../{}_trained_models".format(self.algo_name) + + + ## dataset loader config ## + + # num workers for loading data - generally set to 0 for low-dim datasets, and 2 for image datasets + self.train.num_data_workers = 0 + + # One of ["all", "low_dim", or None]. Set to "all" to cache entire hdf5 in memory - this is + # by far the fastest for data loading. Set to "low_dim" to cache all non-image data. Set + # to None to use no caching - in this case, every batch sample is retrieved via file i/o. + # You should almost never set this to None, even for large image datasets. + self.train.hdf5_cache_mode = "all" + + # used for parallel data loading + self.train.hdf5_use_swmr = True + + # whether to load "next_obs" group from hdf5 - only needed for batch / offline RL algorithms + self.train.hdf5_load_next_obs = True + + # if true, normalize observations at train and test time, using the global mean and standard deviation + # of each observation in each dimension, computed across the training set. See SequenceDataset.normalize_obs + # in utils/dataset.py for more information. + self.train.hdf5_normalize_obs = False + + # if provided, use the list of demo keys under the hdf5 group "mask/@hdf5_filter_key" for training, instead + # of the full dataset. This provides a convenient way to train on only a subset of the trajectories in a dataset. + self.train.hdf5_filter_key = None + + # if provided, use the list of demo keys under the hdf5 group "mask/@hdf5_validation_filter_key" for validation. + # Must be provided if @experiment.validate is True. + self.train.hdf5_validation_filter_key = None + + # length of experience sequence to fetch from the dataset + # and whether to pad the beginning / end of the sequence at boundaries of trajectory in dataset + self.train.seq_length = 1 + self.train.pad_seq_length = True + self.train.frame_stack = 1 + self.train.pad_frame_stack = True + + # keys from hdf5 to load into each batch, besides "obs" and "next_obs". If algorithms + # require additional keys from each trajectory in the hdf5, they should be specified here. + self.train.dataset_keys = ( + "actions", + "rewards", + "dones", + ) + + # one of [None, "last"] - set to "last" to include goal observations in each batch + self.train.goal_mode = None + + self.train.augment_nearby_states = False + self.train.distance_threshold = 0.0 + self.train.num_neighbors = 10 + self.train.advanced_augmentation = False + self.train.augment_init_cutoff_thresh = 50 + self.train.augment_init_cutoff_thresh_expert = 20 + self.train.gripper_key = None + self.train.augment_play = True + self.train.mask_augmentation = False + self.train.proprio_keys = None + # rsm_rise gen_q#265 (actor sweep): expert:play sampling mixture. None = natural mixture (released + # behaviour, uniform over sequences); r = expert:play sequences drawn in the ratio r:1 in expectation + # (SequenceDataset.sequence_weights). Recorded in the run's config.json like every other train key. + self.train.expert_play_ratio = None + # rsm_rise gen_q#265 wave 2: True rewrites every demo's `dones` to 0 except the last frame (=1) at load + # time (SequenceDataset.get_dataset_for_ep). The released files carry the task-success flag as `dones` + # (threading: 1 over the last 3-14 frames of every expert demo; two_piece: no dones at all), which cuts + # a provenance critic's bootstrap short of the goal. False = released behaviour. + self.train.done_mode_terminal_only = False + + ## learning config ## + self.train.cuda = True # use GPU or not + self.train.batch_size = 100 # batch size + self.train.num_epochs = 2000 # number of training epochs + self.train.seed = 1 # seed for training (for reproducibility) + + def algo_config(self): + """ + This function populates the `config.algo` attribute of the config, and is given to the + `Algo` subclass (see `algo/algo.py`) for each algorithm through the `algo_config` + argument to the constructor. Any parameter that an algorithm needs to determine its + training and test-time behavior should be populated here. This function should be + implemented by every subclass. + """ + pass + + def observation_config(self): + """ + This function populates the `config.observation` attribute of the config, and is given + to the `Algo` subclass (see `algo/algo.py`) for each algorithm through the `obs_config` + argument to the constructor. This portion of the config is used to specify what + observation modalities should be used by the networks for training, and how the + observation modalities should be encoded by the networks. While this class has a + default implementation that usually doesn't need to be overriden, certain algorithm + configs may choose to, in order to have seperate configs for different networks + in the algorithm. + """ + + # observation modalities + self.observation.modalities.obs.low_dim = [ # specify low-dim observations for agent + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object", + ] + self.observation.modalities.obs.rgb = [] # specify rgb image observations for agent + self.observation.modalities.obs.depth = [] + self.observation.modalities.obs.scan = [] + self.observation.modalities.goal.low_dim = [] # specify low-dim goal observations to condition agent on + self.observation.modalities.goal.rgb = [] # specify rgb image goal observations to condition agent on + self.observation.modalities.goal.depth = [] + self.observation.modalities.goal.scan = [] + self.observation.modalities.obs.do_not_lock_keys() + self.observation.modalities.goal.do_not_lock_keys() + + # observation encoder architectures (per obs modality) + # This applies to all networks that take observation dicts as input + + # =============== Low Dim default encoder (no encoder) =============== + self.observation.encoder.low_dim.core_class = None + self.observation.encoder.low_dim.core_kwargs = Config() # No kwargs by default + self.observation.encoder.low_dim.core_kwargs.do_not_lock_keys() + + # Low Dim: Obs Randomizer settings + self.observation.encoder.low_dim.obs_randomizer_class = None + self.observation.encoder.low_dim.obs_randomizer_kwargs = Config() # No kwargs by default + self.observation.encoder.low_dim.obs_randomizer_kwargs.do_not_lock_keys() + + # =============== RGB default encoder (ResNet backbone + linear layer output) =============== + self.observation.encoder.rgb.core_class = "VisualCore" # Default VisualCore class combines backbone (like ResNet-18) with pooling operation (like spatial softmax) + self.observation.encoder.rgb.core_kwargs = Config() # See models/obs_core.py for important kwargs to set and defaults used + self.observation.encoder.rgb.core_kwargs.do_not_lock_keys() + + # RGB: Obs Randomizer settings + self.observation.encoder.rgb.obs_randomizer_class = None # Can set to 'CropRandomizer' to use crop randomization + self.observation.encoder.rgb.obs_randomizer_kwargs = Config() # See models/obs_core.py for important kwargs to set and defaults used + self.observation.encoder.rgb.obs_randomizer_kwargs.do_not_lock_keys() + + # Allow for other custom modalities to be specified + self.observation.encoder.do_not_lock_keys() + + # =============== Depth default encoder (same as rgb) =============== + self.observation.encoder.depth = deepcopy(self.observation.encoder.rgb) + + # =============== Scan default encoder (Conv1d backbone + linear layer output) =============== + self.observation.encoder.scan = deepcopy(self.observation.encoder.rgb) + + # Scan: Modify the core class + kwargs, otherwise, is same as rgb encoder + self.observation.encoder.scan.core_class = "ScanCore" # Default ScanCore class uses Conv1D to process this modality + self.observation.encoder.scan.core_kwargs = Config() # See models/obs_core.py for important kwargs to set and defaults used + self.observation.encoder.scan.core_kwargs.do_not_lock_keys() + + def meta_config(self): + """ + This function populates the `config.meta` attribute of the config. This portion of the config + is used to specify job information primarily for hyperparameter sweeps. + It contains hyperparameter keys and values, which are populated automatically + by the hyperparameter config generator (see `utils/hyperparam_utils.py`). + These values are read by the wandb logger (see `utils/log_utils.py`) to set job tags. + """ + + self.meta.hp_base_config_file = None # base config file in hyperparam sweep + self.meta.hp_keys = [] # relevant keys (swept) in hyperparam sweep + self.meta.hp_values = [] # values corresponding to keys in hyperparam sweep + + @property + def use_goals(self): + # whether the agent is goal-conditioned + return len([obs_key for modality in self.observation.modalities.goal.values() for obs_key in modality]) > 0 + + @property + def all_obs_keys(self): + """ + This grabs the union of observation keys over all modalities (e.g.: low_dim, rgb, depth, etc.) and over all + modality groups (e.g: obs, goal, subgoal, etc...) + + Returns: + n-array: all observation keys used for this model + """ + # pool all modalities + return sorted(tuple(set([ + obs_key for group in [ + self.observation.modalities.obs.values(), + self.observation.modalities.goal.values() + ] + for modality in group + for obs_key in modality + ]))) diff --git a/code_src/rise_robomimic/robomimic/config/bc_config.py b/code_src/rise_robomimic/robomimic/config/bc_config.py new file mode 100644 index 0000000000000000000000000000000000000000..1f701c685e9deb7755729d446ff272ba52a5ccc1 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/config/bc_config.py @@ -0,0 +1,106 @@ +""" +Config for BC algorithm. +""" + +from robomimic.config.base_config import BaseConfig + + +class BCConfig(BaseConfig): + ALGO_NAME = "bc" + + def train_config(self): + """ + BC algorithms don't need "next_obs" from hdf5 - so save on storage and compute by disabling it. + """ + super(BCConfig, self).train_config() + self.train.hdf5_load_next_obs = False + + def algo_config(self): + """ + This function populates the `config.algo` attribute of the config, and is given to the + `Algo` subclass (see `algo/algo.py`) for each algorithm through the `algo_config` + argument to the constructor. Any parameter that an algorithm needs to determine its + training and test-time behavior should be populated here. + """ + + # optimization parameters + self.algo.optim_params.policy.optimizer_type = "adam" + self.algo.optim_params.policy.learning_rate.initial = 1e-4 # policy learning rate + self.algo.optim_params.policy.learning_rate.decay_factor = 0.1 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.policy.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.policy.learning_rate.scheduler_type = "multistep" # learning rate scheduler ("multistep", "linear", etc) + self.algo.optim_params.policy.regularization.L2 = 0.00 # L2 regularization strength + + # loss weights + self.algo.loss.l2_weight = 1.0 # L2 loss weight + self.algo.loss.l1_weight = 0.0 # L1 loss weight + self.algo.loss.cos_weight = 0.0 # cosine loss weight + + # MLP network architecture (layers after observation encoder and RNN, if present) + self.algo.actor_layer_dims = (1024, 1024) + + # stochastic Gaussian policy settings + self.algo.gaussian.enabled = False # whether to train a Gaussian policy + self.algo.gaussian.fixed_std = False # whether to train std output or keep it constant + self.algo.gaussian.init_std = 0.1 # initial standard deviation (or constant) + self.algo.gaussian.min_std = 0.01 # minimum std output from network + self.algo.gaussian.std_activation = "softplus" # activation to use for std output from policy net + self.algo.gaussian.low_noise_eval = True # low-std at test-time + + # stochastic GMM policy settings + self.algo.gmm.enabled = False # whether to train a GMM policy + self.algo.gmm.num_modes = 5 # number of GMM modes + self.algo.gmm.min_std = 0.0001 # minimum std output from network + self.algo.gmm.std_activation = "softplus" # activation to use for std output from policy net + self.algo.gmm.low_noise_eval = True # low-std at test-time + + # stochastic VAE policy settings + self.algo.vae.enabled = False # whether to train a VAE policy + self.algo.vae.latent_dim = 14 # VAE latent dimnsion - set to twice the dimensionality of action space + self.algo.vae.latent_clip = None # clip latent space when decoding (set to None to disable) + self.algo.vae.kl_weight = 1. # beta-VAE weight to scale KL loss relative to reconstruction loss in ELBO + + # VAE decoder settings + self.algo.vae.decoder.is_conditioned = True # whether decoder should condition on observation + self.algo.vae.decoder.reconstruction_sum_across_elements = False # sum instead of mean for reconstruction loss + + # VAE prior settings + self.algo.vae.prior.learn = False # learn Gaussian / GMM prior instead of N(0, 1) + self.algo.vae.prior.is_conditioned = False # whether to condition prior on observations + self.algo.vae.prior.use_gmm = False # whether to use GMM prior + self.algo.vae.prior.gmm_num_modes = 10 # number of GMM modes + self.algo.vae.prior.gmm_learn_weights = False # whether to learn GMM weights + self.algo.vae.prior.use_categorical = False # whether to use categorical prior + self.algo.vae.prior.categorical_dim = 10 # the number of categorical classes for each latent dimension + self.algo.vae.prior.categorical_gumbel_softmax_hard = False # use hard selection in forward pass + self.algo.vae.prior.categorical_init_temp = 1.0 # initial gumbel-softmax temp + self.algo.vae.prior.categorical_temp_anneal_step = 0.001 # linear temp annealing rate + self.algo.vae.prior.categorical_min_temp = 0.3 # lowest gumbel-softmax temp + + self.algo.vae.encoder_layer_dims = (300, 400) # encoder MLP layer dimensions + self.algo.vae.decoder_layer_dims = (300, 400) # decoder MLP layer dimensions + self.algo.vae.prior_layer_dims = (300, 400) # prior MLP layer dimensions (if learning conditioned prior) + + # RNN policy settings + self.algo.rnn.enabled = False # whether to train RNN policy + self.algo.rnn.horizon = 10 # unroll length for RNN - should usually match train.seq_length + self.algo.rnn.hidden_dim = 400 # hidden dimension size + self.algo.rnn.rnn_type = "LSTM" # rnn type - one of "LSTM" or "GRU" + self.algo.rnn.num_layers = 2 # number of RNN layers that are stacked + self.algo.rnn.open_loop = False # if True, action predictions are only based on a single observation (not sequence) + self.algo.rnn.kwargs.bidirectional = False # rnn kwargs + self.algo.rnn.kwargs.do_not_lock_keys() + + # Transformer policy settings + self.algo.transformer.enabled = False # whether to train transformer policy + self.algo.transformer.context_length = 10 # length of (s, a) seqeunces to feed to transformer - should usually match train.frame_stack + self.algo.transformer.embed_dim = 512 # dimension for embeddings used by transformer + self.algo.transformer.num_layers = 6 # number of transformer blocks to stack + self.algo.transformer.num_heads = 8 # number of attention heads for each transformer block (should divide embed_dim evenly) + self.algo.transformer.emb_dropout = 0.1 # dropout probability for embedding inputs in transformer + self.algo.transformer.attn_dropout = 0.1 # dropout probability for attention outputs for each transformer block + self.algo.transformer.block_output_dropout = 0.1 # dropout probability for final outputs for each transformer block + self.algo.transformer.sinusoidal_embedding = False # if True, use standard positional encodings (sin/cos) + self.algo.transformer.activation = "gelu" # activation function for MLP in Transformer Block + self.algo.transformer.supervise_all_steps = False # if true, supervise all intermediate actions, otherwise only final one + self.algo.transformer.nn_parameter_for_timesteps = True # if true, use nn.Parameter otherwise use nn.Embedding diff --git a/code_src/rise_robomimic/robomimic/config/bcq_config.py b/code_src/rise_robomimic/robomimic/config/bcq_config.py new file mode 100644 index 0000000000000000000000000000000000000000..e28f5ba5668aa2e5e6d9ca2187953a4e05b56a7d --- /dev/null +++ b/code_src/rise_robomimic/robomimic/config/bcq_config.py @@ -0,0 +1,83 @@ +""" +Config for BCQ algorithm. +""" + +from robomimic.config.base_config import BaseConfig +from robomimic.config.bc_config import BCConfig + + +class BCQConfig(BaseConfig): + ALGO_NAME = "bcq" + + def algo_config(self): + """ + This function populates the `config.algo` attribute of the config, and is given to the + `Algo` subclass (see `algo/algo.py`) for each algorithm through the `algo_config` + argument to the constructor. Any parameter that an algorithm needs to determine its + training and test-time behavior should be populated here. + """ + + # optimization parameters + self.algo.optim_params.critic.learning_rate.initial = 1e-3 # critic learning rate + self.algo.optim_params.critic.learning_rate.decay_factor = 0.1 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.critic.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.critic.regularization.L2 = 0.00 # L2 regularization strength + self.algo.optim_params.critic.start_epoch = -1 # number of epochs before starting critic training (-1 means start right away) + self.algo.optim_params.critic.end_epoch = -1 # number of epochs before ending critic training (-1 means start right away) + + self.algo.optim_params.action_sampler.learning_rate.initial = 1e-3 # action sampler learning rate + self.algo.optim_params.action_sampler.learning_rate.decay_factor = 0.1 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.action_sampler.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.action_sampler.regularization.L2 = 0.00 # L2 regularization strength + self.algo.optim_params.action_sampler.start_epoch = -1 # number of epochs before starting action sampler training (-1 means start right away) + self.algo.optim_params.action_sampler.end_epoch = -1 # number of epochs before ending action sampler training (-1 means start right away) + + self.algo.optim_params.actor.learning_rate.initial = 1e-3 # actor learning rate + self.algo.optim_params.actor.learning_rate.decay_factor = 0.1 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.actor.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.actor.regularization.L2 = 0.00 # L2 regularization strength + self.algo.optim_params.actor.start_epoch = -1 # number of epochs before starting actor training (-1 means start right away) + self.algo.optim_params.actor.end_epoch = -1 # number of epochs before ending actor training (-1 means start right away) + + # target network related parameters + self.algo.discount = 0.99 # discount factor to use + self.algo.n_step = 1 # for using n-step returns in TD-updates + self.algo.target_tau = 0.005 # update rate for target networks + self.algo.infinite_horizon = False # if True, scale terminal rewards by 1 / (1 - discount) to treat as infinite horizon + + # ================== Critic Network Config =================== + self.algo.critic.use_huber = False # Huber Loss instead of L2 for critic + self.algo.critic.max_gradient_norm = None # L2 gradient clipping for critic (None to use no clipping) + self.algo.critic.value_bounds = None # optional 2-tuple to ensure lower and upper bound on value estimates + self.algo.critic.num_action_samples = 10 # number of actions to sample per training batch to get target critic value + self.algo.critic.num_action_samples_rollout = 100 # number of actions to sample per environment step + + # critic ensemble parameters (TD3 trick) + self.algo.critic.ensemble.n = 2 # number of Q networks in the ensemble + self.algo.critic.ensemble.weight = 0.75 # weighting for mixing min and max for target Q value + + # distributional critic + self.algo.critic.distributional.enabled = False # train distributional critic (C51) + self.algo.critic.distributional.num_atoms = 51 # number of values in categorical distribution + + self.algo.critic.layer_dims = (300, 400) # size of critic MLP + + # ================== Action Sampler Config =================== + self.algo.action_sampler = BCConfig().algo + # use VAE by default + self.algo.action_sampler.vae.enabled = True + # remove unused parts of BCConfig algo config + del self.algo.action_sampler.optim_params # since action sampler optim params specified at top-level + del self.algo.action_sampler.loss + del self.algo.action_sampler.gaussian + del self.algo.action_sampler.rnn + del self.algo.action_sampler.transformer + + # Number of epochs before freezing encoder (-1 for no freezing). Only applies to cVAE-based action samplers. + with self.algo.action_sampler.unlocked(): + self.algo.action_sampler.freeze_encoder_epoch = -1 + + # ================== Actor Network Config =================== + self.algo.actor.enabled = False # whether to use the actor perturbation network + self.algo.actor.perturbation_scale = 0.05 # size of learned action perturbations + self.algo.actor.layer_dims = (300, 400) # size of actor MLP diff --git a/code_src/rise_robomimic/robomimic/config/config.py b/code_src/rise_robomimic/robomimic/config/config.py new file mode 100644 index 0000000000000000000000000000000000000000..74da6535b385f91aa5c34e20af731ba2e3d06ecb --- /dev/null +++ b/code_src/rise_robomimic/robomimic/config/config.py @@ -0,0 +1,322 @@ +""" +Basic config class - provides a convenient way to work with nested +dictionaries (by exposing keys as attributes) and to save / load from jsons. + +Based on addict: https://github.com/mewwts/addict +""" + +import json +import copy +import contextlib +from copy import deepcopy + + +class Config(dict): + + def __init__(__self, *args, **kwargs): + object.__setattr__(__self, '__key_locked', False) # disallow adding new keys + object.__setattr__(__self, '__all_locked', False) # disallow both key and value update + object.__setattr__(__self, '__do_not_lock_keys', False) # cannot be key-locked + object.__setattr__(__self, '__parent', kwargs.pop('__parent', None)) + object.__setattr__(__self, '__key', kwargs.pop('__key', None)) + for arg in args: + if not arg: + continue + elif isinstance(arg, dict): + for key, val in arg.items(): + __self[key] = __self._hook(val) + elif isinstance(arg, tuple) and (not isinstance(arg[0], tuple)): + __self[arg[0]] = __self._hook(arg[1]) + else: + for key, val in iter(arg): + __self[key] = __self._hook(val) + + for key, val in kwargs.items(): + __self[key] = __self._hook(val) + + def lock(self): + """ + Lock the config. Afterwards, new keys cannot be added to the + config, and the values of existing keys cannot be modified. + """ + object.__setattr__(self, '__all_locked', True) + if self.key_lockable: + object.__setattr__(self, '__key_locked', True) + + for k in self: + if isinstance(self[k], Config): + self[k].lock() + + def unlock(self): + """ + Unlock the config. Afterwards, new keys can be added to the + config, and the values of existing keys can be modified. + """ + object.__setattr__(self, '__all_locked', False) + object.__setattr__(self, '__key_locked', False) + + for k in self: + if isinstance(self[k], Config): + self[k].unlock() + + def _get_lock_state_recursive(self): + """ + Internal helper function to get the lock state of all sub-configs recursively. + """ + lock_state = {"__all_locked": self.is_locked, "__key_locked": self.is_key_locked} + for k in self: + if isinstance(self[k], Config): + assert k not in ["__all_locked", "__key_locked"] + lock_state[k] = self[k]._get_lock_state_recursive() + return lock_state + + def _set_lock_state_recursive(self, lock_state): + """ + Internal helper function to set the lock state of all sub-configs recursively. + """ + lock_state = deepcopy(lock_state) + object.__setattr__(self, '__all_locked', lock_state.pop("__all_locked")) + object.__setattr__(self, '__key_locked', lock_state.pop("__key_locked")) + for k in lock_state: + if isinstance(self[k], Config): + self[k]._set_lock_state_recursive(lock_state[k]) + + def _get_lock_state(self): + """ + Retrieves the lock state of this config. + + Returns: + lock_state (dict): a dictionary with an "all_locked" key that is True + if both key and value updates are locked and False otherwise, and + a "key_locked" key that is True if only key updates are locked (value + updates still allowed) and False otherwise + """ + return { + "all_locked": self.is_locked, + "key_locked": self.is_key_locked + } + + def _set_lock_state(self, lock_state): + """ + Sets the lock state for this config. + + Args: + lock_state (dict): a dictionary with an "all_locked" key that is True + if both key and value updates should be locked and False otherwise, and + a "key_locked" key that is True if only key updates should be locked (value + updates still allowed) and False otherwise + """ + if lock_state["all_locked"]: + self.lock() + if lock_state["key_locked"]: + self.lock_keys() + + @contextlib.contextmanager + def unlocked(self): + """ + A context scope for modifying a Config object. Within the scope, + both keys and values can be updated. Upon leaving the scope, + the initial level of locking is restored. + """ + lock_state = self._get_lock_state() + self.unlock() + yield + self._set_lock_state(lock_state) + + @contextlib.contextmanager + def values_unlocked(self): + """ + A context scope for modifying a Config object. Within the scope, + only values can be updated (new keys cannot be created). Upon + leaving the scope, the initial level of locking is restored. + """ + lock_state = self._get_lock_state() + self.unlock() + self.lock_keys() + yield + self._set_lock_state(lock_state) + + def lock_keys(self): + """ + Lock this config so that new keys cannot be added. + """ + if not self.key_lockable: + return + object.__setattr__(self, '__key_locked', True) + for k in self: + if isinstance(self[k], Config): + self[k].lock_keys() + + def unlock_keys(self): + """ + Unlock this config so that new keys can be added. + """ + object.__setattr__(self, '__key_locked', False) + for k in self: + if isinstance(self[k], Config): + self[k].unlock_keys() + + @property + def is_locked(self): + """ + Returns True if the config is locked (no key or value updates allowed). + """ + return object.__getattribute__(self, '__all_locked') + + @property + def is_key_locked(self): + """ + Returns True if the config is key-locked (no key updates allowed). + """ + return object.__getattribute__(self, '__key_locked') + + def do_not_lock_keys(self): + """ + Calling this function on this config indicates that key updates should be + allowed even when this config is key-locked (but not when it is completely + locked). This is convenient for attributes that contain kwargs, where there + might be a variable type and number of arguments contained in the sub-config. + """ + object.__setattr__(self, '__do_not_lock_keys', True) + + @property + def key_lockable(self): + """ + Returns true if this config is key-lockable (new keys cannot be inserted in a + key-locked lock level). + """ + return not object.__getattribute__(self, '__do_not_lock_keys') + + def __setattr__(self, name, value): + if self.is_locked: + raise RuntimeError("This config has been locked - cannot set attribute '{}' to {}".format(name, value)) + + if hasattr(Config, name): + raise AttributeError("'Dict' object attribute " + "'{0}' is read-only".format(name)) + elif not hasattr(self, name) and self.is_key_locked: + raise RuntimeError("This config is key-locked - cannot add key '{}'".format(name)) + else: + self[name] = value + + def __setitem__(self, name, value): + super(Config, self).__setitem__(name, value) + p = object.__getattribute__(self, '__parent') + key = object.__getattribute__(self, '__key') + if p is not None: + p[key] = self + + def __add__(self, other): + if not self.keys(): + return other + else: + self_type = type(self).__name__ + other_type = type(other).__name__ + msg = "unsupported operand type(s) for +: '{}' and '{}'" + raise TypeError(msg.format(self_type, other_type)) + + @classmethod + def _hook(cls, item): + if isinstance(item, dict): + # We return Config instance instead of cls instance to ensure all sub-configs are not a top-level class + return Config(item) + elif isinstance(item, (list, tuple)): + return type(item)(Config._hook(elem) for elem in item) + return item + + def __getattr__(self, item): + return self.__getitem__(item) + + def __repr__(self): + json_string = json.dumps(self.to_dict(), indent=4) + return json_string + + def __getitem__(self, name): + if name not in self: + if object.__getattribute__(self, '__all_locked') or object.__getattribute__(self, '__key_locked'): + raise RuntimeError("This config has been locked and '{}' is not in this config".format(name)) + return Config(__parent=self, __key=name) + return super(Config, self).__getitem__(name) + + def __delattr__(self, name): + del self[name] + + def to_dict(self): + base = {} + for key, value in self.items(): + if isinstance(value, type(self)): + base[key] = value.to_dict() + elif isinstance(value, (list, tuple)): + base[key] = type(value)( + item.to_dict() if isinstance(item, type(self)) else + item for item in value) + else: + base[key] = value + return base + + def copy(self): + return copy.copy(self) + + def deepcopy(self): + return copy.deepcopy(self) + + def __deepcopy__(self, memo): + other = self.__class__() + memo[id(self)] = other + for key, value in self.items(): + other[copy.deepcopy(key, memo)] = copy.deepcopy(value, memo) + return other + + def update(self, *args, **kwargs): + """ + Update this config using another config or nested dictionary. + """ + if self.is_locked: + raise RuntimeError('Cannot update - this config has been locked') + other = {} + if args: + if len(args) > 1: + raise TypeError() + other.update(args[0]) + other.update(kwargs) + for k, v in other.items(): + if self.is_key_locked and k not in self: + raise RuntimeError("Cannot update - this config has been key-locked and key '{}' does not exist".format(k)) + if (not isinstance(self[k], dict)) or (not isinstance(v, dict)): + self[k] = v + else: + self[k].update(v) + + def __getnewargs__(self): + return tuple(self.items()) + + def __getstate__(self): + return self + + def __setstate__(self, state): + self.update(state) + + def setdefault(self, key, default=None): + if key in self: + return self[key] + else: + self[key] = default + return default + + def dump(self, filename=None): + """ + Dumps the config to a json. + + Args: + filename (str): if not None, save to json file. + + Returns: + json_string (str): json string representation of + this config + """ + json_string = json.dumps(self.to_dict(), indent=4) + if filename is not None: + f = open(filename, "w") + f.write(json_string) + f.close() + return json_string \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/config/cql_config.py b/code_src/rise_robomimic/robomimic/config/cql_config.py new file mode 100644 index 0000000000000000000000000000000000000000..26fea048fe49d2d2d03f888eedab6754f37c8dcc --- /dev/null +++ b/code_src/rise_robomimic/robomimic/config/cql_config.py @@ -0,0 +1,82 @@ +""" +Config for CQL algorithm. +""" + +from robomimic.config.base_config import BaseConfig + + +class CQLConfig(BaseConfig): + ALGO_NAME = "cql" + + def train_config(self): + """ + Update from superclass to change default batch size. + """ + super(CQLConfig, self).train_config() + + # increase batch size to 1024 (found to work better for most manipulation experiments) + self.train.batch_size = 1024 + + def algo_config(self): + """ + This function populates the `config.algo` attribute of the config, and is given to the + `Algo` subclass (see `algo/algo.py`) for each algorithm through the `algo_config` + argument to the constructor. Any parameter that an algorithm needs to determine its + training and test-time behavior should be populated here. + """ + + # optimization parameters + self.algo.optim_params.critic.learning_rate.initial = 1e-3 # critic learning rate + self.algo.optim_params.critic.learning_rate.decay_factor = 0.0 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.critic.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.critic.regularization.L2 = 0.00 # L2 regularization strength + + self.algo.optim_params.actor.learning_rate.initial = 3e-4 # actor learning rate + self.algo.optim_params.actor.learning_rate.decay_factor = 0.0 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.actor.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.actor.regularization.L2 = 0.00 # L2 regularization strength + + # target network related parameters + self.algo.discount = 0.99 # discount factor to use + self.algo.n_step = 1 # for using n-step returns in TD-updates + self.algo.target_tau = 0.005 # update rate for target networks + + # ================== Actor Network Config =================== + self.algo.actor.bc_start_steps = 0 # uses BC policy loss for first n-training steps + self.algo.actor.target_entropy = "default" # None is fixed entropy, otherwise is automatically tuned to match target. Can specify "default" as well for default tuning target + self.algo.actor.max_gradient_norm = None # L2 gradient clipping for actor + + # Actor network settings + self.algo.actor.net.type = "gaussian" # Options are currently only "gaussian" (no support for GMM yet) + + # Actor network settings - shared + self.algo.actor.net.common.std_activation = "exp" # Activation to use for std output from policy net + self.algo.actor.net.common.use_tanh = True # Whether to use tanh at output of actor network + self.algo.actor.net.common.low_noise_eval = True # Whether to use deterministic action sampling at eval stage + + # Actor network settings - gaussian + self.algo.actor.net.gaussian.init_last_fc_weight = 0.001 # If set, will override the initialization of the final fc layer to be uniformly sampled limited by this value + self.algo.actor.net.gaussian.init_std = 0.3 # Relative scaling factor for std from policy net + self.algo.actor.net.gaussian.fixed_std = False # Whether to learn std dev or not + + self.algo.actor.layer_dims = (300, 400) # actor MLP layer dimensions + + # ================== Critic Network Config =================== + self.algo.critic.use_huber = False # Huber Loss instead of L2 for critic + self.algo.critic.max_gradient_norm = None # L2 gradient clipping for critic (None to use no clipping) + + self.algo.critic.value_bounds = None # optional 2-tuple to ensure lower and upper bound on value estimates + + self.algo.critic.num_action_samples = 1 # number of actions to sample per training batch to get target critic value; use maximum Q value from n random sampled actions when doing TD error backup + + # cql settings for critic + self.algo.critic.cql_weight = 1.0 # weighting for cql component of critic loss (only used if target_q_gap is < 0 or None) + self.algo.critic.deterministic_backup = True # if not set, subtract weighted logprob of action when doing backup + self.algo.critic.min_q_weight = 1.0 # min q weight (scaling factor) to apply + self.algo.critic.target_q_gap = 5.0 # if set, sets the diff threshold at which Q-values will be penalized more (note: this overrides cql weight above!) Use None or a negative value if not set + self.algo.critic.num_random_actions = 10 # Number of random actions to sample when calculating CQL loss + + # critic ensemble parameters (TD3 trick) + self.algo.critic.ensemble.n = 2 # number of Q networks in the ensemble + + self.algo.critic.layer_dims = (300, 400) # critic MLP layer dimensions diff --git a/code_src/rise_robomimic/robomimic/config/default_templates/bc_transformer.json b/code_src/rise_robomimic/robomimic/config/default_templates/bc_transformer.json new file mode 100644 index 0000000000000000000000000000000000000000..ed59f175b532c1cd61e8c4efefba1d985e8eaa31 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/config/default_templates/bc_transformer.json @@ -0,0 +1,171 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "test", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": null, + "output_dir": "../bc_transformer_trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 10, + "pad_frame_stack": true, + "dataset_keys": [ + "actions" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adamw", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [100], + "scheduler_type": "linear" + }, + "regularization": { + "L2": 0.01 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false + }, + "rnn": { + "enabled": false + }, + "transformer": { + "enabled": true, + "supervise_all_steps": false, + "num_layers": 6, + "embed_dim": 512, + "num_heads": 8 + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } +} diff --git a/code_src/rise_robomimic/robomimic/config/discriminator_config.py b/code_src/rise_robomimic/robomimic/config/discriminator_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f65c3d3ac61f26a0cce6b2303f87c222f269befa --- /dev/null +++ b/code_src/rise_robomimic/robomimic/config/discriminator_config.py @@ -0,0 +1,45 @@ +""" +Config for Discriminator algorithm. +""" + +from robomimic.config.base_config import BaseConfig + + +class DiscriminatorConfig(BaseConfig): + ALGO_NAME = "discriminator" + + def experiment_config(self): + super().experiment_config() + + self.experiment.save.every_n_epochs = 2 # save model every n epochs (set to None to disable) + + def train_config(self): + """ + BC algorithms don't need "next_obs" from hdf5 - so save on storage and compute by disabling it. + """ + super(DiscriminatorConfig, self).train_config() + self.train.hdf5_load_next_obs = False + + def algo_config(self): + """ + This function populates the `config.algo` attribute of the config, and is given to the + `Algo` subclass (see `algo/algo.py`) for each algorithm through the `algo_config` + argument to the constructor. Any parameter that an algorithm needs to determine its + training and test-time behavior should be populated here. + """ + + # optimization parameters + self.algo.optim_params.policy.optimizer_type = "adam" + self.algo.optim_params.policy.learning_rate.initial = 1e-4 # policy learning rate + self.algo.optim_params.policy.learning_rate.decay_factor = 0.1 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.policy.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.policy.learning_rate.scheduler_type = "multistep" # learning rate scheduler ("multistep", "linear", etc) + self.algo.optim_params.policy.regularization.L2 = 0.00 # L2 regularization strength + + # loss weights + self.algo.loss.l2_weight = 1.0 # L2 loss weight + self.algo.loss.l1_weight = 0.0 # L1 loss weight + self.algo.loss.cos_weight = 0.0 # cosine loss weight + + # MLP network architecture (layers after observation encoder and RNN, if present) + self.algo.discriminator_layer_dims = (1024, 1024) \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/config/gl_config.py b/code_src/rise_robomimic/robomimic/config/gl_config.py new file mode 100644 index 0000000000000000000000000000000000000000..939103e65dd5f7519fb7be2c9fa1928d5b430bf2 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/config/gl_config.py @@ -0,0 +1,89 @@ +""" +Config for Goal Learning (sub-algorithm used by hierarchical models like HBC and IRIS). +This class of model predicts (or samples) subgoal observations given a current observation. +""" + +from robomimic.config.base_config import BaseConfig + + +class GLConfig(BaseConfig): + ALGO_NAME = "gl" + + def algo_config(self): + """ + This function populates the `config.algo` attribute of the config, and is given to the + `Algo` subclass (see `algo/algo.py`) for each algorithm through the `algo_config` + argument to the constructor. Any parameter that an algorithm needs to determine its + training and test-time behavior should be populated here. + """ + + # optimization parameters + self.algo.optim_params.goal_network.learning_rate.initial = 1e-4 # goal network learning rate + self.algo.optim_params.goal_network.learning_rate.decay_factor = 0.1 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.goal_network.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.goal_network.regularization.L2 = 0.00 + + # subgoal definition: observation that is @subgoal_horizon number of timesteps in future from current observation + self.algo.subgoal_horizon = 10 + + # MLP size for deterministic goal network (unused if VAE is enabled) + self.algo.ae.planner_layer_dims = (300, 400) + + # ================== VAE config ================== + self.algo.vae.enabled = True # set to true to use VAE network + self.algo.vae.latent_dim = 16 # VAE latent dimension + self.algo.vae.latent_clip = None # clip latent space when decoding (set to None to disable) + self.algo.vae.kl_weight = 1. # beta-VAE weight to scale KL loss relative to reconstruction loss in ELBO + + # VAE decoder settings + self.algo.vae.decoder.is_conditioned = True # whether decoder should condition on observation + self.algo.vae.decoder.reconstruction_sum_across_elements = False # sum instead of mean for reconstruction loss + + # VAE prior settings + self.algo.vae.prior.learn = False # learn Gaussian / GMM prior instead of N(0, 1) + self.algo.vae.prior.is_conditioned = False # whether to condition prior on observations + self.algo.vae.prior.use_gmm = False # whether to use GMM prior + self.algo.vae.prior.gmm_num_modes = 10 # number of GMM modes + self.algo.vae.prior.gmm_learn_weights = False # whether to learn GMM weights + self.algo.vae.prior.use_categorical = False # whether to use categorical prior + self.algo.vae.prior.categorical_dim = 10 # the number of categorical classes for each latent dimension + self.algo.vae.prior.categorical_gumbel_softmax_hard = False # use hard selection in forward pass + self.algo.vae.prior.categorical_init_temp = 1.0 # initial gumbel-softmax temp + self.algo.vae.prior.categorical_temp_anneal_step = 0.001 # linear temp annealing rate + self.algo.vae.prior.categorical_min_temp = 0.3 # lowest gumbel-softmax temp + + self.algo.vae.encoder_layer_dims = (300, 400) # encoder MLP layer dimensions + self.algo.vae.decoder_layer_dims = (300, 400) # decoder MLP layer dimensions + self.algo.vae.prior_layer_dims = (300, 400) # prior MLP layer dimensions (if learning conditioned prior) + + def observation_config(self): + """ + Update from superclass to specify subgoal modalities. + """ + super(GLConfig, self).observation_config() + self.observation.modalities.subgoal.low_dim = [ # specify low-dim subgoal observations for agent to predict + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object", + ] + self.observation.modalities.subgoal.rgb = [] # specify rgb image subgoal observations for agent to predict + self.observation.modalities.subgoal.depth = [] + self.observation.modalities.subgoal.scan = [] + self.observation.modalities.subgoal.do_not_lock_keys() + + @property + def all_obs_keys(self): + """ + Update from superclass to include subgoals. + """ + # pool all modalities + return sorted(tuple(set([ + obs_key for group in [ + self.observation.modalities.obs.values(), + self.observation.modalities.goal.values(), + self.observation.modalities.subgoal.values(), + ] + for modality in group + for obs_key in modality + ]))) diff --git a/code_src/rise_robomimic/robomimic/config/hbc_config.py b/code_src/rise_robomimic/robomimic/config/hbc_config.py new file mode 100644 index 0000000000000000000000000000000000000000..ae65c9b85fc168dc65666392fd334810b622ab04 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/config/hbc_config.py @@ -0,0 +1,96 @@ +""" +Config for HBC algorithm. +""" + +from robomimic.config.base_config import BaseConfig +from robomimic.config.gl_config import GLConfig +from robomimic.config.bc_config import BCConfig + + +class HBCConfig(BaseConfig): + ALGO_NAME = "hbc" + + def train_config(self): + """ + Update from superclass to change default sequence length to load from dataset. + """ + super(HBCConfig, self).train_config() + self.train.seq_length = 10 # length of experience sequence to fetch from the buffer + + def algo_config(self): + """ + This function populates the `config.algo` attribute of the config, and is given to the + `Algo` subclass (see `algo/algo.py`) for each algorithm through the `algo_config` + argument to the constructor. Any parameter that an algorithm needs to determine its + training and test-time behavior should be populated here. + """ + + # One of ["separate", "cascade"]. In "separate" mode (default), + # the planner and actor are trained independently and then the planner subgoal predictions are + # used to condition the actor at test-time. In "cascade" mode, the actor is trained directly + # on planner subgoal predictions. In "actor_only" mode, only the actor is trained, and in + # "planner_only" mode, only the planner is trained. + self.algo.mode = "separate" + self.algo.actor_use_random_subgoals = False # whether to sample subgoal index from [1, subgoal_horizon] + self.algo.subgoal_update_interval = 10 # how frequently the subgoal should be updated at test-time + + + # ================== Latent Subgoal Config ================== + self.algo.latent_subgoal.enabled = False # if True, use VAE latent space as subgoals for actor, instead of reconstructions + + # prior correction trick for actor and value training: instead of using encoder for + # transforming subgoals to latent subgoals, generate prior samples and choose + # the closest one to the encoder output + self.algo.latent_subgoal.prior_correction.enabled = False + self.algo.latent_subgoal.prior_correction.num_samples = 100 + + # ================== Planner Config ================== + self.algo.planner = GLConfig().algo # config for goal learning + # set subgoal horizon explicitly + self.algo.planner.subgoal_horizon = 10 + # ensure VAE is used + self.algo.planner.vae.enabled = True + + # ================== Actor Config =================== + self.algo.actor = BCConfig().algo + # use RNN + self.algo.actor.rnn.enabled = True + self.algo.actor.rnn.horizon = 10 + # remove unused parts of BCConfig algo config + del self.algo.actor.gaussian + del self.algo.actor.gmm + del self.algo.actor.vae + + def observation_config(self): + """ + Update from superclass so that planner and actor each get their own observation config. + """ + self.observation.planner = GLConfig().observation + self.observation.actor = BCConfig().observation + + @property + def use_goals(self): + """ + Update from superclass - planner goal modalities determine goal-conditioning + """ + return len( + self.observation.planner.modalities.goal.low_dim + + self.observation.planner.modalities.goal.rgb) > 0 + + @property + def all_obs_keys(self): + """ + Update from superclass to include modalities from planner and actor. + """ + # pool all modalities + return sorted(tuple(set([ + obs_key for group in [ + self.observation.planner.modalities.obs.values(), + self.observation.planner.modalities.goal.values(), + self.observation.planner.modalities.subgoal.values(), + self.observation.actor.modalities.obs.values(), + self.observation.actor.modalities.goal.values(), + ] + for modality in group + for obs_key in modality + ]))) diff --git a/code_src/rise_robomimic/robomimic/config/idql_config.py b/code_src/rise_robomimic/robomimic/config/idql_config.py new file mode 100644 index 0000000000000000000000000000000000000000..3345492dcaaeecf08d4ea78b42087cea495a6039 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/config/idql_config.py @@ -0,0 +1,178 @@ +""" +Config for IQL Diffusion algorithm. +""" + +from robomimic.config.base_config import BaseConfig + + +class IDQLConfig(BaseConfig): + ALGO_NAME = "idql" + + def algo_config(self): + """ + This function populates the `config.algo` attribute of the config, and is given to the + `Algo` subclass (see `algo/algo.py`) for each algorithm through the `algo_config` + argument to the constructor. Any parameter that an algorithm needs to determine its + training and test-time behavior should be populated here. + """ + super(IDQLConfig, self).algo_config() + + # optimization parameters + self.algo.optim_params.critic.learning_rate.initial = 1e-4 # critic learning rate + self.algo.optim_params.critic.learning_rate.decay_factor = 0.0 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.critic.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.critic.regularization.L2 = 0.00 # L2 regularization strength + + self.algo.optim_params.vf.learning_rate.initial = 1e-4 # vf learning rate + self.algo.optim_params.vf.learning_rate.decay_factor = 0.0 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.vf.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.vf.regularization.L2 = 0.00 # L2 regularization strength + + self.algo.optim_params.policy.learning_rate.initial = 1e-4 # policy learning rate + self.algo.optim_params.policy.learning_rate.decay_factor = 0.0 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.policy.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.policy.regularization.L2 = 0.00 # L2 regularization strength + self.algo.optim_params.policy.freeze_until_epoch = None # don't train policy until this epoch + + self.algo.multi_step_method = 'one_step' + self.algo.use_bc = False + + # unet params + self.algo.unet.enabled = True + self.algo.unet.diffusion_step_embed_dim = 256 + self.algo.unet.down_dims = [256,512,1024] + self.algo.unet.kernel_size = 5 + self.algo.unet.n_groups = 8 + + # EMA parameters + self.algo.ema.enabled = True + self.algo.ema.power = 0.75 + + self.algo.horizon.observation_horizon = 1 + self.algo.horizon.action_horizon = 1 + self.algo.horizon.prediction_horizon = 1 + + # Noise Scheduler + ## DDPM + self.algo.ddpm.enabled = True + self.algo.ddpm.num_train_timesteps = 100 + self.algo.ddpm.num_inference_timesteps = 100 + self.algo.ddpm.beta_schedule = 'squaredcos_cap_v2' + self.algo.ddpm.clip_sample = True + self.algo.ddpm.prediction_type = 'epsilon' + + ## DDIM + self.algo.ddim.enabled = False + self.algo.ddim.num_train_timesteps = 100 + self.algo.ddim.num_inference_timesteps = 10 + self.algo.ddim.beta_schedule = 'squaredcos_cap_v2' + self.algo.ddim.clip_sample = True + self.algo.ddim.set_alpha_to_one = True + self.algo.ddim.steps_offset = 0 + self.algo.ddim.prediction_type = 'epsilon' + + # target network related parameters + self.algo.discount = 0.99 # discount factor to use + self.algo.target_tau = 0.01 # update rate for target networks + + # ================== Critic Network Config =================== + # critic ensemble parameters + self.algo.critic.ensemble.n = 2 # number of Q networks in the ensemble + self.algo.critic.layer_dims = (300, 400) # critic MLP layer dimensions + self.algo.critic.use_huber = False # Huber Loss instead of L2 for critic + self.algo.critic.max_gradient_norm = None # L2 gradient clipping for actor + + # ================== Adv Config ============================== + self.algo.adv.clip_adv_value = None # whether to clip raw advantage estimates + self.algo.adv.beta = 1.0 # temperature for operator + self.algo.adv.use_final_clip = True # whether to clip final weight calculations + self.algo.awr_actor = False + self.algo.critic_on_augmented = False # rsm_rise gen_q#265 wave 2: opt-in critic/V update on kNN-augmented rows (released: skipped) # rsm_rise gen_q#265: opt-in AWR actor loss (released: plain BC) + + # ---- rsm_rise BASE_TOPUP (gen_q#287) FAST CRITIC PATH, 2026-09-26 ----------------------------- + # The flagship's `critic:dino` column needs ONLY the IQL critic: the action proposer is the fixed + # published PIXEL actor loaded from a different checkpoint, so the diffusion actor co-trained in + # this run is never read by any cell. `critic_only=True` skips the actor loss AND its update + # (the expensive half of a step) and leaves Q/V bit-for-bit as they were: _compute_critic_loss / + # _update_critic (idql.py) never read the actor, and the actor's advantage weights are .detach()ed, + # so removing the actor cannot change a single critic gradient. + self.algo.critic_only = False + # `critic_skip_even_epochs=True` reproduces the RELEASED critic update SCHEDULE on a run whose + # kNN action augmentation is OFF. With augmentation ON the released recipe alternates epochs and + # `critic_skip = using_augmented and not critic_on_augmented` (idql.py) means the critic updates on + # the ODD epochs only -- 2500 of 5000 epochs x 100 steps = 250k critic updates. A precomputed-feature + # (path-(D)) run cannot build the augmentation pool (its distance space is images), so augmentation + # must be off; without this flag the critic would get 500k updates, i.e. TWICE the released recipe, + # under a name claiming to reproduce it. With it, the update count matches exactly AND the + # checkpoint still lands at epoch 5000, which the table loader requires (critic epoch == proposer + # epoch, verdict_table.py). + self.algo.critic_skip_even_epochs = False + + self.algo.vf_quantile = 0.9 # quantile factor in quantile regression + + self.algo.bottleneck_policy = False + self.algo.bottleneck_value = False + self.algo.q_bottleneck_beta = 0.2 + self.algo.policy_bottleneck_beta = 0.2 + self.algo.spectral_norm_policy = False + self.algo.spectral_norm_value = False + + self.algo.lipschitz = False + self.algo.lipschitz_constant = 3.0 + self.algo.lipschitz_weight = 0.005 + self.algo.lipschitz_slack = False + self.algo.lipschitz_denoiser = False + + # rsm_rise Stage 3 (robomimic/algo/rsm_planner.py, rsm_scorer.py). Defaults = released behaviour. + self.algo.plan_n = None # best-of-N over the diffusion sampler; None/1 = released path + self.algo.plan_rule = "argmax" # argmax | softmax | topk_uniform | random | permuted | argmin + self.algo.plan_temp = 0.2 # softmax temperature on Qbar + self.algo.plan_topk = 8 # topk_uniform: k + self.algo.plan_chunk = 8 # actions of the executed window the RSM scores + self.algo.plan_particles = 16 # successor particles per candidate + self.algo.plan_mode = "fold" # d1 | fold | recursive + self.algo.plan_depth = 2 # hops L + self.algo.plan_beta = 0.95 # hop beta + self.algo.plan_gamma = 0.99 # fold discount / recursion restart gamma + # gen_q#273 added plan_mpc_horizon to sim_pipeline's PLANNER_KEYS (iql_diffusion.py:147), which + # copies it into json_config['algo'], but the key was never declared here -- so config_factory's + # key-locked config rejected it and EVERY new idql / iql_diffusion training died at startup in + # ~23 s with "Cannot update ... key 'plan_mpc_horizon' does not exist" (REWARD_MATRIX jobs + # 1885210/1885211, all 8 cells). Declared here with the SAME default as the training-side field + # (0 = off), so this restores released behaviour and changes nothing for any existing cell. + self.algo.plan_mpc_horizon = 0 # world-model MPC horizon H in FRAMES (0 = off) + self.algo.plan_flow_steps = 8 # Euler steps of the successor ODE + self.algo.plan_seed = -1 # >=0: fixed CRN seed per step and selection RNG + self.algo.rsm_backend = "mlp" # mlp | dwm | mc | iql + self.algo.rsm_ckpt = "" # RSM checkpoint (iql: an S0A .pth or "" for own critic) + self.algo.rsm_hop_ckpt = "" # Stage-2 hop head (bc_arm.py policy_r1.pt) + self.algo.rsm_feat_stats = "" # Stage-1 cache feat_stats.npz + self.algo.rsm_img_layout = "chw" # chw (scripts/relabel_dino.py) | rise_t (RISE offline relabel) + self.algo.rsm_dwm_module = "dwm_readout" + self.algo.plan_score = "prob" # prob (mean sigmoid, released) | logit (mean raw logit over particles) + # | prob_log (prob folded in log space: same quantity, total order) + self.algo.plan_rescore_top = 0 # two-stage screening: rescore the top-K of the ranking (0 = off) + self.algo.plan_particles_rescore = 0 # ... with M particles (0 = off) + self.algo.plan_temperature = 0.0 # 0: checkpoint calib.json T (else 1.0); > 0 overrides the sigmoid T + self.algo.plan_lcb_quantile = 0.1 # plan_score=conformal_lcb: particle quantile that ranks (0.1 = 10th pct) + self.algo.plan_sample_batch = 0 # >0: DDPM-sample the candidates in slices of this many rows (0 = off) + self.algo.plan_max_rows = 0 # >0: scorer row-slice width (cand x particles); 0 = rsm_scorer.MAX_ROWS + # coin-terminated beta chain (gen_q#267). plan_mode=chain walks a Bernoulli(p) number of + # beta-hops, p = (gamma-beta)/(gamma*(1-beta)) [ogbench_genq/rsm.py:113], and reads membership + # ONCE at the frozen node; the composed frame offset is then EXACTLY Geom(1-gamma). + # plan_chain_cap=0 => computed from plan_chain_tail_eps (the 1e-3 truncation tail). The cap is + # a truncation GUARD, never a tuning knob -- plan_depth is ignored in chain mode. + self.algo.plan_chain_cap = 0 # 0 = compute from the tail; >0 = explicit cap (sweep only) + self.algo.plan_chain_tail_eps = 1e-3 # P(walk longer than cap) <= this + self.algo.plan_chain_seed = -1 # <0 = follow the cell's eval seed + self.algo.rsm_adv_v_expectile = 0.5 # E2: tau of the expectile baseline + self.algo.rsm_adv_v_samples = 16 # E2: hop-head chunks M for the baseline + self.algo.rsm_adv_scale = "td" # E2: td | std + self.algo.rsm_adv_permute = False # S3H6 control + + self.algo.critic.late_fusion_key = None + self.algo.critic.late_fusion_layer_index = 1 + self.algo.critic.obs_multiplier_key = None + self.algo.critic.obs_multiplier = 1 + + self.algo.action_augmentation = False \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/config/idql_qsm_config.py b/code_src/rise_robomimic/robomimic/config/idql_qsm_config.py new file mode 100644 index 0000000000000000000000000000000000000000..868a3f95e38cb1043c946a6d1c89d9824810fe03 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/config/idql_qsm_config.py @@ -0,0 +1,92 @@ +""" +Config for IQL Diffusion algorithm. +""" + +from robomimic.config.base_config import BaseConfig + + +class IDQL_QSMConfig(BaseConfig): + ALGO_NAME = "idql_qsm" + + def algo_config(self): + """ + This function populates the `config.algo` attribute of the config, and is given to the + `Algo` subclass (see `algo/algo.py`) for each algorithm through the `algo_config` + argument to the constructor. Any parameter that an algorithm needs to determine its + training and test-time behavior should be populated here. + """ + super(IDQL_QSMConfig, self).algo_config() + + # optimization parameters + self.algo.optim_params.critic.learning_rate.initial = 1e-4 # critic learning rate + self.algo.optim_params.critic.learning_rate.decay_factor = 0.0 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.critic.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.critic.regularization.L2 = 0.00 # L2 regularization strength + + self.algo.optim_params.vf.learning_rate.initial = 1e-4 # vf learning rate + self.algo.optim_params.vf.learning_rate.decay_factor = 0.0 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.vf.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.vf.regularization.L2 = 0.00 # L2 regularization strength + + self.algo.optim_params.policy.learning_rate.initial = 1e-4 # policy learning rate + self.algo.optim_params.policy.learning_rate.decay_factor = 0.0 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.policy.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.policy.regularization.L2 = 0.00 # L2 regularization strength + self.algo.optim_params.policy.freeze_until_epoch = None # don't train policy until this epoch + + self.algo.multi_step_method = 'one_step' + self.algo.use_bc = False + + self.algo.alpha_q = 50 + + # unet params + self.algo.unet.enabled = True + self.algo.unet.diffusion_step_embed_dim = 256 + self.algo.unet.down_dims = [256,512,1024] + self.algo.unet.kernel_size = 5 + self.algo.unet.n_groups = 8 + + # EMA parameters + self.algo.ema.enabled = True + self.algo.ema.power = 0.75 + + self.algo.horizon.observation_horizon = 1 + self.algo.horizon.action_horizon = 1 + self.algo.horizon.prediction_horizon = 1 + + # Noise Scheduler + ## DDPM + self.algo.ddpm.enabled = True + self.algo.ddpm.num_train_timesteps = 100 + self.algo.ddpm.num_inference_timesteps = 100 + self.algo.ddpm.beta_schedule = 'squaredcos_cap_v2' + self.algo.ddpm.clip_sample = True + self.algo.ddpm.prediction_type = 'epsilon' + + ## DDIM + self.algo.ddim.enabled = False + self.algo.ddim.num_train_timesteps = 100 + self.algo.ddim.num_inference_timesteps = 10 + self.algo.ddim.beta_schedule = 'squaredcos_cap_v2' + self.algo.ddim.clip_sample = True + self.algo.ddim.set_alpha_to_one = True + self.algo.ddim.steps_offset = 0 + self.algo.ddim.prediction_type = 'epsilon' + + # target network related parameters + self.algo.discount = 0.99 # discount factor to use + self.algo.target_tau = 0.01 # update rate for target networks + + # ================== Critic Network Config =================== + # critic ensemble parameters + self.algo.critic.ensemble.n = 2 # number of Q networks in the ensemble + self.algo.critic.layer_dims = (300, 400) # critic MLP layer dimensions + self.algo.critic.use_huber = False # Huber Loss instead of L2 for critic + self.algo.critic.max_gradient_norm = None # L2 gradient clipping for actor + + # ================== Adv Config ============================== + self.algo.adv.clip_adv_value = None # whether to clip raw advantage estimates + self.algo.adv.beta = 1.0 # temperature for operator + self.algo.adv.use_final_clip = True # whether to clip final weight calculations + + self.algo.vf_quantile = 0.9 # quantile factor in quantile regression diff --git a/code_src/rise_robomimic/robomimic/config/iql_config.py b/code_src/rise_robomimic/robomimic/config/iql_config.py new file mode 100644 index 0000000000000000000000000000000000000000..bd603d1aa0183639971b16747c5020afa6d04fe3 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/config/iql_config.py @@ -0,0 +1,73 @@ +""" +Config for IQL algorithm. +""" + +from robomimic.config.base_config import BaseConfig + + +class IQLConfig(BaseConfig): + ALGO_NAME = "iql" + + def algo_config(self): + """ + This function populates the `config.algo` attribute of the config, and is given to the + `Algo` subclass (see `algo/algo.py`) for each algorithm through the `algo_config` + argument to the constructor. Any parameter that an algorithm needs to determine its + training and test-time behavior should be populated here. + """ + super(IQLConfig, self).algo_config() + + # optimization parameters + self.algo.optim_params.critic.learning_rate.initial = 1e-4 # critic learning rate + self.algo.optim_params.critic.learning_rate.decay_factor = 0.0 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.critic.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.critic.regularization.L2 = 0.00 # L2 regularization strength + + self.algo.optim_params.vf.learning_rate.initial = 1e-4 # vf learning rate + self.algo.optim_params.vf.learning_rate.decay_factor = 0.0 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.vf.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.vf.regularization.L2 = 0.00 # L2 regularization strength + + self.algo.optim_params.actor.learning_rate.initial = 1e-4 # actor learning rate + self.algo.optim_params.actor.learning_rate.decay_factor = 0.0 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.actor.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.actor.regularization.L2 = 0.00 # L2 regularization strength + + # target network related parameters + self.algo.discount = 0.99 # discount factor to use + self.algo.target_tau = 0.01 # update rate for target networks + + # ================== Actor Network Config =================== + # Actor network settings + self.algo.actor.net.type = "gaussian" # Options are currently ["gaussian", "gmm"] + + # Actor network settings - shared + self.algo.actor.net.common.std_activation = "softplus" # Activation to use for std output from policy net + self.algo.actor.net.common.low_noise_eval = True # Whether to use deterministic action sampling at eval stage + self.algo.actor.net.common.use_tanh = False # Whether to use tanh at output of actor network + + # Actor network settings - gaussian + self.algo.actor.net.gaussian.init_last_fc_weight = 0.001 # If set, will override the initialization of the final fc layer to be uniformly sampled limited by this value + self.algo.actor.net.gaussian.init_std = 0.3 # Relative scaling factor for std from policy net + self.algo.actor.net.gaussian.fixed_std = False # Whether to learn std dev or not + + self.algo.actor.net.gmm.num_modes = 5 # number of GMM modes + self.algo.actor.net.gmm.min_std = 0.0001 # minimum std output from network + + self.algo.actor.layer_dims = (300, 400) # actor MLP layer dimensions + + self.algo.actor.max_gradient_norm = None # L2 gradient clipping for actor + + # ================== Critic Network Config =================== + # critic ensemble parameters + self.algo.critic.ensemble.n = 2 # number of Q networks in the ensemble + self.algo.critic.layer_dims = (300, 400) # critic MLP layer dimensions + self.algo.critic.use_huber = False # Huber Loss instead of L2 for critic + self.algo.critic.max_gradient_norm = None # L2 gradient clipping for actor + + # ================== Adv Config ============================== + self.algo.adv.clip_adv_value = None # whether to clip raw advantage estimates + self.algo.adv.beta = 1.0 # temperature for operator + self.algo.adv.use_final_clip = True # whether to clip final weight calculations + + self.algo.vf_quantile = 0.9 # quantile factor in quantile regression diff --git a/code_src/rise_robomimic/robomimic/config/iql_diffusion_config.py b/code_src/rise_robomimic/robomimic/config/iql_diffusion_config.py new file mode 100644 index 0000000000000000000000000000000000000000..e40db672b3a1be59b975eb93e608a2a46c6f09a4 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/config/iql_diffusion_config.py @@ -0,0 +1,165 @@ +""" +Config for IQL Diffusion algorithm. +""" + +from robomimic.config.base_config import BaseConfig + + +class IQLDiffusionConfig(BaseConfig): + ALGO_NAME = "iql_diffusion" + + def algo_config(self): + """ + This function populates the `config.algo` attribute of the config, and is given to the + `Algo` subclass (see `algo/algo.py`) for each algorithm through the `algo_config` + argument to the constructor. Any parameter that an algorithm needs to determine its + training and test-time behavior should be populated here. + """ + super(IQLDiffusionConfig, self).algo_config() + + # optimization parameters + self.algo.optim_params.critic.learning_rate.initial = 1e-4 # critic learning rate + self.algo.optim_params.critic.learning_rate.decay_factor = 0.0 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.critic.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.critic.regularization.L2 = 0.00 # L2 regularization strength + + self.algo.optim_params.vf.learning_rate.initial = 1e-4 # vf learning rate + self.algo.optim_params.vf.learning_rate.decay_factor = 0.0 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.vf.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.vf.regularization.L2 = 0.00 # L2 regularization strength + + self.algo.optim_params.policy.learning_rate.initial = 1e-4 # policy learning rate + self.algo.optim_params.policy.learning_rate.decay_factor = 0.0 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.policy.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.policy.regularization.L2 = 0.00 # L2 regularization strength + self.algo.optim_params.policy.freeze_until_epoch = None # don't train policy until this epoch + + self.algo.multi_step_method = 'one_step' + self.algo.use_bc = False + + # unet params + self.algo.unet.enabled = True + self.algo.unet.diffusion_step_embed_dim = 256 + self.algo.unet.down_dims = [256,512,1024] + self.algo.unet.kernel_size = 5 + self.algo.unet.n_groups = 8 + + # EMA parameters + self.algo.ema.enabled = True + self.algo.ema.power = 0.75 + + self.algo.horizon.observation_horizon = 1 + self.algo.horizon.action_horizon = 1 + self.algo.horizon.prediction_horizon = 1 + + # Noise Scheduler + ## DDPM + self.algo.ddpm.enabled = True + self.algo.ddpm.num_train_timesteps = 100 + self.algo.ddpm.num_inference_timesteps = 100 + self.algo.ddpm.beta_schedule = 'squaredcos_cap_v2' + self.algo.ddpm.clip_sample = True + self.algo.ddpm.prediction_type = 'epsilon' + + ## DDIM + self.algo.ddim.enabled = False + self.algo.ddim.num_train_timesteps = 100 + self.algo.ddim.num_inference_timesteps = 10 + self.algo.ddim.beta_schedule = 'squaredcos_cap_v2' + self.algo.ddim.clip_sample = True + self.algo.ddim.set_alpha_to_one = True + self.algo.ddim.steps_offset = 0 + self.algo.ddim.prediction_type = 'epsilon' + + # target network related parameters + self.algo.discount = 0.99 # discount factor to use + self.algo.target_tau = 0.01 # update rate for target networks + + # ================== Critic Network Config =================== + # critic ensemble parameters + self.algo.critic.ensemble.n = 2 # number of Q networks in the ensemble + self.algo.critic.layer_dims = (300, 400) # critic MLP layer dimensions + self.algo.critic.use_huber = False # Huber Loss instead of L2 for critic + self.algo.critic.max_gradient_norm = None # L2 gradient clipping for actor + + # ================== Adv Config ============================== + self.algo.adv.clip_adv_value = None # whether to clip raw advantage estimates + self.algo.adv.beta = 1.0 # temperature for operator + self.algo.adv.use_final_clip = True # whether to clip final weight calculations + + self.algo.vf_quantile = 0.5 # IQL expectile of V. 0.5 == mean regression == the + + # BEHAVIOURAL value of the data policy, which is what a RANKING baseline needs: the + + # candidates being ranked are draws from that same policy, so an optimistic upper + + # expectile rescales every candidate's implied advantage by an amount that depends on + + # the local action distribution rather than on the action (owner, 2026-09-23). + + # WAS 0.9: every checkpoint trained before 2026-09-23 -- including the real + + # rise_actor_rsm_real_* and every flagship S0Aidql cell -- carries the optimistic head, + + # so those numbers are optimistic-expectile numbers and must not be pooled with 0.5 ones. + + self.algo.bottleneck_policy = False + self.algo.bottleneck_value = False + self.algo.q_bottleneck_beta = 0.2 + self.algo.policy_bottleneck_beta = 0.2 + + self.algo.spectral_norm_policy = False + self.algo.spectral_norm_value = False + + self.algo.lipschitz = False + self.algo.lipschitz_constant = 3.0 + self.algo.lipschitz_weight = 0.005 + self.algo.lipschitz_slack = False + self.algo.lipschitz_denoiser = False + + # rsm_rise Stage 3 (robomimic/algo/rsm_planner.py, rsm_scorer.py). Defaults = released behaviour. + self.algo.plan_n = None # best-of-N over the diffusion sampler; None/1 = released path + self.algo.plan_rule = "argmax" # argmax | softmax | topk_uniform | random | permuted | argmin + self.algo.plan_temp = 0.2 # softmax temperature on Qbar + self.algo.plan_topk = 8 # topk_uniform: k + self.algo.plan_chunk = 8 # actions of the executed window the RSM scores + self.algo.plan_particles = 16 # successor particles per candidate + self.algo.plan_mode = "fold" # d1 | fold | recursive + self.algo.plan_depth = 2 # hops L + self.algo.plan_beta = 0.95 # hop beta + self.algo.plan_gamma = 0.99 # fold discount / recursion restart gamma + # gen_q#273 added plan_mpc_horizon to sim_pipeline's PLANNER_KEYS (iql_diffusion.py:147), which + # copies it into json_config['algo'], but the key was never declared here -- so config_factory's + # key-locked config rejected it and EVERY new idql / iql_diffusion training died at startup in + # ~23 s with "Cannot update ... key 'plan_mpc_horizon' does not exist" (REWARD_MATRIX jobs + # 1885210/1885211, all 8 cells). Declared here with the SAME default as the training-side field + # (0 = off), so this restores released behaviour and changes nothing for any existing cell. + self.algo.plan_mpc_horizon = 0 # world-model MPC horizon H in FRAMES (0 = off) + self.algo.plan_flow_steps = 8 # Euler steps of the successor ODE + self.algo.plan_seed = -1 # >=0: fixed CRN seed per step and selection RNG + self.algo.rsm_backend = "mlp" # mlp | dwm | mc | iql + self.algo.rsm_ckpt = "" # RSM checkpoint (iql: an S0A .pth or "" for own critic) + self.algo.rsm_hop_ckpt = "" # Stage-2 hop head (bc_arm.py policy_r1.pt) + self.algo.rsm_feat_stats = "" # Stage-1 cache feat_stats.npz + self.algo.rsm_img_layout = "chw" # chw (scripts/relabel_dino.py) | rise_t (RISE offline relabel) + self.algo.rsm_dwm_module = "dwm_readout" + self.algo.plan_score = "prob" # prob (mean sigmoid, released) | logit (mean raw logit over particles) + # | prob_log (prob folded in log space: same quantity, total order) + self.algo.plan_rescore_top = 0 # two-stage screening: rescore the top-K of the ranking (0 = off) + self.algo.plan_particles_rescore = 0 # ... with M particles (0 = off) + self.algo.plan_temperature = 0.0 # 0: checkpoint calib.json T (else 1.0); > 0 overrides the sigmoid T + self.algo.plan_lcb_quantile = 0.1 # plan_score=conformal_lcb: particle quantile that ranks (0.1 = 10th pct) + self.algo.plan_sample_batch = 0 # >0: DDPM-sample the candidates in slices of this many rows (0 = off) + self.algo.plan_max_rows = 0 # >0: scorer row-slice width (cand x particles); 0 = rsm_scorer.MAX_ROWS + # coin-terminated beta chain (gen_q#267). plan_mode=chain walks a Bernoulli(p) number of + # beta-hops, p = (gamma-beta)/(gamma*(1-beta)) [ogbench_genq/rsm.py:113], and reads membership + # ONCE at the frozen node; the composed frame offset is then EXACTLY Geom(1-gamma). + # plan_chain_cap=0 => computed from plan_chain_tail_eps (the 1e-3 truncation tail). The cap is + # a truncation GUARD, never a tuning knob -- plan_depth is ignored in chain mode. + self.algo.plan_chain_cap = 0 # 0 = compute from the tail; >0 = explicit cap (sweep only) + self.algo.plan_chain_tail_eps = 1e-3 # P(walk longer than cap) <= this + self.algo.plan_chain_seed = -1 # <0 = follow the cell's eval seed + self.algo.rsm_adv_v_expectile = 0.5 # E2: tau of the expectile baseline + self.algo.rsm_adv_v_samples = 16 # E2: hop-head chunks M for the baseline + self.algo.rsm_adv_scale = "td" # E2: td | std + self.algo.rsm_adv_permute = False # S3H6 control \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/config/iris_config.py b/code_src/rise_robomimic/robomimic/config/iris_config.py new file mode 100644 index 0000000000000000000000000000000000000000..c03328cead61f1a977d76bb4b684613586c2a08c --- /dev/null +++ b/code_src/rise_robomimic/robomimic/config/iris_config.py @@ -0,0 +1,99 @@ +""" +Config for IRIS algorithm. +""" + +from robomimic.config.bcq_config import BCQConfig +from robomimic.config.gl_config import GLConfig +from robomimic.config.bc_config import BCConfig +from robomimic.config.hbc_config import HBCConfig + + +class IRISConfig(HBCConfig): + ALGO_NAME = "iris" + + def algo_config(self): + """ + This function populates the `config.algo` attribute of the config, and is given to the + `Algo` subclass (see `algo/algo.py`) for each algorithm through the `algo_config` + argument to the constructor. Any parameter that an algorithm needs to determine its + training and test-time behavior should be populated here. + """ + + # One of ["separate", "cascade"]. In "separate" mode (default), + # the planner and actor are trained independently and then the planner subgoal predictions are + # used to condition the actor at test-time. In "cascade" mode, the actor is trained directly + # on planner subgoal predictions. In "actor_only" mode, only the actor is trained, and in + # "planner_only" mode, only the planner is trained. + self.algo.mode = "separate" + + self.algo.actor_use_random_subgoals = False # whether to sample subgoal index from [1, subgoal_horizon] + self.algo.subgoal_update_interval = 10 # how frequently the subgoal should be updated at test-time (usually matches train.seq_length) + + # ================== Latent Subgoal Config ================== + + # NOTE: latent subgoals are not supported by IRIS, but superclass expects this config + self.algo.latent_subgoal.enabled = False + self.algo.latent_subgoal.prior_correction.enabled = False + self.algo.latent_subgoal.prior_correction.num_samples = 100 + + # ================== Planner Config ================== + + # The ValuePlanner planner component is a Goal Learning VAE model + self.algo.value_planner.planner = GLConfig().algo # config for goal learning + # set subgoal horizon explicitly + self.algo.value_planner.planner.subgoal_horizon = 10 + # ensure VAE is used + self.algo.value_planner.planner.vae.enabled = True + + # The ValuePlanner value component is a BCQ model + self.algo.value_planner.value = BCQConfig().algo + self.algo.value_planner.value.actor.enabled = False # ensure no BCQ actor + # number of subgoal samples to use for value planner + self.algo.value_planner.num_samples = 100 + + # ================== Actor Config =================== + self.algo.actor = BCConfig().algo + # use RNN + self.algo.actor.rnn.enabled = True + self.algo.actor.rnn.horizon = 10 + # remove unused parts of BCConfig algo config + del self.algo.actor.gaussian + del self.algo.actor.gmm + del self.algo.actor.vae + + def observation_config(self): + """ + Update from superclass so that value planner and actor each get their own obs config. + """ + self.observation.value_planner.planner = GLConfig().observation + self.observation.value_planner.value = BCQConfig().observation + self.observation.actor = BCConfig().observation + + @property + def use_goals(self): + """ + Update from superclass - value planner goal modalities determine goal-conditioning. + """ + return len( + self.observation.value_planner.planner.modalities.goal.low_dim + + self.observation.value_planner.planner.modalities.goal.rgb) > 0 + + @property + def all_obs_keys(self): + """ + Update from superclass to include modalities from value planner and actor. + """ + # pool all modalities + return sorted(tuple(set([ + obs_key for group in [ + self.observation.value_planner.planner.modalities.obs.values(), + self.observation.value_planner.planner.modalities.goal.values(), + self.observation.value_planner.planner.modalities.subgoal.values(), + self.observation.value_planner.value.modalities.obs.values(), + self.observation.value_planner.value.modalities.goal.values(), + self.observation.actor.modalities.obs.values(), + self.observation.actor.modalities.goal.values(), + ] + for modality in group + for obs_key in modality + ]))) diff --git a/code_src/rise_robomimic/robomimic/config/td3_bc_config.py b/code_src/rise_robomimic/robomimic/config/td3_bc_config.py new file mode 100644 index 0000000000000000000000000000000000000000..036a2591a91b4a4f5da4e2415dd035117e587900 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/config/td3_bc_config.py @@ -0,0 +1,111 @@ +""" +Config for TD3_BC. +""" + +from robomimic.config.base_config import BaseConfig + + +class TD3_BCConfig(BaseConfig): + ALGO_NAME = "td3_bc" + + def experiment_config(self): + """ + Update from subclass to set paper defaults for gym envs. + """ + super(TD3_BCConfig, self).experiment_config() + + # no validation and no video rendering + self.experiment.validate = False + self.experiment.render_video = False + + # save 10 checkpoints throughout training + self.experiment.save.every_n_epochs = 20 + + # save models that achieve best rollout return instead of best success rate + self.experiment.save.on_best_rollout_return = True + self.experiment.save.on_best_rollout_success_rate = False + + # epoch definition - 5000 gradient steps per epoch, with 200 epochs = 1M gradient steps, and eval every 1 epochs + self.experiment.epoch_every_n_steps = 5000 + + # evaluate with normal environment rollouts + self.experiment.rollout.enabled = True + self.experiment.rollout.n = 50 # paper uses 10, but we can afford to do 50 + self.experiment.rollout.horizon = 1000 + self.experiment.rollout.rate = 1 # rollout every epoch to match paper + + def train_config(self): + """ + Update from subclass to set paper defaults for gym envs. + """ + super(TD3_BCConfig, self).train_config() + + # update to normalize observations + self.train.hdf5_normalize_obs = True + + # increase batch size to 256 + self.train.batch_size = 256 + + # 200 epochs, with each epoch lasting 5000 gradient steps, for 1M total steps + self.train.num_epochs = 200 + + def algo_config(self): + """ + This function populates the `config.algo` attribute of the config, and is given to the + `Algo` subclass (see `algo/algo.py`) for each algorithm through the `algo_config` + argument to the constructor. Any parameter that an algorithm needs to determine its + training and test-time behavior should be populated here. + """ + + # optimization parameters + self.algo.optim_params.critic.learning_rate.initial = 3e-4 # critic learning rate + self.algo.optim_params.critic.learning_rate.decay_factor = 0.1 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.critic.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.critic.regularization.L2 = 0.00 # L2 regularization strength + self.algo.optim_params.critic.start_epoch = -1 # number of epochs before starting critic training (-1 means start right away) + self.algo.optim_params.critic.end_epoch = -1 # number of epochs before ending critic training (-1 means start right away) + + self.algo.optim_params.actor.learning_rate.initial = 3e-4 # actor learning rate + self.algo.optim_params.actor.learning_rate.decay_factor = 0.1 # factor to decay LR by (if epoch schedule non-empty) + self.algo.optim_params.actor.learning_rate.epoch_schedule = [] # epochs where LR decay occurs + self.algo.optim_params.actor.regularization.L2 = 0.00 # L2 regularization strength + self.algo.optim_params.actor.start_epoch = -1 # number of epochs before starting actor training (-1 means start right away) + self.algo.optim_params.actor.end_epoch = -1 # number of epochs before ending actor training (-1 means start right away) + + # alpha value - for weighting critic loss vs. BC loss + self.algo.alpha = 2.5 + + # target network related parameters + self.algo.discount = 0.99 # discount factor to use + self.algo.n_step = 1 # for using n-step returns in TD-updates + self.algo.target_tau = 0.005 # update rate for target networks + self.algo.infinite_horizon = False # if True, scale terminal rewards by 1 / (1 - discount) to treat as infinite horizon + + # ================== Critic Network Config =================== + self.algo.critic.use_huber = False # Huber Loss instead of L2 for critic + self.algo.critic.max_gradient_norm = None # L2 gradient clipping for critic (None to use no clipping) + self.algo.critic.value_bounds = None # optional 2-tuple to ensure lower and upper bound on value estimates + + # critic ensemble parameters (TD3 trick) + self.algo.critic.ensemble.n = 2 # number of Q networks in the ensemble + self.algo.critic.ensemble.weight = 1.0 # weighting for mixing min and max for target Q value + + self.algo.critic.layer_dims = (256, 256) # size of critic MLP + + # ================== Actor Network Config =================== + + # update actor and target networks every n gradients steps for each critic gradient step + self.algo.actor.update_freq = 2 + + # exploration noise used to form target action for Q-update - clipped Gaussian noise + self.algo.actor.noise_std = 0.2 # zero-mean gaussian noise with this std is applied to actions + self.algo.actor.noise_clip = 0.5 # noise is clipped in each dimension to (-noise_clip, noise_clip) + + self.algo.actor.layer_dims = (256, 256) # size of actor MLP + + def observation_config(self): + """ + Update from superclass to use flat observations from gym envs. + """ + super(TD3_BCConfig, self).observation_config() + self.observation.modalities.obs.low_dim = ["flat"] diff --git a/code_src/rise_robomimic/robomimic/envs/__init__.py b/code_src/rise_robomimic/robomimic/envs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/code_src/rise_robomimic/robomimic/envs/env_base.py b/code_src/rise_robomimic/robomimic/envs/env_base.py new file mode 100644 index 0000000000000000000000000000000000000000..9634db01b5d1e5bae4077d134f9dd84b021131a4 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/envs/env_base.py @@ -0,0 +1,241 @@ +""" +This file contains the base class for environment wrappers that are used +to provide a standardized environment API for training policies and interacting +with metadata present in datasets. +""" +import abc + + +class EnvType: + """ + Holds environment types - one per environment class. + These act as identifiers for different environments. + """ + ROBOSUITE_TYPE = 1 + GYM_TYPE = 2 + IG_MOMART_TYPE = 3 + + +class EnvBase(abc.ABC): + """A base class method for environments used by this repo.""" + @abc.abstractmethod + def __init__( + self, + env_name, + render=False, + render_offscreen=False, + use_image_obs=False, + use_depth_obs=False, + postprocess_visual_obs=True, + **kwargs, + ): + """ + Args: + env_name (str): name of environment. Only needs to be provided if making a different + environment from the one in @env_meta. + + render (bool): if True, environment supports on-screen rendering + + render_offscreen (bool): if True, environment supports off-screen rendering. This + is forced to be True if @env_meta["use_images"] is True. + + use_image_obs (bool): if True, environment is expected to render rgb image observations + on every env.step call. Set this to False for efficiency reasons, if image + observations are not required. + + use_depth_obs (bool): if True, environment is expected to render depth image observations + on every env.step call. Set this to False for efficiency reasons, if depth + observations are not required. + + postprocess_visual_obs (bool): if True, postprocess image observations + to prepare for learning. This should only be False when extracting observations + for saving to a dataset (to save space on RGB images for example). + """ + return + + @abc.abstractmethod + def step(self, action): + """ + Step in the environment with an action. + + Args: + action (np.array): action to take + + Returns: + observation (dict): new observation dictionary + reward (float): reward for this step + done (bool): whether the task is done + info (dict): extra information + """ + return + + @abc.abstractmethod + def reset(self): + """ + Reset environment. + + Returns: + observation (dict): initial observation dictionary. + """ + return + + @abc.abstractmethod + def reset_to(self, state): + """ + Reset to a specific simulator state. + + Args: + state (dict): current simulator state + + Returns: + observation (dict): observation dictionary after setting the simulator state + """ + return + + @abc.abstractmethod + def render(self, mode="human", height=None, width=None, camera_name=None): + """Render""" + return + + @abc.abstractmethod + def get_observation(self): + """Get environment observation""" + return + + @abc.abstractmethod + def get_state(self): + """Get environment simulator state, compatible with @reset_to""" + return + + @abc.abstractmethod + def get_reward(self): + """ + Get current reward. + """ + return + + @abc.abstractmethod + def get_goal(self): + """ + Get goal observation. Not all environments support this. + """ + return + + @abc.abstractmethod + def set_goal(self, **kwargs): + """ + Set goal observation with external specification. Not all environments support this. + """ + return + + @abc.abstractmethod + def is_done(self): + """ + Check if the task is done (not necessarily successful). + """ + return + + @abc.abstractmethod + def is_success(self): + """ + Check if the task condition(s) is reached. Should return a dictionary + { str: bool } with at least a "task" key for the overall task success, + and additional optional keys corresponding to other task criteria. + """ + return + + @property + @abc.abstractmethod + def action_dimension(self): + """ + Returns dimension of actions (int). + """ + return + + @property + @abc.abstractmethod + def name(self): + """ + Returns name of environment name (str). + """ + return + + @property + @abc.abstractmethod + def type(self): + """ + Returns environment type (int) for this kind of environment. + This helps identify this env class. + """ + return + + @property + def version(self): + """ + Returns version of environment (str). + This is not an abstract method, some subclasses do not implement it + """ + return None + + @abc.abstractmethod + def serialize(self): + """ + Save all information needed to re-instantiate this environment in a dictionary. + This is the same as @env_meta - environment metadata stored in hdf5 datasets, + and used in utils/env_utils.py. + """ + return + + @classmethod + @abc.abstractmethod + def create_for_data_processing( + cls, + camera_names, + camera_height, + camera_width, + reward_shaping, + render=None, + render_offscreen=None, + use_image_obs=None, + use_depth_obs=None, + **kwargs, + ): + """ + Create environment for processing datasets, which includes extracting + observations, labeling dense / sparse rewards, and annotating dones in + transitions. + + Args: + camera_names ([str]): list of camera names that correspond to image observations + camera_height (int): camera height for all cameras + camera_width (int): camera width for all cameras + reward_shaping (bool): if True, use shaped environment rewards, else use sparse task completion rewards + render (bool or None): optionally override rendering behavior. Defaults to False. + render_offscreen (bool or None): optionally override rendering behavior. The default value is True if + @camera_names is non-empty, False otherwise. + use_image_obs (bool or None): optionally override rendering behavior. The default value is True if + @camera_names is non-empty, False otherwise. + use_depth_obs (bool): if True, use depth observations + + Returns: + env (EnvBase instance) + """ + return + + @property + @abc.abstractmethod + def rollout_exceptions(self): + """ + Return tuple of exceptions to except when doing rollouts. This is useful to ensure + that the entire training run doesn't crash because of a bad policy that causes unstable + simulation computations. + """ + return + + @property + @abc.abstractmethod + def base_env(self): + """ + Grabs base simulation environment. + """ + return diff --git a/code_src/rise_robomimic/robomimic/envs/env_gym.py b/code_src/rise_robomimic/robomimic/envs/env_gym.py new file mode 100644 index 0000000000000000000000000000000000000000..7b56d1ebb3be670c8e2207fa6afcdf4ee1ec5190 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/envs/env_gym.py @@ -0,0 +1,267 @@ +""" +This file contains the gym environment wrapper that is used +to provide a standardized environment API for training policies and interacting +with metadata present in datasets. +""" +import json +import numpy as np +from copy import deepcopy + +import gym +try: + import d4rl +except: + print("WARNING: could not load d4rl environments!") + +import robomimic.envs.env_base as EB +import robomimic.utils.obs_utils as ObsUtils + + +class EnvGym(EB.EnvBase): + """Wrapper class for gym""" + def __init__( + self, + env_name, + render=False, + render_offscreen=False, + use_image_obs=False, + use_depth_obs=False, + postprocess_visual_obs=True, + **kwargs, + ): + """ + Args: + env_name (str): name of environment. Only needs to be provided if making a different + environment from the one in @env_meta. + + render (bool): ignored - gym envs always support on-screen rendering + + render_offscreen (bool): ignored - gym envs always support off-screen rendering + + use_image_obs (bool): ignored - gym envs don't typically use images + + postprocess_visual_obs (bool): ignored - gym envs don't typically use images + """ + self._init_kwargs = deepcopy(kwargs) + self._env_name = env_name + self._current_obs = None + self._current_reward = None + self._current_done = None + self._done = None + self.env = gym.make(env_name, **kwargs) + + def step(self, action): + """ + Step in the environment with an action. + + Args: + action (np.array): action to take + + Returns: + observation (dict): new observation dictionary + reward (float): reward for this step + done (bool): whether the task is done + info (dict): extra information + """ + obs, reward, done, info = self.env.step(action) + self._current_obs = obs + self._current_reward = reward + self._current_done = done + return self.get_observation(obs), reward, self.is_done(), info + + def reset(self): + """ + Reset environment. + + Returns: + observation (dict): initial observation dictionary. + """ + self._current_obs = self.env.reset() + self._current_reward = None + self._current_done = None + return self.get_observation(self._current_obs) + + def reset_to(self, state): + """ + Reset to a specific simulator state. + + Args: + state (dict): current simulator state that contains: + - states (np.ndarray): initial state of the mujoco environment + + Returns: + observation (dict): observation dictionary after setting the simulator state + """ + if hasattr(self.env.unwrapped.sim, "set_state_from_flattened"): + self.env.unwrapped.sim.set_state_from_flattened(state["states"]) + self.env.unwrapped.sim.forward() + return { "flat" : self.env.unwrapped._get_obs() } + else: + raise NotImplementedError + + def render(self, mode="human", height=None, width=None, camera_name=None, **kwargs): + """ + Render from simulation to either an on-screen window or off-screen to RGB array. + + Args: + mode (str): pass "human" for on-screen rendering or "rgb_array" for off-screen rendering + height (int): height of image to render - only used if mode is "rgb_array" + width (int): width of image to render - only used if mode is "rgb_array" + """ + if mode =="human": + return self.env.render(mode=mode, **kwargs) + if mode == "rgb_array": + return self.env.render(mode="rgb_array", height=height, width=width) + else: + raise NotImplementedError("mode={} is not implemented".format(mode)) + + def get_observation(self, obs=None): + """ + Get current environment observation dictionary. + + Args: + ob (np.array): current flat observation vector to wrap and provide as a dictionary. + If not provided, uses self._current_obs. + """ + if obs is None: + assert self._current_obs is not None + obs = self._current_obs + return { "flat" : np.copy(obs) } + + def get_state(self): + """ + Get current environment simulator state as a dictionary. Should be compatible with @reset_to. + """ + # NOTE: assumes MuJoCo gym task! + xml = self.env.sim.model.get_xml() # model xml file + state = np.array(self.env.sim.get_state().flatten()) # simulator state + return dict(model=xml, states=state) + + def get_reward(self): + """ + Get current reward. + """ + assert self._current_reward is not None + return self._current_reward + + def get_goal(self): + """ + Get goal observation. Not all environments support this. + """ + raise NotImplementedError + + def set_goal(self, **kwargs): + """ + Set goal observation with external specification. Not all environments support this. + """ + raise NotImplementedError + + def is_done(self): + """ + Check if the task is done (not necessarily successful). + """ + assert self._current_done is not None + return self._current_done + + def is_success(self): + """ + Check if the task condition(s) is reached. Should return a dictionary + { str: bool } with at least a "task" key for the overall task success, + and additional optional keys corresponding to other task criteria. + """ + if hasattr(self.env.unwrapped, "_check_success"): + return self.env.unwrapped._check_success() + + # gym envs generally don't check task success - we only compare returns + return { "task" : False } + + @property + def action_dimension(self): + """ + Returns dimension of actions (int). + """ + return self.env.action_space.shape[0] + + @property + def name(self): + """ + Returns name of environment name (str). + """ + return self._env_name + + @property + def type(self): + """ + Returns environment type (int) for this kind of environment. + This helps identify this env class. + """ + return EB.EnvType.GYM_TYPE + + def serialize(self): + """ + Save all information needed to re-instantiate this environment in a dictionary. + This is the same as @env_meta - environment metadata stored in hdf5 datasets, + and used in utils/env_utils.py. + """ + return dict(env_name=self.name, type=self.type, env_kwargs=deepcopy(self._init_kwargs)) + + @classmethod + def create_for_data_processing( + cls, + env_name, + camera_names, + camera_height, + camera_width, + reward_shaping, + render=None, + render_offscreen=None, + use_image_obs=None, + use_depth_obs=None, + **kwargs, + ): + """ + Create environment for processing datasets, which includes extracting + observations, labeling dense / sparse rewards, and annotating dones in + transitions. For gym environments, input arguments (other than @env_name) + are ignored, since environments are mostly pre-configured. + + Args: + env_name (str): name of gym environment to create + + Returns: + env (EnvGym instance) + """ + + # make sure to initialize obs utils so it knows which modalities are image modalities. + # For currently supported gym tasks, there are no image observations. + obs_modality_specs = { + "obs": { + "low_dim": ["flat"], + "rgb": [], + } + } + ObsUtils.initialize_obs_utils_with_obs_specs(obs_modality_specs) + + return cls(env_name=env_name, **kwargs) + + @property + def rollout_exceptions(self): + """ + Return tuple of exceptions to except when doing rollouts. This is useful to ensure + that the entire training run doesn't crash because of a bad policy that causes unstable + simulation computations. + """ + return () + + @property + def base_env(self): + """ + Grabs base simulation environment. + """ + return self.env + + def __repr__(self): + """ + Pretty-print env description. + """ + return self.name + "\n" + json.dumps(self._init_kwargs, sort_keys=True, indent=4) diff --git a/code_src/rise_robomimic/robomimic/envs/env_ig_momart.py b/code_src/rise_robomimic/robomimic/envs/env_ig_momart.py new file mode 100644 index 0000000000000000000000000000000000000000..951eedf393c4269a39a26e4ea4b5f69c992a4431 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/envs/env_ig_momart.py @@ -0,0 +1,414 @@ +""" +Wrapper environment class to enable using iGibson-based environments used in the MOMART paper +""" + +from copy import deepcopy +import numpy as np +import json + +import pybullet as p +import gibson2 +from gibson2.envs.semantic_organize_and_fetch import SemanticOrganizeAndFetch +from gibson2.utils.custom_utils import ObjectConfig +import gibson2.external.pybullet_tools.utils as PBU +import tempfile +import os +import yaml +import cv2 + +import robomimic.utils.obs_utils as ObsUtils +import robomimic.envs.env_base as EB + + +# TODO: Once iG 2.0 is more stable, automate available environments, similar to robosuite +ENV_MAPPING = { + "SemanticOrganizeAndFetch": SemanticOrganizeAndFetch, +} + + +class EnvGibsonMOMART(EB.EnvBase): + """ + Wrapper class for gibson environments (https://github.com/StanfordVL/iGibson) specifically compatible with + MoMaRT datasets + """ + def __init__( + self, + env_name, + ig_config, + postprocess_visual_obs=True, + render=False, + render_offscreen=False, + use_image_obs=False, + use_depth_obs=False, + image_height=None, + image_width=None, + physics_timestep=1./240., + action_timestep=1./20., + **kwargs, + ): + """ + Args: + ig_config (dict): YAML configuration to use for iGibson, as a dict + + postprocess_visual_obs (bool): if True, postprocess image observations + to prepare for learning + + render (bool): if True, environment supports on-screen rendering + + render_offscreen (bool): if True, environment supports off-screen rendering. This + is forced to be True if @use_image_obs is True. + + use_image_obs (bool): if True, environment is expected to render rgb image observations + on every env.step call. Set this to False for efficiency reasons, if image + observations are not required. + + use_depth_obs (bool): if True, environment is expected to render depth image observations + on every env.step call. Set this to False for efficiency reasons, if depth + observations are not required. + + render_mode (str): How to run simulation rendering. Options are {"pbgui", "iggui", or "headless"} + + image_height (int): If specified, overrides internal iG image height when rendering + + image_width (int): If specified, overrides internal iG image width when rendering + + physics_timestep (float): Pybullet physics timestep to use + + action_timestep (float): Action timestep to use for robot in simulation + + kwargs (unrolled dict): Any args to substitute in the ig_configuration + """ + self._env_name = env_name + self.ig_config = deepcopy(ig_config) + self.postprocess_visual_obs = postprocess_visual_obs + self._init_kwargs = kwargs + + # Determine rendering mode + self.render_mode = "iggui" if render else "headless" + self.render_onscreen = render + + # Make sure rgb is part of obs in ig config + self.ig_config["output"] = list(set(self.ig_config["output"] + ["rgb"])) + + # Warn user that iG always uses a renderer + if (not render) and (not render_offscreen): + print("WARNING: iGibson always uses a renderer -- using headless by default.") + + # Update ig config + for k, v in kwargs.items(): + assert k in self.ig_config, f"Got unknown ig configuration key {k}!" + self.ig_config[k] = v + + # Set rendering values + self.obs_img_height = image_height if image_height is not None else self.ig_config.get("obs_image_height", 120) + self.obs_img_width = image_width if image_width is not None else self.ig_config.get("obs_image_width", 120) + + # Get class to create + envClass = ENV_MAPPING.get(self._env_name, None) + + # Make sure we have a valid environment class + assert envClass is not None, "No valid environment for the requested task was found!" + + # Set device idx for rendering + # ensure that we select the correct GPU device for rendering by testing for EGL rendering + # NOTE: this package should be installed from this link (https://github.com/StanfordVL/egl_probe) + import egl_probe + device_idx = 0 + valid_gpu_devices = egl_probe.get_available_devices() + if len(valid_gpu_devices) > 0: + device_idx = valid_gpu_devices[0] + + # Create environment + self.env = envClass( + config_file=deepcopy(self.ig_config), + mode=self.render_mode, + physics_timestep=physics_timestep, + action_timestep=action_timestep, + device_idx=device_idx, + ) + + # If we have a viewer, make sure to remove all bodies belonging to the visual markers + self.exclude_body_ids = [] # Bodies to exclude when saving state + if self.env.simulator.viewer is not None: + self.exclude_body_ids.append(self.env.simulator.viewer.constraint_marker.body_id) + self.exclude_body_ids.append(self.env.simulator.viewer.constraint_marker2.body_id) + + def step(self, action): + """ + Step in the environment with an action + + Args: + action: action to take + + Returns: + observation: new observation + reward: step reward + done: whether the task is done + info: extra information + """ + obs, r, done, info = self.env.step(action) + obs = self.get_observation(obs) + return obs, r, self.is_done(), info + + def reset(self): + """Reset environment""" + di = self.env.reset() + return self.get_observation(di) + + def reset_to(self, state): + """ + Reset to a specific state + Args: + state (dict): contains: + - states (np.ndarray): initial state of the mujoco environment + - goal (dict): goal components to reset + Returns: + new observation + """ + if "states" in state: + self.env.reset_to(state["states"], exclude=self.exclude_body_ids) + + if "goal" in state: + self.set_goal(**state["goal"]) + + # Return obs + return self.get_observation() + + def render(self, mode="human", camera_name="rgb", height=None, width=None): + """ + Render + + Args: + mode (str): Mode(s) to render. Options are either 'human' (rendering onscreen) or 'rgb' (rendering to + frames offscreen) + camera_name (str): Name of the camera to use -- valid options are "rgb" or "rgb_wrist" + height (int): If specified with width, resizes the rendered image to this height + width (int): If specified with height, resizes the rendered image to this width + + Returns: + array or None: If rendering to frame, returns the rendered frame. Otherwise, returns None + """ + # Only robotview camera is currently supported + assert camera_name in {"rgb", "rgb_wrist"}, \ + f"Only rgb, rgb_wrist cameras currently supported, got {camera_name}." + + if mode == "human": + assert self.render_onscreen, "Rendering has not been enabled for onscreen!" + self.env.simulator.sync() + else: + assert self.env.simulator.renderer is not None, "No renderer enabled for this env!" + + frame = self.env.sensors["vision"].get_obs(self.env)[camera_name] + + # Reshape all frames + if height is not None and width is not None: + frame = cv2.resize(frame, dsize=(height, width), interpolation=cv2.INTER_CUBIC) + return frame + + def resize_obs_frame(self, frame): + """ + Resizes frame to be internal height and width values + """ + return cv2.resize(frame, dsize=(self.obs_img_width, self.obs_img_height), interpolation=cv2.INTER_CUBIC) + + def get_observation(self, di=None): + """Get environment observation""" + if di is None: + di = self.env.get_state() + ret = {} + for k in di: + # RGB Images + if "rgb" in k: + ret[k] = di[k] + # ret[k] = np.transpose(di[k], (2, 0, 1)) + if self.postprocess_visual_obs: + ret[k] = ObsUtils.process_obs(obs=self.resize_obs_frame(ret[k]), obs_key=k) + + # Depth images + elif "depth" in k: + # ret[k] = np.transpose(di[k], (2, 0, 1)) + # Values can be corrupted (negative or > 1.0, so we clip values) + ret[k] = np.clip(di[k], 0.0, 1.0) + if self.postprocess_visual_obs: + ret[k] = ObsUtils.process_obs(obs=self.resize_obs_frame(ret[k])[..., None], obs_key=k) + + # Segmentation Images + elif "seg" in k: + ret[k] = di[k][..., None] + if self.postprocess_visual_obs: + ret[k] = ObsUtils.process_obs(obs=self.resize_obs_frame(ret[k]), obs_key=k) + + # Scans + elif "scan" in k: + ret[k] = np.transpose(np.array(di[k]), axes=(1, 0)) + + # Compose proprio obs + proprio_obs = di["proprio"] + + # Compute intermediate values + lin_vel = np.linalg.norm(proprio_obs["base_lin_vel"][:2]) + ang_vel = proprio_obs["base_ang_vel"][2] + + ret["proprio"] = np.concatenate([ + proprio_obs["head_joint_pos"], + proprio_obs["grasped"], + proprio_obs["eef_pos"], + proprio_obs["eef_quat"], + ]) + + # Proprio info that's only relevant for navigation + ret["proprio_nav"] = np.concatenate([ + [lin_vel], + [ang_vel], + ]) + + # Compose task obs + ret["object"] = np.concatenate([ + np.array(di["task_obs"]["object-state"]), + ]) + + # Add ground truth navigational state + ret["gt_nav"] = np.concatenate([ + proprio_obs["base_pos"][:2], + [np.sin(proprio_obs["base_rpy"][2])], + [np.cos(proprio_obs["base_rpy"][2])], + ]) + + return ret + + def sync_task(self): + """ + Method to synchronize iG task, since we're not actually resetting the env but instead setting states directly. + Should only be called after resetting the initial state of an episode + """ + self.env.task.update_target_object_init_pos() + self.env.task.update_location_info() + + def set_task_conditions(self, task_conditions): + """ + Method to override task conditions (e.g.: target object), useful in cases such as playing back + from demonstrations + + Args: + task_conditions (dict): Keyword-mapped arguments to pass to task instance to set internally + """ + self.env.set_task_conditions(task_conditions) + + def get_state(self): + """Get iG flattened state""" + return {"states": PBU.WorldSaver(exclude_body_ids=self.exclude_body_ids).serialize()} + + def get_reward(self): + return self.env.task.get_reward(self.env)[0] + # return float(self.is_success()["task"]) + + def get_goal(self): + """Get goal specification""" + # No support yet in iG + raise NotImplementedError + + def set_goal(self, **kwargs): + """Set env target with external specification""" + # No support yet in iG + raise NotImplementedError + + def is_done(self): + """Check if the agent is done (not necessarily successful).""" + return False + + def is_success(self): + """ + Check if the task condition(s) is reached. Should return a dictionary + { str: bool } with at least a "task" key for the overall task success, + and additional optional keys corresponding to other task criteria. + """ + succ = self.env.check_success() + if isinstance(succ, dict): + assert "task" in succ + return succ + return { "task" : succ } + + @classmethod + def create_for_data_processing( + cls, + env_name, + camera_names, + camera_height, + camera_width, + reward_shaping, + render=None, + render_offscreen=None, + use_image_obs=None, + use_depth_obs=None, + **kwargs, + ): + """ + Create environment for processing datasets, which includes extracting + observations, labeling dense / sparse rewards, and annotating dones in + transitions. + + Args: + env_name (str): name of environment + camera_names (list of str): list of camera names that correspond to image observations + camera_height (int): camera height for all cameras + camera_width (int): camera width for all cameras + reward_shaping (bool): if True, use shaped environment rewards, else use sparse task completion rewards + render (bool or None): optionally override rendering behavior + render_offscreen (bool or None): optionally override rendering behavior + use_image_obs (bool or None): optionally override rendering behavior + """ + has_camera = (len(camera_names) > 0) + + # note that @postprocess_visual_obs is False since this env's images will be written to a dataset + return cls( + env_name=env_name, + render=(False if render is None else render), + render_offscreen=(has_camera if render_offscreen is None else render_offscreen), + use_image_obs=(has_camera if use_image_obs is None else use_image_obs), + postprocess_visual_obs=False, + image_height=camera_height, + image_width=camera_width, + **kwargs, + ) + + @property + def action_dimension(self): + """Action dimension""" + return self.env.robots[0].action_dim + + @property + def name(self): + """Environment name""" + return self._env_name + + @property + def type(self): + """Environment type""" + return EB.EnvType.IG_MOMART_TYPE + + def serialize(self): + """Serialize to dictionary""" + return dict(env_name=self.name, type=self.type, + ig_config=self.ig_config, + env_kwargs=deepcopy(self._init_kwargs)) + + @classmethod + def deserialize(cls, info, postprocess_visual_obs=True): + """Create environment with external info""" + return cls(env_name=info["env_name"], ig_config=info["ig_config"], postprocess_visual_obs=postprocess_visual_obs, **info["env_kwargs"]) + + @property + def rollout_exceptions(self): + """Return tuple of exceptions to except when doing rollouts""" + return (RuntimeError) + + @property + def base_env(self): + """ + Grabs base simulation environment. + """ + return self.env + + def __repr__(self): + return self.name + "\n" + json.dumps(self._init_kwargs, sort_keys=True, indent=4) + \ + "\niGibson Config: \n" + json.dumps(self.ig_config, sort_keys=True, indent=4) diff --git a/code_src/rise_robomimic/robomimic/envs/env_robosuite.py b/code_src/rise_robomimic/robomimic/envs/env_robosuite.py new file mode 100644 index 0000000000000000000000000000000000000000..2b675ee3d9d886589a1f993c8c2b606d5fb056ec --- /dev/null +++ b/code_src/rise_robomimic/robomimic/envs/env_robosuite.py @@ -0,0 +1,520 @@ +""" +This file contains the robosuite environment wrapper that is used +to provide a standardized environment API for training policies and interacting +with metadata present in datasets. +""" +import json +import numpy as np +from copy import deepcopy + +import robosuite +import robosuite.utils.transform_utils as T +try: + # this is needed for ensuring robosuite can find the additional mimicgen environments (see https://mimicgen.github.io) + import mimicgen +except ImportError: + pass +try: + # deprecated version of mimicgen + import mimicgen_envs +except ImportError: + pass + +import robomimic.utils.obs_utils as ObsUtils +import robomimic.envs.env_base as EB + +# protect against missing mujoco-py module, since robosuite might be using mujoco-py or DM backend +try: + import mujoco_py + MUJOCO_EXCEPTIONS = [mujoco_py.builder.MujocoException] +except ImportError: + MUJOCO_EXCEPTIONS = [] + + +class EnvRobosuite(EB.EnvBase): + """Wrapper class for robosuite environments (https://github.com/ARISE-Initiative/robosuite)""" + def __init__( + self, + env_name, + render=False, + render_offscreen=False, + use_image_obs=False, + use_depth_obs=False, + postprocess_visual_obs=True, + **kwargs, + ): + """ + Args: + env_name (str): name of environment. Only needs to be provided if making a different + environment from the one in @env_meta. + + render (bool): if True, environment supports on-screen rendering + + render_offscreen (bool): if True, environment supports off-screen rendering. This + is forced to be True if @env_meta["use_images"] is True. + + use_image_obs (bool): if True, environment is expected to render rgb image observations + on every env.step call. Set this to False for efficiency reasons, if image + observations are not required. + + use_depth_obs (bool): if True, environment is expected to render depth image observations + on every env.step call. Set this to False for efficiency reasons, if depth + observations are not required. + + postprocess_visual_obs (bool): if True, postprocess image observations + to prepare for learning. This should only be False when extracting observations + for saving to a dataset (to save space on RGB images for example). + """ + self.postprocess_visual_obs = postprocess_visual_obs + self.use_depth_obs = use_depth_obs + + # robosuite version check + self._is_v1 = (robosuite.__version__.split(".")[0] == "1") + if self._is_v1: + assert (int(robosuite.__version__.split(".")[1]) >= 2), "only support robosuite v0.3 and v1.2+" + + kwargs = deepcopy(kwargs) + + # update kwargs based on passed arguments + update_kwargs = dict( + has_renderer=render, + has_offscreen_renderer=(render_offscreen or use_image_obs), + ignore_done=True, + use_object_obs=True, + use_camera_obs=use_image_obs, + camera_depths=use_depth_obs, + ) + kwargs.update(update_kwargs) + + if self._is_v1: + if kwargs["has_offscreen_renderer"]: + # ensure that we select the correct GPU device for rendering by testing for EGL rendering + # NOTE: this package should be installed from this link (https://github.com/StanfordVL/egl_probe) + import egl_probe + valid_gpu_devices = egl_probe.get_available_devices() + if len(valid_gpu_devices) > 0: + kwargs["render_gpu_device_id"] = valid_gpu_devices[0] + else: + # make sure gripper visualization is turned off (we almost always want this for learning) + kwargs["gripper_visualization"] = False + del kwargs["camera_depths"] + kwargs["camera_depth"] = use_depth_obs # rename kwarg + + self._env_name = env_name + self._init_kwargs = deepcopy(kwargs) + self.env = robosuite.make(self._env_name, **kwargs) + + if self._is_v1: + # Make sure joint position observations and eef vel observations are active + for ob_name in self.env.observation_names: + if ("joint_pos" in ob_name) or ("eef_vel" in ob_name): + self.env.modify_observable(observable_name=ob_name, attribute="active", modifier=True) + + def step(self, action): + """ + Step in the environment with an action. + + Args: + action (np.array): action to take + + Returns: + observation (dict): new observation dictionary + reward (float): reward for this step + done (bool): whether the task is done + info (dict): extra information + """ + obs, r, done, info = self.env.step(action) + obs = self.get_observation(obs) + return obs, r, self.is_done(), info + + def reset(self): + """ + Reset environment. + + Returns: + observation (dict): initial observation dictionary. + """ + di = self.env.reset() + return self.get_observation(di) + + def reset_to(self, state): + """ + Reset to a specific simulator state. + + Args: + state (dict): current simulator state that contains one or more of: + - states (np.ndarray): initial state of the mujoco environment + - model (str): mujoco scene xml + + Returns: + observation (dict): observation dictionary after setting the simulator state (only + if "states" is in @state) + """ + should_ret = False + if "model" in state: + self.reset() + robosuite_version_id = int(robosuite.__version__.split(".")[1]) + if robosuite_version_id <= 3: + from robosuite.utils.mjcf_utils import postprocess_model_xml + xml = postprocess_model_xml(state["model"]) + else: + # v1.4 and above use the class-based edit_model_xml function + xml = self.env.edit_model_xml(state["model"]) + self.env.reset_from_xml_string(xml) + self.env.sim.reset() + if not self._is_v1: + # hide teleop visualization after restoring from model + self.env.sim.model.site_rgba[self.env.eef_site_id] = np.array([0., 0., 0., 0.]) + self.env.sim.model.site_rgba[self.env.eef_cylinder_id] = np.array([0., 0., 0., 0.]) + if "states" in state: + self.env.sim.set_state_from_flattened(state["states"]) + self.env.sim.forward() + should_ret = True + + if "goal" in state: + self.set_goal(**state["goal"]) + if should_ret: + # only return obs if we've done a forward call - otherwise the observations will be garbage + return self.get_observation() + return None + + def render(self, mode="human", height=None, width=None, camera_name="agentview"): + """ + Render from simulation to either an on-screen window or off-screen to RGB array. + + Args: + mode (str): pass "human" for on-screen rendering or "rgb_array" for off-screen rendering + height (int): height of image to render - only used if mode is "rgb_array" + width (int): width of image to render - only used if mode is "rgb_array" + camera_name (str): camera name to use for rendering + """ + if mode == "human": + cam_id = self.env.sim.model.camera_name2id(camera_name) + self.env.viewer.set_camera(cam_id) + return self.env.render() + elif mode == "rgb_array": + im = self.env.sim.render(height=height, width=width, camera_name=camera_name) + if self.use_depth_obs: + # render() returns a tuple when self.use_depth_obs=True + return im[0][::-1] + return im[::-1] + else: + raise NotImplementedError("mode={} is not implemented".format(mode)) + + def get_observation(self, di=None): + """ + Get current environment observation dictionary. + + Args: + di (dict): current raw observation dictionary from robosuite to wrap and provide + as a dictionary. If not provided, will be queried from robosuite. + """ + if di is None: + di = self.env._get_observations(force_update=True) if self._is_v1 else self.env._get_observation() + ret = {} + + for k in di: + if (k in ObsUtils.OBS_KEYS_TO_MODALITIES) and ObsUtils.key_is_obs_modality(key=k, obs_modality="rgb"): + # by default images from mujoco are flipped in height + ret[k] = di[k][::-1] + if self.postprocess_visual_obs: + ret[k] = ObsUtils.process_obs(obs=ret[k], obs_key=k) + elif (k in ObsUtils.OBS_KEYS_TO_MODALITIES) and ObsUtils.key_is_obs_modality(key=k, obs_modality="depth"): + # by default depth images from mujoco are flipped in height + ret[k] = di[k][::-1] + if len(ret[k].shape) == 2: + ret[k] = ret[k][..., None] # (H, W, 1) + assert len(ret[k].shape) == 3 + # scale entries in depth map to correspond to real distance. + ret[k] = self.get_real_depth_map(ret[k]) + if self.postprocess_visual_obs: + ret[k] = ObsUtils.process_obs(obs=ret[k], obs_key=k) + + # "object" key contains object information + ret["object"] = np.array(di["object-state"]) + + if self._is_v1: + for robot in self.env.robots: + # add all robot-arm-specific observations. Note the (k not in ret) check + # ensures that we don't accidentally add robot wrist images a second time + pf = robot.robot_model.naming_prefix + for k in di: + if k.startswith(pf) and (k not in ret) and \ + (not k.endswith("proprio-state")): + ret[k] = np.array(di[k]) + else: + # minimal proprioception for older versions of robosuite + ret["proprio"] = np.array(di["robot-state"]) + ret["eef_pos"] = np.array(di["eef_pos"]) + ret["eef_quat"] = np.array(di["eef_quat"]) + ret["gripper_qpos"] = np.array(di["gripper_qpos"]) + return ret + + def get_real_depth_map(self, depth_map): + """ + Reproduced from https://github.com/ARISE-Initiative/robosuite/blob/c57e282553a4f42378f2635b9a3cbc4afba270fd/robosuite/utils/camera_utils.py#L106 + since older versions of robosuite do not have this conversion from normalized depth values returned by MuJoCo + to real depth values. + """ + # Make sure that depth values are normalized + assert np.all(depth_map >= 0.0) and np.all(depth_map <= 1.0) + extent = self.env.sim.model.stat.extent + far = self.env.sim.model.vis.map.zfar * extent + near = self.env.sim.model.vis.map.znear * extent + return near / (1.0 - depth_map * (1.0 - near / far)) + + def get_camera_intrinsic_matrix(self, camera_name, camera_height, camera_width): + """ + Obtains camera intrinsic matrix. + Args: + camera_name (str): name of camera + camera_height (int): height of camera images in pixels + camera_width (int): width of camera images in pixels + Return: + K (np.array): 3x3 camera matrix + """ + cam_id = self.env.sim.model.camera_name2id(camera_name) + fovy = self.env.sim.model.cam_fovy[cam_id] + f = 0.5 * camera_height / np.tan(fovy * np.pi / 360) + K = np.array([[f, 0, camera_width / 2], [0, f, camera_height / 2], [0, 0, 1]]) + return K + + def get_camera_extrinsic_matrix(self, camera_name): + """ + Returns a 4x4 homogenous matrix corresponding to the camera pose in the + world frame. MuJoCo has a weird convention for how it sets up the + camera body axis, so we also apply a correction so that the x and y + axis are along the camera view and the z axis points along the + viewpoint. + Normal camera convention: https://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html + Args: + camera_name (str): name of camera + Return: + R (np.array): 4x4 camera extrinsic matrix + """ + cam_id = self.env.sim.model.camera_name2id(camera_name) + camera_pos = self.env.sim.data.cam_xpos[cam_id] + camera_rot = self.env.sim.data.cam_xmat[cam_id].reshape(3, 3) + R = T.make_pose(camera_pos, camera_rot) + + # IMPORTANT! This is a correction so that the camera axis is set up along the viewpoint correctly. + camera_axis_correction = np.array( + [[1.0, 0.0, 0.0, 0.0], [0.0, -1.0, 0.0, 0.0], [0.0, 0.0, -1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] + ) + R = R @ camera_axis_correction + return R + + def get_camera_transform_matrix(self, camera_name, camera_height, camera_width): + """ + Camera transform matrix to project from world coordinates to pixel coordinates. + Args: + camera_name (str): name of camera + camera_height (int): height of camera images in pixels + camera_width (int): width of camera images in pixels + Return: + K (np.array): 4x4 camera matrix to project from world coordinates to pixel coordinates + """ + R = self.get_camera_extrinsic_matrix(camera_name=camera_name) + K = self.get_camera_intrinsic_matrix( + camera_name=camera_name, camera_height=camera_height, camera_width=camera_width + ) + K_exp = np.eye(4) + K_exp[:3, :3] = K + + # Takes a point in world, transforms to camera frame, and then projects onto image plane. + return K_exp @ T.pose_inv(R) + + def get_state(self): + """ + Get current environment simulator state as a dictionary. Should be compatible with @reset_to. + """ + xml = self.env.sim.model.get_xml() # model xml file + state = np.array(self.env.sim.get_state().flatten()) # simulator state + return dict(model=xml, states=state) + + def get_reward(self): + """ + Get current reward. + """ + return self.env.reward() + + def get_goal(self): + """ + Get goal observation. Not all environments support this. + """ + return self.get_observation(self.env._get_goal()) + + def set_goal(self, **kwargs): + """ + Set goal observation with external specification. Not all environments support this. + """ + return self.env.set_goal(**kwargs) + + def is_done(self): + """ + Check if the task is done (not necessarily successful). + """ + + # Robosuite envs always rollout to fixed horizon. + return False + + def is_success(self): + """ + Check if the task condition(s) is reached. Should return a dictionary + { str: bool } with at least a "task" key for the overall task success, + and additional optional keys corresponding to other task criteria. + """ + succ = self.env._check_success() + if isinstance(succ, dict): + assert "task" in succ + return succ + return { "task" : succ } + + @property + def action_dimension(self): + """ + Returns dimension of actions (int). + """ + return self.env.action_spec[0].shape[0] + + @property + def name(self): + """ + Returns name of environment name (str). + """ + return self._env_name + + @property + def type(self): + """ + Returns environment type (int) for this kind of environment. + This helps identify this env class. + """ + return EB.EnvType.ROBOSUITE_TYPE + + @property + def version(self): + """ + Returns version of robosuite used for this environment, eg. 1.2.0 + """ + return robosuite.__version__ + + def serialize(self): + """ + Save all information needed to re-instantiate this environment in a dictionary. + This is the same as @env_meta - environment metadata stored in hdf5 datasets, + and used in utils/env_utils.py. + """ + return dict( + env_name=self.name, + env_version=self.version, + type=self.type, + env_kwargs=deepcopy(self._init_kwargs) + ) + + @classmethod + def create_for_data_processing( + cls, + env_name, + camera_names, + camera_height, + camera_width, + reward_shaping, + render=None, + render_offscreen=None, + use_image_obs=None, + use_depth_obs=None, + **kwargs, + ): + """ + Create environment for processing datasets, which includes extracting + observations, labeling dense / sparse rewards, and annotating dones in + transitions. + + Args: + env_name (str): name of environment + camera_names (list of str): list of camera names that correspond to image observations + camera_height (int): camera height for all cameras + camera_width (int): camera width for all cameras + reward_shaping (bool): if True, use shaped environment rewards, else use sparse task completion rewards + render (bool or None): optionally override rendering behavior. Defaults to False. + render_offscreen (bool or None): optionally override rendering behavior. The default value is True if + @camera_names is non-empty, False otherwise. + use_image_obs (bool or None): optionally override rendering behavior. The default value is True if + @camera_names is non-empty, False otherwise. + use_depth_obs (bool): if True, use depth observations + """ + is_v1 = (robosuite.__version__.split(".")[0] == "1") + has_camera = (len(camera_names) > 0) + + new_kwargs = { + "reward_shaping": reward_shaping, + } + + if has_camera: + if is_v1: + new_kwargs["camera_names"] = list(camera_names) + new_kwargs["camera_heights"] = camera_height + new_kwargs["camera_widths"] = camera_width + else: + assert len(camera_names) == 1 + if has_camera: + new_kwargs["camera_name"] = camera_names[0] + new_kwargs["camera_height"] = camera_height + new_kwargs["camera_width"] = camera_width + + kwargs.update(new_kwargs) + + # also initialize obs utils so it knows which modalities are image modalities + image_modalities = list(camera_names) + depth_modalities = list(camera_names) + if is_v1: + image_modalities = ["{}_image".format(cn) for cn in camera_names] + depth_modalities = ["{}_depth".format(cn) for cn in camera_names] + elif has_camera: + # v0.3 only had support for one image, and it was named "image" + assert len(image_modalities) == 1 + image_modalities = ["image"] + depth_modalities = ["depth"] + obs_modality_specs = { + "obs": { + "low_dim": [], # technically unused, so we don't have to specify all of them + "rgb": image_modalities, + } + } + if use_depth_obs: + obs_modality_specs["obs"]["depth"] = depth_modalities + ObsUtils.initialize_obs_utils_with_obs_specs(obs_modality_specs) + + # note that @postprocess_visual_obs is False since this env's images will be written to a dataset + return cls( + env_name=env_name, + render=(False if render is None else render), + render_offscreen=(has_camera if render_offscreen is None else render_offscreen), + use_image_obs=(has_camera if use_image_obs is None else use_image_obs), + use_depth_obs=use_depth_obs, + postprocess_visual_obs=False, + **kwargs, + ) + + @property + def rollout_exceptions(self): + """ + Return tuple of exceptions to except when doing rollouts. This is useful to ensure + that the entire training run doesn't crash because of a bad policy that causes unstable + simulation computations. + """ + return tuple(MUJOCO_EXCEPTIONS) + + @property + def base_env(self): + """ + Grabs base simulation environment. + """ + return self.env + + def __repr__(self): + """ + Pretty-print env description. + """ + return self.name + "\n" + json.dumps(self._init_kwargs, sort_keys=True, indent=4) diff --git a/code_src/rise_robomimic/robomimic/envs/wrappers.py b/code_src/rise_robomimic/robomimic/envs/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..9936f9de70573c78aba8389328b911a139666f05 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/envs/wrappers.py @@ -0,0 +1,220 @@ +""" +A collection of useful environment wrappers. +""" +from copy import deepcopy +import textwrap +import numpy as np +from collections import deque + +import robomimic.envs.env_base as EB + + +class EnvWrapper(object): + """ + Base class for all environment wrappers in robomimic. + """ + def __init__(self, env): + """ + Args: + env (EnvBase instance): The environment to wrap. + """ + assert isinstance(env, EB.EnvBase) or isinstance(env, EnvWrapper) + self.env = env + + @classmethod + def class_name(cls): + return cls.__name__ + + def _warn_double_wrap(self): + """ + Utility function that checks if we're accidentally trying to double wrap an env + Raises: + Exception: [Double wrapping env] + """ + env = self.env + while True: + if isinstance(env, EnvWrapper): + if env.class_name() == self.class_name(): + raise Exception( + "Attempted to double wrap with Wrapper: {}".format( + self.__class__.__name__ + ) + ) + env = env.env + else: + break + + @property + def unwrapped(self): + """ + Grabs unwrapped environment + + Returns: + env (EnvBase instance): Unwrapped environment + """ + if hasattr(self.env, "unwrapped"): + return self.env.unwrapped + else: + return self.env + + def _to_string(self): + """ + Subclasses should override this method to print out info about the + wrapper (such as arguments passed to it). + """ + return '' + + def __repr__(self): + """Pretty print environment.""" + header = '{}'.format(str(self.__class__.__name__)) + msg = '' + indent = ' ' * 4 + if self._to_string() != '': + msg += textwrap.indent("\n" + self._to_string(), indent) + msg += textwrap.indent("\nenv={}".format(self.env), indent) + msg = header + '(' + msg + '\n)' + return msg + + # this method is a fallback option on any methods the original env might support + def __getattr__(self, attr): + # using getattr ensures that both __getattribute__ and __getattr__ (fallback) get called + # (see https://stackoverflow.com/questions/3278077/difference-between-getattr-vs-getattribute) + orig_attr = getattr(self.env, attr) + if callable(orig_attr): + + def hooked(*args, **kwargs): + result = orig_attr(*args, **kwargs) + # prevent wrapped_class from becoming unwrapped + if id(result) == id(self.env): + return self + return result + + return hooked + else: + return orig_attr + + +class FrameStackWrapper(EnvWrapper): + """ + Wrapper for frame stacking observations during rollouts. The agent + receives a sequence of past observations instead of a single observation + when it calls @env.reset, @env.reset_to, or @env.step in the rollout loop. + """ + def __init__(self, env, num_frames): + """ + Args: + env (EnvBase instance): The environment to wrap. + num_frames (int): number of past observations (including current observation) + to stack together. Must be greater than 1 (otherwise this wrapper would + be a no-op). + """ + assert num_frames > 1, "error: FrameStackWrapper must have num_frames > 1 but got num_frames of {}".format(num_frames) + + super(FrameStackWrapper, self).__init__(env=env) + self.num_frames = num_frames + + # keep track of last @num_frames observations for each obs key + self.obs_history = None + + def _get_initial_obs_history(self, init_obs): + """ + Helper method to get observation history from the initial observation, by + repeating it. + + Returns: + obs_history (dict): a deque for each observation key, with an extra + leading dimension of 1 for each key (for easy concatenation later) + """ + obs_history = {} + for k in init_obs: + obs_history[k] = deque( + [init_obs[k][None] for _ in range(self.num_frames)], + maxlen=self.num_frames, + ) + return obs_history + + def _get_stacked_obs_from_history(self): + """ + Helper method to convert internal variable @self.obs_history to a + stacked observation where each key is a numpy array with leading dimension + @self.num_frames. + """ + # concatenate all frames per key so we return a numpy array per key + return { k : np.concatenate(self.obs_history[k], axis=0) for k in self.obs_history } + + def cache_obs_history(self): + self.obs_history_cache = deepcopy(self.obs_history) + + def uncache_obs_history(self): + self.obs_history = self.obs_history_cache + self.obs_history_cache = None + + def reset(self): + """ + Modify to return frame stacked observation which is @self.num_frames copies of + the initial observation. + + Returns: + obs_stacked (dict): each observation key in original observation now has + leading shape @self.num_frames and consists of the previous @self.num_frames + observations + """ + obs = self.env.reset() + self.timestep = 0 # always zero regardless of timestep type + self.update_obs(obs, reset=True) + self.obs_history = self._get_initial_obs_history(init_obs=obs) + return self._get_stacked_obs_from_history() + + def reset_to(self, state): + """ + Modify to return frame stacked observation which is @self.num_frames copies of + the initial observation. + + Returns: + obs_stacked (dict): each observation key in original observation now has + leading shape @self.num_frames and consists of the previous @self.num_frames + observations + """ + obs = self.env.reset_to(state) + self.timestep = 0 # always zero regardless of timestep type + self.update_obs(obs, reset=True) + self.obs_history = self._get_initial_obs_history(init_obs=obs) + return self._get_stacked_obs_from_history() + + def step(self, action): + """ + Modify to update the internal frame history and return frame stacked observation, + which will have leading dimension @self.num_frames for each key. + + Args: + action (np.array): action to take + + Returns: + obs_stacked (dict): each observation key in original observation now has + leading shape @self.num_frames and consists of the previous @self.num_frames + observations + reward (float): reward for this step + done (bool): whether the task is done + info (dict): extra information + """ + obs, r, done, info = self.env.step(action) + self.update_obs(obs, action=action, reset=False) + # update frame history + for k in obs: + # make sure to have leading dim of 1 for easy concatenation + self.obs_history[k].append(obs[k][None]) + obs_ret = self._get_stacked_obs_from_history() + return obs_ret, r, done, info + + def update_obs(self, obs, action=None, reset=False): + obs["timesteps"] = np.array([self.timestep]) + + if reset: + obs["actions"] = np.zeros(self.env.action_dimension) + else: + self.timestep += 1 + obs["actions"] = action[: self.env.action_dimension] + + def _to_string(self): + """Info to pretty print.""" + return "num_frames={}".format(self.num_frames) \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_dense/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_dense/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..dc98a74486a6b8a6746ef146edbbf682783afd39 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_dense/bc.json @@ -0,0 +1,236 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_can_mg_image_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/image_dense_v141.hdf5", + "output_dir": "experiments/core/bc/can/mg/image_dense/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_dense/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_dense/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..90f3550fa44061ae555eaed9269f7e195d4104ba --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_dense/bc_rnn.json @@ -0,0 +1,233 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_can_mg_image_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/image_dense_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/can/mg/image_dense/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 1000, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_dense/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_dense/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..16cd5bc17c45e56346834083c87c9596c3925961 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_dense/bcq.json @@ -0,0 +1,256 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_can_mg_image_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/image_dense_v141.hdf5", + "output_dir": "experiments/core/bcq/can/mg/image_dense/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_dense/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_dense/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..8a6247992abcf5dbb2a579f60be1fa931bac9f93 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_dense/cql.json @@ -0,0 +1,203 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_can_mg_image_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/image_dense_v141.hdf5", + "output_dir": "experiments/core/cql/can/mg/image_dense/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 8, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_sparse/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_sparse/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..9f71cbb1ab49fa108b74300635b3cd7ef9d70058 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_sparse/bc.json @@ -0,0 +1,236 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_can_mg_image_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/image_sparse_v141.hdf5", + "output_dir": "experiments/core/bc/can/mg/image_sparse/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_sparse/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_sparse/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..6d23d548fe31c701e72bd0f14bd2086dfba4f20b --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_sparse/bc_rnn.json @@ -0,0 +1,233 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_can_mg_image_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/image_sparse_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/can/mg/image_sparse/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 1000, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_sparse/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_sparse/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..043c055b81fb3c5991b2d705414f618b44dc3dd3 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_sparse/bcq.json @@ -0,0 +1,256 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_can_mg_image_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/image_sparse_v141.hdf5", + "output_dir": "experiments/core/bcq/can/mg/image_sparse/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_sparse/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_sparse/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..fedb4401bc0d143fdeb13773ffa3ba8e57dc9d34 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/image_sparse/cql.json @@ -0,0 +1,203 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_can_mg_image_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/image_sparse_v141.hdf5", + "output_dir": "experiments/core/cql/can/mg/image_sparse/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 8, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..47c95d11c22a3adfb8bbf9cc81fc02ffd69cb0d9 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/bc.json @@ -0,0 +1,215 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_can_mg_low_dim_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/low_dim_dense_v141.hdf5", + "output_dir": "experiments/core/bc/can/mg/low_dim_dense/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..3ffc37ed005d97288dd677b49e91567712bfa81c --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/bc_rnn.json @@ -0,0 +1,212 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_can_mg_low_dim_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/low_dim_dense_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/can/mg/low_dim_dense/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..b148eee04391c8ec6bab17b65fe8e6fc3fa485b4 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/bcq.json @@ -0,0 +1,235 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_can_mg_low_dim_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/low_dim_dense_v141.hdf5", + "output_dir": "experiments/core/bcq/can/mg/low_dim_dense/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": true, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..231595e3dabefd3811fadf306a9ad4839fb66610 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/cql.json @@ -0,0 +1,182 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_can_mg_low_dim_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/low_dim_dense_v141.hdf5", + "output_dir": "experiments/core/cql/can/mg/low_dim_dense/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 1024, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0003, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/hbc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/hbc.json new file mode 100644 index 0000000000000000000000000000000000000000..a1e48fdc085fd1e214406d80055adb7cfc5a3758 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/hbc.json @@ -0,0 +1,293 @@ +{ + "algo_name": "hbc", + "experiment": { + "name": "core_hbc_can_mg_low_dim_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/low_dim_dense_v141.hdf5", + "output_dir": "experiments/core/hbc/can/mg/low_dim_dense/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 100, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/iris.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/iris.json new file mode 100644 index 0000000000000000000000000000000000000000..99727e5e66e861fb2aabe451f397fac83d092ca5 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_dense/iris.json @@ -0,0 +1,462 @@ +{ + "algo_name": "iris", + "experiment": { + "name": "core_iris_can_mg_low_dim_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/low_dim_dense_v141.hdf5", + "output_dir": "experiments/core/iris/can/mg/low_dim_dense/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "value_planner": { + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "value": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 300, + 400 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": true, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "num_samples": 100 + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "value_planner": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "value": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..b5dc32e5fc4580a5b643a76f1d578b1ef6ddd857 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/bc.json @@ -0,0 +1,215 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_can_mg_low_dim_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/low_dim_sparse_v141.hdf5", + "output_dir": "experiments/core/bc/can/mg/low_dim_sparse/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..6c732f83755879ef0018364cba4e36dabe5e914a --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/bc_rnn.json @@ -0,0 +1,212 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_can_mg_low_dim_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/low_dim_sparse_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/can/mg/low_dim_sparse/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..6bf18b5932e561e37142e38253a31af6b4bbd9c2 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/bcq.json @@ -0,0 +1,235 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_can_mg_low_dim_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/low_dim_sparse_v141.hdf5", + "output_dir": "experiments/core/bcq/can/mg/low_dim_sparse/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": true, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..d47d7fcdf2295075aaef0bb7c88bb87a9a888faa --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/cql.json @@ -0,0 +1,182 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_can_mg_low_dim_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/low_dim_sparse_v141.hdf5", + "output_dir": "experiments/core/cql/can/mg/low_dim_sparse/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 1024, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0003, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/hbc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/hbc.json new file mode 100644 index 0000000000000000000000000000000000000000..98b63f2b73ba0bd0cead60fc874f19b3719a9605 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/hbc.json @@ -0,0 +1,293 @@ +{ + "algo_name": "hbc", + "experiment": { + "name": "core_hbc_can_mg_low_dim_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/low_dim_sparse_v141.hdf5", + "output_dir": "experiments/core/hbc/can/mg/low_dim_sparse/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 100, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/iris.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/iris.json new file mode 100644 index 0000000000000000000000000000000000000000..fb681090c8413dc69b82f4938913c98d73d5428c --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mg/low_dim_sparse/iris.json @@ -0,0 +1,462 @@ +{ + "algo_name": "iris", + "experiment": { + "name": "core_iris_can_mg_low_dim_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mg/low_dim_sparse_v141.hdf5", + "output_dir": "experiments/core/iris/can/mg/low_dim_sparse/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "value_planner": { + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "value": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 300, + 400 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": true, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "num_samples": 100 + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "value_planner": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "value": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/image/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/image/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..69122768a8b9634857a5d008363319eb13e84fa9 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/image/bc.json @@ -0,0 +1,236 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_can_mh_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mh/image_v141.hdf5", + "output_dir": "experiments/core/bc/can/mh/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/image/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/image/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..4cba9ac2a1f1d10f9051a22de3c35035e4132b5e --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/image/bc_rnn.json @@ -0,0 +1,233 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_can_mh_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mh/image_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/can/mh/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 1000, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/image/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/image/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..0a18da02e523cdbb8b3136f6debdd61568d1128f --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/image/bcq.json @@ -0,0 +1,256 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_can_mh_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mh/image_v141.hdf5", + "output_dir": "experiments/core/bcq/can/mh/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 1024, + 1024 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.05, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/image/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/image/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..49d589817f13d6416e3d09f7d0681e5138a3a1e7 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/image/cql.json @@ -0,0 +1,203 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_can_mh_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mh/image_v141.hdf5", + "output_dir": "experiments/core/cql/can/mh/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 8, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..4df11ce8696ea8352d1334c96bc8cd0b32333c6f --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/bc.json @@ -0,0 +1,215 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_can_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/bc/can/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..08db26d69ce40fa4d7f4bf83f13b50bdf32e1082 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/bc_rnn.json @@ -0,0 +1,212 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_can_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/can/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..9ce68fdb0a810024cbcbd1340da45a506c4e96e3 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/bcq.json @@ -0,0 +1,235 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_can_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/bcq/can/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 1024, + 1024 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..6d57ebf461485251088cd948dc11b0c9ce70d5b6 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/cql.json @@ -0,0 +1,182 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_can_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/cql/can/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 1024, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0003, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/hbc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/hbc.json new file mode 100644 index 0000000000000000000000000000000000000000..4ebe4907f1d495e31edb56fdc8af21a712f912a1 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/hbc.json @@ -0,0 +1,290 @@ +{ + "algo_name": "hbc", + "experiment": { + "name": "core_hbc_can_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/hbc/can/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/iris.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/iris.json new file mode 100644 index 0000000000000000000000000000000000000000..a90f1c3141e6c7bd8001ec4c2992a3c167a4b93d --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/mh/low_dim/iris.json @@ -0,0 +1,462 @@ +{ + "algo_name": "iris", + "experiment": { + "name": "core_iris_can_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/iris/can/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "value_planner": { + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "value": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 300, + 400 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.05, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "num_samples": 100 + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "value_planner": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "value": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/image/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/image/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..5a2cf95c9c6d5e499bf482a26f3814e6c5ec1710 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/image/bc.json @@ -0,0 +1,236 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_can_paired_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/paired/image_v141.hdf5", + "output_dir": "experiments/core/bc/can/paired/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/image/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/image/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..0797bcb625c75041bf91f428286bed9649651a8f --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/image/bc_rnn.json @@ -0,0 +1,233 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_can_paired_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/paired/image_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/can/paired/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 1000, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/image/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/image/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..4483e1ae843b52db3ebd467c4f20ff2e4563a0b6 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/image/bcq.json @@ -0,0 +1,256 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_can_paired_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/paired/image_v141.hdf5", + "output_dir": "experiments/core/bcq/can/paired/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 1024, + 1024 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.05, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/image/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/image/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..84fc1b075110731c63894b676a41c39da417d884 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/image/cql.json @@ -0,0 +1,203 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_can_paired_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/paired/image_v141.hdf5", + "output_dir": "experiments/core/cql/can/paired/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 8, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..b81afb4edb4e010764f5252a297a8919e2ad41ab --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/bc.json @@ -0,0 +1,215 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_can_paired_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/paired/low_dim_v141.hdf5", + "output_dir": "experiments/core/bc/can/paired/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..41365aaebdb1f192dc93b0b28a1eab6dd55e7223 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/bc_rnn.json @@ -0,0 +1,212 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_can_paired_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/paired/low_dim_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/can/paired/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..c4ff7ddce48819b202a9ec7d6e6cad6bdf117ad3 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/bcq.json @@ -0,0 +1,235 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_can_paired_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/paired/low_dim_v141.hdf5", + "output_dir": "experiments/core/bcq/can/paired/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 1024, + 1024 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..fb0c9bbe7215ac69ed6ee91e57bd12fdfacce281 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/cql.json @@ -0,0 +1,182 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_can_paired_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/paired/low_dim_v141.hdf5", + "output_dir": "experiments/core/cql/can/paired/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 1024, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0003, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/hbc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/hbc.json new file mode 100644 index 0000000000000000000000000000000000000000..332e64dffb6a2aafbd9a4644415ca7a00d538783 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/hbc.json @@ -0,0 +1,290 @@ +{ + "algo_name": "hbc", + "experiment": { + "name": "core_hbc_can_paired_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/paired/low_dim_v141.hdf5", + "output_dir": "experiments/core/hbc/can/paired/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/iris.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/iris.json new file mode 100644 index 0000000000000000000000000000000000000000..c7edfd126124ecced3ac4950582262512e371560 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/paired/low_dim/iris.json @@ -0,0 +1,462 @@ +{ + "algo_name": "iris", + "experiment": { + "name": "core_iris_can_paired_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/paired/low_dim_v141.hdf5", + "output_dir": "experiments/core/iris/can/paired/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "value_planner": { + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "value": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 300, + 400 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.05, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "num_samples": 100 + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "value_planner": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "value": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/image/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/image/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..0909c65373b2457d145fda8ce9cc72fda35a2e03 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/image/bc.json @@ -0,0 +1,236 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_can_ph_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/ph/image_v141.hdf5", + "output_dir": "experiments/core/bc/can/ph/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/image/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/image/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..92790f0fcd82d84c93b84f93d6680756b1a1a090 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/image/bc_rnn.json @@ -0,0 +1,233 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_can_ph_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/ph/image_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/can/ph/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 1000, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/image/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/image/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..ef317e03cf912251b13b814ce7af33c27d5d6d84 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/image/bcq.json @@ -0,0 +1,256 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_can_ph_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/ph/image_v141.hdf5", + "output_dir": "experiments/core/bcq/can/ph/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.05, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/image/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/image/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..1d768b820e82ece32316d60297e3e8e970f1ac75 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/image/cql.json @@ -0,0 +1,203 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_can_ph_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/ph/image_v141.hdf5", + "output_dir": "experiments/core/cql/can/ph/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 8, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..08d9f84473f7a7544a55fe9137b9b1f7057be6ec --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/bc.json @@ -0,0 +1,215 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_can_ph_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/ph/low_dim_v141.hdf5", + "output_dir": "experiments/core/bc/can/ph/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..fdf60c2a7a6c928813b62c65f212fc1b17b6c5dd --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/bc_rnn.json @@ -0,0 +1,212 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_can_ph_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/ph/low_dim_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/can/ph/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..fa8a7d4502f3e05ff448110a3b64fa1fd040c945 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/bcq.json @@ -0,0 +1,235 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_can_ph_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/ph/low_dim_v141.hdf5", + "output_dir": "experiments/core/bcq/can/ph/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.05, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..cb3d60bcc6908cf71f412e936f1c97544d21223b --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/cql.json @@ -0,0 +1,182 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_can_ph_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/ph/low_dim_v141.hdf5", + "output_dir": "experiments/core/cql/can/ph/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 1024, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0003, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/hbc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/hbc.json new file mode 100644 index 0000000000000000000000000000000000000000..a44f56f4d18525fe15073b0c8ef9ca595ef9107b --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/hbc.json @@ -0,0 +1,290 @@ +{ + "algo_name": "hbc", + "experiment": { + "name": "core_hbc_can_ph_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/ph/low_dim_v141.hdf5", + "output_dir": "experiments/core/hbc/can/ph/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/iris.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/iris.json new file mode 100644 index 0000000000000000000000000000000000000000..4e5803309bf4e1f41ada741bb915212c9fb1ee69 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can/ph/low_dim/iris.json @@ -0,0 +1,462 @@ +{ + "algo_name": "iris", + "experiment": { + "name": "core_iris_can_ph_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can/ph/low_dim_v141.hdf5", + "output_dir": "experiments/core/iris/can/ph/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "value_planner": { + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "value": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 300, + 400 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "num_samples": 100 + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "value_planner": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "value": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/can_real/ph/raw/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/can_real/ph/raw/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..f553da644e6e80951373c662f066b24fd778e3f8 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/can_real/ph/raw/bc_rnn.json @@ -0,0 +1,232 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_can_real_ph_raw", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": false, + "n": 50, + "horizon": 1000, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/can_real/ph/demo.hdf5", + "output_dir": "experiments/core/bc_rnn/can_real/ph/raw/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 1000, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "ee_pose", + "gripper_position" + ], + "rgb": [ + "image", + "image_wrist" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 108, + "crop_width": 108, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_dense/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_dense/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..70ac97d06b9ab432bf34244483b39f5050363d75 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_dense/bc.json @@ -0,0 +1,236 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_lift_mg_image_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/image_dense_v141.hdf5", + "output_dir": "experiments/core/bc/lift/mg/image_dense/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_dense/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_dense/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..2b7f720a616e2569255d6e7a9ecb703641ee9338 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_dense/bc_rnn.json @@ -0,0 +1,233 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_lift_mg_image_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/image_dense_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/lift/mg/image_dense/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 1000, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_dense/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_dense/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..75cf45fb1165aed7ee4efdda4b65d26870c8fb97 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_dense/bcq.json @@ -0,0 +1,256 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_lift_mg_image_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/image_dense_v141.hdf5", + "output_dir": "experiments/core/bcq/lift/mg/image_dense/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_dense/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_dense/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..5c1b6db8cd2e284d118b186ab0daa4b0c58ce21e --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_dense/cql.json @@ -0,0 +1,203 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_lift_mg_image_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/image_dense_v141.hdf5", + "output_dir": "experiments/core/cql/lift/mg/image_dense/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 8, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_sparse/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_sparse/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..f70b22f061725e382b684cf5c8287a7c2295365a --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_sparse/bc.json @@ -0,0 +1,236 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_lift_mg_image_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/image_sparse_v141.hdf5", + "output_dir": "experiments/core/bc/lift/mg/image_sparse/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_sparse/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_sparse/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..4dd0edf188de6ba1bd8873cb698933ca6439cbf9 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_sparse/bc_rnn.json @@ -0,0 +1,233 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_lift_mg_image_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/image_sparse_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/lift/mg/image_sparse/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 1000, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_sparse/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_sparse/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..87995e28b28a069adf8d23a459fff9bc6784ed5f --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_sparse/bcq.json @@ -0,0 +1,256 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_lift_mg_image_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/image_sparse_v141.hdf5", + "output_dir": "experiments/core/bcq/lift/mg/image_sparse/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_sparse/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_sparse/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..62c6dede8eee7da771e78715044d715c4134bd4f --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/image_sparse/cql.json @@ -0,0 +1,203 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_lift_mg_image_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/image_sparse_v141.hdf5", + "output_dir": "experiments/core/cql/lift/mg/image_sparse/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 8, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..27abab3c7762263854ebc7e8b8ed0a5857081599 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/bc.json @@ -0,0 +1,215 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_lift_mg_low_dim_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/low_dim_dense_v141.hdf5", + "output_dir": "experiments/core/bc/lift/mg/low_dim_dense/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..a2885289e66827fd71b9d204c99d70fed563b207 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/bc_rnn.json @@ -0,0 +1,212 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_lift_mg_low_dim_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/low_dim_dense_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/lift/mg/low_dim_dense/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..dd711f50a088d0530e349630dd7390c9dc29e1c2 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/bcq.json @@ -0,0 +1,235 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_lift_mg_low_dim_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/low_dim_dense_v141.hdf5", + "output_dir": "experiments/core/bcq/lift/mg/low_dim_dense/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": true, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..19957199522b22b01e0ed5a83c5d2b57734acaa7 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/cql.json @@ -0,0 +1,182 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_lift_mg_low_dim_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/low_dim_dense_v141.hdf5", + "output_dir": "experiments/core/cql/lift/mg/low_dim_dense/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 1024, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0003, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/hbc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/hbc.json new file mode 100644 index 0000000000000000000000000000000000000000..9dd9baecd41a4d37a861071b52a7f4daa4958d84 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/hbc.json @@ -0,0 +1,293 @@ +{ + "algo_name": "hbc", + "experiment": { + "name": "core_hbc_lift_mg_low_dim_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/low_dim_dense_v141.hdf5", + "output_dir": "experiments/core/hbc/lift/mg/low_dim_dense/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 100, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/iris.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/iris.json new file mode 100644 index 0000000000000000000000000000000000000000..0b0dddcc42b026501b4590b035b199962d317707 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_dense/iris.json @@ -0,0 +1,462 @@ +{ + "algo_name": "iris", + "experiment": { + "name": "core_iris_lift_mg_low_dim_dense", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/low_dim_dense_v141.hdf5", + "output_dir": "experiments/core/iris/lift/mg/low_dim_dense/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "value_planner": { + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "value": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 300, + 400 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": true, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "num_samples": 100 + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "value_planner": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "value": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..570042bd0c8cf32bffd6167cacc855900f580844 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/bc.json @@ -0,0 +1,215 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_lift_mg_low_dim_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/low_dim_sparse_v141.hdf5", + "output_dir": "experiments/core/bc/lift/mg/low_dim_sparse/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..7b90a4e60cae4871e65fa1395509a2098d5a9f44 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/bc_rnn.json @@ -0,0 +1,212 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_lift_mg_low_dim_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/low_dim_sparse_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/lift/mg/low_dim_sparse/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..f7f73393bd9bf929115b6dbdfa594e73fca9e2be --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/bcq.json @@ -0,0 +1,235 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_lift_mg_low_dim_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/low_dim_sparse_v141.hdf5", + "output_dir": "experiments/core/bcq/lift/mg/low_dim_sparse/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": true, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..e5b60e061a15268807a9f4a0cd480268cc50fea8 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/cql.json @@ -0,0 +1,182 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_lift_mg_low_dim_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/low_dim_sparse_v141.hdf5", + "output_dir": "experiments/core/cql/lift/mg/low_dim_sparse/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 1024, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0003, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/hbc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/hbc.json new file mode 100644 index 0000000000000000000000000000000000000000..8326003568f871973be8161225e1f7a0af59db92 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/hbc.json @@ -0,0 +1,293 @@ +{ + "algo_name": "hbc", + "experiment": { + "name": "core_hbc_lift_mg_low_dim_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/low_dim_sparse_v141.hdf5", + "output_dir": "experiments/core/hbc/lift/mg/low_dim_sparse/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 100, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/iris.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/iris.json new file mode 100644 index 0000000000000000000000000000000000000000..4a0245b8234df4f658ce3dd017aa98acd8e92b87 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mg/low_dim_sparse/iris.json @@ -0,0 +1,462 @@ +{ + "algo_name": "iris", + "experiment": { + "name": "core_iris_lift_mg_low_dim_sparse", + "validate": false, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mg/low_dim_sparse_v141.hdf5", + "output_dir": "experiments/core/iris/lift/mg/low_dim_sparse/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": null, + "hdf5_validation_filter_key": null, + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "value_planner": { + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "value": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 300, + 400 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": true, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "num_samples": 100 + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "value_planner": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "value": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/image/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/image/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..61f282f8871c2cba5e487bd2ab6334b5bcc47706 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/image/bc.json @@ -0,0 +1,236 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_lift_mh_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mh/image_v141.hdf5", + "output_dir": "experiments/core/bc/lift/mh/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/image/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/image/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..a2433bb084514829e941e6131ca7d4b4bef7b955 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/image/bc_rnn.json @@ -0,0 +1,233 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_lift_mh_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mh/image_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/lift/mh/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 1000, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/image/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/image/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..a53558c48f2108b92e8fb0dd835baa6689f274a3 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/image/bcq.json @@ -0,0 +1,256 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_lift_mh_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mh/image_v141.hdf5", + "output_dir": "experiments/core/bcq/lift/mh/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 1024, + 1024 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.05, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/image/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/image/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..e198678928f7fa882daf32ad9c46bc29cb4eee0f --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/image/cql.json @@ -0,0 +1,203 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_lift_mh_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mh/image_v141.hdf5", + "output_dir": "experiments/core/cql/lift/mh/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 8, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..a1ac0eb4028214921704d64370045458eb938d87 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/bc.json @@ -0,0 +1,215 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_lift_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/bc/lift/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..3481ba216419c988f98818573eba998baceaee98 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/bc_rnn.json @@ -0,0 +1,212 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_lift_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/lift/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..abc49d74365a705b1308e94c1dc7fb3dbb3c5875 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/bcq.json @@ -0,0 +1,235 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_lift_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/bcq/lift/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 1024, + 1024 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..55b1b5cbefe1e105f9c16834249fb4a7b3230252 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/cql.json @@ -0,0 +1,182 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_lift_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/cql/lift/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 1024, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0003, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/hbc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/hbc.json new file mode 100644 index 0000000000000000000000000000000000000000..1538d4bb55ae90ea628ebb4a55689de62b170463 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/hbc.json @@ -0,0 +1,290 @@ +{ + "algo_name": "hbc", + "experiment": { + "name": "core_hbc_lift_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/hbc/lift/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/iris.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/iris.json new file mode 100644 index 0000000000000000000000000000000000000000..4afbdae425c7d12f5f237dc63cc2a1e41b774d0b --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/mh/low_dim/iris.json @@ -0,0 +1,462 @@ +{ + "algo_name": "iris", + "experiment": { + "name": "core_iris_lift_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/iris/lift/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "value_planner": { + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "value": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 300, + 400 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.05, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "num_samples": 100 + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "value_planner": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "value": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/image/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/image/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..69bbd4f38dfb56f8734fb8177f803be560a940db --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/image/bc.json @@ -0,0 +1,236 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_lift_ph_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/ph/image_v141.hdf5", + "output_dir": "experiments/core/bc/lift/ph/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/image/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/image/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..fc78eb6f6f525dad0ee15e853a8dd591b6c30400 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/image/bc_rnn.json @@ -0,0 +1,233 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_lift_ph_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/ph/image_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/lift/ph/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 1000, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/image/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/image/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..28931624a29c3239316c332bfe2d96da93afd962 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/image/bcq.json @@ -0,0 +1,256 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_lift_ph_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/ph/image_v141.hdf5", + "output_dir": "experiments/core/bcq/lift/ph/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.05, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/image/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/image/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..def138f6c8dd8d37f6052b1b2f32e31f8b95e3d1 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/image/cql.json @@ -0,0 +1,203 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_lift_ph_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/ph/image_v141.hdf5", + "output_dir": "experiments/core/cql/lift/ph/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 8, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..d5d31362acddb280087de67fdeea35acf7fe208b --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/bc.json @@ -0,0 +1,215 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_lift_ph_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/ph/low_dim_v141.hdf5", + "output_dir": "experiments/core/bc/lift/ph/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..3a686acb60eb4f7f0cd5d47eaf09eb9616f7b15f --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/bc_rnn.json @@ -0,0 +1,212 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_lift_ph_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/ph/low_dim_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/lift/ph/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..d6a579a8fc61a0d64e86b3a1a9f63469e6ce0fc5 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/bcq.json @@ -0,0 +1,235 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_lift_ph_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/ph/low_dim_v141.hdf5", + "output_dir": "experiments/core/bcq/lift/ph/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.05, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..6956a1384c6f0a4ed96c744693fb51ba6b7347d8 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/cql.json @@ -0,0 +1,182 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_lift_ph_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/ph/low_dim_v141.hdf5", + "output_dir": "experiments/core/cql/lift/ph/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 1024, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0003, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/hbc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/hbc.json new file mode 100644 index 0000000000000000000000000000000000000000..09000617acf636c175e318c56d808c633cb85104 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/hbc.json @@ -0,0 +1,290 @@ +{ + "algo_name": "hbc", + "experiment": { + "name": "core_hbc_lift_ph_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/ph/low_dim_v141.hdf5", + "output_dir": "experiments/core/hbc/lift/ph/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/iris.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/iris.json new file mode 100644 index 0000000000000000000000000000000000000000..aa872b20846c651d7e4fe065c1b10bda232b1f65 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift/ph/low_dim/iris.json @@ -0,0 +1,462 @@ +{ + "algo_name": "iris", + "experiment": { + "name": "core_iris_lift_ph_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift/ph/low_dim_v141.hdf5", + "output_dir": "experiments/core/iris/lift/ph/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "value_planner": { + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "value": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 300, + 400 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "num_samples": 100 + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "value_planner": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "value": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/lift_real/ph/raw/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/lift_real/ph/raw/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..d1d7bd66f13d80f92f72707d2b806b8a98c98257 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/lift_real/ph/raw/bc_rnn.json @@ -0,0 +1,232 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_lift_real_ph_raw", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": false, + "n": 50, + "horizon": 1000, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/lift_real/ph/demo.hdf5", + "output_dir": "experiments/core/bc_rnn/lift_real/ph/raw/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 1000, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "ee_pose", + "gripper_position" + ], + "rgb": [ + "image", + "image_wrist" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 108, + "crop_width": 108, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/image/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/image/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..8ac134ff4191c3cc3e602b28e59fd36cb1fac535 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/image/bc.json @@ -0,0 +1,236 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_square_mh_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/square/mh/image_v141.hdf5", + "output_dir": "experiments/core/bc/square/mh/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/image/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/image/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..b5eeb7ddfb98190ee16e0e9fd4ba9bb9c2a219af --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/image/bc_rnn.json @@ -0,0 +1,233 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_square_mh_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/square/mh/image_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/square/mh/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 1000, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/image/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/image/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..a669720db87e084189af4760f793788adf195330 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/image/bcq.json @@ -0,0 +1,256 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_square_mh_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/square/mh/image_v141.hdf5", + "output_dir": "experiments/core/bcq/square/mh/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 1024, + 1024 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.05, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/image/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/image/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..644e2461fb696282059d4354aa37204f5817f42a --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/image/cql.json @@ -0,0 +1,203 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_square_mh_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/square/mh/image_v141.hdf5", + "output_dir": "experiments/core/cql/square/mh/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 8, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..e4bd97aa94c1a83975ea502097ff838ad57acb3a --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/bc.json @@ -0,0 +1,215 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_square_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/square/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/bc/square/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..236eca9eea7f9fbaeeb44ae8bf3f4d13faefa49f --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/bc_rnn.json @@ -0,0 +1,212 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_square_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/square/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/square/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..d0b8a0515d4468eafad6b2979661796730d8e068 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/bcq.json @@ -0,0 +1,235 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_square_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/square/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/bcq/square/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 1024, + 1024 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.5, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/cql.json b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/cql.json new file mode 100644 index 0000000000000000000000000000000000000000..5f33317d95f8b93f2baaec668f29e13436962ff9 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/cql.json @@ -0,0 +1,182 @@ +{ + "algo_name": "cql", + "experiment": { + "name": "core_cql_square_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/square/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/cql/square/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 1024, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + }, + "actor": { + "learning_rate": { + "initial": 0.0003, + "decay_factor": 0.0, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.005, + "actor": { + "bc_start_steps": 0, + "target_entropy": "default", + "max_gradient_norm": null, + "net": { + "type": "gaussian", + "common": { + "std_activation": "exp", + "use_tanh": true, + "low_noise_eval": true + }, + "gaussian": { + "init_last_fc_weight": 0.001, + "init_std": 0.3, + "fixed_std": false + } + }, + "layer_dims": [ + 300, + 400 + ] + }, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 1, + "cql_weight": 1.0, + "deterministic_backup": true, + "min_q_weight": 1.0, + "target_q_gap": 5.0, + "num_random_actions": 10, + "ensemble": { + "n": 2 + }, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/hbc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/hbc.json new file mode 100644 index 0000000000000000000000000000000000000000..5005e6973c009ac2662f26497993544be7592e0b --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/hbc.json @@ -0,0 +1,290 @@ +{ + "algo_name": "hbc", + "experiment": { + "name": "core_hbc_square_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/square/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/hbc/square/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/iris.json b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/iris.json new file mode 100644 index 0000000000000000000000000000000000000000..91227b4e6c9a4b9fe4b987f6b806771aba4dbc43 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/square/mh/low_dim/iris.json @@ -0,0 +1,462 @@ +{ + "algo_name": "iris", + "experiment": { + "name": "core_iris_square_mh_low_dim", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 50, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 100, + "validation_epoch_every_n_steps": 10, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 500, + "rate": 50, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/square/mh/low_dim_v141.hdf5", + "output_dir": "experiments/core/iris/square/mh/low_dim/trained_models", + "num_data_workers": 0, + "hdf5_cache_mode": "all", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 100, + "num_epochs": 2000, + "seed": 1 + }, + "algo": { + "mode": "separate", + "actor_use_random_subgoals": false, + "subgoal_update_interval": 10, + "latent_subgoal": { + "enabled": false, + "prior_correction": { + "enabled": false, + "num_samples": 100 + } + }, + "value_planner": { + "planner": { + "optim_params": { + "goal_network": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + } + } + }, + "subgoal_horizon": 10, + "ae": { + "planner_layer_dims": [ + 300, + 400 + ] + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.0005, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": true, + "is_conditioned": true, + "use_gmm": true, + "gmm_num_modes": 10, + "gmm_learn_weights": true, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 1024, + 1024 + ] + } + }, + "value": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 300, + 400 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 16, + "latent_clip": null, + "kl_weight": 0.05, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "num_samples": 100 + }, + "actor": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + } + }, + "observation": { + "value_planner": { + "planner": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + }, + "subgoal": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "value": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "actor": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos", + "object" + ], + "rgb": [], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/square/ph/image/bc.json b/code_src/rise_robomimic/robomimic/exps/paper/core/square/ph/image/bc.json new file mode 100644 index 0000000000000000000000000000000000000000..26a60e210ed7fc057e65cf211dcfec69a4d28916 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/square/ph/image/bc.json @@ -0,0 +1,236 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_square_ph_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/square/ph/image_v141.hdf5", + "output_dir": "experiments/core/bc/square/ph/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [ + 1024, + 1024 + ], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": false, + "horizon": 10, + "hidden_dim": 400, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/square/ph/image/bc_rnn.json b/code_src/rise_robomimic/robomimic/exps/paper/core/square/ph/image/bc_rnn.json new file mode 100644 index 0000000000000000000000000000000000000000..ff105ad32bdfca7a31a3a0d3d43d22327ae0b81b --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/square/ph/image/bc_rnn.json @@ -0,0 +1,233 @@ +{ + "algo_name": "bc", + "experiment": { + "name": "core_bc_rnn_square_ph_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/square/ph/image_v141.hdf5", + "output_dir": "experiments/core/bc_rnn/square/ph/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": false, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 10, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "policy": { + "optimizer_type": "adam", + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [], + "scheduler_type": "multistep" + }, + "regularization": { + "L2": 0.0 + } + } + }, + "loss": { + "l2_weight": 1.0, + "l1_weight": 0.0, + "cos_weight": 0.0 + }, + "actor_layer_dims": [], + "gaussian": { + "enabled": false, + "fixed_std": false, + "init_std": 0.1, + "min_std": 0.01, + "std_activation": "softplus", + "low_noise_eval": true + }, + "gmm": { + "enabled": true, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": false, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 1.0, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 300, + 400 + ], + "decoder_layer_dims": [ + 300, + 400 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "rnn": { + "enabled": true, + "horizon": 10, + "hidden_dim": 1000, + "rnn_type": "LSTM", + "num_layers": 2, + "open_loop": false, + "kwargs": { + "bidirectional": false + } + }, + "transformer": { + "enabled": false, + "context_length": 10, + "embed_dim": 512, + "num_layers": 6, + "num_heads": 8, + "emb_dropout": 0.1, + "attn_dropout": 0.1, + "block_output_dropout": 0.1, + "sinusoidal_embedding": false, + "activation": "gelu", + "supervise_all_steps": false, + "nn_parameter_for_timesteps": true + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file diff --git a/code_src/rise_robomimic/robomimic/exps/paper/core/square/ph/image/bcq.json b/code_src/rise_robomimic/robomimic/exps/paper/core/square/ph/image/bcq.json new file mode 100644 index 0000000000000000000000000000000000000000..b0cda8875ec0f3a82559328d068893bc30b10b24 --- /dev/null +++ b/code_src/rise_robomimic/robomimic/exps/paper/core/square/ph/image/bcq.json @@ -0,0 +1,256 @@ +{ + "algo_name": "bcq", + "experiment": { + "name": "core_bcq_square_ph_image", + "validate": true, + "logging": { + "terminal_output_to_txt": true, + "log_tb": true, + "log_wandb": false, + "wandb_proj_name": "debug" + }, + "save": { + "enabled": true, + "every_n_seconds": null, + "every_n_epochs": 20, + "epochs": [], + "on_best_validation": false, + "on_best_rollout_return": false, + "on_best_rollout_success_rate": true + }, + "epoch_every_n_steps": 500, + "validation_epoch_every_n_steps": 50, + "env": null, + "additional_envs": null, + "render": false, + "render_video": true, + "keep_all_videos": false, + "video_skip": 5, + "rollout": { + "enabled": true, + "n": 50, + "horizon": 400, + "rate": 20, + "warmstart": 0, + "terminate_on_success": true + } + }, + "train": { + "data": "/home/kevin/ood/robomimic/robomimic/../datasets/square/ph/image_v141.hdf5", + "output_dir": "experiments/core/bcq/square/ph/image/trained_models", + "num_data_workers": 2, + "hdf5_cache_mode": "low_dim", + "hdf5_use_swmr": true, + "hdf5_load_next_obs": true, + "hdf5_normalize_obs": false, + "hdf5_filter_key": "train", + "hdf5_validation_filter_key": "valid", + "seq_length": 1, + "pad_seq_length": true, + "frame_stack": 1, + "pad_frame_stack": true, + "dataset_keys": [ + "actions", + "rewards", + "dones" + ], + "goal_mode": null, + "cuda": true, + "batch_size": 16, + "num_epochs": 600, + "seed": 1 + }, + "algo": { + "optim_params": { + "critic": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "action_sampler": { + "learning_rate": { + "initial": 0.0001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + }, + "actor": { + "learning_rate": { + "initial": 0.001, + "decay_factor": 0.1, + "epoch_schedule": [] + }, + "regularization": { + "L2": 0.0 + }, + "start_epoch": -1, + "end_epoch": -1 + } + }, + "discount": 0.99, + "n_step": 1, + "target_tau": 0.0005, + "infinite_horizon": false, + "critic": { + "use_huber": false, + "max_gradient_norm": null, + "value_bounds": null, + "num_action_samples": 10, + "num_action_samples_rollout": 100, + "ensemble": { + "n": 2, + "weight": 0.75 + }, + "distributional": { + "enabled": false, + "num_atoms": 51 + }, + "layer_dims": [ + 300, + 400 + ] + }, + "action_sampler": { + "actor_layer_dims": [ + 1024, + 1024 + ], + "gmm": { + "enabled": false, + "num_modes": 5, + "min_std": 0.0001, + "std_activation": "softplus", + "low_noise_eval": true + }, + "vae": { + "enabled": true, + "latent_dim": 14, + "latent_clip": null, + "kl_weight": 0.05, + "decoder": { + "is_conditioned": true, + "reconstruction_sum_across_elements": false + }, + "prior": { + "learn": false, + "is_conditioned": false, + "use_gmm": false, + "gmm_num_modes": 10, + "gmm_learn_weights": false, + "use_categorical": false, + "categorical_dim": 10, + "categorical_gumbel_softmax_hard": false, + "categorical_init_temp": 1.0, + "categorical_temp_anneal_step": 0.001, + "categorical_min_temp": 0.3 + }, + "encoder_layer_dims": [ + 1024, + 1024 + ], + "decoder_layer_dims": [ + 1024, + 1024 + ], + "prior_layer_dims": [ + 300, + 400 + ] + }, + "freeze_encoder_epoch": -1 + }, + "actor": { + "enabled": false, + "perturbation_scale": 0.05, + "layer_dims": [ + 300, + 400 + ] + } + }, + "observation": { + "modalities": { + "obs": { + "low_dim": [ + "robot0_eef_pos", + "robot0_eef_quat", + "robot0_gripper_qpos" + ], + "rgb": [ + "agentview_image", + "robot0_eye_in_hand_image" + ], + "depth": [], + "scan": [] + }, + "goal": { + "low_dim": [], + "rgb": [], + "depth": [], + "scan": [] + } + }, + "encoder": { + "low_dim": { + "core_class": null, + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "rgb": { + "core_class": "VisualCore", + "core_kwargs": { + "feature_dimension": 64, + "backbone_class": "ResNet18Conv", + "backbone_kwargs": { + "pretrained": false, + "input_coord_conv": false + }, + "pool_class": "SpatialSoftmax", + "pool_kwargs": { + "num_kp": 32, + "learnable_temperature": false, + "temperature": 1.0, + "noise_std": 0.0 + } + }, + "obs_randomizer_class": "CropRandomizer", + "obs_randomizer_kwargs": { + "crop_height": 76, + "crop_width": 76, + "num_crops": 1, + "pos_enc": false + } + }, + "depth": { + "core_class": "VisualCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + }, + "scan": { + "core_class": "ScanCore", + "core_kwargs": {}, + "obs_randomizer_class": null, + "obs_randomizer_kwargs": {} + } + } + }, + "meta": { + "hp_base_config_file": null, + "hp_keys": [], + "hp_values": [] + } +} \ No newline at end of file