souglad21 commited on
Commit
f9e7c90
·
verified ·
1 Parent(s): 6f870cd

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. real_inference/check_fixture.py +42 -0
  2. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/json_logger.py +115 -0
  3. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/pose_trajectory_interpolator.py +211 -0
  4. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/precise_sleep.py +27 -0
  5. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/pymunk_override.py +246 -0
  6. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/pymunk_util.py +51 -0
  7. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/pytorch_util.py +79 -0
  8. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/robomimic_util.py +170 -0
  9. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/sampler.py +164 -0
  10. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/config/robot_dp.yaml +154 -0
  11. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/config/task/aloha_garment.yaml +51 -0
  12. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/config/task/default_task.yaml +50 -0
  13. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/dataset/base_dataset.py +54 -0
  14. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/dataset/robot_image_dataset.py +194 -0
  15. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/action_ae/__init__.py +64 -0
  16. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/action_ae/discretizers/k_means.py +136 -0
  17. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/latent_generators/latent_generator.py +67 -0
  18. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/latent_generators/mingpt.py +177 -0
  19. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/latent_generators/transformer.py +99 -0
  20. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/loss_fn.py +165 -0
  21. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/mingpt/LICENSE +8 -0
  22. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/mingpt/__init__.py +0 -0
  23. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/mingpt/model.py +231 -0
  24. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/mingpt/trainer.py +145 -0
  25. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/mingpt/utils.py +49 -0
  26. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/utils.py +130 -0
  27. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/common/dict_of_tensor_mixin.py +50 -0
  28. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/common/lr_scheduler.py +55 -0
  29. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/common/module_attr_mixin.py +16 -0
  30. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/common/normalizer.py +369 -0
  31. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/common/rotation_transformer.py +97 -0
  32. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/common/shape_util.py +22 -0
  33. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/common/tensor_util.py +972 -0
  34. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/conditional_unet1d.py +278 -0
  35. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/conv1d_components.py +51 -0
  36. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/ema_model.py +89 -0
  37. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/mask_generator.py +225 -0
  38. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/positional_embedding.py +19 -0
  39. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/transformer_for_diffusion.py +391 -0
  40. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/vision/crop_randomizer.py +298 -0
  41. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/vision/model_getter.py +36 -0
  42. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/vision/multi_image_obs_encoder.py +191 -0
  43. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/policy/base_image_policy.py +26 -0
  44. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/policy/diffusion_unet_image_policy.py +258 -0
  45. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/shared_memory/shared_memory_queue.py +184 -0
  46. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/shared_memory/shared_memory_ring_buffer.py +213 -0
  47. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/shared_memory/shared_memory_util.py +38 -0
  48. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/shared_memory/shared_ndarray.py +161 -0
  49. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/workspace/base_workspace.py +138 -0
  50. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/workspace/robotworkspace.py +350 -0
real_inference/check_fixture.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Model-only test against one recorded RGB observation; never controls hardware."""
3
+ import argparse
4
+ import os
5
+ from pathlib import Path
6
+ import sys
7
+ import numpy as np
8
+
9
+ root=Path(__file__).resolve().parent
10
+ parser=argparse.ArgumentParser()
11
+ parser.add_argument('policy',choices=('act','dp','pi05'))
12
+ args=parser.parse_args()
13
+ if args.policy=='pi05':
14
+ import logging
15
+ logging.basicConfig(level=logging.INFO)
16
+ src=root/'source/XPolicyLab'
17
+ sys.path.insert(0,str(root/'reference'))
18
+ sys.path.insert(0,str(src/'policy/Pi_05/openpi/src'))
19
+ sys.path.insert(0,str(src/'policy/Pi_05/openpi/packages/openpi-client/src'))
20
+ os.environ['ALOHA_ACT_CHECKPOINT_DIR']=str(root/'models/act')
21
+ os.environ['ALOHA_DP_CHECKPOINT']=str(root/'models/dp/10.ckpt')
22
+ os.environ['ALOHA_PI05_CHECKPOINT']=str(root/'models/pi05/29999')
23
+ os.environ['OPENPI_DATA_HOME']=str(root/'models/shared/openpi')
24
+ os.environ['TORCH_HOME']=str(root/'models/shared/torch')
25
+ os.environ.setdefault('XLA_PYTHON_CLIENT_PREALLOCATE','false')
26
+
27
+ from deform_manip_sim.policy.schema import Observation
28
+ import deform_manip_sim.policy.aloha.adapters as adapters
29
+ adapters.ROOT=src
30
+ with np.load(root/'fixtures/0041_episode0_frame100.npz') as data:
31
+ images={name:data[name].copy() for name in adapters.CAMERAS}
32
+ obs=Observation(timestamp_ns=0,episode_step=100,instruction='Fold the garment.',
33
+ images=images,qpos=data['qpos'].copy(),ee_pose=np.zeros(14,np.float32))
34
+ target=data['recorded_next_qpos'].copy()
35
+ adapter={'act':adapters.ACTAdapter,'dp':adapters.DPAdapter,'pi05':adapters.Pi05Adapter}[args.policy]()
36
+ result=adapter(obs)
37
+ expected={'act':(50,14),'dp':(6,14),'pi05':(50,14)}[args.policy]
38
+ if result.actions.shape!=expected or not np.isfinite(result.actions).all():
39
+ raise ValueError(f'Invalid output {result.actions.shape}; expected {expected}, all finite')
40
+ print(f'OK policy={args.policy} actions={result.actions.shape} dt={result.dt} diagnostics={result.diagnostics}')
41
+ print('First-action RMSE vs recorded next qpos:',float(np.sqrt(np.mean((result.actions[0]-target)**2))))
42
+ print('The recorded action is not necessarily a unique ground truth for model evaluation.')
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/json_logger.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Callable, Any, Sequence
2
+ import os
3
+ import copy
4
+ import json
5
+ import numbers
6
+ import pandas as pd
7
+
8
+
9
+ def read_json_log(path: str, required_keys: Sequence[str] = tuple(), **kwargs) -> pd.DataFrame:
10
+ """
11
+ Read json-per-line file, with potentially incomplete lines.
12
+ kwargs passed to pd.read_json
13
+ """
14
+ lines = list()
15
+ with open(path, "r") as f:
16
+ while True:
17
+ # one json per line
18
+ line = f.readline()
19
+ if len(line) == 0:
20
+ # EOF
21
+ break
22
+ elif not line.endswith("\n"):
23
+ # incomplete line
24
+ break
25
+ is_relevant = False
26
+ for k in required_keys:
27
+ if k in line:
28
+ is_relevant = True
29
+ break
30
+ if is_relevant:
31
+ lines.append(line)
32
+ if len(lines) < 1:
33
+ return pd.DataFrame()
34
+ json_buf = (f'[{",".join([line for line in (line.strip() for line in lines) if line])}]')
35
+ df = pd.read_json(json_buf, **kwargs)
36
+ return df
37
+
38
+
39
+ class JsonLogger:
40
+
41
+ def __init__(self, path: str, filter_fn: Optional[Callable[[str, Any], bool]] = None):
42
+ if filter_fn is None:
43
+ filter_fn = lambda k, v: isinstance(v, numbers.Number)
44
+
45
+ # default to append mode
46
+ self.path = path
47
+ self.filter_fn = filter_fn
48
+ self.file = None
49
+ self.last_log = None
50
+
51
+ def start(self):
52
+ # use line buffering
53
+ try:
54
+ self.file = file = open(self.path, "r+", buffering=1)
55
+ except FileNotFoundError:
56
+ self.file = file = open(self.path, "w+", buffering=1)
57
+
58
+ # Move the pointer (similar to a cursor in a text editor) to the end of the file
59
+ pos = file.seek(0, os.SEEK_END)
60
+
61
+ # Read each character in the file one at a time from the last
62
+ # character going backwards, searching for a newline character
63
+ # If we find a new line, exit the search
64
+ while pos > 0 and file.read(1) != "\n":
65
+ pos -= 1
66
+ file.seek(pos, os.SEEK_SET)
67
+ # now the file pointer is at one past the last '\n'
68
+ # and pos is at the last '\n'.
69
+ last_line_end = file.tell()
70
+
71
+ # find the start of second last line
72
+ pos = max(0, pos - 1)
73
+ file.seek(pos, os.SEEK_SET)
74
+ while pos > 0 and file.read(1) != "\n":
75
+ pos -= 1
76
+ file.seek(pos, os.SEEK_SET)
77
+ # now the file pointer is at one past the second last '\n'
78
+ last_line_start = file.tell()
79
+
80
+ if last_line_start < last_line_end:
81
+ # has last line of json
82
+ last_line = file.readline()
83
+ self.last_log = json.loads(last_line)
84
+
85
+ # remove the last incomplete line
86
+ file.seek(last_line_end)
87
+ file.truncate()
88
+
89
+ def stop(self):
90
+ self.file.close()
91
+ self.file = None
92
+
93
+ def __enter__(self):
94
+ self.start()
95
+ return self
96
+
97
+ def __exit__(self, exc_type, exc_val, exc_tb):
98
+ self.stop()
99
+
100
+ def log(self, data: dict):
101
+ filtered_data = dict(filter(lambda x: self.filter_fn(*x), data.items()))
102
+ # save current as last log
103
+ self.last_log = filtered_data
104
+ for k, v in filtered_data.items():
105
+ if isinstance(v, numbers.Integral):
106
+ filtered_data[k] = int(v)
107
+ elif isinstance(v, numbers.Number):
108
+ filtered_data[k] = float(v)
109
+ buf = json.dumps(filtered_data)
110
+ # ensure one line per json
111
+ buf = buf.replace("\n", "") + "\n"
112
+ self.file.write(buf)
113
+
114
+ def get_last_log(self):
115
+ return copy.deepcopy(self.last_log)
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/pose_trajectory_interpolator.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+ import numbers
3
+ import numpy as np
4
+ import scipy.interpolate as si
5
+ import scipy.spatial.transform as st
6
+
7
+
8
+ def rotation_distance(a: st.Rotation, b: st.Rotation) -> float:
9
+ return (b * a.inv()).magnitude()
10
+
11
+
12
+ def pose_distance(start_pose, end_pose):
13
+ start_pose = np.array(start_pose)
14
+ end_pose = np.array(end_pose)
15
+ start_pos = start_pose[:3]
16
+ end_pos = end_pose[:3]
17
+ start_rot = st.Rotation.from_rotvec(start_pose[3:])
18
+ end_rot = st.Rotation.from_rotvec(end_pose[3:])
19
+ pos_dist = np.linalg.norm(end_pos - start_pos)
20
+ rot_dist = rotation_distance(start_rot, end_rot)
21
+ return pos_dist, rot_dist
22
+
23
+
24
+ class PoseTrajectoryInterpolator:
25
+
26
+ def __init__(self, times: np.ndarray, poses: np.ndarray):
27
+ assert len(times) >= 1
28
+ assert len(poses) == len(times)
29
+ if not isinstance(times, np.ndarray):
30
+ times = np.array(times)
31
+ if not isinstance(poses, np.ndarray):
32
+ poses = np.array(poses)
33
+
34
+ if len(times) == 1:
35
+ # special treatment for single step interpolation
36
+ self.single_step = True
37
+ self._times = times
38
+ self._poses = poses
39
+ else:
40
+ self.single_step = False
41
+ assert np.all(times[1:] >= times[:-1])
42
+
43
+ pos = poses[:, :3]
44
+ rot = st.Rotation.from_rotvec(poses[:, 3:])
45
+
46
+ self.pos_interp = si.interp1d(times, pos, axis=0, assume_sorted=True)
47
+ self.rot_interp = st.Slerp(times, rot)
48
+
49
+ @property
50
+ def times(self) -> np.ndarray:
51
+ if self.single_step:
52
+ return self._times
53
+ else:
54
+ return self.pos_interp.x
55
+
56
+ @property
57
+ def poses(self) -> np.ndarray:
58
+ if self.single_step:
59
+ return self._poses
60
+ else:
61
+ n = len(self.times)
62
+ poses = np.zeros((n, 6))
63
+ poses[:, :3] = self.pos_interp.y
64
+ poses[:, 3:] = self.rot_interp(self.times).as_rotvec()
65
+ return poses
66
+
67
+ def trim(self, start_t: float, end_t: float) -> "PoseTrajectoryInterpolator":
68
+ assert start_t <= end_t
69
+ times = self.times
70
+ should_keep = (start_t < times) & (times < end_t)
71
+ keep_times = times[should_keep]
72
+ all_times = np.concatenate([[start_t], keep_times, [end_t]])
73
+ # remove duplicates, Slerp requires strictly increasing x
74
+ all_times = np.unique(all_times)
75
+ # interpolate
76
+ all_poses = self(all_times)
77
+ return PoseTrajectoryInterpolator(times=all_times, poses=all_poses)
78
+
79
+ def drive_to_waypoint(self,
80
+ pose,
81
+ time,
82
+ curr_time,
83
+ max_pos_speed=np.inf,
84
+ max_rot_speed=np.inf) -> "PoseTrajectoryInterpolator":
85
+ assert max_pos_speed > 0
86
+ assert max_rot_speed > 0
87
+ time = max(time, curr_time)
88
+
89
+ curr_pose = self(curr_time)
90
+ pos_dist, rot_dist = pose_distance(curr_pose, pose)
91
+ pos_min_duration = pos_dist / max_pos_speed
92
+ rot_min_duration = rot_dist / max_rot_speed
93
+ duration = time - curr_time
94
+ duration = max(duration, max(pos_min_duration, rot_min_duration))
95
+ assert duration >= 0
96
+ last_waypoint_time = curr_time + duration
97
+
98
+ # insert new pose
99
+ trimmed_interp = self.trim(curr_time, curr_time)
100
+ times = np.append(trimmed_interp.times, [last_waypoint_time], axis=0)
101
+ poses = np.append(trimmed_interp.poses, [pose], axis=0)
102
+
103
+ # create new interpolator
104
+ final_interp = PoseTrajectoryInterpolator(times, poses)
105
+ return final_interp
106
+
107
+ def schedule_waypoint(
108
+ self,
109
+ pose,
110
+ time,
111
+ max_pos_speed=np.inf,
112
+ max_rot_speed=np.inf,
113
+ curr_time=None,
114
+ last_waypoint_time=None,
115
+ ) -> "PoseTrajectoryInterpolator":
116
+ assert max_pos_speed > 0
117
+ assert max_rot_speed > 0
118
+ if last_waypoint_time is not None:
119
+ assert curr_time is not None
120
+
121
+ # trim current interpolator to between curr_time and last_waypoint_time
122
+ start_time = self.times[0]
123
+ end_time = self.times[-1]
124
+ assert start_time <= end_time
125
+
126
+ if curr_time is not None:
127
+ if time <= curr_time:
128
+ # if insert time is earlier than current time
129
+ # no effect should be done to the interpolator
130
+ return self
131
+ # now, curr_time < time
132
+ start_time = max(curr_time, start_time)
133
+
134
+ if last_waypoint_time is not None:
135
+ # if last_waypoint_time is earlier than start_time
136
+ # use start_time
137
+ if time <= last_waypoint_time:
138
+ end_time = curr_time
139
+ else:
140
+ end_time = max(last_waypoint_time, curr_time)
141
+ else:
142
+ end_time = curr_time
143
+
144
+ end_time = min(end_time, time)
145
+ start_time = min(start_time, end_time)
146
+ # end time should be the latest of all times except time
147
+ # after this we can assume order (proven by zhenjia, due to the 2 min operations)
148
+
149
+ # Constraints:
150
+ # start_time <= end_time <= time (proven by zhenjia)
151
+ # curr_time <= start_time (proven by zhenjia)
152
+ # curr_time <= time (proven by zhenjia)
153
+
154
+ # time can't change
155
+ # last_waypoint_time can't change
156
+ # curr_time can't change
157
+ assert start_time <= end_time
158
+ assert end_time <= time
159
+ if last_waypoint_time is not None:
160
+ if time <= last_waypoint_time:
161
+ assert end_time == curr_time
162
+ else:
163
+ assert end_time == max(last_waypoint_time, curr_time)
164
+
165
+ if curr_time is not None:
166
+ assert curr_time <= start_time
167
+ assert curr_time <= time
168
+
169
+ trimmed_interp = self.trim(start_time, end_time)
170
+ # after this, all waypoints in trimmed_interp is within start_time and end_time
171
+ # and is earlier than time
172
+
173
+ # determine speed
174
+ duration = time - end_time
175
+ end_pose = trimmed_interp(end_time)
176
+ pos_dist, rot_dist = pose_distance(pose, end_pose)
177
+ pos_min_duration = pos_dist / max_pos_speed
178
+ rot_min_duration = rot_dist / max_rot_speed
179
+ duration = max(duration, max(pos_min_duration, rot_min_duration))
180
+ assert duration >= 0
181
+ last_waypoint_time = end_time + duration
182
+
183
+ # insert new pose
184
+ times = np.append(trimmed_interp.times, [last_waypoint_time], axis=0)
185
+ poses = np.append(trimmed_interp.poses, [pose], axis=0)
186
+
187
+ # create new interpolator
188
+ final_interp = PoseTrajectoryInterpolator(times, poses)
189
+ return final_interp
190
+
191
+ def __call__(self, t: Union[numbers.Number, np.ndarray]) -> np.ndarray:
192
+ is_single = False
193
+ if isinstance(t, numbers.Number):
194
+ is_single = True
195
+ t = np.array([t])
196
+
197
+ pose = np.zeros((len(t), 6))
198
+ if self.single_step:
199
+ pose[:] = self._poses[0]
200
+ else:
201
+ start_time = self.times[0]
202
+ end_time = self.times[-1]
203
+ t = np.clip(t, start_time, end_time)
204
+
205
+ pose = np.zeros((len(t), 6))
206
+ pose[:, :3] = self.pos_interp(t)
207
+ pose[:, 3:] = self.rot_interp(t).as_rotvec()
208
+
209
+ if is_single:
210
+ pose = pose[0]
211
+ return pose
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/precise_sleep.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+
3
+
4
+ def precise_sleep(dt: float, slack_time: float = 0.001, time_func=time.monotonic):
5
+ """
6
+ Use hybrid of time.sleep and spinning to minimize jitter.
7
+ Sleep dt - slack_time seconds first, then spin for the rest.
8
+ """
9
+ t_start = time_func()
10
+ if dt > slack_time:
11
+ time.sleep(dt - slack_time)
12
+ t_end = t_start + dt
13
+ while time_func() < t_end:
14
+ pass
15
+ return
16
+
17
+
18
+ def precise_wait(t_end: float, slack_time: float = 0.001, time_func=time.monotonic):
19
+ t_start = time_func()
20
+ t_wait = t_end - t_start
21
+ if t_wait > 0:
22
+ t_sleep = t_wait - slack_time
23
+ if t_sleep > 0:
24
+ time.sleep(t_sleep)
25
+ while time_func() < t_end:
26
+ pass
27
+ return
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/pymunk_override.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ----------------------------------------------------------------------------
2
+ # pymunk
3
+ # Copyright (c) 2007-2016 Victor Blomqvist
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be included in
13
+ # all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ # SOFTWARE.
22
+ # ----------------------------------------------------------------------------
23
+ """This submodule contains helper functions to help with quick prototyping
24
+ using pymunk together with pygame.
25
+
26
+ Intended to help with debugging and prototyping, not for actual production use
27
+ in a full application. The methods contained in this module is opinionated
28
+ about your coordinate system and not in any way optimized.
29
+ """
30
+
31
+ __docformat__ = "reStructuredText"
32
+
33
+ __all__ = [
34
+ "DrawOptions",
35
+ "get_mouse_pos",
36
+ "to_pygame",
37
+ "from_pygame",
38
+ "lighten",
39
+ "positive_y_is_up",
40
+ ]
41
+
42
+ from typing import List, Sequence, Tuple
43
+
44
+ import pygame
45
+
46
+ import numpy as np
47
+
48
+ import pymunk
49
+ from pymunk.space_debug_draw_options import SpaceDebugColor
50
+ from pymunk.vec2d import Vec2d
51
+
52
+ positive_y_is_up: bool = False
53
+ """Make increasing values of y point upwards.
54
+
55
+ When True::
56
+
57
+ y
58
+ ^
59
+ | . (3, 3)
60
+ |
61
+ | . (2, 2)
62
+ |
63
+ +------ > x
64
+
65
+ When False::
66
+
67
+ +------ > x
68
+ |
69
+ | . (2, 2)
70
+ |
71
+ | . (3, 3)
72
+ v
73
+ y
74
+
75
+ """
76
+
77
+
78
+ class DrawOptions(pymunk.SpaceDebugDrawOptions):
79
+
80
+ def __init__(self, surface: pygame.Surface) -> None:
81
+ """Draw a pymunk.Space on a pygame.Surface object.
82
+
83
+ Typical usage::
84
+
85
+ >>> import pymunk
86
+ >>> surface = pygame.Surface((10,10))
87
+ >>> space = pymunk.Space()
88
+ >>> options = pymunk.pygame_util.DrawOptions(surface)
89
+ >>> space.debug_draw(options)
90
+
91
+ You can control the color of a shape by setting shape.color to the color
92
+ you want it drawn in::
93
+
94
+ >>> c = pymunk.Circle(None, 10)
95
+ >>> c.color = pygame.Color("pink")
96
+
97
+ See pygame_util.demo.py for a full example
98
+
99
+ Since pygame uses a coordinate system where y points down (in contrast
100
+ to many other cases), you either have to make the physics simulation
101
+ with Pymunk also behave in that way, or flip everything when you draw.
102
+
103
+ The easiest is probably to just make the simulation behave the same
104
+ way as Pygame does. In that way all coordinates used are in the same
105
+ orientation and easy to reason about::
106
+
107
+ >>> space = pymunk.Space()
108
+ >>> space.gravity = (0, -1000)
109
+ >>> body = pymunk.Body()
110
+ >>> body.position = (0, 0) # will be positioned in the top left corner
111
+ >>> space.debug_draw(options)
112
+
113
+ To flip the drawing its possible to set the module property
114
+ :py:data:`positive_y_is_up` to True. Then the pygame drawing will flip
115
+ the simulation upside down before drawing::
116
+
117
+ >>> positive_y_is_up = True
118
+ >>> body = pymunk.Body()
119
+ >>> body.position = (0, 0)
120
+ >>> # Body will be position in bottom left corner
121
+
122
+ :Parameters:
123
+ surface : pygame.Surface
124
+ Surface that the objects will be drawn on
125
+ """
126
+ self.surface = surface
127
+ super(DrawOptions, self).__init__()
128
+
129
+ def draw_circle(
130
+ self,
131
+ pos: Vec2d,
132
+ angle: float,
133
+ radius: float,
134
+ outline_color: SpaceDebugColor,
135
+ fill_color: SpaceDebugColor,
136
+ ) -> None:
137
+ p = to_pygame(pos, self.surface)
138
+
139
+ pygame.draw.circle(self.surface, fill_color.as_int(), p, round(radius), 0)
140
+ pygame.draw.circle(self.surface, light_color(fill_color).as_int(), p, round(radius - 4), 0)
141
+
142
+ circle_edge = pos + Vec2d(radius, 0).rotated(angle)
143
+ p2 = to_pygame(circle_edge, self.surface)
144
+ line_r = 2 if radius > 20 else 1
145
+ # pygame.draw.lines(self.surface, outline_color.as_int(), False, [p, p2], line_r)
146
+
147
+ def draw_segment(self, a: Vec2d, b: Vec2d, color: SpaceDebugColor) -> None:
148
+ p1 = to_pygame(a, self.surface)
149
+ p2 = to_pygame(b, self.surface)
150
+
151
+ pygame.draw.aalines(self.surface, color.as_int(), False, [p1, p2])
152
+
153
+ def draw_fat_segment(
154
+ self,
155
+ a: Tuple[float, float],
156
+ b: Tuple[float, float],
157
+ radius: float,
158
+ outline_color: SpaceDebugColor,
159
+ fill_color: SpaceDebugColor,
160
+ ) -> None:
161
+ p1 = to_pygame(a, self.surface)
162
+ p2 = to_pygame(b, self.surface)
163
+
164
+ r = round(max(1, radius * 2))
165
+ pygame.draw.lines(self.surface, fill_color.as_int(), False, [p1, p2], r)
166
+ if r > 2:
167
+ orthog = [abs(p2[1] - p1[1]), abs(p2[0] - p1[0])]
168
+ if orthog[0] == 0 and orthog[1] == 0:
169
+ return
170
+ scale = radius / (orthog[0] * orthog[0] + orthog[1] * orthog[1])**0.5
171
+ orthog[0] = round(orthog[0] * scale)
172
+ orthog[1] = round(orthog[1] * scale)
173
+ points = [
174
+ (p1[0] - orthog[0], p1[1] - orthog[1]),
175
+ (p1[0] + orthog[0], p1[1] + orthog[1]),
176
+ (p2[0] + orthog[0], p2[1] + orthog[1]),
177
+ (p2[0] - orthog[0], p2[1] - orthog[1]),
178
+ ]
179
+ pygame.draw.polygon(self.surface, fill_color.as_int(), points)
180
+ pygame.draw.circle(
181
+ self.surface,
182
+ fill_color.as_int(),
183
+ (round(p1[0]), round(p1[1])),
184
+ round(radius),
185
+ )
186
+ pygame.draw.circle(
187
+ self.surface,
188
+ fill_color.as_int(),
189
+ (round(p2[0]), round(p2[1])),
190
+ round(radius),
191
+ )
192
+
193
+ def draw_polygon(
194
+ self,
195
+ verts: Sequence[Tuple[float, float]],
196
+ radius: float,
197
+ outline_color: SpaceDebugColor,
198
+ fill_color: SpaceDebugColor,
199
+ ) -> None:
200
+ ps = [to_pygame(v, self.surface) for v in verts]
201
+ ps += [ps[0]]
202
+
203
+ radius = 2
204
+ pygame.draw.polygon(self.surface, light_color(fill_color).as_int(), ps)
205
+
206
+ if radius > 0:
207
+ for i in range(len(verts)):
208
+ a = verts[i]
209
+ b = verts[(i + 1) % len(verts)]
210
+ self.draw_fat_segment(a, b, radius, fill_color, fill_color)
211
+
212
+ def draw_dot(self, size: float, pos: Tuple[float, float], color: SpaceDebugColor) -> None:
213
+ p = to_pygame(pos, self.surface)
214
+ pygame.draw.circle(self.surface, color.as_int(), p, round(size), 0)
215
+
216
+
217
+ def get_mouse_pos(surface: pygame.Surface) -> Tuple[int, int]:
218
+ """Get position of the mouse pointer in pymunk coordinates."""
219
+ p = pygame.mouse.get_pos()
220
+ return from_pygame(p, surface)
221
+
222
+
223
+ def to_pygame(p: Tuple[float, float], surface: pygame.Surface) -> Tuple[int, int]:
224
+ """Convenience method to convert pymunk coordinates to pygame surface
225
+ local coordinates.
226
+
227
+ Note that in case positive_y_is_up is False, this function won't actually do
228
+ anything except converting the point to integers.
229
+ """
230
+ if positive_y_is_up:
231
+ return round(p[0]), surface.get_height() - round(p[1])
232
+ else:
233
+ return round(p[0]), round(p[1])
234
+
235
+
236
+ def from_pygame(p: Tuple[float, float], surface: pygame.Surface) -> Tuple[int, int]:
237
+ """Convenience method to convert pygame surface local coordinates to
238
+ pymunk coordinates
239
+ """
240
+ return to_pygame(p, surface)
241
+
242
+
243
+ def light_color(color: SpaceDebugColor):
244
+ color = np.minimum(1.2 * np.float32([color.r, color.g, color.b, color.a]), np.float32([255]))
245
+ color = SpaceDebugColor(r=color[0], g=color[1], b=color[2], a=color[3])
246
+ return color
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/pymunk_util.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pygame
2
+ import pymunk
3
+ import pymunk.pygame_util
4
+ import numpy as np
5
+
6
+ COLLTYPE_DEFAULT = 0
7
+ COLLTYPE_MOUSE = 1
8
+ COLLTYPE_BALL = 2
9
+
10
+
11
+ def get_body_type(static=False):
12
+ body_type = pymunk.Body.DYNAMIC
13
+ if static:
14
+ body_type = pymunk.Body.STATIC
15
+ return body_type
16
+
17
+
18
+ def create_rectangle(space, pos_x, pos_y, width, height, density=3, static=False):
19
+ body = pymunk.Body(body_type=get_body_type(static))
20
+ body.position = (pos_x, pos_y)
21
+ shape = pymunk.Poly.create_box(body, (width, height))
22
+ shape.density = density
23
+ space.add(body, shape)
24
+ return body, shape
25
+
26
+
27
+ def create_rectangle_bb(space, left, bottom, right, top, **kwargs):
28
+ pos_x = (left + right) / 2
29
+ pos_y = (top + bottom) / 2
30
+ height = top - bottom
31
+ width = right - left
32
+ return create_rectangle(space, pos_x, pos_y, width, height, **kwargs)
33
+
34
+
35
+ def create_circle(space, pos_x, pos_y, radius, density=3, static=False):
36
+ body = pymunk.Body(body_type=get_body_type(static))
37
+ body.position = (pos_x, pos_y)
38
+ shape = pymunk.Circle(body, radius=radius)
39
+ shape.density = density
40
+ shape.collision_type = COLLTYPE_BALL
41
+ space.add(body, shape)
42
+ return body, shape
43
+
44
+
45
+ def get_body_state(body):
46
+ state = np.zeros(6, dtype=np.float32)
47
+ state[:2] = body.position
48
+ state[2] = body.angle
49
+ state[3:5] = body.velocity
50
+ state[5] = body.angular_velocity
51
+ return state
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/pytorch_util.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Callable, List
2
+ import collections
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+
7
+ def dict_apply(x: Dict[str, torch.Tensor], func: Callable[[torch.Tensor], torch.Tensor]) -> Dict[str, torch.Tensor]:
8
+ result = dict()
9
+ for key, value in x.items():
10
+ if isinstance(value, dict):
11
+ result[key] = dict_apply(value, func)
12
+ else:
13
+ result[key] = func(value)
14
+ return result
15
+
16
+ def pad_remaining_dims(x, target):
17
+ assert x.shape == target.shape[:len(x.shape)]
18
+ return x.reshape(x.shape + (1, ) * (len(target.shape) - len(x.shape)))
19
+
20
+ def dict_apply_split(
21
+ x: Dict[str, torch.Tensor],
22
+ split_func: Callable[[torch.Tensor], Dict[str, torch.Tensor]],
23
+ ) -> Dict[str, torch.Tensor]:
24
+ results = collections.defaultdict(dict)
25
+ for key, value in x.items():
26
+ result = split_func(value)
27
+ for k, v in result.items():
28
+ results[k][key] = v
29
+ return results
30
+
31
+
32
+ def dict_apply_reduce(
33
+ x: List[Dict[str, torch.Tensor]],
34
+ reduce_func: Callable[[List[torch.Tensor]], torch.Tensor],
35
+ ) -> Dict[str, torch.Tensor]:
36
+ result = dict()
37
+ for key in x[0].keys():
38
+ result[key] = reduce_func([x_[key] for x_ in x])
39
+ return result
40
+
41
+
42
+ def replace_submodules(
43
+ root_module: nn.Module,
44
+ predicate: Callable[[nn.Module], bool],
45
+ func: Callable[[nn.Module], nn.Module],
46
+ ) -> nn.Module:
47
+ """
48
+ predicate: Return true if the module is to be replaced.
49
+ func: Return new module to use.
50
+ """
51
+ if predicate(root_module):
52
+ return func(root_module)
53
+
54
+ bn_list = [k.split(".") for k, m in root_module.named_modules(remove_duplicate=True) if predicate(m)]
55
+ for *parent, k in bn_list:
56
+ parent_module = root_module
57
+ if len(parent) > 0:
58
+ parent_module = root_module.get_submodule(".".join(parent))
59
+ if isinstance(parent_module, nn.Sequential):
60
+ src_module = parent_module[int(k)]
61
+ else:
62
+ src_module = getattr(parent_module, k)
63
+ tgt_module = func(src_module)
64
+ if isinstance(parent_module, nn.Sequential):
65
+ parent_module[int(k)] = tgt_module
66
+ else:
67
+ setattr(parent_module, k, tgt_module)
68
+ # verify that all BN are replaced
69
+ bn_list = [k.split(".") for k, m in root_module.named_modules(remove_duplicate=True) if predicate(m)]
70
+ assert len(bn_list) == 0
71
+ return root_module
72
+
73
+
74
+ def optimizer_to(optimizer, device):
75
+ for state in optimizer.state.values():
76
+ for k, v in state.items():
77
+ if isinstance(v, torch.Tensor):
78
+ state[k] = v.to(device=device)
79
+ return optimizer
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/robomimic_util.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import copy
3
+
4
+ import h5py
5
+ import robomimic.utils.obs_utils as ObsUtils
6
+ import robomimic.utils.file_utils as FileUtils
7
+ import robomimic.utils.env_utils as EnvUtils
8
+ from scipy.spatial.transform import Rotation
9
+
10
+ from robomimic.config import config_factory
11
+
12
+
13
+ class RobomimicAbsoluteActionConverter:
14
+
15
+ def __init__(self, dataset_path, algo_name="bc"):
16
+ # default BC config
17
+ config = config_factory(algo_name=algo_name)
18
+
19
+ # read config to set up metadata for observation modalities (e.g. detecting rgb observations)
20
+ # must ran before create dataset
21
+ ObsUtils.initialize_obs_utils_with_config(config)
22
+
23
+ env_meta = FileUtils.get_env_metadata_from_dataset(dataset_path)
24
+ abs_env_meta = copy.deepcopy(env_meta)
25
+ abs_env_meta["env_kwargs"]["controller_configs"]["control_delta"] = False
26
+
27
+ env = EnvUtils.create_env_from_metadata(
28
+ env_meta=env_meta,
29
+ render=False,
30
+ render_offscreen=False,
31
+ use_image_obs=False,
32
+ )
33
+ assert len(env.env.robots) in (1, 2)
34
+
35
+ abs_env = EnvUtils.create_env_from_metadata(
36
+ env_meta=abs_env_meta,
37
+ render=False,
38
+ render_offscreen=False,
39
+ use_image_obs=False,
40
+ )
41
+ assert not abs_env.env.robots[0].controller.use_delta
42
+
43
+ self.env = env
44
+ self.abs_env = abs_env
45
+ self.file = h5py.File(dataset_path, "r")
46
+
47
+ def __len__(self):
48
+ return len(self.file["data"])
49
+
50
+ def convert_actions(self, states: np.ndarray, actions: np.ndarray) -> np.ndarray:
51
+ """
52
+ Given state and delta action sequence
53
+ generate equivalent goal position and orientation for each step
54
+ keep the original gripper action intact.
55
+ """
56
+ # in case of multi robot
57
+ # reshape (N,14) to (N,2,7)
58
+ # or (N,7) to (N,1,7)
59
+ stacked_actions = actions.reshape(*actions.shape[:-1], -1, 7)
60
+
61
+ env = self.env
62
+ # generate abs actions
63
+ action_goal_pos = np.zeros(stacked_actions.shape[:-1] + (3, ), dtype=stacked_actions.dtype)
64
+ action_goal_ori = np.zeros(stacked_actions.shape[:-1] + (3, ), dtype=stacked_actions.dtype)
65
+ action_gripper = stacked_actions[..., [-1]]
66
+ for i in range(len(states)):
67
+ _ = env.reset_to({"states": states[i]})
68
+
69
+ # taken from robot_env.py L#454
70
+ for idx, robot in enumerate(env.env.robots):
71
+ # run controller goal generator
72
+ robot.control(stacked_actions[i, idx], policy_step=True)
73
+
74
+ # read pos and ori from robots
75
+ controller = robot.controller
76
+ action_goal_pos[i, idx] = controller.goal_pos
77
+ action_goal_ori[i, idx] = Rotation.from_matrix(controller.goal_ori).as_rotvec()
78
+
79
+ stacked_abs_actions = np.concatenate([action_goal_pos, action_goal_ori, action_gripper], axis=-1)
80
+ abs_actions = stacked_abs_actions.reshape(actions.shape)
81
+ return abs_actions
82
+
83
+ def convert_idx(self, idx):
84
+ file = self.file
85
+ demo = file[f"data/demo_{idx}"]
86
+ # input
87
+ states = demo["states"][:]
88
+ actions = demo["actions"][:]
89
+
90
+ # generate abs actions
91
+ abs_actions = self.convert_actions(states, actions)
92
+ return abs_actions
93
+
94
+ def convert_and_eval_idx(self, idx):
95
+ env = self.env
96
+ abs_env = self.abs_env
97
+ file = self.file
98
+ # first step have high error for some reason, not representative
99
+ eval_skip_steps = 1
100
+
101
+ demo = file[f"data/demo_{idx}"]
102
+ # input
103
+ states = demo["states"][:]
104
+ actions = demo["actions"][:]
105
+
106
+ # generate abs actions
107
+ abs_actions = self.convert_actions(states, actions)
108
+
109
+ # verify
110
+ robot0_eef_pos = demo["obs"]["robot0_eef_pos"][:]
111
+ robot0_eef_quat = demo["obs"]["robot0_eef_quat"][:]
112
+
113
+ delta_error_info = self.evaluate_rollout_error(
114
+ env,
115
+ states,
116
+ actions,
117
+ robot0_eef_pos,
118
+ robot0_eef_quat,
119
+ metric_skip_steps=eval_skip_steps,
120
+ )
121
+ abs_error_info = self.evaluate_rollout_error(
122
+ abs_env,
123
+ states,
124
+ abs_actions,
125
+ robot0_eef_pos,
126
+ robot0_eef_quat,
127
+ metric_skip_steps=eval_skip_steps,
128
+ )
129
+
130
+ info = {"delta_max_error": delta_error_info, "abs_max_error": abs_error_info}
131
+ return abs_actions, info
132
+
133
+ @staticmethod
134
+ def evaluate_rollout_error(env, states, actions, robot0_eef_pos, robot0_eef_quat, metric_skip_steps=1):
135
+ # first step have high error for some reason, not representative
136
+
137
+ # evaluate abs actions
138
+ rollout_next_states = list()
139
+ rollout_next_eef_pos = list()
140
+ rollout_next_eef_quat = list()
141
+ obs = env.reset_to({"states": states[0]})
142
+ for i in range(len(states)):
143
+ obs = env.reset_to({"states": states[i]})
144
+ obs, reward, done, info = env.step(actions[i])
145
+ obs = env.get_observation()
146
+ rollout_next_states.append(env.get_state()["states"])
147
+ rollout_next_eef_pos.append(obs["robot0_eef_pos"])
148
+ rollout_next_eef_quat.append(obs["robot0_eef_quat"])
149
+ rollout_next_states = np.array(rollout_next_states)
150
+ rollout_next_eef_pos = np.array(rollout_next_eef_pos)
151
+ rollout_next_eef_quat = np.array(rollout_next_eef_quat)
152
+
153
+ next_state_diff = states[1:] - rollout_next_states[:-1]
154
+ max_next_state_diff = np.max(np.abs(next_state_diff[metric_skip_steps:]))
155
+
156
+ next_eef_pos_diff = robot0_eef_pos[1:] - rollout_next_eef_pos[:-1]
157
+ next_eef_pos_dist = np.linalg.norm(next_eef_pos_diff, axis=-1)
158
+ max_next_eef_pos_dist = next_eef_pos_dist[metric_skip_steps:].max()
159
+
160
+ next_eef_rot_diff = (Rotation.from_quat(robot0_eef_quat[1:]) *
161
+ Rotation.from_quat(rollout_next_eef_quat[:-1]).inv())
162
+ next_eef_rot_dist = next_eef_rot_diff.magnitude()
163
+ max_next_eef_rot_dist = next_eef_rot_dist[metric_skip_steps:].max()
164
+
165
+ info = {
166
+ "state": max_next_state_diff,
167
+ "pos": max_next_eef_pos_dist,
168
+ "rot": max_next_eef_rot_dist,
169
+ }
170
+ return info
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/sampler.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ import numpy as np
3
+ import numba
4
+ from diffusion_policy.common.replay_buffer import ReplayBuffer
5
+
6
+
7
+ @numba.jit(nopython=True)
8
+ def create_indices(
9
+ episode_ends: np.ndarray,
10
+ sequence_length: int,
11
+ episode_mask: np.ndarray,
12
+ pad_before: int = 0,
13
+ pad_after: int = 0,
14
+ debug: bool = True,
15
+ ) -> np.ndarray:
16
+ episode_mask.shape == episode_ends.shape
17
+ pad_before = min(max(pad_before, 0), sequence_length - 1)
18
+ pad_after = min(max(pad_after, 0), sequence_length - 1)
19
+
20
+ indices = list()
21
+ for i in range(len(episode_ends)):
22
+ if not episode_mask[i]:
23
+ # skip episode
24
+ continue
25
+ start_idx = 0
26
+ if i > 0:
27
+ start_idx = episode_ends[i - 1]
28
+ end_idx = episode_ends[i]
29
+ episode_length = end_idx - start_idx
30
+
31
+ min_start = -pad_before
32
+ max_start = episode_length - sequence_length + pad_after
33
+
34
+ # range stops one idx before end
35
+ for idx in range(min_start, max_start + 1):
36
+ buffer_start_idx = max(idx, 0) + start_idx
37
+ buffer_end_idx = min(idx + sequence_length, episode_length) + start_idx
38
+ start_offset = buffer_start_idx - (idx + start_idx)
39
+ end_offset = (idx + sequence_length + start_idx) - buffer_end_idx
40
+ sample_start_idx = 0 + start_offset
41
+ sample_end_idx = sequence_length - end_offset
42
+ if debug:
43
+ assert start_offset >= 0
44
+ assert end_offset >= 0
45
+ assert (sample_end_idx - sample_start_idx) == (buffer_end_idx - buffer_start_idx)
46
+ indices.append([buffer_start_idx, buffer_end_idx, sample_start_idx, sample_end_idx])
47
+ indices = np.array(indices)
48
+ return indices
49
+
50
+
51
+ def get_val_mask(n_episodes, val_ratio, seed=0):
52
+ val_mask = np.zeros(n_episodes, dtype=bool)
53
+ if val_ratio <= 0:
54
+ return val_mask
55
+
56
+ # have at least 1 episode for validation, and at least 1 episode for train
57
+ n_val = min(max(1, round(n_episodes * val_ratio)), n_episodes - 1)
58
+ rng = np.random.default_rng(seed=seed)
59
+ # val_idxs = rng.choice(n_episodes, size=n_val, replace=False)
60
+ val_idxs = -1
61
+ val_mask[val_idxs] = True
62
+ return val_mask
63
+
64
+
65
+ def downsample_mask(mask, max_n, seed=0):
66
+ # subsample training data
67
+ train_mask = mask
68
+ if (max_n is not None) and (np.sum(train_mask) > max_n):
69
+ n_train = int(max_n)
70
+ curr_train_idxs = np.nonzero(train_mask)[0]
71
+ rng = np.random.default_rng(seed=seed)
72
+ train_idxs_idx = rng.choice(len(curr_train_idxs), size=n_train, replace=False)
73
+ train_idxs = curr_train_idxs[train_idxs_idx]
74
+ train_mask = np.zeros_like(train_mask)
75
+ train_mask[train_idxs] = True
76
+ assert np.sum(train_mask) == n_train
77
+ return train_mask
78
+
79
+
80
+ class SequenceSampler:
81
+
82
+ def __init__(
83
+ self,
84
+ replay_buffer: ReplayBuffer,
85
+ sequence_length: int,
86
+ pad_before: int = 0,
87
+ pad_after: int = 0,
88
+ keys=None,
89
+ key_first_k=dict(),
90
+ episode_mask: Optional[np.ndarray] = None,
91
+ ):
92
+ """
93
+ key_first_k: dict str: int
94
+ Only take first k data from these keys (to improve perf)
95
+ """
96
+
97
+ super().__init__()
98
+ assert sequence_length >= 1
99
+ if keys is None:
100
+ keys = list(replay_buffer.keys())
101
+
102
+ episode_ends = replay_buffer.episode_ends[:]
103
+ if episode_mask is None:
104
+ episode_mask = np.ones(episode_ends.shape, dtype=bool)
105
+
106
+ if np.any(episode_mask):
107
+ indices = create_indices(
108
+ episode_ends,
109
+ sequence_length=sequence_length,
110
+ pad_before=pad_before,
111
+ pad_after=pad_after,
112
+ episode_mask=episode_mask,
113
+ )
114
+ else:
115
+ indices = np.zeros((0, 4), dtype=np.int64)
116
+
117
+ # (buffer_start_idx, buffer_end_idx, sample_start_idx, sample_end_idx)
118
+ self.indices = indices
119
+ self.keys = list(keys) # prevent OmegaConf list performance problem
120
+ self.sequence_length = sequence_length
121
+ self.replay_buffer = replay_buffer
122
+ self.key_first_k = key_first_k
123
+
124
+ def __len__(self):
125
+ return len(self.indices)
126
+
127
+ def sample_sequence(self, idx):
128
+ buffer_start_idx, buffer_end_idx, sample_start_idx, sample_end_idx = (self.indices[idx])
129
+ result = dict()
130
+ for key in self.keys:
131
+ input_arr = self.replay_buffer[key]
132
+ # performance optimization, avoid small allocation if possible
133
+ if key not in self.key_first_k:
134
+ sample = input_arr[buffer_start_idx:buffer_end_idx]
135
+ else:
136
+ # performance optimization, only load used obs steps
137
+ n_data = buffer_end_idx - buffer_start_idx
138
+ k_data = min(self.key_first_k[key], n_data)
139
+ # fill value with Nan to catch bugs
140
+ # the non-loaded region should never be used
141
+ sample = np.full(
142
+ (n_data, ) + input_arr.shape[1:],
143
+ fill_value=np.nan,
144
+ dtype=input_arr.dtype,
145
+ )
146
+ try:
147
+ sample[:k_data] = input_arr[buffer_start_idx:buffer_start_idx + k_data]
148
+ except Exception as e:
149
+ import pdb
150
+
151
+ pdb.set_trace()
152
+ data = sample
153
+ if (sample_start_idx > 0) or (sample_end_idx < self.sequence_length):
154
+ data = np.zeros(
155
+ shape=(self.sequence_length, ) + input_arr.shape[1:],
156
+ dtype=input_arr.dtype,
157
+ )
158
+ if sample_start_idx > 0:
159
+ data[:sample_start_idx] = sample[0]
160
+ if sample_end_idx < self.sequence_length:
161
+ data[sample_end_idx:] = sample[-1]
162
+ data[sample_start_idx:sample_end_idx] = sample
163
+ result[key] = data
164
+ return result
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/config/robot_dp.yaml ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ defaults:
2
+ - _self_
3
+ - task: default_task
4
+
5
+ name: robot_${task.name}
6
+ _target_: diffusion_policy.workspace.robotworkspace.RobotWorkspace
7
+
8
+ bench_name: null
9
+ task_name: ${task.name}
10
+ shape_meta: ${task.shape_meta}
11
+ exp_name: "default"
12
+
13
+ horizon: 8
14
+ n_obs_steps: 3
15
+ n_action_steps: 6
16
+ n_latency_steps: 0
17
+ dataset_obs_steps: ${n_obs_steps}
18
+ past_action_visible: False
19
+ keypoint_visible_rate: 1.0
20
+ obs_as_global_cond: True
21
+
22
+ policy:
23
+ _target_: diffusion_policy.policy.diffusion_unet_image_policy.DiffusionUnetImagePolicy
24
+
25
+ shape_meta: ${shape_meta}
26
+
27
+ noise_scheduler:
28
+ _target_: diffusers.schedulers.scheduling_ddpm.DDPMScheduler
29
+ num_train_timesteps: 100
30
+ beta_start: 0.0001
31
+ beta_end: 0.02
32
+ beta_schedule: squaredcos_cap_v2
33
+ variance_type: fixed_small # Yilun's paper uses fixed_small_log instead, but easy to cause Nan
34
+ clip_sample: True # required when predict_epsilon=False
35
+ prediction_type: epsilon # or sample
36
+
37
+ obs_encoder:
38
+ _target_: diffusion_policy.model.vision.multi_image_obs_encoder.MultiImageObsEncoder
39
+ shape_meta: ${shape_meta}
40
+ rgb_model:
41
+ _target_: diffusion_policy.model.vision.model_getter.get_resnet
42
+ name: resnet18
43
+ weights: null
44
+ resize_shape: null
45
+ crop_shape: null
46
+ # constant center crop
47
+ random_crop: True
48
+ use_group_norm: True
49
+ share_rgb_model: False
50
+ imagenet_norm: True
51
+
52
+ horizon: ${horizon}
53
+ n_action_steps: ${eval:'${n_action_steps}+${n_latency_steps}'}
54
+ n_obs_steps: ${n_obs_steps}
55
+ num_inference_steps: 100
56
+ obs_as_global_cond: ${obs_as_global_cond}
57
+ # crop_shape: null
58
+ diffusion_step_embed_dim: 128
59
+ # down_dims: [512, 1024, 2048]
60
+ down_dims: [256, 512, 1024]
61
+ kernel_size: 5
62
+ n_groups: 8
63
+ cond_predict_scale: True
64
+
65
+ # scheduler.step params
66
+ # predict_epsilon: True
67
+
68
+ ema:
69
+ _target_: diffusion_policy.model.diffusion.ema_model.EMAModel
70
+ update_after_step: 0
71
+ inv_gamma: 1.0
72
+ power: 0.75
73
+ min_value: 0.0
74
+ max_value: 0.9999
75
+
76
+ dataloader:
77
+ batch_size: 128
78
+ num_workers: 0
79
+ shuffle: True
80
+ pin_memory: True
81
+ persistent_workers: False
82
+
83
+ val_dataloader:
84
+ batch_size: 128
85
+ num_workers: 0
86
+ shuffle: False
87
+ pin_memory: True
88
+ persistent_workers: False
89
+
90
+ optimizer:
91
+ _target_: torch.optim.AdamW
92
+ lr: 1.0e-4
93
+ betas: [0.95, 0.999]
94
+ eps: 1.0e-8
95
+ weight_decay: 1.0e-6
96
+
97
+ training:
98
+ device: "cuda:0"
99
+ seed: 42
100
+ debug: False
101
+ resume: True
102
+ # optimization
103
+ lr_scheduler: cosine
104
+ lr_warmup_steps: 500
105
+ num_epochs: 600
106
+ gradient_accumulate_every: 1
107
+ # EMA destroys performance when used with BatchNorm
108
+ # replace BatchNorm with GroupNorm.
109
+ use_ema: True
110
+ freeze_encoder: False
111
+ # training loop control
112
+ # in epochs
113
+ rollout_every: 50
114
+ checkpoint_every: 600
115
+ val_every: 1
116
+ sample_every: 5
117
+ # steps per epoch
118
+ max_train_steps: null
119
+ max_val_steps: null
120
+ # misc
121
+ tqdm_interval_sec: 1.0
122
+
123
+ logging:
124
+ project: diffusion_policy_debug
125
+ resume: True
126
+ mode: online
127
+ name: ${now:%Y.%m.%d-%H.%M.%S}_${name}_${task_name}
128
+ tags: ["${name}", "${task_name}", "${exp_name}"]
129
+ id: null
130
+ group: null
131
+
132
+ checkpoint:
133
+ topk:
134
+ monitor_key: test_mean_score
135
+ mode: max
136
+ k: 5
137
+ format_str: 'epoch={epoch:04d}-test_mean_score={test_mean_score:.3f}.ckpt'
138
+ save_last_ckpt: True
139
+ save_last_snapshot: False
140
+
141
+ multi_run:
142
+ run_dir: data/outputs/${now:%Y.%m.%d}/${now:%H.%M.%S}_${name}_${task_name}
143
+ wandb_name_base: ${now:%Y.%m.%d-%H.%M.%S}_${name}_${task_name}
144
+
145
+ hydra:
146
+ job:
147
+ override_dirname: ${name}
148
+ run:
149
+ dir: data/outputs/${now:%Y.%m.%d}/${now:%H.%M.%S}_${name}_${task_name}
150
+ sweep:
151
+ dir: data/outputs/${now:%Y.%m.%d}/${now:%H.%M.%S}_${name}_${task_name}
152
+ subdir: ${hydra.job.num}
153
+
154
+ setting: null
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/config/task/aloha_garment.yaml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: task_config
2
+
3
+ image_shape: &image_shape [3, 240, 320]
4
+ shape_meta: &shape_meta
5
+ # acceptable types: rgb, low_dim
6
+ obs:
7
+ head_cam:
8
+ shape: *image_shape
9
+ type: rgb
10
+ # front_cam:
11
+ # shape: *image_shape
12
+ # type: rgb
13
+ left_cam:
14
+ shape: *image_shape
15
+ type: rgb
16
+ right_cam:
17
+ shape: *image_shape
18
+ type: rgb
19
+ agent_pos:
20
+ shape: [14]
21
+ type: low_dim
22
+ action:
23
+ shape: [14]
24
+
25
+ env_runner:
26
+ _target_: diffusion_policy.env_runner.pusht_image_runner.PushTImageRunner
27
+ n_train: 6
28
+ n_train_vis: 2
29
+ train_start_seed: 0
30
+ n_test: 50
31
+ n_test_vis: 4
32
+ legacy_test: True
33
+ test_start_seed: 100000
34
+ max_steps: 300
35
+ n_obs_steps: ${n_obs_steps}
36
+ n_action_steps: ${n_action_steps}
37
+ fps: 10
38
+ past_action: ${past_action_visible}
39
+ n_envs: null
40
+
41
+ dataset:
42
+ _target_: diffusion_policy.dataset.robot_image_dataset.RobotImageDataset
43
+ zarr_path: /data2/wushuang/my_projects/Aloha2-CollectData-DeformableObject/policy_training/dp.zarr
44
+ aloha_manifest_split: true
45
+ batch_size: ${dataloader.batch_size}
46
+ horizon: ${horizon}
47
+ pad_before: ${eval:'${n_obs_steps}-1'}
48
+ pad_after: ${eval:'${n_action_steps}-1'}
49
+ seed: 42
50
+ val_ratio: 0.02
51
+ max_train_episodes: null
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/config/task/default_task.yaml ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: task_config
2
+
3
+ image_shape: &image_shape [3, 240, 320]
4
+ shape_meta: &shape_meta
5
+ # acceptable types: rgb, low_dim
6
+ obs:
7
+ head_cam:
8
+ shape: *image_shape
9
+ type: rgb
10
+ # front_cam:
11
+ # shape: *image_shape
12
+ # type: rgb
13
+ # left_cam:
14
+ # shape: *image_shape
15
+ # type: rgb
16
+ # right_cam:
17
+ # shape: *image_shape
18
+ # type: rgb
19
+ # agent_pos:
20
+ # shape: null
21
+ # type: low_dim
22
+ action:
23
+ shape: null
24
+
25
+ env_runner:
26
+ _target_: diffusion_policy.env_runner.pusht_image_runner.PushTImageRunner
27
+ n_train: 6
28
+ n_train_vis: 2
29
+ train_start_seed: 0
30
+ n_test: 50
31
+ n_test_vis: 4
32
+ legacy_test: True
33
+ test_start_seed: 100000
34
+ max_steps: 300
35
+ n_obs_steps: ${n_obs_steps}
36
+ n_action_steps: ${n_action_steps}
37
+ fps: 10
38
+ past_action: ${past_action_visible}
39
+ n_envs: null
40
+
41
+ dataset:
42
+ _target_: diffusion_policy.dataset.robot_image_dataset.RobotImageDataset
43
+ zarr_path: null
44
+ batch_size: ${dataloader.batch_size}
45
+ horizon: ${horizon}
46
+ pad_before: ${eval:'${n_obs_steps}-1'}
47
+ pad_after: ${eval:'${n_action_steps}-1'}
48
+ seed: 42
49
+ val_ratio: 0.02
50
+ max_train_episodes: null
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/dataset/base_dataset.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict
2
+
3
+ import torch
4
+ import torch.nn
5
+ from diffusion_policy.model.common.normalizer import LinearNormalizer
6
+
7
+
8
+ class BaseLowdimDataset(torch.utils.data.Dataset):
9
+
10
+ def get_validation_dataset(self) -> "BaseLowdimDataset":
11
+ # return an empty dataset by default
12
+ return BaseLowdimDataset()
13
+
14
+ def get_normalizer(self, **kwargs) -> LinearNormalizer:
15
+ raise NotImplementedError()
16
+
17
+ def get_all_actions(self) -> torch.Tensor:
18
+ raise NotImplementedError()
19
+
20
+ def __len__(self) -> int:
21
+ return 0
22
+
23
+ def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
24
+ """
25
+ output:
26
+ obs: T, Do
27
+ action: T, Da
28
+ """
29
+ raise NotImplementedError()
30
+
31
+
32
+ class BaseImageDataset(torch.utils.data.Dataset):
33
+
34
+ def get_validation_dataset(self) -> "BaseLowdimDataset":
35
+ # return an empty dataset by default
36
+ return BaseImageDataset()
37
+
38
+ def get_normalizer(self, **kwargs) -> LinearNormalizer:
39
+ raise NotImplementedError()
40
+
41
+ def get_all_actions(self) -> torch.Tensor:
42
+ raise NotImplementedError()
43
+
44
+ def __len__(self) -> int:
45
+ return 0
46
+
47
+ def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]:
48
+ """
49
+ output:
50
+ obs:
51
+ key: T, *
52
+ action: T, Da
53
+ """
54
+ raise NotImplementedError()
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/dataset/robot_image_dataset.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict
2
+ import numba
3
+ import torch
4
+ import numpy as np
5
+ import copy
6
+ from diffusion_policy.common.pytorch_util import dict_apply
7
+ from diffusion_policy.common.replay_buffer import ReplayBuffer
8
+ from diffusion_policy.common.sampler import (
9
+ SequenceSampler,
10
+ get_val_mask,
11
+ downsample_mask,
12
+ )
13
+ from diffusion_policy.model.common.normalizer import LinearNormalizer
14
+ from diffusion_policy.dataset.base_dataset import BaseImageDataset
15
+ from diffusion_policy.common.normalize_util import get_image_range_normalizer
16
+
17
+ class RobotImageDataset(BaseImageDataset):
18
+
19
+ def __init__(
20
+ self,
21
+ zarr_path,
22
+ horizon=1,
23
+ pad_before=0,
24
+ pad_after=0,
25
+ seed=42,
26
+ val_ratio=0.0,
27
+ batch_size=128,
28
+ max_train_episodes=None,
29
+ aloha_manifest_split=False,
30
+ ):
31
+
32
+ super().__init__()
33
+ if aloha_manifest_split:
34
+ self.replay_buffer = ReplayBuffer.create_from_path(zarr_path, mode="r")
35
+ if not self.replay_buffer.root.attrs.get("complete", False):
36
+ raise ValueError("Incomplete Aloha Zarr conversion")
37
+ else:
38
+ self.replay_buffer = ReplayBuffer.copy_from_path(
39
+ zarr_path, keys=["head_camera", "left_camera", "right_camera", "state", "action"])
40
+ self.aloha_manifest_split = aloha_manifest_split
41
+
42
+ val_mask = get_val_mask(n_episodes=self.replay_buffer.n_episodes, val_ratio=val_ratio, seed=seed)
43
+ train_mask = np.asarray(self.replay_buffer.root["meta/train_mask"][:], dtype=bool) if aloha_manifest_split else ~val_mask
44
+ train_mask = downsample_mask(mask=train_mask, max_n=max_train_episodes, seed=seed)
45
+
46
+ self.sampler = SequenceSampler(
47
+ replay_buffer=self.replay_buffer,
48
+ sequence_length=horizon,
49
+ pad_before=pad_before,
50
+ pad_after=pad_after,
51
+ episode_mask=train_mask,
52
+ )
53
+ self.train_mask = train_mask
54
+ self.horizon = horizon
55
+ self.pad_before = pad_before
56
+ self.pad_after = pad_after
57
+
58
+ self.batch_size = batch_size
59
+ sequence_length = self.sampler.sequence_length
60
+ self.buffers = {
61
+ k: np.zeros((batch_size, sequence_length, *v.shape[1:]), dtype=v.dtype)
62
+ for k, v in self.sampler.replay_buffer.items()
63
+ }
64
+ self.buffers_torch = {k: torch.from_numpy(v) for k, v in self.buffers.items()}
65
+ for v in self.buffers_torch.values():
66
+ if torch.cuda.is_available():
67
+ v.pin_memory()
68
+
69
+ def get_validation_dataset(self):
70
+ val_set = copy.copy(self)
71
+ val_set.sampler = SequenceSampler(
72
+ replay_buffer=self.replay_buffer,
73
+ sequence_length=self.horizon,
74
+ pad_before=self.pad_before,
75
+ pad_after=self.pad_after,
76
+ episode_mask=~self.train_mask,
77
+ )
78
+ val_set.train_mask = ~self.train_mask
79
+ return val_set
80
+
81
+ def get_normalizer(self, mode="limits", **kwargs):
82
+ if self.aloha_manifest_split:
83
+ ends = self.replay_buffer.episode_ends[:]
84
+ starts = np.r_[0, ends[:-1]]
85
+ data = {key: np.concatenate([self.replay_buffer[src][int(a):int(b)] for a, b, keep in zip(starts, ends, self.train_mask) if keep])
86
+ for key, src in (("action", "action"), ("agent_pos", "state"))}
87
+ else:
88
+ data = {"action": self.replay_buffer["action"], "agent_pos": self.replay_buffer["state"]}
89
+ normalizer = LinearNormalizer()
90
+ normalizer.fit(data=data, last_n_dims=1, mode=mode, **kwargs)
91
+ normalizer["head_cam"] = get_image_range_normalizer()
92
+ # normalizer["front_cam"] = get_image_range_normalizer()
93
+ normalizer["left_cam"] = get_image_range_normalizer()
94
+ normalizer["right_cam"] = get_image_range_normalizer()
95
+ return normalizer
96
+
97
+ def __len__(self) -> int:
98
+ return len(self.sampler)
99
+
100
+ def _sample_to_data(self, sample):
101
+ agent_pos = sample["state"].astype(np.float32) # (agent_posx2, block_posex3)
102
+ head_cam = np.moveaxis(sample["head_camera"], -1, 1) / 255
103
+ # front_cam = np.moveaxis(sample['front_camera'],-1,1)/255
104
+ left_cam = np.moveaxis(sample['left_camera'],-1,1) / 255
105
+ right_cam = np.moveaxis(sample['right_camera'],-1,1) / 255
106
+
107
+ data = {
108
+ "obs": {
109
+ "head_cam": head_cam, # T, 3, H, W
110
+ # 'front_cam': front_cam, # T, 3, H, W
111
+ 'left_cam': left_cam, # T, 3, H, W
112
+ 'right_cam': right_cam, # T, 3, H, W
113
+ "agent_pos": agent_pos, # T, D
114
+ },
115
+ "action": sample["action"].astype(np.float32), # T, D
116
+ }
117
+ return data
118
+
119
+ def __getitem__(self, idx) -> Dict[str, torch.Tensor]:
120
+ if isinstance(idx, slice):
121
+ raise NotImplementedError # Specialized
122
+ elif isinstance(idx, int):
123
+ sample = self.sampler.sample_sequence(idx)
124
+ sample = dict_apply(sample, torch.from_numpy)
125
+ return sample
126
+ elif isinstance(idx, np.ndarray):
127
+ if self.aloha_manifest_split:
128
+ samples = [self.sampler.sample_sequence(int(i)) for i in idx]
129
+ return {key: torch.from_numpy(np.stack([s[key] for s in samples])) for key in samples[0]}
130
+ assert len(idx) == self.batch_size
131
+ for k, v in self.sampler.replay_buffer.items():
132
+ batch_sample_sequence(
133
+ self.buffers[k],
134
+ v,
135
+ self.sampler.indices,
136
+ idx,
137
+ self.sampler.sequence_length,
138
+ )
139
+ return self.buffers_torch
140
+ else:
141
+ raise ValueError(idx)
142
+
143
+ def postprocess(self, samples, device):
144
+ agent_pos = samples["state"].to(device, non_blocking=True)
145
+ head_cam = samples["head_camera"].to(device, non_blocking=True) / 255.0
146
+ # front_cam = samples['front_camera'].to(device, non_blocking=True) / 255.0
147
+ left_cam = samples['left_camera'].to(device, non_blocking=True) / 255.0
148
+ right_cam = samples['right_camera'].to(device, non_blocking=True) / 255.0
149
+ action = samples["action"].to(device, non_blocking=True)
150
+ return {
151
+ "obs": {
152
+ "head_cam": head_cam, # B, T, 3, H, W
153
+ # 'front_cam': front_cam, # B, T, 3, H, W
154
+ 'left_cam': left_cam, # B, T, 3, H, W
155
+ 'right_cam': right_cam, # B, T, 3, H, W
156
+ "agent_pos": agent_pos, # B, T, D
157
+ },
158
+ "action": action, # B, T, D
159
+ }
160
+
161
+
162
+ def _batch_sample_sequence(
163
+ data: np.ndarray,
164
+ input_arr: np.ndarray,
165
+ indices: np.ndarray,
166
+ idx: np.ndarray,
167
+ sequence_length: int,
168
+ ):
169
+ for i in numba.prange(len(idx)):
170
+ buffer_start_idx, buffer_end_idx, sample_start_idx, sample_end_idx = indices[idx[i]]
171
+ data[i, sample_start_idx:sample_end_idx] = input_arr[buffer_start_idx:buffer_end_idx]
172
+ if sample_start_idx > 0:
173
+ data[i, :sample_start_idx] = data[i, sample_start_idx]
174
+ if sample_end_idx < sequence_length:
175
+ data[i, sample_end_idx:] = data[i, sample_end_idx - 1]
176
+
177
+
178
+ _batch_sample_sequence_sequential = numba.jit(_batch_sample_sequence, nopython=True, parallel=False)
179
+ _batch_sample_sequence_parallel = numba.jit(_batch_sample_sequence, nopython=True, parallel=True)
180
+
181
+
182
+ def batch_sample_sequence(
183
+ data: np.ndarray,
184
+ input_arr: np.ndarray,
185
+ indices: np.ndarray,
186
+ idx: np.ndarray,
187
+ sequence_length: int,
188
+ ):
189
+ batch_size = len(idx)
190
+ assert data.shape == (batch_size, sequence_length, *input_arr.shape[1:])
191
+ if batch_size >= 16 and data.nbytes // batch_size >= 2**16:
192
+ _batch_sample_sequence_parallel(data, input_arr, indices, idx, sequence_length)
193
+ else:
194
+ _batch_sample_sequence_sequential(data, input_arr, indices, idx, sequence_length)
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/action_ae/__init__.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.utils.data import DataLoader
4
+ import abc
5
+
6
+ from typing import Optional, Union
7
+
8
+ import diffusion_policy.model.bet.utils as utils
9
+
10
+
11
+ class AbstractActionAE(utils.SaveModule, abc.ABC):
12
+
13
+ @abc.abstractmethod
14
+ def fit_model(
15
+ self,
16
+ input_dataloader: DataLoader,
17
+ eval_dataloader: DataLoader,
18
+ obs_encoding_net: Optional[nn.Module] = None,
19
+ ) -> None:
20
+ pass
21
+
22
+ @abc.abstractmethod
23
+ def encode_into_latent(
24
+ self,
25
+ input_action: torch.Tensor,
26
+ input_rep: Optional[torch.Tensor],
27
+ ) -> torch.Tensor:
28
+ """
29
+ Given the input action, discretize it.
30
+
31
+ Inputs:
32
+ input_action (shape: ... x action_dim): The input action to discretize. This can be in a batch,
33
+ and is generally assumed that the last dimnesion is the action dimension.
34
+
35
+ Outputs:
36
+ discretized_action (shape: ... x num_tokens): The discretized action.
37
+ """
38
+ raise NotImplementedError
39
+
40
+ @abc.abstractmethod
41
+ def decode_actions(
42
+ self,
43
+ latent_action_batch: Optional[torch.Tensor],
44
+ input_rep_batch: Optional[torch.Tensor] = None,
45
+ ) -> torch.Tensor:
46
+ """
47
+ Given a discretized action, convert it to a continuous action.
48
+
49
+ Inputs:
50
+ latent_action_batch (shape: ... x num_tokens): The discretized action
51
+ generated by the discretizer.
52
+
53
+ Outputs:
54
+ continuous_action (shape: ... x action_dim): The continuous action.
55
+ """
56
+ raise NotImplementedError
57
+
58
+ @property
59
+ @abc.abstractmethod
60
+ def num_latents(self) -> Union[int, float]:
61
+ """
62
+ Number of possible latents for this generator, useful for state priors that use softmax.
63
+ """
64
+ return float("inf")
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/action_ae/discretizers/k_means.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+
4
+ import tqdm
5
+
6
+ from typing import Optional, Tuple, Union
7
+ from diffusion_policy.model.common.dict_of_tensor_mixin import DictOfTensorMixin
8
+
9
+
10
+ class KMeansDiscretizer(DictOfTensorMixin):
11
+ """
12
+ Simplified and modified version of KMeans algorithm from sklearn.
13
+ """
14
+
15
+ def __init__(
16
+ self,
17
+ action_dim: int,
18
+ num_bins: int = 100,
19
+ predict_offsets: bool = False,
20
+ ):
21
+ super().__init__()
22
+ self.n_bins = num_bins
23
+ self.action_dim = action_dim
24
+ self.predict_offsets = predict_offsets
25
+
26
+ def fit_discretizer(self, input_actions: torch.Tensor) -> None:
27
+ assert (self.action_dim == input_actions.shape[-1]
28
+ ), f"Input action dimension {self.action_dim} does not match fitted model {input_actions.shape[-1]}"
29
+
30
+ flattened_actions = input_actions.view(-1, self.action_dim)
31
+ cluster_centers = KMeansDiscretizer._kmeans(flattened_actions, ncluster=self.n_bins)
32
+ self.params_dict["bin_centers"] = cluster_centers
33
+
34
+ @property
35
+ def suggested_actions(self) -> torch.Tensor:
36
+ return self.params_dict["bin_centers"]
37
+
38
+ @classmethod
39
+ def _kmeans(cls, x: torch.Tensor, ncluster: int = 512, niter: int = 50):
40
+ """
41
+ Simple k-means clustering algorithm adapted from Karpathy's minGPT library
42
+ https://github.com/karpathy/minGPT/blob/master/play_image.ipynb
43
+ """
44
+ N, D = x.size()
45
+ c = x[torch.randperm(N)[:ncluster]] # init clusters at random
46
+
47
+ pbar = tqdm.trange(niter)
48
+ pbar.set_description("K-means clustering")
49
+ for i in pbar:
50
+ # assign all pixels to the closest codebook element
51
+ a = ((x[:, None, :] - c[None, :, :])**2).sum(-1).argmin(1)
52
+ # move each codebook element to be the mean of the pixels that assigned to it
53
+ c = torch.stack([x[a == k].mean(0) for k in range(ncluster)])
54
+ # re-assign any poorly positioned codebook elements
55
+ nanix = torch.any(torch.isnan(c), dim=1)
56
+ ndead = nanix.sum().item()
57
+ if ndead:
58
+ tqdm.tqdm.write("done step %d/%d, re-initialized %d dead clusters" % (i + 1, niter, ndead))
59
+ c[nanix] = x[torch.randperm(N)[:ndead]] # re-init dead clusters
60
+ return c
61
+
62
+ def encode_into_latent(self, input_action: torch.Tensor, input_rep: Optional[torch.Tensor] = None) -> torch.Tensor:
63
+ """
64
+ Given the input action, discretize it using the k-Means clustering algorithm.
65
+
66
+ Inputs:
67
+ input_action (shape: ... x action_dim): The input action to discretize. This can be in a batch,
68
+ and is generally assumed that the last dimnesion is the action dimension.
69
+
70
+ Outputs:
71
+ discretized_action (shape: ... x num_tokens): The discretized action.
72
+ If self.predict_offsets is True, then the offsets are also returned.
73
+ """
74
+ assert (input_action.shape[-1] == self.action_dim), "Input action dimension does not match fitted model"
75
+
76
+ # flatten the input action
77
+ flattened_actions = input_action.view(-1, self.action_dim)
78
+
79
+ # get the closest cluster center
80
+ closest_cluster_center = torch.argmin(
81
+ torch.sum(
82
+ (flattened_actions[:, None, :] - self.params_dict["bin_centers"][None, :, :])**2,
83
+ dim=2,
84
+ ),
85
+ dim=1,
86
+ )
87
+ # Reshape to the original shape
88
+ discretized_action = closest_cluster_center.view(input_action.shape[:-1] + (1, ))
89
+
90
+ if self.predict_offsets:
91
+ # decode from latent and get the difference
92
+ reconstructed_action = self.decode_actions(discretized_action)
93
+ offsets = input_action - reconstructed_action
94
+ return (discretized_action, offsets)
95
+ else:
96
+ # return the one-hot vector
97
+ return discretized_action
98
+
99
+ def decode_actions(
100
+ self,
101
+ latent_action_batch: torch.Tensor,
102
+ input_rep_batch: Optional[torch.Tensor] = None,
103
+ ) -> torch.Tensor:
104
+ """
105
+ Given the latent action, reconstruct the original action.
106
+
107
+ Inputs:
108
+ latent_action (shape: ... x 1): The latent action to reconstruct. This can be in a batch,
109
+ and is generally assumed that the last dimension is the action dimension. If the latent_action_batch
110
+ is a tuple, then it is assumed to be (discretized_action, offsets).
111
+
112
+ Outputs:
113
+ reconstructed_action (shape: ... x action_dim): The reconstructed action.
114
+ """
115
+ offsets = None
116
+ if type(latent_action_batch) == tuple:
117
+ latent_action_batch, offsets = latent_action_batch
118
+ # get the closest cluster center
119
+ closest_cluster_center = self.params_dict["bin_centers"][latent_action_batch]
120
+ # Reshape to the original shape
121
+ reconstructed_action = closest_cluster_center.view(latent_action_batch.shape[:-1] + (self.action_dim, ))
122
+ if offsets is not None:
123
+ reconstructed_action += offsets
124
+ return reconstructed_action
125
+
126
+ @property
127
+ def discretized_space(self) -> int:
128
+ return self.n_bins
129
+
130
+ @property
131
+ def latent_dim(self) -> int:
132
+ return 1
133
+
134
+ @property
135
+ def num_latents(self) -> int:
136
+ return self.n_bins
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/latent_generators/latent_generator.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import torch
3
+ from typing import Tuple, Optional
4
+
5
+ import diffusion_policy.model.bet.utils as utils
6
+
7
+
8
+ class AbstractLatentGenerator(abc.ABC, utils.SaveModule):
9
+ """
10
+ Abstract class for a generative model that can generate latents given observation representations.
11
+
12
+ In the probabilisitc sense, this model fits and samples from P(latent|observation) given some observation.
13
+ """
14
+
15
+ @abc.abstractmethod
16
+ def get_latent_and_loss(
17
+ self,
18
+ obs_rep: torch.Tensor,
19
+ target_latents: torch.Tensor,
20
+ seq_masks: Optional[torch.Tensor] = None,
21
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
22
+ """
23
+ Given a set of observation representation and generated latents, get the encoded latent and the loss.
24
+
25
+ Inputs:
26
+ input_action: Batch of the actions taken in the multimodal demonstrations.
27
+ target_latents: Batch of the latents that the generator should learn to generate the actions from.
28
+ seq_masks: Batch of masks that indicate which timesteps are valid.
29
+
30
+ Outputs:
31
+ latent: The sampled latent from the observation.
32
+ loss: The loss of the latent generator.
33
+ """
34
+ pass
35
+
36
+ @abc.abstractmethod
37
+ def generate_latents(self, seq_obses: torch.Tensor, seq_masks: torch.Tensor) -> torch.Tensor:
38
+ """
39
+ Given a batch of sequences of observations, generate a batch of sequences of latents.
40
+
41
+ Inputs:
42
+ seq_obses: Batch of sequences of observations, of shape seq x batch x dim, following the transformer convention.
43
+ seq_masks: Batch of sequences of masks, of shape seq x batch, following the transformer convention.
44
+
45
+ Outputs:
46
+ seq_latents: Batch of sequences of latents of shape seq x batch x latent_dim.
47
+ """
48
+ pass
49
+
50
+ def get_optimizer(self, weight_decay: float, learning_rate: float, betas: Tuple[float,
51
+ float]) -> torch.optim.Optimizer:
52
+ """
53
+ Default optimizer class. Override this if you want to use a different optimizer.
54
+ """
55
+ return torch.optim.Adam(self.parameters(), lr=learning_rate, weight_decay=weight_decay, betas=betas)
56
+
57
+
58
+ class LatentGeneratorDataParallel(torch.nn.DataParallel):
59
+
60
+ def get_latent_and_loss(self, *args, **kwargs):
61
+ return self.module.get_latent_and_loss(*args, **kwargs) # type: ignore
62
+
63
+ def generate_latents(self, *args, **kwargs):
64
+ return self.module.generate_latents(*args, **kwargs) # type: ignore
65
+
66
+ def get_optimizer(self, *args, **kwargs):
67
+ return self.module.get_optimizer(*args, **kwargs) # type: ignore
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/latent_generators/mingpt.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import einops
5
+ import diffusion_policy.model.bet.latent_generators.latent_generator as latent_generator
6
+
7
+ import diffusion_policy.model.bet.libraries.mingpt.model as mingpt_model
8
+ import diffusion_policy.model.bet.libraries.mingpt.trainer as mingpt_trainer
9
+ from diffusion_policy.model.bet.libraries.loss_fn import FocalLoss, soft_cross_entropy
10
+
11
+ from typing import Optional, Tuple
12
+
13
+
14
+ class MinGPT(latent_generator.AbstractLatentGenerator):
15
+
16
+ def __init__(
17
+ self,
18
+ input_dim: int,
19
+ n_layer: int = 12,
20
+ n_head: int = 12,
21
+ n_embd: int = 768,
22
+ embd_pdrop: float = 0.1,
23
+ resid_pdrop: float = 0.1,
24
+ attn_pdrop: float = 0.1,
25
+ block_size: int = 128,
26
+ vocab_size: int = 50257,
27
+ latent_dim: int = 768, # Ignore, used for compatibility with other models.
28
+ action_dim: int = 0,
29
+ discrete_input: bool = False,
30
+ predict_offsets: bool = False,
31
+ offset_loss_scale: float = 1.0,
32
+ focal_loss_gamma: float = 0.0,
33
+ **kwargs):
34
+ super().__init__()
35
+ self.input_size = input_dim
36
+ self.n_layer = n_layer
37
+ self.n_head = n_head
38
+ self.n_embd = n_embd
39
+ self.embd_pdrop = embd_pdrop
40
+ self.resid_pdrop = resid_pdrop
41
+ self.attn_pdrop = attn_pdrop
42
+ self.block_size = block_size
43
+ self.vocab_size = vocab_size
44
+ self.action_dim = action_dim
45
+ self.predict_offsets = predict_offsets
46
+ self.offset_loss_scale = offset_loss_scale
47
+ self.focal_loss_gamma = focal_loss_gamma
48
+ for k, v in kwargs.items():
49
+ setattr(self, k, v)
50
+
51
+ gpt_config = mingpt_model.GPTConfig(
52
+ input_size=self.input_size,
53
+ vocab_size=(self.vocab_size * (1 + self.action_dim) if self.predict_offsets else self.vocab_size),
54
+ block_size=self.block_size,
55
+ n_layer=n_layer,
56
+ n_head=n_head,
57
+ n_embd=n_embd,
58
+ discrete_input=discrete_input,
59
+ embd_pdrop=embd_pdrop,
60
+ resid_pdrop=resid_pdrop,
61
+ attn_pdrop=attn_pdrop,
62
+ )
63
+
64
+ self.model = mingpt_model.GPT(gpt_config)
65
+
66
+ def get_latent_and_loss(
67
+ self,
68
+ obs_rep: torch.Tensor,
69
+ target_latents: torch.Tensor,
70
+ seq_masks: Optional[torch.Tensor] = None,
71
+ return_loss_components: bool = False,
72
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
73
+ # Unlike torch.transformers, GPT takes in batch x seq_len x embd_dim
74
+ # obs_rep = einops.rearrange(obs_rep, "seq batch embed -> batch seq embed")
75
+ # target_latents = einops.rearrange(
76
+ # target_latents, "seq batch embed -> batch seq embed"
77
+ # )
78
+ # While this has been trained autoregressively,
79
+ # there is no reason why it needs to be so.
80
+ # We can just use the observation as the input and the next latent as the target.
81
+ if self.predict_offsets:
82
+ target_latents, target_offsets = target_latents
83
+ is_soft_target = (target_latents.shape[-1] == self.vocab_size) and (self.vocab_size != 1)
84
+ if is_soft_target:
85
+ target_latents = target_latents.view(-1, target_latents.size(-1))
86
+ criterion = soft_cross_entropy
87
+ else:
88
+ target_latents = target_latents.view(-1)
89
+ if self.vocab_size == 1:
90
+ # unify k-means (target_class == 0) and GMM (target_prob == 1)
91
+ target_latents = torch.zeros_like(target_latents)
92
+ criterion = FocalLoss(gamma=self.focal_loss_gamma)
93
+ if self.predict_offsets:
94
+ output, _ = self.model(obs_rep)
95
+ logits = output[:, :, :self.vocab_size]
96
+ offsets = output[:, :, self.vocab_size:]
97
+ batch = logits.shape[0]
98
+ seq = logits.shape[1]
99
+ offsets = einops.rearrange(
100
+ offsets,
101
+ "N T (V A) -> (N T) V A", # N = batch, T = seq
102
+ V=self.vocab_size,
103
+ A=self.action_dim,
104
+ )
105
+ # calculate (optionally soft) cross entropy and offset losses
106
+ class_loss = criterion(logits.view(-1, logits.size(-1)), target_latents)
107
+ # offset loss is only calculated on the target class
108
+ # if soft targets, argmax is considered the target class
109
+ selected_offsets = offsets[
110
+ torch.arange(offsets.size(0)),
111
+ (target_latents.argmax(dim=-1).view(-1) if is_soft_target else target_latents.view(-1)),
112
+ ]
113
+ offset_loss = self.offset_loss_scale * F.mse_loss(selected_offsets, target_offsets.view(
114
+ -1, self.action_dim))
115
+ loss = offset_loss + class_loss
116
+ logits = einops.rearrange(logits, "batch seq classes -> seq batch classes")
117
+ offsets = einops.rearrange(
118
+ offsets,
119
+ "(N T) V A -> T N V A", # ? N, T order? Anyway does not affect loss and training (might affect visualization)
120
+ N=batch,
121
+ T=seq,
122
+ )
123
+ if return_loss_components:
124
+ return (
125
+ (logits, offsets),
126
+ loss,
127
+ {
128
+ "offset": offset_loss,
129
+ "class": class_loss,
130
+ "total": loss
131
+ },
132
+ )
133
+ else:
134
+ return (logits, offsets), loss
135
+ else:
136
+ logits, _ = self.model(obs_rep)
137
+ loss = criterion(logits.view(-1, logits.size(-1)), target_latents)
138
+ logits = einops.rearrange(
139
+ logits, "batch seq classes -> seq batch classes"
140
+ ) # ? N, T order? Anyway does not affect loss and training (might affect visualization)
141
+ if return_loss_components:
142
+ return logits, loss, {"class": loss, "total": loss}
143
+ else:
144
+ return logits, loss
145
+
146
+ def generate_latents(self, obs_rep: torch.Tensor) -> torch.Tensor:
147
+ batch, seq, embed = obs_rep.shape
148
+
149
+ output, _ = self.model(obs_rep, None)
150
+ if self.predict_offsets:
151
+ logits = output[:, :, :self.vocab_size]
152
+ offsets = output[:, :, self.vocab_size:]
153
+ offsets = einops.rearrange(
154
+ offsets,
155
+ "N T (V A) -> (N T) V A", # N = batch, T = seq
156
+ V=self.vocab_size,
157
+ A=self.action_dim,
158
+ )
159
+ else:
160
+ logits = output
161
+ probs = F.softmax(logits, dim=-1)
162
+ batch, seq, choices = probs.shape
163
+ # Sample from the multinomial distribution, one per row.
164
+ sampled_data = torch.multinomial(probs.view(-1, choices), num_samples=1)
165
+ sampled_data = einops.rearrange(sampled_data, "(batch seq) 1 -> batch seq 1", batch=batch, seq=seq)
166
+ if self.predict_offsets:
167
+ sampled_offsets = offsets[torch.arange(offsets.shape[0]),
168
+ sampled_data.flatten()].view(batch, seq, self.action_dim)
169
+
170
+ return (sampled_data, sampled_offsets)
171
+ else:
172
+ return sampled_data
173
+
174
+ def get_optimizer(self, weight_decay: float, learning_rate: float, betas: Tuple[float,
175
+ float]) -> torch.optim.Optimizer:
176
+ trainer_cfg = mingpt_trainer.TrainerConfig(weight_decay=weight_decay, learning_rate=learning_rate, betas=betas)
177
+ return self.model.configure_optimizers(trainer_cfg)
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/latent_generators/transformer.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import einops
5
+ import diffusion_policy.model.bet.latent_generators.latent_generator as latent_generator
6
+
7
+ from diffusion_policy.model.diffusion.transformer_for_diffusion import (
8
+ TransformerForDiffusion, )
9
+ from diffusion_policy.model.bet.libraries.loss_fn import FocalLoss, soft_cross_entropy
10
+
11
+ from typing import Optional, Tuple
12
+
13
+
14
+ class Transformer(latent_generator.AbstractLatentGenerator):
15
+
16
+ def __init__(self, input_dim: int, num_bins: int, action_dim: int, horizon: int, focal_loss_gamma: float,
17
+ offset_loss_scale: float, **kwargs):
18
+ super().__init__()
19
+ self.model = TransformerForDiffusion(input_dim=input_dim,
20
+ output_dim=num_bins * (1 + action_dim),
21
+ horizon=horizon,
22
+ **kwargs)
23
+ self.vocab_size = num_bins
24
+ self.focal_loss_gamma = focal_loss_gamma
25
+ self.offset_loss_scale = offset_loss_scale
26
+ self.action_dim = action_dim
27
+
28
+ def get_optimizer(self, **kwargs) -> torch.optim.Optimizer:
29
+ return self.model.configure_optimizers(**kwargs)
30
+
31
+ def get_latent_and_loss(
32
+ self,
33
+ obs_rep: torch.Tensor,
34
+ target_latents: torch.Tensor,
35
+ return_loss_components=True,
36
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
37
+ target_latents, target_offsets = target_latents
38
+ target_latents = target_latents.view(-1)
39
+ criterion = FocalLoss(gamma=self.focal_loss_gamma)
40
+
41
+ t = torch.tensor(0, device=self.model.device)
42
+ output = self.model(obs_rep, t)
43
+ logits = output[:, :, :self.vocab_size]
44
+ offsets = output[:, :, self.vocab_size:]
45
+ batch = logits.shape[0]
46
+ seq = logits.shape[1]
47
+ offsets = einops.rearrange(
48
+ offsets,
49
+ "N T (V A) -> (N T) V A", # N = batch, T = seq
50
+ V=self.vocab_size,
51
+ A=self.action_dim,
52
+ )
53
+ # calculate (optionally soft) cross entropy and offset losses
54
+ class_loss = criterion(logits.view(-1, logits.size(-1)), target_latents)
55
+ # offset loss is only calculated on the target class
56
+ # if soft targets, argmax is considered the target class
57
+ selected_offsets = offsets[
58
+ torch.arange(offsets.size(0)),
59
+ target_latents.view(-1),
60
+ ]
61
+ offset_loss = self.offset_loss_scale * F.mse_loss(selected_offsets, target_offsets.view(-1, self.action_dim))
62
+ loss = offset_loss + class_loss
63
+ logits = einops.rearrange(logits, "batch seq classes -> seq batch classes")
64
+ offsets = einops.rearrange(
65
+ offsets,
66
+ "(N T) V A -> T N V A", # ? N, T order? Anyway does not affect loss and training (might affect visualization)
67
+ N=batch,
68
+ T=seq,
69
+ )
70
+ return (
71
+ (logits, offsets),
72
+ loss,
73
+ {
74
+ "offset": offset_loss,
75
+ "class": class_loss,
76
+ "total": loss
77
+ },
78
+ )
79
+
80
+ def generate_latents(self, obs_rep: torch.Tensor) -> torch.Tensor:
81
+ t = torch.tensor(0, device=self.model.device)
82
+ output = self.model(obs_rep, t)
83
+ logits = output[:, :, :self.vocab_size]
84
+ offsets = output[:, :, self.vocab_size:]
85
+ offsets = einops.rearrange(
86
+ offsets,
87
+ "N T (V A) -> (N T) V A", # N = batch, T = seq
88
+ V=self.vocab_size,
89
+ A=self.action_dim,
90
+ )
91
+
92
+ probs = F.softmax(logits, dim=-1)
93
+ batch, seq, choices = probs.shape
94
+ # Sample from the multinomial distribution, one per row.
95
+ sampled_data = torch.multinomial(probs.view(-1, choices), num_samples=1)
96
+ sampled_data = einops.rearrange(sampled_data, "(batch seq) 1 -> batch seq 1", batch=batch, seq=seq)
97
+ sampled_offsets = offsets[torch.arange(offsets.shape[0]),
98
+ sampled_data.flatten()].view(batch, seq, self.action_dim)
99
+ return (sampled_data, sampled_offsets)
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/loss_fn.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Sequence
2
+
3
+ import torch
4
+ from torch import Tensor
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+
8
+
9
+ # Reference: https://github.com/pytorch/pytorch/issues/11959
10
+ def soft_cross_entropy(
11
+ input: torch.Tensor,
12
+ target: torch.Tensor,
13
+ ) -> torch.Tensor:
14
+ """
15
+ Args:
16
+ input: (batch_size, num_classes): tensor of raw logits
17
+ target: (batch_size, num_classes): tensor of class probability; sum(target) == 1
18
+
19
+ Returns:
20
+ loss: (batch_size,)
21
+ """
22
+ log_probs = torch.log_softmax(input, dim=-1)
23
+ # target is a distribution
24
+ loss = F.kl_div(log_probs, target, reduction="batchmean")
25
+ return loss
26
+
27
+
28
+ # Focal loss implementation
29
+ # Source: https://github.com/AdeelH/pytorch-multi-class-focal-loss/blob/master/focal_loss.py
30
+ # MIT License
31
+ #
32
+ # Copyright (c) 2020 Adeel Hassan
33
+ #
34
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
35
+ # of this software and associated documentation files (the "Software"), to deal
36
+ # in the Software without restriction, including without limitation the rights
37
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
38
+ # copies of the Software, and to permit persons to whom the Software is
39
+ # furnished to do so, subject to the following conditions:
40
+ #
41
+ # The above copyright notice and this permission notice shall be included in all
42
+ # copies or substantial portions of the Software.
43
+ #
44
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
45
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
46
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
47
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
48
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
49
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
50
+ # SOFTWARE.
51
+ class FocalLoss(nn.Module):
52
+ """Focal Loss, as described in https://arxiv.org/abs/1708.02002.
53
+ It is essentially an enhancement to cross entropy loss and is
54
+ useful for classification tasks when there is a large class imbalance.
55
+ x is expected to contain raw, unnormalized scores for each class.
56
+ y is expected to contain class labels.
57
+ Shape:
58
+ - x: (batch_size, C) or (batch_size, C, d1, d2, ..., dK), K > 0.
59
+ - y: (batch_size,) or (batch_size, d1, d2, ..., dK), K > 0.
60
+ """
61
+
62
+ def __init__(
63
+ self,
64
+ alpha: Optional[Tensor] = None,
65
+ gamma: float = 0.0,
66
+ reduction: str = "mean",
67
+ ignore_index: int = -100,
68
+ ):
69
+ """Constructor.
70
+ Args:
71
+ alpha (Tensor, optional): Weights for each class. Defaults to None.
72
+ gamma (float, optional): A constant, as described in the paper.
73
+ Defaults to 0.
74
+ reduction (str, optional): 'mean', 'sum' or 'none'.
75
+ Defaults to 'mean'.
76
+ ignore_index (int, optional): class label to ignore.
77
+ Defaults to -100.
78
+ """
79
+ if reduction not in ("mean", "sum", "none"):
80
+ raise ValueError('Reduction must be one of: "mean", "sum", "none".')
81
+
82
+ super().__init__()
83
+ self.alpha = alpha
84
+ self.gamma = gamma
85
+ self.ignore_index = ignore_index
86
+ self.reduction = reduction
87
+
88
+ self.nll_loss = nn.NLLLoss(weight=alpha, reduction="none", ignore_index=ignore_index)
89
+
90
+ def __repr__(self):
91
+ arg_keys = ["alpha", "gamma", "ignore_index", "reduction"]
92
+ arg_vals = [self.__dict__[k] for k in arg_keys]
93
+ arg_strs = [f"{k}={v}" for k, v in zip(arg_keys, arg_vals)]
94
+ arg_str = ", ".join(arg_strs)
95
+ return f"{type(self).__name__}({arg_str})"
96
+
97
+ def forward(self, x: Tensor, y: Tensor) -> Tensor:
98
+ if x.ndim > 2:
99
+ # (N, C, d1, d2, ..., dK) --> (N * d1 * ... * dK, C)
100
+ c = x.shape[1]
101
+ x = x.permute(0, *range(2, x.ndim), 1).reshape(-1, c)
102
+ # (N, d1, d2, ..., dK) --> (N * d1 * ... * dK,)
103
+ y = y.view(-1)
104
+
105
+ unignored_mask = y != self.ignore_index
106
+ y = y[unignored_mask]
107
+ if len(y) == 0:
108
+ return 0.0
109
+ x = x[unignored_mask]
110
+
111
+ # compute weighted cross entropy term: -alpha * log(pt)
112
+ # (alpha is already part of self.nll_loss)
113
+ log_p = F.log_softmax(x, dim=-1)
114
+ ce = self.nll_loss(log_p, y)
115
+
116
+ # get true class column from each row
117
+ all_rows = torch.arange(len(x))
118
+ log_pt = log_p[all_rows, y]
119
+
120
+ # compute focal term: (1 - pt)^gamma
121
+ pt = log_pt.exp()
122
+ focal_term = (1 - pt)**self.gamma
123
+
124
+ # the full loss: -alpha * ((1 - pt)^gamma) * log(pt)
125
+ loss = focal_term * ce
126
+
127
+ if self.reduction == "mean":
128
+ loss = loss.mean()
129
+ elif self.reduction == "sum":
130
+ loss = loss.sum()
131
+
132
+ return loss
133
+
134
+
135
+ def focal_loss(
136
+ alpha: Optional[Sequence] = None,
137
+ gamma: float = 0.0,
138
+ reduction: str = "mean",
139
+ ignore_index: int = -100,
140
+ device="cpu",
141
+ dtype=torch.float32,
142
+ ) -> FocalLoss:
143
+ """Factory function for FocalLoss.
144
+ Args:
145
+ alpha (Sequence, optional): Weights for each class. Will be converted
146
+ to a Tensor if not None. Defaults to None.
147
+ gamma (float, optional): A constant, as described in the paper.
148
+ Defaults to 0.
149
+ reduction (str, optional): 'mean', 'sum' or 'none'.
150
+ Defaults to 'mean'.
151
+ ignore_index (int, optional): class label to ignore.
152
+ Defaults to -100.
153
+ device (str, optional): Device to move alpha to. Defaults to 'cpu'.
154
+ dtype (torch.dtype, optional): dtype to cast alpha to.
155
+ Defaults to torch.float32.
156
+ Returns:
157
+ A FocalLoss object
158
+ """
159
+ if alpha is not None:
160
+ if not isinstance(alpha, Tensor):
161
+ alpha = torch.tensor(alpha)
162
+ alpha = alpha.to(device=device, dtype=dtype)
163
+
164
+ fl = FocalLoss(alpha=alpha, gamma=gamma, reduction=reduction, ignore_index=ignore_index)
165
+ return fl
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/mingpt/LICENSE ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ The MIT License (MIT) Copyright (c) 2020 Andrej Karpathy
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8
+
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/mingpt/__init__.py ADDED
File without changes
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/mingpt/model.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ GPT model:
3
+ - the initial stem consists of a combination of token encoding and a positional encoding
4
+ - the meat of it is a uniform sequence of Transformer blocks
5
+ - each Transformer is a sequential combination of a 1-hidden-layer MLP block and a self-attention block
6
+ - all blocks feed into a central residual pathway similar to resnets
7
+ - the final decoder is a linear projection into a vanilla Softmax classifier
8
+ """
9
+
10
+ import math
11
+ import logging
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+ from torch.nn import functional as F
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class GPTConfig:
21
+ """base GPT config, params common to all GPT versions"""
22
+
23
+ embd_pdrop = 0.1
24
+ resid_pdrop = 0.1
25
+ attn_pdrop = 0.1
26
+ discrete_input = False
27
+ input_size = 10
28
+ n_embd = 768
29
+ n_layer = 12
30
+
31
+ def __init__(self, vocab_size, block_size, **kwargs):
32
+ self.vocab_size = vocab_size
33
+ self.block_size = block_size
34
+ for k, v in kwargs.items():
35
+ setattr(self, k, v)
36
+
37
+
38
+ class GPT1Config(GPTConfig):
39
+ """GPT-1 like network roughly 125M params"""
40
+
41
+ n_layer = 12
42
+ n_head = 12
43
+ n_embd = 768
44
+
45
+
46
+ class CausalSelfAttention(nn.Module):
47
+ """
48
+ A vanilla multi-head masked self-attention layer with a projection at the end.
49
+ It is possible to use torch.nn.MultiheadAttention here but I am including an
50
+ explicit implementation here to show that there is nothing too scary here.
51
+ """
52
+
53
+ def __init__(self, config):
54
+ super().__init__()
55
+ assert config.n_embd % config.n_head == 0
56
+ # key, query, value projections for all heads
57
+ self.key = nn.Linear(config.n_embd, config.n_embd)
58
+ self.query = nn.Linear(config.n_embd, config.n_embd)
59
+ self.value = nn.Linear(config.n_embd, config.n_embd)
60
+ # regularization
61
+ self.attn_drop = nn.Dropout(config.attn_pdrop)
62
+ self.resid_drop = nn.Dropout(config.resid_pdrop)
63
+ # output projection
64
+ self.proj = nn.Linear(config.n_embd, config.n_embd)
65
+ # causal mask to ensure that attention is only applied to the left in the input sequence
66
+ self.register_buffer(
67
+ "mask",
68
+ torch.tril(torch.ones(config.block_size, config.block_size)).view(1, 1, config.block_size,
69
+ config.block_size),
70
+ )
71
+ self.n_head = config.n_head
72
+
73
+ def forward(self, x):
74
+ (
75
+ B,
76
+ T,
77
+ C,
78
+ ) = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
79
+
80
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
81
+ k = (self.key(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2)) # (B, nh, T, hs)
82
+ q = (self.query(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2)) # (B, nh, T, hs)
83
+ v = (self.value(x).view(B, T, self.n_head, C // self.n_head).transpose(1, 2)) # (B, nh, T, hs)
84
+
85
+ # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
86
+ att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
87
+ att = att.masked_fill(self.mask[:, :, :T, :T] == 0, float("-inf"))
88
+ att = F.softmax(att, dim=-1)
89
+ att = self.attn_drop(att)
90
+ y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
91
+ y = (y.transpose(1, 2).contiguous().view(B, T, C)) # re-assemble all head outputs side by side
92
+
93
+ # output projection
94
+ y = self.resid_drop(self.proj(y))
95
+ return y
96
+
97
+
98
+ class Block(nn.Module):
99
+ """an unassuming Transformer block"""
100
+
101
+ def __init__(self, config):
102
+ super().__init__()
103
+ self.ln1 = nn.LayerNorm(config.n_embd)
104
+ self.ln2 = nn.LayerNorm(config.n_embd)
105
+ self.attn = CausalSelfAttention(config)
106
+ self.mlp = nn.Sequential(
107
+ nn.Linear(config.n_embd, 4 * config.n_embd),
108
+ nn.GELU(),
109
+ nn.Linear(4 * config.n_embd, config.n_embd),
110
+ nn.Dropout(config.resid_pdrop),
111
+ )
112
+
113
+ def forward(self, x):
114
+ x = x + self.attn(self.ln1(x))
115
+ x = x + self.mlp(self.ln2(x))
116
+ return x
117
+
118
+
119
+ class GPT(nn.Module):
120
+ """the full GPT language model, with a context size of block_size"""
121
+
122
+ def __init__(self, config: GPTConfig):
123
+ super().__init__()
124
+
125
+ # input embedding stem
126
+ if config.discrete_input:
127
+ self.tok_emb = nn.Embedding(config.vocab_size, config.n_embd)
128
+ else:
129
+ self.tok_emb = nn.Linear(config.input_size, config.n_embd)
130
+ self.discrete_input = config.discrete_input
131
+ self.pos_emb = nn.Parameter(torch.zeros(1, config.block_size, config.n_embd))
132
+ self.drop = nn.Dropout(config.embd_pdrop)
133
+ # transformer
134
+ self.blocks = nn.Sequential(*[Block(config) for _ in range(config.n_layer)])
135
+ # decoder head
136
+ self.ln_f = nn.LayerNorm(config.n_embd)
137
+ self.head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
138
+
139
+ self.block_size = config.block_size
140
+ self.apply(self._init_weights)
141
+
142
+ logger.info("number of parameters: %e", sum(p.numel() for p in self.parameters()))
143
+
144
+ def get_block_size(self):
145
+ return self.block_size
146
+
147
+ def _init_weights(self, module):
148
+ if isinstance(module, (nn.Linear, nn.Embedding)):
149
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
150
+ if isinstance(module, nn.Linear) and module.bias is not None:
151
+ torch.nn.init.zeros_(module.bias)
152
+ elif isinstance(module, nn.LayerNorm):
153
+ torch.nn.init.zeros_(module.bias)
154
+ torch.nn.init.ones_(module.weight)
155
+ elif isinstance(module, GPT):
156
+ torch.nn.init.normal_(module.pos_emb, mean=0.0, std=0.02)
157
+
158
+ def configure_optimizers(self, train_config):
159
+ """
160
+ This long function is unfortunately doing something very simple and is being very defensive:
161
+ We are separating out all parameters of the model into two buckets: those that will experience
162
+ weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
163
+ We are then returning the PyTorch optimizer object.
164
+ """
165
+
166
+ # separate out all parameters to those that will and won't experience regularizing weight decay
167
+ decay = set()
168
+ no_decay = set()
169
+ whitelist_weight_modules = (torch.nn.Linear, )
170
+ blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)
171
+ for mn, m in self.named_modules():
172
+ for pn, p in m.named_parameters():
173
+ fpn = "%s.%s" % (mn, pn) if mn else pn # full param name
174
+
175
+ if pn.endswith("bias"):
176
+ # all biases will not be decayed
177
+ no_decay.add(fpn)
178
+ elif pn.endswith("weight") and isinstance(m, whitelist_weight_modules):
179
+ # weights of whitelist modules will be weight decayed
180
+ decay.add(fpn)
181
+ elif pn.endswith("weight") and isinstance(m, blacklist_weight_modules):
182
+ # weights of blacklist modules will NOT be weight decayed
183
+ no_decay.add(fpn)
184
+
185
+ # special case the position embedding parameter in the root GPT module as not decayed
186
+ no_decay.add("pos_emb")
187
+
188
+ # validate that we considered every parameter
189
+ param_dict = {pn: p for pn, p in self.named_parameters()}
190
+ inter_params = decay & no_decay
191
+ union_params = decay | no_decay
192
+ assert (len(inter_params) == 0), "parameters %s made it into both decay/no_decay sets!" % (str(inter_params), )
193
+ assert (len(param_dict.keys() -
194
+ union_params) == 0), "parameters %s were not separated into either decay/no_decay set!" % (
195
+ str(param_dict.keys() - union_params), )
196
+
197
+ # create the pytorch optimizer object
198
+ optim_groups = [
199
+ {
200
+ "params": [param_dict[pn] for pn in sorted(list(decay))],
201
+ "weight_decay": train_config.weight_decay,
202
+ },
203
+ {
204
+ "params": [param_dict[pn] for pn in sorted(list(no_decay))],
205
+ "weight_decay": 0.0,
206
+ },
207
+ ]
208
+ optimizer = torch.optim.AdamW(optim_groups, lr=train_config.learning_rate, betas=train_config.betas)
209
+ return optimizer
210
+
211
+ def forward(self, idx, targets=None):
212
+ if self.discrete_input:
213
+ b, t = idx.size()
214
+ else:
215
+ b, t, dim = idx.size()
216
+ assert t <= self.block_size, "Cannot forward, model block size is exhausted."
217
+
218
+ # forward the GPT model
219
+ token_embeddings = self.tok_emb(idx) # each index maps to a (learnable) vector
220
+ position_embeddings = self.pos_emb[:, :t, :] # each position maps to a (learnable) vector
221
+ x = self.drop(token_embeddings + position_embeddings)
222
+ x = self.blocks(x)
223
+ x = self.ln_f(x)
224
+ logits = self.head(x)
225
+
226
+ # if we are given some desired targets also calculate the loss
227
+ loss = None
228
+ if targets is not None:
229
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
230
+
231
+ return logits, loss
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/mingpt/trainer.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Simple training loop; Boilerplate that could apply to any arbitrary neural network,
3
+ so nothing in this file really has anything to do with GPT specifically.
4
+ """
5
+
6
+ import math
7
+ import logging
8
+
9
+ from tqdm import tqdm
10
+ import numpy as np
11
+
12
+ import torch
13
+ import torch.optim as optim
14
+ from torch.optim.lr_scheduler import LambdaLR
15
+ from torch.utils.data.dataloader import DataLoader
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class TrainerConfig:
21
+ # optimization parameters
22
+ max_epochs = 10
23
+ batch_size = 64
24
+ learning_rate = 3e-4
25
+ betas = (0.9, 0.95)
26
+ grad_norm_clip = 1.0
27
+ weight_decay = 0.1 # only applied on matmul weights
28
+ # learning rate decay params: linear warmup followed by cosine decay to 10% of original
29
+ lr_decay = False
30
+ warmup_tokens = 375e6 # these two numbers come from the GPT-3 paper, but may not be good defaults elsewhere
31
+ final_tokens = 260e9 # (at what point we reach 10% of original LR)
32
+ # checkpoint settings
33
+ ckpt_path = None
34
+ num_workers = 0 # for DataLoader
35
+
36
+ def __init__(self, **kwargs):
37
+ for k, v in kwargs.items():
38
+ setattr(self, k, v)
39
+
40
+
41
+ class Trainer:
42
+
43
+ def __init__(self, model, train_dataset, test_dataset, config):
44
+ self.model = model
45
+ self.train_dataset = train_dataset
46
+ self.test_dataset = test_dataset
47
+ self.config = config
48
+
49
+ # take over whatever gpus are on the system
50
+ self.device = "cpu"
51
+ if torch.cuda.is_available():
52
+ self.device = torch.cuda.current_device()
53
+ self.model = torch.nn.DataParallel(self.model).to(self.device)
54
+
55
+ def save_checkpoint(self):
56
+ # DataParallel wrappers keep raw model object in .module attribute
57
+ raw_model = self.model.module if hasattr(self.model, "module") else self.model
58
+ logger.info("saving %s", self.config.ckpt_path)
59
+ torch.save(raw_model.state_dict(), self.config.ckpt_path)
60
+
61
+ def train(self):
62
+ model, config = self.model, self.config
63
+ raw_model = model.module if hasattr(self.model, "module") else model
64
+ optimizer = raw_model.configure_optimizers(config)
65
+
66
+ def run_epoch(loader, is_train):
67
+ model.train(is_train)
68
+
69
+ losses = []
70
+ pbar = (tqdm(enumerate(loader), total=len(loader)) if is_train else enumerate(loader))
71
+ for it, (x, y) in pbar:
72
+
73
+ # place data on the correct device
74
+ x = x.to(self.device)
75
+ y = y.to(self.device)
76
+
77
+ # forward the model
78
+ with torch.set_grad_enabled(is_train):
79
+ logits, loss = model(x, y)
80
+ loss = (loss.mean()) # collapse all losses if they are scattered on multiple gpus
81
+ losses.append(loss.item())
82
+
83
+ if is_train:
84
+
85
+ # backprop and update the parameters
86
+ model.zero_grad()
87
+ loss.backward()
88
+ torch.nn.utils.clip_grad_norm_(model.parameters(), config.grad_norm_clip)
89
+ optimizer.step()
90
+
91
+ # decay the learning rate based on our progress
92
+ if config.lr_decay:
93
+ self.tokens += (y >= 0).sum() # number of tokens processed this step (i.e. label is not -100)
94
+ if self.tokens < config.warmup_tokens:
95
+ # linear warmup
96
+ lr_mult = float(self.tokens) / float(max(1, config.warmup_tokens))
97
+ else:
98
+ # cosine learning rate decay
99
+ progress = float(self.tokens - config.warmup_tokens) / float(
100
+ max(1, config.final_tokens - config.warmup_tokens))
101
+ lr_mult = max(0.1, 0.5 * (1.0 + math.cos(math.pi * progress)))
102
+ lr = config.learning_rate * lr_mult
103
+ for param_group in optimizer.param_groups:
104
+ param_group["lr"] = lr
105
+ else:
106
+ lr = config.learning_rate
107
+
108
+ # report progress
109
+ pbar.set_description( # type: ignore
110
+ f"epoch {epoch+1} iter {it}: train loss {loss.item():.5f}. lr {lr:e}")
111
+
112
+ if not is_train:
113
+ test_loss = float(np.mean(losses))
114
+ logger.info("test loss: %f", test_loss)
115
+ return test_loss
116
+
117
+ best_loss = float("inf")
118
+ self.tokens = 0 # counter used for learning rate decay
119
+
120
+ train_loader = DataLoader(
121
+ self.train_dataset,
122
+ shuffle=True,
123
+ pin_memory=True,
124
+ batch_size=config.batch_size,
125
+ num_workers=config.num_workers,
126
+ )
127
+ if self.test_dataset is not None:
128
+ test_loader = DataLoader(
129
+ self.test_dataset,
130
+ shuffle=True,
131
+ pin_memory=True,
132
+ batch_size=config.batch_size,
133
+ num_workers=config.num_workers,
134
+ )
135
+
136
+ for epoch in range(config.max_epochs):
137
+ run_epoch(train_loader, is_train=True)
138
+ if self.test_dataset is not None:
139
+ test_loss = run_epoch(test_loader, is_train=False)
140
+
141
+ # supports early stopping based on the test loss, or just save always if no test set is provided
142
+ good_model = self.test_dataset is None or test_loss < best_loss
143
+ if self.config.ckpt_path is not None and good_model:
144
+ best_loss = test_loss
145
+ self.save_checkpoint()
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/libraries/mingpt/utils.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch.nn import functional as F
5
+
6
+
7
+ def set_seed(seed):
8
+ random.seed(seed)
9
+ np.random.seed(seed)
10
+ torch.manual_seed(seed)
11
+ torch.cuda.manual_seed_all(seed)
12
+
13
+
14
+ def top_k_logits(logits, k):
15
+ v, ix = torch.topk(logits, k)
16
+ out = logits.clone()
17
+ out[out < v[:, [-1]]] = -float("Inf")
18
+ return out
19
+
20
+
21
+ @torch.no_grad()
22
+ def sample(model, x, steps, temperature=1.0, sample=False, top_k=None):
23
+ """
24
+ take a conditioning sequence of indices in x (of shape (b,t)) and predict the next token in
25
+ the sequence, feeding the predictions back into the model each time. Clearly the sampling
26
+ has quadratic complexity unlike an RNN that is only linear, and has a finite context window
27
+ of block_size, unlike an RNN that has an infinite context window.
28
+ """
29
+ block_size = model.get_block_size()
30
+ model.eval()
31
+ for k in range(steps):
32
+ x_cond = (x if x.size(1) <= block_size else x[:, -block_size:]) # crop context if needed
33
+ logits, _ = model(x_cond)
34
+ # pluck the logits at the final step and scale by temperature
35
+ logits = logits[:, -1, :] / temperature
36
+ # optionally crop probabilities to only the top k options
37
+ if top_k is not None:
38
+ logits = top_k_logits(logits, top_k)
39
+ # apply softmax to convert to probabilities
40
+ probs = F.softmax(logits, dim=-1)
41
+ # sample from the distribution or take the most likely
42
+ if sample:
43
+ ix = torch.multinomial(probs, num_samples=1)
44
+ else:
45
+ _, ix = torch.topk(probs, k=1, dim=-1)
46
+ # append to the sequence and continue
47
+ x = torch.cat((x, ix), dim=1)
48
+
49
+ return x
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/bet/utils.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from collections import OrderedDict
4
+ from typing import List, Optional
5
+
6
+ import einops
7
+ import numpy as np
8
+ import torch
9
+ import torch.nn as nn
10
+
11
+ from torch.utils.data import random_split
12
+ import wandb
13
+
14
+
15
+ def mlp(input_dim, hidden_dim, output_dim, hidden_depth, output_mod=None):
16
+ if hidden_depth == 0:
17
+ mods = [nn.Linear(input_dim, output_dim)]
18
+ else:
19
+ mods = [nn.Linear(input_dim, hidden_dim), nn.ReLU(inplace=True)]
20
+ for i in range(hidden_depth - 1):
21
+ mods += [nn.Linear(hidden_dim, hidden_dim), nn.ReLU(inplace=True)]
22
+ mods.append(nn.Linear(hidden_dim, output_dim))
23
+ if output_mod is not None:
24
+ mods.append(output_mod)
25
+ trunk = nn.Sequential(*mods)
26
+ return trunk
27
+
28
+
29
+ class eval_mode:
30
+
31
+ def __init__(self, *models, no_grad=False):
32
+ self.models = models
33
+ self.no_grad = no_grad
34
+ self.no_grad_context = torch.no_grad()
35
+
36
+ def __enter__(self):
37
+ self.prev_states = []
38
+ for model in self.models:
39
+ self.prev_states.append(model.training)
40
+ model.train(False)
41
+ if self.no_grad:
42
+ self.no_grad_context.__enter__()
43
+
44
+ def __exit__(self, *args):
45
+ if self.no_grad:
46
+ self.no_grad_context.__exit__(*args)
47
+ for model, state in zip(self.models, self.prev_states):
48
+ model.train(state)
49
+ return False
50
+
51
+
52
+ def freeze_module(module: nn.Module) -> nn.Module:
53
+ for param in module.parameters():
54
+ param.requires_grad = False
55
+ module.eval()
56
+ return module
57
+
58
+
59
+ def set_seed_everywhere(seed):
60
+ torch.manual_seed(seed)
61
+ if torch.cuda.is_available():
62
+ torch.cuda.manual_seed_all(seed)
63
+ np.random.seed(seed)
64
+ random.seed(seed)
65
+
66
+
67
+ def shuffle_along_axis(a, axis):
68
+ idx = np.random.rand(*a.shape).argsort(axis=axis)
69
+ return np.take_along_axis(a, idx, axis=axis)
70
+
71
+
72
+ def transpose_batch_timestep(*args):
73
+ return (einops.rearrange(arg, "b t ... -> t b ...") for arg in args)
74
+
75
+
76
+ class TrainWithLogger:
77
+
78
+ def reset_log(self):
79
+ self.log_components = OrderedDict()
80
+
81
+ def log_append(self, log_key, length, loss_components):
82
+ for key, value in loss_components.items():
83
+ key_name = f"{log_key}/{key}"
84
+ count, sum = self.log_components.get(key_name, (0, 0.0))
85
+ self.log_components[key_name] = (
86
+ count + length,
87
+ sum + (length * value.detach().cpu().item()),
88
+ )
89
+
90
+ def flush_log(self, epoch, iterator=None):
91
+ log_components = OrderedDict()
92
+ iterator_log_component = OrderedDict()
93
+ for key, value in self.log_components.items():
94
+ count, sum = value
95
+ to_log = sum / count
96
+ log_components[key] = to_log
97
+ # Set the iterator status
98
+ log_key, name_key = key.split("/")
99
+ iterator_log_name = f"{log_key[0]}{name_key[0]}".upper()
100
+ iterator_log_component[iterator_log_name] = to_log
101
+ postfix = ",".join("{}:{:.2e}".format(key, iterator_log_component[key])
102
+ for key in iterator_log_component.keys())
103
+ if iterator is not None:
104
+ iterator.set_postfix_str(postfix)
105
+ wandb.log(log_components, step=epoch)
106
+ self.log_components = OrderedDict()
107
+
108
+
109
+ class SaveModule(nn.Module):
110
+
111
+ def set_snapshot_path(self, path):
112
+ self.snapshot_path = path
113
+ print(f"Setting snapshot path to {self.snapshot_path}")
114
+
115
+ def save_snapshot(self):
116
+ os.makedirs(self.snapshot_path, exist_ok=True)
117
+ torch.save(self.state_dict(), self.snapshot_path / "snapshot.pth")
118
+
119
+ def load_snapshot(self):
120
+ self.load_state_dict(torch.load(self.snapshot_path / "snapshot.pth"))
121
+
122
+
123
+ def split_datasets(dataset, train_fraction=0.95, random_seed=42):
124
+ dataset_length = len(dataset)
125
+ lengths = [
126
+ int(train_fraction * dataset_length),
127
+ dataset_length - int(train_fraction * dataset_length),
128
+ ]
129
+ train_set, val_set = random_split(dataset, lengths, generator=torch.Generator().manual_seed(random_seed))
130
+ return train_set, val_set
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/common/dict_of_tensor_mixin.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+
4
+
5
+ class DictOfTensorMixin(nn.Module):
6
+
7
+ def __init__(self, params_dict=None):
8
+ super().__init__()
9
+ if params_dict is None:
10
+ params_dict = nn.ParameterDict()
11
+ self.params_dict = params_dict
12
+
13
+ @property
14
+ def device(self):
15
+ return next(iter(self.parameters())).device
16
+
17
+ def _load_from_state_dict(
18
+ self,
19
+ state_dict,
20
+ prefix,
21
+ local_metadata,
22
+ strict,
23
+ missing_keys,
24
+ unexpected_keys,
25
+ error_msgs,
26
+ ):
27
+
28
+ def dfs_add(dest, keys, value: torch.Tensor):
29
+ if len(keys) == 1:
30
+ dest[keys[0]] = value
31
+ return
32
+
33
+ if keys[0] not in dest:
34
+ dest[keys[0]] = nn.ParameterDict()
35
+ dfs_add(dest[keys[0]], keys[1:], value)
36
+
37
+ def load_dict(state_dict, prefix):
38
+ out_dict = nn.ParameterDict()
39
+ for key, value in state_dict.items():
40
+ value: torch.Tensor
41
+ if key.startswith(prefix):
42
+ param_keys = key[len(prefix):].split(".")[1:]
43
+ # if len(param_keys) == 0:
44
+ # import pdb; pdb.set_trace()
45
+ dfs_add(out_dict, param_keys, value.clone())
46
+ return out_dict
47
+
48
+ self.params_dict = load_dict(state_dict, prefix + "params_dict")
49
+ self.params_dict.requires_grad_(False)
50
+ return
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/common/lr_scheduler.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusers.optimization import (
2
+ Union,
3
+ SchedulerType,
4
+ Optional,
5
+ Optimizer,
6
+ TYPE_TO_SCHEDULER_FUNCTION,
7
+ )
8
+
9
+
10
+ def get_scheduler(
11
+ name: Union[str, SchedulerType],
12
+ optimizer: Optimizer,
13
+ num_warmup_steps: Optional[int] = None,
14
+ num_training_steps: Optional[int] = None,
15
+ **kwargs,
16
+ ):
17
+ """
18
+ Added kwargs vs diffuser's original implementation
19
+
20
+ Unified API to get any scheduler from its name.
21
+
22
+ Args:
23
+ name (`str` or `SchedulerType`):
24
+ The name of the scheduler to use.
25
+ optimizer (`torch.optim.Optimizer`):
26
+ The optimizer that will be used during training.
27
+ num_warmup_steps (`int`, *optional*):
28
+ The number of warmup steps to do. This is not required by all schedulers (hence the argument being
29
+ optional), the function will raise an error if it's unset and the scheduler type requires it.
30
+ num_training_steps (`int``, *optional*):
31
+ The number of training steps to do. This is not required by all schedulers (hence the argument being
32
+ optional), the function will raise an error if it's unset and the scheduler type requires it.
33
+ """
34
+ name = SchedulerType(name)
35
+ schedule_func = TYPE_TO_SCHEDULER_FUNCTION[name]
36
+ if name == SchedulerType.CONSTANT:
37
+ return schedule_func(optimizer, **kwargs)
38
+
39
+ # All other schedulers require `num_warmup_steps`
40
+ if num_warmup_steps is None:
41
+ raise ValueError(f"{name} requires `num_warmup_steps`, please provide that argument.")
42
+
43
+ if name == SchedulerType.CONSTANT_WITH_WARMUP:
44
+ return schedule_func(optimizer, num_warmup_steps=num_warmup_steps, **kwargs)
45
+
46
+ # All other schedulers require `num_training_steps`
47
+ if num_training_steps is None:
48
+ raise ValueError(f"{name} requires `num_training_steps`, please provide that argument.")
49
+
50
+ return schedule_func(
51
+ optimizer,
52
+ num_warmup_steps=num_warmup_steps,
53
+ num_training_steps=num_training_steps,
54
+ **kwargs,
55
+ )
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/common/module_attr_mixin.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+
3
+
4
+ class ModuleAttrMixin(nn.Module):
5
+
6
+ def __init__(self):
7
+ super().__init__()
8
+ self._dummy_variable = nn.Parameter()
9
+
10
+ @property
11
+ def device(self):
12
+ return next(iter(self.parameters())).device
13
+
14
+ @property
15
+ def dtype(self):
16
+ return next(iter(self.parameters())).dtype
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/common/normalizer.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, Dict
2
+
3
+ import unittest
4
+ import zarr
5
+ import numpy as np
6
+ import torch
7
+ import torch.nn as nn
8
+ from diffusion_policy.common.pytorch_util import dict_apply
9
+ from diffusion_policy.model.common.dict_of_tensor_mixin import DictOfTensorMixin
10
+
11
+
12
+ class LinearNormalizer(DictOfTensorMixin):
13
+ avaliable_modes = ["limits", "gaussian"]
14
+
15
+ @torch.no_grad()
16
+ def fit(
17
+ self,
18
+ data: Union[Dict, torch.Tensor, np.ndarray, zarr.Array],
19
+ last_n_dims=1,
20
+ dtype=torch.float32,
21
+ mode="limits",
22
+ output_max=1.0,
23
+ output_min=-1.0,
24
+ range_eps=1e-4,
25
+ fit_offset=True,
26
+ ):
27
+ if isinstance(data, dict):
28
+ for key, value in data.items():
29
+ self.params_dict[key] = _fit(
30
+ value,
31
+ last_n_dims=last_n_dims,
32
+ dtype=dtype,
33
+ mode=mode,
34
+ output_max=output_max,
35
+ output_min=output_min,
36
+ range_eps=range_eps,
37
+ fit_offset=fit_offset,
38
+ )
39
+ else:
40
+ self.params_dict["_default"] = _fit(
41
+ data,
42
+ last_n_dims=last_n_dims,
43
+ dtype=dtype,
44
+ mode=mode,
45
+ output_max=output_max,
46
+ output_min=output_min,
47
+ range_eps=range_eps,
48
+ fit_offset=fit_offset,
49
+ )
50
+
51
+ def __call__(self, x: Union[Dict, torch.Tensor, np.ndarray]) -> torch.Tensor:
52
+ return self.normalize(x)
53
+
54
+ def __getitem__(self, key: str):
55
+ return SingleFieldLinearNormalizer(self.params_dict[key])
56
+
57
+ def __setitem__(self, key: str, value: "SingleFieldLinearNormalizer"):
58
+ self.params_dict[key] = value.params_dict
59
+
60
+ def _normalize_impl(self, x, forward=True):
61
+ if isinstance(x, dict):
62
+ result = dict()
63
+ for key, value in x.items():
64
+ params = self.params_dict[key]
65
+ result[key] = _normalize(value, params, forward=forward)
66
+ return result
67
+ else:
68
+ if "_default" not in self.params_dict:
69
+ raise RuntimeError("Not initialized")
70
+ params = self.params_dict["_default"]
71
+ return _normalize(x, params, forward=forward)
72
+
73
+ def normalize(self, x: Union[Dict, torch.Tensor, np.ndarray]) -> torch.Tensor:
74
+ return self._normalize_impl(x, forward=True)
75
+
76
+ def unnormalize(self, x: Union[Dict, torch.Tensor, np.ndarray]) -> torch.Tensor:
77
+ return self._normalize_impl(x, forward=False)
78
+
79
+ def get_input_stats(self) -> Dict:
80
+ if len(self.params_dict) == 0:
81
+ raise RuntimeError("Not initialized")
82
+ if len(self.params_dict) == 1 and "_default" in self.params_dict:
83
+ return self.params_dict["_default"]["input_stats"]
84
+
85
+ result = dict()
86
+ for key, value in self.params_dict.items():
87
+ if key != "_default":
88
+ result[key] = value["input_stats"]
89
+ return result
90
+
91
+ def get_output_stats(self, key="_default"):
92
+ input_stats = self.get_input_stats()
93
+ if "min" in input_stats:
94
+ # no dict
95
+ return dict_apply(input_stats, self.normalize)
96
+
97
+ result = dict()
98
+ for key, group in input_stats.items():
99
+ this_dict = dict()
100
+ for name, value in group.items():
101
+ this_dict[name] = self.normalize({key: value})[key]
102
+ result[key] = this_dict
103
+ return result
104
+
105
+
106
+ class SingleFieldLinearNormalizer(DictOfTensorMixin):
107
+ avaliable_modes = ["limits", "gaussian"]
108
+
109
+ @torch.no_grad()
110
+ def fit(
111
+ self,
112
+ data: Union[torch.Tensor, np.ndarray, zarr.Array],
113
+ last_n_dims=1,
114
+ dtype=torch.float32,
115
+ mode="limits",
116
+ output_max=1.0,
117
+ output_min=-1.0,
118
+ range_eps=1e-4,
119
+ fit_offset=True,
120
+ ):
121
+ self.params_dict = _fit(
122
+ data,
123
+ last_n_dims=last_n_dims,
124
+ dtype=dtype,
125
+ mode=mode,
126
+ output_max=output_max,
127
+ output_min=output_min,
128
+ range_eps=range_eps,
129
+ fit_offset=fit_offset,
130
+ )
131
+
132
+ @classmethod
133
+ def create_fit(cls, data: Union[torch.Tensor, np.ndarray, zarr.Array], **kwargs):
134
+ obj = cls()
135
+ obj.fit(data, **kwargs)
136
+ return obj
137
+
138
+ @classmethod
139
+ def create_manual(
140
+ cls,
141
+ scale: Union[torch.Tensor, np.ndarray],
142
+ offset: Union[torch.Tensor, np.ndarray],
143
+ input_stats_dict: Dict[str, Union[torch.Tensor, np.ndarray]],
144
+ ):
145
+
146
+ def to_tensor(x):
147
+ if not isinstance(x, torch.Tensor):
148
+ x = torch.from_numpy(x)
149
+ x = x.flatten()
150
+ return x
151
+
152
+ # check
153
+ for x in [offset] + list(input_stats_dict.values()):
154
+ assert x.shape == scale.shape
155
+ assert x.dtype == scale.dtype
156
+
157
+ params_dict = nn.ParameterDict({
158
+ "scale": to_tensor(scale),
159
+ "offset": to_tensor(offset),
160
+ "input_stats": nn.ParameterDict(dict_apply(input_stats_dict, to_tensor)),
161
+ })
162
+ return cls(params_dict)
163
+
164
+ @classmethod
165
+ def create_identity(cls, dtype=torch.float32):
166
+ scale = torch.tensor([1], dtype=dtype)
167
+ offset = torch.tensor([0], dtype=dtype)
168
+ input_stats_dict = {
169
+ "min": torch.tensor([-1], dtype=dtype),
170
+ "max": torch.tensor([1], dtype=dtype),
171
+ "mean": torch.tensor([0], dtype=dtype),
172
+ "std": torch.tensor([1], dtype=dtype),
173
+ }
174
+ return cls.create_manual(scale, offset, input_stats_dict)
175
+
176
+ def normalize(self, x: Union[torch.Tensor, np.ndarray]) -> torch.Tensor:
177
+ return _normalize(x, self.params_dict, forward=True)
178
+
179
+ def unnormalize(self, x: Union[torch.Tensor, np.ndarray]) -> torch.Tensor:
180
+ return _normalize(x, self.params_dict, forward=False)
181
+
182
+ def get_input_stats(self):
183
+ return self.params_dict["input_stats"]
184
+
185
+ def get_output_stats(self):
186
+ return dict_apply(self.params_dict["input_stats"], self.normalize)
187
+
188
+ def __call__(self, x: Union[torch.Tensor, np.ndarray]) -> torch.Tensor:
189
+ return self.normalize(x)
190
+
191
+
192
+ def _fit(
193
+ data: Union[torch.Tensor, np.ndarray, zarr.Array],
194
+ last_n_dims=1,
195
+ dtype=torch.float32,
196
+ mode="limits",
197
+ output_max=1.0,
198
+ output_min=-1.0,
199
+ range_eps=1e-4,
200
+ fit_offset=True,
201
+ ):
202
+ assert mode in ["limits", "gaussian"]
203
+ assert last_n_dims >= 0
204
+ assert output_max > output_min
205
+
206
+ # convert data to torch and type
207
+ if isinstance(data, zarr.Array):
208
+ data = data[:]
209
+ if isinstance(data, np.ndarray):
210
+ data = torch.from_numpy(data)
211
+ if dtype is not None:
212
+ data = data.type(dtype)
213
+
214
+ # convert shape
215
+ dim = 1
216
+ if last_n_dims > 0:
217
+ dim = np.prod(data.shape[-last_n_dims:])
218
+ data = data.reshape(-1, dim)
219
+
220
+ # compute input stats min max mean std
221
+ input_min, _ = data.min(axis=0)
222
+ input_max, _ = data.max(axis=0)
223
+ input_mean = data.mean(axis=0)
224
+ input_std = data.std(axis=0)
225
+
226
+ # compute scale and offset
227
+ if mode == "limits":
228
+ if fit_offset:
229
+ # unit scale
230
+ input_range = input_max - input_min
231
+ ignore_dim = input_range < range_eps
232
+ input_range[ignore_dim] = output_max - output_min
233
+ scale = (output_max - output_min) / input_range
234
+ offset = output_min - scale * input_min
235
+ offset[ignore_dim] = (output_max + output_min) / 2 - input_min[ignore_dim]
236
+ # ignore dims scaled to mean of output max and min
237
+ else:
238
+ # use this when data is pre-zero-centered.
239
+ assert output_max > 0
240
+ assert output_min < 0
241
+ # unit abs
242
+ output_abs = min(abs(output_min), abs(output_max))
243
+ input_abs = torch.maximum(torch.abs(input_min), torch.abs(input_max))
244
+ ignore_dim = input_abs < range_eps
245
+ input_abs[ignore_dim] = output_abs
246
+ # don't scale constant channels
247
+ scale = output_abs / input_abs
248
+ offset = torch.zeros_like(input_mean)
249
+ elif mode == "gaussian":
250
+ ignore_dim = input_std < range_eps
251
+ scale = input_std.clone()
252
+ scale[ignore_dim] = 1
253
+ scale = 1 / scale
254
+
255
+ if fit_offset:
256
+ offset = -input_mean * scale
257
+ else:
258
+ offset = torch.zeros_like(input_mean)
259
+
260
+ # save
261
+ this_params = nn.ParameterDict({
262
+ "scale":
263
+ scale,
264
+ "offset":
265
+ offset,
266
+ "input_stats":
267
+ nn.ParameterDict({
268
+ "min": input_min,
269
+ "max": input_max,
270
+ "mean": input_mean,
271
+ "std": input_std,
272
+ }),
273
+ })
274
+ for p in this_params.parameters():
275
+ p.requires_grad_(False)
276
+ return this_params
277
+
278
+
279
+ def _normalize(x, params, forward=True):
280
+ assert "scale" in params
281
+ if isinstance(x, np.ndarray):
282
+ x = torch.from_numpy(x)
283
+ scale = params["scale"]
284
+ offset = params["offset"]
285
+ x = x.to(device=scale.device, dtype=scale.dtype)
286
+ src_shape = x.shape
287
+ # import pdb
288
+ # pdb.set_trace()
289
+ x = x.reshape(-1, scale.shape[0])
290
+ if forward:
291
+ x = x * scale + offset
292
+ else:
293
+ x = (x - offset) / scale
294
+ x = x.reshape(src_shape)
295
+ return x
296
+
297
+
298
+ def test():
299
+ data = torch.zeros((100, 10, 9, 2)).uniform_()
300
+ data[..., 0, 0] = 0
301
+
302
+ normalizer = SingleFieldLinearNormalizer()
303
+ normalizer.fit(data, mode="limits", last_n_dims=2)
304
+ datan = normalizer.normalize(data)
305
+ assert datan.shape == data.shape
306
+ assert np.allclose(datan.max(), 1.0)
307
+ assert np.allclose(datan.min(), -1.0)
308
+ dataun = normalizer.unnormalize(datan)
309
+ assert torch.allclose(data, dataun, atol=1e-7)
310
+
311
+ input_stats = normalizer.get_input_stats()
312
+ output_stats = normalizer.get_output_stats()
313
+
314
+ normalizer = SingleFieldLinearNormalizer()
315
+ normalizer.fit(data, mode="limits", last_n_dims=1, fit_offset=False)
316
+ datan = normalizer.normalize(data)
317
+ assert datan.shape == data.shape
318
+ assert np.allclose(datan.max(), 1.0, atol=1e-3)
319
+ assert np.allclose(datan.min(), 0.0, atol=1e-3)
320
+ dataun = normalizer.unnormalize(datan)
321
+ assert torch.allclose(data, dataun, atol=1e-7)
322
+
323
+ data = torch.zeros((100, 10, 9, 2)).uniform_()
324
+ normalizer = SingleFieldLinearNormalizer()
325
+ normalizer.fit(data, mode="gaussian", last_n_dims=0)
326
+ datan = normalizer.normalize(data)
327
+ assert datan.shape == data.shape
328
+ assert np.allclose(datan.mean(), 0.0, atol=1e-3)
329
+ assert np.allclose(datan.std(), 1.0, atol=1e-3)
330
+ dataun = normalizer.unnormalize(datan)
331
+ assert torch.allclose(data, dataun, atol=1e-7)
332
+
333
+ # dict
334
+ data = torch.zeros((100, 10, 9, 2)).uniform_()
335
+ data[..., 0, 0] = 0
336
+
337
+ normalizer = LinearNormalizer()
338
+ normalizer.fit(data, mode="limits", last_n_dims=2)
339
+ datan = normalizer.normalize(data)
340
+ assert datan.shape == data.shape
341
+ assert np.allclose(datan.max(), 1.0)
342
+ assert np.allclose(datan.min(), -1.0)
343
+ dataun = normalizer.unnormalize(datan)
344
+ assert torch.allclose(data, dataun, atol=1e-7)
345
+
346
+ input_stats = normalizer.get_input_stats()
347
+ output_stats = normalizer.get_output_stats()
348
+
349
+ data = {
350
+ "obs": torch.zeros((1000, 128, 9, 2)).uniform_() * 512,
351
+ "action": torch.zeros((1000, 128, 2)).uniform_() * 512,
352
+ }
353
+ normalizer = LinearNormalizer()
354
+ normalizer.fit(data)
355
+ datan = normalizer.normalize(data)
356
+ dataun = normalizer.unnormalize(datan)
357
+ for key in data:
358
+ assert torch.allclose(data[key], dataun[key], atol=1e-4)
359
+
360
+ input_stats = normalizer.get_input_stats()
361
+ output_stats = normalizer.get_output_stats()
362
+
363
+ state_dict = normalizer.state_dict()
364
+ n = LinearNormalizer()
365
+ n.load_state_dict(state_dict)
366
+ datan = n.normalize(data)
367
+ dataun = n.unnormalize(datan)
368
+ for key in data:
369
+ assert torch.allclose(data[key], dataun[key], atol=1e-4)
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/common/rotation_transformer.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+ import pytorch3d.transforms as pt
3
+ import torch
4
+ import numpy as np
5
+ import functools
6
+
7
+
8
+ class RotationTransformer:
9
+ valid_reps = ["axis_angle", "euler_angles", "quaternion", "rotation_6d", "matrix"]
10
+
11
+ def __init__(
12
+ self,
13
+ from_rep="axis_angle",
14
+ to_rep="rotation_6d",
15
+ from_convention=None,
16
+ to_convention=None,
17
+ ):
18
+ """
19
+ Valid representations
20
+
21
+ Always use matrix as intermediate representation.
22
+ """
23
+ assert from_rep != to_rep
24
+ assert from_rep in self.valid_reps
25
+ assert to_rep in self.valid_reps
26
+ if from_rep == "euler_angles":
27
+ assert from_convention is not None
28
+ if to_rep == "euler_angles":
29
+ assert to_convention is not None
30
+
31
+ forward_funcs = list()
32
+ inverse_funcs = list()
33
+
34
+ if from_rep != "matrix":
35
+ funcs = [
36
+ getattr(pt, f"{from_rep}_to_matrix"),
37
+ getattr(pt, f"matrix_to_{from_rep}"),
38
+ ]
39
+ if from_convention is not None:
40
+ funcs = [functools.partial(func, convention=from_convention) for func in funcs]
41
+ forward_funcs.append(funcs[0])
42
+ inverse_funcs.append(funcs[1])
43
+
44
+ if to_rep != "matrix":
45
+ funcs = [
46
+ getattr(pt, f"matrix_to_{to_rep}"),
47
+ getattr(pt, f"{to_rep}_to_matrix"),
48
+ ]
49
+ if to_convention is not None:
50
+ funcs = [functools.partial(func, convention=to_convention) for func in funcs]
51
+ forward_funcs.append(funcs[0])
52
+ inverse_funcs.append(funcs[1])
53
+
54
+ inverse_funcs = inverse_funcs[::-1]
55
+
56
+ self.forward_funcs = forward_funcs
57
+ self.inverse_funcs = inverse_funcs
58
+
59
+ @staticmethod
60
+ def _apply_funcs(x: Union[np.ndarray, torch.Tensor], funcs: list) -> Union[np.ndarray, torch.Tensor]:
61
+ x_ = x
62
+ if isinstance(x, np.ndarray):
63
+ x_ = torch.from_numpy(x)
64
+ x_: torch.Tensor
65
+ for func in funcs:
66
+ x_ = func(x_)
67
+ y = x_
68
+ if isinstance(x, np.ndarray):
69
+ y = x_.numpy()
70
+ return y
71
+
72
+ def forward(self, x: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
73
+ return self._apply_funcs(x, self.forward_funcs)
74
+
75
+ def inverse(self, x: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
76
+ return self._apply_funcs(x, self.inverse_funcs)
77
+
78
+
79
+ def test():
80
+ tf = RotationTransformer()
81
+
82
+ rotvec = np.random.uniform(-2 * np.pi, 2 * np.pi, size=(1000, 3))
83
+ rot6d = tf.forward(rotvec)
84
+ new_rotvec = tf.inverse(rot6d)
85
+
86
+ from scipy.spatial.transform import Rotation
87
+
88
+ diff = Rotation.from_rotvec(rotvec) * Rotation.from_rotvec(new_rotvec).inv()
89
+ dist = diff.magnitude()
90
+ assert dist.max() < 1e-7
91
+
92
+ tf = RotationTransformer("rotation_6d", "matrix")
93
+ rot6d_wrong = rot6d + np.random.normal(scale=0.1, size=rot6d.shape)
94
+ mat = tf.forward(rot6d_wrong)
95
+ mat_det = np.linalg.det(mat)
96
+ assert np.allclose(mat_det, 1)
97
+ # rotaiton_6d will be normalized to rotation matrix
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/common/shape_util.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Tuple, Callable
2
+ import torch
3
+ import torch.nn as nn
4
+
5
+
6
+ def get_module_device(m: nn.Module):
7
+ device = torch.device("cpu")
8
+ try:
9
+ param = next(iter(m.parameters()))
10
+ device = param.device
11
+ except StopIteration:
12
+ pass
13
+ return device
14
+
15
+
16
+ @torch.no_grad()
17
+ def get_output_shape(input_shape: Tuple[int], net: Callable[[torch.Tensor], torch.Tensor]):
18
+ device = get_module_device(net)
19
+ test_input = torch.zeros((1, ) + tuple(input_shape), device=device)
20
+ test_output = net(test_input)
21
+ output_shape = tuple(test_output.shape[1:])
22
+ return output_shape
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/common/tensor_util.py ADDED
@@ -0,0 +1,972 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A collection of utilities for working with nested tensor structures consisting
3
+ of numpy arrays and torch tensors.
4
+ """
5
+
6
+ import collections
7
+ import numpy as np
8
+ import torch
9
+
10
+
11
+ def recursive_dict_list_tuple_apply(x, type_func_dict):
12
+ """
13
+ Recursively apply functions to a nested dictionary or list or tuple, given a dictionary of
14
+ {data_type: function_to_apply}.
15
+
16
+ Args:
17
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
18
+ type_func_dict (dict): a mapping from data types to the functions to be
19
+ applied for each data type.
20
+
21
+ Returns:
22
+ y (dict or list or tuple): new nested dict-list-tuple
23
+ """
24
+ assert list not in type_func_dict
25
+ assert tuple not in type_func_dict
26
+ assert dict not in type_func_dict
27
+
28
+ if isinstance(x, (dict, collections.OrderedDict)):
29
+ new_x = (collections.OrderedDict() if isinstance(x, collections.OrderedDict) else dict())
30
+ for k, v in x.items():
31
+ new_x[k] = recursive_dict_list_tuple_apply(v, type_func_dict)
32
+ return new_x
33
+ elif isinstance(x, (list, tuple)):
34
+ ret = [recursive_dict_list_tuple_apply(v, type_func_dict) for v in x]
35
+ if isinstance(x, tuple):
36
+ ret = tuple(ret)
37
+ return ret
38
+ else:
39
+ for t, f in type_func_dict.items():
40
+ if isinstance(x, t):
41
+ return f(x)
42
+ else:
43
+ raise NotImplementedError("Cannot handle data type %s" % str(type(x)))
44
+
45
+
46
+ def map_tensor(x, func):
47
+ """
48
+ Apply function @func to torch.Tensor objects in a nested dictionary or
49
+ list or tuple.
50
+
51
+ Args:
52
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
53
+ func (function): function to apply to each tensor
54
+
55
+ Returns:
56
+ y (dict or list or tuple): new nested dict-list-tuple
57
+ """
58
+ return recursive_dict_list_tuple_apply(
59
+ x,
60
+ {
61
+ torch.Tensor: func,
62
+ type(None): lambda x: x,
63
+ },
64
+ )
65
+
66
+
67
+ def map_ndarray(x, func):
68
+ """
69
+ Apply function @func to np.ndarray objects in a nested dictionary or
70
+ list or tuple.
71
+
72
+ Args:
73
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
74
+ func (function): function to apply to each array
75
+
76
+ Returns:
77
+ y (dict or list or tuple): new nested dict-list-tuple
78
+ """
79
+ return recursive_dict_list_tuple_apply(
80
+ x,
81
+ {
82
+ np.ndarray: func,
83
+ type(None): lambda x: x,
84
+ },
85
+ )
86
+
87
+
88
+ def map_tensor_ndarray(x, tensor_func, ndarray_func):
89
+ """
90
+ Apply function @tensor_func to torch.Tensor objects and @ndarray_func to
91
+ np.ndarray objects in a nested dictionary or list or tuple.
92
+
93
+ Args:
94
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
95
+ tensor_func (function): function to apply to each tensor
96
+ ndarray_Func (function): function to apply to each array
97
+
98
+ Returns:
99
+ y (dict or list or tuple): new nested dict-list-tuple
100
+ """
101
+ return recursive_dict_list_tuple_apply(
102
+ x,
103
+ {
104
+ torch.Tensor: tensor_func,
105
+ np.ndarray: ndarray_func,
106
+ type(None): lambda x: x,
107
+ },
108
+ )
109
+
110
+
111
+ def clone(x):
112
+ """
113
+ Clones all torch tensors and numpy arrays in nested dictionary or list
114
+ or tuple and returns a new nested structure.
115
+
116
+ Args:
117
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
118
+
119
+ Returns:
120
+ y (dict or list or tuple): new nested dict-list-tuple
121
+ """
122
+ return recursive_dict_list_tuple_apply(
123
+ x,
124
+ {
125
+ torch.Tensor: lambda x: x.clone(),
126
+ np.ndarray: lambda x: x.copy(),
127
+ type(None): lambda x: x,
128
+ },
129
+ )
130
+
131
+
132
+ def detach(x):
133
+ """
134
+ Detaches all torch tensors in nested dictionary or list
135
+ or tuple and returns a new nested structure.
136
+
137
+ Args:
138
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
139
+
140
+ Returns:
141
+ y (dict or list or tuple): new nested dict-list-tuple
142
+ """
143
+ return recursive_dict_list_tuple_apply(
144
+ x,
145
+ {
146
+ torch.Tensor: lambda x: x.detach(),
147
+ },
148
+ )
149
+
150
+
151
+ def to_batch(x):
152
+ """
153
+ Introduces a leading batch dimension of 1 for all torch tensors and numpy
154
+ arrays in nested dictionary or list or tuple and returns a new nested structure.
155
+
156
+ Args:
157
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
158
+
159
+ Returns:
160
+ y (dict or list or tuple): new nested dict-list-tuple
161
+ """
162
+ return recursive_dict_list_tuple_apply(
163
+ x,
164
+ {
165
+ torch.Tensor: lambda x: x[None, ...],
166
+ np.ndarray: lambda x: x[None, ...],
167
+ type(None): lambda x: x,
168
+ },
169
+ )
170
+
171
+
172
+ def to_sequence(x):
173
+ """
174
+ Introduces a time dimension of 1 at dimension 1 for all torch tensors and numpy
175
+ arrays in nested dictionary or list or tuple and returns a new nested structure.
176
+
177
+ Args:
178
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
179
+
180
+ Returns:
181
+ y (dict or list or tuple): new nested dict-list-tuple
182
+ """
183
+ return recursive_dict_list_tuple_apply(
184
+ x,
185
+ {
186
+ torch.Tensor: lambda x: x[:, None, ...],
187
+ np.ndarray: lambda x: x[:, None, ...],
188
+ type(None): lambda x: x,
189
+ },
190
+ )
191
+
192
+
193
+ def index_at_time(x, ind):
194
+ """
195
+ Indexes all torch tensors and numpy arrays in dimension 1 with index @ind in
196
+ nested dictionary or list or tuple and returns a new nested structure.
197
+
198
+ Args:
199
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
200
+ ind (int): index
201
+
202
+ Returns:
203
+ y (dict or list or tuple): new nested dict-list-tuple
204
+ """
205
+ return recursive_dict_list_tuple_apply(
206
+ x,
207
+ {
208
+ torch.Tensor: lambda x: x[:, ind, ...],
209
+ np.ndarray: lambda x: x[:, ind, ...],
210
+ type(None): lambda x: x,
211
+ },
212
+ )
213
+
214
+
215
+ def unsqueeze(x, dim):
216
+ """
217
+ Adds dimension of size 1 at dimension @dim in all torch tensors and numpy arrays
218
+ in nested dictionary or list or tuple and returns a new nested structure.
219
+
220
+ Args:
221
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
222
+ dim (int): dimension
223
+
224
+ Returns:
225
+ y (dict or list or tuple): new nested dict-list-tuple
226
+ """
227
+ return recursive_dict_list_tuple_apply(
228
+ x,
229
+ {
230
+ torch.Tensor: lambda x: x.unsqueeze(dim=dim),
231
+ np.ndarray: lambda x: np.expand_dims(x, axis=dim),
232
+ type(None): lambda x: x,
233
+ },
234
+ )
235
+
236
+
237
+ def contiguous(x):
238
+ """
239
+ Makes all torch tensors and numpy arrays contiguous in nested dictionary or
240
+ list or tuple and returns a new nested structure.
241
+
242
+ Args:
243
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
244
+
245
+ Returns:
246
+ y (dict or list or tuple): new nested dict-list-tuple
247
+ """
248
+ return recursive_dict_list_tuple_apply(
249
+ x,
250
+ {
251
+ torch.Tensor: lambda x: x.contiguous(),
252
+ np.ndarray: lambda x: np.ascontiguousarray(x),
253
+ type(None): lambda x: x,
254
+ },
255
+ )
256
+
257
+
258
+ def to_device(x, device):
259
+ """
260
+ Sends all torch tensors in nested dictionary or list or tuple to device
261
+ @device, and returns a new nested structure.
262
+
263
+ Args:
264
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
265
+ device (torch.Device): device to send tensors to
266
+
267
+ Returns:
268
+ y (dict or list or tuple): new nested dict-list-tuple
269
+ """
270
+ return recursive_dict_list_tuple_apply(
271
+ x,
272
+ {
273
+ torch.Tensor: lambda x, d=device: x.to(d),
274
+ type(None): lambda x: x,
275
+ },
276
+ )
277
+
278
+
279
+ def to_tensor(x):
280
+ """
281
+ Converts all numpy arrays in nested dictionary or list or tuple to
282
+ torch tensors (and leaves existing torch Tensors as-is), and returns
283
+ a new nested structure.
284
+
285
+ Args:
286
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
287
+
288
+ Returns:
289
+ y (dict or list or tuple): new nested dict-list-tuple
290
+ """
291
+ return recursive_dict_list_tuple_apply(
292
+ x,
293
+ {
294
+ torch.Tensor: lambda x: x,
295
+ np.ndarray: lambda x: torch.from_numpy(x),
296
+ type(None): lambda x: x,
297
+ },
298
+ )
299
+
300
+
301
+ def to_numpy(x):
302
+ """
303
+ Converts all torch tensors in nested dictionary or list or tuple to
304
+ numpy (and leaves existing numpy arrays as-is), and returns
305
+ a new nested structure.
306
+
307
+ Args:
308
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
309
+
310
+ Returns:
311
+ y (dict or list or tuple): new nested dict-list-tuple
312
+ """
313
+
314
+ def f(tensor):
315
+ if tensor.is_cuda:
316
+ return tensor.detach().cpu().numpy()
317
+ else:
318
+ return tensor.detach().numpy()
319
+
320
+ return recursive_dict_list_tuple_apply(
321
+ x,
322
+ {
323
+ torch.Tensor: f,
324
+ np.ndarray: lambda x: x,
325
+ type(None): lambda x: x,
326
+ },
327
+ )
328
+
329
+
330
+ def to_list(x):
331
+ """
332
+ Converts all torch tensors and numpy arrays in nested dictionary or list
333
+ or tuple to a list, and returns a new nested structure. Useful for
334
+ json encoding.
335
+
336
+ Args:
337
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
338
+
339
+ Returns:
340
+ y (dict or list or tuple): new nested dict-list-tuple
341
+ """
342
+
343
+ def f(tensor):
344
+ if tensor.is_cuda:
345
+ return tensor.detach().cpu().numpy().tolist()
346
+ else:
347
+ return tensor.detach().numpy().tolist()
348
+
349
+ return recursive_dict_list_tuple_apply(
350
+ x,
351
+ {
352
+ torch.Tensor: f,
353
+ np.ndarray: lambda x: x.tolist(),
354
+ type(None): lambda x: x,
355
+ },
356
+ )
357
+
358
+
359
+ def to_float(x):
360
+ """
361
+ Converts all torch tensors and numpy arrays in nested dictionary or list
362
+ or tuple to float type entries, and returns a new nested structure.
363
+
364
+ Args:
365
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
366
+
367
+ Returns:
368
+ y (dict or list or tuple): new nested dict-list-tuple
369
+ """
370
+ return recursive_dict_list_tuple_apply(
371
+ x,
372
+ {
373
+ torch.Tensor: lambda x: x.float(),
374
+ np.ndarray: lambda x: x.astype(np.float32),
375
+ type(None): lambda x: x,
376
+ },
377
+ )
378
+
379
+
380
+ def to_uint8(x):
381
+ """
382
+ Converts all torch tensors and numpy arrays in nested dictionary or list
383
+ or tuple to uint8 type entries, and returns a new nested structure.
384
+
385
+ Args:
386
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
387
+
388
+ Returns:
389
+ y (dict or list or tuple): new nested dict-list-tuple
390
+ """
391
+ return recursive_dict_list_tuple_apply(
392
+ x,
393
+ {
394
+ torch.Tensor: lambda x: x.byte(),
395
+ np.ndarray: lambda x: x.astype(np.uint8),
396
+ type(None): lambda x: x,
397
+ },
398
+ )
399
+
400
+
401
+ def to_torch(x, device):
402
+ """
403
+ Converts all numpy arrays and torch tensors in nested dictionary or list or tuple to
404
+ torch tensors on device @device and returns a new nested structure.
405
+
406
+ Args:
407
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
408
+ device (torch.Device): device to send tensors to
409
+
410
+ Returns:
411
+ y (dict or list or tuple): new nested dict-list-tuple
412
+ """
413
+ return to_device(to_float(to_tensor(x)), device)
414
+
415
+
416
+ def to_one_hot_single(tensor, num_class):
417
+ """
418
+ Convert tensor to one-hot representation, assuming a certain number of total class labels.
419
+
420
+ Args:
421
+ tensor (torch.Tensor): tensor containing integer labels
422
+ num_class (int): number of classes
423
+
424
+ Returns:
425
+ x (torch.Tensor): tensor containing one-hot representation of labels
426
+ """
427
+ x = torch.zeros(tensor.size() + (num_class, )).to(tensor.device)
428
+ x.scatter_(-1, tensor.unsqueeze(-1), 1)
429
+ return x
430
+
431
+
432
+ def to_one_hot(tensor, num_class):
433
+ """
434
+ Convert all tensors in nested dictionary or list or tuple to one-hot representation,
435
+ assuming a certain number of total class labels.
436
+
437
+ Args:
438
+ tensor (dict or list or tuple): a possibly nested dictionary or list or tuple
439
+ num_class (int): number of classes
440
+
441
+ Returns:
442
+ y (dict or list or tuple): new nested dict-list-tuple
443
+ """
444
+ return map_tensor(tensor, func=lambda x, nc=num_class: to_one_hot_single(x, nc))
445
+
446
+
447
+ def flatten_single(x, begin_axis=1):
448
+ """
449
+ Flatten a tensor in all dimensions from @begin_axis onwards.
450
+
451
+ Args:
452
+ x (torch.Tensor): tensor to flatten
453
+ begin_axis (int): which axis to flatten from
454
+
455
+ Returns:
456
+ y (torch.Tensor): flattened tensor
457
+ """
458
+ fixed_size = x.size()[:begin_axis]
459
+ _s = list(fixed_size) + [-1]
460
+ return x.reshape(*_s)
461
+
462
+
463
+ def flatten(x, begin_axis=1):
464
+ """
465
+ Flatten all tensors in nested dictionary or list or tuple, from @begin_axis onwards.
466
+
467
+ Args:
468
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
469
+ begin_axis (int): which axis to flatten from
470
+
471
+ Returns:
472
+ y (dict or list or tuple): new nested dict-list-tuple
473
+ """
474
+ return recursive_dict_list_tuple_apply(
475
+ x,
476
+ {
477
+ torch.Tensor: lambda x, b=begin_axis: flatten_single(x, begin_axis=b),
478
+ },
479
+ )
480
+
481
+
482
+ def reshape_dimensions_single(x, begin_axis, end_axis, target_dims):
483
+ """
484
+ Reshape selected dimensions in a tensor to a target dimension.
485
+
486
+ Args:
487
+ x (torch.Tensor): tensor to reshape
488
+ begin_axis (int): begin dimension
489
+ end_axis (int): end dimension
490
+ target_dims (tuple or list): target shape for the range of dimensions
491
+ (@begin_axis, @end_axis)
492
+
493
+ Returns:
494
+ y (torch.Tensor): reshaped tensor
495
+ """
496
+ assert begin_axis <= end_axis
497
+ assert begin_axis >= 0
498
+ assert end_axis < len(x.shape)
499
+ assert isinstance(target_dims, (tuple, list))
500
+ s = x.shape
501
+ final_s = []
502
+ for i in range(len(s)):
503
+ if i == begin_axis:
504
+ final_s.extend(target_dims)
505
+ elif i < begin_axis or i > end_axis:
506
+ final_s.append(s[i])
507
+ return x.reshape(*final_s)
508
+
509
+
510
+ def reshape_dimensions(x, begin_axis, end_axis, target_dims):
511
+ """
512
+ Reshape selected dimensions for all tensors in nested dictionary or list or tuple
513
+ to a target dimension.
514
+
515
+ Args:
516
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
517
+ begin_axis (int): begin dimension
518
+ end_axis (int): end dimension
519
+ target_dims (tuple or list): target shape for the range of dimensions
520
+ (@begin_axis, @end_axis)
521
+
522
+ Returns:
523
+ y (dict or list or tuple): new nested dict-list-tuple
524
+ """
525
+ return recursive_dict_list_tuple_apply(
526
+ x,
527
+ {
528
+ torch.Tensor:
529
+ lambda x, b=begin_axis, e=end_axis, t=target_dims: reshape_dimensions_single(
530
+ x, begin_axis=b, end_axis=e, target_dims=t),
531
+ np.ndarray:
532
+ lambda x, b=begin_axis, e=end_axis, t=target_dims: reshape_dimensions_single(
533
+ x, begin_axis=b, end_axis=e, target_dims=t),
534
+ type(None):
535
+ lambda x: x,
536
+ },
537
+ )
538
+
539
+
540
+ def join_dimensions(x, begin_axis, end_axis):
541
+ """
542
+ Joins all dimensions between dimensions (@begin_axis, @end_axis) into a flat dimension, for
543
+ all tensors in nested dictionary or list or tuple.
544
+
545
+ Args:
546
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
547
+ begin_axis (int): begin dimension
548
+ end_axis (int): end dimension
549
+
550
+ Returns:
551
+ y (dict or list or tuple): new nested dict-list-tuple
552
+ """
553
+ return recursive_dict_list_tuple_apply(
554
+ x,
555
+ {
556
+ torch.Tensor:
557
+ lambda x, b=begin_axis, e=end_axis: reshape_dimensions_single(x, begin_axis=b, end_axis=e, target_dims=[-1]
558
+ ),
559
+ np.ndarray:
560
+ lambda x, b=begin_axis, e=end_axis: reshape_dimensions_single(x, begin_axis=b, end_axis=e, target_dims=[-1]
561
+ ),
562
+ type(None):
563
+ lambda x: x,
564
+ },
565
+ )
566
+
567
+
568
+ def expand_at_single(x, size, dim):
569
+ """
570
+ Expand a tensor at a single dimension @dim by @size
571
+
572
+ Args:
573
+ x (torch.Tensor): input tensor
574
+ size (int): size to expand
575
+ dim (int): dimension to expand
576
+
577
+ Returns:
578
+ y (torch.Tensor): expanded tensor
579
+ """
580
+ assert dim < x.ndimension()
581
+ assert x.shape[dim] == 1
582
+ expand_dims = [-1] * x.ndimension()
583
+ expand_dims[dim] = size
584
+ return x.expand(*expand_dims)
585
+
586
+
587
+ def expand_at(x, size, dim):
588
+ """
589
+ Expand all tensors in nested dictionary or list or tuple at a single
590
+ dimension @dim by @size.
591
+
592
+ Args:
593
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
594
+ size (int): size to expand
595
+ dim (int): dimension to expand
596
+
597
+ Returns:
598
+ y (dict or list or tuple): new nested dict-list-tuple
599
+ """
600
+ return map_tensor(x, lambda t, s=size, d=dim: expand_at_single(t, s, d))
601
+
602
+
603
+ def unsqueeze_expand_at(x, size, dim):
604
+ """
605
+ Unsqueeze and expand a tensor at a dimension @dim by @size.
606
+
607
+ Args:
608
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
609
+ size (int): size to expand
610
+ dim (int): dimension to unsqueeze and expand
611
+
612
+ Returns:
613
+ y (dict or list or tuple): new nested dict-list-tuple
614
+ """
615
+ x = unsqueeze(x, dim)
616
+ return expand_at(x, size, dim)
617
+
618
+
619
+ def repeat_by_expand_at(x, repeats, dim):
620
+ """
621
+ Repeat a dimension by combining expand and reshape operations.
622
+
623
+ Args:
624
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
625
+ repeats (int): number of times to repeat the target dimension
626
+ dim (int): dimension to repeat on
627
+
628
+ Returns:
629
+ y (dict or list or tuple): new nested dict-list-tuple
630
+ """
631
+ x = unsqueeze_expand_at(x, repeats, dim + 1)
632
+ return join_dimensions(x, dim, dim + 1)
633
+
634
+
635
+ def named_reduce_single(x, reduction, dim):
636
+ """
637
+ Reduce tensor at a dimension by named reduction functions.
638
+
639
+ Args:
640
+ x (torch.Tensor): tensor to be reduced
641
+ reduction (str): one of ["sum", "max", "mean", "flatten"]
642
+ dim (int): dimension to be reduced (or begin axis for flatten)
643
+
644
+ Returns:
645
+ y (torch.Tensor): reduced tensor
646
+ """
647
+ assert x.ndimension() > dim
648
+ assert reduction in ["sum", "max", "mean", "flatten"]
649
+ if reduction == "flatten":
650
+ x = flatten(x, begin_axis=dim)
651
+ elif reduction == "max":
652
+ x = torch.max(x, dim=dim)[0] # [B, D]
653
+ elif reduction == "sum":
654
+ x = torch.sum(x, dim=dim)
655
+ else:
656
+ x = torch.mean(x, dim=dim)
657
+ return x
658
+
659
+
660
+ def named_reduce(x, reduction, dim):
661
+ """
662
+ Reduces all tensors in nested dictionary or list or tuple at a dimension
663
+ using a named reduction function.
664
+
665
+ Args:
666
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
667
+ reduction (str): one of ["sum", "max", "mean", "flatten"]
668
+ dim (int): dimension to be reduced (or begin axis for flatten)
669
+
670
+ Returns:
671
+ y (dict or list or tuple): new nested dict-list-tuple
672
+ """
673
+ return map_tensor(x, func=lambda t, r=reduction, d=dim: named_reduce_single(t, r, d))
674
+
675
+
676
+ def gather_along_dim_with_dim_single(x, target_dim, source_dim, indices):
677
+ """
678
+ This function indexes out a target dimension of a tensor in a structured way,
679
+ by allowing a different value to be selected for each member of a flat index
680
+ tensor (@indices) corresponding to a source dimension. This can be interpreted
681
+ as moving along the source dimension, using the corresponding index value
682
+ in @indices to select values for all other dimensions outside of the
683
+ source and target dimensions. A common use case is to gather values
684
+ in target dimension 1 for each batch member (target dimension 0).
685
+
686
+ Args:
687
+ x (torch.Tensor): tensor to gather values for
688
+ target_dim (int): dimension to gather values along
689
+ source_dim (int): dimension to hold constant and use for gathering values
690
+ from the other dimensions
691
+ indices (torch.Tensor): flat index tensor with same shape as tensor @x along
692
+ @source_dim
693
+
694
+ Returns:
695
+ y (torch.Tensor): gathered tensor, with dimension @target_dim indexed out
696
+ """
697
+ assert len(indices.shape) == 1
698
+ assert x.shape[source_dim] == indices.shape[0]
699
+
700
+ # unsqueeze in all dimensions except the source dimension
701
+ new_shape = [1] * x.ndimension()
702
+ new_shape[source_dim] = -1
703
+ indices = indices.reshape(*new_shape)
704
+
705
+ # repeat in all dimensions - but preserve shape of source dimension,
706
+ # and make sure target_dimension has singleton dimension
707
+ expand_shape = list(x.shape)
708
+ expand_shape[source_dim] = -1
709
+ expand_shape[target_dim] = 1
710
+ indices = indices.expand(*expand_shape)
711
+
712
+ out = x.gather(dim=target_dim, index=indices)
713
+ return out.squeeze(target_dim)
714
+
715
+
716
+ def gather_along_dim_with_dim(x, target_dim, source_dim, indices):
717
+ """
718
+ Apply @gather_along_dim_with_dim_single to all tensors in a nested
719
+ dictionary or list or tuple.
720
+
721
+ Args:
722
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
723
+ target_dim (int): dimension to gather values along
724
+ source_dim (int): dimension to hold constant and use for gathering values
725
+ from the other dimensions
726
+ indices (torch.Tensor): flat index tensor with same shape as tensor @x along
727
+ @source_dim
728
+
729
+ Returns:
730
+ y (dict or list or tuple): new nested dict-list-tuple
731
+ """
732
+ return map_tensor(
733
+ x,
734
+ lambda y, t=target_dim, s=source_dim, i=indices: gather_along_dim_with_dim_single(y, t, s, i),
735
+ )
736
+
737
+
738
+ def gather_sequence_single(seq, indices):
739
+ """
740
+ Given a tensor with leading dimensions [B, T, ...], gather an element from each sequence in
741
+ the batch given an index for each sequence.
742
+
743
+ Args:
744
+ seq (torch.Tensor): tensor with leading dimensions [B, T, ...]
745
+ indices (torch.Tensor): tensor indices of shape [B]
746
+
747
+ Return:
748
+ y (torch.Tensor): indexed tensor of shape [B, ....]
749
+ """
750
+ return gather_along_dim_with_dim_single(seq, target_dim=1, source_dim=0, indices=indices)
751
+
752
+
753
+ def gather_sequence(seq, indices):
754
+ """
755
+ Given a nested dictionary or list or tuple, gathers an element from each sequence of the batch
756
+ for tensors with leading dimensions [B, T, ...].
757
+
758
+ Args:
759
+ seq (dict or list or tuple): a possibly nested dictionary or list or tuple with tensors
760
+ of leading dimensions [B, T, ...]
761
+ indices (torch.Tensor): tensor indices of shape [B]
762
+
763
+ Returns:
764
+ y (dict or list or tuple): new nested dict-list-tuple with tensors of shape [B, ...]
765
+ """
766
+ return gather_along_dim_with_dim(seq, target_dim=1, source_dim=0, indices=indices)
767
+
768
+
769
+ def pad_sequence_single(seq, padding, batched=False, pad_same=True, pad_values=None):
770
+ """
771
+ Pad input tensor or array @seq in the time dimension (dimension 1).
772
+
773
+ Args:
774
+ seq (np.ndarray or torch.Tensor): sequence to be padded
775
+ padding (tuple): begin and end padding, e.g. [1, 1] pads both begin and end of the sequence by 1
776
+ batched (bool): if sequence has the batch dimension
777
+ pad_same (bool): if pad by duplicating
778
+ pad_values (scalar or (ndarray, Tensor)): values to be padded if not pad_same
779
+
780
+ Returns:
781
+ padded sequence (np.ndarray or torch.Tensor)
782
+ """
783
+ assert isinstance(seq, (np.ndarray, torch.Tensor))
784
+ assert pad_same or pad_values is not None
785
+ if pad_values is not None:
786
+ assert isinstance(pad_values, float)
787
+ repeat_func = np.repeat if isinstance(seq, np.ndarray) else torch.repeat_interleave
788
+ concat_func = np.concatenate if isinstance(seq, np.ndarray) else torch.cat
789
+ ones_like_func = np.ones_like if isinstance(seq, np.ndarray) else torch.ones_like
790
+ seq_dim = 1 if batched else 0
791
+
792
+ begin_pad = []
793
+ end_pad = []
794
+
795
+ if padding[0] > 0:
796
+ pad = seq[[0]] if pad_same else ones_like_func(seq[[0]]) * pad_values
797
+ begin_pad.append(repeat_func(pad, padding[0], seq_dim))
798
+ if padding[1] > 0:
799
+ pad = seq[[-1]] if pad_same else ones_like_func(seq[[-1]]) * pad_values
800
+ end_pad.append(repeat_func(pad, padding[1], seq_dim))
801
+
802
+ return concat_func(begin_pad + [seq] + end_pad, seq_dim)
803
+
804
+
805
+ def pad_sequence(seq, padding, batched=False, pad_same=True, pad_values=None):
806
+ """
807
+ Pad a nested dictionary or list or tuple of sequence tensors in the time dimension (dimension 1).
808
+
809
+ Args:
810
+ seq (dict or list or tuple): a possibly nested dictionary or list or tuple with tensors
811
+ of leading dimensions [B, T, ...]
812
+ padding (tuple): begin and end padding, e.g. [1, 1] pads both begin and end of the sequence by 1
813
+ batched (bool): if sequence has the batch dimension
814
+ pad_same (bool): if pad by duplicating
815
+ pad_values (scalar or (ndarray, Tensor)): values to be padded if not pad_same
816
+
817
+ Returns:
818
+ padded sequence (dict or list or tuple)
819
+ """
820
+ return recursive_dict_list_tuple_apply(
821
+ seq,
822
+ {
823
+ torch.Tensor:
824
+ lambda x, p=padding, b=batched, ps=pad_same, pv=pad_values: pad_sequence_single(x, p, b, ps, pv),
825
+ np.ndarray:
826
+ lambda x, p=padding, b=batched, ps=pad_same, pv=pad_values: pad_sequence_single(x, p, b, ps, pv),
827
+ type(None): lambda x: x,
828
+ },
829
+ )
830
+
831
+
832
+ def assert_size_at_dim_single(x, size, dim, msg):
833
+ """
834
+ Ensure that array or tensor @x has size @size in dim @dim.
835
+
836
+ Args:
837
+ x (np.ndarray or torch.Tensor): input array or tensor
838
+ size (int): size that tensors should have at @dim
839
+ dim (int): dimension to check
840
+ msg (str): text to display if assertion fails
841
+ """
842
+ assert x.shape[dim] == size, msg
843
+
844
+
845
+ def assert_size_at_dim(x, size, dim, msg):
846
+ """
847
+ Ensure that arrays and tensors in nested dictionary or list or tuple have
848
+ size @size in dim @dim.
849
+
850
+ Args:
851
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
852
+ size (int): size that tensors should have at @dim
853
+ dim (int): dimension to check
854
+ """
855
+ map_tensor(x, lambda t, s=size, d=dim, m=msg: assert_size_at_dim_single(t, s, d, m))
856
+
857
+
858
+ def get_shape(x):
859
+ """
860
+ Get all shapes of arrays and tensors in nested dictionary or list or tuple.
861
+
862
+ Args:
863
+ x (dict or list or tuple): a possibly nested dictionary or list or tuple
864
+
865
+ Returns:
866
+ y (dict or list or tuple): new nested dict-list-tuple that contains each array or
867
+ tensor's shape
868
+ """
869
+ return recursive_dict_list_tuple_apply(
870
+ x,
871
+ {
872
+ torch.Tensor: lambda x: x.shape,
873
+ np.ndarray: lambda x: x.shape,
874
+ type(None): lambda x: x,
875
+ },
876
+ )
877
+
878
+
879
+ def list_of_flat_dict_to_dict_of_list(list_of_dict):
880
+ """
881
+ Helper function to go from a list of flat dictionaries to a dictionary of lists.
882
+ By "flat" we mean that none of the values are dictionaries, but are numpy arrays,
883
+ floats, etc.
884
+
885
+ Args:
886
+ list_of_dict (list): list of flat dictionaries
887
+
888
+ Returns:
889
+ dict_of_list (dict): dictionary of lists
890
+ """
891
+ assert isinstance(list_of_dict, list)
892
+ dic = collections.OrderedDict()
893
+ for i in range(len(list_of_dict)):
894
+ for k in list_of_dict[i]:
895
+ if k not in dic:
896
+ dic[k] = []
897
+ dic[k].append(list_of_dict[i][k])
898
+ return dic
899
+
900
+
901
+ def flatten_nested_dict_list(d, parent_key="", sep="_", item_key=""):
902
+ """
903
+ Flatten a nested dict or list to a list.
904
+
905
+ For example, given a dict
906
+ {
907
+ a: 1
908
+ b: {
909
+ c: 2
910
+ }
911
+ c: 3
912
+ }
913
+
914
+ the function would return [(a, 1), (b_c, 2), (c, 3)]
915
+
916
+ Args:
917
+ d (dict, list): a nested dict or list to be flattened
918
+ parent_key (str): recursion helper
919
+ sep (str): separator for nesting keys
920
+ item_key (str): recursion helper
921
+ Returns:
922
+ list: a list of (key, value) tuples
923
+ """
924
+ items = []
925
+ if isinstance(d, (tuple, list)):
926
+ new_key = parent_key + sep + item_key if len(parent_key) > 0 else item_key
927
+ for i, v in enumerate(d):
928
+ items.extend(flatten_nested_dict_list(v, new_key, sep=sep, item_key=str(i)))
929
+ return items
930
+ elif isinstance(d, dict):
931
+ new_key = parent_key + sep + item_key if len(parent_key) > 0 else item_key
932
+ for k, v in d.items():
933
+ assert isinstance(k, str)
934
+ items.extend(flatten_nested_dict_list(v, new_key, sep=sep, item_key=k))
935
+ return items
936
+ else:
937
+ new_key = parent_key + sep + item_key if len(parent_key) > 0 else item_key
938
+ return [(new_key, d)]
939
+
940
+
941
+ def time_distributed(inputs, op, activation=None, inputs_as_kwargs=False, inputs_as_args=False, **kwargs):
942
+ """
943
+ Apply function @op to all tensors in nested dictionary or list or tuple @inputs in both the
944
+ batch (B) and time (T) dimension, where the tensors are expected to have shape [B, T, ...].
945
+ Will do this by reshaping tensors to [B * T, ...], passing through the op, and then reshaping
946
+ outputs to [B, T, ...].
947
+
948
+ Args:
949
+ inputs (list or tuple or dict): a possibly nested dictionary or list or tuple with tensors
950
+ of leading dimensions [B, T, ...]
951
+ op: a layer op that accepts inputs
952
+ activation: activation to apply at the output
953
+ inputs_as_kwargs (bool): whether to feed input as a kwargs dict to the op
954
+ inputs_as_args (bool) whether to feed input as a args list to the op
955
+ kwargs (dict): other kwargs to supply to the op
956
+
957
+ Returns:
958
+ outputs (dict or list or tuple): new nested dict-list-tuple with tensors of leading dimension [B, T].
959
+ """
960
+ batch_size, seq_len = flatten_nested_dict_list(inputs)[0][1].shape[:2]
961
+ inputs = join_dimensions(inputs, 0, 1)
962
+ if inputs_as_kwargs:
963
+ outputs = op(**inputs, **kwargs)
964
+ elif inputs_as_args:
965
+ outputs = op(*inputs, **kwargs)
966
+ else:
967
+ outputs = op(inputs, **kwargs)
968
+
969
+ if activation is not None:
970
+ outputs = map_tensor(outputs, activation)
971
+ outputs = reshape_dimensions(outputs, begin_axis=0, end_axis=0, target_dims=(batch_size, seq_len))
972
+ return outputs
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/conditional_unet1d.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+ import logging
3
+ import torch
4
+ import torch.nn as nn
5
+ import einops
6
+ from einops.layers.torch import Rearrange
7
+
8
+ from diffusion_policy.model.diffusion.conv1d_components import (
9
+ Downsample1d,
10
+ Upsample1d,
11
+ Conv1dBlock,
12
+ )
13
+ from diffusion_policy.model.diffusion.positional_embedding import SinusoidalPosEmb
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class ConditionalResidualBlock1D(nn.Module):
19
+
20
+ def __init__(
21
+ self,
22
+ in_channels,
23
+ out_channels,
24
+ cond_dim,
25
+ kernel_size=3,
26
+ n_groups=8,
27
+ cond_predict_scale=False,
28
+ ):
29
+ super().__init__()
30
+
31
+ self.blocks = nn.ModuleList([
32
+ Conv1dBlock(in_channels, out_channels, kernel_size, n_groups=n_groups),
33
+ Conv1dBlock(out_channels, out_channels, kernel_size, n_groups=n_groups),
34
+ ])
35
+
36
+ # FiLM modulation https://arxiv.org/abs/1709.07871
37
+ # predicts per-channel scale and bias
38
+ cond_channels = out_channels
39
+ if cond_predict_scale:
40
+ cond_channels = out_channels * 2
41
+ self.cond_predict_scale = cond_predict_scale
42
+ self.out_channels = out_channels
43
+ self.cond_encoder = nn.Sequential(
44
+ nn.Mish(),
45
+ nn.Linear(cond_dim, cond_channels),
46
+ Rearrange("batch t -> batch t 1"),
47
+ )
48
+
49
+ # make sure dimensions compatible
50
+ self.residual_conv = (nn.Conv1d(in_channels, out_channels, 1) if in_channels != out_channels else nn.Identity())
51
+
52
+ def forward(self, x, cond):
53
+ """
54
+ x : [ batch_size x in_channels x horizon ]
55
+ cond : [ batch_size x cond_dim]
56
+
57
+ returns:
58
+ out : [ batch_size x out_channels x horizon ]
59
+ """
60
+ out = self.blocks[0](x)
61
+ embed = self.cond_encoder(cond)
62
+ if self.cond_predict_scale:
63
+ embed = embed.reshape(embed.shape[0], 2, self.out_channels, 1)
64
+ scale = embed[:, 0, ...]
65
+ bias = embed[:, 1, ...]
66
+ out = scale * out + bias
67
+ else:
68
+ out = out + embed
69
+ out = self.blocks[1](out)
70
+ out = out + self.residual_conv(x)
71
+ return out
72
+
73
+
74
+ class ConditionalUnet1D(nn.Module):
75
+
76
+ def __init__(
77
+ self,
78
+ input_dim,
79
+ local_cond_dim=None,
80
+ global_cond_dim=None,
81
+ diffusion_step_embed_dim=256,
82
+ down_dims=[256, 512, 1024],
83
+ kernel_size=3,
84
+ n_groups=8,
85
+ cond_predict_scale=False,
86
+ ):
87
+ super().__init__()
88
+ all_dims = [input_dim] + list(down_dims)
89
+ start_dim = down_dims[0]
90
+
91
+ dsed = diffusion_step_embed_dim
92
+ diffusion_step_encoder = nn.Sequential(
93
+ SinusoidalPosEmb(dsed),
94
+ nn.Linear(dsed, dsed * 4),
95
+ nn.Mish(),
96
+ nn.Linear(dsed * 4, dsed),
97
+ )
98
+ cond_dim = dsed
99
+ if global_cond_dim is not None:
100
+ cond_dim += global_cond_dim
101
+
102
+ in_out = list(zip(all_dims[:-1], all_dims[1:]))
103
+
104
+ local_cond_encoder = None
105
+ if local_cond_dim is not None:
106
+ _, dim_out = in_out[0]
107
+ dim_in = local_cond_dim
108
+ local_cond_encoder = nn.ModuleList([
109
+ # down encoder
110
+ ConditionalResidualBlock1D(
111
+ dim_in,
112
+ dim_out,
113
+ cond_dim=cond_dim,
114
+ kernel_size=kernel_size,
115
+ n_groups=n_groups,
116
+ cond_predict_scale=cond_predict_scale,
117
+ ),
118
+ # up encoder
119
+ ConditionalResidualBlock1D(
120
+ dim_in,
121
+ dim_out,
122
+ cond_dim=cond_dim,
123
+ kernel_size=kernel_size,
124
+ n_groups=n_groups,
125
+ cond_predict_scale=cond_predict_scale,
126
+ ),
127
+ ])
128
+
129
+ mid_dim = all_dims[-1]
130
+ self.mid_modules = nn.ModuleList([
131
+ ConditionalResidualBlock1D(
132
+ mid_dim,
133
+ mid_dim,
134
+ cond_dim=cond_dim,
135
+ kernel_size=kernel_size,
136
+ n_groups=n_groups,
137
+ cond_predict_scale=cond_predict_scale,
138
+ ),
139
+ ConditionalResidualBlock1D(
140
+ mid_dim,
141
+ mid_dim,
142
+ cond_dim=cond_dim,
143
+ kernel_size=kernel_size,
144
+ n_groups=n_groups,
145
+ cond_predict_scale=cond_predict_scale,
146
+ ),
147
+ ])
148
+
149
+ down_modules = nn.ModuleList([])
150
+ for ind, (dim_in, dim_out) in enumerate(in_out):
151
+ is_last = ind >= (len(in_out) - 1)
152
+ down_modules.append(
153
+ nn.ModuleList([
154
+ ConditionalResidualBlock1D(
155
+ dim_in,
156
+ dim_out,
157
+ cond_dim=cond_dim,
158
+ kernel_size=kernel_size,
159
+ n_groups=n_groups,
160
+ cond_predict_scale=cond_predict_scale,
161
+ ),
162
+ ConditionalResidualBlock1D(
163
+ dim_out,
164
+ dim_out,
165
+ cond_dim=cond_dim,
166
+ kernel_size=kernel_size,
167
+ n_groups=n_groups,
168
+ cond_predict_scale=cond_predict_scale,
169
+ ),
170
+ Downsample1d(dim_out) if not is_last else nn.Identity(),
171
+ ]))
172
+
173
+ up_modules = nn.ModuleList([])
174
+ for ind, (dim_in, dim_out) in enumerate(reversed(in_out[1:])):
175
+ is_last = ind >= (len(in_out) - 1)
176
+ up_modules.append(
177
+ nn.ModuleList([
178
+ ConditionalResidualBlock1D(
179
+ dim_out * 2,
180
+ dim_in,
181
+ cond_dim=cond_dim,
182
+ kernel_size=kernel_size,
183
+ n_groups=n_groups,
184
+ cond_predict_scale=cond_predict_scale,
185
+ ),
186
+ ConditionalResidualBlock1D(
187
+ dim_in,
188
+ dim_in,
189
+ cond_dim=cond_dim,
190
+ kernel_size=kernel_size,
191
+ n_groups=n_groups,
192
+ cond_predict_scale=cond_predict_scale,
193
+ ),
194
+ Upsample1d(dim_in) if not is_last else nn.Identity(),
195
+ ]))
196
+
197
+ final_conv = nn.Sequential(
198
+ Conv1dBlock(start_dim, start_dim, kernel_size=kernel_size),
199
+ nn.Conv1d(start_dim, input_dim, 1),
200
+ )
201
+
202
+ self.diffusion_step_encoder = diffusion_step_encoder
203
+ self.local_cond_encoder = local_cond_encoder
204
+ self.up_modules = up_modules
205
+ self.down_modules = down_modules
206
+ self.final_conv = final_conv
207
+
208
+ logger.info("number of parameters: %e", sum(p.numel() for p in self.parameters()))
209
+
210
+ def forward(self,
211
+ sample: torch.Tensor,
212
+ timestep: Union[torch.Tensor, float, int],
213
+ local_cond=None,
214
+ global_cond=None,
215
+ **kwargs):
216
+ """
217
+ x: (B,T,input_dim)
218
+ timestep: (B,) or int, diffusion step
219
+ local_cond: (B,T,local_cond_dim)
220
+ global_cond: (B,global_cond_dim)
221
+ output: (B,T,input_dim)
222
+ """
223
+ sample = einops.rearrange(sample, "b h t -> b t h")
224
+
225
+ # 1. time
226
+ timesteps = timestep
227
+ if not torch.is_tensor(timesteps):
228
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
229
+ timesteps = torch.tensor([timesteps], dtype=torch.long, device=sample.device)
230
+ elif torch.is_tensor(timesteps) and len(timesteps.shape) == 0:
231
+ timesteps = timesteps[None].to(sample.device)
232
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
233
+ timesteps = timesteps.expand(sample.shape[0])
234
+
235
+ global_feature = self.diffusion_step_encoder(timesteps)
236
+
237
+ if global_cond is not None:
238
+ global_feature = torch.cat([global_feature, global_cond], axis=-1)
239
+
240
+ # encode local features
241
+ h_local = list()
242
+ if local_cond is not None:
243
+ local_cond = einops.rearrange(local_cond, "b h t -> b t h")
244
+ resnet, resnet2 = self.local_cond_encoder
245
+ x = resnet(local_cond, global_feature)
246
+ h_local.append(x)
247
+ x = resnet2(local_cond, global_feature)
248
+ h_local.append(x)
249
+
250
+ x = sample
251
+ h = []
252
+ for idx, (resnet, resnet2, downsample) in enumerate(self.down_modules):
253
+ x = resnet(x, global_feature)
254
+ if idx == 0 and len(h_local) > 0:
255
+ x = x + h_local[0]
256
+ x = resnet2(x, global_feature)
257
+ h.append(x)
258
+ x = downsample(x)
259
+
260
+ for mid_module in self.mid_modules:
261
+ x = mid_module(x, global_feature)
262
+
263
+ for idx, (resnet, resnet2, upsample) in enumerate(self.up_modules):
264
+ x = torch.cat((x, h.pop()), dim=1)
265
+ x = resnet(x, global_feature)
266
+ # The correct condition should be:
267
+ # if idx == (len(self.up_modules)-1) and len(h_local) > 0:
268
+ # However this change will break compatibility with published checkpoints.
269
+ # Therefore it is left as a comment.
270
+ if idx == len(self.up_modules) and len(h_local) > 0:
271
+ x = x + h_local[1]
272
+ x = resnet2(x, global_feature)
273
+ x = upsample(x)
274
+
275
+ x = self.final_conv(x)
276
+
277
+ x = einops.rearrange(x, "b t h -> b h t")
278
+ return x
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/conv1d_components.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ # from einops.layers.torch import Rearrange
6
+
7
+
8
+ class Downsample1d(nn.Module):
9
+
10
+ def __init__(self, dim):
11
+ super().__init__()
12
+ self.conv = nn.Conv1d(dim, dim, 3, 2, 1)
13
+
14
+ def forward(self, x):
15
+ return self.conv(x)
16
+
17
+
18
+ class Upsample1d(nn.Module):
19
+
20
+ def __init__(self, dim):
21
+ super().__init__()
22
+ self.conv = nn.ConvTranspose1d(dim, dim, 4, 2, 1)
23
+
24
+ def forward(self, x):
25
+ return self.conv(x)
26
+
27
+
28
+ class Conv1dBlock(nn.Module):
29
+ """
30
+ Conv1d --> GroupNorm --> Mish
31
+ """
32
+
33
+ def __init__(self, inp_channels, out_channels, kernel_size, n_groups=8):
34
+ super().__init__()
35
+
36
+ self.block = nn.Sequential(
37
+ nn.Conv1d(inp_channels, out_channels, kernel_size, padding=kernel_size // 2),
38
+ # Rearrange('batch channels horizon -> batch channels 1 horizon'),
39
+ nn.GroupNorm(n_groups, out_channels),
40
+ # Rearrange('batch channels 1 horizon -> batch channels horizon'),
41
+ nn.Mish(),
42
+ )
43
+
44
+ def forward(self, x):
45
+ return self.block(x)
46
+
47
+
48
+ def test():
49
+ cb = Conv1dBlock(256, 128, kernel_size=3)
50
+ x = torch.zeros((1, 256, 16))
51
+ o = cb(x)
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/ema_model.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import torch
3
+ from torch.nn.modules.batchnorm import _BatchNorm
4
+
5
+
6
+ class EMAModel:
7
+ """
8
+ Exponential Moving Average of models weights
9
+ """
10
+
11
+ def __init__(
12
+ self,
13
+ model,
14
+ update_after_step=0,
15
+ inv_gamma=1.0,
16
+ power=2 / 3,
17
+ min_value=0.0,
18
+ max_value=0.9999,
19
+ ):
20
+ """
21
+ @crowsonkb's notes on EMA Warmup:
22
+ If gamma=1 and power=1, implements a simple average. gamma=1, power=2/3 are good values for models you plan
23
+ to train for a million or more steps (reaches decay factor 0.999 at 31.6K steps, 0.9999 at 1M steps),
24
+ gamma=1, power=3/4 for models you plan to train for less (reaches decay factor 0.999 at 10K steps, 0.9999
25
+ at 215.4k steps).
26
+ Args:
27
+ inv_gamma (float): Inverse multiplicative factor of EMA warmup. Default: 1.
28
+ power (float): Exponential factor of EMA warmup. Default: 2/3.
29
+ min_value (float): The minimum EMA decay rate. Default: 0.
30
+ """
31
+
32
+ self.averaged_model = model
33
+ self.averaged_model.eval()
34
+ self.averaged_model.requires_grad_(False)
35
+
36
+ self.update_after_step = update_after_step
37
+ self.inv_gamma = inv_gamma
38
+ self.power = power
39
+ self.min_value = min_value
40
+ self.max_value = max_value
41
+
42
+ self.decay = 0.0
43
+ self.optimization_step = 0
44
+
45
+ def get_decay(self, optimization_step):
46
+ """
47
+ Compute the decay factor for the exponential moving average.
48
+ """
49
+ step = max(0, optimization_step - self.update_after_step - 1)
50
+ value = 1 - (1 + step / self.inv_gamma)**-self.power
51
+
52
+ if step <= 0:
53
+ return 0.0
54
+
55
+ return max(self.min_value, min(value, self.max_value))
56
+
57
+ @torch.no_grad()
58
+ def step(self, new_model):
59
+ self.decay = self.get_decay(self.optimization_step)
60
+
61
+ # old_all_dataptrs = set()
62
+ # for param in new_model.parameters():
63
+ # data_ptr = param.data_ptr()
64
+ # if data_ptr != 0:
65
+ # old_all_dataptrs.add(data_ptr)
66
+
67
+ all_dataptrs = set()
68
+ for module, ema_module in zip(new_model.modules(), self.averaged_model.modules()):
69
+ for param, ema_param in zip(module.parameters(recurse=False), ema_module.parameters(recurse=False)):
70
+ # iterative over immediate parameters only.
71
+ if isinstance(param, dict):
72
+ raise RuntimeError("Dict parameter not supported")
73
+
74
+ # data_ptr = param.data_ptr()
75
+ # if data_ptr != 0:
76
+ # all_dataptrs.add(data_ptr)
77
+
78
+ if isinstance(module, _BatchNorm):
79
+ # skip batchnorms
80
+ ema_param.copy_(param.to(dtype=ema_param.dtype).data)
81
+ elif not param.requires_grad:
82
+ ema_param.copy_(param.to(dtype=ema_param.dtype).data)
83
+ else:
84
+ ema_param.mul_(self.decay)
85
+ ema_param.add_(param.data.to(dtype=ema_param.dtype), alpha=1 - self.decay)
86
+
87
+ # verify that iterating over module and then parameters is identical to parameters recursively.
88
+ # assert old_all_dataptrs == all_dataptrs
89
+ self.optimization_step += 1
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/mask_generator.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Sequence, Optional
2
+ import torch
3
+ from torch import nn
4
+ from diffusion_policy.model.common.module_attr_mixin import ModuleAttrMixin
5
+
6
+
7
+ def get_intersection_slice_mask(shape: tuple, dim_slices: Sequence[slice], device: Optional[torch.device] = None):
8
+ assert len(shape) == len(dim_slices)
9
+ mask = torch.zeros(size=shape, dtype=torch.bool, device=device)
10
+ mask[dim_slices] = True
11
+ return mask
12
+
13
+
14
+ def get_union_slice_mask(shape: tuple, dim_slices: Sequence[slice], device: Optional[torch.device] = None):
15
+ assert len(shape) == len(dim_slices)
16
+ mask = torch.zeros(size=shape, dtype=torch.bool, device=device)
17
+ for i in range(len(dim_slices)):
18
+ this_slices = [slice(None)] * len(shape)
19
+ this_slices[i] = dim_slices[i]
20
+ mask[this_slices] = True
21
+ return mask
22
+
23
+
24
+ class DummyMaskGenerator(ModuleAttrMixin):
25
+
26
+ def __init__(self):
27
+ super().__init__()
28
+
29
+ @torch.no_grad()
30
+ def forward(self, shape):
31
+ device = self.device
32
+ mask = torch.ones(size=shape, dtype=torch.bool, device=device)
33
+ return mask
34
+
35
+
36
+ class LowdimMaskGenerator(ModuleAttrMixin):
37
+
38
+ def __init__(
39
+ self,
40
+ action_dim,
41
+ obs_dim,
42
+ # obs mask setup
43
+ max_n_obs_steps=2,
44
+ fix_obs_steps=True,
45
+ # action mask
46
+ action_visible=False,
47
+ ):
48
+ super().__init__()
49
+ self.action_dim = action_dim
50
+ self.obs_dim = obs_dim
51
+ self.max_n_obs_steps = max_n_obs_steps
52
+ self.fix_obs_steps = fix_obs_steps
53
+ self.action_visible = action_visible
54
+
55
+ @torch.no_grad()
56
+ def forward(self, shape, seed=None):
57
+ device = self.device
58
+ B, T, D = shape
59
+ assert D == (self.action_dim + self.obs_dim)
60
+
61
+ # create all tensors on this device
62
+ rng = torch.Generator(device=device)
63
+ if seed is not None:
64
+ rng = rng.manual_seed(seed)
65
+
66
+ # generate dim mask
67
+ dim_mask = torch.zeros(size=shape, dtype=torch.bool, device=device)
68
+ is_action_dim = dim_mask.clone()
69
+ is_action_dim[..., :self.action_dim] = True
70
+ is_obs_dim = ~is_action_dim
71
+
72
+ # generate obs mask
73
+ if self.fix_obs_steps:
74
+ obs_steps = torch.full((B, ), fill_value=self.max_n_obs_steps, device=device)
75
+ else:
76
+ obs_steps = torch.randint(
77
+ low=1,
78
+ high=self.max_n_obs_steps + 1,
79
+ size=(B, ),
80
+ generator=rng,
81
+ device=device,
82
+ )
83
+
84
+ steps = torch.arange(0, T, device=device).reshape(1, T).expand(B, T)
85
+ obs_mask = (steps.T < obs_steps).T.reshape(B, T, 1).expand(B, T, D)
86
+ obs_mask = obs_mask & is_obs_dim
87
+
88
+ # generate action mask
89
+ if self.action_visible:
90
+ action_steps = torch.maximum(
91
+ obs_steps - 1,
92
+ torch.tensor(0, dtype=obs_steps.dtype, device=obs_steps.device),
93
+ )
94
+ action_mask = (steps.T < action_steps).T.reshape(B, T, 1).expand(B, T, D)
95
+ action_mask = action_mask & is_action_dim
96
+
97
+ mask = obs_mask
98
+ if self.action_visible:
99
+ mask = mask | action_mask
100
+
101
+ return mask
102
+
103
+
104
+ class KeypointMaskGenerator(ModuleAttrMixin):
105
+
106
+ def __init__(
107
+ self,
108
+ # dimensions
109
+ action_dim,
110
+ keypoint_dim,
111
+ # obs mask setup
112
+ max_n_obs_steps=2,
113
+ fix_obs_steps=True,
114
+ # keypoint mask setup
115
+ keypoint_visible_rate=0.7,
116
+ time_independent=False,
117
+ # action mask
118
+ action_visible=False,
119
+ context_dim=0, # dim for context
120
+ n_context_steps=1,
121
+ ):
122
+ super().__init__()
123
+ self.action_dim = action_dim
124
+ self.keypoint_dim = keypoint_dim
125
+ self.context_dim = context_dim
126
+ self.max_n_obs_steps = max_n_obs_steps
127
+ self.fix_obs_steps = fix_obs_steps
128
+ self.keypoint_visible_rate = keypoint_visible_rate
129
+ self.time_independent = time_independent
130
+ self.action_visible = action_visible
131
+ self.n_context_steps = n_context_steps
132
+
133
+ @torch.no_grad()
134
+ def forward(self, shape, seed=None):
135
+ device = self.device
136
+ B, T, D = shape
137
+ all_keypoint_dims = D - self.action_dim - self.context_dim
138
+ n_keypoints = all_keypoint_dims // self.keypoint_dim
139
+
140
+ # create all tensors on this device
141
+ rng = torch.Generator(device=device)
142
+ if seed is not None:
143
+ rng = rng.manual_seed(seed)
144
+
145
+ # generate dim mask
146
+ dim_mask = torch.zeros(size=shape, dtype=torch.bool, device=device)
147
+ is_action_dim = dim_mask.clone()
148
+ is_action_dim[..., :self.action_dim] = True
149
+ is_context_dim = dim_mask.clone()
150
+ if self.context_dim > 0:
151
+ is_context_dim[..., -self.context_dim:] = True
152
+ is_obs_dim = ~(is_action_dim | is_context_dim)
153
+ # assumption trajectory=cat([action, keypoints, context], dim=-1)
154
+
155
+ # generate obs mask
156
+ if self.fix_obs_steps:
157
+ obs_steps = torch.full((B, ), fill_value=self.max_n_obs_steps, device=device)
158
+ else:
159
+ obs_steps = torch.randint(
160
+ low=1,
161
+ high=self.max_n_obs_steps + 1,
162
+ size=(B, ),
163
+ generator=rng,
164
+ device=device,
165
+ )
166
+
167
+ steps = torch.arange(0, T, device=device).reshape(1, T).expand(B, T)
168
+ obs_mask = (steps.T < obs_steps).T.reshape(B, T, 1).expand(B, T, D)
169
+ obs_mask = obs_mask & is_obs_dim
170
+
171
+ # generate action mask
172
+ if self.action_visible:
173
+ action_steps = torch.maximum(
174
+ obs_steps - 1,
175
+ torch.tensor(0, dtype=obs_steps.dtype, device=obs_steps.device),
176
+ )
177
+ action_mask = (steps.T < action_steps).T.reshape(B, T, 1).expand(B, T, D)
178
+ action_mask = action_mask & is_action_dim
179
+
180
+ # generate keypoint mask
181
+ if self.time_independent:
182
+ visible_kps = (torch.rand(size=(B, T, n_keypoints), generator=rng, device=device)
183
+ < self.keypoint_visible_rate)
184
+ visible_dims = torch.repeat_interleave(visible_kps, repeats=self.keypoint_dim, dim=-1)
185
+ visible_dims_mask = torch.cat(
186
+ [
187
+ torch.ones((B, T, self.action_dim), dtype=torch.bool, device=device),
188
+ visible_dims,
189
+ torch.ones((B, T, self.context_dim), dtype=torch.bool, device=device),
190
+ ],
191
+ axis=-1,
192
+ )
193
+ keypoint_mask = visible_dims_mask
194
+ else:
195
+ visible_kps = (torch.rand(size=(B, n_keypoints), generator=rng, device=device) < self.keypoint_visible_rate)
196
+ visible_dims = torch.repeat_interleave(visible_kps, repeats=self.keypoint_dim, dim=-1)
197
+ visible_dims_mask = torch.cat(
198
+ [
199
+ torch.ones((B, self.action_dim), dtype=torch.bool, device=device),
200
+ visible_dims,
201
+ torch.ones((B, self.context_dim), dtype=torch.bool, device=device),
202
+ ],
203
+ axis=-1,
204
+ )
205
+ keypoint_mask = visible_dims_mask.reshape(B, 1, D).expand(B, T, D)
206
+ keypoint_mask = keypoint_mask & is_obs_dim
207
+
208
+ # generate context mask
209
+ context_mask = is_context_dim.clone()
210
+ context_mask[:, self.n_context_steps:, :] = False
211
+
212
+ mask = obs_mask & keypoint_mask
213
+ if self.action_visible:
214
+ mask = mask | action_mask
215
+ if self.context_dim > 0:
216
+ mask = mask | context_mask
217
+
218
+ return mask
219
+
220
+
221
+ def test():
222
+ # kmg = KeypointMaskGenerator(2,2, random_obs_steps=True)
223
+ # self = KeypointMaskGenerator(2,2,context_dim=2, action_visible=True)
224
+ # self = KeypointMaskGenerator(2,2,context_dim=0, action_visible=True)
225
+ self = LowdimMaskGenerator(2, 20, max_n_obs_steps=3, action_visible=True)
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/positional_embedding.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+
5
+
6
+ class SinusoidalPosEmb(nn.Module):
7
+
8
+ def __init__(self, dim):
9
+ super().__init__()
10
+ self.dim = dim
11
+
12
+ def forward(self, x):
13
+ device = x.device
14
+ half_dim = self.dim // 2
15
+ emb = math.log(10000) / (half_dim - 1)
16
+ emb = torch.exp(torch.arange(half_dim, device=device) * -emb)
17
+ emb = x[:, None] * emb[None, :]
18
+ emb = torch.cat((emb.sin(), emb.cos()), dim=-1)
19
+ return emb
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/diffusion/transformer_for_diffusion.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, Optional, Tuple
2
+ import logging
3
+ import torch
4
+ import torch.nn as nn
5
+ from diffusion_policy.model.diffusion.positional_embedding import SinusoidalPosEmb
6
+ from diffusion_policy.model.common.module_attr_mixin import ModuleAttrMixin
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ class TransformerForDiffusion(ModuleAttrMixin):
12
+
13
+ def __init__(
14
+ self,
15
+ input_dim: int,
16
+ output_dim: int,
17
+ horizon: int,
18
+ n_obs_steps: int = None,
19
+ cond_dim: int = 0,
20
+ n_layer: int = 12,
21
+ n_head: int = 12,
22
+ n_emb: int = 768,
23
+ p_drop_emb: float = 0.1,
24
+ p_drop_attn: float = 0.1,
25
+ causal_attn: bool = False,
26
+ time_as_cond: bool = True,
27
+ obs_as_cond: bool = False,
28
+ n_cond_layers: int = 0,
29
+ ) -> None:
30
+ super().__init__()
31
+
32
+ # compute number of tokens for main trunk and condition encoder
33
+ if n_obs_steps is None:
34
+ n_obs_steps = horizon
35
+
36
+ T = horizon
37
+ T_cond = 1
38
+ if not time_as_cond:
39
+ T += 1
40
+ T_cond -= 1
41
+ obs_as_cond = cond_dim > 0
42
+ if obs_as_cond:
43
+ assert time_as_cond
44
+ T_cond += n_obs_steps
45
+
46
+ # input embedding stem
47
+ self.input_emb = nn.Linear(input_dim, n_emb)
48
+ self.pos_emb = nn.Parameter(torch.zeros(1, T, n_emb))
49
+ self.drop = nn.Dropout(p_drop_emb)
50
+
51
+ # cond encoder
52
+ self.time_emb = SinusoidalPosEmb(n_emb)
53
+ self.cond_obs_emb = None
54
+
55
+ if obs_as_cond:
56
+ self.cond_obs_emb = nn.Linear(cond_dim, n_emb)
57
+
58
+ self.cond_pos_emb = None
59
+ self.encoder = None
60
+ self.decoder = None
61
+ encoder_only = False
62
+ if T_cond > 0:
63
+ self.cond_pos_emb = nn.Parameter(torch.zeros(1, T_cond, n_emb))
64
+ if n_cond_layers > 0:
65
+ encoder_layer = nn.TransformerEncoderLayer(
66
+ d_model=n_emb,
67
+ nhead=n_head,
68
+ dim_feedforward=4 * n_emb,
69
+ dropout=p_drop_attn,
70
+ activation="gelu",
71
+ batch_first=True,
72
+ norm_first=True,
73
+ )
74
+ self.encoder = nn.TransformerEncoder(encoder_layer=encoder_layer, num_layers=n_cond_layers)
75
+ else:
76
+ self.encoder = nn.Sequential(nn.Linear(n_emb, 4 * n_emb), nn.Mish(), nn.Linear(4 * n_emb, n_emb))
77
+ # decoder
78
+ decoder_layer = nn.TransformerDecoderLayer(
79
+ d_model=n_emb,
80
+ nhead=n_head,
81
+ dim_feedforward=4 * n_emb,
82
+ dropout=p_drop_attn,
83
+ activation="gelu",
84
+ batch_first=True,
85
+ norm_first=True, # important for stability
86
+ )
87
+ self.decoder = nn.TransformerDecoder(decoder_layer=decoder_layer, num_layers=n_layer)
88
+ else:
89
+ # encoder only BERT
90
+ encoder_only = True
91
+
92
+ encoder_layer = nn.TransformerEncoderLayer(
93
+ d_model=n_emb,
94
+ nhead=n_head,
95
+ dim_feedforward=4 * n_emb,
96
+ dropout=p_drop_attn,
97
+ activation="gelu",
98
+ batch_first=True,
99
+ norm_first=True,
100
+ )
101
+ self.encoder = nn.TransformerEncoder(encoder_layer=encoder_layer, num_layers=n_layer)
102
+
103
+ # attention mask
104
+ if causal_attn:
105
+ # causal mask to ensure that attention is only applied to the left in the input sequence
106
+ # torch.nn.Transformer uses additive mask as opposed to multiplicative mask in minGPT
107
+ # therefore, the upper triangle should be -inf and others (including diag) should be 0.
108
+ sz = T
109
+ mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
110
+ mask = (mask.float().masked_fill(mask == 0, float("-inf")).masked_fill(mask == 1, float(0.0)))
111
+ self.register_buffer("mask", mask)
112
+
113
+ if time_as_cond and obs_as_cond:
114
+ S = T_cond
115
+ t, s = torch.meshgrid(torch.arange(T), torch.arange(S), indexing="ij")
116
+ mask = t >= (s - 1) # add one dimension since time is the first token in cond
117
+ mask = (mask.float().masked_fill(mask == 0, float("-inf")).masked_fill(mask == 1, float(0.0)))
118
+ self.register_buffer("memory_mask", mask)
119
+ else:
120
+ self.memory_mask = None
121
+ else:
122
+ self.mask = None
123
+ self.memory_mask = None
124
+
125
+ # decoder head
126
+ self.ln_f = nn.LayerNorm(n_emb)
127
+ self.head = nn.Linear(n_emb, output_dim)
128
+
129
+ # constants
130
+ self.T = T
131
+ self.T_cond = T_cond
132
+ self.horizon = horizon
133
+ self.time_as_cond = time_as_cond
134
+ self.obs_as_cond = obs_as_cond
135
+ self.encoder_only = encoder_only
136
+
137
+ # init
138
+ self.apply(self._init_weights)
139
+ logger.info("number of parameters: %e", sum(p.numel() for p in self.parameters()))
140
+
141
+ def _init_weights(self, module):
142
+ ignore_types = (
143
+ nn.Dropout,
144
+ SinusoidalPosEmb,
145
+ nn.TransformerEncoderLayer,
146
+ nn.TransformerDecoderLayer,
147
+ nn.TransformerEncoder,
148
+ nn.TransformerDecoder,
149
+ nn.ModuleList,
150
+ nn.Mish,
151
+ nn.Sequential,
152
+ )
153
+ if isinstance(module, (nn.Linear, nn.Embedding)):
154
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
155
+ if isinstance(module, nn.Linear) and module.bias is not None:
156
+ torch.nn.init.zeros_(module.bias)
157
+ elif isinstance(module, nn.MultiheadAttention):
158
+ weight_names = [
159
+ "in_proj_weight",
160
+ "q_proj_weight",
161
+ "k_proj_weight",
162
+ "v_proj_weight",
163
+ ]
164
+ for name in weight_names:
165
+ weight = getattr(module, name)
166
+ if weight is not None:
167
+ torch.nn.init.normal_(weight, mean=0.0, std=0.02)
168
+
169
+ bias_names = ["in_proj_bias", "bias_k", "bias_v"]
170
+ for name in bias_names:
171
+ bias = getattr(module, name)
172
+ if bias is not None:
173
+ torch.nn.init.zeros_(bias)
174
+ elif isinstance(module, nn.LayerNorm):
175
+ torch.nn.init.zeros_(module.bias)
176
+ torch.nn.init.ones_(module.weight)
177
+ elif isinstance(module, TransformerForDiffusion):
178
+ torch.nn.init.normal_(module.pos_emb, mean=0.0, std=0.02)
179
+ if module.cond_obs_emb is not None:
180
+ torch.nn.init.normal_(module.cond_pos_emb, mean=0.0, std=0.02)
181
+ elif isinstance(module, ignore_types):
182
+ # no param
183
+ pass
184
+ else:
185
+ raise RuntimeError("Unaccounted module {}".format(module))
186
+
187
+ def get_optim_groups(self, weight_decay: float = 1e-3):
188
+ """
189
+ This long function is unfortunately doing something very simple and is being very defensive:
190
+ We are separating out all parameters of the model into two buckets: those that will experience
191
+ weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
192
+ We are then returning the PyTorch optimizer object.
193
+ """
194
+
195
+ # separate out all parameters to those that will and won't experience regularizing weight decay
196
+ decay = set()
197
+ no_decay = set()
198
+ whitelist_weight_modules = (torch.nn.Linear, torch.nn.MultiheadAttention)
199
+ blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)
200
+ for mn, m in self.named_modules():
201
+ for pn, p in m.named_parameters():
202
+ fpn = "%s.%s" % (mn, pn) if mn else pn # full param name
203
+
204
+ if pn.endswith("bias"):
205
+ # all biases will not be decayed
206
+ no_decay.add(fpn)
207
+ elif pn.startswith("bias"):
208
+ # MultiheadAttention bias starts with "bias"
209
+ no_decay.add(fpn)
210
+ elif pn.endswith("weight") and isinstance(m, whitelist_weight_modules):
211
+ # weights of whitelist modules will be weight decayed
212
+ decay.add(fpn)
213
+ elif pn.endswith("weight") and isinstance(m, blacklist_weight_modules):
214
+ # weights of blacklist modules will NOT be weight decayed
215
+ no_decay.add(fpn)
216
+
217
+ # special case the position embedding parameter in the root GPT module as not decayed
218
+ no_decay.add("pos_emb")
219
+ no_decay.add("_dummy_variable")
220
+ if self.cond_pos_emb is not None:
221
+ no_decay.add("cond_pos_emb")
222
+
223
+ # validate that we considered every parameter
224
+ param_dict = {pn: p for pn, p in self.named_parameters()}
225
+ inter_params = decay & no_decay
226
+ union_params = decay | no_decay
227
+ assert (len(inter_params) == 0), "parameters %s made it into both decay/no_decay sets!" % (str(inter_params), )
228
+ assert (len(param_dict.keys() -
229
+ union_params) == 0), "parameters %s were not separated into either decay/no_decay set!" % (
230
+ str(param_dict.keys() - union_params), )
231
+
232
+ # create the pytorch optimizer object
233
+ optim_groups = [
234
+ {
235
+ "params": [param_dict[pn] for pn in sorted(list(decay))],
236
+ "weight_decay": weight_decay,
237
+ },
238
+ {
239
+ "params": [param_dict[pn] for pn in sorted(list(no_decay))],
240
+ "weight_decay": 0.0,
241
+ },
242
+ ]
243
+ return optim_groups
244
+
245
+ def configure_optimizers(
246
+ self,
247
+ learning_rate: float = 1e-4,
248
+ weight_decay: float = 1e-3,
249
+ betas: Tuple[float, float] = (0.9, 0.95),
250
+ ):
251
+ optim_groups = self.get_optim_groups(weight_decay=weight_decay)
252
+ optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas)
253
+ return optimizer
254
+
255
+ def forward(self,
256
+ sample: torch.Tensor,
257
+ timestep: Union[torch.Tensor, float, int],
258
+ cond: Optional[torch.Tensor] = None,
259
+ **kwargs):
260
+ """
261
+ x: (B,T,input_dim)
262
+ timestep: (B,) or int, diffusion step
263
+ cond: (B,T',cond_dim)
264
+ output: (B,T,input_dim)
265
+ """
266
+ # 1. time
267
+ timesteps = timestep
268
+ if not torch.is_tensor(timesteps):
269
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
270
+ timesteps = torch.tensor([timesteps], dtype=torch.long, device=sample.device)
271
+ elif torch.is_tensor(timesteps) and len(timesteps.shape) == 0:
272
+ timesteps = timesteps[None].to(sample.device)
273
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
274
+ timesteps = timesteps.expand(sample.shape[0])
275
+ time_emb = self.time_emb(timesteps).unsqueeze(1)
276
+ # (B,1,n_emb)
277
+
278
+ # process input
279
+ input_emb = self.input_emb(sample)
280
+
281
+ if self.encoder_only:
282
+ # BERT
283
+ token_embeddings = torch.cat([time_emb, input_emb], dim=1)
284
+ t = token_embeddings.shape[1]
285
+ position_embeddings = self.pos_emb[:, :t, :] # each position maps to a (learnable) vector
286
+ x = self.drop(token_embeddings + position_embeddings)
287
+ # (B,T+1,n_emb)
288
+ x = self.encoder(src=x, mask=self.mask)
289
+ # (B,T+1,n_emb)
290
+ x = x[:, 1:, :]
291
+ # (B,T,n_emb)
292
+ else:
293
+ # encoder
294
+ cond_embeddings = time_emb
295
+ if self.obs_as_cond:
296
+ cond_obs_emb = self.cond_obs_emb(cond)
297
+ # (B,To,n_emb)
298
+ cond_embeddings = torch.cat([cond_embeddings, cond_obs_emb], dim=1)
299
+ tc = cond_embeddings.shape[1]
300
+ position_embeddings = self.cond_pos_emb[:, :tc, :] # each position maps to a (learnable) vector
301
+ x = self.drop(cond_embeddings + position_embeddings)
302
+ x = self.encoder(x)
303
+ memory = x
304
+ # (B,T_cond,n_emb)
305
+
306
+ # decoder
307
+ token_embeddings = input_emb
308
+ t = token_embeddings.shape[1]
309
+ position_embeddings = self.pos_emb[:, :t, :] # each position maps to a (learnable) vector
310
+ x = self.drop(token_embeddings + position_embeddings)
311
+ # (B,T,n_emb)
312
+ x = self.decoder(tgt=x, memory=memory, tgt_mask=self.mask, memory_mask=self.memory_mask)
313
+ # (B,T,n_emb)
314
+
315
+ # head
316
+ x = self.ln_f(x)
317
+ x = self.head(x)
318
+ # (B,T,n_out)
319
+ return x
320
+
321
+
322
+ def test():
323
+ # GPT with time embedding
324
+ transformer = TransformerForDiffusion(
325
+ input_dim=16,
326
+ output_dim=16,
327
+ horizon=8,
328
+ n_obs_steps=4,
329
+ # cond_dim=10,
330
+ causal_attn=True,
331
+ # time_as_cond=False,
332
+ # n_cond_layers=4
333
+ )
334
+ opt = transformer.configure_optimizers()
335
+
336
+ timestep = torch.tensor(0)
337
+ sample = torch.zeros((4, 8, 16))
338
+ out = transformer(sample, timestep)
339
+
340
+ # GPT with time embedding and obs cond
341
+ transformer = TransformerForDiffusion(
342
+ input_dim=16,
343
+ output_dim=16,
344
+ horizon=8,
345
+ n_obs_steps=4,
346
+ cond_dim=10,
347
+ causal_attn=True,
348
+ # time_as_cond=False,
349
+ # n_cond_layers=4
350
+ )
351
+ opt = transformer.configure_optimizers()
352
+
353
+ timestep = torch.tensor(0)
354
+ sample = torch.zeros((4, 8, 16))
355
+ cond = torch.zeros((4, 4, 10))
356
+ out = transformer(sample, timestep, cond)
357
+
358
+ # GPT with time embedding and obs cond and encoder
359
+ transformer = TransformerForDiffusion(
360
+ input_dim=16,
361
+ output_dim=16,
362
+ horizon=8,
363
+ n_obs_steps=4,
364
+ cond_dim=10,
365
+ causal_attn=True,
366
+ # time_as_cond=False,
367
+ n_cond_layers=4,
368
+ )
369
+ opt = transformer.configure_optimizers()
370
+
371
+ timestep = torch.tensor(0)
372
+ sample = torch.zeros((4, 8, 16))
373
+ cond = torch.zeros((4, 4, 10))
374
+ out = transformer(sample, timestep, cond)
375
+
376
+ # BERT with time embedding token
377
+ transformer = TransformerForDiffusion(
378
+ input_dim=16,
379
+ output_dim=16,
380
+ horizon=8,
381
+ n_obs_steps=4,
382
+ # cond_dim=10,
383
+ # causal_attn=True,
384
+ time_as_cond=False,
385
+ # n_cond_layers=4
386
+ )
387
+ opt = transformer.configure_optimizers()
388
+
389
+ timestep = torch.tensor(0)
390
+ sample = torch.zeros((4, 8, 16))
391
+ out = transformer(sample, timestep)
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/vision/crop_randomizer.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torchvision.transforms.functional as ttf
4
+ import diffusion_policy.model.common.tensor_util as tu
5
+
6
+
7
+ class CropRandomizer(nn.Module):
8
+ """
9
+ Randomly sample crops at input, and then average across crop features at output.
10
+ """
11
+
12
+ def __init__(
13
+ self,
14
+ input_shape,
15
+ crop_height,
16
+ crop_width,
17
+ num_crops=1,
18
+ pos_enc=False,
19
+ ):
20
+ """
21
+ Args:
22
+ input_shape (tuple, list): shape of input (not including batch dimension)
23
+ crop_height (int): crop height
24
+ crop_width (int): crop width
25
+ num_crops (int): number of random crops to take
26
+ pos_enc (bool): if True, add 2 channels to the output to encode the spatial
27
+ location of the cropped pixels in the source image
28
+ """
29
+ super().__init__()
30
+
31
+ assert len(input_shape) == 3 # (C, H, W)
32
+ assert crop_height < input_shape[1]
33
+ assert crop_width < input_shape[2]
34
+
35
+ self.input_shape = input_shape
36
+ self.crop_height = crop_height
37
+ self.crop_width = crop_width
38
+ self.num_crops = num_crops
39
+ self.pos_enc = pos_enc
40
+
41
+ def output_shape_in(self, input_shape=None):
42
+ """
43
+ Function to compute output shape from inputs to this module. Corresponds to
44
+ the @forward_in operation, where raw inputs (usually observation modalities)
45
+ are passed in.
46
+
47
+ Args:
48
+ input_shape (iterable of int): shape of input. Does not include batch dimension.
49
+ Some modules may not need this argument, if their output does not depend
50
+ on the size of the input, or if they assume fixed size input.
51
+
52
+ Returns:
53
+ out_shape ([int]): list of integers corresponding to output shape
54
+ """
55
+
56
+ # outputs are shape (C, CH, CW), or maybe C + 2 if using position encoding, because
57
+ # the number of crops are reshaped into the batch dimension, increasing the batch
58
+ # size from B to B * N
59
+ out_c = self.input_shape[0] + 2 if self.pos_enc else self.input_shape[0]
60
+ return [out_c, self.crop_height, self.crop_width]
61
+
62
+ def output_shape_out(self, input_shape=None):
63
+ """
64
+ Function to compute output shape from inputs to this module. Corresponds to
65
+ the @forward_out operation, where processed inputs (usually encoded observation
66
+ modalities) are passed in.
67
+
68
+ Args:
69
+ input_shape (iterable of int): shape of input. Does not include batch dimension.
70
+ Some modules may not need this argument, if their output does not depend
71
+ on the size of the input, or if they assume fixed size input.
72
+
73
+ Returns:
74
+ out_shape ([int]): list of integers corresponding to output shape
75
+ """
76
+
77
+ # since the forward_out operation splits [B * N, ...] -> [B, N, ...]
78
+ # and then pools to result in [B, ...], only the batch dimension changes,
79
+ # and so the other dimensions retain their shape.
80
+ return list(input_shape)
81
+
82
+ def forward_in(self, inputs):
83
+ """
84
+ Samples N random crops for each input in the batch, and then reshapes
85
+ inputs to [B * N, ...].
86
+ """
87
+ assert len(inputs.shape) >= 3 # must have at least (C, H, W) dimensions
88
+ if self.training:
89
+ # generate random crops
90
+ out, _ = sample_random_image_crops(
91
+ images=inputs,
92
+ crop_height=self.crop_height,
93
+ crop_width=self.crop_width,
94
+ num_crops=self.num_crops,
95
+ pos_enc=self.pos_enc,
96
+ )
97
+ # [B, N, ...] -> [B * N, ...]
98
+ return tu.join_dimensions(out, 0, 1)
99
+ else:
100
+ # take center crop during eval
101
+ out = ttf.center_crop(img=inputs, output_size=(self.crop_height, self.crop_width))
102
+ if self.num_crops > 1:
103
+ B, C, H, W = out.shape
104
+ out = (out.unsqueeze(1).expand(B, self.num_crops, C, H, W).reshape(-1, C, H, W))
105
+ # [B * N, ...]
106
+ return out
107
+
108
+ def forward_out(self, inputs):
109
+ """
110
+ Splits the outputs from shape [B * N, ...] -> [B, N, ...] and then average across N
111
+ to result in shape [B, ...] to make sure the network output is consistent with
112
+ what would have happened if there were no randomization.
113
+ """
114
+ if self.num_crops <= 1:
115
+ return inputs
116
+ else:
117
+ batch_size = inputs.shape[0] // self.num_crops
118
+ out = tu.reshape_dimensions(
119
+ inputs,
120
+ begin_axis=0,
121
+ end_axis=0,
122
+ target_dims=(batch_size, self.num_crops),
123
+ )
124
+ return out.mean(dim=1)
125
+
126
+ def forward(self, inputs):
127
+ return self.forward_in(inputs)
128
+
129
+ def __repr__(self):
130
+ """Pretty print network."""
131
+ header = "{}".format(str(self.__class__.__name__))
132
+ msg = header + "(input_shape={}, crop_size=[{}, {}], num_crops={})".format(self.input_shape, self.crop_height,
133
+ self.crop_width, self.num_crops)
134
+ return msg
135
+
136
+
137
+ def crop_image_from_indices(images, crop_indices, crop_height, crop_width):
138
+ """
139
+ Crops images at the locations specified by @crop_indices. Crops will be
140
+ taken across all channels.
141
+
142
+ Args:
143
+ images (torch.Tensor): batch of images of shape [..., C, H, W]
144
+
145
+ crop_indices (torch.Tensor): batch of indices of shape [..., N, 2] where
146
+ N is the number of crops to take per image and each entry corresponds
147
+ to the pixel height and width of where to take the crop. Note that
148
+ the indices can also be of shape [..., 2] if only 1 crop should
149
+ be taken per image. Leading dimensions must be consistent with
150
+ @images argument. Each index specifies the top left of the crop.
151
+ Values must be in range [0, H - CH - 1] x [0, W - CW - 1] where
152
+ H and W are the height and width of @images and CH and CW are
153
+ @crop_height and @crop_width.
154
+
155
+ crop_height (int): height of crop to take
156
+
157
+ crop_width (int): width of crop to take
158
+
159
+ Returns:
160
+ crops (torch.Tesnor): cropped images of shape [..., C, @crop_height, @crop_width]
161
+ """
162
+
163
+ # make sure length of input shapes is consistent
164
+ assert crop_indices.shape[-1] == 2
165
+ ndim_im_shape = len(images.shape)
166
+ ndim_indices_shape = len(crop_indices.shape)
167
+ assert (ndim_im_shape == ndim_indices_shape + 1) or (ndim_im_shape == ndim_indices_shape + 2)
168
+
169
+ # maybe pad so that @crop_indices is shape [..., N, 2]
170
+ is_padded = False
171
+ if ndim_im_shape == ndim_indices_shape + 2:
172
+ crop_indices = crop_indices.unsqueeze(-2)
173
+ is_padded = True
174
+
175
+ # make sure leading dimensions between images and indices are consistent
176
+ assert images.shape[:-3] == crop_indices.shape[:-2]
177
+
178
+ device = images.device
179
+ image_c, image_h, image_w = images.shape[-3:]
180
+ num_crops = crop_indices.shape[-2]
181
+
182
+ # make sure @crop_indices are in valid range
183
+ assert (crop_indices[..., 0] >= 0).all().item()
184
+ assert (crop_indices[..., 0] < (image_h - crop_height)).all().item()
185
+ assert (crop_indices[..., 1] >= 0).all().item()
186
+ assert (crop_indices[..., 1] < (image_w - crop_width)).all().item()
187
+
188
+ # convert each crop index (ch, cw) into a list of pixel indices that correspond to the entire window.
189
+
190
+ # 2D index array with columns [0, 1, ..., CH - 1] and shape [CH, CW]
191
+ crop_ind_grid_h = torch.arange(crop_height).to(device)
192
+ crop_ind_grid_h = tu.unsqueeze_expand_at(crop_ind_grid_h, size=crop_width, dim=-1)
193
+ # 2D index array with rows [0, 1, ..., CW - 1] and shape [CH, CW]
194
+ crop_ind_grid_w = torch.arange(crop_width).to(device)
195
+ crop_ind_grid_w = tu.unsqueeze_expand_at(crop_ind_grid_w, size=crop_height, dim=0)
196
+ # combine into shape [CH, CW, 2]
197
+ crop_in_grid = torch.cat((crop_ind_grid_h.unsqueeze(-1), crop_ind_grid_w.unsqueeze(-1)), dim=-1)
198
+
199
+ # Add above grid with the offset index of each sampled crop to get 2d indices for each crop.
200
+ # After broadcasting, this will be shape [..., N, CH, CW, 2] and each crop has a [CH, CW, 2]
201
+ # shape array that tells us which pixels from the corresponding source image to grab.
202
+ grid_reshape = [1] * len(crop_indices.shape[:-1]) + [crop_height, crop_width, 2]
203
+ all_crop_inds = crop_indices.unsqueeze(-2).unsqueeze(-2) + crop_in_grid.reshape(grid_reshape)
204
+
205
+ # For using @torch.gather, convert to flat indices from 2D indices, and also
206
+ # repeat across the channel dimension. To get flat index of each pixel to grab for
207
+ # each sampled crop, we just use the mapping: ind = h_ind * @image_w + w_ind
208
+ all_crop_inds = (all_crop_inds[..., 0] * image_w + all_crop_inds[..., 1]) # shape [..., N, CH, CW]
209
+ all_crop_inds = tu.unsqueeze_expand_at(all_crop_inds, size=image_c, dim=-3) # shape [..., N, C, CH, CW]
210
+ all_crop_inds = tu.flatten(all_crop_inds, begin_axis=-2) # shape [..., N, C, CH * CW]
211
+
212
+ # Repeat and flatten the source images -> [..., N, C, H * W] and then use gather to index with crop pixel inds
213
+ images_to_crop = tu.unsqueeze_expand_at(images, size=num_crops, dim=-4)
214
+ images_to_crop = tu.flatten(images_to_crop, begin_axis=-2)
215
+ crops = torch.gather(images_to_crop, dim=-1, index=all_crop_inds)
216
+ # [..., N, C, CH * CW] -> [..., N, C, CH, CW]
217
+ reshape_axis = len(crops.shape) - 1
218
+ crops = tu.reshape_dimensions(
219
+ crops,
220
+ begin_axis=reshape_axis,
221
+ end_axis=reshape_axis,
222
+ target_dims=(crop_height, crop_width),
223
+ )
224
+
225
+ if is_padded:
226
+ # undo padding -> [..., C, CH, CW]
227
+ crops = crops.squeeze(-4)
228
+ return crops
229
+
230
+
231
+ def sample_random_image_crops(images, crop_height, crop_width, num_crops, pos_enc=False):
232
+ """
233
+ For each image, randomly sample @num_crops crops of size (@crop_height, @crop_width), from
234
+ @images.
235
+
236
+ Args:
237
+ images (torch.Tensor): batch of images of shape [..., C, H, W]
238
+
239
+ crop_height (int): height of crop to take
240
+
241
+ crop_width (int): width of crop to take
242
+
243
+ num_crops (n): number of crops to sample
244
+
245
+ pos_enc (bool): if True, also add 2 channels to the outputs that gives a spatial
246
+ encoding of the original source pixel locations. This means that the
247
+ output crops will contain information about where in the source image
248
+ it was sampled from.
249
+
250
+ Returns:
251
+ crops (torch.Tensor): crops of shape (..., @num_crops, C, @crop_height, @crop_width)
252
+ if @pos_enc is False, otherwise (..., @num_crops, C + 2, @crop_height, @crop_width)
253
+
254
+ crop_inds (torch.Tensor): sampled crop indices of shape (..., N, 2)
255
+ """
256
+ device = images.device
257
+
258
+ # maybe add 2 channels of spatial encoding to the source image
259
+ source_im = images
260
+ if pos_enc:
261
+ # spatial encoding [y, x] in [0, 1]
262
+ h, w = source_im.shape[-2:]
263
+ pos_y, pos_x = torch.meshgrid(torch.arange(h), torch.arange(w))
264
+ pos_y = pos_y.float().to(device) / float(h)
265
+ pos_x = pos_x.float().to(device) / float(w)
266
+ position_enc = torch.stack((pos_y, pos_x)) # shape [C, H, W]
267
+
268
+ # unsqueeze and expand to match leading dimensions -> shape [..., C, H, W]
269
+ leading_shape = source_im.shape[:-3]
270
+ position_enc = position_enc[(None, ) * len(leading_shape)]
271
+ position_enc = position_enc.expand(*leading_shape, -1, -1, -1)
272
+
273
+ # concat across channel dimension with input
274
+ source_im = torch.cat((source_im, position_enc), dim=-3)
275
+
276
+ # make sure sample boundaries ensure crops are fully within the images
277
+ image_c, image_h, image_w = source_im.shape[-3:]
278
+ max_sample_h = image_h - crop_height
279
+ max_sample_w = image_w - crop_width
280
+
281
+ # Sample crop locations for all tensor dimensions up to the last 3, which are [C, H, W].
282
+ # Each gets @num_crops samples - typically this will just be the batch dimension (B), so
283
+ # we will sample [B, N] indices, but this supports having more than one leading dimension,
284
+ # or possibly no leading dimension.
285
+ #
286
+ # Trick: sample in [0, 1) with rand, then re-scale to [0, M) and convert to long to get sampled ints
287
+ crop_inds_h = (max_sample_h * torch.rand(*source_im.shape[:-3], num_crops).to(device)).long()
288
+ crop_inds_w = (max_sample_w * torch.rand(*source_im.shape[:-3], num_crops).to(device)).long()
289
+ crop_inds = torch.cat((crop_inds_h.unsqueeze(-1), crop_inds_w.unsqueeze(-1)), dim=-1) # shape [..., N, 2]
290
+
291
+ crops = crop_image_from_indices(
292
+ images=source_im,
293
+ crop_indices=crop_inds,
294
+ crop_height=crop_height,
295
+ crop_width=crop_width,
296
+ )
297
+
298
+ return crops, crop_inds
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/vision/model_getter.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision
3
+
4
+
5
+ def get_resnet(name, weights=None, **kwargs):
6
+ """
7
+ name: resnet18, resnet34, resnet50
8
+ weights: "IMAGENET1K_V1", "r3m"
9
+ """
10
+ # load r3m weights
11
+ if (weights == "r3m") or (weights == "R3M"):
12
+ return get_r3m(name=name, **kwargs)
13
+
14
+ func = getattr(torchvision.models, name)
15
+ resnet = func(weights=weights, **kwargs)
16
+ resnet.fc = torch.nn.Identity()
17
+ # resnet_new = torch.nn.Sequential(
18
+ # resnet,
19
+ # torch.nn.Linear(512, 128)
20
+ # )
21
+ # return resnet_new
22
+ return resnet
23
+
24
+
25
+ def get_r3m(name, **kwargs):
26
+ """
27
+ name: resnet18, resnet34, resnet50
28
+ """
29
+ import r3m
30
+
31
+ r3m.device = "cpu"
32
+ model = r3m.load_r3m(name)
33
+ r3m_model = model.module
34
+ resnet_model = r3m_model.convnet
35
+ resnet_model = resnet_model.to("cpu")
36
+ return resnet_model
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/model/vision/multi_image_obs_encoder.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Tuple, Union
2
+ import copy
3
+ import torch
4
+ import torch.nn as nn
5
+ import torchvision
6
+ from diffusion_policy.model.vision.crop_randomizer import CropRandomizer
7
+ from diffusion_policy.model.common.module_attr_mixin import ModuleAttrMixin
8
+ from diffusion_policy.common.pytorch_util import dict_apply, replace_submodules
9
+
10
+
11
+ class MultiImageObsEncoder(ModuleAttrMixin):
12
+
13
+ def __init__(
14
+ self,
15
+ shape_meta: dict,
16
+ rgb_model: Union[nn.Module, Dict[str, nn.Module]],
17
+ resize_shape: Union[Tuple[int, int], Dict[str, tuple], None] = None,
18
+ crop_shape: Union[Tuple[int, int], Dict[str, tuple], None] = None,
19
+ random_crop: bool = True,
20
+ # replace BatchNorm with GroupNorm
21
+ use_group_norm: bool = False,
22
+ # use single rgb model for all rgb inputs
23
+ share_rgb_model: bool = False,
24
+ # renormalize rgb input with imagenet normalization
25
+ # assuming input in [0,1]
26
+ imagenet_norm: bool = False,
27
+ ):
28
+ """
29
+ Assumes rgb input: B,C,H,W
30
+ Assumes low_dim input: B,D
31
+ """
32
+ super().__init__()
33
+
34
+ rgb_keys = list()
35
+ low_dim_keys = list()
36
+ key_model_map = nn.ModuleDict()
37
+ key_transform_map = nn.ModuleDict()
38
+ key_shape_map = dict()
39
+
40
+ # handle sharing vision backbone
41
+ if share_rgb_model:
42
+ assert isinstance(rgb_model, nn.Module)
43
+ key_model_map["rgb"] = rgb_model
44
+
45
+ obs_shape_meta = shape_meta["obs"]
46
+ for key, attr in obs_shape_meta.items():
47
+ shape = tuple(attr["shape"])
48
+ type = attr.get("type", "low_dim")
49
+ key_shape_map[key] = shape
50
+ if type == "rgb":
51
+ rgb_keys.append(key)
52
+ # configure model for this key
53
+ this_model = None
54
+ if not share_rgb_model:
55
+ if isinstance(rgb_model, dict):
56
+ # have provided model for each key
57
+ this_model = rgb_model[key]
58
+ else:
59
+ assert isinstance(rgb_model, nn.Module)
60
+ # have a copy of the rgb model
61
+ this_model = copy.deepcopy(rgb_model)
62
+
63
+ if this_model is not None:
64
+ if use_group_norm:
65
+ this_model = replace_submodules(
66
+ root_module=this_model,
67
+ predicate=lambda x: isinstance(x, nn.BatchNorm2d),
68
+ func=lambda x: nn.GroupNorm(
69
+ num_groups=x.num_features // 16,
70
+ num_channels=x.num_features,
71
+ ),
72
+ )
73
+ key_model_map[key] = this_model
74
+
75
+ # configure resize
76
+ input_shape = shape
77
+ this_resizer = nn.Identity()
78
+ if resize_shape is not None:
79
+ if isinstance(resize_shape, dict):
80
+ h, w = resize_shape[key]
81
+ else:
82
+ h, w = resize_shape
83
+ this_resizer = torchvision.transforms.Resize(size=(h, w))
84
+ input_shape = (shape[0], h, w)
85
+
86
+ # configure randomizer
87
+ this_randomizer = nn.Identity()
88
+ if crop_shape is not None:
89
+ if isinstance(crop_shape, dict):
90
+ h, w = crop_shape[key]
91
+ else:
92
+ h, w = crop_shape
93
+ if random_crop:
94
+ this_randomizer = CropRandomizer(
95
+ input_shape=input_shape,
96
+ crop_height=h,
97
+ crop_width=w,
98
+ num_crops=1,
99
+ pos_enc=False,
100
+ )
101
+ else:
102
+ this_normalizer = torchvision.transforms.CenterCrop(size=(h, w))
103
+ # configure normalizer
104
+ this_normalizer = nn.Identity()
105
+ if imagenet_norm:
106
+ this_normalizer = torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406],
107
+ std=[0.229, 0.224, 0.225])
108
+
109
+ this_transform = nn.Sequential(this_resizer, this_randomizer, this_normalizer)
110
+ key_transform_map[key] = this_transform
111
+ elif type == "low_dim":
112
+ low_dim_keys.append(key)
113
+ else:
114
+ raise RuntimeError(f"Unsupported obs type: {type}")
115
+ rgb_keys = sorted(rgb_keys)
116
+ low_dim_keys = sorted(low_dim_keys)
117
+
118
+ self.shape_meta = shape_meta
119
+ self.key_model_map = key_model_map
120
+ self.key_transform_map = key_transform_map
121
+ self.share_rgb_model = share_rgb_model
122
+ self.rgb_keys = rgb_keys
123
+ self.low_dim_keys = low_dim_keys
124
+ self.key_shape_map = key_shape_map
125
+
126
+ def forward(self, obs_dict):
127
+ batch_size = None
128
+ features = list()
129
+ # process rgb input
130
+ if self.share_rgb_model:
131
+ # pass all rgb obs to rgb model
132
+ imgs = list()
133
+ for key in self.rgb_keys:
134
+ img = obs_dict[key]
135
+ if batch_size is None:
136
+ batch_size = img.shape[0]
137
+ else:
138
+ assert batch_size == img.shape[0]
139
+ assert img.shape[1:] == self.key_shape_map[key]
140
+ img = self.key_transform_map[key](img)
141
+ imgs.append(img)
142
+ # (N*B,C,H,W)
143
+ imgs = torch.cat(imgs, dim=0)
144
+ # (N*B,D)
145
+ feature = self.key_model_map["rgb"](imgs)
146
+ # (N,B,D)
147
+ feature = feature.reshape(-1, batch_size, *feature.shape[1:])
148
+ # (B,N,D)
149
+ feature = torch.moveaxis(feature, 0, 1)
150
+ # (B,N*D)
151
+ feature = feature.reshape(batch_size, -1)
152
+ features.append(feature)
153
+ else:
154
+ # run each rgb obs to independent models
155
+ for key in self.rgb_keys:
156
+ img = obs_dict[key]
157
+ if batch_size is None:
158
+ batch_size = img.shape[0]
159
+ else:
160
+ assert batch_size == img.shape[0]
161
+ assert img.shape[1:] == self.key_shape_map[key], f"Image shape error: {img.shape[1:]} vs {self.key_shape_map[key]}"
162
+ img = self.key_transform_map[key](img)
163
+ feature = self.key_model_map[key](img)
164
+ features.append(feature)
165
+
166
+ # process lowdim input
167
+ for key in self.low_dim_keys:
168
+ data = obs_dict[key]
169
+ if batch_size is None:
170
+ batch_size = data.shape[0]
171
+ else:
172
+ assert batch_size == data.shape[0]
173
+ assert data.shape[1:] == self.key_shape_map[key]
174
+ features.append(data)
175
+
176
+ # concatenate all features
177
+ result = torch.cat(features, dim=-1)
178
+ return result
179
+
180
+ @torch.no_grad()
181
+ def output_shape(self):
182
+ example_obs_dict = dict()
183
+ obs_shape_meta = self.shape_meta["obs"]
184
+ batch_size = 1
185
+ for key, attr in obs_shape_meta.items():
186
+ shape = tuple(attr["shape"])
187
+ this_obs = torch.zeros((batch_size, ) + shape, dtype=self.dtype, device=self.device)
188
+ example_obs_dict[key] = this_obs
189
+ example_output = self.forward(example_obs_dict)
190
+ output_shape = example_output.shape[1:]
191
+ return output_shape
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/policy/base_image_policy.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict
2
+ import torch
3
+ import torch.nn as nn
4
+ from diffusion_policy.model.common.module_attr_mixin import ModuleAttrMixin
5
+ from diffusion_policy.model.common.normalizer import LinearNormalizer
6
+
7
+
8
+ class BaseImagePolicy(ModuleAttrMixin):
9
+ # init accepts keyword argument shape_meta, see config/task/*_image.yaml
10
+
11
+ def predict_action(self, obs_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
12
+ """
13
+ obs_dict:
14
+ str: B,To,*
15
+ return: B,Ta,Da
16
+ """
17
+ raise NotImplementedError()
18
+
19
+ # reset state for stateful policies
20
+ def reset(self):
21
+ pass
22
+
23
+ # ========== training ===========
24
+ # no standard training interface except setting normalizer
25
+ def set_normalizer(self, normalizer: LinearNormalizer):
26
+ raise NotImplementedError()
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/policy/diffusion_unet_image_policy.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from einops import rearrange, reduce
6
+ from diffusers.schedulers.scheduling_ddpm import DDPMScheduler
7
+
8
+ from diffusion_policy.model.common.normalizer import LinearNormalizer
9
+ from diffusion_policy.policy.base_image_policy import BaseImagePolicy
10
+ from diffusion_policy.model.diffusion.conditional_unet1d import ConditionalUnet1D
11
+ from diffusion_policy.model.diffusion.mask_generator import LowdimMaskGenerator
12
+ from diffusion_policy.model.vision.multi_image_obs_encoder import MultiImageObsEncoder
13
+ from diffusion_policy.common.pytorch_util import dict_apply
14
+
15
+
16
+ class DiffusionUnetImagePolicy(BaseImagePolicy):
17
+
18
+ def __init__(
19
+ self,
20
+ shape_meta: dict,
21
+ noise_scheduler: DDPMScheduler,
22
+ obs_encoder: MultiImageObsEncoder,
23
+ horizon,
24
+ n_action_steps,
25
+ n_obs_steps,
26
+ num_inference_steps=None,
27
+ obs_as_global_cond=True,
28
+ diffusion_step_embed_dim=256,
29
+ down_dims=(256, 512, 1024),
30
+ kernel_size=5,
31
+ n_groups=8,
32
+ cond_predict_scale=True,
33
+ # parameters passed to step
34
+ **kwargs,
35
+ ):
36
+ super().__init__()
37
+
38
+ # parse shapes
39
+ action_shape = shape_meta["action"]["shape"]
40
+ assert len(action_shape) == 1
41
+ action_dim = action_shape[0]
42
+ # get feature dim
43
+ obs_feature_dim = obs_encoder.output_shape()[0]
44
+
45
+ # create diffusion model
46
+ input_dim = action_dim + obs_feature_dim
47
+ global_cond_dim = None
48
+ if obs_as_global_cond:
49
+ input_dim = action_dim
50
+ global_cond_dim = obs_feature_dim * n_obs_steps
51
+
52
+ model = ConditionalUnet1D(
53
+ input_dim=input_dim,
54
+ local_cond_dim=None,
55
+ global_cond_dim=global_cond_dim,
56
+ diffusion_step_embed_dim=diffusion_step_embed_dim,
57
+ down_dims=down_dims,
58
+ kernel_size=kernel_size,
59
+ n_groups=n_groups,
60
+ cond_predict_scale=cond_predict_scale,
61
+ )
62
+
63
+ self.obs_encoder = obs_encoder
64
+ self.model = model
65
+ self.noise_scheduler = noise_scheduler
66
+ self.mask_generator = LowdimMaskGenerator(
67
+ action_dim=action_dim,
68
+ obs_dim=0 if obs_as_global_cond else obs_feature_dim,
69
+ max_n_obs_steps=n_obs_steps,
70
+ fix_obs_steps=True,
71
+ action_visible=False,
72
+ )
73
+ self.normalizer = LinearNormalizer()
74
+ self.horizon = horizon
75
+ self.obs_feature_dim = obs_feature_dim
76
+ self.action_dim = action_dim
77
+ self.n_action_steps = n_action_steps
78
+ self.n_obs_steps = n_obs_steps
79
+ self.obs_as_global_cond = obs_as_global_cond
80
+ self.kwargs = kwargs
81
+
82
+ if num_inference_steps is None:
83
+ num_inference_steps = noise_scheduler.config.num_train_timesteps
84
+ self.num_inference_steps = num_inference_steps
85
+
86
+ # ========= inference ============
87
+ def conditional_sample(
88
+ self,
89
+ condition_data,
90
+ condition_mask,
91
+ local_cond=None,
92
+ global_cond=None,
93
+ generator=None,
94
+ # keyword arguments to scheduler.step
95
+ **kwargs,
96
+ ):
97
+ model = self.model
98
+ scheduler = self.noise_scheduler
99
+
100
+ trajectory = torch.randn(
101
+ size=condition_data.shape,
102
+ dtype=condition_data.dtype,
103
+ device=condition_data.device,
104
+ generator=generator,
105
+ )
106
+
107
+ # set step values
108
+ scheduler.set_timesteps(self.num_inference_steps)
109
+
110
+ for t in scheduler.timesteps:
111
+ # 1. apply conditioning
112
+ trajectory[condition_mask] = condition_data[condition_mask]
113
+
114
+ # 2. predict model output
115
+ model_output = model(trajectory, t, local_cond=local_cond, global_cond=global_cond)
116
+
117
+ # 3. compute previous image: x_t -> x_t-1
118
+ trajectory = scheduler.step(model_output, t, trajectory, generator=generator, **kwargs).prev_sample
119
+
120
+ # finally make sure conditioning is enforced
121
+ trajectory[condition_mask] = condition_data[condition_mask]
122
+
123
+ return trajectory
124
+
125
+ def predict_action(self, obs_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
126
+ """
127
+ obs_dict: must include "obs" key
128
+ result: must include "action" key
129
+ """
130
+ assert "past_action" not in obs_dict # not implemented yet
131
+ # normalize input
132
+ nobs = self.normalizer.normalize(obs_dict)
133
+ value = next(iter(nobs.values()))
134
+ B, To = value.shape[:2]
135
+ T = self.horizon
136
+ Da = self.action_dim
137
+ Do = self.obs_feature_dim
138
+ To = self.n_obs_steps
139
+
140
+ # build input
141
+ device = self.device
142
+ dtype = self.dtype
143
+
144
+ # handle different ways of passing observation
145
+ local_cond = None
146
+ global_cond = None
147
+ if self.obs_as_global_cond:
148
+ # condition through global feature
149
+ this_nobs = dict_apply(nobs, lambda x: x[:, :To, ...].reshape(-1, *x.shape[2:]))
150
+ nobs_features = self.obs_encoder(this_nobs)
151
+ # reshape back to B, Do
152
+ global_cond = nobs_features.reshape(B, -1)
153
+ # empty data for action
154
+ cond_data = torch.zeros(size=(B, T, Da), device=device, dtype=dtype)
155
+ cond_mask = torch.zeros_like(cond_data, dtype=torch.bool)
156
+ else:
157
+ # condition through impainting
158
+ this_nobs = dict_apply(nobs, lambda x: x[:, :To, ...].reshape(-1, *x.shape[2:]))
159
+ nobs_features = self.obs_encoder(this_nobs)
160
+ # reshape back to B, T, Do
161
+ nobs_features = nobs_features.reshape(B, To, -1)
162
+ cond_data = torch.zeros(size=(B, T, Da + Do), device=device, dtype=dtype)
163
+ cond_mask = torch.zeros_like(cond_data, dtype=torch.bool)
164
+ cond_data[:, :To, Da:] = nobs_features
165
+ cond_mask[:, :To, Da:] = True
166
+
167
+ # run sampling
168
+ nsample = self.conditional_sample(
169
+ cond_data,
170
+ cond_mask,
171
+ local_cond=local_cond,
172
+ global_cond=global_cond,
173
+ **self.kwargs,
174
+ )
175
+
176
+ # unnormalize prediction
177
+ naction_pred = nsample[..., :Da]
178
+ action_pred = self.normalizer["action"].unnormalize(naction_pred)
179
+
180
+ # get action
181
+ start = To - 1
182
+ end = start + self.n_action_steps
183
+ action = action_pred[:, start:end]
184
+
185
+ result = {"action": action, "action_pred": action_pred}
186
+ return result
187
+
188
+ # ========= training ============
189
+ def set_normalizer(self, normalizer: LinearNormalizer):
190
+ self.normalizer.load_state_dict(normalizer.state_dict())
191
+
192
+ def compute_loss(self, batch):
193
+ # normalize input
194
+ assert "valid_mask" not in batch
195
+ nobs = self.normalizer.normalize(batch["obs"])
196
+ nactions = self.normalizer["action"].normalize(batch["action"])
197
+ batch_size = nactions.shape[0]
198
+ horizon = nactions.shape[1]
199
+
200
+ # handle different ways of passing observation
201
+ local_cond = None
202
+ global_cond = None
203
+ trajectory = nactions
204
+ cond_data = trajectory
205
+ if self.obs_as_global_cond:
206
+ # reshape B, T, ... to B*T
207
+ this_nobs = dict_apply(nobs, lambda x: x[:, :self.n_obs_steps, ...].reshape(-1, *x.shape[2:]))
208
+ nobs_features = self.obs_encoder(this_nobs)
209
+ # reshape back to B, Do
210
+ global_cond = nobs_features.reshape(batch_size, -1)
211
+ else:
212
+ # reshape B, T, ... to B*T
213
+ this_nobs = dict_apply(nobs, lambda x: x.reshape(-1, *x.shape[2:]))
214
+ nobs_features = self.obs_encoder(this_nobs)
215
+ # reshape back to B, T, Do
216
+ nobs_features = nobs_features.reshape(batch_size, horizon, -1)
217
+ cond_data = torch.cat([nactions, nobs_features], dim=-1)
218
+ trajectory = cond_data.detach()
219
+
220
+ # generate impainting mask
221
+ condition_mask = self.mask_generator(trajectory.shape)
222
+
223
+ # Sample noise that we'll add to the images
224
+ noise = torch.randn(trajectory.shape, device=trajectory.device)
225
+ bsz = trajectory.shape[0]
226
+ # Sample a random timestep for each image
227
+ timesteps = torch.randint(
228
+ 0,
229
+ self.noise_scheduler.config.num_train_timesteps,
230
+ (bsz, ),
231
+ device=trajectory.device,
232
+ ).long()
233
+ # Add noise to the clean images according to the noise magnitude at each timestep
234
+ # (this is the forward diffusion process)
235
+ noisy_trajectory = self.noise_scheduler.add_noise(trajectory, noise, timesteps)
236
+
237
+ # compute loss mask
238
+ loss_mask = ~condition_mask
239
+
240
+ # apply conditioning
241
+ noisy_trajectory[condition_mask] = cond_data[condition_mask]
242
+
243
+ # Predict the noise residual
244
+ pred = self.model(noisy_trajectory, timesteps, local_cond=local_cond, global_cond=global_cond)
245
+
246
+ pred_type = self.noise_scheduler.config.prediction_type
247
+ if pred_type == "epsilon":
248
+ target = noise
249
+ elif pred_type == "sample":
250
+ target = trajectory
251
+ else:
252
+ raise ValueError(f"Unsupported prediction type {pred_type}")
253
+
254
+ loss = F.mse_loss(pred, target, reduction="none")
255
+ loss = loss * loss_mask.type(loss.dtype)
256
+ loss = reduce(loss, "b ... -> b (...)", "mean")
257
+ loss = loss.mean()
258
+ return loss
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/shared_memory/shared_memory_queue.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Union
2
+ import numbers
3
+ from queue import Empty, Full
4
+ from multiprocessing.managers import SharedMemoryManager
5
+ import numpy as np
6
+ from diffusion_policy.shared_memory.shared_memory_util import (
7
+ ArraySpec,
8
+ SharedAtomicCounter,
9
+ )
10
+ from diffusion_policy.shared_memory.shared_ndarray import SharedNDArray
11
+
12
+
13
+ class SharedMemoryQueue:
14
+ """
15
+ A Lock-Free FIFO Shared Memory Data Structure.
16
+ Stores a sequence of dict of numpy arrays.
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ shm_manager: SharedMemoryManager,
22
+ array_specs: List[ArraySpec],
23
+ buffer_size: int,
24
+ ):
25
+
26
+ # create atomic counter
27
+ write_counter = SharedAtomicCounter(shm_manager)
28
+ read_counter = SharedAtomicCounter(shm_manager)
29
+
30
+ # allocate shared memory
31
+ shared_arrays = dict()
32
+ for spec in array_specs:
33
+ key = spec.name
34
+ assert key not in shared_arrays
35
+ array = SharedNDArray.create_from_shape(
36
+ mem_mgr=shm_manager,
37
+ shape=(buffer_size, ) + tuple(spec.shape),
38
+ dtype=spec.dtype,
39
+ )
40
+ shared_arrays[key] = array
41
+
42
+ self.buffer_size = buffer_size
43
+ self.array_specs = array_specs
44
+ self.write_counter = write_counter
45
+ self.read_counter = read_counter
46
+ self.shared_arrays = shared_arrays
47
+
48
+ @classmethod
49
+ def create_from_examples(
50
+ cls,
51
+ shm_manager: SharedMemoryManager,
52
+ examples: Dict[str, Union[np.ndarray, numbers.Number]],
53
+ buffer_size: int,
54
+ ):
55
+ specs = list()
56
+ for key, value in examples.items():
57
+ shape = None
58
+ dtype = None
59
+ if isinstance(value, np.ndarray):
60
+ shape = value.shape
61
+ dtype = value.dtype
62
+ assert dtype != np.dtype("O")
63
+ elif isinstance(value, numbers.Number):
64
+ shape = tuple()
65
+ dtype = np.dtype(type(value))
66
+ else:
67
+ raise TypeError(f"Unsupported type {type(value)}")
68
+
69
+ spec = ArraySpec(name=key, shape=shape, dtype=dtype)
70
+ specs.append(spec)
71
+
72
+ obj = cls(shm_manager=shm_manager, array_specs=specs, buffer_size=buffer_size)
73
+ return obj
74
+
75
+ def qsize(self):
76
+ read_count = self.read_counter.load()
77
+ write_count = self.write_counter.load()
78
+ n_data = write_count - read_count
79
+ return n_data
80
+
81
+ def empty(self):
82
+ n_data = self.qsize()
83
+ return n_data <= 0
84
+
85
+ def clear(self):
86
+ self.read_counter.store(self.write_counter.load())
87
+
88
+ def put(self, data: Dict[str, Union[np.ndarray, numbers.Number]]):
89
+ read_count = self.read_counter.load()
90
+ write_count = self.write_counter.load()
91
+ n_data = write_count - read_count
92
+ if n_data >= self.buffer_size:
93
+ raise Full()
94
+
95
+ next_idx = write_count % self.buffer_size
96
+
97
+ # write to shared memory
98
+ for key, value in data.items():
99
+ arr: np.ndarray
100
+ arr = self.shared_arrays[key].get()
101
+ if isinstance(value, np.ndarray):
102
+ arr[next_idx] = value
103
+ else:
104
+ arr[next_idx] = np.array(value, dtype=arr.dtype)
105
+
106
+ # update idx
107
+ self.write_counter.add(1)
108
+
109
+ def get(self, out=None) -> Dict[str, np.ndarray]:
110
+ write_count = self.write_counter.load()
111
+ read_count = self.read_counter.load()
112
+ n_data = write_count - read_count
113
+ if n_data <= 0:
114
+ raise Empty()
115
+
116
+ if out is None:
117
+ out = self._allocate_empty()
118
+
119
+ next_idx = read_count % self.buffer_size
120
+ for key, value in self.shared_arrays.items():
121
+ arr = value.get()
122
+ np.copyto(out[key], arr[next_idx])
123
+
124
+ # update idx
125
+ self.read_counter.add(1)
126
+ return out
127
+
128
+ def get_k(self, k, out=None) -> Dict[str, np.ndarray]:
129
+ write_count = self.write_counter.load()
130
+ read_count = self.read_counter.load()
131
+ n_data = write_count - read_count
132
+ if n_data <= 0:
133
+ raise Empty()
134
+ assert k <= n_data
135
+
136
+ out = self._get_k_impl(k, read_count, out=out)
137
+ self.read_counter.add(k)
138
+ return out
139
+
140
+ def get_all(self, out=None) -> Dict[str, np.ndarray]:
141
+ write_count = self.write_counter.load()
142
+ read_count = self.read_counter.load()
143
+ n_data = write_count - read_count
144
+ if n_data <= 0:
145
+ raise Empty()
146
+
147
+ out = self._get_k_impl(n_data, read_count, out=out)
148
+ self.read_counter.add(n_data)
149
+ return out
150
+
151
+ def _get_k_impl(self, k, read_count, out=None) -> Dict[str, np.ndarray]:
152
+ if out is None:
153
+ out = self._allocate_empty(k)
154
+
155
+ curr_idx = read_count % self.buffer_size
156
+ for key, value in self.shared_arrays.items():
157
+ arr = value.get()
158
+ target = out[key]
159
+
160
+ start = curr_idx
161
+ end = min(start + k, self.buffer_size)
162
+ target_start = 0
163
+ target_end = end - start
164
+ target[target_start:target_end] = arr[start:end]
165
+
166
+ remainder = k - (end - start)
167
+ if remainder > 0:
168
+ # wrap around
169
+ start = 0
170
+ end = start + remainder
171
+ target_start = target_end
172
+ target_end = k
173
+ target[target_start:target_end] = arr[start:end]
174
+
175
+ return out
176
+
177
+ def _allocate_empty(self, k=None):
178
+ result = dict()
179
+ for spec in self.array_specs:
180
+ shape = spec.shape
181
+ if k is not None:
182
+ shape = (k, ) + shape
183
+ result[spec.name] = np.empty(shape=shape, dtype=spec.dtype)
184
+ return result
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/shared_memory/shared_memory_ring_buffer.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Union
2
+
3
+ from queue import Empty
4
+ import numbers
5
+ import time
6
+ from multiprocessing.managers import SharedMemoryManager
7
+ import numpy as np
8
+
9
+ from diffusion_policy.shared_memory.shared_ndarray import SharedNDArray
10
+ from diffusion_policy.shared_memory.shared_memory_util import (
11
+ ArraySpec,
12
+ SharedAtomicCounter,
13
+ )
14
+
15
+
16
+ class SharedMemoryRingBuffer:
17
+ """
18
+ A Lock-Free FILO Shared Memory Data Structure.
19
+ Stores a sequence of dict of numpy arrays.
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ shm_manager: SharedMemoryManager,
25
+ array_specs: List[ArraySpec],
26
+ get_max_k: int,
27
+ get_time_budget: float,
28
+ put_desired_frequency: float,
29
+ safety_margin: float = 1.5,
30
+ ):
31
+ """
32
+ shm_manager: Manages the life cycle of share memories
33
+ across processes. Remember to run .start() before passing.
34
+ array_specs: Name, shape and type of arrays for a single time step.
35
+ get_max_k: The maxmum number of items can be queried at once.
36
+ get_time_budget: The maxmum amount of time spent copying data from
37
+ shared memory to local memory. Increase this number for larger arrays.
38
+ put_desired_frequency: The maximum frequency that .put() can be called.
39
+ This influces the buffer size.
40
+ """
41
+
42
+ # create atomic counter
43
+ counter = SharedAtomicCounter(shm_manager)
44
+
45
+ # compute buffer size
46
+ # At any given moment, the past get_max_k items should never
47
+ # be touched (to be read freely). Assuming the reading is reading
48
+ # these k items, which takes maximum of get_time_budget seconds,
49
+ # we need enough empty slots to make sure put_desired_frequency Hz
50
+ # of put can be sustaied.
51
+ buffer_size = (int(np.ceil(put_desired_frequency * get_time_budget * safety_margin)) + get_max_k)
52
+
53
+ # allocate shared memory
54
+ shared_arrays = dict()
55
+ for spec in array_specs:
56
+ key = spec.name
57
+ assert key not in shared_arrays
58
+ array = SharedNDArray.create_from_shape(
59
+ mem_mgr=shm_manager,
60
+ shape=(buffer_size, ) + tuple(spec.shape),
61
+ dtype=spec.dtype,
62
+ )
63
+ shared_arrays[key] = array
64
+
65
+ # allocate timestamp array
66
+ timestamp_array = SharedNDArray.create_from_shape(mem_mgr=shm_manager, shape=(buffer_size, ), dtype=np.float64)
67
+ timestamp_array.get()[:] = -np.inf
68
+
69
+ self.buffer_size = buffer_size
70
+ self.array_specs = array_specs
71
+ self.counter = counter
72
+ self.shared_arrays = shared_arrays
73
+ self.timestamp_array = timestamp_array
74
+ self.get_time_budget = get_time_budget
75
+ self.get_max_k = get_max_k
76
+ self.put_desired_frequency = put_desired_frequency
77
+
78
+ @property
79
+ def count(self):
80
+ return self.counter.load()
81
+
82
+ @classmethod
83
+ def create_from_examples(
84
+ cls,
85
+ shm_manager: SharedMemoryManager,
86
+ examples: Dict[str, Union[np.ndarray, numbers.Number]],
87
+ get_max_k: int = 32,
88
+ get_time_budget: float = 0.01,
89
+ put_desired_frequency: float = 60,
90
+ ):
91
+ specs = list()
92
+ for key, value in examples.items():
93
+ shape = None
94
+ dtype = None
95
+ if isinstance(value, np.ndarray):
96
+ shape = value.shape
97
+ dtype = value.dtype
98
+ assert dtype != np.dtype("O")
99
+ elif isinstance(value, numbers.Number):
100
+ shape = tuple()
101
+ dtype = np.dtype(type(value))
102
+ else:
103
+ raise TypeError(f"Unsupported type {type(value)}")
104
+
105
+ spec = ArraySpec(name=key, shape=shape, dtype=dtype)
106
+ specs.append(spec)
107
+
108
+ obj = cls(
109
+ shm_manager=shm_manager,
110
+ array_specs=specs,
111
+ get_max_k=get_max_k,
112
+ get_time_budget=get_time_budget,
113
+ put_desired_frequency=put_desired_frequency,
114
+ )
115
+ return obj
116
+
117
+ def clear(self):
118
+ self.counter.store(0)
119
+
120
+ def put(self, data: Dict[str, Union[np.ndarray, numbers.Number]], wait: bool = True):
121
+ count = self.counter.load()
122
+ next_idx = count % self.buffer_size
123
+ # Make sure the next self.get_max_k elements in the ring buffer have at least
124
+ # self.get_time_budget seconds untouched after written, so that
125
+ # get_last_k can safely read k elements from any count location.
126
+ # Sanity check: when get_max_k == 1, the element pointed by next_idx
127
+ # should be rewritten at minimum self.get_time_budget seconds later.
128
+ timestamp_lookahead_idx = (next_idx + self.get_max_k - 1) % self.buffer_size
129
+ old_timestamp = self.timestamp_array.get()[timestamp_lookahead_idx]
130
+ t = time.monotonic()
131
+ if (t - old_timestamp) < self.get_time_budget:
132
+ deltat = t - old_timestamp
133
+ if wait:
134
+ # sleep the remaining time to be safe
135
+ time.sleep(self.get_time_budget - deltat)
136
+ else:
137
+ # throw an error
138
+ past_iters = self.buffer_size - self.get_max_k
139
+ hz = past_iters / deltat
140
+ raise TimeoutError("Put executed too fast {}items/{:.4f}s ~= {}Hz".format(past_iters, deltat, hz))
141
+
142
+ # write to shared memory
143
+ for key, value in data.items():
144
+ arr: np.ndarray
145
+ arr = self.shared_arrays[key].get()
146
+ if isinstance(value, np.ndarray):
147
+ arr[next_idx] = value
148
+ else:
149
+ arr[next_idx] = np.array(value, dtype=arr.dtype)
150
+
151
+ # update timestamp
152
+ self.timestamp_array.get()[next_idx] = time.monotonic()
153
+ self.counter.add(1)
154
+
155
+ def _allocate_empty(self, k=None):
156
+ result = dict()
157
+ for spec in self.array_specs:
158
+ shape = spec.shape
159
+ if k is not None:
160
+ shape = (k, ) + shape
161
+ result[spec.name] = np.empty(shape=shape, dtype=spec.dtype)
162
+ return result
163
+
164
+ def get(self, out=None) -> Dict[str, np.ndarray]:
165
+ if out is None:
166
+ out = self._allocate_empty()
167
+ start_time = time.monotonic()
168
+ count = self.counter.load()
169
+ curr_idx = (count - 1) % self.buffer_size
170
+ for key, value in self.shared_arrays.items():
171
+ arr = value.get()
172
+ np.copyto(out[key], arr[curr_idx])
173
+ end_time = time.monotonic()
174
+ dt = end_time - start_time
175
+ if dt > self.get_time_budget:
176
+ raise TimeoutError(f"Get time out {dt} vs {self.get_time_budget}")
177
+ return out
178
+
179
+ def get_last_k(self, k: int, out=None) -> Dict[str, np.ndarray]:
180
+ assert k <= self.get_max_k
181
+ if out is None:
182
+ out = self._allocate_empty(k)
183
+ start_time = time.monotonic()
184
+ count = self.counter.load()
185
+ assert k <= count
186
+ curr_idx = (count - 1) % self.buffer_size
187
+ for key, value in self.shared_arrays.items():
188
+ arr = value.get()
189
+ target = out[key]
190
+
191
+ end = curr_idx + 1
192
+ start = max(0, end - k)
193
+ target_end = k
194
+ target_start = target_end - (end - start)
195
+ target[target_start:target_end] = arr[start:end]
196
+
197
+ remainder = k - (end - start)
198
+ if remainder > 0:
199
+ # wrap around
200
+ end = self.buffer_size
201
+ start = end - remainder
202
+ target_start = 0
203
+ target_end = end - start
204
+ target[target_start:target_end] = arr[start:end]
205
+ end_time = time.monotonic()
206
+ dt = end_time - start_time
207
+ if dt > self.get_time_budget:
208
+ raise TimeoutError(f"Get time out {dt} vs {self.get_time_budget}")
209
+ return out
210
+
211
+ def get_all(self) -> Dict[str, np.ndarray]:
212
+ k = min(self.count, self.get_max_k)
213
+ return self.get_last_k(k=k)
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/shared_memory/shared_memory_util.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple
2
+ from dataclasses import dataclass
3
+ import numpy as np
4
+ from multiprocessing.managers import SharedMemoryManager
5
+ from atomics import atomicview, MemoryOrder, UINT
6
+
7
+
8
+ @dataclass
9
+ class ArraySpec:
10
+ name: str
11
+ shape: Tuple[int]
12
+ dtype: np.dtype
13
+
14
+
15
+ class SharedAtomicCounter:
16
+
17
+ def __init__(self, shm_manager: SharedMemoryManager, size: int = 8): # 64bit int
18
+ shm = shm_manager.SharedMemory(size=size)
19
+ self.shm = shm
20
+ self.size = size
21
+ self.store(0) # initialize
22
+
23
+ @property
24
+ def buf(self):
25
+ return self.shm.buf[:self.size]
26
+
27
+ def load(self) -> int:
28
+ with atomicview(buffer=self.buf, atype=UINT) as a:
29
+ value = a.load(order=MemoryOrder.ACQUIRE)
30
+ return value
31
+
32
+ def store(self, value: int):
33
+ with atomicview(buffer=self.buf, atype=UINT) as a:
34
+ a.store(value, order=MemoryOrder.RELEASE)
35
+
36
+ def add(self, value: int):
37
+ with atomicview(buffer=self.buf, atype=UINT) as a:
38
+ a.add(value, order=MemoryOrder.ACQ_REL)
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/shared_memory/shared_ndarray.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import multiprocessing
4
+ import multiprocessing.synchronize
5
+ from multiprocessing.managers import SharedMemoryManager
6
+ from multiprocessing.shared_memory import SharedMemory
7
+ from typing import Any, TYPE_CHECKING, Generic, Optional, Tuple, TypeVar, Union
8
+
9
+ import numpy as np
10
+ import numpy.typing as npt
11
+ from diffusion_policy.common.nested_dict_util import nested_dict_check, nested_dict_map
12
+
13
+ SharedMemoryLike = Union[str, SharedMemory] # shared memory or name of shared memory
14
+ SharedT = TypeVar("SharedT", bound=np.generic)
15
+
16
+
17
+ class SharedNDArray(Generic[SharedT]):
18
+ """Class to keep track of and retrieve the data in a shared array
19
+ Attributes
20
+ ----------
21
+ shm
22
+ SharedMemory object containing the data of the array
23
+ shape
24
+ Shape of the NumPy array
25
+ dtype
26
+ Type of the NumPy array. Anything that may be passed to the `dtype=` argument in `np.ndarray`.
27
+ lock
28
+ (Optional) multiprocessing.Lock to manage access to the SharedNDArray. This is only created if
29
+ lock=True is passed to the constructor, otherwise it is set to `None`.
30
+ A SharedNDArray object may be created either directly with a preallocated shared memory object plus the
31
+ dtype and shape of the numpy array it represents:
32
+ >>> from multiprocessing.shared_memory import SharedMemory
33
+ >>> import numpy as np
34
+ >>> from shared_ndarray2 import SharedNDArray
35
+ >>> x = np.array([1, 2, 3])
36
+ >>> shm = SharedMemory(name="x", create=True, size=x.nbytes)
37
+ >>> arr = SharedNDArray(shm, x.shape, x.dtype)
38
+ >>> arr[:] = x[:] # copy x into the array
39
+ >>> print(arr[:])
40
+ [1 2 3]
41
+ >>> shm.close()
42
+ >>> shm.unlink()
43
+ Or using a SharedMemoryManager either from an existing array or from arbitrary shape and nbytes:
44
+ >>> from multiprocessing.managers import SharedMemoryManager
45
+ >>> mem_mgr = SharedMemoryManager()
46
+ >>> mem_mgr.start() # Better yet, use SharedMemoryManager context manager
47
+ >>> arr = SharedNDArray.from_shape(mem_mgr, x.shape, x.dtype)
48
+ >>> arr[:] = x[:] # copy x into the array
49
+ >>> print(arr[:])
50
+ [1 2 3]
51
+ >>> # -or in one step-
52
+ >>> arr = SharedNDArray.from_array(mem_mgr, x)
53
+ >>> print(arr[:])
54
+ [1 2 3]
55
+ `SharedNDArray` does not subclass numpy.ndarray but rather generates an ndarray on-the-fly in get(),
56
+ which is used in __getitem__ and __setitem__. Thus to access the data and/or use any ndarray methods
57
+ get() or __getitem__ or __setitem__ must be used
58
+ >>> arr.max() # ERROR: SharedNDArray has no `max` method.
59
+ Traceback (most recent call last):
60
+ ....
61
+ AttributeError: SharedNDArray object has no attribute 'max'. To access NumPy ndarray object use .get() method.
62
+ >>> arr.get().max() # (or arr[:].max()) OK: This gets an ndarray on which we can operate
63
+ 3
64
+ >>> y = np.zeros(3)
65
+ >>> y[:] = arr # ERROR: Cannot broadcast-assign a SharedNDArray to ndarray `y`
66
+ Traceback (most recent call last):
67
+ ...
68
+ ValueError: setting an array element with a sequence.
69
+ >>> y[:] = arr[:] # OK: This gets an ndarray that can be copied element-wise to `y`
70
+ >>> mem_mgr.shutdown()
71
+ """
72
+
73
+ shm: SharedMemory
74
+ # shape: Tuple[int, ...] # is a property
75
+ dtype: np.dtype
76
+ lock: Optional[multiprocessing.synchronize.Lock]
77
+
78
+ def __init__(self, shm: SharedMemoryLike, shape: Tuple[int, ...], dtype: npt.DTypeLike):
79
+ """Initialize a SharedNDArray object from existing shared memory, object shape, and dtype.
80
+ To initialize a SharedNDArray object from a memory manager and data or shape, use the `from_array()
81
+ or `from_shape()` classmethods.
82
+ Parameters
83
+ ----------
84
+ shm
85
+ `multiprocessing.shared_memory.SharedMemory` object or name for connecting to an existing block
86
+ of shared memory (using SharedMemory constructor)
87
+ shape
88
+ Shape of the NumPy array to be represented in the shared memory
89
+ dtype
90
+ Data type for the NumPy array to be represented in shared memory. Any valid argument for
91
+ `np.dtype` may be used as it will be converted to an actual `dtype` object.
92
+ lock : bool, optional
93
+ If True, create a multiprocessing.Lock object accessible with the `.lock` attribute, by default
94
+ False. If passing the `SharedNDArray` as an argument to a `multiprocessing.Pool` function this
95
+ should not be used -- see this comment to a Stack Overflow question about `multiprocessing.Lock`:
96
+ https://stackoverflow.com/questions/25557686/python-sharing-a-lock-between-processes#comment72803059_25558333
97
+ Raises
98
+ ------
99
+ ValueError
100
+ The SharedMemory size (number of bytes) does not match the product of the shape and dtype
101
+ itemsize.
102
+ """
103
+ if isinstance(shm, str):
104
+ shm = SharedMemory(name=shm, create=False)
105
+ dtype = np.dtype(dtype) # Try to convert to dtype
106
+ assert shm.size >= (dtype.itemsize * np.prod(shape))
107
+ self.shm = shm
108
+ self.dtype = dtype
109
+ self._shape: Tuple[int, ...] = shape
110
+
111
+ def __repr__(self):
112
+ # Like numpy's ndarray repr
113
+ cls_name = self.__class__.__name__
114
+ nspaces = len(cls_name) + 1
115
+ array_repr = str(self.get())
116
+ array_repr = array_repr.replace("\n", "\n" + " " * nspaces)
117
+ return f"{cls_name}({array_repr}, dtype={self.dtype})"
118
+
119
+ @classmethod
120
+ def create_from_array(cls, mem_mgr: SharedMemoryManager, arr: npt.NDArray[SharedT]) -> SharedNDArray[SharedT]:
121
+ """Create a SharedNDArray from a SharedMemoryManager and an existing numpy array.
122
+ Parameters
123
+ ----------
124
+ mem_mgr
125
+ Running `multiprocessing.managers.SharedMemoryManager` instance from which to create the
126
+ SharedMemory for the SharedNDArray
127
+ arr
128
+ NumPy `ndarray` object to copy into the created SharedNDArray upon initialization.
129
+ """
130
+ # Simply use from_shape() to create the SharedNDArray and copy the data into it.
131
+ shared_arr = cls.create_from_shape(mem_mgr, arr.shape, arr.dtype)
132
+ shared_arr.get()[:] = arr[:]
133
+ return shared_arr
134
+
135
+ @classmethod
136
+ def create_from_shape(cls, mem_mgr: SharedMemoryManager, shape: Tuple, dtype: npt.DTypeLike) -> SharedNDArray:
137
+ """Create a SharedNDArray directly from a SharedMemoryManager
138
+ Parameters
139
+ ----------
140
+ mem_mgr
141
+ SharedMemoryManager instance that has been started
142
+ shape
143
+ Shape of the array
144
+ dtype
145
+ Data type for the NumPy array to be represented in shared memory. Any valid argument for
146
+ `np.dtype` may be used as it will be converted to an actual `dtype` object.
147
+ """
148
+ dtype = np.dtype(dtype) # Convert to dtype if possible
149
+ shm = mem_mgr.SharedMemory(np.prod(shape) * dtype.itemsize)
150
+ return cls(shm=shm, shape=shape, dtype=dtype)
151
+
152
+ @property
153
+ def shape(self) -> Tuple[int, ...]:
154
+ return self._shape
155
+
156
+ def get(self) -> npt.NDArray[SharedT]:
157
+ """Get a numpy array with access to the shared memory"""
158
+ return np.ndarray(self.shape, dtype=self.dtype, buffer=self.shm.buf)
159
+
160
+ def __del__(self):
161
+ self.shm.close()
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/workspace/base_workspace.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ import os
3
+ import pathlib
4
+ import hydra
5
+ import copy
6
+ from hydra.core.hydra_config import HydraConfig
7
+ from omegaconf import OmegaConf
8
+ import dill
9
+ import torch
10
+ import threading
11
+
12
+
13
+ class BaseWorkspace:
14
+ include_keys = tuple()
15
+ exclude_keys = tuple()
16
+
17
+ def __init__(self, cfg: OmegaConf, output_dir: Optional[str] = None):
18
+ self.cfg = cfg
19
+ self._output_dir = output_dir
20
+ self._saving_thread = None
21
+
22
+ @property
23
+ def output_dir(self):
24
+ output_dir = self._output_dir
25
+ if output_dir is None:
26
+ output_dir = HydraConfig.get().runtime.output_dir
27
+ return output_dir
28
+
29
+ def run(self):
30
+ """
31
+ Create any resource shouldn't be serialized as local variables
32
+ """
33
+ pass
34
+
35
+ def save_checkpoint(
36
+ self,
37
+ path=None,
38
+ tag="latest",
39
+ exclude_keys=None,
40
+ include_keys=None,
41
+ use_thread=True,
42
+ ):
43
+ if path is None:
44
+ path = pathlib.Path(self.output_dir).joinpath("checkpoints", f"{tag}.ckpt")
45
+ else:
46
+ path = pathlib.Path(path)
47
+ if exclude_keys is None:
48
+ exclude_keys = tuple(self.exclude_keys)
49
+ if include_keys is None:
50
+ include_keys = tuple(self.include_keys) + ("_output_dir", )
51
+
52
+ path.parent.mkdir(parents=True, exist_ok=True)
53
+ payload = {"cfg": self.cfg, "state_dicts": dict(), "pickles": dict()}
54
+
55
+ for key, value in self.__dict__.items():
56
+ if hasattr(value, "state_dict") and hasattr(value, "load_state_dict"):
57
+ # modules, optimizers and samplers etc
58
+ if key not in exclude_keys:
59
+ if use_thread:
60
+ payload["state_dicts"][key] = _copy_to_cpu(value.state_dict())
61
+ else:
62
+ payload["state_dicts"][key] = value.state_dict()
63
+ elif key in include_keys:
64
+ payload["pickles"][key] = dill.dumps(value)
65
+ if use_thread:
66
+ self._saving_thread = threading.Thread(
67
+ target=lambda: torch.save(payload, path.open("wb"), pickle_module=dill))
68
+ self._saving_thread.start()
69
+ else:
70
+ torch.save(payload, path.open("wb"), pickle_module=dill)
71
+ return str(path.absolute())
72
+
73
+ def get_checkpoint_path(self, tag="latest"):
74
+ return pathlib.Path(self.output_dir).joinpath("checkpoints", f"{tag}.ckpt")
75
+
76
+ def load_payload(self, payload, exclude_keys=None, include_keys=None, **kwargs):
77
+ if exclude_keys is None:
78
+ exclude_keys = tuple()
79
+ if include_keys is None:
80
+ include_keys = payload["pickles"].keys()
81
+
82
+ for key, value in payload["state_dicts"].items():
83
+ if key not in exclude_keys:
84
+ self.__dict__[key].load_state_dict(value, **kwargs)
85
+ for key in include_keys:
86
+ if key in payload["pickles"]:
87
+ self.__dict__[key] = dill.loads(payload["pickles"][key])
88
+
89
+ def load_checkpoint(self, path=None, tag="latest", exclude_keys=None, include_keys=None, **kwargs):
90
+ if path is None:
91
+ path = self.get_checkpoint_path(tag=tag)
92
+ else:
93
+ path = pathlib.Path(path)
94
+ payload = torch.load(path.open("rb"), pickle_module=dill, **kwargs)
95
+ self.load_payload(payload, exclude_keys=exclude_keys, include_keys=include_keys)
96
+ return payload
97
+
98
+ @classmethod
99
+ def create_from_checkpoint(cls, path, exclude_keys=None, include_keys=None, **kwargs):
100
+ payload = torch.load(open(path, "rb"), pickle_module=dill)
101
+ instance = cls(payload["cfg"])
102
+ instance.load_payload(
103
+ payload=payload,
104
+ exclude_keys=exclude_keys,
105
+ include_keys=include_keys,
106
+ **kwargs,
107
+ )
108
+ return instance
109
+
110
+ def save_snapshot(self, tag="latest"):
111
+ """
112
+ Quick loading and saving for reserach, saves full state of the workspace.
113
+
114
+ However, loading a snapshot assumes the code stays exactly the same.
115
+ Use save_checkpoint for long-term storage.
116
+ """
117
+ path = pathlib.Path(self.output_dir).joinpath("snapshots", f"{tag}.pkl")
118
+ path.parent.mkdir(parents=False, exist_ok=True)
119
+ torch.save(self, path.open("wb"), pickle_module=dill)
120
+ return str(path.absolute())
121
+
122
+ @classmethod
123
+ def create_from_snapshot(cls, path):
124
+ return torch.load(open(path, "rb"), pickle_module=dill)
125
+
126
+
127
+ def _copy_to_cpu(x):
128
+ if isinstance(x, torch.Tensor):
129
+ return x.detach().to("cpu")
130
+ elif isinstance(x, dict):
131
+ result = dict()
132
+ for k, v in x.items():
133
+ result[k] = _copy_to_cpu(v)
134
+ return result
135
+ elif isinstance(x, list):
136
+ return [_copy_to_cpu(k) for k in x]
137
+ else:
138
+ return copy.deepcopy(x)
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/workspace/robotworkspace.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ if __name__ == "__main__":
2
+ import sys
3
+ import os
4
+ import pathlib
5
+
6
+ ROOT_DIR = str(pathlib.Path(__file__).parent.parent.parent)
7
+ sys.path.append(ROOT_DIR)
8
+ os.chdir(ROOT_DIR)
9
+
10
+ import os
11
+ import hydra
12
+ import torch
13
+ from omegaconf import OmegaConf
14
+ import pathlib
15
+ from torch.utils.data import DataLoader
16
+ import copy
17
+
18
+ import tqdm, random
19
+ import numpy as np
20
+ from diffusion_policy.workspace.base_workspace import BaseWorkspace
21
+ from diffusion_policy.policy.diffusion_unet_image_policy import DiffusionUnetImagePolicy
22
+ from diffusion_policy.dataset.base_dataset import BaseImageDataset
23
+ from diffusion_policy.common.checkpoint_util import TopKCheckpointManager
24
+ from diffusion_policy.common.json_logger import JsonLogger
25
+ from diffusion_policy.common.pytorch_util import dict_apply, optimizer_to
26
+ from diffusion_policy.model.diffusion.ema_model import EMAModel
27
+ from diffusion_policy.model.common.lr_scheduler import get_scheduler
28
+
29
+ OmegaConf.register_new_resolver("eval", eval, replace=True)
30
+
31
+
32
+ class RobotWorkspace(BaseWorkspace):
33
+ include_keys = ["global_step", "epoch"]
34
+
35
+ def __init__(self, cfg: OmegaConf, output_dir=None):
36
+ super().__init__(cfg, output_dir=output_dir)
37
+
38
+ # set seed
39
+ seed = cfg.training.seed
40
+ torch.manual_seed(seed)
41
+ np.random.seed(seed)
42
+ random.seed(seed)
43
+
44
+ # configure model
45
+ self.model: DiffusionUnetImagePolicy = hydra.utils.instantiate(cfg.policy)
46
+
47
+ self.ema_model: DiffusionUnetImagePolicy = None
48
+ if cfg.training.use_ema:
49
+ self.ema_model = copy.deepcopy(self.model)
50
+
51
+ # configure training state
52
+ self.optimizer = hydra.utils.instantiate(cfg.optimizer, params=self.model.parameters())
53
+
54
+ # configure training state
55
+ self.global_step = 0
56
+ self.epoch = 0
57
+
58
+ def run(self):
59
+ cfg = copy.deepcopy(self.cfg)
60
+ seed = cfg.training.seed
61
+
62
+ # resume training
63
+ if cfg.training.resume:
64
+ lastest_ckpt_path = self.get_checkpoint_path()
65
+ if lastest_ckpt_path.is_file():
66
+ print(f"Resuming from checkpoint {lastest_ckpt_path}")
67
+ self.load_checkpoint(path=lastest_ckpt_path)
68
+
69
+ # configure dataset
70
+ dataset: BaseImageDataset
71
+ dataset = hydra.utils.instantiate(cfg.task.dataset)
72
+ assert isinstance(dataset, BaseImageDataset)
73
+ train_dataloader = create_dataloader(dataset, **cfg.dataloader)
74
+ normalizer = dataset.get_normalizer()
75
+
76
+ # configure validation dataset
77
+ val_dataset = dataset.get_validation_dataset()
78
+ val_dataloader = create_dataloader(val_dataset, **cfg.val_dataloader)
79
+
80
+ self.model.set_normalizer(normalizer)
81
+ if cfg.training.use_ema:
82
+ self.ema_model.set_normalizer(normalizer)
83
+
84
+ # configure lr scheduler
85
+ lr_scheduler = get_scheduler(
86
+ cfg.training.lr_scheduler,
87
+ optimizer=self.optimizer,
88
+ num_warmup_steps=cfg.training.lr_warmup_steps,
89
+ num_training_steps=(len(train_dataloader) * cfg.training.num_epochs) //
90
+ cfg.training.gradient_accumulate_every,
91
+ # pytorch assumes stepping LRScheduler every epoch
92
+ # however huggingface diffusers steps it every batch
93
+ last_epoch=self.global_step - 1,
94
+ )
95
+
96
+ # configure ema
97
+ ema: EMAModel = None
98
+ if cfg.training.use_ema:
99
+ ema = hydra.utils.instantiate(cfg.ema, model=self.ema_model)
100
+
101
+ # configure env
102
+ # env_runner: BaseImageRunner
103
+ # env_runner = hydra.utils.instantiate(
104
+ # cfg.task.env_runner,
105
+ # output_dir=self.output_dir)
106
+ # assert isinstance(env_runner, BaseImageRunner)
107
+ env_runner = None
108
+
109
+ # configure logging
110
+ # wandb_run = wandb.init(
111
+ # dir=str(self.output_dir),
112
+ # config=OmegaConf.to_container(cfg, resolve=True),
113
+ # **cfg.logging
114
+ # )
115
+ # wandb.config.update(
116
+ # {
117
+ # "output_dir": self.output_dir,
118
+ # }
119
+ # )
120
+
121
+ # configure checkpoint
122
+ topk_manager = TopKCheckpointManager(save_dir=os.path.join(self.output_dir, "checkpoints"),
123
+ **cfg.checkpoint.topk)
124
+
125
+ # device transfer
126
+ device = torch.device(cfg.training.device)
127
+ self.model.to(device)
128
+ if self.ema_model is not None:
129
+ self.ema_model.to(device)
130
+ optimizer_to(self.optimizer, device)
131
+
132
+ # save batch for sampling
133
+ train_sampling_batch = None
134
+
135
+ if cfg.training.debug:
136
+ cfg.training.num_epochs = 2
137
+ cfg.training.max_train_steps = 3
138
+ cfg.training.max_val_steps = 3
139
+ cfg.training.rollout_every = 1
140
+ cfg.training.checkpoint_every = 1
141
+ cfg.training.val_every = 1
142
+ cfg.training.sample_every = 1
143
+
144
+ # training loop
145
+ log_path = os.path.join(self.output_dir, "logs.json.txt")
146
+
147
+ with JsonLogger(log_path) as json_logger:
148
+ for local_epoch_idx in range(cfg.training.num_epochs):
149
+ step_log = dict()
150
+ # ========= train for this epoch ==========
151
+ if cfg.training.freeze_encoder:
152
+ self.model.obs_encoder.eval()
153
+ self.model.obs_encoder.requires_grad_(False)
154
+
155
+ train_losses = list()
156
+ with tqdm.tqdm(
157
+ train_dataloader,
158
+ desc=f"Training epoch {self.epoch}",
159
+ leave=False,
160
+ mininterval=cfg.training.tqdm_interval_sec,
161
+ ) as tepoch:
162
+ for batch_idx, batch in enumerate(tepoch):
163
+ batch = dataset.postprocess(batch, device)
164
+ if train_sampling_batch is None:
165
+ train_sampling_batch = batch
166
+ # compute loss
167
+ raw_loss = self.model.compute_loss(batch)
168
+ loss = raw_loss / cfg.training.gradient_accumulate_every
169
+ loss.backward()
170
+
171
+ # step optimizer
172
+ if (self.global_step % cfg.training.gradient_accumulate_every == 0):
173
+ self.optimizer.step()
174
+ self.optimizer.zero_grad()
175
+ lr_scheduler.step()
176
+
177
+ # update ema
178
+ if cfg.training.use_ema:
179
+ ema.step(self.model)
180
+
181
+ # logging
182
+ raw_loss_cpu = raw_loss.item()
183
+ tepoch.set_postfix(loss=raw_loss_cpu, refresh=False)
184
+ train_losses.append(raw_loss_cpu)
185
+ step_log = {
186
+ "train_loss": raw_loss_cpu,
187
+ "global_step": self.global_step,
188
+ "epoch": self.epoch,
189
+ "lr": lr_scheduler.get_last_lr()[0],
190
+ }
191
+
192
+ is_last_batch = batch_idx == (len(train_dataloader) - 1)
193
+ if not is_last_batch:
194
+ # log of last step is combined with validation and rollout
195
+ json_logger.log(step_log)
196
+ self.global_step += 1
197
+
198
+ if (cfg.training.max_train_steps
199
+ is not None) and batch_idx >= (cfg.training.max_train_steps - 1):
200
+ break
201
+
202
+ # at the end of each epoch
203
+ # replace train_loss with epoch average
204
+ train_loss = np.mean(train_losses)
205
+ step_log["train_loss"] = train_loss
206
+
207
+ # ========= eval for this epoch ==========
208
+ policy = self.model
209
+ if cfg.training.use_ema:
210
+ policy = self.ema_model
211
+ policy.eval()
212
+
213
+ # run rollout
214
+ # if (self.epoch % cfg.training.rollout_every) == 0:
215
+ # runner_log = env_runner.run(policy)
216
+ # # log all
217
+ # step_log.update(runner_log)
218
+
219
+ # run validation
220
+ if (self.epoch % cfg.training.val_every) == 0:
221
+ with torch.no_grad():
222
+ val_losses = list()
223
+ with tqdm.tqdm(
224
+ val_dataloader,
225
+ desc=f"Validation epoch {self.epoch}",
226
+ leave=False,
227
+ mininterval=cfg.training.tqdm_interval_sec,
228
+ ) as tepoch:
229
+ for batch_idx, batch in enumerate(tepoch):
230
+ batch = dataset.postprocess(batch, device)
231
+ loss = self.model.compute_loss(batch)
232
+ val_losses.append(loss)
233
+ if (cfg.training.max_val_steps
234
+ is not None) and batch_idx >= (cfg.training.max_val_steps - 1):
235
+ break
236
+ if len(val_losses) > 0:
237
+ val_loss = torch.mean(torch.tensor(val_losses)).item()
238
+ # log epoch average validation loss
239
+ step_log["val_loss"] = val_loss
240
+
241
+ # run diffusion sampling on a training batch
242
+ if (self.epoch % cfg.training.sample_every) == 0:
243
+ with torch.no_grad():
244
+ # sample trajectory from training set, and evaluate difference
245
+ batch = train_sampling_batch
246
+ obs_dict = batch["obs"]
247
+ gt_action = batch["action"]
248
+
249
+ result = policy.predict_action(obs_dict)
250
+ pred_action = result["action_pred"]
251
+ mse = torch.nn.functional.mse_loss(pred_action, gt_action)
252
+ step_log["train_action_mse_error"] = mse.item()
253
+ del batch
254
+ del obs_dict
255
+ del gt_action
256
+ del result
257
+ del pred_action
258
+ del mse
259
+
260
+ # checkpoint
261
+ if ((self.epoch + 1) % cfg.training.checkpoint_every) == 0:
262
+ # checkpointing
263
+ # Anchor to the policy directory so eval can resolve
264
+ # checkpoints/<bench>-<ckpt>-<env_cfg>-<action>-<seed>/ regardless of cwd.
265
+ save_name = pathlib.Path(self.cfg.task.dataset.zarr_path).stem
266
+ policy_dir = pathlib.Path(__file__).resolve().parents[2]
267
+ self.save_checkpoint(str(policy_dir / "checkpoints" / f"{save_name}-{seed}" / f"{self.epoch + 1}.ckpt"))
268
+
269
+ # ========= eval end for this epoch ==========
270
+ policy.train()
271
+
272
+ # end of epoch
273
+ # log of last step is combined with validation and rollout
274
+ json_logger.log(step_log)
275
+ self.global_step += 1
276
+ self.epoch += 1
277
+
278
+
279
+ class BatchSampler:
280
+
281
+ def __init__(
282
+ self,
283
+ data_size: int,
284
+ batch_size: int,
285
+ shuffle: bool = False,
286
+ seed: int = 0,
287
+ drop_last: bool = True,
288
+ ):
289
+ assert drop_last
290
+ self.data_size = data_size
291
+ self.batch_size = batch_size
292
+ self.num_batch = data_size // batch_size
293
+ self.discard = data_size - batch_size * self.num_batch
294
+ self.shuffle = shuffle
295
+ self.rng = np.random.default_rng(seed) if shuffle else None
296
+
297
+ def __iter__(self):
298
+ if self.shuffle:
299
+ perm = self.rng.permutation(self.data_size)
300
+ else:
301
+ perm = np.arange(self.data_size)
302
+ if self.discard > 0:
303
+ perm = perm[:-self.discard]
304
+ perm = perm.reshape(self.num_batch, self.batch_size)
305
+ for i in range(self.num_batch):
306
+ yield perm[i]
307
+
308
+ def __len__(self):
309
+ return self.num_batch
310
+
311
+
312
+ def create_dataloader(
313
+ dataset,
314
+ *,
315
+ batch_size: int,
316
+ shuffle: bool,
317
+ num_workers: int,
318
+ pin_memory: bool,
319
+ persistent_workers: bool,
320
+ seed: int = 0,
321
+ ):
322
+ batch_sampler = BatchSampler(len(dataset), batch_size, shuffle=shuffle, seed=seed, drop_last=True)
323
+
324
+ def collate(x):
325
+ assert len(x) == 1
326
+ return x[0]
327
+
328
+ dataloader = DataLoader(
329
+ dataset,
330
+ collate_fn=collate,
331
+ sampler=batch_sampler,
332
+ num_workers=num_workers,
333
+ pin_memory=False,
334
+ persistent_workers=persistent_workers,
335
+ )
336
+ return dataloader
337
+
338
+
339
+ @hydra.main(
340
+ version_base=None,
341
+ config_path=str(pathlib.Path(__file__).parent.parent.joinpath("config")),
342
+ config_name=pathlib.Path(__file__).stem,
343
+ )
344
+ def main(cfg):
345
+ workspace = RobotWorkspace(cfg)
346
+ workspace.run()
347
+
348
+
349
+ if __name__ == "__main__":
350
+ main()