souglad21 commited on
Commit
1e275f8
·
verified ·
1 Parent(s): d8a2faa

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. real_inference/models/shared/torch/hub/checkpoints/resnet18-f37072fd.pth +3 -0
  2. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/__init__.py +0 -0
  3. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/checkpoint_util.py +61 -0
  4. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/cv2_util.py +150 -0
  5. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/env_util.py +28 -0
  6. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/nested_dict_util.py +34 -0
  7. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/normalize_util.py +197 -0
  8. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/replay_buffer.py +622 -0
  9. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/robomimic_config_util.py +41 -0
  10. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/timestamp_accumulator.py +220 -0
  11. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/env_runner/dp_runner.py +101 -0
  12. real_inference/source/XPolicyLab/policy/DP/diffusion_policy/process_data.py +122 -0
  13. real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/pyproject.toml +23 -0
  14. real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/__init__.py +1 -0
  15. real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/action_chunk_broker.py +50 -0
  16. real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/base_policy.py +12 -0
  17. real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/image_tools.py +58 -0
  18. real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/image_tools_test.py +37 -0
  19. real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/msgpack_numpy.py +57 -0
  20. real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/msgpack_numpy_test.py +45 -0
  21. real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/runtime/agent.py +17 -0
  22. real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/runtime/agents/policy_agent.py +18 -0
  23. real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/runtime/environment.py +32 -0
  24. real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/runtime/runtime.py +92 -0
  25. real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/runtime/subscriber.py +20 -0
  26. real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/websocket_client_policy.py +58 -0
  27. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/model_test.py +94 -0
  28. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/pi0.py +279 -0
  29. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/pi0_config.py +117 -0
  30. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/utils/fsq_tokenizer.py +472 -0
  31. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/gemma_pytorch.py +281 -0
  32. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/pi0_pytorch.py +462 -0
  33. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/transformers_replace/models/gemma/configuration_gemma.py +173 -0
  34. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/transformers_replace/models/gemma/modeling_gemma.py +862 -0
  35. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/transformers_replace/models/paligemma/modeling_paligemma.py +622 -0
  36. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/transformers_replace/models/siglip/check.py +4 -0
  37. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/transformers_replace/models/siglip/modeling_siglip.py +1237 -0
  38. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/aloha_policy.py +209 -0
  39. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/droid_policy.py +81 -0
  40. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/libero_policy.py +100 -0
  41. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/pika_bimanual_policy.py +163 -0
  42. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/pika_bimanual_policy_test.py +44 -0
  43. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/policy.py +156 -0
  44. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/policy_config.py +94 -0
  45. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/policy_test.py +34 -0
  46. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/wuji_policy.py +88 -0
  47. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/checkpoints.py +159 -0
  48. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/config.py +1026 -0
  49. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/data_loader.py +549 -0
  50. real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/data_loader_test.py +84 -0
real_inference/models/shared/torch/hub/checkpoints/resnet18-f37072fd.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f37072fd47e89c5e827621c5baffa7500819f7896bbacec160b1a16c560e07ec
3
+ size 46830571
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/__init__.py ADDED
File without changes
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/checkpoint_util.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Dict
2
+ import os
3
+
4
+
5
+ class TopKCheckpointManager:
6
+
7
+ def __init__(
8
+ self,
9
+ save_dir,
10
+ monitor_key: str,
11
+ mode="min",
12
+ k=1,
13
+ format_str="epoch={epoch:03d}-train_loss={train_loss:.3f}.ckpt",
14
+ ):
15
+ assert mode in ["max", "min"]
16
+ assert k >= 0
17
+
18
+ self.save_dir = save_dir
19
+ self.monitor_key = monitor_key
20
+ self.mode = mode
21
+ self.k = k
22
+ self.format_str = format_str
23
+ self.path_value_map = dict()
24
+
25
+ def get_ckpt_path(self, data: Dict[str, float]) -> Optional[str]:
26
+ if self.k == 0:
27
+ return None
28
+
29
+ value = data[self.monitor_key]
30
+ ckpt_path = os.path.join(self.save_dir, self.format_str.format(**data))
31
+
32
+ if len(self.path_value_map) < self.k:
33
+ # under-capacity
34
+ self.path_value_map[ckpt_path] = value
35
+ return ckpt_path
36
+
37
+ # at capacity
38
+ sorted_map = sorted(self.path_value_map.items(), key=lambda x: x[1])
39
+ min_path, min_value = sorted_map[0]
40
+ max_path, max_value = sorted_map[-1]
41
+
42
+ delete_path = None
43
+ if self.mode == "max":
44
+ if value > min_value:
45
+ delete_path = min_path
46
+ else:
47
+ if value < max_value:
48
+ delete_path = max_path
49
+
50
+ if delete_path is None:
51
+ return None
52
+ else:
53
+ del self.path_value_map[delete_path]
54
+ self.path_value_map[ckpt_path] = value
55
+
56
+ if not os.path.exists(self.save_dir):
57
+ os.mkdir(self.save_dir)
58
+
59
+ if os.path.exists(delete_path):
60
+ os.remove(delete_path)
61
+ return ckpt_path
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/cv2_util.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple
2
+ import math
3
+ import cv2
4
+ import numpy as np
5
+
6
+
7
+ def draw_reticle(img, u, v, label_color):
8
+ """
9
+ Draws a reticle (cross-hair) on the image at the given position on top of
10
+ the original image.
11
+ @param img (In/Out) uint8 3 channel image
12
+ @param u X coordinate (width)
13
+ @param v Y coordinate (height)
14
+ @param label_color tuple of 3 ints for RGB color used for drawing.
15
+ """
16
+ # Cast to int.
17
+ u = int(u)
18
+ v = int(v)
19
+
20
+ white = (255, 255, 255)
21
+ cv2.circle(img, (u, v), 10, label_color, 1)
22
+ cv2.circle(img, (u, v), 11, white, 1)
23
+ cv2.circle(img, (u, v), 12, label_color, 1)
24
+ cv2.line(img, (u, v + 1), (u, v + 3), white, 1)
25
+ cv2.line(img, (u + 1, v), (u + 3, v), white, 1)
26
+ cv2.line(img, (u, v - 1), (u, v - 3), white, 1)
27
+ cv2.line(img, (u - 1, v), (u - 3, v), white, 1)
28
+
29
+
30
+ def draw_text(
31
+ img,
32
+ *,
33
+ text,
34
+ uv_top_left,
35
+ color=(255, 255, 255),
36
+ fontScale=0.5,
37
+ thickness=1,
38
+ fontFace=cv2.FONT_HERSHEY_SIMPLEX,
39
+ outline_color=(0, 0, 0),
40
+ line_spacing=1.5,
41
+ ):
42
+ """
43
+ Draws multiline with an outline.
44
+ """
45
+ assert isinstance(text, str)
46
+
47
+ uv_top_left = np.array(uv_top_left, dtype=float)
48
+ assert uv_top_left.shape == (2, )
49
+
50
+ for line in text.splitlines():
51
+ (w, h), _ = cv2.getTextSize(
52
+ text=line,
53
+ fontFace=fontFace,
54
+ fontScale=fontScale,
55
+ thickness=thickness,
56
+ )
57
+ uv_bottom_left_i = uv_top_left + [0, h]
58
+ org = tuple(uv_bottom_left_i.astype(int))
59
+
60
+ if outline_color is not None:
61
+ cv2.putText(
62
+ img,
63
+ text=line,
64
+ org=org,
65
+ fontFace=fontFace,
66
+ fontScale=fontScale,
67
+ color=outline_color,
68
+ thickness=thickness * 3,
69
+ lineType=cv2.LINE_AA,
70
+ )
71
+ cv2.putText(
72
+ img,
73
+ text=line,
74
+ org=org,
75
+ fontFace=fontFace,
76
+ fontScale=fontScale,
77
+ color=color,
78
+ thickness=thickness,
79
+ lineType=cv2.LINE_AA,
80
+ )
81
+
82
+ uv_top_left += [0, h * line_spacing]
83
+
84
+
85
+ def get_image_transform(
86
+ input_res: Tuple[int, int] = (1280, 720),
87
+ output_res: Tuple[int, int] = (640, 480),
88
+ bgr_to_rgb: bool = False,
89
+ ):
90
+
91
+ iw, ih = input_res
92
+ ow, oh = output_res
93
+ rw, rh = None, None
94
+ interp_method = cv2.INTER_AREA
95
+
96
+ if (iw / ih) >= (ow / oh):
97
+ # input is wider
98
+ rh = oh
99
+ rw = math.ceil(rh / ih * iw)
100
+ if oh > ih:
101
+ interp_method = cv2.INTER_LINEAR
102
+ else:
103
+ rw = ow
104
+ rh = math.ceil(rw / iw * ih)
105
+ if ow > iw:
106
+ interp_method = cv2.INTER_LINEAR
107
+
108
+ w_slice_start = (rw - ow) // 2
109
+ w_slice = slice(w_slice_start, w_slice_start + ow)
110
+ h_slice_start = (rh - oh) // 2
111
+ h_slice = slice(h_slice_start, h_slice_start + oh)
112
+ c_slice = slice(None)
113
+ if bgr_to_rgb:
114
+ c_slice = slice(None, None, -1)
115
+
116
+ def transform(img: np.ndarray):
117
+ assert img.shape == ((ih, iw, 3))
118
+ # resize
119
+ img = cv2.resize(img, (rw, rh), interpolation=interp_method)
120
+ # crop
121
+ img = img[h_slice, w_slice, c_slice]
122
+ return img
123
+
124
+ return transform
125
+
126
+
127
+ def optimal_row_cols(n_cameras, in_wh_ratio, max_resolution=(1920, 1080)):
128
+ out_w, out_h = max_resolution
129
+ out_wh_ratio = out_w / out_h
130
+
131
+ n_rows = np.arange(n_cameras, dtype=np.int64) + 1
132
+ n_cols = np.ceil(n_cameras / n_rows).astype(np.int64)
133
+ cat_wh_ratio = in_wh_ratio * (n_cols / n_rows)
134
+ ratio_diff = np.abs(out_wh_ratio - cat_wh_ratio)
135
+ best_idx = np.argmin(ratio_diff)
136
+ best_n_row = n_rows[best_idx]
137
+ best_n_col = n_cols[best_idx]
138
+ best_cat_wh_ratio = cat_wh_ratio[best_idx]
139
+
140
+ rw, rh = None, None
141
+ if best_cat_wh_ratio >= out_wh_ratio:
142
+ # cat is wider
143
+ rw = math.floor(out_w / best_n_col)
144
+ rh = math.floor(rw / in_wh_ratio)
145
+ else:
146
+ rh = math.floor(out_h / best_n_row)
147
+ rw = math.floor(rh * in_wh_ratio)
148
+
149
+ # crop_resolution = (rw, rh)
150
+ return rw, rh, best_n_col, best_n_row
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/env_util.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+
4
+
5
+ def render_env_video(env, states, actions=None):
6
+ observations = states
7
+ imgs = list()
8
+ for i in range(len(observations)):
9
+ state = observations[i]
10
+ env.set_state(state)
11
+ if i == 0:
12
+ env.set_state(state)
13
+ img = env.render()
14
+ # draw action
15
+ if actions is not None:
16
+ action = actions[i]
17
+ coord = (action / 512 * 96).astype(np.int32)
18
+ cv2.drawMarker(
19
+ img,
20
+ coord,
21
+ color=(255, 0, 0),
22
+ markerType=cv2.MARKER_CROSS,
23
+ markerSize=8,
24
+ thickness=1,
25
+ )
26
+ imgs.append(img)
27
+ imgs = np.array(imgs)
28
+ return imgs
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/nested_dict_util.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+
3
+
4
+ def nested_dict_map(f, x):
5
+ """
6
+ Map f over all leaf of nested dict x
7
+ """
8
+
9
+ if not isinstance(x, dict):
10
+ return f(x)
11
+ y = dict()
12
+ for key, value in x.items():
13
+ y[key] = nested_dict_map(f, value)
14
+ return y
15
+
16
+
17
+ def nested_dict_reduce(f, x):
18
+ """
19
+ Map f over all values of nested dict x, and reduce to a single value
20
+ """
21
+ if not isinstance(x, dict):
22
+ return x
23
+
24
+ reduced_values = list()
25
+ for value in x.values():
26
+ reduced_values.append(nested_dict_reduce(f, value))
27
+ y = functools.reduce(f, reduced_values)
28
+ return y
29
+
30
+
31
+ def nested_dict_check(f, x):
32
+ bool_dict = nested_dict_map(f, x)
33
+ result = nested_dict_reduce(lambda x, y: x and y, bool_dict)
34
+ return result
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/normalize_util.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusion_policy.model.common.normalizer import SingleFieldLinearNormalizer
2
+ from diffusion_policy.common.pytorch_util import (
3
+ dict_apply,
4
+ dict_apply_reduce,
5
+ dict_apply_split,
6
+ )
7
+ import numpy as np
8
+
9
+
10
+ def get_range_normalizer_from_stat(stat, output_max=1, output_min=-1, range_eps=1e-7):
11
+ # -1, 1 normalization
12
+ input_max = stat["max"]
13
+ input_min = stat["min"]
14
+ input_range = input_max - input_min
15
+ ignore_dim = input_range < range_eps
16
+ input_range[ignore_dim] = output_max - output_min
17
+ scale = (output_max - output_min) / input_range
18
+ offset = output_min - scale * input_min
19
+ offset[ignore_dim] = (output_max + output_min) / 2 - input_min[ignore_dim]
20
+
21
+ return SingleFieldLinearNormalizer.create_manual(scale=scale, offset=offset, input_stats_dict=stat)
22
+
23
+
24
+ def get_image_range_normalizer():
25
+ scale = np.array([2], dtype=np.float32)
26
+ offset = np.array([-1], dtype=np.float32)
27
+ stat = {
28
+ "min": np.array([0], dtype=np.float32),
29
+ "max": np.array([1], dtype=np.float32),
30
+ "mean": np.array([0.5], dtype=np.float32),
31
+ "std": np.array([np.sqrt(1 / 12)], dtype=np.float32),
32
+ }
33
+ return SingleFieldLinearNormalizer.create_manual(scale=scale, offset=offset, input_stats_dict=stat)
34
+
35
+
36
+ def get_identity_normalizer_from_stat(stat):
37
+ scale = np.ones_like(stat["min"])
38
+ offset = np.zeros_like(stat["min"])
39
+ return SingleFieldLinearNormalizer.create_manual(scale=scale, offset=offset, input_stats_dict=stat)
40
+
41
+
42
+ def robomimic_abs_action_normalizer_from_stat(stat, rotation_transformer):
43
+ result = dict_apply_split(stat, lambda x: {"pos": x[..., :3], "rot": x[..., 3:6], "gripper": x[..., 6:]})
44
+
45
+ def get_pos_param_info(stat, output_max=1, output_min=-1, range_eps=1e-7):
46
+ # -1, 1 normalization
47
+ input_max = stat["max"]
48
+ input_min = stat["min"]
49
+ input_range = input_max - input_min
50
+ ignore_dim = input_range < range_eps
51
+ input_range[ignore_dim] = output_max - output_min
52
+ scale = (output_max - output_min) / input_range
53
+ offset = output_min - scale * input_min
54
+ offset[ignore_dim] = (output_max + output_min) / 2 - input_min[ignore_dim]
55
+
56
+ return {"scale": scale, "offset": offset}, stat
57
+
58
+ def get_rot_param_info(stat):
59
+ example = rotation_transformer.forward(stat["mean"])
60
+ scale = np.ones_like(example)
61
+ offset = np.zeros_like(example)
62
+ info = {
63
+ "max": np.ones_like(example),
64
+ "min": np.full_like(example, -1),
65
+ "mean": np.zeros_like(example),
66
+ "std": np.ones_like(example),
67
+ }
68
+ return {"scale": scale, "offset": offset}, info
69
+
70
+ def get_gripper_param_info(stat):
71
+ example = stat["max"]
72
+ scale = np.ones_like(example)
73
+ offset = np.zeros_like(example)
74
+ info = {
75
+ "max": np.ones_like(example),
76
+ "min": np.full_like(example, -1),
77
+ "mean": np.zeros_like(example),
78
+ "std": np.ones_like(example),
79
+ }
80
+ return {"scale": scale, "offset": offset}, info
81
+
82
+ pos_param, pos_info = get_pos_param_info(result["pos"])
83
+ rot_param, rot_info = get_rot_param_info(result["rot"])
84
+ gripper_param, gripper_info = get_gripper_param_info(result["gripper"])
85
+
86
+ param = dict_apply_reduce([pos_param, rot_param, gripper_param], lambda x: np.concatenate(x, axis=-1))
87
+ info = dict_apply_reduce([pos_info, rot_info, gripper_info], lambda x: np.concatenate(x, axis=-1))
88
+
89
+ return SingleFieldLinearNormalizer.create_manual(scale=param["scale"],
90
+ offset=param["offset"],
91
+ input_stats_dict=info)
92
+
93
+
94
+ def robomimic_abs_action_only_normalizer_from_stat(stat):
95
+ result = dict_apply_split(stat, lambda x: {"pos": x[..., :3], "other": x[..., 3:]})
96
+
97
+ def get_pos_param_info(stat, output_max=1, output_min=-1, range_eps=1e-7):
98
+ # -1, 1 normalization
99
+ input_max = stat["max"]
100
+ input_min = stat["min"]
101
+ input_range = input_max - input_min
102
+ ignore_dim = input_range < range_eps
103
+ input_range[ignore_dim] = output_max - output_min
104
+ scale = (output_max - output_min) / input_range
105
+ offset = output_min - scale * input_min
106
+ offset[ignore_dim] = (output_max + output_min) / 2 - input_min[ignore_dim]
107
+
108
+ return {"scale": scale, "offset": offset}, stat
109
+
110
+ def get_other_param_info(stat):
111
+ example = stat["max"]
112
+ scale = np.ones_like(example)
113
+ offset = np.zeros_like(example)
114
+ info = {
115
+ "max": np.ones_like(example),
116
+ "min": np.full_like(example, -1),
117
+ "mean": np.zeros_like(example),
118
+ "std": np.ones_like(example),
119
+ }
120
+ return {"scale": scale, "offset": offset}, info
121
+
122
+ pos_param, pos_info = get_pos_param_info(result["pos"])
123
+ other_param, other_info = get_other_param_info(result["other"])
124
+
125
+ param = dict_apply_reduce([pos_param, other_param], lambda x: np.concatenate(x, axis=-1))
126
+ info = dict_apply_reduce([pos_info, other_info], lambda x: np.concatenate(x, axis=-1))
127
+
128
+ return SingleFieldLinearNormalizer.create_manual(scale=param["scale"],
129
+ offset=param["offset"],
130
+ input_stats_dict=info)
131
+
132
+
133
+ def robomimic_abs_action_only_dual_arm_normalizer_from_stat(stat):
134
+ Da = stat["max"].shape[-1]
135
+ Dah = Da // 2
136
+ result = dict_apply_split(
137
+ stat,
138
+ lambda x: {
139
+ "pos0": x[..., :3],
140
+ "other0": x[..., 3:Dah],
141
+ "pos1": x[..., Dah:Dah + 3],
142
+ "other1": x[..., Dah + 3:],
143
+ },
144
+ )
145
+
146
+ def get_pos_param_info(stat, output_max=1, output_min=-1, range_eps=1e-7):
147
+ # -1, 1 normalization
148
+ input_max = stat["max"]
149
+ input_min = stat["min"]
150
+ input_range = input_max - input_min
151
+ ignore_dim = input_range < range_eps
152
+ input_range[ignore_dim] = output_max - output_min
153
+ scale = (output_max - output_min) / input_range
154
+ offset = output_min - scale * input_min
155
+ offset[ignore_dim] = (output_max + output_min) / 2 - input_min[ignore_dim]
156
+
157
+ return {"scale": scale, "offset": offset}, stat
158
+
159
+ def get_other_param_info(stat):
160
+ example = stat["max"]
161
+ scale = np.ones_like(example)
162
+ offset = np.zeros_like(example)
163
+ info = {
164
+ "max": np.ones_like(example),
165
+ "min": np.full_like(example, -1),
166
+ "mean": np.zeros_like(example),
167
+ "std": np.ones_like(example),
168
+ }
169
+ return {"scale": scale, "offset": offset}, info
170
+
171
+ pos0_param, pos0_info = get_pos_param_info(result["pos0"])
172
+ pos1_param, pos1_info = get_pos_param_info(result["pos1"])
173
+ other0_param, other0_info = get_other_param_info(result["other0"])
174
+ other1_param, other1_info = get_other_param_info(result["other1"])
175
+
176
+ param = dict_apply_reduce(
177
+ [pos0_param, other0_param, pos1_param, other1_param],
178
+ lambda x: np.concatenate(x, axis=-1),
179
+ )
180
+ info = dict_apply_reduce(
181
+ [pos0_info, other0_info, pos1_info, other1_info],
182
+ lambda x: np.concatenate(x, axis=-1),
183
+ )
184
+
185
+ return SingleFieldLinearNormalizer.create_manual(scale=param["scale"],
186
+ offset=param["offset"],
187
+ input_stats_dict=info)
188
+
189
+
190
+ def array_to_stats(arr: np.ndarray):
191
+ stat = {
192
+ "min": np.min(arr, axis=0),
193
+ "max": np.max(arr, axis=0),
194
+ "mean": np.mean(arr, axis=0),
195
+ "std": np.std(arr, axis=0),
196
+ }
197
+ return stat
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/replay_buffer.py ADDED
@@ -0,0 +1,622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union, Dict, Optional
2
+ import os
3
+ import math
4
+ import numbers
5
+ import zarr
6
+ import numcodecs
7
+ import numpy as np
8
+ from functools import cached_property
9
+
10
+
11
+ def check_chunks_compatible(chunks: tuple, shape: tuple):
12
+ assert len(shape) == len(chunks)
13
+ for c in chunks:
14
+ assert isinstance(c, numbers.Integral)
15
+ assert c > 0
16
+
17
+
18
+ def rechunk_recompress_array(group, name, chunks=None, chunk_length=None, compressor=None, tmp_key="_temp"):
19
+ old_arr = group[name]
20
+ if chunks is None:
21
+ if chunk_length is not None:
22
+ chunks = (chunk_length, ) + old_arr.chunks[1:]
23
+ else:
24
+ chunks = old_arr.chunks
25
+ check_chunks_compatible(chunks, old_arr.shape)
26
+
27
+ if compressor is None:
28
+ compressor = old_arr.compressor
29
+
30
+ if (chunks == old_arr.chunks) and (compressor == old_arr.compressor):
31
+ # no change
32
+ return old_arr
33
+
34
+ # rechunk recompress
35
+ group.move(name, tmp_key)
36
+ old_arr = group[tmp_key]
37
+ n_copied, n_skipped, n_bytes_copied = zarr.copy(
38
+ source=old_arr,
39
+ dest=group,
40
+ name=name,
41
+ chunks=chunks,
42
+ compressor=compressor,
43
+ )
44
+ del group[tmp_key]
45
+ arr = group[name]
46
+ return arr
47
+
48
+
49
+ def get_optimal_chunks(shape, dtype, target_chunk_bytes=2e6, max_chunk_length=None):
50
+ """
51
+ Common shapes
52
+ T,D
53
+ T,N,D
54
+ T,H,W,C
55
+ T,N,H,W,C
56
+ """
57
+ itemsize = np.dtype(dtype).itemsize
58
+ # reversed
59
+ rshape = list(shape[::-1])
60
+ if max_chunk_length is not None:
61
+ rshape[-1] = int(max_chunk_length)
62
+ split_idx = len(shape) - 1
63
+ for i in range(len(shape) - 1):
64
+ this_chunk_bytes = itemsize * np.prod(rshape[:i])
65
+ next_chunk_bytes = itemsize * np.prod(rshape[:i + 1])
66
+ if (this_chunk_bytes <= target_chunk_bytes and next_chunk_bytes > target_chunk_bytes):
67
+ split_idx = i
68
+
69
+ rchunks = rshape[:split_idx]
70
+ item_chunk_bytes = itemsize * np.prod(rshape[:split_idx])
71
+ this_max_chunk_length = rshape[split_idx]
72
+ next_chunk_length = min(this_max_chunk_length, math.ceil(target_chunk_bytes / item_chunk_bytes))
73
+ rchunks.append(next_chunk_length)
74
+ len_diff = len(shape) - len(rchunks)
75
+ rchunks.extend([1] * len_diff)
76
+ chunks = tuple(rchunks[::-1])
77
+ # print(np.prod(chunks) * itemsize / target_chunk_bytes)
78
+ return chunks
79
+
80
+
81
+ class ReplayBuffer:
82
+ """
83
+ Zarr-based temporal datastructure.
84
+ Assumes first dimension to be time. Only chunk in time dimension.
85
+ """
86
+
87
+ def __init__(self, root: Union[zarr.Group, Dict[str, dict]]):
88
+ """
89
+ Dummy constructor. Use copy_from* and create_from* class methods instead.
90
+ """
91
+ assert "data" in root
92
+ assert "meta" in root
93
+ assert "episode_ends" in root["meta"]
94
+ for key, value in root["data"].items():
95
+ assert value.shape[0] == root["meta"]["episode_ends"][-1]
96
+ self.root = root
97
+
98
+ # ============= create constructors ===============
99
+ @classmethod
100
+ def create_empty_zarr(cls, storage=None, root=None):
101
+ if root is None:
102
+ if storage is None:
103
+ storage = zarr.MemoryStore()
104
+ root = zarr.group(store=storage)
105
+ data = root.require_group("data", overwrite=False)
106
+ meta = root.require_group("meta", overwrite=False)
107
+ if "episode_ends" not in meta:
108
+ episode_ends = meta.zeros(
109
+ "episode_ends",
110
+ shape=(0, ),
111
+ dtype=np.int64,
112
+ compressor=None,
113
+ overwrite=False,
114
+ )
115
+ return cls(root=root)
116
+
117
+ @classmethod
118
+ def create_empty_numpy(cls):
119
+ root = {
120
+ "data": dict(),
121
+ "meta": {
122
+ "episode_ends": np.zeros((0, ), dtype=np.int64)
123
+ },
124
+ }
125
+ return cls(root=root)
126
+
127
+ @classmethod
128
+ def create_from_group(cls, group, **kwargs):
129
+ if "data" not in group:
130
+ # create from stratch
131
+ buffer = cls.create_empty_zarr(root=group, **kwargs)
132
+ else:
133
+ # already exist
134
+ buffer = cls(root=group, **kwargs)
135
+ return buffer
136
+
137
+ @classmethod
138
+ def create_from_path(cls, zarr_path, mode="r", **kwargs):
139
+ """
140
+ Open a on-disk zarr directly (for dataset larger than memory).
141
+ Slower.
142
+ """
143
+ group = zarr.open(os.path.expanduser(zarr_path), mode)
144
+ return cls.create_from_group(group, **kwargs)
145
+
146
+ # ============= copy constructors ===============
147
+ @classmethod
148
+ def copy_from_store(
149
+ cls,
150
+ src_store,
151
+ store=None,
152
+ keys=None,
153
+ chunks: Dict[str, tuple] = dict(),
154
+ compressors: Union[dict, str, numcodecs.abc.Codec] = dict(),
155
+ if_exists="replace",
156
+ **kwargs,
157
+ ):
158
+ """
159
+ Load to memory.
160
+ """
161
+ src_root = zarr.group(src_store)
162
+ root = None
163
+ if store is None:
164
+ # numpy backend
165
+ meta = dict()
166
+ for key, value in src_root["meta"].items():
167
+ if len(value.shape) == 0:
168
+ meta[key] = np.array(value)
169
+ else:
170
+ meta[key] = value[:]
171
+
172
+ if keys is None:
173
+ keys = src_root["data"].keys()
174
+ data = dict()
175
+ for key in keys:
176
+ arr = src_root["data"][key]
177
+ data[key] = arr[:]
178
+
179
+ root = {"meta": meta, "data": data}
180
+ else:
181
+ root = zarr.group(store=store)
182
+ # copy without recompression
183
+ n_copied, n_skipped, n_bytes_copied = zarr.copy_store(
184
+ source=src_store,
185
+ dest=store,
186
+ source_path="/meta",
187
+ dest_path="/meta",
188
+ if_exists=if_exists,
189
+ )
190
+ data_group = root.create_group("data", overwrite=True)
191
+ if keys is None:
192
+ keys = src_root["data"].keys()
193
+ for key in keys:
194
+ value = src_root["data"][key]
195
+ cks = cls._resolve_array_chunks(chunks=chunks, key=key, array=value)
196
+ cpr = cls._resolve_array_compressor(compressors=compressors, key=key, array=value)
197
+ if cks == value.chunks and cpr == value.compressor:
198
+ # copy without recompression
199
+ this_path = "/data/" + key
200
+ n_copied, n_skipped, n_bytes_copied = zarr.copy_store(
201
+ source=src_store,
202
+ dest=store,
203
+ source_path=this_path,
204
+ dest_path=this_path,
205
+ if_exists=if_exists,
206
+ )
207
+ else:
208
+ # copy with recompression
209
+ n_copied, n_skipped, n_bytes_copied = zarr.copy(
210
+ source=value,
211
+ dest=data_group,
212
+ name=key,
213
+ chunks=cks,
214
+ compressor=cpr,
215
+ if_exists=if_exists,
216
+ )
217
+ buffer = cls(root=root)
218
+ return buffer
219
+
220
+ @classmethod
221
+ def copy_from_path(
222
+ cls,
223
+ zarr_path,
224
+ backend=None,
225
+ store=None,
226
+ keys=None,
227
+ chunks: Dict[str, tuple] = dict(),
228
+ compressors: Union[dict, str, numcodecs.abc.Codec] = dict(),
229
+ if_exists="replace",
230
+ **kwargs,
231
+ ):
232
+ """
233
+ Copy a on-disk zarr to in-memory compressed.
234
+ Recommended
235
+ """
236
+ if backend == "numpy":
237
+ print("backend argument is deprecated!")
238
+ store = None
239
+ group = zarr.open(os.path.expanduser(zarr_path), "r")
240
+ return cls.copy_from_store(
241
+ src_store=group.store,
242
+ store=store,
243
+ keys=keys,
244
+ chunks=chunks,
245
+ compressors=compressors,
246
+ if_exists=if_exists,
247
+ **kwargs,
248
+ )
249
+
250
+ # ============= save methods ===============
251
+ def save_to_store(
252
+ self,
253
+ store,
254
+ chunks: Optional[Dict[str, tuple]] = dict(),
255
+ compressors: Union[str, numcodecs.abc.Codec, dict] = dict(),
256
+ if_exists="replace",
257
+ **kwargs,
258
+ ):
259
+
260
+ root = zarr.group(store)
261
+ if self.backend == "zarr":
262
+ # recompression free copy
263
+ n_copied, n_skipped, n_bytes_copied = zarr.copy_store(
264
+ source=self.root.store,
265
+ dest=store,
266
+ source_path="/meta",
267
+ dest_path="/meta",
268
+ if_exists=if_exists,
269
+ )
270
+ else:
271
+ meta_group = root.create_group("meta", overwrite=True)
272
+ # save meta, no chunking
273
+ for key, value in self.root["meta"].items():
274
+ _ = meta_group.array(name=key, data=value, shape=value.shape, chunks=value.shape)
275
+
276
+ # save data, chunk
277
+ data_group = root.create_group("data", overwrite=True)
278
+ for key, value in self.root["data"].items():
279
+ cks = self._resolve_array_chunks(chunks=chunks, key=key, array=value)
280
+ cpr = self._resolve_array_compressor(compressors=compressors, key=key, array=value)
281
+ if isinstance(value, zarr.Array):
282
+ if cks == value.chunks and cpr == value.compressor:
283
+ # copy without recompression
284
+ this_path = "/data/" + key
285
+ n_copied, n_skipped, n_bytes_copied = zarr.copy_store(
286
+ source=self.root.store,
287
+ dest=store,
288
+ source_path=this_path,
289
+ dest_path=this_path,
290
+ if_exists=if_exists,
291
+ )
292
+ else:
293
+ # copy with recompression
294
+ n_copied, n_skipped, n_bytes_copied = zarr.copy(
295
+ source=value,
296
+ dest=data_group,
297
+ name=key,
298
+ chunks=cks,
299
+ compressor=cpr,
300
+ if_exists=if_exists,
301
+ )
302
+ else:
303
+ # numpy
304
+ _ = data_group.array(name=key, data=value, chunks=cks, compressor=cpr)
305
+ return store
306
+
307
+ def save_to_path(
308
+ self,
309
+ zarr_path,
310
+ chunks: Optional[Dict[str, tuple]] = dict(),
311
+ compressors: Union[str, numcodecs.abc.Codec, dict] = dict(),
312
+ if_exists="replace",
313
+ **kwargs,
314
+ ):
315
+ store = zarr.DirectoryStore(os.path.expanduser(zarr_path))
316
+ return self.save_to_store(store, chunks=chunks, compressors=compressors, if_exists=if_exists, **kwargs)
317
+
318
+ @staticmethod
319
+ def resolve_compressor(compressor="default"):
320
+ if compressor == "default":
321
+ compressor = numcodecs.Blosc(cname="lz4", clevel=5, shuffle=numcodecs.Blosc.NOSHUFFLE)
322
+ elif compressor == "disk":
323
+ compressor = numcodecs.Blosc("zstd", clevel=5, shuffle=numcodecs.Blosc.BITSHUFFLE)
324
+ return compressor
325
+
326
+ @classmethod
327
+ def _resolve_array_compressor(cls, compressors: Union[dict, str, numcodecs.abc.Codec], key, array):
328
+ # allows compressor to be explicitly set to None
329
+ cpr = "nil"
330
+ if isinstance(compressors, dict):
331
+ if key in compressors:
332
+ cpr = cls.resolve_compressor(compressors[key])
333
+ elif isinstance(array, zarr.Array):
334
+ cpr = array.compressor
335
+ else:
336
+ cpr = cls.resolve_compressor(compressors)
337
+ # backup default
338
+ if cpr == "nil":
339
+ cpr = cls.resolve_compressor("default")
340
+ return cpr
341
+
342
+ @classmethod
343
+ def _resolve_array_chunks(cls, chunks: Union[dict, tuple], key, array):
344
+ cks = None
345
+ if isinstance(chunks, dict):
346
+ if key in chunks:
347
+ cks = chunks[key]
348
+ elif isinstance(array, zarr.Array):
349
+ cks = array.chunks
350
+ elif isinstance(chunks, tuple):
351
+ cks = chunks
352
+ else:
353
+ raise TypeError(f"Unsupported chunks type {type(chunks)}")
354
+ # backup default
355
+ if cks is None:
356
+ cks = get_optimal_chunks(shape=array.shape, dtype=array.dtype)
357
+ # check
358
+ check_chunks_compatible(chunks=cks, shape=array.shape)
359
+ return cks
360
+
361
+ # ============= properties =================
362
+ @cached_property
363
+ def data(self):
364
+ return self.root["data"]
365
+
366
+ @cached_property
367
+ def meta(self):
368
+ return self.root["meta"]
369
+
370
+ def update_meta(self, data):
371
+ # sanitize data
372
+ np_data = dict()
373
+ for key, value in data.items():
374
+ if isinstance(value, np.ndarray):
375
+ np_data[key] = value
376
+ else:
377
+ arr = np.array(value)
378
+ if arr.dtype == object:
379
+ raise TypeError(f"Invalid value type {type(value)}")
380
+ np_data[key] = arr
381
+
382
+ meta_group = self.meta
383
+ if self.backend == "zarr":
384
+ for key, value in np_data.items():
385
+ _ = meta_group.array(
386
+ name=key,
387
+ data=value,
388
+ shape=value.shape,
389
+ chunks=value.shape,
390
+ overwrite=True,
391
+ )
392
+ else:
393
+ meta_group.update(np_data)
394
+
395
+ return meta_group
396
+
397
+ @property
398
+ def episode_ends(self):
399
+ return self.meta["episode_ends"]
400
+
401
+ def get_episode_idxs(self):
402
+ import numba
403
+
404
+ numba.jit(nopython=True)
405
+
406
+ def _get_episode_idxs(episode_ends):
407
+ result = np.zeros((episode_ends[-1], ), dtype=np.int64)
408
+ for i in range(len(episode_ends)):
409
+ start = 0
410
+ if i > 0:
411
+ start = episode_ends[i - 1]
412
+ end = episode_ends[i]
413
+ for idx in range(start, end):
414
+ result[idx] = i
415
+ return result
416
+
417
+ return _get_episode_idxs(self.episode_ends)
418
+
419
+ @property
420
+ def backend(self):
421
+ backend = "numpy"
422
+ if isinstance(self.root, zarr.Group):
423
+ backend = "zarr"
424
+ return backend
425
+
426
+ # =========== dict-like API ==============
427
+ def __repr__(self) -> str:
428
+ if self.backend == "zarr":
429
+ return str(self.root.tree())
430
+ else:
431
+ return super().__repr__()
432
+
433
+ def keys(self):
434
+ return self.data.keys()
435
+
436
+ def values(self):
437
+ return self.data.values()
438
+
439
+ def items(self):
440
+ return self.data.items()
441
+
442
+ def __getitem__(self, key):
443
+ return self.data[key]
444
+
445
+ def __contains__(self, key):
446
+ return key in self.data
447
+
448
+ # =========== our API ==============
449
+ @property
450
+ def n_steps(self):
451
+ if len(self.episode_ends) == 0:
452
+ return 0
453
+ return self.episode_ends[-1]
454
+
455
+ @property
456
+ def n_episodes(self):
457
+ return len(self.episode_ends)
458
+
459
+ @property
460
+ def chunk_size(self):
461
+ if self.backend == "zarr":
462
+ return next(iter(self.data.arrays()))[-1].chunks[0]
463
+ return None
464
+
465
+ @property
466
+ def episode_lengths(self):
467
+ ends = self.episode_ends[:]
468
+ ends = np.insert(ends, 0, 0)
469
+ lengths = np.diff(ends)
470
+ return lengths
471
+
472
+ def add_episode(
473
+ self,
474
+ data: Dict[str, np.ndarray],
475
+ chunks: Optional[Dict[str, tuple]] = dict(),
476
+ compressors: Union[str, numcodecs.abc.Codec, dict] = dict(),
477
+ ):
478
+ assert len(data) > 0
479
+ is_zarr = self.backend == "zarr"
480
+
481
+ curr_len = self.n_steps
482
+ episode_length = None
483
+ for key, value in data.items():
484
+ assert len(value.shape) >= 1
485
+ if episode_length is None:
486
+ episode_length = len(value)
487
+ else:
488
+ assert episode_length == len(value)
489
+ new_len = curr_len + episode_length
490
+
491
+ for key, value in data.items():
492
+ new_shape = (new_len, ) + value.shape[1:]
493
+ # create array
494
+ if key not in self.data:
495
+ if is_zarr:
496
+ cks = self._resolve_array_chunks(chunks=chunks, key=key, array=value)
497
+ cpr = self._resolve_array_compressor(compressors=compressors, key=key, array=value)
498
+ arr = self.data.zeros(
499
+ name=key,
500
+ shape=new_shape,
501
+ chunks=cks,
502
+ dtype=value.dtype,
503
+ compressor=cpr,
504
+ )
505
+ else:
506
+ # copy data to prevent modify
507
+ arr = np.zeros(shape=new_shape, dtype=value.dtype)
508
+ self.data[key] = arr
509
+ else:
510
+ arr = self.data[key]
511
+ assert value.shape[1:] == arr.shape[1:]
512
+ # same method for both zarr and numpy
513
+ if is_zarr:
514
+ arr.resize(new_shape)
515
+ else:
516
+ arr.resize(new_shape, refcheck=False)
517
+ # copy data
518
+ arr[-value.shape[0]:] = value
519
+
520
+ # append to episode ends
521
+ episode_ends = self.episode_ends
522
+ if is_zarr:
523
+ episode_ends.resize(episode_ends.shape[0] + 1)
524
+ else:
525
+ episode_ends.resize(episode_ends.shape[0] + 1, refcheck=False)
526
+ episode_ends[-1] = new_len
527
+
528
+ # rechunk
529
+ if is_zarr:
530
+ if episode_ends.chunks[0] < episode_ends.shape[0]:
531
+ rechunk_recompress_array(
532
+ self.meta,
533
+ "episode_ends",
534
+ chunk_length=int(episode_ends.shape[0] * 1.5),
535
+ )
536
+
537
+ def drop_episode(self):
538
+ is_zarr = self.backend == "zarr"
539
+ episode_ends = self.episode_ends[:].copy()
540
+ assert len(episode_ends) > 0
541
+ start_idx = 0
542
+ if len(episode_ends) > 1:
543
+ start_idx = episode_ends[-2]
544
+ for key, value in self.data.items():
545
+ new_shape = (start_idx, ) + value.shape[1:]
546
+ if is_zarr:
547
+ value.resize(new_shape)
548
+ else:
549
+ value.resize(new_shape, refcheck=False)
550
+ if is_zarr:
551
+ self.episode_ends.resize(len(episode_ends) - 1)
552
+ else:
553
+ self.episode_ends.resize(len(episode_ends) - 1, refcheck=False)
554
+
555
+ def pop_episode(self):
556
+ assert self.n_episodes > 0
557
+ episode = self.get_episode(self.n_episodes - 1, copy=True)
558
+ self.drop_episode()
559
+ return episode
560
+
561
+ def extend(self, data):
562
+ self.add_episode(data)
563
+
564
+ def get_episode(self, idx, copy=False):
565
+ idx = list(range(len(self.episode_ends)))[idx]
566
+ start_idx = 0
567
+ if idx > 0:
568
+ start_idx = self.episode_ends[idx - 1]
569
+ end_idx = self.episode_ends[idx]
570
+ result = self.get_steps_slice(start_idx, end_idx, copy=copy)
571
+ return result
572
+
573
+ def get_episode_slice(self, idx):
574
+ start_idx = 0
575
+ if idx > 0:
576
+ start_idx = self.episode_ends[idx - 1]
577
+ end_idx = self.episode_ends[idx]
578
+ return slice(start_idx, end_idx)
579
+
580
+ def get_steps_slice(self, start, stop, step=None, copy=False):
581
+ _slice = slice(start, stop, step)
582
+
583
+ result = dict()
584
+ for key, value in self.data.items():
585
+ x = value[_slice]
586
+ if copy and isinstance(value, np.ndarray):
587
+ x = x.copy()
588
+ result[key] = x
589
+ return result
590
+
591
+ # =========== chunking =============
592
+ def get_chunks(self) -> dict:
593
+ assert self.backend == "zarr"
594
+ chunks = dict()
595
+ for key, value in self.data.items():
596
+ chunks[key] = value.chunks
597
+ return chunks
598
+
599
+ def set_chunks(self, chunks: dict):
600
+ assert self.backend == "zarr"
601
+ for key, value in chunks.items():
602
+ if key in self.data:
603
+ arr = self.data[key]
604
+ if value != arr.chunks:
605
+ check_chunks_compatible(chunks=value, shape=arr.shape)
606
+ rechunk_recompress_array(self.data, key, chunks=value)
607
+
608
+ def get_compressors(self) -> dict:
609
+ assert self.backend == "zarr"
610
+ compressors = dict()
611
+ for key, value in self.data.items():
612
+ compressors[key] = value.compressor
613
+ return compressors
614
+
615
+ def set_compressors(self, compressors: dict):
616
+ assert self.backend == "zarr"
617
+ for key, value in compressors.items():
618
+ if key in self.data:
619
+ arr = self.data[key]
620
+ compressor = self.resolve_compressor(value)
621
+ if compressor != arr.compressor:
622
+ rechunk_recompress_array(self.data, key, compressor=compressor)
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/robomimic_config_util.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from omegaconf import OmegaConf
2
+ from robomimic.config import config_factory
3
+ import robomimic.scripts.generate_paper_configs as gpc
4
+ from robomimic.scripts.generate_paper_configs import (
5
+ modify_config_for_default_image_exp,
6
+ modify_config_for_default_low_dim_exp,
7
+ modify_config_for_dataset,
8
+ )
9
+
10
+
11
+ def get_robomimic_config(algo_name="bc_rnn", hdf5_type="low_dim", task_name="square", dataset_type="ph"):
12
+ base_dataset_dir = "/tmp/null"
13
+ filter_key = None
14
+
15
+ # decide whether to use low-dim or image training defaults
16
+ modifier_for_obs = modify_config_for_default_image_exp
17
+ if hdf5_type in ["low_dim", "low_dim_sparse", "low_dim_dense"]:
18
+ modifier_for_obs = modify_config_for_default_low_dim_exp
19
+
20
+ algo_config_name = "bc" if algo_name == "bc_rnn" else algo_name
21
+ config = config_factory(algo_name=algo_config_name)
22
+ # turn into default config for observation modalities (e.g.: low-dim or rgb)
23
+ config = modifier_for_obs(config)
24
+ # add in config based on the dataset
25
+ config = modify_config_for_dataset(
26
+ config=config,
27
+ task_name=task_name,
28
+ dataset_type=dataset_type,
29
+ hdf5_type=hdf5_type,
30
+ base_dataset_dir=base_dataset_dir,
31
+ filter_key=filter_key,
32
+ )
33
+ # add in algo hypers based on dataset
34
+ algo_config_modifier = getattr(gpc, f"modify_{algo_name}_config_for_dataset")
35
+ config = algo_config_modifier(
36
+ config=config,
37
+ task_name=task_name,
38
+ dataset_type=dataset_type,
39
+ hdf5_type=hdf5_type,
40
+ )
41
+ return config
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/common/timestamp_accumulator.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Tuple, Optional, Dict
2
+ import math
3
+ import numpy as np
4
+
5
+
6
+ def get_accumulate_timestamp_idxs(
7
+ timestamps: List[float],
8
+ start_time: float,
9
+ dt: float,
10
+ eps: float = 1e-5,
11
+ next_global_idx: Optional[int] = 0,
12
+ allow_negative=False,
13
+ ) -> Tuple[List[int], List[int], int]:
14
+ """
15
+ For each dt window, choose the first timestamp in the window.
16
+ Assumes timestamps sorted. One timestamp might be chosen multiple times due to dropped frames.
17
+ next_global_idx should start at 0 normally, and then use the returned next_global_idx.
18
+ However, when overwiting previous values are desired, set last_global_idx to None.
19
+
20
+ Returns:
21
+ local_idxs: which index in the given timestamps array to chose from
22
+ global_idxs: the global index of each chosen timestamp
23
+ next_global_idx: used for next call.
24
+ """
25
+ local_idxs = list()
26
+ global_idxs = list()
27
+ for local_idx, ts in enumerate(timestamps):
28
+ # add eps * dt to timestamps so that when ts == start_time + k * dt
29
+ # is always recorded as kth element (avoiding floating point errors)
30
+ global_idx = math.floor((ts - start_time) / dt + eps)
31
+ if (not allow_negative) and (global_idx < 0):
32
+ continue
33
+ if next_global_idx is None:
34
+ next_global_idx = global_idx
35
+
36
+ n_repeats = max(0, global_idx - next_global_idx + 1)
37
+ for i in range(n_repeats):
38
+ local_idxs.append(local_idx)
39
+ global_idxs.append(next_global_idx + i)
40
+ next_global_idx += n_repeats
41
+ return local_idxs, global_idxs, next_global_idx
42
+
43
+
44
+ def align_timestamps(
45
+ timestamps: List[float],
46
+ target_global_idxs: List[int],
47
+ start_time: float,
48
+ dt: float,
49
+ eps: float = 1e-5,
50
+ ):
51
+ if isinstance(target_global_idxs, np.ndarray):
52
+ target_global_idxs = target_global_idxs.tolist()
53
+ assert len(target_global_idxs) > 0
54
+
55
+ local_idxs, global_idxs, _ = get_accumulate_timestamp_idxs(
56
+ timestamps=timestamps,
57
+ start_time=start_time,
58
+ dt=dt,
59
+ eps=eps,
60
+ next_global_idx=target_global_idxs[0],
61
+ allow_negative=True,
62
+ )
63
+ if len(global_idxs) > len(target_global_idxs):
64
+ # if more steps available, truncate
65
+ global_idxs = global_idxs[:len(target_global_idxs)]
66
+ local_idxs = local_idxs[:len(target_global_idxs)]
67
+
68
+ if len(global_idxs) == 0:
69
+ import pdb
70
+
71
+ pdb.set_trace()
72
+
73
+ for i in range(len(target_global_idxs) - len(global_idxs)):
74
+ # if missing, repeat
75
+ local_idxs.append(len(timestamps) - 1)
76
+ global_idxs.append(global_idxs[-1] + 1)
77
+ assert global_idxs == target_global_idxs
78
+ assert len(local_idxs) == len(global_idxs)
79
+ return local_idxs
80
+
81
+
82
+ class TimestampObsAccumulator:
83
+
84
+ def __init__(self, start_time: float, dt: float, eps: float = 1e-5):
85
+ self.start_time = start_time
86
+ self.dt = dt
87
+ self.eps = eps
88
+ self.obs_buffer = dict()
89
+ self.timestamp_buffer = None
90
+ self.next_global_idx = 0
91
+
92
+ def __len__(self):
93
+ return self.next_global_idx
94
+
95
+ @property
96
+ def data(self):
97
+ if self.timestamp_buffer is None:
98
+ return dict()
99
+ result = dict()
100
+ for key, value in self.obs_buffer.items():
101
+ result[key] = value[:len(self)]
102
+ return result
103
+
104
+ @property
105
+ def actual_timestamps(self):
106
+ if self.timestamp_buffer is None:
107
+ return np.array([])
108
+ return self.timestamp_buffer[:len(self)]
109
+
110
+ @property
111
+ def timestamps(self):
112
+ if self.timestamp_buffer is None:
113
+ return np.array([])
114
+ return self.start_time + np.arange(len(self)) * self.dt
115
+
116
+ def put(self, data: Dict[str, np.ndarray], timestamps: np.ndarray):
117
+ """
118
+ data:
119
+ key: T,*
120
+ """
121
+
122
+ local_idxs, global_idxs, self.next_global_idx = get_accumulate_timestamp_idxs(
123
+ timestamps=timestamps,
124
+ start_time=self.start_time,
125
+ dt=self.dt,
126
+ eps=self.eps,
127
+ next_global_idx=self.next_global_idx,
128
+ )
129
+
130
+ if len(global_idxs) > 0:
131
+ if self.timestamp_buffer is None:
132
+ # first allocation
133
+ self.obs_buffer = dict()
134
+ for key, value in data.items():
135
+ self.obs_buffer[key] = np.zeros_like(value)
136
+ self.timestamp_buffer = np.zeros((len(timestamps), ), dtype=np.float64)
137
+
138
+ this_max_size = global_idxs[-1] + 1
139
+ if this_max_size > len(self.timestamp_buffer):
140
+ # reallocate
141
+ new_size = max(this_max_size, len(self.timestamp_buffer) * 2)
142
+ for key in list(self.obs_buffer.keys()):
143
+ new_shape = (new_size, ) + self.obs_buffer[key].shape[1:]
144
+ self.obs_buffer[key] = np.resize(self.obs_buffer[key], new_shape)
145
+ self.timestamp_buffer = np.resize(self.timestamp_buffer, (new_size))
146
+
147
+ # write data
148
+ for key, value in self.obs_buffer.items():
149
+ value[global_idxs] = data[key][local_idxs]
150
+ self.timestamp_buffer[global_idxs] = timestamps[local_idxs]
151
+
152
+
153
+ class TimestampActionAccumulator:
154
+
155
+ def __init__(self, start_time: float, dt: float, eps: float = 1e-5):
156
+ """
157
+ Different from Obs accumulator, the action accumulator
158
+ allows overwriting previous values.
159
+ """
160
+ self.start_time = start_time
161
+ self.dt = dt
162
+ self.eps = eps
163
+ self.action_buffer = None
164
+ self.timestamp_buffer = None
165
+ self.size = 0
166
+
167
+ def __len__(self):
168
+ return self.size
169
+
170
+ @property
171
+ def actions(self):
172
+ if self.action_buffer is None:
173
+ return np.array([])
174
+ return self.action_buffer[:len(self)]
175
+
176
+ @property
177
+ def actual_timestamps(self):
178
+ if self.timestamp_buffer is None:
179
+ return np.array([])
180
+ return self.timestamp_buffer[:len(self)]
181
+
182
+ @property
183
+ def timestamps(self):
184
+ if self.timestamp_buffer is None:
185
+ return np.array([])
186
+ return self.start_time + np.arange(len(self)) * self.dt
187
+
188
+ def put(self, actions: np.ndarray, timestamps: np.ndarray):
189
+ """
190
+ Note: timestamps is the time when the action will be issued,
191
+ not when the action will be completed (target_timestamp)
192
+ """
193
+
194
+ local_idxs, global_idxs, _ = get_accumulate_timestamp_idxs(
195
+ timestamps=timestamps,
196
+ start_time=self.start_time,
197
+ dt=self.dt,
198
+ eps=self.eps,
199
+ # allows overwriting previous actions
200
+ next_global_idx=None,
201
+ )
202
+
203
+ if len(global_idxs) > 0:
204
+ if self.timestamp_buffer is None:
205
+ # first allocation
206
+ self.action_buffer = np.zeros_like(actions)
207
+ self.timestamp_buffer = np.zeros((len(actions), ), dtype=np.float64)
208
+
209
+ this_max_size = global_idxs[-1] + 1
210
+ if this_max_size > len(self.timestamp_buffer):
211
+ # reallocate
212
+ new_size = max(this_max_size, len(self.timestamp_buffer) * 2)
213
+ new_shape = (new_size, ) + self.action_buffer.shape[1:]
214
+ self.action_buffer = np.resize(self.action_buffer, new_shape)
215
+ self.timestamp_buffer = np.resize(self.timestamp_buffer, (new_size, ))
216
+
217
+ # potentially rewrite old data (as expected)
218
+ self.action_buffer[global_idxs] = actions[local_idxs]
219
+ self.timestamp_buffer[global_idxs] = timestamps[local_idxs]
220
+ self.size = max(self.size, this_max_size)
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/env_runner/dp_runner.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ from collections import deque
4
+
5
+ from diffusion_policy.common.pytorch_util import dict_apply
6
+ from diffusion_policy.policy.base_image_policy import BaseImagePolicy
7
+
8
+ class DPRunner:
9
+
10
+ def __init__(
11
+ self,
12
+ eval_episodes=20,
13
+ max_steps=300,
14
+ n_obs_steps=3,
15
+ n_action_steps=8,
16
+ fps=10,
17
+ crf=22,
18
+ tqdm_interval_sec=5.0,
19
+ task_name=None,
20
+ ):
21
+ self.task_name = task_name
22
+ self.eval_episodes = eval_episodes
23
+ self.fps = fps
24
+ self.crf = crf
25
+ self.n_obs_steps = n_obs_steps
26
+ self.n_action_steps = n_action_steps
27
+ self.max_steps = max_steps
28
+ self.tqdm_interval_sec = tqdm_interval_sec
29
+
30
+ self.obs_list = [deque(maxlen=n_obs_steps + 1) for _ in range(100)] # TODO
31
+
32
+ def stack_last_n_obs(self, all_obs, n_steps):
33
+ assert len(all_obs) > 0
34
+ all_obs = list(all_obs)
35
+ if isinstance(all_obs[0], np.ndarray):
36
+ result = np.zeros((n_steps, ) + all_obs[-1].shape, dtype=all_obs[-1].dtype)
37
+ start_idx = -min(n_steps, len(all_obs))
38
+ result[start_idx:] = np.array(all_obs[start_idx:])
39
+ if n_steps > len(all_obs):
40
+ # pad
41
+ result[:start_idx] = result[start_idx]
42
+ elif isinstance(all_obs[0], torch.Tensor):
43
+ result = torch.zeros((n_steps, ) + all_obs[-1].shape, dtype=all_obs[-1].dtype)
44
+ start_idx = -min(n_steps, len(all_obs))
45
+ result[start_idx:] = torch.stack(all_obs[start_idx:])
46
+ if n_steps > len(all_obs):
47
+ # pad
48
+ result[:start_idx] = result[start_idx]
49
+ else:
50
+ raise RuntimeError(f"Unsupported obs type {type(all_obs[0])}")
51
+ return result
52
+
53
+ def reset_obs(self):
54
+ for q in self.obs_list:
55
+ q.clear()
56
+
57
+ def update_obs(self, current_obs_list, env_idx_list):
58
+ for env_idx, current_obs in zip(env_idx_list, current_obs_list):
59
+ self.obs_list[env_idx].append(current_obs)
60
+
61
+ def get_n_steps_obs(self, env_idx_list):
62
+ result_list = []
63
+ for env_idx in env_idx_list:
64
+ result = dict()
65
+ for key in self.obs_list[env_idx][0].keys():
66
+ result[key] = self.stack_last_n_obs([obs[key] for obs in self.obs_list[env_idx]], self.n_obs_steps)
67
+ result_list.append(result)
68
+ return result_list
69
+
70
+ def get_action(self, policy: BaseImagePolicy, env_idx_list):
71
+ device = policy.device
72
+ obs_list = self.get_n_steps_obs(env_idx_list)
73
+
74
+ # device transfer
75
+
76
+ obs_list_numpy = [
77
+ dict_apply(obs, lambda x: torch.from_numpy(x).to(device=device))
78
+ for obs in obs_list
79
+ ]
80
+
81
+ with torch.no_grad():
82
+ obs_dict_input = {}
83
+ obs_dict_input["head_cam"] = torch.stack(
84
+ [obs_torch["head_cam"] for obs_torch in obs_list_numpy], dim=0
85
+ )
86
+ obs_dict_input["left_cam"] = torch.stack(
87
+ [obs_torch["left_cam"] for obs_torch in obs_list_numpy], dim=0
88
+ )
89
+ obs_dict_input["right_cam"] = torch.stack(
90
+ [obs_torch["right_cam"] for obs_torch in obs_list_numpy], dim=0
91
+ )
92
+ obs_dict_input["agent_pos"] = torch.stack(
93
+ [obs_torch["agent_pos"] for obs_torch in obs_list_numpy], dim=0
94
+ )
95
+
96
+ action_dict = policy.predict_action(obs_dict_input)
97
+
98
+ np_action_dict = dict_apply(action_dict, lambda x: x.detach().cpu().numpy())
99
+ actions = np_action_dict["action"][:, :self.n_action_steps]
100
+
101
+ return actions
real_inference/source/XPolicyLab/policy/DP/diffusion_policy/process_data.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import glob
3
+ import numpy as np
4
+ import zarr
5
+ import shutil
6
+ import argparse
7
+ import cv2
8
+ from XPolicyLab.utils.load_file import load_hdf5
9
+ from XPolicyLab.utils.process_data import pack_robot_state, get_robot_action_dim_info, decode_image_bit
10
+
11
+ def main():
12
+ parser = argparse.ArgumentParser(description="Process some episodes.")
13
+ parser.add_argument("bench_name", type=str, help="The name of the benchmark (e.g., RoboDojo)",)
14
+ parser.add_argument("ckpt_name", type=str, help="Run name; also selects raw task dir under data/<bench>/",)
15
+ parser.add_argument("env_cfg_type", type=str, help="The name of the environment config",)
16
+ parser.add_argument("action_type", type=str, help="The type of action to process (e.g., joint)",)
17
+ parser.add_argument("expert_data_num", type=int, nargs="?", default=None,
18
+ help="Optional number of episodes to process; defaults to all episodes.",)
19
+ args = parser.parse_args()
20
+
21
+ bench_name = args.bench_name
22
+ ckpt_name = args.ckpt_name
23
+ env_cfg_type = args.env_cfg_type
24
+ expert_data_num = args.expert_data_num
25
+ action_type = args.action_type
26
+ load_data_dir = os.path.join("../../../data", str(bench_name), str(ckpt_name), str(env_cfg_type))
27
+
28
+ robot_action_dim_info = get_robot_action_dim_info(env_cfg_type)
29
+
30
+ available_episodes = len(glob.glob(os.path.join(load_data_dir, "data", "episode_*.hdf5")))
31
+ if expert_data_num is None:
32
+ expert_data_num = available_episodes
33
+ assert expert_data_num <= available_episodes, (
34
+ f"Requested {expert_data_num} episodes but only {available_episodes} available in {load_data_dir}")
35
+
36
+ frame_count = 0
37
+
38
+ save_dir = f"./data/{bench_name}-{ckpt_name}-{env_cfg_type}-{action_type}.zarr"
39
+
40
+ if os.path.exists(save_dir):
41
+ shutil.rmtree(save_dir)
42
+
43
+ current_episode = 0
44
+
45
+ zarr_root = zarr.group(save_dir)
46
+ zarr_data = zarr_root.create_group("data")
47
+ zarr_meta = zarr_root.create_group("meta")
48
+
49
+ head_camera_arrays, left_camera_arrays, right_camera_arrays = [], [], []
50
+ episode_ends_arrays, action_arrays, state_arrays = ([], [], [],)
51
+
52
+ while current_episode < expert_data_num:
53
+ print(f"DP: processing episode: {current_episode + 1} / {expert_data_num}", end="\r")
54
+
55
+ load_path = os.path.join(load_data_dir, f"data/episode_{current_episode:07d}.hdf5")
56
+ data = load_hdf5(load_path)
57
+
58
+ state_all = pack_robot_state(data, action_type, robot_action_dim_info, source_type="dataset", state_type="state")
59
+ action_all = pack_robot_state(data, action_type, robot_action_dim_info, source_type="dataset", state_type="action")
60
+
61
+ for j in range(0, state_all.shape[0]):
62
+ head_img_bit = data['vision']['cam_head']['colors'][j]
63
+ left_img_bit = data['vision']['cam_left_wrist']['colors'][j]
64
+ right_img_bit = data['vision']['cam_right_wrist']['colors'][j]
65
+
66
+ state, action = state_all[j], action_all[j]
67
+
68
+ head_img = decode_image_bit(head_img_bit)
69
+ assert head_img.ndim == 3 and head_img.shape[-1] == 3, f"Expected HxWx3, got {head_img.shape}"
70
+ head_img = cv2.resize(head_img, (320, 240), interpolation=cv2.INTER_AREA) # (W, H)
71
+ assert head_img.shape == (240, 320, 3)
72
+
73
+ left_img = decode_image_bit(left_img_bit)
74
+ assert left_img.ndim == 3 and left_img.shape[-1] == 3, f"Expected HxWx3, got {left_img.shape}"
75
+ left_img = cv2.resize(left_img, (320, 240), interpolation=cv2.INTER_AREA) # (W, H)
76
+ assert left_img.shape == (240, 320, 3)
77
+
78
+ right_img = decode_image_bit(right_img_bit)
79
+ assert right_img.ndim == 3 and right_img.shape[-1] == 3, f"Expected HxWx3, got {right_img.shape}"
80
+ right_img = cv2.resize(right_img, (320, 240), interpolation=cv2.INTER_AREA) # (W, H)
81
+ assert right_img.shape == (240, 320, 3)
82
+
83
+ head_camera_arrays.append(head_img)
84
+ left_camera_arrays.append(left_img)
85
+ right_camera_arrays.append(right_img)
86
+ state_arrays.append(state)
87
+ action_arrays.append(action)
88
+
89
+ current_episode += 1
90
+ frame_count += state_all.shape[0]
91
+ episode_ends_arrays.append(frame_count)
92
+
93
+ print()
94
+ episode_ends_arrays = np.array(episode_ends_arrays)
95
+ action_arrays = np.array(action_arrays)
96
+ state_arrays = np.array(state_arrays)
97
+
98
+ head_camera_arrays = np.array(head_camera_arrays)
99
+ head_camera_arrays = np.moveaxis(head_camera_arrays, -1, 1) # NHWC -> NCHW
100
+
101
+ left_camera_arrays = np.array(left_camera_arrays)
102
+ left_camera_arrays = np.moveaxis(left_camera_arrays, -1, 1) # NHWC -> NCHW
103
+
104
+ right_camera_arrays = np.array(right_camera_arrays)
105
+ right_camera_arrays = np.moveaxis(right_camera_arrays, -1, 1) # NHWC -> NCHW
106
+
107
+ compressor = zarr.Blosc(cname="zstd", clevel=3, shuffle=1)
108
+ action_chunk_size = (100, action_arrays.shape[1])
109
+ state_chunk_size = (100, state_arrays.shape[1])
110
+ head_camera_chunk_size = (100, *head_camera_arrays.shape[1:])
111
+ left_camera_chunk_size = (100, *left_camera_arrays.shape[1:])
112
+ right_camera_chunk_size = (100, *right_camera_arrays.shape[1:])
113
+
114
+ zarr_data.create_dataset("head_camera", data=head_camera_arrays, chunks=head_camera_chunk_size, overwrite=True, compressor=compressor,)
115
+ zarr_data.create_dataset("left_camera", data=left_camera_arrays, chunks=left_camera_chunk_size, overwrite=True, compressor=compressor,)
116
+ zarr_data.create_dataset("right_camera", data=right_camera_arrays, chunks=right_camera_chunk_size, overwrite=True, compressor=compressor,)
117
+ zarr_data.create_dataset("state", data=state_arrays, chunks=state_chunk_size, dtype="float32", overwrite=True, compressor=compressor,)
118
+ zarr_data.create_dataset("action", data=action_arrays, chunks=action_chunk_size,dtype="float32", overwrite=True, compressor=compressor,)
119
+ zarr_meta.create_dataset("episode_ends", data=episode_ends_arrays, dtype="int64", overwrite=True, compressor=compressor,)
120
+
121
+ if __name__ == "__main__":
122
+ main()
real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/pyproject.toml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "openpi-client"
3
+ version = "0.1.0"
4
+ requires-python = ">=3.7"
5
+ dependencies = [
6
+ "dm-tree>=0.1.8",
7
+ "msgpack>=1.0.5",
8
+ "numpy>=1.22.4,<2.0.0",
9
+ "pillow>=9.0.0",
10
+ "tree>=0.2.4",
11
+ "websockets>=11.0",
12
+ ]
13
+
14
+ [build-system]
15
+ requires = ["hatchling"]
16
+ build-backend = "hatchling.build"
17
+
18
+ [tool.uv]
19
+ dev-dependencies = ["pytest>=8.3.4"]
20
+
21
+ [tool.ruff]
22
+ line-length = 120
23
+ target-version = "py37"
real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ __version__ = "0.1.0"
real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/action_chunk_broker.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict
2
+
3
+ import numpy as np
4
+ import tree
5
+ from typing_extensions import override
6
+
7
+ from openpi_client import base_policy as _base_policy
8
+
9
+
10
+ class ActionChunkBroker(_base_policy.BasePolicy):
11
+ """Wraps a policy to return action chunks one-at-a-time.
12
+
13
+ Assumes that the first dimension of all action fields is the chunk size.
14
+
15
+ A new inference call to the inner policy is only made when the current
16
+ list of chunks is exhausted.
17
+ """
18
+
19
+ def __init__(self, policy: _base_policy.BasePolicy, action_horizon: int):
20
+ self._policy = policy
21
+ self._action_horizon = action_horizon
22
+ self._cur_step: int = 0
23
+
24
+ self._last_results: Dict[str, np.ndarray] | None = None
25
+
26
+ @override
27
+ def infer(self, obs: Dict) -> Dict: # noqa: UP006
28
+ if self._last_results is None:
29
+ self._last_results = self._policy.infer(obs)
30
+ self._cur_step = 0
31
+
32
+ def slicer(x):
33
+ if isinstance(x, np.ndarray):
34
+ return x[self._cur_step, ...]
35
+ else:
36
+ return x
37
+
38
+ results = tree.map_structure(slicer, self._last_results)
39
+ self._cur_step += 1
40
+
41
+ if self._cur_step >= self._action_horizon:
42
+ self._last_results = None
43
+
44
+ return results
45
+
46
+ @override
47
+ def reset(self) -> None:
48
+ self._policy.reset()
49
+ self._last_results = None
50
+ self._cur_step = 0
real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/base_policy.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ from typing import Dict
3
+
4
+
5
+ class BasePolicy(abc.ABC):
6
+ @abc.abstractmethod
7
+ def infer(self, obs: Dict) -> Dict:
8
+ """Infer actions from observations."""
9
+
10
+ def reset(self) -> None:
11
+ """Reset the policy to its initial state."""
12
+ pass
real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/image_tools.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from PIL import Image
3
+
4
+
5
+ def convert_to_uint8(img: np.ndarray) -> np.ndarray:
6
+ """Converts an image to uint8 if it is a float image.
7
+
8
+ This is important for reducing the size of the image when sending it over the network.
9
+ """
10
+ if np.issubdtype(img.dtype, np.floating):
11
+ img = (255 * img).astype(np.uint8)
12
+ return img
13
+
14
+
15
+ def resize_with_pad(images: np.ndarray, height: int, width: int, method=Image.BILINEAR) -> np.ndarray:
16
+ """Replicates tf.image.resize_with_pad for multiple images using PIL. Resizes a batch of images to a target height.
17
+
18
+ Args:
19
+ images: A batch of images in [..., height, width, channel] format.
20
+ height: The target height of the image.
21
+ width: The target width of the image.
22
+ method: The interpolation method to use. Default is bilinear.
23
+
24
+ Returns:
25
+ The resized images in [..., height, width, channel].
26
+ """
27
+ # If the images are already the correct size, return them as is.
28
+ if images.shape[-3:-1] == (height, width):
29
+ return images
30
+
31
+ original_shape = images.shape
32
+
33
+ images = images.reshape(-1, *original_shape[-3:])
34
+ resized = np.stack([_resize_with_pad_pil(Image.fromarray(im), height, width, method=method) for im in images])
35
+ return resized.reshape(*original_shape[:-3], *resized.shape[-3:])
36
+
37
+
38
+ def _resize_with_pad_pil(image: Image.Image, height: int, width: int, method: int) -> Image.Image:
39
+ """Replicates tf.image.resize_with_pad for one image using PIL. Resizes an image to a target height and
40
+ width without distortion by padding with zeros.
41
+
42
+ Unlike the jax version, note that PIL uses [width, height, channel] ordering instead of [batch, h, w, c].
43
+ """
44
+ cur_width, cur_height = image.size
45
+ if cur_width == width and cur_height == height:
46
+ return image # No need to resize if the image is already the correct size.
47
+
48
+ ratio = max(cur_width / width, cur_height / height)
49
+ resized_height = int(cur_height / ratio)
50
+ resized_width = int(cur_width / ratio)
51
+ resized_image = image.resize((resized_width, resized_height), resample=method)
52
+
53
+ zero_image = Image.new(resized_image.mode, (width, height), 0)
54
+ pad_height = max(0, int((height - resized_height) / 2))
55
+ pad_width = max(0, int((width - resized_width) / 2))
56
+ zero_image.paste(resized_image, (pad_width, pad_height))
57
+ assert zero_image.size == (width, height)
58
+ return zero_image
real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/image_tools_test.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ import openpi_client.image_tools as image_tools
4
+
5
+
6
+ def test_resize_with_pad_shapes():
7
+ # Test case 1: Resize image with larger dimensions
8
+ images = np.zeros((2, 10, 10, 3), dtype=np.uint8) # Input images of shape (batch_size, height, width, channels)
9
+ height = 20
10
+ width = 20
11
+ resized_images = image_tools.resize_with_pad(images, height, width)
12
+ assert resized_images.shape == (2, height, width, 3)
13
+ assert np.all(resized_images == 0)
14
+
15
+ # Test case 2: Resize image with smaller dimensions
16
+ images = np.zeros((3, 30, 30, 3), dtype=np.uint8)
17
+ height = 15
18
+ width = 15
19
+ resized_images = image_tools.resize_with_pad(images, height, width)
20
+ assert resized_images.shape == (3, height, width, 3)
21
+ assert np.all(resized_images == 0)
22
+
23
+ # Test case 3: Resize image with the same dimensions
24
+ images = np.zeros((1, 50, 50, 3), dtype=np.uint8)
25
+ height = 50
26
+ width = 50
27
+ resized_images = image_tools.resize_with_pad(images, height, width)
28
+ assert resized_images.shape == (1, height, width, 3)
29
+ assert np.all(resized_images == 0)
30
+
31
+ # Test case 3: Resize image with odd-numbered padding
32
+ images = np.zeros((1, 256, 320, 3), dtype=np.uint8)
33
+ height = 60
34
+ width = 80
35
+ resized_images = image_tools.resize_with_pad(images, height, width)
36
+ assert resized_images.shape == (1, height, width, 3)
37
+ assert np.all(resized_images == 0)
real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/msgpack_numpy.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adds NumPy array support to msgpack.
2
+
3
+ msgpack is good for (de)serializing data over a network for multiple reasons:
4
+ - msgpack is secure (as opposed to pickle/dill/etc which allow for arbitrary code execution)
5
+ - msgpack is widely used and has good cross-language support
6
+ - msgpack does not require a schema (as opposed to protobuf/flatbuffers/etc) which is convenient in dynamically typed
7
+ languages like Python and JavaScript
8
+ - msgpack is fast and efficient (as opposed to readable formats like JSON/YAML/etc); I found that msgpack was ~4x faster
9
+ than pickle for serializing large arrays using the below strategy
10
+
11
+ The code below is adapted from https://github.com/lebedov/msgpack-numpy. The reason not to use that library directly is
12
+ that it falls back to pickle for object arrays.
13
+ """
14
+
15
+ import functools
16
+
17
+ import msgpack
18
+ import numpy as np
19
+
20
+
21
+ def pack_array(obj):
22
+ if (isinstance(obj, (np.ndarray, np.generic))) and obj.dtype.kind in ("V", "O", "c"):
23
+ raise ValueError(f"Unsupported dtype: {obj.dtype}")
24
+
25
+ if isinstance(obj, np.ndarray):
26
+ return {
27
+ b"__ndarray__": True,
28
+ b"data": obj.tobytes(),
29
+ b"dtype": obj.dtype.str,
30
+ b"shape": obj.shape,
31
+ }
32
+
33
+ if isinstance(obj, np.generic):
34
+ return {
35
+ b"__npgeneric__": True,
36
+ b"data": obj.item(),
37
+ b"dtype": obj.dtype.str,
38
+ }
39
+
40
+ return obj
41
+
42
+
43
+ def unpack_array(obj):
44
+ if b"__ndarray__" in obj:
45
+ return np.ndarray(buffer=obj[b"data"], dtype=np.dtype(obj[b"dtype"]), shape=obj[b"shape"])
46
+
47
+ if b"__npgeneric__" in obj:
48
+ return np.dtype(obj[b"dtype"]).type(obj[b"data"])
49
+
50
+ return obj
51
+
52
+
53
+ Packer = functools.partial(msgpack.Packer, default=pack_array)
54
+ packb = functools.partial(msgpack.packb, default=pack_array)
55
+
56
+ Unpacker = functools.partial(msgpack.Unpacker, object_hook=unpack_array)
57
+ unpackb = functools.partial(msgpack.unpackb, object_hook=unpack_array)
real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/msgpack_numpy_test.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+ import tree
4
+
5
+ from openpi_client import msgpack_numpy
6
+
7
+
8
+ def _check(expected, actual):
9
+ if isinstance(expected, np.ndarray):
10
+ assert expected.shape == actual.shape
11
+ assert expected.dtype == actual.dtype
12
+ assert np.array_equal(expected, actual, equal_nan=expected.dtype.kind == "f")
13
+ else:
14
+ assert expected == actual
15
+
16
+
17
+ @pytest.mark.parametrize(
18
+ "data",
19
+ [
20
+ 1, # int
21
+ 1.0, # float
22
+ "hello", # string
23
+ np.bool_(True), # boolean scalar
24
+ np.array([1, 2, 3])[0], # int scalar
25
+ np.str_("asdf"), # string scalar
26
+ [1, 2, 3], # list
27
+ {"key": "value"}, # dict
28
+ {"key": [1, 2, 3]}, # nested dict
29
+ np.array(1.0), # 0D array
30
+ np.array([1, 2, 3], dtype=np.int32), # 1D integer array
31
+ np.array(["asdf", "qwer"]), # string array
32
+ np.array([True, False]), # boolean array
33
+ np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32), # 2D float array
34
+ np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], dtype=np.int16), # 3D integer array
35
+ np.array([np.nan, np.inf, -np.inf]), # special float values
36
+ {"arr": np.array([1, 2, 3]), "nested": {"arr": np.array([4, 5, 6])}}, # nested dict with arrays
37
+ [np.array([1, 2]), np.array([3, 4])], # list of arrays
38
+ np.zeros((3, 4, 5), dtype=np.float32), # 3D zeros
39
+ np.ones((2, 3), dtype=np.float64), # 2D ones with double precision
40
+ ],
41
+ )
42
+ def test_pack_unpack(data):
43
+ packed = msgpack_numpy.packb(data)
44
+ unpacked = msgpack_numpy.unpackb(packed)
45
+ tree.map_structure(_check, data, unpacked)
real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/runtime/agent.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+
3
+
4
+ class Agent(abc.ABC):
5
+ """An Agent is the thing with agency, i.e. the entity that makes decisions.
6
+
7
+ Agents receive observations about the state of the world, and return actions
8
+ to take in response.
9
+ """
10
+
11
+ @abc.abstractmethod
12
+ def get_action(self, observation: dict) -> dict:
13
+ """Query the agent for the next action."""
14
+
15
+ @abc.abstractmethod
16
+ def reset(self) -> None:
17
+ """Reset the agent to its initial state."""
real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/runtime/agents/policy_agent.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing_extensions import override
2
+
3
+ from openpi_client import base_policy as _base_policy
4
+ from openpi_client.runtime import agent as _agent
5
+
6
+
7
+ class PolicyAgent(_agent.Agent):
8
+ """An agent that uses a policy to determine actions."""
9
+
10
+ def __init__(self, policy: _base_policy.BasePolicy) -> None:
11
+ self._policy = policy
12
+
13
+ @override
14
+ def get_action(self, observation: dict) -> dict:
15
+ return self._policy.infer(observation)
16
+
17
+ def reset(self) -> None:
18
+ self._policy.reset()
real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/runtime/environment.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+
3
+
4
+ class Environment(abc.ABC):
5
+ """An Environment represents the robot and the environment it inhabits.
6
+
7
+ The primary contract of environments is that they can be queried for observations
8
+ about their state, and have actions applied to them to change that state.
9
+ """
10
+
11
+ @abc.abstractmethod
12
+ def reset(self) -> None:
13
+ """Reset the environment to its initial state.
14
+
15
+ This will be called once before starting each episode.
16
+ """
17
+
18
+ @abc.abstractmethod
19
+ def is_episode_complete(self) -> bool:
20
+ """Allow the environment to signal that the episode is complete.
21
+
22
+ This will be called after each step. It should return `True` if the episode is
23
+ complete (either successfully or unsuccessfully), and `False` otherwise.
24
+ """
25
+
26
+ @abc.abstractmethod
27
+ def get_observation(self) -> dict:
28
+ """Query the environment for the current state."""
29
+
30
+ @abc.abstractmethod
31
+ def apply_action(self, action: dict) -> None:
32
+ """Take an action in the environment."""
real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/runtime/runtime.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import threading
3
+ import time
4
+
5
+ from openpi_client.runtime import agent as _agent
6
+ from openpi_client.runtime import environment as _environment
7
+ from openpi_client.runtime import subscriber as _subscriber
8
+
9
+
10
+ class Runtime:
11
+ """The core module orchestrating interactions between key components of the system."""
12
+
13
+ def __init__(
14
+ self,
15
+ environment: _environment.Environment,
16
+ agent: _agent.Agent,
17
+ subscribers: list[_subscriber.Subscriber],
18
+ max_hz: float = 0,
19
+ num_episodes: int = 1,
20
+ max_episode_steps: int = 0,
21
+ ) -> None:
22
+ self._environment = environment
23
+ self._agent = agent
24
+ self._subscribers = subscribers
25
+ self._max_hz = max_hz
26
+ self._num_episodes = num_episodes
27
+ self._max_episode_steps = max_episode_steps
28
+
29
+ self._in_episode = False
30
+ self._episode_steps = 0
31
+
32
+ def run(self) -> None:
33
+ """Runs the runtime loop continuously until stop() is called or the environment is done."""
34
+ for _ in range(self._num_episodes):
35
+ self._run_episode()
36
+
37
+ # Final reset, this is important for real environments to move the robot to its home position.
38
+ self._environment.reset()
39
+
40
+ def run_in_new_thread(self) -> threading.Thread:
41
+ """Runs the runtime loop in a new thread."""
42
+ thread = threading.Thread(target=self.run)
43
+ thread.start()
44
+ return thread
45
+
46
+ def mark_episode_complete(self) -> None:
47
+ """Marks the end of an episode."""
48
+ self._in_episode = False
49
+
50
+ def _run_episode(self) -> None:
51
+ """Runs a single episode."""
52
+ logging.info("Starting episode...")
53
+ self._environment.reset()
54
+ self._agent.reset()
55
+ for subscriber in self._subscribers:
56
+ subscriber.on_episode_start()
57
+
58
+ self._in_episode = True
59
+ self._episode_steps = 0
60
+ step_time = 1 / self._max_hz if self._max_hz > 0 else 0
61
+ last_step_time = time.time()
62
+
63
+ while self._in_episode:
64
+ self._step()
65
+ self._episode_steps += 1
66
+
67
+ # Sleep to maintain the desired frame rate
68
+ now = time.time()
69
+ dt = now - last_step_time
70
+ if dt < step_time:
71
+ time.sleep(step_time - dt)
72
+ last_step_time = time.time()
73
+ else:
74
+ last_step_time = now
75
+
76
+ logging.info("Episode completed.")
77
+ for subscriber in self._subscribers:
78
+ subscriber.on_episode_end()
79
+
80
+ def _step(self) -> None:
81
+ """A single step of the runtime loop."""
82
+ observation = self._environment.get_observation()
83
+ action = self._agent.get_action(observation)
84
+ self._environment.apply_action(action)
85
+
86
+ for subscriber in self._subscribers:
87
+ subscriber.on_step(observation, action)
88
+
89
+ if self._environment.is_episode_complete() or (
90
+ self._max_episode_steps > 0 and self._episode_steps >= self._max_episode_steps
91
+ ):
92
+ self.mark_episode_complete()
real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/runtime/subscriber.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+
3
+
4
+ class Subscriber(abc.ABC):
5
+ """Subscribes to events in the runtime.
6
+
7
+ Subscribers can be used to save data, visualize, etc.
8
+ """
9
+
10
+ @abc.abstractmethod
11
+ def on_episode_start(self) -> None:
12
+ """Called when an episode starts."""
13
+
14
+ @abc.abstractmethod
15
+ def on_step(self, observation: dict, action: dict) -> None:
16
+ """Append a step to the episode."""
17
+
18
+ @abc.abstractmethod
19
+ def on_episode_end(self) -> None:
20
+ """Called when an episode ends."""
real_inference/source/XPolicyLab/policy/Pi_05/openpi/packages/openpi-client/src/openpi_client/websocket_client_policy.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import time
3
+ from typing import Dict, Optional, Tuple
4
+
5
+ from typing_extensions import override
6
+ import websockets.sync.client
7
+
8
+ from openpi_client import base_policy as _base_policy
9
+ from openpi_client import msgpack_numpy
10
+
11
+
12
+ class WebsocketClientPolicy(_base_policy.BasePolicy):
13
+ """Implements the Policy interface by communicating with a server over websocket.
14
+
15
+ See WebsocketPolicyServer for a corresponding server implementation.
16
+ """
17
+
18
+ def __init__(self, host: str = "0.0.0.0", port: Optional[int] = None, api_key: Optional[str] = None) -> None:
19
+ if host.startswith("ws"):
20
+ self._uri = host
21
+ else:
22
+ self._uri = f"ws://{host}"
23
+ if port is not None:
24
+ self._uri += f":{port}"
25
+ self._packer = msgpack_numpy.Packer()
26
+ self._api_key = api_key
27
+ self._ws, self._server_metadata = self._wait_for_server()
28
+
29
+ def get_server_metadata(self) -> Dict:
30
+ return self._server_metadata
31
+
32
+ def _wait_for_server(self) -> Tuple[websockets.sync.client.ClientConnection, Dict]:
33
+ logging.info(f"Waiting for server at {self._uri}...")
34
+ while True:
35
+ try:
36
+ headers = {"Authorization": f"Api-Key {self._api_key}"} if self._api_key else None
37
+ conn = websockets.sync.client.connect(
38
+ self._uri, compression=None, max_size=None, additional_headers=headers
39
+ )
40
+ metadata = msgpack_numpy.unpackb(conn.recv())
41
+ return conn, metadata
42
+ except ConnectionRefusedError:
43
+ logging.info("Still waiting for server...")
44
+ time.sleep(5)
45
+
46
+ @override
47
+ def infer(self, obs: Dict) -> Dict: # noqa: UP006
48
+ data = self._packer.pack(obs)
49
+ self._ws.send(data)
50
+ response = self._ws.recv()
51
+ if isinstance(response, str):
52
+ # we're expecting bytes; if the server sends a string, it's an error.
53
+ raise RuntimeError(f"Error in inference server:\n{response}")
54
+ return msgpack_numpy.unpackb(response)
55
+
56
+ @override
57
+ def reset(self) -> None:
58
+ pass
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/model_test.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flax import nnx
2
+ import jax
3
+ import pytest
4
+
5
+ from openpi.models import model as _model
6
+ from openpi.models import pi0_config
7
+ from openpi.models import pi0_fast
8
+ from openpi.shared import download
9
+ from openpi.shared import nnx_utils
10
+
11
+
12
+ def test_pi0_model():
13
+ key = jax.random.key(0)
14
+ config = pi0_config.Pi0Config()
15
+ model = config.create(key)
16
+
17
+ batch_size = 2
18
+ obs, act = config.fake_obs(batch_size), config.fake_act(batch_size)
19
+
20
+ loss = nnx_utils.module_jit(model.compute_loss)(key, obs, act)
21
+ assert loss.shape == (batch_size, config.action_horizon)
22
+
23
+ actions = nnx_utils.module_jit(model.sample_actions)(key, obs, num_steps=10)
24
+ assert actions.shape == (batch_size, model.action_horizon, model.action_dim)
25
+
26
+
27
+ def test_pi0_lora_model():
28
+ key = jax.random.key(0)
29
+ config = pi0_config.Pi0Config(paligemma_variant="gemma_2b_lora")
30
+ model = config.create(key)
31
+
32
+ batch_size = 2
33
+ obs, act = config.fake_obs(batch_size), config.fake_act(batch_size)
34
+
35
+ loss = nnx_utils.module_jit(model.compute_loss)(key, obs, act)
36
+ assert loss.shape == (batch_size, config.action_horizon)
37
+
38
+ actions = nnx_utils.module_jit(model.sample_actions)(key, obs, num_steps=10)
39
+ assert actions.shape == (batch_size, model.action_horizon, model.action_dim)
40
+
41
+
42
+ def test_pi0_fast_model():
43
+ key = jax.random.key(0)
44
+ config = pi0_fast.Pi0FASTConfig()
45
+ model = config.create(key)
46
+
47
+ batch_size = 2
48
+ obs, act = config.fake_obs(batch_size), config.fake_act(batch_size)
49
+
50
+ loss = nnx_utils.module_jit(model.compute_loss)(key, obs, act)
51
+ assert loss.shape == (batch_size,)
52
+
53
+ actions = nnx_utils.module_jit(model.sample_actions)(key, obs)
54
+ assert actions.shape == (batch_size, 256)
55
+
56
+
57
+ def test_pi0_fast_lora_model():
58
+ key = jax.random.key(0)
59
+ config = pi0_fast.Pi0FASTConfig(paligemma_variant="gemma_2b_lora")
60
+ model = config.create(key)
61
+
62
+ batch_size = 2
63
+ obs, act = config.fake_obs(batch_size), config.fake_act(batch_size)
64
+
65
+ loss = nnx_utils.module_jit(model.compute_loss)(key, obs, act)
66
+ assert loss.shape == (batch_size,)
67
+
68
+ actions = nnx_utils.module_jit(model.sample_actions)(key, obs)
69
+ assert actions.shape == (batch_size, 256)
70
+
71
+ lora_filter = nnx_utils.PathRegex(".*lora.*")
72
+ model_state = nnx.state(model)
73
+
74
+ lora_state_elems = list(model_state.filter(lora_filter))
75
+ assert len(lora_state_elems) > 0
76
+
77
+
78
+ @pytest.mark.manual
79
+ def test_model_restore():
80
+ key = jax.random.key(0)
81
+ config = pi0_config.Pi0Config()
82
+
83
+ batch_size = 2
84
+ obs, act = config.fake_obs(batch_size), config.fake_act(batch_size)
85
+
86
+ model = config.load(
87
+ _model.restore_params(download.maybe_download("gs://openpi-assets/checkpoints/pi0_base/params"))
88
+ )
89
+
90
+ loss = model.compute_loss(key, obs, act)
91
+ assert loss.shape == (batch_size, config.action_horizon)
92
+
93
+ actions = model.sample_actions(key, obs, num_steps=10)
94
+ assert actions.shape == (batch_size, model.action_horizon, model.action_dim)
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/pi0.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ import einops
4
+ import flax.nnx as nnx
5
+ import flax.nnx.bridge as nnx_bridge
6
+ import jax
7
+ import jax.numpy as jnp
8
+ from typing_extensions import override
9
+
10
+ from openpi.models import model as _model
11
+ from openpi.models import pi0_config
12
+ import openpi.models.gemma as _gemma
13
+ import openpi.models.siglip as _siglip
14
+ from openpi.shared import array_typing as at
15
+
16
+ logger = logging.getLogger("openpi")
17
+
18
+
19
+ def make_attn_mask(input_mask, mask_ar):
20
+ """Adapted from big_vision.
21
+
22
+ Tokens can attend to valid inputs tokens which have a cumulative mask_ar
23
+ smaller or equal to theirs. This way `mask_ar` bool[?B, N] can be used to
24
+ setup several types of attention, for example:
25
+
26
+ [[1 1 1 1 1 1]]: pure causal attention.
27
+
28
+ [[0 0 0 1 1 1]]: prefix-lm attention. The first 3 tokens can attend between
29
+ themselves and the last 3 tokens have a causal attention. The first
30
+ entry could also be a 1 without changing behaviour.
31
+
32
+ [[1 0 1 0 1 0 0 1 0 0]]: causal attention between 4 blocks. Tokens of a
33
+ block can attend all previous blocks and all tokens on the same block.
34
+
35
+ Args:
36
+ input_mask: bool[B, N] true if its part of the input, false if padding.
37
+ mask_ar: bool[?B, N] mask that's true where previous tokens cannot depend on
38
+ it and false where it shares the same attention mask as the previous token.
39
+ """
40
+ mask_ar = jnp.broadcast_to(mask_ar, input_mask.shape)
41
+ cumsum = jnp.cumsum(mask_ar, axis=1)
42
+ attn_mask = cumsum[:, None, :] <= cumsum[:, :, None]
43
+ valid_mask = input_mask[:, None, :] * input_mask[:, :, None]
44
+ return jnp.logical_and(attn_mask, valid_mask)
45
+
46
+
47
+ @at.typecheck
48
+ def posemb_sincos(
49
+ pos: at.Real[at.Array, " b"], embedding_dim: int, min_period: float, max_period: float
50
+ ) -> at.Float[at.Array, "b {embedding_dim}"]:
51
+ """Computes sine-cosine positional embedding vectors for scalar positions."""
52
+ if embedding_dim % 2 != 0:
53
+ raise ValueError(f"embedding_dim ({embedding_dim}) must be divisible by 2")
54
+
55
+ fraction = jnp.linspace(0.0, 1.0, embedding_dim // 2)
56
+ period = min_period * (max_period / min_period) ** fraction
57
+ sinusoid_input = jnp.einsum(
58
+ "i,j->ij",
59
+ pos,
60
+ 1.0 / period * 2 * jnp.pi,
61
+ precision=jax.lax.Precision.HIGHEST,
62
+ )
63
+ return jnp.concatenate([jnp.sin(sinusoid_input), jnp.cos(sinusoid_input)], axis=-1)
64
+
65
+
66
+ class Pi0(_model.BaseModel):
67
+ def __init__(self, config: pi0_config.Pi0Config, rngs: nnx.Rngs):
68
+ super().__init__(config.action_dim, config.action_horizon, config.max_token_len)
69
+ self.pi05 = config.pi05
70
+ paligemma_config = _gemma.get_config(config.paligemma_variant)
71
+ action_expert_config = _gemma.get_config(config.action_expert_variant)
72
+ # TODO: rewrite gemma in NNX. For now, use bridge.
73
+ llm = nnx_bridge.ToNNX(
74
+ _gemma.Module(
75
+ configs=[paligemma_config, action_expert_config],
76
+ embed_dtype=config.dtype,
77
+ adarms=config.pi05,
78
+ )
79
+ )
80
+ llm.lazy_init(rngs=rngs, method="init", use_adarms=[False, True] if config.pi05 else [False, False])
81
+ img = nnx_bridge.ToNNX(
82
+ _siglip.Module(
83
+ num_classes=paligemma_config.width,
84
+ variant="So400m/14",
85
+ pool_type="none",
86
+ scan=True,
87
+ dtype_mm=config.dtype,
88
+ )
89
+ )
90
+ img.lazy_init(next(iter(config.fake_obs().images.values())), train=False, rngs=rngs)
91
+ self.PaliGemma = nnx.Dict(llm=llm, img=img)
92
+ self.action_in_proj = nnx.Linear(config.action_dim, action_expert_config.width, rngs=rngs)
93
+ if config.pi05:
94
+ self.time_mlp_in = nnx.Linear(action_expert_config.width, action_expert_config.width, rngs=rngs)
95
+ self.time_mlp_out = nnx.Linear(action_expert_config.width, action_expert_config.width, rngs=rngs)
96
+ else:
97
+ self.state_proj = nnx.Linear(config.action_dim, action_expert_config.width, rngs=rngs)
98
+ self.action_time_mlp_in = nnx.Linear(2 * action_expert_config.width, action_expert_config.width, rngs=rngs)
99
+ self.action_time_mlp_out = nnx.Linear(action_expert_config.width, action_expert_config.width, rngs=rngs)
100
+ self.action_out_proj = nnx.Linear(action_expert_config.width, config.action_dim, rngs=rngs)
101
+
102
+ # This attribute gets automatically set by model.train() and model.eval().
103
+ self.deterministic = True
104
+
105
+ @at.typecheck
106
+ def embed_prefix(
107
+ self, obs: _model.Observation
108
+ ) -> tuple[at.Float[at.Array, "b s emb"], at.Bool[at.Array, "b s"], at.Bool[at.Array, " s"]]:
109
+ input_mask = []
110
+ ar_mask = []
111
+ tokens = []
112
+ # embed images
113
+ for name in obs.images:
114
+ image_tokens, _ = self.PaliGemma.img(obs.images[name], train=False)
115
+
116
+ tokens.append(image_tokens)
117
+ input_mask.append(
118
+ einops.repeat(
119
+ obs.image_masks[name],
120
+ "b -> b s",
121
+ s=image_tokens.shape[1],
122
+ )
123
+ )
124
+ # image tokens attend to each other
125
+ ar_mask += [False] * image_tokens.shape[1]
126
+
127
+ # add language (aka tokenized inputs)
128
+ if obs.tokenized_prompt is not None:
129
+ tokenized_inputs = self.PaliGemma.llm(obs.tokenized_prompt, method="embed")
130
+ tokens.append(tokenized_inputs)
131
+ input_mask.append(obs.tokenized_prompt_mask)
132
+ # full attention between image and language inputs
133
+ ar_mask += [False] * tokenized_inputs.shape[1]
134
+ tokens = jnp.concatenate(tokens, axis=1)
135
+ input_mask = jnp.concatenate(input_mask, axis=1)
136
+ ar_mask = jnp.array(ar_mask)
137
+ return tokens, input_mask, ar_mask
138
+
139
+ @at.typecheck
140
+ def embed_suffix(
141
+ self, obs: _model.Observation, noisy_actions: _model.Actions, timestep: at.Float[at.Array, " b"]
142
+ ) -> tuple[
143
+ at.Float[at.Array, "b s emb"],
144
+ at.Bool[at.Array, "b s"],
145
+ at.Bool[at.Array, " s"],
146
+ at.Float[at.Array, "b emb"] | None,
147
+ ]:
148
+ input_mask = []
149
+ ar_mask = []
150
+ tokens = []
151
+ if not self.pi05:
152
+ # add a single state token
153
+ state_token = self.state_proj(obs.state)[:, None, :]
154
+ tokens.append(state_token)
155
+ input_mask.append(jnp.ones((obs.state.shape[0], 1), dtype=jnp.bool_))
156
+ # image/language inputs do not attend to state or actions
157
+ ar_mask += [True]
158
+
159
+ action_tokens = self.action_in_proj(noisy_actions)
160
+ # embed timestep using sine-cosine positional encoding with sensitivity in the range [0, 1]
161
+ time_emb = posemb_sincos(timestep, self.action_in_proj.out_features, min_period=4e-3, max_period=4.0)
162
+ if self.pi05:
163
+ # time MLP (for adaRMS)
164
+ time_emb = self.time_mlp_in(time_emb)
165
+ time_emb = nnx.swish(time_emb)
166
+ time_emb = self.time_mlp_out(time_emb)
167
+ time_emb = nnx.swish(time_emb)
168
+ action_expert_tokens = action_tokens
169
+ adarms_cond = time_emb
170
+ else:
171
+ # mix timestep + action information using an MLP (no adaRMS)
172
+ time_tokens = einops.repeat(time_emb, "b emb -> b s emb", s=self.action_horizon)
173
+ action_time_tokens = jnp.concatenate([action_tokens, time_tokens], axis=-1)
174
+ action_time_tokens = self.action_time_mlp_in(action_time_tokens)
175
+ action_time_tokens = nnx.swish(action_time_tokens)
176
+ action_time_tokens = self.action_time_mlp_out(action_time_tokens)
177
+ action_expert_tokens = action_time_tokens
178
+ adarms_cond = None
179
+ tokens.append(action_expert_tokens)
180
+ input_mask.append(jnp.ones(action_expert_tokens.shape[:2], dtype=jnp.bool_))
181
+ # image/language/state inputs do not attend to action tokens
182
+ ar_mask += [True] + ([False] * (self.action_horizon - 1))
183
+ tokens = jnp.concatenate(tokens, axis=1)
184
+ input_mask = jnp.concatenate(input_mask, axis=1)
185
+ ar_mask = jnp.array(ar_mask)
186
+ return tokens, input_mask, ar_mask, adarms_cond
187
+
188
+ @override
189
+ def compute_loss(
190
+ self, rng: at.KeyArrayLike, observation: _model.Observation, actions: _model.Actions, *, train: bool = False
191
+ ) -> at.Float[at.Array, "*b ah"]:
192
+ preprocess_rng, noise_rng, time_rng = jax.random.split(rng, 3)
193
+ observation = _model.preprocess_observation(preprocess_rng, observation, train=train)
194
+
195
+ batch_shape = actions.shape[:-2]
196
+ noise = jax.random.normal(noise_rng, actions.shape)
197
+ time = jax.random.beta(time_rng, 1.5, 1, batch_shape) * 0.999 + 0.001
198
+ time_expanded = time[..., None, None]
199
+ x_t = time_expanded * noise + (1 - time_expanded) * actions
200
+ u_t = noise - actions
201
+
202
+ # one big forward pass of prefix + suffix at once
203
+ prefix_tokens, prefix_mask, prefix_ar_mask = self.embed_prefix(observation)
204
+ suffix_tokens, suffix_mask, suffix_ar_mask, adarms_cond = self.embed_suffix(observation, x_t, time)
205
+ input_mask = jnp.concatenate([prefix_mask, suffix_mask], axis=1)
206
+ ar_mask = jnp.concatenate([prefix_ar_mask, suffix_ar_mask], axis=0)
207
+ attn_mask = make_attn_mask(input_mask, ar_mask)
208
+ positions = jnp.cumsum(input_mask, axis=1) - 1
209
+ (prefix_out, suffix_out), _ = self.PaliGemma.llm(
210
+ [prefix_tokens, suffix_tokens], mask=attn_mask, positions=positions, adarms_cond=[None, adarms_cond]
211
+ )
212
+ v_t = self.action_out_proj(suffix_out[:, -self.action_horizon :])
213
+
214
+ return jnp.mean(jnp.square(v_t - u_t), axis=-1)
215
+
216
+ @override
217
+ def sample_actions(
218
+ self,
219
+ rng: at.KeyArrayLike,
220
+ observation: _model.Observation,
221
+ *,
222
+ num_steps: int | at.Int[at.Array, ""] = 10,
223
+ noise: at.Float[at.Array, "b ah ad"] | None = None,
224
+ ) -> _model.Actions:
225
+ observation = _model.preprocess_observation(None, observation, train=False)
226
+ # note that we use the convention more common in diffusion literature, where t=1 is noise and t=0 is the target
227
+ # distribution. yes, this is the opposite of the pi0 paper, and I'm sorry.
228
+ dt = -1.0 / num_steps
229
+ batch_size = observation.state.shape[0]
230
+ if noise is None:
231
+ noise = jax.random.normal(rng, (batch_size, self.action_horizon, self.action_dim))
232
+
233
+ # first fill KV cache with a forward pass of the prefix
234
+ prefix_tokens, prefix_mask, prefix_ar_mask = self.embed_prefix(observation)
235
+ prefix_attn_mask = make_attn_mask(prefix_mask, prefix_ar_mask)
236
+ positions = jnp.cumsum(prefix_mask, axis=1) - 1
237
+ _, kv_cache = self.PaliGemma.llm([prefix_tokens, None], mask=prefix_attn_mask, positions=positions)
238
+
239
+ def step(carry):
240
+ x_t, time = carry
241
+ suffix_tokens, suffix_mask, suffix_ar_mask, adarms_cond = self.embed_suffix(
242
+ observation, x_t, jnp.broadcast_to(time, batch_size)
243
+ )
244
+ # `suffix_attn_mask` is shape (b, suffix_len, suffix_len) indicating how the suffix tokens can attend to each
245
+ # other
246
+ suffix_attn_mask = make_attn_mask(suffix_mask, suffix_ar_mask)
247
+ # `prefix_attn_mask` is shape (b, suffix_len, prefix_len) indicating how the suffix tokens can attend to the
248
+ # prefix tokens
249
+ prefix_attn_mask = einops.repeat(prefix_mask, "b p -> b s p", s=suffix_tokens.shape[1])
250
+ # `combined_mask` is shape (b, suffix_len, prefix_len + suffix_len) indicating how the suffix tokens (which
251
+ # generate the queries) can attend to the full prefix + suffix sequence (which generates the keys and values)
252
+ full_attn_mask = jnp.concatenate([prefix_attn_mask, suffix_attn_mask], axis=-1)
253
+ assert full_attn_mask.shape == (
254
+ batch_size,
255
+ suffix_tokens.shape[1],
256
+ prefix_tokens.shape[1] + suffix_tokens.shape[1],
257
+ )
258
+ # `positions` is shape (b, suffix_len) indicating the positions of the suffix tokens
259
+ positions = jnp.sum(prefix_mask, axis=-1)[:, None] + jnp.cumsum(suffix_mask, axis=-1) - 1
260
+
261
+ (prefix_out, suffix_out), _ = self.PaliGemma.llm(
262
+ [None, suffix_tokens],
263
+ mask=full_attn_mask,
264
+ positions=positions,
265
+ kv_cache=kv_cache,
266
+ adarms_cond=[None, adarms_cond],
267
+ )
268
+ assert prefix_out is None
269
+ v_t = self.action_out_proj(suffix_out[:, -self.action_horizon :])
270
+
271
+ return x_t + dt * v_t, time + dt
272
+
273
+ def cond(carry):
274
+ x_t, time = carry
275
+ # robust to floating-point error
276
+ return time >= -dt / 2
277
+
278
+ x_0, _ = jax.lax.while_loop(cond, step, (noise, 1.0))
279
+ return x_0
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/pi0_config.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ from typing import TYPE_CHECKING
3
+
4
+ import flax.nnx as nnx
5
+ import jax
6
+ import jax.numpy as jnp
7
+ from typing_extensions import override
8
+
9
+ from openpi.models import model as _model
10
+ import openpi.models.gemma as _gemma
11
+ from openpi.shared import array_typing as at
12
+ import openpi.shared.nnx_utils as nnx_utils
13
+
14
+ if TYPE_CHECKING:
15
+ from openpi.models.pi0 import Pi0
16
+
17
+
18
+ @dataclasses.dataclass(frozen=True)
19
+ class Pi0Config(_model.BaseModelConfig):
20
+ dtype: str = "bfloat16"
21
+ paligemma_variant: _gemma.Variant = "gemma_2b"
22
+ action_expert_variant: _gemma.Variant = "gemma_300m"
23
+
24
+ # Set the model specific defaults.
25
+ action_dim: int = 32
26
+ action_horizon: int = 50
27
+ max_token_len: int = None # type: ignore
28
+ # Pi05 has two differences from Pi0:
29
+ # - the state input is part of the discrete language tokens rather than a continuous input that is part of the suffix
30
+ # - the action expert uses adaRMSNorm to inject the flow matching timestep
31
+ pi05: bool = False
32
+ # This config option is not used directly by the model, but it is read by the ModelTransformFactory.
33
+ discrete_state_input: bool = None # type: ignore
34
+
35
+ pytorch_compile_mode: str | None = "max-autotune"
36
+
37
+ def __post_init__(self):
38
+ if self.max_token_len is None:
39
+ object.__setattr__(self, "max_token_len", 200 if self.pi05 else 48)
40
+ if self.discrete_state_input is None:
41
+ object.__setattr__(self, "discrete_state_input", self.pi05)
42
+ if self.pytorch_compile_mode is not None:
43
+ assert self.pytorch_compile_mode in [
44
+ "default",
45
+ "reduce-overhead",
46
+ "max-autotune",
47
+ "max-autotune-no-cudagraphs",
48
+ ]
49
+
50
+ @property
51
+ @override
52
+ def model_type(self) -> _model.ModelType:
53
+ if self.pi05:
54
+ return _model.ModelType.PI05
55
+ return _model.ModelType.PI0
56
+
57
+ @override
58
+ def create(self, rng: at.KeyArrayLike) -> "Pi0":
59
+ from openpi.models.pi0 import Pi0
60
+
61
+ return Pi0(self, rngs=nnx.Rngs(rng))
62
+
63
+ @override
64
+ def inputs_spec(self, *, batch_size: int = 1) -> tuple[_model.Observation, _model.Actions]:
65
+ image_spec = jax.ShapeDtypeStruct([batch_size, *_model.IMAGE_RESOLUTION, 3], jnp.float32)
66
+ image_mask_spec = jax.ShapeDtypeStruct([batch_size], jnp.bool_)
67
+
68
+ with at.disable_typechecking():
69
+ observation_spec = _model.Observation(
70
+ images={
71
+ "base_0_rgb": image_spec,
72
+ "left_wrist_0_rgb": image_spec,
73
+ "right_wrist_0_rgb": image_spec,
74
+ },
75
+ image_masks={
76
+ "base_0_rgb": image_mask_spec,
77
+ "left_wrist_0_rgb": image_mask_spec,
78
+ "right_wrist_0_rgb": image_mask_spec,
79
+ },
80
+ state=jax.ShapeDtypeStruct([batch_size, self.action_dim], jnp.float32),
81
+ tokenized_prompt=jax.ShapeDtypeStruct([batch_size, self.max_token_len], jnp.int32),
82
+ tokenized_prompt_mask=jax.ShapeDtypeStruct([batch_size, self.max_token_len], bool),
83
+ )
84
+ action_spec = jax.ShapeDtypeStruct([batch_size, self.action_horizon, self.action_dim], jnp.float32)
85
+
86
+ return observation_spec, action_spec
87
+
88
+ def get_freeze_filter(self) -> nnx.filterlib.Filter:
89
+ """Returns the freeze filter based on the model config."""
90
+ filters = []
91
+ has_lora = False
92
+ gemma_params_filter = nnx_utils.PathRegex(".*llm.*")
93
+ action_expert_params_filter = nnx_utils.PathRegex(".*llm.*_1.*")
94
+ if "lora" in self.paligemma_variant:
95
+ filters.append(
96
+ gemma_params_filter,
97
+ )
98
+ if "lora" not in self.action_expert_variant:
99
+ # If only freeze gemma params, exclude action expert params.
100
+ filters.append(
101
+ nnx.Not(action_expert_params_filter),
102
+ )
103
+ has_lora = True
104
+ elif "lora" in self.action_expert_variant:
105
+ filters.append(
106
+ action_expert_params_filter,
107
+ )
108
+ has_lora = True
109
+
110
+ if has_lora:
111
+ # If any lora is used, exclude all lora params.
112
+ filters.append(
113
+ nnx.Not(nnx_utils.PathRegex(".*lora.*")),
114
+ )
115
+ if not filters:
116
+ return nnx.Nothing
117
+ return nnx.All(*filters)
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models/utils/fsq_tokenizer.py ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Any, Literal
3
+
4
+ import chex
5
+ from einops import einops
6
+ from flax import linen as nn
7
+ from flax.linen.module import Module
8
+ from flax.linen.module import compact
9
+ from flax.struct import dataclass
10
+ from flax.typing import Array
11
+ import jax
12
+ import jax.numpy as jnp
13
+
14
+
15
+ class FsqCodebook(nn.Module):
16
+ input_dim: int
17
+ target_codebook_size: int
18
+ codebook_type: Literal["fsq", "lfq"]
19
+
20
+ _bins_per_dim: tuple[int] | None = None
21
+
22
+ @property
23
+ def bins_per_dim(self) -> tuple[int]:
24
+ if self._bins_per_dim is not None:
25
+ return self._bins_per_dim
26
+
27
+ if self.codebook_type == "fsq":
28
+ return self._get_bins_fsq(self.target_codebook_size)
29
+ elif self.codebook_type == "lfq": # noqa: RET505
30
+ return self._get_bins_lfq(self.target_codebook_size)
31
+ elif self.codebook_type == "custom":
32
+ return self._get_bins_custom(self.target_codebook_size)
33
+ else:
34
+ raise ValueError(f"Codebook type {self.codebook_type} not supported.")
35
+
36
+ @property
37
+ def place_values(self) -> jnp.ndarray:
38
+ place_values = [1]
39
+ for b in self.bins_per_dim[:-1]:
40
+ place_values.append(place_values[-1] * b)
41
+ return jnp.array(place_values)
42
+
43
+ @staticmethod
44
+ def _get_bins_fsq(target_codebook_size: int) -> tuple[int]:
45
+ """
46
+ Get bins per dimension based on codebook size, from the original FSQ paper.
47
+ """
48
+ if target_codebook_size == 2**8:
49
+ return (8, 6, 5)
50
+ elif target_codebook_size == 2**10: # noqa: RET505
51
+ return (8, 5, 5, 5)
52
+ elif target_codebook_size == 2**12:
53
+ return (7, 5, 5, 5, 5)
54
+ elif target_codebook_size == 2**14:
55
+ return (8, 8, 8, 6, 5)
56
+ elif target_codebook_size == 2**16:
57
+ return (8, 8, 8, 5, 5, 5)
58
+ else:
59
+ raise ValueError(f"Codebook size {target_codebook_size} not supported.")
60
+
61
+ @staticmethod
62
+ def _get_bins_custom(target_codebook_size: int) -> tuple[int]:
63
+ if target_codebook_size == 2**8:
64
+ return (16, 16)
65
+ elif target_codebook_size == 2**10: # noqa: RET505
66
+ return (32, 32)
67
+ elif target_codebook_size == 2**12:
68
+ return (64, 64)
69
+ elif target_codebook_size == 2**14:
70
+ return (128, 128)
71
+ elif target_codebook_size == 2**16:
72
+ return (256, 256)
73
+ return None
74
+
75
+ @staticmethod
76
+ def _get_bins_lfq(target_codebook_size: int) -> tuple[int]:
77
+ """
78
+ Get bins per dimension according to the Lookup-Free Quantization paper (2 bins per dimension)
79
+ """
80
+ assert target_codebook_size & (target_codebook_size - 1) == 0, "Codebook size should be a power of two for LFQ"
81
+
82
+ return (2,) * int(math.log2(target_codebook_size))
83
+
84
+ def setup(self):
85
+ self.proj_down = nn.Dense(len(self.bins_per_dim))
86
+ self.proj_up = nn.Dense(self.input_dim)
87
+
88
+ def __call__(self, inputs: jnp.ndarray) -> tuple[jnp.ndarray, jnp.ndarray]:
89
+ tokens, z = self.encode(inputs)
90
+ output = self.decode(tokens, z_grad=z)
91
+ return tokens, output
92
+
93
+ def encode(self, inputs: jnp.ndarray) -> tuple[jnp.ndarray, jnp.ndarray]:
94
+ bases = jnp.array(self.bins_per_dim)
95
+
96
+ x = self.proj_down(inputs)
97
+ z = jnp.tanh(x)
98
+
99
+ # Quantize
100
+ digits = jnp.round((z + 1) * (bases - 1) / 2).astype(jnp.int32)
101
+ tokens = self.undigitize(digits)
102
+
103
+ return tokens, z
104
+
105
+ def decode(self, tokens: jnp.ndarray, z_grad: jax.Array | None = None) -> jnp.ndarray:
106
+ bases = jnp.array(self.bins_per_dim)
107
+ digits = self.digitize(tokens)
108
+
109
+ z_q = digits / (bases - 1) * 2 - 1
110
+
111
+ if z_grad is not None:
112
+ chex.assert_equal_shape([z_q, z_grad])
113
+ z_q = jax.lax.stop_gradient(z_q - z_grad) + z_grad
114
+
115
+ return self.proj_up(z_q)
116
+
117
+ def undigitize(self, digits: jnp.ndarray) -> jnp.ndarray:
118
+ return jnp.sum(digits * jnp.array(self.place_values), axis=-1)
119
+
120
+ def digitize(self, tokens: jnp.ndarray) -> jnp.ndarray:
121
+ return (tokens[..., None] // jnp.array(self.place_values)) % jnp.array(self.bins_per_dim)
122
+
123
+ @property
124
+ def vocab_size(self) -> int:
125
+ return math.prod(self.bins_per_dim)
126
+
127
+
128
+ class ResNetDownBlock(nn.Module):
129
+ stride: int = 1
130
+ n_filters: int = 64
131
+ dropout_rate: float = 0.0
132
+ group_size: int = 32
133
+
134
+ @nn.compact
135
+ def __call__(self, x: jnp.ndarray, *, train: bool = True) -> jnp.ndarray:
136
+ skip = x
137
+
138
+ if self.stride > 1 or x.shape[-1] != self.n_filters:
139
+ skip = nn.Conv(self.n_filters, (self.stride,), (self.stride,), "SAME")(skip)
140
+
141
+ x = nn.Conv(self.n_filters, (3,), (self.stride,), "SAME")(x)
142
+ x = nn.GroupNorm(num_groups=self.n_filters // self.group_size)(x)
143
+ x = nn.Dropout(self.dropout_rate)(x, deterministic=not train)
144
+ x = nn.relu(x)
145
+ x = nn.Conv(self.n_filters, (3,), (1,), "SAME")(x)
146
+
147
+ return skip + x
148
+
149
+
150
+ class ResNetUpBlock(nn.Module):
151
+ stride: int = 1
152
+ n_filters: int = 64
153
+ dropout_rate: float = 0.0
154
+ group_size: int = 32
155
+
156
+ @nn.compact
157
+ def __call__(self, x: jnp.ndarray, *, train: bool = True) -> jnp.ndarray:
158
+ skip = x
159
+
160
+ if self.stride > 1:
161
+ skip = nn.ConvTranspose(self.n_filters, (self.stride,), (self.stride,), "SAME")(skip)
162
+
163
+ x = nn.ConvTranspose(self.n_filters, (3,), (self.stride,), "SAME")(x)
164
+ x = nn.GroupNorm(num_groups=self.n_filters // self.group_size)(x)
165
+ x = nn.Dropout(self.dropout_rate)(x, deterministic=not train)
166
+ x = nn.relu(x)
167
+ x = nn.ConvTranspose(self.n_filters, (3,), (1,), "SAME")(x)
168
+
169
+ return skip + x
170
+
171
+
172
+ @dataclass
173
+ class LfqCodebookOutput:
174
+ tokens: jnp.ndarray
175
+ z: jnp.ndarray
176
+ z_q: jnp.ndarray
177
+ token_log_probs: jnp.ndarray
178
+ commit_loss: jnp.ndarray
179
+
180
+
181
+ class LookupFreeQuantization(nn.Module):
182
+ num_dims: int
183
+ latent_dim: int
184
+
185
+ def setup(self):
186
+ self.codebook = jnp.array([-1, 1])
187
+ self.activation = nn.tanh
188
+
189
+ self.project_down = nn.Dense(self.num_dims)
190
+ self.project_up = nn.Dense(self.latent_dim)
191
+
192
+ def encode(self, z: jnp.ndarray) -> jnp.ndarray:
193
+ z = self.project_down(z)
194
+ token_squared_distances = jnp.square(z[..., None] - self.codebook)
195
+ token_bits = jnp.argmin(token_squared_distances, axis=-1)
196
+ return jnp.sum(token_bits * (2 ** jnp.arange(self.num_dims)), axis=-1)
197
+
198
+ def decode(self, tokens: jnp.ndarray) -> jnp.ndarray:
199
+ token_bits = (tokens[..., None] & (2 ** jnp.arange(self.num_dims))).astype(jnp.int32)
200
+ return self.project_up(self.codebook[token_bits])
201
+
202
+ def loss(self, x: jnp.ndarray) -> LfqCodebookOutput:
203
+ z = self.project_down(x)
204
+ z = self.activation(z)
205
+
206
+ token_squared_distances = jnp.square(z[..., None] - self.codebook)
207
+ tokens = jnp.argmin(token_squared_distances, axis=-1)
208
+
209
+ token_bit_log_probs = -token_squared_distances
210
+ # Compute token log probs for tokens 0..2^num_dims-1 by summing corresponding log-probs
211
+ token_bit_expansions = jnp.bitwise_and(
212
+ jnp.arange(2**self.num_dims)[None, :], 2 ** jnp.arange(self.num_dims)[:, None]
213
+ ).astype(jnp.int32)
214
+ token_log_probs = (
215
+ token_bit_log_probs[..., 0] @ (1 - token_bit_expansions)
216
+ + token_bit_log_probs[..., 1] @ token_bit_expansions
217
+ ) # (batch_size, num_tokens, 2 ** num_dims)
218
+ token_log_probs = jax.lax.stop_gradient(jax.nn.log_softmax(token_log_probs, axis=-1))
219
+ chex.assert_shape(token_log_probs, (*x.shape[:-1], 2**self.num_dims))
220
+
221
+ z_q = self.codebook[tokens]
222
+ commit_loss = jnp.square(z - z_q).mean()
223
+ z_q = jax.lax.stop_gradient(z_q - z) + z
224
+
225
+ z_q = self.project_up(z_q)
226
+ z = self.project_up(z)
227
+
228
+ tokens = jnp.sum(tokens * (len(self.codebook) ** jnp.arange(self.num_dims)), axis=-1)
229
+ return LfqCodebookOutput(
230
+ tokens=tokens,
231
+ z=z,
232
+ z_q=z_q,
233
+ token_log_probs=jnp.zeros(()),
234
+ commit_loss=commit_loss,
235
+ )
236
+
237
+
238
+ def make_block_causal_attention_matrix(q: jnp.ndarray, k: jnp.ndarray, bs_q: int, bs_k: int) -> jnp.ndarray:
239
+ return nn.make_attention_mask(q, k, pairwise_fn=lambda x, y: jnp.greater_equal(x // bs_k, y // bs_q))
240
+
241
+
242
+ class GeGLU(Module):
243
+ """Gated Linear Unit with GELU (GeGLU) activation function.
244
+ GeGLU is a Flax layer that combines a linear transformation with a GELU
245
+ activation function in a gating mechanism. It is often used in Transformer models
246
+ to provide non-linear capabilities while preserving a strong linear component.
247
+
248
+ Attributes:
249
+ features: the number of output features (default: None).
250
+ """
251
+
252
+ output_dim: int = -1
253
+
254
+ @compact
255
+ def __call__(self, inputs: Array) -> Array:
256
+ """Applies the GeGLU activation to the inputs.
257
+ Args:
258
+ inputs: the nd-array to apply the GeGLU activation function to.
259
+ Returns:
260
+ The transformed input.
261
+ """
262
+ output_dim = inputs.shape[-1] if self.output_dim == -1 else self.output_dim
263
+
264
+ x = nn.Dense(output_dim * 2)(inputs)
265
+ x, gate = x[..., :output_dim], x[..., output_dim:]
266
+ return x * nn.gelu(gate)
267
+
268
+
269
+ class CrossAttentionLayer(nn.Module):
270
+ dropout_rate: float = 0.0
271
+ num_heads: int = None
272
+ causal: bool = False
273
+ mlp_ratio: float = 4.0
274
+
275
+ @nn.compact
276
+ def __call__(
277
+ self,
278
+ x: jnp.ndarray,
279
+ y: jnp.ndarray,
280
+ *,
281
+ mask_self: jnp.ndarray | None = None,
282
+ mask_cross: jnp.ndarray | None = None,
283
+ train: bool = True,
284
+ ) -> jnp.ndarray:
285
+ d_embed = x.shape[-1]
286
+ seq_len_q = x.shape[-2]
287
+ seq_len_k = y.shape[-2]
288
+
289
+ if self.causal:
290
+ # One block size will be 1
291
+ bs_q = max(seq_len_q // seq_len_k, 1)
292
+ bs_k = max(seq_len_k // seq_len_q, 1)
293
+
294
+ mask_self = nn.make_causal_mask(x[..., 0])
295
+ mask_cross = make_block_causal_attention_matrix(x[..., 0], y[..., 0], bs_q, bs_k)
296
+
297
+ # Self-attention block
298
+ skip = x
299
+ x = nn.LayerNorm()(x)
300
+ x = nn.MultiHeadDotProductAttention(
301
+ num_heads=self.num_heads or d_embed // 64,
302
+ dropout_rate=self.dropout_rate,
303
+ deterministic=not train,
304
+ )(x, x, x, mask=mask_self)
305
+ x = skip + x
306
+
307
+ # Cross-attention block
308
+ skip = x
309
+ x = nn.LayerNorm()(x)
310
+ x = nn.MultiHeadDotProductAttention(
311
+ num_heads=self.num_heads or d_embed // 64,
312
+ dropout_rate=self.dropout_rate,
313
+ deterministic=not train,
314
+ )(x, y, y, mask=mask_cross)
315
+ x = skip + x
316
+
317
+ # MLP block
318
+ skip = x
319
+ x = nn.LayerNorm()(x)
320
+ x = nn.Dense(int(d_embed * self.mlp_ratio))(x)
321
+ x = nn.Dropout(self.dropout_rate)(x, deterministic=not train)
322
+ x = GeGLU()(x)
323
+ x = nn.Dense(d_embed)(x)
324
+ return skip + x
325
+
326
+
327
+ def sinusoidal_pe_init(_, shape: tuple[int, int]) -> jnp.ndarray:
328
+ seq_len, d_embed = shape
329
+
330
+ position = jnp.arange(0, seq_len, 1)
331
+ div_term = jnp.exp(jnp.arange(0, d_embed, 2) * -(jnp.log(10000.0) / d_embed))
332
+ return jnp.concatenate(
333
+ [
334
+ jnp.sin(position[:, jnp.newaxis] * div_term),
335
+ jnp.cos(position[:, jnp.newaxis] * div_term),
336
+ ],
337
+ axis=-1,
338
+ )
339
+
340
+
341
+ class TokenizerEncoderDecoder(nn.Module):
342
+ num_tokens: int
343
+ num_cross_tokens: int
344
+ num_layers: int
345
+ causal: bool
346
+
347
+ mlp_ratio: float = 4.0
348
+ use_state_conditioning: bool = False
349
+
350
+ @nn.compact
351
+ def __call__(
352
+ self,
353
+ y: jnp.ndarray,
354
+ *,
355
+ train: bool = True,
356
+ state_conditioning: jnp.ndarray | None = None,
357
+ mask: jnp.ndarray | None = None,
358
+ ) -> jnp.ndarray:
359
+ x = self.param("q_embed", sinusoidal_pe_init, (self.num_tokens, y.shape[-1]))
360
+ x = jax.numpy.broadcast_to(x, y.shape[:-2] + x.shape[-2:])
361
+
362
+ if mask is not None:
363
+ # mask is (batch_dims..., num_cross_tokens)
364
+ chex.assert_equal_shape([y[..., 0], mask])
365
+ attn_mask = einops.repeat(mask, "... kv -> ... 1 q kv", q=self.num_tokens)
366
+ else:
367
+ attn_mask = jnp.ones((*y.shape[:-2], 1, self.num_tokens, self.num_cross_tokens))
368
+
369
+ if self.use_state_conditioning:
370
+ assert state_conditioning is not None, "State conditioning is required for this model."
371
+ state_embed = nn.Dense(y.shape[-1], name="state_proj")(state_conditioning)[..., None, :]
372
+ y = jnp.concatenate([y, state_embed], axis=-2)
373
+ attn_mask = jnp.concatenate([attn_mask, jnp.ones_like(attn_mask[..., 0:1])], axis=-1)
374
+
375
+ y = y + self.param("y_pos_enc", sinusoidal_pe_init, y.shape[-2:])
376
+
377
+ for _ in range(self.num_layers):
378
+ x = CrossAttentionLayer(causal=self.causal, mlp_ratio=self.mlp_ratio)(
379
+ x, y, train=train, mask_self=None, mask_cross=attn_mask
380
+ )
381
+
382
+ return x
383
+
384
+
385
+ class FsqAttentionTokenizer(nn.Module):
386
+ embed_dim: int
387
+ data_dim: int
388
+ data_horizon: int
389
+ num_tokens: int
390
+ num_layers: int
391
+ target_codebook_size: int
392
+ causal: bool = False
393
+ mlp_ratio: float = 2.0
394
+
395
+ bound: float | None = None
396
+
397
+ use_state_conditioning: bool = False
398
+
399
+ @property
400
+ def vocab_size(self) -> int:
401
+ return math.prod(FsqCodebook._get_bins_fsq(self.target_codebook_size)) # noqa: SLF001
402
+
403
+ def setup(self):
404
+ self.proj = nn.Dense(self.embed_dim)
405
+ self.encoder = TokenizerEncoderDecoder(
406
+ num_tokens=self.num_tokens,
407
+ num_cross_tokens=self.data_horizon,
408
+ num_layers=self.num_layers,
409
+ causal=self.causal,
410
+ use_state_conditioning=self.use_state_conditioning,
411
+ mlp_ratio=self.mlp_ratio,
412
+ )
413
+ self.codebook = FsqCodebook(
414
+ input_dim=self.embed_dim,
415
+ target_codebook_size=self.target_codebook_size,
416
+ codebook_type="custom",
417
+ )
418
+ self.decoder = TokenizerEncoderDecoder(
419
+ num_tokens=self.data_horizon,
420
+ num_cross_tokens=self.num_tokens,
421
+ num_layers=self.num_layers,
422
+ causal=self.causal,
423
+ use_state_conditioning=self.use_state_conditioning,
424
+ mlp_ratio=self.mlp_ratio,
425
+ )
426
+
427
+ self.proj_mean = nn.Dense(self.data_dim)
428
+ self.out_scale = self.param("out_scale", lambda _: jnp.full((), 1.0))
429
+
430
+ def tokenize(
431
+ self, action: jnp.ndarray, *, obs: jnp.ndarray | None = None, train: bool = False
432
+ ) -> tuple[jnp.ndarray, jnp.ndarray]:
433
+ if self.bound is not None:
434
+ action = jnp.clip(action, -self.bound, self.bound)
435
+
436
+ x = self.proj(action)
437
+ x = self.encoder(x, train=train, state_conditioning=obs)
438
+
439
+ return self.codebook.encode(x)
440
+
441
+ def detokenize(self, tokens: jnp.ndarray, *, obs: jnp.ndarray | None = None) -> jnp.ndarray:
442
+ x = self.decoder(self.codebook.decode(tokens), state_conditioning=obs)
443
+ mean = self.proj_mean(x)
444
+ return mean * self.out_scale
445
+
446
+ def loss(
447
+ self, action: jnp.ndarray, *, obs: jnp.ndarray | None = None, train: bool = True
448
+ ) -> tuple[jnp.ndarray, dict[str, jnp.ndarray]]:
449
+ # Encode
450
+ x = self.proj(action)
451
+ z = self.encoder(x, train=train, state_conditioning=obs)
452
+
453
+ # Quantize
454
+ tokens, z = self.codebook(z)
455
+
456
+ # Decode
457
+ x = self.decoder(z, train=train, state_conditioning=obs)
458
+ mean = self.proj_mean(x) * self.out_scale
459
+
460
+ mse = jnp.mean(jnp.square(action - mean))
461
+ mae = jnp.mean(jnp.abs(action - mean))
462
+
463
+ return mse, {
464
+ "mse": mse,
465
+ "mae": mae,
466
+ }
467
+
468
+ def __call__(self, *args: Any, **kwargs: Any) -> tuple[jnp.ndarray, dict[str, jnp.ndarray]]:
469
+ """
470
+ Dummy for .init
471
+ """
472
+ return self.loss(*args, **kwargs)
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/gemma_pytorch.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Literal
2
+
3
+ import pytest
4
+ import torch
5
+ from torch import nn
6
+ from transformers import GemmaForCausalLM
7
+ from transformers import PaliGemmaForConditionalGeneration
8
+ from transformers.models.auto import CONFIG_MAPPING
9
+ from transformers.models.gemma import modeling_gemma
10
+
11
+
12
+ class PaliGemmaWithExpertModel(nn.Module):
13
+ def __init__(
14
+ self,
15
+ vlm_config,
16
+ action_expert_config,
17
+ use_adarms=None,
18
+ precision: Literal["bfloat16", "float32"] = "bfloat16",
19
+ ):
20
+ if use_adarms is None:
21
+ use_adarms = [False, False]
22
+ super().__init__()
23
+
24
+ vlm_config_hf = CONFIG_MAPPING["paligemma"]()
25
+ vlm_config_hf._vocab_size = 257152 # noqa: SLF001
26
+ vlm_config_hf.image_token_index = 257152
27
+ vlm_config_hf.text_config.hidden_size = vlm_config.width
28
+ vlm_config_hf.text_config.intermediate_size = vlm_config.mlp_dim
29
+ vlm_config_hf.text_config.num_attention_heads = vlm_config.num_heads
30
+ vlm_config_hf.text_config.head_dim = vlm_config.head_dim
31
+ vlm_config_hf.text_config.num_hidden_layers = vlm_config.depth
32
+ vlm_config_hf.text_config.num_key_value_heads = vlm_config.num_kv_heads
33
+ vlm_config_hf.text_config.hidden_activation = "gelu_pytorch_tanh"
34
+ vlm_config_hf.text_config.torch_dtype = "float32"
35
+ vlm_config_hf.text_config.vocab_size = 257152
36
+ vlm_config_hf.text_config.use_adarms = use_adarms[0]
37
+ vlm_config_hf.text_config.adarms_cond_dim = vlm_config.width if use_adarms[0] else None
38
+ vlm_config_hf.vision_config.intermediate_size = 4304
39
+ vlm_config_hf.vision_config.projection_dim = 2048
40
+ vlm_config_hf.vision_config.projector_hidden_act = "gelu_fast"
41
+ vlm_config_hf.vision_config.torch_dtype = "float32"
42
+
43
+ action_expert_config_hf = CONFIG_MAPPING["gemma"](
44
+ head_dim=action_expert_config.head_dim,
45
+ hidden_size=action_expert_config.width,
46
+ intermediate_size=action_expert_config.mlp_dim,
47
+ num_attention_heads=action_expert_config.num_heads,
48
+ num_hidden_layers=action_expert_config.depth,
49
+ num_key_value_heads=action_expert_config.num_kv_heads,
50
+ vocab_size=257152,
51
+ hidden_activation="gelu_pytorch_tanh",
52
+ torch_dtype="float32",
53
+ use_adarms=use_adarms[1],
54
+ adarms_cond_dim=action_expert_config.width if use_adarms[1] else None,
55
+ )
56
+
57
+ self.paligemma = PaliGemmaForConditionalGeneration(config=vlm_config_hf)
58
+ self.gemma_expert = GemmaForCausalLM(config=action_expert_config_hf)
59
+ self.gemma_expert.model.embed_tokens = None
60
+
61
+ self.to_bfloat16_for_selected_params(precision)
62
+
63
+ def to_bfloat16_for_selected_params(self, precision: Literal["bfloat16", "float32"] = "bfloat16"):
64
+ if precision == "bfloat16":
65
+ self.to(dtype=torch.bfloat16)
66
+ elif precision == "float32":
67
+ self.to(dtype=torch.float32)
68
+ return
69
+ else:
70
+ raise ValueError(f"Invalid precision: {precision}")
71
+
72
+ params_to_keep_float32 = [
73
+ "vision_tower.vision_model.embeddings.patch_embedding.weight",
74
+ "vision_tower.vision_model.embeddings.patch_embedding.bias",
75
+ "vision_tower.vision_model.embeddings.position_embedding.weight",
76
+ "input_layernorm",
77
+ "post_attention_layernorm",
78
+ "model.norm",
79
+ ]
80
+
81
+ for name, param in self.named_parameters():
82
+ if any(selector in name for selector in params_to_keep_float32):
83
+ param.data = param.data.to(dtype=torch.float32)
84
+
85
+ def embed_image(self, image: torch.Tensor):
86
+ return self.paligemma.model.get_image_features(image)
87
+
88
+ def embed_language_tokens(self, tokens: torch.Tensor):
89
+ return self.paligemma.language_model.embed_tokens(tokens)
90
+
91
+ def forward(
92
+ self,
93
+ attention_mask: torch.Tensor | None = None,
94
+ position_ids: torch.LongTensor | None = None,
95
+ past_key_values: list[torch.FloatTensor] | pytest.Cache | None = None,
96
+ inputs_embeds: list[torch.FloatTensor] | None = None,
97
+ use_cache: bool | None = None,
98
+ adarms_cond: list[torch.Tensor] | None = None,
99
+ ):
100
+ if adarms_cond is None:
101
+ adarms_cond = [None, None]
102
+ if inputs_embeds[1] is None:
103
+ prefix_output = self.paligemma.language_model.forward(
104
+ inputs_embeds=inputs_embeds[0],
105
+ attention_mask=attention_mask,
106
+ position_ids=position_ids,
107
+ past_key_values=past_key_values,
108
+ use_cache=use_cache,
109
+ adarms_cond=adarms_cond[0] if adarms_cond is not None else None,
110
+ )
111
+ prefix_past_key_values = prefix_output.past_key_values
112
+ prefix_output = prefix_output.last_hidden_state
113
+ suffix_output = None
114
+ elif inputs_embeds[0] is None:
115
+ suffix_output = self.gemma_expert.model.forward(
116
+ inputs_embeds=inputs_embeds[1],
117
+ attention_mask=attention_mask,
118
+ position_ids=position_ids,
119
+ past_key_values=past_key_values,
120
+ use_cache=use_cache,
121
+ adarms_cond=adarms_cond[1] if adarms_cond is not None else None,
122
+ )
123
+ suffix_output = suffix_output.last_hidden_state
124
+ prefix_output = None
125
+ prefix_past_key_values = None
126
+ else:
127
+ models = [self.paligemma.language_model, self.gemma_expert.model]
128
+ num_layers = self.paligemma.config.text_config.num_hidden_layers
129
+
130
+ # Check if gradient checkpointing is enabled for any of the models
131
+ use_gradient_checkpointing = (
132
+ hasattr(self.gemma_expert.model, "gradient_checkpointing")
133
+ and self.gemma_expert.model.gradient_checkpointing
134
+ and self.training
135
+ ) or (hasattr(self, "gradient_checkpointing") and self.gradient_checkpointing and self.training)
136
+
137
+ # Force enable gradient checkpointing if we're in training mode and the model supports it
138
+ if self.training and hasattr(self.gemma_expert.model, "gradient_checkpointing"):
139
+ if not self.gemma_expert.model.gradient_checkpointing:
140
+ print("Forcing gradient checkpointing to be enabled for Gemma expert model")
141
+ self.gemma_expert.model.gradient_checkpointing = True
142
+ use_gradient_checkpointing = True
143
+
144
+ # Debug gradient checkpointing status
145
+ if hasattr(self, "_debug_gc_printed") and not self._debug_gc_printed:
146
+ print(f"Gemma expert model gradient checkpointing: {use_gradient_checkpointing}")
147
+ print(f"Model training mode: {self.training}")
148
+ print(
149
+ f"Gemma expert model has gradient_checkpointing attr: {hasattr(self.gemma_expert.model, 'gradient_checkpointing')}"
150
+ )
151
+ if hasattr(self.gemma_expert.model, "gradient_checkpointing"):
152
+ print(
153
+ f"Gemma expert model gradient_checkpointing value: {self.gemma_expert.model.gradient_checkpointing}"
154
+ )
155
+ self._debug_gc_printed = True
156
+
157
+ # Define the complete layer computation function for gradient checkpointing
158
+ def compute_layer_complete(layer_idx, inputs_embeds, attention_mask, position_ids, adarms_cond):
159
+ models = [self.paligemma.language_model, self.gemma_expert.model]
160
+
161
+ query_states = []
162
+ key_states = []
163
+ value_states = []
164
+ gates = []
165
+ for i, hidden_states in enumerate(inputs_embeds):
166
+ layer = models[i].layers[layer_idx]
167
+ hidden_states, gate = layer.input_layernorm(hidden_states, cond=adarms_cond[i]) # noqa: PLW2901
168
+ gates.append(gate)
169
+
170
+ input_shape = hidden_states.shape[:-1]
171
+ hidden_shape = (*input_shape, -1, layer.self_attn.head_dim)
172
+ query_state = layer.self_attn.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
173
+ key_state = layer.self_attn.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
174
+ value_state = layer.self_attn.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
175
+
176
+ query_states.append(query_state)
177
+ key_states.append(key_state)
178
+ value_states.append(value_state)
179
+
180
+ # Concatenate and process attention
181
+ query_states = torch.cat(query_states, dim=2)
182
+ key_states = torch.cat(key_states, dim=2)
183
+ value_states = torch.cat(value_states, dim=2)
184
+
185
+ dummy_tensor = torch.zeros(
186
+ query_states.shape[0],
187
+ query_states.shape[2],
188
+ query_states.shape[-1],
189
+ device=query_states.device,
190
+ dtype=query_states.dtype,
191
+ )
192
+ cos, sin = self.paligemma.model.language_model.rotary_emb(dummy_tensor, position_ids)
193
+ query_states, key_states = modeling_gemma.apply_rotary_pos_emb(
194
+ query_states, key_states, cos, sin, unsqueeze_dim=1
195
+ )
196
+
197
+ batch_size = query_states.shape[0]
198
+ scaling = self.paligemma.language_model.layers[layer_idx].self_attn.scaling
199
+
200
+ # Attention computation
201
+ att_output, _ = modeling_gemma.eager_attention_forward(
202
+ self.paligemma.language_model.layers[layer_idx].self_attn,
203
+ query_states,
204
+ key_states,
205
+ value_states,
206
+ attention_mask,
207
+ scaling,
208
+ )
209
+ # Get head_dim from the current layer, not from the model
210
+ head_dim = self.paligemma.language_model.layers[layer_idx].self_attn.head_dim
211
+ att_output = att_output.reshape(batch_size, -1, 1 * 8 * head_dim)
212
+
213
+ # Process layer outputs
214
+ outputs_embeds = []
215
+ start_pos = 0
216
+ for i, hidden_states in enumerate(inputs_embeds):
217
+ layer = models[i].layers[layer_idx]
218
+ end_pos = start_pos + hidden_states.shape[1]
219
+
220
+ if att_output.dtype != layer.self_attn.o_proj.weight.dtype:
221
+ att_output = att_output.to(layer.self_attn.o_proj.weight.dtype)
222
+ out_emb = layer.self_attn.o_proj(att_output[:, start_pos:end_pos])
223
+
224
+ # first residual
225
+ out_emb = modeling_gemma._gated_residual(hidden_states, out_emb, gates[i]) # noqa: SLF001
226
+ after_first_residual = out_emb.clone()
227
+ out_emb, gate = layer.post_attention_layernorm(out_emb, cond=adarms_cond[i])
228
+ # Convert to bfloat16 if the next layer (mlp) uses bfloat16
229
+ if layer.mlp.up_proj.weight.dtype == torch.bfloat16:
230
+ out_emb = out_emb.to(dtype=torch.bfloat16)
231
+
232
+ out_emb = layer.mlp(out_emb)
233
+ # second residual
234
+ out_emb = modeling_gemma._gated_residual(after_first_residual, out_emb, gate) # noqa: SLF001
235
+ outputs_embeds.append(out_emb)
236
+ start_pos = end_pos
237
+
238
+ return outputs_embeds
239
+
240
+ # Process all layers with gradient checkpointing if enabled
241
+ for layer_idx in range(num_layers):
242
+ if use_gradient_checkpointing:
243
+ inputs_embeds = torch.utils.checkpoint.checkpoint(
244
+ compute_layer_complete,
245
+ layer_idx,
246
+ inputs_embeds,
247
+ attention_mask,
248
+ position_ids,
249
+ adarms_cond,
250
+ use_reentrant=False,
251
+ preserve_rng_state=False,
252
+ )
253
+ else:
254
+ inputs_embeds = compute_layer_complete(
255
+ layer_idx, inputs_embeds, attention_mask, position_ids, adarms_cond
256
+ )
257
+
258
+ # Old code removed - now using compute_layer_complete function above
259
+
260
+ # final norm
261
+ # Define final norm computation function for gradient checkpointing
262
+ def compute_final_norms(inputs_embeds, adarms_cond):
263
+ outputs_embeds = []
264
+ for i, hidden_states in enumerate(inputs_embeds):
265
+ out_emb, _ = models[i].norm(hidden_states, cond=adarms_cond[i])
266
+ outputs_embeds.append(out_emb)
267
+ return outputs_embeds
268
+
269
+ # Apply gradient checkpointing to final norm if enabled
270
+ if use_gradient_checkpointing:
271
+ outputs_embeds = torch.utils.checkpoint.checkpoint(
272
+ compute_final_norms, inputs_embeds, adarms_cond, use_reentrant=False, preserve_rng_state=False
273
+ )
274
+ else:
275
+ outputs_embeds = compute_final_norms(inputs_embeds, adarms_cond)
276
+
277
+ prefix_output = outputs_embeds[0]
278
+ suffix_output = outputs_embeds[1]
279
+ prefix_past_key_values = None
280
+
281
+ return [prefix_output, suffix_output], prefix_past_key_values
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/pi0_pytorch.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import math
3
+
4
+ import torch
5
+ from torch import Tensor
6
+ from torch import nn
7
+ import torch.nn.functional as F # noqa: N812
8
+
9
+ import openpi.models.gemma as _gemma
10
+ from openpi.models_pytorch.gemma_pytorch import PaliGemmaWithExpertModel
11
+ import openpi.models_pytorch.preprocessing_pytorch as _preprocessing
12
+
13
+
14
+ def get_safe_dtype(target_dtype, device_type):
15
+ """Get a safe dtype for the given device type."""
16
+ if device_type == "cpu":
17
+ # CPU doesn't support bfloat16, use float32 instead
18
+ if target_dtype == torch.bfloat16:
19
+ return torch.float32
20
+ if target_dtype == torch.float64:
21
+ return torch.float64
22
+ return target_dtype
23
+
24
+
25
+ def create_sinusoidal_pos_embedding(
26
+ time: torch.tensor, dimension: int, min_period: float, max_period: float, device="cpu"
27
+ ) -> Tensor:
28
+ """Computes sine-cosine positional embedding vectors for scalar positions."""
29
+ if dimension % 2 != 0:
30
+ raise ValueError(f"dimension ({dimension}) must be divisible by 2")
31
+
32
+ if time.ndim != 1:
33
+ raise ValueError("The time tensor is expected to be of shape `(batch_size, )`.")
34
+
35
+ dtype = get_safe_dtype(torch.float64, device.type)
36
+ fraction = torch.linspace(0.0, 1.0, dimension // 2, dtype=dtype, device=device)
37
+ period = min_period * (max_period / min_period) ** fraction
38
+
39
+ # Compute the outer product
40
+ scaling_factor = 1.0 / period * 2 * math.pi
41
+ sin_input = scaling_factor[None, :] * time[:, None]
42
+ return torch.cat([torch.sin(sin_input), torch.cos(sin_input)], dim=1)
43
+
44
+
45
+ def sample_beta(alpha, beta, bsize, device):
46
+ alpha_t = torch.as_tensor(alpha, dtype=torch.float32, device=device)
47
+ beta_t = torch.as_tensor(beta, dtype=torch.float32, device=device)
48
+ dist = torch.distributions.Beta(alpha_t, beta_t)
49
+ return dist.sample((bsize,))
50
+
51
+
52
+ def make_att_2d_masks(pad_masks, att_masks):
53
+ """Copied from big_vision.
54
+
55
+ Tokens can attend to valid inputs tokens which have a cumulative mask_ar
56
+ smaller or equal to theirs. This way `mask_ar` int[B, N] can be used to
57
+ setup several types of attention, for example:
58
+
59
+ [[1 1 1 1 1 1]]: pure causal attention.
60
+
61
+ [[0 0 0 1 1 1]]: prefix-lm attention. The first 3 tokens can attend between
62
+ themselves and the last 3 tokens have a causal attention. The first
63
+ entry could also be a 1 without changing behaviour.
64
+
65
+ [[1 0 1 0 1 0 0 1 0 0]]: causal attention between 4 blocks. Tokens of a
66
+ block can attend all previous blocks and all tokens on the same block.
67
+
68
+ Args:
69
+ input_mask: bool[B, N] true if its part of the input, false if padding.
70
+ mask_ar: int32[B, N] mask that's 1 where previous tokens cannot depend on
71
+ it and 0 where it shares the same attention mask as the previous token.
72
+ """
73
+ if att_masks.ndim != 2:
74
+ raise ValueError(att_masks.ndim)
75
+ if pad_masks.ndim != 2:
76
+ raise ValueError(pad_masks.ndim)
77
+
78
+ cumsum = torch.cumsum(att_masks, dim=1)
79
+ att_2d_masks = cumsum[:, None, :] <= cumsum[:, :, None]
80
+ pad_2d_masks = pad_masks[:, None, :] * pad_masks[:, :, None]
81
+ return att_2d_masks & pad_2d_masks
82
+
83
+
84
+ class PI0Pytorch(nn.Module):
85
+ def __init__(self, config):
86
+ super().__init__()
87
+ self.config = config
88
+ self.pi05 = config.pi05
89
+
90
+ paligemma_config = _gemma.get_config(config.paligemma_variant)
91
+ action_expert_config = _gemma.get_config(config.action_expert_variant)
92
+
93
+ self.paligemma_with_expert = PaliGemmaWithExpertModel(
94
+ paligemma_config,
95
+ action_expert_config,
96
+ use_adarms=[False, True] if self.pi05 else [False, False],
97
+ precision=config.dtype,
98
+ )
99
+
100
+ self.action_in_proj = nn.Linear(config.action_dim, action_expert_config.width)
101
+ self.action_out_proj = nn.Linear(action_expert_config.width, config.action_dim)
102
+
103
+ if self.pi05:
104
+ self.time_mlp_in = nn.Linear(action_expert_config.width, action_expert_config.width)
105
+ self.time_mlp_out = nn.Linear(action_expert_config.width, action_expert_config.width)
106
+ else:
107
+ self.state_proj = nn.Linear(config.action_dim, action_expert_config.width)
108
+ self.action_time_mlp_in = nn.Linear(2 * action_expert_config.width, action_expert_config.width)
109
+ self.action_time_mlp_out = nn.Linear(action_expert_config.width, action_expert_config.width)
110
+
111
+ torch.set_float32_matmul_precision("high")
112
+ if config.pytorch_compile_mode is not None:
113
+ self.sample_actions = torch.compile(self.sample_actions, mode=config.pytorch_compile_mode)
114
+
115
+ # Initialize gradient checkpointing flag
116
+ self.gradient_checkpointing_enabled = False
117
+
118
+ msg = "transformers_replace is not installed correctly. Please install it with `uv pip install transformers==4.53.2` and `cp -r ./src/openpi/models_pytorch/transformers_replace/* .venv/lib/python3.11/site-packages/transformers/`."
119
+ try:
120
+ from transformers.models.siglip import check
121
+
122
+ if not check.check_whether_transformers_replace_is_installed_correctly():
123
+ raise ValueError(msg)
124
+ except ImportError:
125
+ raise ValueError(msg) from None
126
+
127
+ def gradient_checkpointing_enable(self):
128
+ """Enable gradient checkpointing for memory optimization."""
129
+ self.gradient_checkpointing_enabled = True
130
+ self.paligemma_with_expert.paligemma.language_model.gradient_checkpointing = True
131
+ self.paligemma_with_expert.paligemma.vision_tower.gradient_checkpointing = True
132
+ self.paligemma_with_expert.gemma_expert.model.gradient_checkpointing = True
133
+
134
+ logging.info("Enabled gradient checkpointing for PI0Pytorch model")
135
+
136
+ def gradient_checkpointing_disable(self):
137
+ """Disable gradient checkpointing."""
138
+ self.gradient_checkpointing_enabled = False
139
+ self.paligemma_with_expert.paligemma.language_model.gradient_checkpointing = False
140
+ self.paligemma_with_expert.paligemma.vision_tower.gradient_checkpointing = False
141
+ self.paligemma_with_expert.gemma_expert.model.gradient_checkpointing = False
142
+
143
+ logging.info("Disabled gradient checkpointing for PI0Pytorch model")
144
+
145
+ def is_gradient_checkpointing_enabled(self):
146
+ """Check if gradient checkpointing is enabled."""
147
+ return self.gradient_checkpointing_enabled
148
+
149
+ def _apply_checkpoint(self, func, *args, **kwargs):
150
+ """Helper method to apply gradient checkpointing if enabled."""
151
+ if self.gradient_checkpointing_enabled and self.training:
152
+ return torch.utils.checkpoint.checkpoint(
153
+ func, *args, use_reentrant=False, preserve_rng_state=False, **kwargs
154
+ )
155
+ return func(*args, **kwargs)
156
+
157
+ def _prepare_attention_masks_4d(self, att_2d_masks):
158
+ """Helper method to prepare 4D attention masks for transformer."""
159
+ att_2d_masks_4d = att_2d_masks[:, None, :, :]
160
+ return torch.where(att_2d_masks_4d, 0.0, -2.3819763e38)
161
+
162
+ def _preprocess_observation(self, observation, *, train=True):
163
+ """Helper method to preprocess observation."""
164
+ observation = _preprocessing.preprocess_observation_pytorch(observation, train=train)
165
+ return (
166
+ list(observation.images.values()),
167
+ list(observation.image_masks.values()),
168
+ observation.tokenized_prompt,
169
+ observation.tokenized_prompt_mask,
170
+ observation.state,
171
+ )
172
+
173
+ def sample_noise(self, shape, device):
174
+ return torch.normal(
175
+ mean=0.0,
176
+ std=1.0,
177
+ size=shape,
178
+ dtype=torch.float32,
179
+ device=device,
180
+ )
181
+
182
+ def sample_time(self, bsize, device):
183
+ time_beta = sample_beta(1.5, 1.0, bsize, device)
184
+ time = time_beta * 0.999 + 0.001
185
+ return time.to(dtype=torch.float32, device=device)
186
+
187
+ def embed_prefix(
188
+ self, images, img_masks, lang_tokens, lang_masks
189
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
190
+ """Embed images with SigLIP and language tokens with embedding layer to prepare
191
+ for PaliGemma transformer processing.
192
+ """
193
+ embs = []
194
+ pad_masks = []
195
+ att_masks = []
196
+
197
+ # Process images
198
+ for img, img_mask in zip(images, img_masks, strict=True):
199
+
200
+ def image_embed_func(img):
201
+ return self.paligemma_with_expert.embed_image(img)
202
+
203
+ img_emb = self._apply_checkpoint(image_embed_func, img)
204
+
205
+ bsize, num_img_embs = img_emb.shape[:2]
206
+
207
+ embs.append(img_emb)
208
+ pad_masks.append(img_mask[:, None].expand(bsize, num_img_embs))
209
+
210
+ # Create attention masks so that image tokens attend to each other
211
+ att_masks += [0] * num_img_embs
212
+
213
+ # Process language tokens
214
+ def lang_embed_func(lang_tokens):
215
+ lang_emb = self.paligemma_with_expert.embed_language_tokens(lang_tokens)
216
+ lang_emb_dim = lang_emb.shape[-1]
217
+ return lang_emb * math.sqrt(lang_emb_dim)
218
+
219
+ lang_emb = self._apply_checkpoint(lang_embed_func, lang_tokens)
220
+
221
+ embs.append(lang_emb)
222
+ pad_masks.append(lang_masks)
223
+
224
+ # full attention between image and language inputs
225
+ num_lang_embs = lang_emb.shape[1]
226
+ att_masks += [0] * num_lang_embs
227
+
228
+ embs = torch.cat(embs, dim=1)
229
+ pad_masks = torch.cat(pad_masks, dim=1)
230
+ att_masks = torch.tensor(att_masks, dtype=torch.bool, device=pad_masks.device)
231
+
232
+ # Get batch size from the first dimension of the concatenated tensors
233
+ bsize = pad_masks.shape[0]
234
+ att_masks = att_masks[None, :].expand(bsize, len(att_masks))
235
+
236
+ return embs, pad_masks, att_masks
237
+
238
+ def embed_suffix(self, state, noisy_actions, timestep):
239
+ """Embed state, noisy_actions, timestep to prepare for Expert Gemma processing."""
240
+ embs = []
241
+ pad_masks = []
242
+ att_masks = []
243
+
244
+ if not self.pi05:
245
+ if self.state_proj.weight.dtype == torch.float32:
246
+ state = state.to(torch.float32)
247
+
248
+ # Embed state
249
+ def state_proj_func(state):
250
+ return self.state_proj(state)
251
+
252
+ state_emb = self._apply_checkpoint(state_proj_func, state)
253
+
254
+ embs.append(state_emb[:, None, :])
255
+ bsize = state_emb.shape[0]
256
+ device = state_emb.device
257
+
258
+ state_mask = torch.ones(bsize, 1, dtype=torch.bool, device=device)
259
+ pad_masks.append(state_mask)
260
+
261
+ # Set attention masks so that image and language inputs do not attend to state or actions
262
+ att_masks += [1]
263
+
264
+ # Embed timestep using sine-cosine positional encoding with sensitivity in the range [0, 1]
265
+ time_emb = create_sinusoidal_pos_embedding(
266
+ timestep, self.action_in_proj.out_features, min_period=4e-3, max_period=4.0, device=timestep.device
267
+ )
268
+ time_emb = time_emb.type(dtype=timestep.dtype)
269
+
270
+ # Fuse timestep + action information using an MLP
271
+ def action_proj_func(noisy_actions):
272
+ return self.action_in_proj(noisy_actions)
273
+
274
+ action_emb = self._apply_checkpoint(action_proj_func, noisy_actions)
275
+
276
+ if not self.pi05:
277
+ time_emb = time_emb[:, None, :].expand_as(action_emb)
278
+ action_time_emb = torch.cat([action_emb, time_emb], dim=2)
279
+
280
+ # Apply MLP layers
281
+ def mlp_func(action_time_emb):
282
+ x = self.action_time_mlp_in(action_time_emb)
283
+ x = F.silu(x) # swish == silu
284
+ return self.action_time_mlp_out(x)
285
+
286
+ action_time_emb = self._apply_checkpoint(mlp_func, action_time_emb)
287
+ adarms_cond = None
288
+ else:
289
+ # time MLP (for adaRMS)
290
+ def time_mlp_func(time_emb):
291
+ x = self.time_mlp_in(time_emb)
292
+ x = F.silu(x) # swish == silu
293
+ x = self.time_mlp_out(x)
294
+ return F.silu(x)
295
+
296
+ time_emb = self._apply_checkpoint(time_mlp_func, time_emb)
297
+ action_time_emb = action_emb
298
+ adarms_cond = time_emb
299
+
300
+ # Add to input tokens
301
+ embs.append(action_time_emb)
302
+
303
+ bsize, action_time_dim = action_time_emb.shape[:2]
304
+ action_time_mask = torch.ones(bsize, action_time_dim, dtype=torch.bool, device=timestep.device)
305
+ pad_masks.append(action_time_mask)
306
+
307
+ # Set attention masks so that image, language and state inputs do not attend to action tokens
308
+ att_masks += [1] + ([0] * (self.config.action_horizon - 1))
309
+
310
+ embs = torch.cat(embs, dim=1)
311
+ pad_masks = torch.cat(pad_masks, dim=1)
312
+ att_masks = torch.tensor(att_masks, dtype=embs.dtype, device=embs.device)
313
+ att_masks = att_masks[None, :].expand(bsize, len(att_masks))
314
+
315
+ return embs, pad_masks, att_masks, adarms_cond
316
+
317
+ def forward(self, observation, actions, noise=None, time=None) -> Tensor:
318
+ """Do a full training forward pass and compute the loss (batch_size x num_steps x num_motors)"""
319
+ images, img_masks, lang_tokens, lang_masks, state = self._preprocess_observation(observation, train=True)
320
+
321
+ if noise is None:
322
+ noise = self.sample_noise(actions.shape, actions.device)
323
+
324
+ if time is None:
325
+ time = self.sample_time(actions.shape[0], actions.device)
326
+
327
+ time_expanded = time[:, None, None]
328
+ x_t = time_expanded * noise + (1 - time_expanded) * actions
329
+ u_t = noise - actions
330
+
331
+ prefix_embs, prefix_pad_masks, prefix_att_masks = self.embed_prefix(images, img_masks, lang_tokens, lang_masks)
332
+ suffix_embs, suffix_pad_masks, suffix_att_masks, adarms_cond = self.embed_suffix(state, x_t, time)
333
+ if (
334
+ self.paligemma_with_expert.paligemma.language_model.layers[0].self_attn.q_proj.weight.dtype
335
+ == torch.bfloat16
336
+ ):
337
+ suffix_embs = suffix_embs.to(dtype=torch.bfloat16)
338
+ prefix_embs = prefix_embs.to(dtype=torch.bfloat16)
339
+
340
+ pad_masks = torch.cat([prefix_pad_masks, suffix_pad_masks], dim=1)
341
+ att_masks = torch.cat([prefix_att_masks, suffix_att_masks], dim=1)
342
+
343
+ att_2d_masks = make_att_2d_masks(pad_masks, att_masks)
344
+ position_ids = torch.cumsum(pad_masks, dim=1) - 1
345
+
346
+ # Prepare attention masks
347
+ att_2d_masks_4d = self._prepare_attention_masks_4d(att_2d_masks)
348
+
349
+ # Apply gradient checkpointing if enabled
350
+ def forward_func(prefix_embs, suffix_embs, att_2d_masks_4d, position_ids, adarms_cond):
351
+ (_, suffix_out), _ = self.paligemma_with_expert.forward(
352
+ attention_mask=att_2d_masks_4d,
353
+ position_ids=position_ids,
354
+ past_key_values=None,
355
+ inputs_embeds=[prefix_embs, suffix_embs],
356
+ use_cache=False,
357
+ adarms_cond=[None, adarms_cond],
358
+ )
359
+ return suffix_out
360
+
361
+ suffix_out = self._apply_checkpoint(
362
+ forward_func, prefix_embs, suffix_embs, att_2d_masks_4d, position_ids, adarms_cond
363
+ )
364
+
365
+ suffix_out = suffix_out[:, -self.config.action_horizon :]
366
+ suffix_out = suffix_out.to(dtype=torch.float32)
367
+
368
+ # Apply gradient checkpointing to final action projection if enabled
369
+ def action_out_proj_func(suffix_out):
370
+ return self.action_out_proj(suffix_out)
371
+
372
+ v_t = self._apply_checkpoint(action_out_proj_func, suffix_out)
373
+
374
+ return F.mse_loss(u_t, v_t, reduction="none")
375
+
376
+ @torch.no_grad()
377
+ def sample_actions(self, device, observation, noise=None, num_steps=10) -> Tensor:
378
+ """Do a full inference forward and compute the action (batch_size x num_steps x num_motors)"""
379
+ bsize = observation.state.shape[0]
380
+ if noise is None:
381
+ actions_shape = (bsize, self.config.action_horizon, self.config.action_dim)
382
+ noise = self.sample_noise(actions_shape, device)
383
+
384
+ images, img_masks, lang_tokens, lang_masks, state = self._preprocess_observation(observation, train=False)
385
+
386
+ prefix_embs, prefix_pad_masks, prefix_att_masks = self.embed_prefix(images, img_masks, lang_tokens, lang_masks)
387
+ prefix_att_2d_masks = make_att_2d_masks(prefix_pad_masks, prefix_att_masks)
388
+ prefix_position_ids = torch.cumsum(prefix_pad_masks, dim=1) - 1
389
+
390
+ # Compute image and language key value cache
391
+ prefix_att_2d_masks_4d = self._prepare_attention_masks_4d(prefix_att_2d_masks)
392
+ self.paligemma_with_expert.paligemma.language_model.config._attn_implementation = "eager" # noqa: SLF001
393
+
394
+ _, past_key_values = self.paligemma_with_expert.forward(
395
+ attention_mask=prefix_att_2d_masks_4d,
396
+ position_ids=prefix_position_ids,
397
+ past_key_values=None,
398
+ inputs_embeds=[prefix_embs, None],
399
+ use_cache=True,
400
+ )
401
+
402
+ dt = -1.0 / num_steps
403
+ dt = torch.tensor(dt, dtype=torch.float32, device=device)
404
+
405
+ x_t = noise
406
+ time = torch.tensor(1.0, dtype=torch.float32, device=device)
407
+ while time >= -dt / 2:
408
+ expanded_time = time.expand(bsize)
409
+ v_t = self.denoise_step(
410
+ state,
411
+ prefix_pad_masks,
412
+ past_key_values,
413
+ x_t,
414
+ expanded_time,
415
+ )
416
+
417
+ # Euler step - use new tensor assignment instead of in-place operation
418
+ x_t = x_t + dt * v_t
419
+ time += dt
420
+ return x_t
421
+
422
+ def denoise_step(
423
+ self,
424
+ state,
425
+ prefix_pad_masks,
426
+ past_key_values,
427
+ x_t,
428
+ timestep,
429
+ ):
430
+ """Apply one denoising step of the noise `x_t` at a given timestep."""
431
+ suffix_embs, suffix_pad_masks, suffix_att_masks, adarms_cond = self.embed_suffix(state, x_t, timestep)
432
+
433
+ suffix_len = suffix_pad_masks.shape[1]
434
+ batch_size = prefix_pad_masks.shape[0]
435
+ prefix_len = prefix_pad_masks.shape[1]
436
+
437
+ prefix_pad_2d_masks = prefix_pad_masks[:, None, :].expand(batch_size, suffix_len, prefix_len)
438
+
439
+ suffix_att_2d_masks = make_att_2d_masks(suffix_pad_masks, suffix_att_masks)
440
+
441
+ full_att_2d_masks = torch.cat([prefix_pad_2d_masks, suffix_att_2d_masks], dim=2)
442
+
443
+ prefix_offsets = torch.sum(prefix_pad_masks, dim=-1)[:, None]
444
+ position_ids = prefix_offsets + torch.cumsum(suffix_pad_masks, dim=1) - 1
445
+
446
+ # Prepare attention masks
447
+ full_att_2d_masks_4d = self._prepare_attention_masks_4d(full_att_2d_masks)
448
+ self.paligemma_with_expert.gemma_expert.model.config._attn_implementation = "eager" # noqa: SLF001
449
+
450
+ outputs_embeds, _ = self.paligemma_with_expert.forward(
451
+ attention_mask=full_att_2d_masks_4d,
452
+ position_ids=position_ids,
453
+ past_key_values=past_key_values,
454
+ inputs_embeds=[None, suffix_embs],
455
+ use_cache=False,
456
+ adarms_cond=[None, adarms_cond],
457
+ )
458
+
459
+ suffix_out = outputs_embeds[1]
460
+ suffix_out = suffix_out[:, -self.config.action_horizon :]
461
+ suffix_out = suffix_out.to(dtype=torch.float32)
462
+ return self.action_out_proj(suffix_out)
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/transformers_replace/models/gemma/configuration_gemma.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/gemma/modular_gemma.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_gemma.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2024 Google Inc. HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+ from typing import Optional
23
+ from ...configuration_utils import PretrainedConfig
24
+
25
+
26
+ class GemmaConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`GemmaModel`]. It is used to instantiate an Gemma
29
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
30
+ defaults will yield a similar configuration to that of the Gemma-7B.
31
+ e.g. [google/gemma-7b](https://huggingface.co/google/gemma-7b)
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+ Args:
35
+ vocab_size (`int`, *optional*, defaults to 256000):
36
+ Vocabulary size of the Gemma model. Defines the number of different tokens that can be represented by the
37
+ `inputs_ids` passed when calling [`GemmaModel`]
38
+ hidden_size (`int`, *optional*, defaults to 3072):
39
+ Dimension of the hidden representations.
40
+ intermediate_size (`int`, *optional*, defaults to 24576):
41
+ Dimension of the MLP representations.
42
+ num_hidden_layers (`int`, *optional*, defaults to 28):
43
+ Number of hidden layers in the Transformer decoder.
44
+ num_attention_heads (`int`, *optional*, defaults to 16):
45
+ Number of attention heads for each attention layer in the Transformer decoder.
46
+ num_key_value_heads (`int`, *optional*, defaults to 16):
47
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
48
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
49
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
50
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
51
+ by meanpooling all the original heads within that group. For more details, check out [this
52
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
53
+ `num_attention_heads`.
54
+ head_dim (`int`, *optional*, defaults to 256):
55
+ The attention head dimension.
56
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
57
+ The legacy activation function. It is overwritten by the `hidden_activation`.
58
+ hidden_activation (`str` or `function`, *optional*):
59
+ The non-linear activation function (function or string) in the decoder. Will default to `"gelu_pytorch_tanh"`
60
+ if not specified. `"gelu_pytorch_tanh"` uses an approximation of the `"gelu"` activation function.
61
+ max_position_embeddings (`int`, *optional*, defaults to 8192):
62
+ The maximum sequence length that this model might ever be used with.
63
+ initializer_range (`float`, *optional*, defaults to 0.02):
64
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
65
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
66
+ The epsilon used by the rms normalization layers.
67
+ use_cache (`bool`, *optional*, defaults to `True`):
68
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
69
+ relevant if `config.is_decoder=True`.
70
+ pad_token_id (`int`, *optional*, defaults to 0):
71
+ Padding token id.
72
+ eos_token_id (`int`, *optional*, defaults to 1):
73
+ End of stream token id.
74
+ bos_token_id (`int`, *optional*, defaults to 2):
75
+ Beginning of stream token id.
76
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
77
+ Whether to tie weight embeddings
78
+ rope_theta (`float`, *optional*, defaults to 10000.0):
79
+ The base period of the RoPE embeddings.
80
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
81
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
82
+ attention_dropout (`float`, *optional*, defaults to 0.0):
83
+ The dropout ratio for the attention probabilities.
84
+ use_adarms (`bool`, *optional*, defaults to `False`):
85
+ Whether to use ADARMS.
86
+ adarms_cond_dim (`int`, *optional*, defaults to `None`):
87
+ The dimension of the ADARMS condition.
88
+ ```python
89
+ >>> from transformers import GemmaModel, GemmaConfig
90
+ >>> # Initializing a Gemma gemma-7b style configuration
91
+ >>> configuration = GemmaConfig()
92
+ >>> # Initializing a model from the gemma-7b style configuration
93
+ >>> model = GemmaModel(configuration)
94
+ >>> # Accessing the model configuration
95
+ >>> configuration = model.config
96
+ ```"""
97
+
98
+ model_type = "gemma"
99
+ keys_to_ignore_at_inference = ["past_key_values"]
100
+ base_model_tp_plan = {
101
+ "layers.*.self_attn.q_proj": "colwise",
102
+ "layers.*.self_attn.k_proj": "colwise",
103
+ "layers.*.self_attn.v_proj": "colwise",
104
+ "layers.*.self_attn.o_proj": "rowwise",
105
+ "layers.*.mlp.gate_proj": "colwise",
106
+ "layers.*.mlp.up_proj": "colwise",
107
+ "layers.*.mlp.down_proj": "rowwise",
108
+ }
109
+ base_model_pp_plan = {
110
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
111
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
112
+ "norm": (["hidden_states"], ["hidden_states"]),
113
+ }
114
+
115
+ def __init__(
116
+ self,
117
+ vocab_size=256000,
118
+ hidden_size=3072,
119
+ intermediate_size=24576,
120
+ num_hidden_layers=28,
121
+ num_attention_heads=16,
122
+ num_key_value_heads=16,
123
+ head_dim=256,
124
+ hidden_act="gelu_pytorch_tanh",
125
+ hidden_activation=None,
126
+ max_position_embeddings=8192,
127
+ initializer_range=0.02,
128
+ rms_norm_eps=1e-6,
129
+ use_cache=True,
130
+ pad_token_id=0,
131
+ eos_token_id=1,
132
+ bos_token_id=2,
133
+ tie_word_embeddings=True,
134
+ rope_theta=10000.0,
135
+ attention_bias=False,
136
+ attention_dropout=0.0,
137
+ use_adarms: bool = False,
138
+ adarms_cond_dim: Optional[int] = None,
139
+ **kwargs,
140
+ ):
141
+ self.vocab_size = vocab_size
142
+ self.max_position_embeddings = max_position_embeddings
143
+ self.hidden_size = hidden_size
144
+ self.intermediate_size = intermediate_size
145
+ self.num_hidden_layers = num_hidden_layers
146
+ self.num_attention_heads = num_attention_heads
147
+ self.head_dim = head_dim
148
+ self.num_key_value_heads = num_key_value_heads
149
+ self.hidden_act = hidden_act
150
+ self.hidden_activation = hidden_activation
151
+ self.initializer_range = initializer_range
152
+ self.rms_norm_eps = rms_norm_eps
153
+ self.use_cache = use_cache
154
+ self.rope_theta = rope_theta
155
+ self.attention_bias = attention_bias
156
+ self.attention_dropout = attention_dropout
157
+ self.use_adarms = use_adarms
158
+ self.adarms_cond_dim = adarms_cond_dim
159
+
160
+ # Set default for adarms_cond_dim if use_adarms is True
161
+ if self.use_adarms and self.adarms_cond_dim is None:
162
+ self.adarms_cond_dim = self.hidden_size
163
+
164
+ super().__init__(
165
+ pad_token_id=pad_token_id,
166
+ bos_token_id=bos_token_id,
167
+ eos_token_id=eos_token_id,
168
+ tie_word_embeddings=tie_word_embeddings,
169
+ **kwargs,
170
+ )
171
+
172
+
173
+ __all__ = ["GemmaConfig"]
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/transformers_replace/models/gemma/modeling_gemma.py ADDED
@@ -0,0 +1,862 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/gemma/modular_gemma.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_gemma.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2024 Google Inc. HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+ from typing import Callable, Optional, Union
23
+
24
+ import torch
25
+ from torch import nn
26
+
27
+ from ...activations import ACT2FN
28
+ from ...cache_utils import Cache, DynamicCache
29
+ from ...generation import GenerationMixin
30
+ from ...masking_utils import create_causal_mask
31
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
32
+ from ...modeling_layers import GradientCheckpointingLayer
33
+ from ...modeling_outputs import (
34
+ BaseModelOutputWithPast,
35
+ CausalLMOutputWithPast,
36
+ SequenceClassifierOutputWithPast,
37
+ TokenClassifierOutput,
38
+ )
39
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
40
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
41
+ from ...processing_utils import Unpack
42
+ from ...utils import LossKwargs, auto_docstring, can_return_tuple, logging
43
+ from .configuration_gemma import GemmaConfig
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ class GemmaRMSNorm(nn.Module):
50
+ def __init__(self, dim: int, eps: float = 1e-6, cond_dim: Optional[int] = None):
51
+ super().__init__()
52
+ self.eps = eps
53
+ self.dim = dim
54
+ self.cond_dim = cond_dim
55
+
56
+ # Dense layer for adaptive normalization (if cond_dim is provided)
57
+ if cond_dim is not None:
58
+ #self.dense = nn.Linear(cond_dim, dim * 3, bias=True, dtype=torch.bfloat16)
59
+ self.dense = nn.Linear(cond_dim, dim * 3, bias=True)
60
+ # Initialize with zeros (matches source implementation)
61
+ nn.init.zeros_(self.dense.weight)
62
+ else:
63
+ self.weight = nn.Parameter(torch.zeros(dim, dtype=torch.bfloat16))
64
+ self.dense = None
65
+
66
+ def _norm(self, x):
67
+ # Compute variance in float32 (like the source implementation)
68
+ var = torch.mean(torch.square(x.float()), dim=-1, keepdim=True)
69
+ # Compute normalization in float32
70
+ normed_inputs = x * torch.rsqrt(var + self.eps)
71
+ return normed_inputs
72
+
73
+ def forward(self, x, cond=None):
74
+ dtype = x.dtype # original dtype, could be half-precision
75
+ normed_inputs = self._norm(x)
76
+
77
+ if cond is None or self.dense is None:
78
+ # regular RMSNorm
79
+ # scale by learned parameter in float32 (matches source implementation)
80
+ normed_inputs = normed_inputs * (1.0 + self.weight.float())
81
+ return normed_inputs.to(dtype), None # return in original dtype with None gate
82
+
83
+ # adaptive RMSNorm (if cond is provided and dense layer exists)
84
+ if cond.shape[-1] != self.cond_dim:
85
+ raise ValueError(f"Expected cond dimension {self.cond_dim}, got {cond.shape[-1]}")
86
+
87
+ #self.dense.to(dtype=torch.bfloat16).to(dtype=torch.float32)
88
+ modulation = self.dense(cond)
89
+ # Reshape modulation to broadcast properly: [batch, 1, features] for [batch, seq, features]
90
+ if len(x.shape) == 3: # [batch, seq, features]
91
+ modulation = modulation.unsqueeze(1)
92
+
93
+ scale, shift, gate = torch.chunk(modulation, 3, dim=-1)
94
+
95
+ # Apply adaptive normalization: use model weight dtype to ensure compatibility
96
+ # model_dtype = self.dense.weight.dtype # Use the model's dtype (bfloat16)
97
+ # scale = scale.to(model_dtype)
98
+ # shift = shift.to(model_dtype)
99
+ # gate = gate.to(model_dtype)
100
+ # normed_inputs = normed_inputs.to(model_dtype) # Convert normed_inputs to model dtype
101
+
102
+ normed_inputs = normed_inputs * (1 + scale.to(torch.float32)) + shift.to(torch.float32)
103
+
104
+ return normed_inputs.to(dtype), gate.to(dtype)
105
+
106
+ def extra_repr(self):
107
+ repr_str = f"{tuple(self.weight.shape)}, eps={self.eps}"
108
+ if self.dense is not None:
109
+ repr_str += f", adaptive=True, cond_dim={self.cond_dim}"
110
+ return repr_str
111
+
112
+
113
+ class GemmaMLP(nn.Module):
114
+ def __init__(self, config):
115
+ super().__init__()
116
+ self.config = config
117
+ self.hidden_size = config.hidden_size
118
+ self.intermediate_size = config.intermediate_size
119
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
120
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
121
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
122
+ self.act_fn = ACT2FN[config.hidden_act]
123
+
124
+ def forward(self, x):
125
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
126
+ return down_proj
127
+
128
+
129
+ class GemmaRotaryEmbedding(nn.Module):
130
+ def __init__(self, config: GemmaConfig, device=None):
131
+ super().__init__()
132
+ # BC: "rope_type" was originally "type"
133
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
134
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
135
+ else:
136
+ self.rope_type = "default"
137
+ self.max_seq_len_cached = config.max_position_embeddings
138
+ self.original_max_seq_len = config.max_position_embeddings
139
+
140
+ self.config = config
141
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
142
+
143
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
144
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
145
+ self.original_inv_freq = self.inv_freq
146
+
147
+ @torch.no_grad()
148
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
149
+ def forward(self, x, position_ids):
150
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
151
+ position_ids_expanded = position_ids[:, None, :].float()
152
+
153
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
154
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
155
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
156
+ emb = torch.cat((freqs, freqs), dim=-1)
157
+ cos = emb.cos() * self.attention_scaling
158
+ sin = emb.sin() * self.attention_scaling
159
+
160
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
161
+
162
+
163
+ def rotate_half(x):
164
+ """Rotates half the hidden dims of the input."""
165
+ x1 = x[..., : x.shape[-1] // 2]
166
+ x2 = x[..., x.shape[-1] // 2 :]
167
+ return torch.cat((-x2, x1), dim=-1)
168
+
169
+
170
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
171
+ """Applies Rotary Position Embedding to the query and key tensors.
172
+
173
+ Args:
174
+ q (`torch.Tensor`): The query tensor.
175
+ k (`torch.Tensor`): The key tensor.
176
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
177
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
178
+ position_ids (`torch.Tensor`, *optional*):
179
+ Deprecated and unused.
180
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
181
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
182
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
183
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
184
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
185
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
186
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
187
+ Returns:
188
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
189
+ """
190
+ cos = cos.unsqueeze(unsqueeze_dim)
191
+ sin = sin.unsqueeze(unsqueeze_dim)
192
+ q_embed = (q * cos) + (rotate_half(q) * sin)
193
+ k_embed = (k * cos) + (rotate_half(k) * sin)
194
+ return q_embed, k_embed
195
+
196
+
197
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
198
+ """
199
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
200
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
201
+ """
202
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
203
+ if n_rep == 1:
204
+ return hidden_states
205
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
206
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
207
+
208
+
209
+ def _gated_residual(x, y, gate):
210
+ """
211
+ Applies gated residual connection with optional gate parameter.
212
+
213
+ Args:
214
+ x: Input tensor (residual)
215
+ y: Output tensor to be added
216
+ gate: Optional gate tensor to modulate the addition
217
+
218
+ Returns:
219
+ x + y if gate is None, otherwise x + y * gate
220
+ """
221
+ if x is None and y is None:
222
+ return None
223
+ if x is None or y is None:
224
+ return x if x is not None else y
225
+ if gate is None:
226
+ return x + y
227
+ return x + y * gate
228
+
229
+
230
+ def eager_attention_forward(
231
+ module: nn.Module,
232
+ query: torch.Tensor,
233
+ key: torch.Tensor,
234
+ value: torch.Tensor,
235
+ attention_mask: Optional[torch.Tensor],
236
+ scaling: float,
237
+ dropout: float = 0.0,
238
+ **kwargs,
239
+ ):
240
+ key_states = repeat_kv(key, module.num_key_value_groups)
241
+ value_states = repeat_kv(value, module.num_key_value_groups)
242
+
243
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
244
+ if attention_mask is not None:
245
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
246
+ attn_weights = attn_weights + causal_mask
247
+
248
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
249
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
250
+ attn_output = torch.matmul(attn_weights, value_states)
251
+ attn_output = attn_output.transpose(1, 2).contiguous()
252
+
253
+ return attn_output, attn_weights
254
+
255
+
256
+ class GemmaAttention(nn.Module):
257
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
258
+
259
+ def __init__(self, config: GemmaConfig, layer_idx: int):
260
+ super().__init__()
261
+ self.config = config
262
+ self.layer_idx = layer_idx
263
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
264
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
265
+ self.scaling = self.head_dim**-0.5
266
+ self.attention_dropout = config.attention_dropout
267
+ self.is_causal = True
268
+
269
+ self.q_proj = nn.Linear(
270
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
271
+ )
272
+ self.k_proj = nn.Linear(
273
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
274
+ )
275
+ self.v_proj = nn.Linear(
276
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
277
+ )
278
+ self.o_proj = nn.Linear(
279
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
280
+ )
281
+
282
+ def forward(
283
+ self,
284
+ hidden_states: torch.Tensor,
285
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
286
+ attention_mask: Optional[torch.Tensor],
287
+ past_key_value: Optional[Cache] = None,
288
+ cache_position: Optional[torch.LongTensor] = None,
289
+ use_cache: bool = False,
290
+ **kwargs: Unpack[FlashAttentionKwargs],
291
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
292
+ input_shape = hidden_states.shape[:-1]
293
+ hidden_shape = (*input_shape, -1, self.head_dim)
294
+
295
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
296
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
297
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
298
+
299
+ cos, sin = position_embeddings
300
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
301
+
302
+ # Use cache if provided
303
+ if past_key_value is not None:
304
+ if use_cache:
305
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
306
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
307
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
308
+ else:
309
+ key_states = torch.cat([past_key_value[self.layer_idx][0], key_states], dim=2)
310
+ value_states = torch.cat([past_key_value[self.layer_idx][1], value_states], dim=2)
311
+
312
+ attention_interface: Callable = eager_attention_forward
313
+ if self.config._attn_implementation != "eager":
314
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
315
+
316
+ attn_output, attn_weights = attention_interface(
317
+ self,
318
+ query_states,
319
+ key_states,
320
+ value_states,
321
+ attention_mask,
322
+ dropout=0.0 if not self.training else self.attention_dropout,
323
+ scaling=self.scaling,
324
+ **kwargs,
325
+ )
326
+
327
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
328
+ attn_output = self.o_proj(attn_output)
329
+ return attn_output, attn_weights
330
+
331
+
332
+ class GemmaDecoderLayer(GradientCheckpointingLayer):
333
+ def __init__(self, config: GemmaConfig, layer_idx: int):
334
+ super().__init__()
335
+ self.hidden_size = config.hidden_size
336
+
337
+ self.self_attn = GemmaAttention(config=config, layer_idx=layer_idx)
338
+
339
+ self.mlp = GemmaMLP(config)
340
+ cond_dim = getattr(config, 'adarms_cond_dim', None) if getattr(config, 'use_adarms', False) else None
341
+ self.input_layernorm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps, cond_dim=cond_dim)
342
+ self.post_attention_layernorm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps, cond_dim=cond_dim)
343
+
344
+ def forward(
345
+ self,
346
+ hidden_states: torch.Tensor,
347
+ attention_mask: Optional[torch.Tensor] = None,
348
+ position_ids: Optional[torch.LongTensor] = None,
349
+ past_key_value: Optional[Cache] = None,
350
+ output_attentions: Optional[bool] = False,
351
+ use_cache: Optional[bool] = False,
352
+ cache_position: Optional[torch.LongTensor] = None,
353
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
354
+ adarms_cond: Optional[torch.Tensor] = None,
355
+ **kwargs: Unpack[FlashAttentionKwargs],
356
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
357
+ residual = hidden_states
358
+ hidden_states, gate = self.input_layernorm(hidden_states, adarms_cond)
359
+
360
+ # Self Attention
361
+ hidden_states, self_attn_weights = self.self_attn(
362
+ hidden_states=hidden_states,
363
+ attention_mask=attention_mask,
364
+ position_ids=position_ids,
365
+ past_key_value=past_key_value,
366
+ output_attentions=output_attentions,
367
+ use_cache=use_cache,
368
+ cache_position=cache_position,
369
+ position_embeddings=position_embeddings,
370
+ **kwargs,
371
+ )
372
+ hidden_states = _gated_residual(residual, hidden_states, gate)
373
+
374
+ # Fully Connected
375
+ residual = hidden_states
376
+ hidden_states, gate = self.post_attention_layernorm(hidden_states, adarms_cond)
377
+ hidden_states = self.mlp(hidden_states)
378
+ hidden_states = _gated_residual(residual, hidden_states, gate)
379
+
380
+ outputs = (hidden_states,)
381
+ if output_attentions:
382
+ outputs += (self_attn_weights,)
383
+
384
+ return outputs
385
+
386
+
387
+ @auto_docstring
388
+ class GemmaPreTrainedModel(PreTrainedModel):
389
+ config_class = GemmaConfig
390
+ base_model_prefix = "model"
391
+ supports_gradient_checkpointing = True
392
+ _no_split_modules = ["GemmaDecoderLayer"]
393
+ _skip_keys_device_placement = ["past_key_values"]
394
+ _supports_flash_attn_3 = True
395
+ _supports_flash_attn_2 = True
396
+ _supports_sdpa = True
397
+ _supports_flex_attn = True
398
+ _supports_cache_class = True
399
+ _supports_quantized_cache = True
400
+ _supports_static_cache = True
401
+ _supports_attention_backend = True
402
+
403
+ def _init_weights(self, module):
404
+ std = self.config.initializer_range
405
+ if isinstance(module, nn.Linear):
406
+ module.weight.data.normal_(mean=0.0, std=std)
407
+ if module.bias is not None:
408
+ module.bias.data.zero_()
409
+ elif isinstance(module, nn.Embedding):
410
+ module.weight.data.normal_(mean=0.0, std=std)
411
+ if module.padding_idx is not None:
412
+ module.weight.data[module.padding_idx].zero_()
413
+ elif isinstance(module, GemmaRMSNorm):
414
+ if hasattr(module, 'weight'):
415
+ module.weight.data.fill_(1.0)
416
+
417
+
418
+ @auto_docstring
419
+ class GemmaModel(GemmaPreTrainedModel):
420
+ def __init__(self, config: GemmaConfig):
421
+ super().__init__(config)
422
+ self.padding_idx = config.pad_token_id
423
+ self.vocab_size = config.vocab_size
424
+
425
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
426
+ self.layers = nn.ModuleList(
427
+ [GemmaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
428
+ )
429
+
430
+ cond_dim = getattr(config, 'adarms_cond_dim', None) if getattr(config, 'use_adarms', False) else None
431
+ self.norm = GemmaRMSNorm(config.hidden_size, eps=config.rms_norm_eps, cond_dim=cond_dim)
432
+ self.rotary_emb = GemmaRotaryEmbedding(config=config)
433
+ self.gradient_checkpointing = False
434
+
435
+ # Initialize weights and apply final processing
436
+ self.post_init()
437
+
438
+ def get_input_embeddings(self):
439
+ return self.embed_tokens
440
+
441
+ def set_input_embeddings(self, value):
442
+ self.embed_tokens = value
443
+
444
+ @can_return_tuple
445
+ @auto_docstring
446
+ def forward(
447
+ self,
448
+ input_ids: Optional[torch.LongTensor] = None,
449
+ attention_mask: Optional[torch.Tensor] = None,
450
+ position_ids: Optional[torch.LongTensor] = None,
451
+ past_key_values: Optional[Cache] = None,
452
+ inputs_embeds: Optional[torch.FloatTensor] = None,
453
+ use_cache: Optional[bool] = None,
454
+ output_attentions: Optional[bool] = None,
455
+ output_hidden_states: Optional[bool] = None,
456
+ cache_position: Optional[torch.LongTensor] = None,
457
+ adarms_cond: Optional[torch.Tensor] = None,
458
+ **kwargs: Unpack[FlashAttentionKwargs],
459
+ ) -> BaseModelOutputWithPast:
460
+ """
461
+ adarms_cond (`torch.Tensor` of shape `(batch_size, cond_dim)`, *optional*):
462
+ Condition for ADARMS.
463
+ """
464
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
465
+ output_hidden_states = (
466
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
467
+ )
468
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
469
+
470
+ if (input_ids is None) ^ (inputs_embeds is not None):
471
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
472
+
473
+ if self.gradient_checkpointing and self.training and use_cache:
474
+ logger.warning_once(
475
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
476
+ )
477
+ use_cache = False
478
+
479
+ if inputs_embeds is None:
480
+ inputs_embeds = self.embed_tokens(input_ids)
481
+
482
+ if use_cache and past_key_values is None:
483
+ past_key_values = DynamicCache()
484
+
485
+ if cache_position is None:
486
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
487
+ cache_position = torch.arange(
488
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
489
+ )
490
+
491
+ if position_ids is None:
492
+ position_ids = cache_position.unsqueeze(0)
493
+
494
+ causal_mask = create_causal_mask(
495
+ config=self.config,
496
+ input_embeds=inputs_embeds,
497
+ attention_mask=attention_mask,
498
+ cache_position=cache_position,
499
+ past_key_values=past_key_values,
500
+ position_ids=position_ids,
501
+ )
502
+
503
+ # embed positions
504
+ hidden_states = inputs_embeds
505
+ # Convert to bfloat16 if the first layer uses bfloat16
506
+ if len(self.layers) > 0 and self.layers[0].self_attn.q_proj.weight.dtype == torch.bfloat16:
507
+ hidden_states = hidden_states.to(torch.bfloat16)
508
+
509
+ # create position embeddings to be shared across the decoder layers
510
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
511
+
512
+ # normalized
513
+ # Gemma downcasts the below to float16, causing sqrt(3072)=55.4256 to become 55.5
514
+ # See https://github.com/huggingface/transformers/pull/29402
515
+ normalizer = torch.tensor(self.config.hidden_size**0.5, dtype=hidden_states.dtype)
516
+ #hidden_states = hidden_states * normalizer
517
+
518
+ # decoder layers
519
+ all_hidden_states = () if output_hidden_states else None
520
+ all_self_attns = () if output_attentions else None
521
+
522
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
523
+ if output_hidden_states:
524
+ all_hidden_states += (hidden_states,)
525
+
526
+ layer_outputs = decoder_layer(
527
+ hidden_states,
528
+ attention_mask=causal_mask,
529
+ position_ids=position_ids,
530
+ past_key_value=past_key_values,
531
+ output_attentions=output_attentions,
532
+ use_cache=use_cache,
533
+ cache_position=cache_position,
534
+ position_embeddings=position_embeddings,
535
+ adarms_cond=adarms_cond,
536
+ **kwargs,
537
+ )
538
+
539
+ hidden_states = layer_outputs[0]
540
+
541
+ if output_attentions:
542
+ all_self_attns += (layer_outputs[1],)
543
+
544
+ hidden_states, _ = self.norm(hidden_states, adarms_cond)
545
+
546
+ # add hidden states from the last decoder layer
547
+ if output_hidden_states:
548
+ all_hidden_states += (hidden_states,)
549
+
550
+ return BaseModelOutputWithPast(
551
+ last_hidden_state=hidden_states,
552
+ past_key_values=past_key_values if use_cache else None,
553
+ hidden_states=all_hidden_states,
554
+ attentions=all_self_attns,
555
+ )
556
+
557
+
558
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
559
+
560
+
561
+ @auto_docstring
562
+ class GemmaForCausalLM(GemmaPreTrainedModel, GenerationMixin):
563
+ _tied_weights_keys = ["lm_head.weight"]
564
+ _tp_plan = {"lm_head": "colwise_rep"}
565
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
566
+
567
+ def __init__(self, config):
568
+ super().__init__(config)
569
+ self.model = GemmaModel(config)
570
+ self.vocab_size = config.vocab_size
571
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
572
+
573
+ # Initialize weights and apply final processing
574
+ self.post_init()
575
+
576
+ def get_input_embeddings(self):
577
+ return self.model.embed_tokens
578
+
579
+ def set_input_embeddings(self, value):
580
+ self.model.embed_tokens = value
581
+
582
+ def get_output_embeddings(self):
583
+ return self.lm_head
584
+
585
+ def set_output_embeddings(self, new_embeddings):
586
+ self.lm_head = new_embeddings
587
+
588
+ def set_decoder(self, decoder):
589
+ self.model = decoder
590
+
591
+ def get_decoder(self):
592
+ return self.model
593
+
594
+ @can_return_tuple
595
+ @auto_docstring
596
+ def forward(
597
+ self,
598
+ input_ids: Optional[torch.LongTensor] = None,
599
+ attention_mask: Optional[torch.Tensor] = None,
600
+ position_ids: Optional[torch.LongTensor] = None,
601
+ past_key_values: Optional[Cache] = None,
602
+ inputs_embeds: Optional[torch.FloatTensor] = None,
603
+ labels: Optional[torch.LongTensor] = None,
604
+ use_cache: Optional[bool] = None,
605
+ output_attentions: Optional[bool] = None,
606
+ output_hidden_states: Optional[bool] = None,
607
+ cache_position: Optional[torch.LongTensor] = None,
608
+ logits_to_keep: Union[int, torch.Tensor] = 0,
609
+ adarms_cond: Optional[torch.Tensor] = None,
610
+ **kwargs: Unpack[KwargsForCausalLM],
611
+ ) -> CausalLMOutputWithPast:
612
+ r"""
613
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
614
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
615
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
616
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
617
+
618
+ adarms_cond (`torch.Tensor` of shape `(batch_size, cond_dim)`, *optional*):
619
+ Condition for ADARMS.
620
+
621
+ Example:
622
+
623
+ ```python
624
+ >>> from transformers import AutoTokenizer, GemmaForCausalLM
625
+
626
+ >>> model = GemmaForCausalLM.from_pretrained("google/gemma-7b")
627
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b")
628
+
629
+ >>> prompt = "What is your favorite condiment?"
630
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
631
+
632
+ >>> # Generate
633
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
634
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
635
+ "What is your favorite condiment?"
636
+ ```"""
637
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
638
+ output_hidden_states = (
639
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
640
+ )
641
+
642
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
643
+ outputs: BaseModelOutputWithPast = self.model(
644
+ input_ids=input_ids,
645
+ attention_mask=attention_mask,
646
+ position_ids=position_ids,
647
+ past_key_values=past_key_values,
648
+ inputs_embeds=inputs_embeds,
649
+ use_cache=use_cache,
650
+ output_attentions=output_attentions,
651
+ output_hidden_states=output_hidden_states,
652
+ cache_position=cache_position,
653
+ adarms_cond=adarms_cond,
654
+ **kwargs,
655
+ )
656
+
657
+ hidden_states = outputs.last_hidden_state
658
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
659
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
660
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
661
+
662
+ loss = None
663
+ if labels is not None:
664
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
665
+
666
+ return CausalLMOutputWithPast(
667
+ loss=loss,
668
+ logits=logits,
669
+ past_key_values=outputs.past_key_values,
670
+ hidden_states=outputs.hidden_states,
671
+ attentions=outputs.attentions,
672
+ )
673
+
674
+
675
+ @auto_docstring(
676
+ custom_intro="""
677
+ The Gemma Model transformer with a sequence classification head on top (linear layer).
678
+
679
+ [`GemmaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
680
+ (e.g. GPT-2) do.
681
+
682
+ Since it does classification on the last token, it requires to know the position of the last token. If a
683
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
684
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
685
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
686
+ each row of the batch).
687
+ """
688
+ )
689
+ class GemmaForSequenceClassification(GemmaPreTrainedModel):
690
+ def __init__(self, config):
691
+ super().__init__(config)
692
+ self.num_labels = config.num_labels
693
+ self.model = GemmaModel(config)
694
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
695
+
696
+ # Initialize weights and apply final processing
697
+ self.post_init()
698
+
699
+ def get_input_embeddings(self):
700
+ return self.model.embed_tokens
701
+
702
+ def set_input_embeddings(self, value):
703
+ self.model.embed_tokens = value
704
+
705
+ @can_return_tuple
706
+ @auto_docstring
707
+ def forward(
708
+ self,
709
+ input_ids: Optional[torch.LongTensor] = None,
710
+ attention_mask: Optional[torch.Tensor] = None,
711
+ position_ids: Optional[torch.LongTensor] = None,
712
+ past_key_values: Optional[Cache] = None,
713
+ inputs_embeds: Optional[torch.FloatTensor] = None,
714
+ labels: Optional[torch.LongTensor] = None,
715
+ use_cache: Optional[bool] = None,
716
+ output_attentions: Optional[bool] = None,
717
+ output_hidden_states: Optional[bool] = None,
718
+ adarms_cond: Optional[torch.Tensor] = None,
719
+ ) -> SequenceClassifierOutputWithPast:
720
+ r"""
721
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
722
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
723
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
724
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
725
+
726
+ adarms_cond (`torch.Tensor` of shape `(batch_size, cond_dim)`, *optional*):
727
+ Condition for ADARMS.
728
+ """
729
+
730
+ transformer_outputs: BaseModelOutputWithPast = self.model(
731
+ input_ids,
732
+ attention_mask=attention_mask,
733
+ position_ids=position_ids,
734
+ past_key_values=past_key_values,
735
+ inputs_embeds=inputs_embeds,
736
+ use_cache=use_cache,
737
+ output_attentions=output_attentions,
738
+ output_hidden_states=output_hidden_states,
739
+ adarms_cond=adarms_cond,
740
+ )
741
+ hidden_states = transformer_outputs.last_hidden_state
742
+ logits = self.score(hidden_states)
743
+
744
+ if input_ids is not None:
745
+ batch_size = input_ids.shape[0]
746
+ else:
747
+ batch_size = inputs_embeds.shape[0]
748
+
749
+ if self.config.pad_token_id is None and batch_size != 1:
750
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
751
+ if self.config.pad_token_id is None:
752
+ last_non_pad_token = -1
753
+ elif input_ids is not None:
754
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
755
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
756
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
757
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
758
+ else:
759
+ last_non_pad_token = -1
760
+ logger.warning_once(
761
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
762
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
763
+ )
764
+
765
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
766
+
767
+ loss = None
768
+ if labels is not None:
769
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
770
+
771
+ return SequenceClassifierOutputWithPast(
772
+ loss=loss,
773
+ logits=pooled_logits,
774
+ past_key_values=transformer_outputs.past_key_values,
775
+ hidden_states=transformer_outputs.hidden_states,
776
+ attentions=transformer_outputs.attentions,
777
+ )
778
+
779
+
780
+ @auto_docstring
781
+ class GemmaForTokenClassification(GemmaPreTrainedModel):
782
+ def __init__(self, config):
783
+ super().__init__(config)
784
+ self.num_labels = config.num_labels
785
+ self.model = GemmaModel(config)
786
+ if getattr(config, "classifier_dropout", None) is not None:
787
+ classifier_dropout = config.classifier_dropout
788
+ elif getattr(config, "hidden_dropout", None) is not None:
789
+ classifier_dropout = config.hidden_dropout
790
+ else:
791
+ classifier_dropout = 0.1
792
+ self.dropout = nn.Dropout(classifier_dropout)
793
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
794
+
795
+ # Initialize weights and apply final processing
796
+ self.post_init()
797
+
798
+ def get_input_embeddings(self):
799
+ return self.model.embed_tokens
800
+
801
+ def set_input_embeddings(self, value):
802
+ self.model.embed_tokens = value
803
+
804
+ @can_return_tuple
805
+ @auto_docstring
806
+ def forward(
807
+ self,
808
+ input_ids: Optional[torch.LongTensor] = None,
809
+ attention_mask: Optional[torch.Tensor] = None,
810
+ position_ids: Optional[torch.LongTensor] = None,
811
+ past_key_values: Optional[Cache] = None,
812
+ inputs_embeds: Optional[torch.FloatTensor] = None,
813
+ labels: Optional[torch.LongTensor] = None,
814
+ use_cache: Optional[bool] = None,
815
+ output_attentions: Optional[bool] = None,
816
+ output_hidden_states: Optional[bool] = None,
817
+ adarms_cond: Optional[torch.Tensor] = None,
818
+ ) -> TokenClassifierOutput:
819
+ r"""
820
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
821
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
822
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
823
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
824
+
825
+ adarms_cond (`torch.Tensor` of shape `(batch_size, cond_dim)`, *optional*):
826
+ Condition for ADARMS.
827
+ """
828
+
829
+ outputs: BaseModelOutputWithPast = self.model(
830
+ input_ids,
831
+ attention_mask=attention_mask,
832
+ position_ids=position_ids,
833
+ past_key_values=past_key_values,
834
+ inputs_embeds=inputs_embeds,
835
+ use_cache=use_cache,
836
+ output_attentions=output_attentions,
837
+ output_hidden_states=output_hidden_states,
838
+ adarms_cond=adarms_cond,
839
+ )
840
+ sequence_output = outputs.last_hidden_state
841
+ sequence_output = self.dropout(sequence_output)
842
+ logits = self.score(sequence_output)
843
+
844
+ loss = None
845
+ if labels is not None:
846
+ loss = self.loss_function(logits, labels, self.config)
847
+
848
+ return TokenClassifierOutput(
849
+ loss=loss,
850
+ logits=logits,
851
+ hidden_states=outputs.hidden_states,
852
+ attentions=outputs.attentions,
853
+ )
854
+
855
+
856
+ __all__ = [
857
+ "GemmaModel",
858
+ "GemmaForCausalLM",
859
+ "GemmaForSequenceClassification",
860
+ "GemmaForTokenClassification",
861
+ "GemmaPreTrainedModel",
862
+ ]
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/transformers_replace/models/paligemma/modeling_paligemma.py ADDED
@@ -0,0 +1,622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch PaliGemmamodel."""
16
+
17
+ from dataclasses import dataclass
18
+ from typing import Optional, Union
19
+
20
+ import torch
21
+ import torch.utils.checkpoint
22
+ from torch import nn
23
+
24
+ from ...cache_utils import Cache, HybridCache, StaticCache
25
+ from ...generation import GenerationMixin
26
+ from ...modeling_flash_attention_utils import FlashAttentionKwargs
27
+ from ...modeling_outputs import BaseModelOutputWithPast
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...processing_utils import Unpack
30
+ from ...utils import LossKwargs, ModelOutput, auto_docstring, can_return_tuple, is_torchdynamo_compiling, logging
31
+ from ..auto import AutoModel
32
+ from .configuration_paligemma import PaliGemmaConfig
33
+
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ @dataclass
39
+ @auto_docstring(
40
+ custom_intro="""
41
+ Base class for Paligemma outputs, with hidden states and attentions.
42
+ """
43
+ )
44
+ class PaligemmaModelOutputWithPast(BaseModelOutputWithPast):
45
+ r"""
46
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
47
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
48
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
49
+
50
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
51
+ `past_key_values` input) to speed up sequential decoding.
52
+ image_hidden_states (`torch.FloatTensor`, *optional*):
53
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
54
+ image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
55
+ """
56
+
57
+ image_hidden_states: Optional[torch.FloatTensor] = None
58
+
59
+
60
+ @dataclass
61
+ @auto_docstring(
62
+ custom_intro="""
63
+ Base class for PaliGemma causal language model (or autoregressive) outputs.
64
+ """
65
+ )
66
+ class PaliGemmaCausalLMOutputWithPast(ModelOutput):
67
+ r"""
68
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
69
+ Language modeling loss (for next-token prediction).
70
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.text_config.vocab_size)`):
71
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
72
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
73
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
74
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
75
+
76
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
77
+ `past_key_values` input) to speed up sequential decoding.
78
+ image_hidden_states (`torch.FloatTensor`, *optional*):
79
+ A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
80
+ image_hidden_states of the model produced by the vision encoder after projecting last hidden state.
81
+ """
82
+
83
+ loss: Optional[torch.FloatTensor] = None
84
+ logits: Optional[torch.FloatTensor] = None
85
+ past_key_values: Optional[Union[list[torch.FloatTensor], Cache]] = None
86
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
87
+ attentions: Optional[tuple[torch.FloatTensor]] = None
88
+ image_hidden_states: Optional[torch.FloatTensor] = None
89
+
90
+
91
+ class PaliGemmaMultiModalProjector(nn.Module):
92
+ def __init__(self, config: PaliGemmaConfig):
93
+ super().__init__()
94
+ self.linear = nn.Linear(config.vision_config.hidden_size, config.vision_config.projection_dim, bias=True)
95
+
96
+ def forward(self, image_features):
97
+ hidden_states = self.linear(image_features)
98
+
99
+ return hidden_states
100
+
101
+
102
+ @auto_docstring
103
+ class PaliGemmaPreTrainedModel(PreTrainedModel):
104
+ config_class = PaliGemmaConfig
105
+ base_model_prefix = ""
106
+ supports_gradient_checkpointing = True
107
+ _no_split_modules = ["PaliGemmaMultiModalProjector"]
108
+ _skip_keys_device_placement = "past_key_values"
109
+ _supports_cache_class = True
110
+ _supports_quantized_cache = True
111
+ _supports_static_cache = True
112
+ _supports_flash_attn_2 = True
113
+ _supports_sdpa = True
114
+ _supports_flex_attn = True
115
+ _supports_attention_backend = True
116
+
117
+ def _init_weights(self, module):
118
+ # important: this ported version of PaliGemmaisn't meant for training from scratch - only
119
+ # inference and fine-tuning
120
+ std = getattr(self.config, "initializer_range", self.config.get_text_config().initializer_range)
121
+
122
+ if isinstance(module, nn.Linear):
123
+ module.weight.data.normal_(mean=0.0, std=std)
124
+ if module.bias is not None:
125
+ module.bias.data.zero_()
126
+
127
+
128
+ @auto_docstring(
129
+ custom_intro="""
130
+ The Base Paligemma model which consists of a vision backbone and a language model withou language modeling head.,
131
+ """
132
+ )
133
+ class PaliGemmaModel(PaliGemmaPreTrainedModel):
134
+ _checkpoint_conversion_mapping = {"language_model.model": "language_model"}
135
+ # we are filtering the logits/labels so we shouldn't divide the loss based on num_items_in_batch
136
+ accepts_loss_kwargs = False
137
+
138
+ def __init__(self, config: PaliGemmaConfig):
139
+ super().__init__(config)
140
+ self.vision_tower = AutoModel.from_config(config=config.vision_config)
141
+ self.multi_modal_projector = PaliGemmaMultiModalProjector(config)
142
+ self.vocab_size = config.text_config.vocab_size
143
+
144
+ language_model = AutoModel.from_config(config=config.text_config)
145
+ self.language_model = language_model
146
+
147
+ self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
148
+ self.post_init()
149
+
150
+ # Copied from transformers.models.llava.modeling_llava.LlavaModel.get_input_embeddings with Llava->PaliGemma
151
+ def get_input_embeddings(self):
152
+ return self.language_model.get_input_embeddings()
153
+
154
+ # Copied from transformers.models.llava.modeling_llava.LlavaModel.set_input_embeddings with Llava->PaliGemma
155
+ def set_input_embeddings(self, value):
156
+ self.language_model.set_input_embeddings(value)
157
+
158
+ def set_decoder(self, decoder):
159
+ self.language_model = decoder
160
+
161
+ def get_decoder(self):
162
+ return self.language_model
163
+
164
+ def _update_causal_mask(
165
+ self,
166
+ attention_mask,
167
+ token_type_ids=None,
168
+ past_key_values=None,
169
+ cache_position=None,
170
+ input_tensor=None,
171
+ is_training: Optional[bool] = None,
172
+ ):
173
+ if self.config.text_config._attn_implementation == "flash_attention_2":
174
+ if attention_mask is not None and 0.0 in attention_mask:
175
+ return attention_mask
176
+ return None
177
+ is_training = is_training if is_training is not None else self.training
178
+ using_static_cache = isinstance(past_key_values, StaticCache)
179
+ min_dtype = torch.finfo(self.dtype).min
180
+ if input_tensor is None:
181
+ input_tensor = attention_mask
182
+
183
+ inputs_lead_dim, sequence_length = input_tensor.shape[:2]
184
+ if using_static_cache:
185
+ target_length = past_key_values.get_max_cache_shape()
186
+ elif isinstance(past_key_values, HybridCache):
187
+ target_length = past_key_values.get_max_cache_shape()
188
+ else:
189
+ target_length = (
190
+ attention_mask.shape[-1]
191
+ if isinstance(attention_mask, torch.Tensor)
192
+ else cache_position[0] + sequence_length + 1
193
+ )
194
+
195
+ if attention_mask is not None and attention_mask.dim() == 4:
196
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
197
+ return attention_mask
198
+
199
+ causal_mask = torch.full(
200
+ (sequence_length, target_length), fill_value=min_dtype, dtype=self.dtype, device=cache_position.device
201
+ )
202
+ # Causal diagonal mask only if training, otherwise attend to the whole prefix. Training-specific attn for prefix is handled below
203
+ if sequence_length != 1:
204
+ if is_training:
205
+ causal_mask = torch.triu(causal_mask, diagonal=1)
206
+ else:
207
+ causal_mask[:, :sequence_length] = 0.0
208
+
209
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
210
+ causal_mask = causal_mask[None, None, :, :].expand(inputs_lead_dim, 1, -1, -1)
211
+ if attention_mask is not None:
212
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
213
+ mask_length = attention_mask.shape[-1]
214
+
215
+ # First unmask prefix tokens during training
216
+ if is_training:
217
+ if token_type_ids is None:
218
+ raise ValueError("Token type ids must be provided during training")
219
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
220
+ token_type_ids[:, None, None, :].to(causal_mask.device) == 0, 0
221
+ )
222
+
223
+ # Then apply padding mask (will mask pad tokens)
224
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(causal_mask.device)
225
+ padding_mask = padding_mask == 0
226
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
227
+ padding_mask, min_dtype
228
+ )
229
+
230
+ return causal_mask
231
+
232
+ def get_image_features(self, pixel_values: torch.FloatTensor):
233
+ """
234
+ Obtains image last hidden states from the vision tower and apply multimodal projection.
235
+
236
+ Args:
237
+ pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
238
+ The tensors corresponding to the input images.
239
+ Returns:
240
+ image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
241
+ """
242
+ image_outputs = self.vision_tower(pixel_values)
243
+ selected_image_feature = image_outputs.last_hidden_state
244
+ image_features = self.multi_modal_projector(selected_image_feature)
245
+ return image_features
246
+
247
+ @can_return_tuple
248
+ @auto_docstring
249
+ def forward(
250
+ self,
251
+ input_ids: torch.LongTensor = None,
252
+ pixel_values: torch.FloatTensor = None,
253
+ attention_mask: Optional[torch.Tensor] = None,
254
+ position_ids: Optional[torch.LongTensor] = None,
255
+ past_key_values: Optional[Union[list[torch.FloatTensor], Cache]] = None,
256
+ token_type_ids: Optional[torch.LongTensor] = None,
257
+ cache_position: Optional[torch.LongTensor] = None,
258
+ inputs_embeds: Optional[torch.FloatTensor] = None,
259
+ labels: Optional[torch.LongTensor] = None,
260
+ use_cache: Optional[bool] = None,
261
+ output_attentions: Optional[bool] = None,
262
+ output_hidden_states: Optional[bool] = None,
263
+ return_dict: Optional[bool] = None,
264
+ **kwargs: Unpack[FlashAttentionKwargs],
265
+ ) -> Union[tuple, PaligemmaModelOutputWithPast]:
266
+ r"""
267
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
268
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
269
+ config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
270
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
271
+
272
+ Example:
273
+
274
+ ```python
275
+ >>> from PIL import Image
276
+ >>> import requests
277
+ >>> from transformers import AutoProcessor, PaliGemmaForConditionalGeneration
278
+
279
+ >>> model = PaliGemmaForConditionalGeneration.from_pretrained("google/paligemma2-3b-mix-224")
280
+ >>> processor = AutoProcessor.from_pretrained("google/paligemma2-3b-mix-224")
281
+
282
+ >>> prompt = "Where is the cat standing?"
283
+ >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
284
+ >>> image = Image.open(requests.get(url, stream=True).raw)
285
+
286
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
287
+
288
+ >>> # Generate
289
+ >>> generate_ids = model.generate(**inputs,)
290
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
291
+ "Where is the cat standing?\nsnow"
292
+ ```"""
293
+
294
+ if (input_ids is None) ^ (inputs_embeds is not None):
295
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
296
+
297
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
298
+ output_hidden_states = (
299
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
300
+ )
301
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
302
+
303
+ is_training = token_type_ids is not None and labels is not None
304
+
305
+ # Replace image id woth PAD if the image token if OOV, to avoid index-errors
306
+ if input_ids is not None and self.config.image_token_id >= self.vocab_size:
307
+ special_image_mask = input_ids == self.config.image_token_id
308
+ llm_input_ids = input_ids.clone()
309
+ llm_input_ids[special_image_mask] = 0
310
+ else:
311
+ llm_input_ids = input_ids
312
+
313
+ if inputs_embeds is None:
314
+ inputs_embeds = self.get_input_embeddings()(llm_input_ids)
315
+
316
+ if cache_position is None:
317
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
318
+ cache_position = torch.arange(
319
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
320
+ )
321
+
322
+ if position_ids is None:
323
+ position_ids = cache_position.unsqueeze(0) + 1 # Paligemma positions are 1-indexed
324
+
325
+ # Merge text and images
326
+ if pixel_values is not None:
327
+ image_features = self.get_image_features(pixel_values)
328
+
329
+ if input_ids is None:
330
+ special_image_mask = inputs_embeds == self.get_input_embeddings()(
331
+ torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
332
+ )
333
+ else:
334
+ special_image_mask = (input_ids == self.config.image_token_id).unsqueeze(-1)
335
+ special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device)
336
+
337
+ if not is_torchdynamo_compiling() and inputs_embeds[special_image_mask].numel() != image_features.numel():
338
+ image_tokens_in_text = (special_image_mask).sum(dim=1).sum(dim=0)[0]
339
+ raise ValueError(
340
+ f"Number of images does not match number of special image tokens in the input text. "
341
+ f"Got {image_tokens_in_text} image tokens in the text but {image_features.shape[0] * image_features.shape[1]} "
342
+ "tokens from image embeddings."
343
+ )
344
+ image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
345
+ inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
346
+
347
+ causal_mask = self._update_causal_mask(
348
+ attention_mask, token_type_ids, past_key_values, cache_position, inputs_embeds, is_training
349
+ )
350
+ outputs = self.language_model(
351
+ attention_mask=causal_mask,
352
+ position_ids=position_ids,
353
+ past_key_values=past_key_values,
354
+ inputs_embeds=inputs_embeds,
355
+ use_cache=use_cache,
356
+ output_attentions=output_attentions,
357
+ output_hidden_states=output_hidden_states,
358
+ return_dict=True,
359
+ cache_position=cache_position,
360
+ **kwargs,
361
+ )
362
+
363
+ return PaligemmaModelOutputWithPast(
364
+ last_hidden_state=outputs.last_hidden_state,
365
+ past_key_values=outputs.past_key_values,
366
+ hidden_states=outputs.hidden_states,
367
+ attentions=outputs.attentions,
368
+ image_hidden_states=image_features if pixel_values is not None else None,
369
+ )
370
+
371
+
372
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
373
+
374
+
375
+ @auto_docstring(
376
+ custom_intro="""
377
+ The Base Paligemma model which consists of a vision backbone and a language model without language modeling head.,
378
+ """
379
+ )
380
+ class PaliGemmaForConditionalGeneration(PaliGemmaPreTrainedModel, GenerationMixin):
381
+ _checkpoint_conversion_mapping = {
382
+ "^language_model.model": "model.language_model",
383
+ "^vision_tower": "model.vision_tower",
384
+ "^multi_modal_projector": "model.multi_modal_projector",
385
+ "^language_model.lm_head": "lm_head",
386
+ }
387
+ _tied_weights_keys = ["lm_head.weight"]
388
+
389
+ def __init__(self, config: PaliGemmaConfig):
390
+ super().__init__(config)
391
+ self.model = PaliGemmaModel(config)
392
+ self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
393
+ self.post_init()
394
+
395
+ def get_input_embeddings(self):
396
+ return self.model.get_input_embeddings()
397
+
398
+ def set_input_embeddings(self, value):
399
+ self.model.set_input_embeddings(value)
400
+
401
+ def get_output_embeddings(self):
402
+ return self.lm_head
403
+
404
+ def set_output_embeddings(self, new_embeddings):
405
+ self.lm_head = new_embeddings
406
+
407
+ def set_decoder(self, decoder):
408
+ self.model.set_decoder(decoder)
409
+
410
+ def get_decoder(self):
411
+ return self.model.get_decoder()
412
+
413
+ def get_image_features(self, pixel_values):
414
+ return self.model.get_image_features(pixel_values)
415
+
416
+ # Make modules available throught conditional class for BC
417
+ @property
418
+ def language_model(self):
419
+ return self.model.language_model
420
+
421
+ @property
422
+ def vision_tower(self):
423
+ return self.model.vision_tower
424
+
425
+ @property
426
+ def multi_modal_projector(self):
427
+ return self.model.multi_modal_projector
428
+
429
+ @can_return_tuple
430
+ @auto_docstring
431
+ def forward(
432
+ self,
433
+ input_ids: torch.LongTensor = None,
434
+ pixel_values: torch.FloatTensor = None,
435
+ attention_mask: Optional[torch.Tensor] = None,
436
+ position_ids: Optional[torch.LongTensor] = None,
437
+ past_key_values: Optional[Union[list[torch.FloatTensor], Cache]] = None,
438
+ token_type_ids: Optional[torch.LongTensor] = None,
439
+ cache_position: Optional[torch.LongTensor] = None,
440
+ inputs_embeds: Optional[torch.FloatTensor] = None,
441
+ labels: Optional[torch.LongTensor] = None,
442
+ use_cache: Optional[bool] = None,
443
+ output_attentions: Optional[bool] = None,
444
+ output_hidden_states: Optional[bool] = None,
445
+ return_dict: Optional[bool] = None,
446
+ logits_to_keep: Union[int, torch.Tensor] = 0,
447
+ **kwargs: Unpack[KwargsForCausalLM],
448
+ ) -> Union[tuple, PaliGemmaCausalLMOutputWithPast]:
449
+ r"""
450
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
451
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
452
+ config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
453
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
454
+
455
+ Example:
456
+
457
+ ```python
458
+ >>> from PIL import Image
459
+ >>> import requests
460
+ >>> from transformers import AutoProcessor, PaliGemmaForConditionalGeneration
461
+
462
+ >>> model = PaliGemmaForConditionalGeneration.from_pretrained("google/paligemma2-3b-mix-224")
463
+ >>> processor = AutoProcessor.from_pretrained("google/paligemma2-3b-mix-224")
464
+
465
+ >>> prompt = "Where is the cat standing?"
466
+ >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
467
+ >>> image = Image.open(requests.get(url, stream=True).raw)
468
+
469
+ >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
470
+
471
+ >>> # Generate
472
+ >>> generate_ids = model.generate(**inputs,)
473
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
474
+ "Where is the cat standing?\nsnow"
475
+ ```"""
476
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
477
+ output_hidden_states = (
478
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
479
+ )
480
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
481
+
482
+ outputs = self.model(
483
+ input_ids=input_ids,
484
+ pixel_values=pixel_values,
485
+ token_type_ids=token_type_ids,
486
+ attention_mask=attention_mask,
487
+ position_ids=position_ids,
488
+ past_key_values=past_key_values,
489
+ inputs_embeds=inputs_embeds,
490
+ use_cache=use_cache,
491
+ labels=labels,
492
+ output_attentions=output_attentions,
493
+ output_hidden_states=output_hidden_states,
494
+ return_dict=True,
495
+ cache_position=cache_position,
496
+ **kwargs,
497
+ )
498
+
499
+ hidden_states = outputs[0]
500
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
501
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
502
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
503
+
504
+ loss = None
505
+ if labels is not None:
506
+ loss = self.loss_function(
507
+ logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
508
+ )
509
+
510
+ return PaliGemmaCausalLMOutputWithPast(
511
+ loss=loss,
512
+ logits=logits,
513
+ past_key_values=outputs.past_key_values,
514
+ hidden_states=outputs.hidden_states,
515
+ attentions=outputs.attentions,
516
+ image_hidden_states=outputs.image_hidden_states,
517
+ )
518
+
519
+ def prepare_inputs_for_generation(
520
+ self,
521
+ input_ids,
522
+ past_key_values=None,
523
+ inputs_embeds=None,
524
+ cache_position=None,
525
+ position_ids=None,
526
+ pixel_values=None,
527
+ attention_mask=None,
528
+ token_type_ids=None,
529
+ use_cache=True,
530
+ logits_to_keep=None,
531
+ labels=None,
532
+ **kwargs,
533
+ ):
534
+ # Overwritten -- custom `position_ids` and `pixel_values` handling
535
+ model_inputs = super().prepare_inputs_for_generation(
536
+ input_ids,
537
+ past_key_values=past_key_values,
538
+ inputs_embeds=inputs_embeds,
539
+ attention_mask=attention_mask,
540
+ position_ids=position_ids,
541
+ cache_position=cache_position,
542
+ use_cache=use_cache,
543
+ logits_to_keep=logits_to_keep,
544
+ token_type_ids=token_type_ids,
545
+ **kwargs,
546
+ )
547
+
548
+ # position_ids in Paligemma are 1-indexed
549
+ if model_inputs.get("position_ids") is not None:
550
+ model_inputs["position_ids"] += 1
551
+ # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
552
+ # Otherwise we need pixel values to be passed to model. NOTE: use_cache=False needs pixel_values always
553
+ if cache_position[0] == 0:
554
+ model_inputs["pixel_values"] = pixel_values
555
+ is_training = token_type_ids is not None and labels is not None
556
+ if cache_position[0] == 0 and isinstance(past_key_values, HybridCache):
557
+ input_tensor = inputs_embeds if inputs_embeds is not None else input_ids
558
+ causal_mask = self.model._update_causal_mask(
559
+ attention_mask, token_type_ids, past_key_values, cache_position, input_tensor, is_training
560
+ )
561
+ model_inputs["attention_mask"] = causal_mask
562
+
563
+ return model_inputs
564
+
565
+ @staticmethod
566
+ # Copied from transformers.models.gptj.modeling_gptj.GPTJModel._prepare_4d_causal_attention_mask_with_cache_position
567
+ def _prepare_4d_causal_attention_mask_with_cache_position(
568
+ attention_mask: torch.Tensor,
569
+ sequence_length: int,
570
+ target_length: int,
571
+ dtype: torch.dtype,
572
+ cache_position: torch.Tensor,
573
+ batch_size: int,
574
+ **kwargs,
575
+ ):
576
+ """
577
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
578
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
579
+
580
+ Args:
581
+ attention_mask (`torch.Tensor`):
582
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
583
+ `(batch_size, 1, query_length, key_value_length)`.
584
+ sequence_length (`int`):
585
+ The sequence length being processed.
586
+ target_length (`int`):
587
+ The target length: when generating with static cache, the mask should be as long as the static cache,
588
+ to account for the 0 padding, the part of the cache that is not filled yet.
589
+ dtype (`torch.dtype`):
590
+ The dtype to use for the 4D attention mask.
591
+ cache_position (`torch.Tensor`):
592
+ Indices depicting the position of the input sequence tokens in the sequence.
593
+ batch_size (`torch.Tensor`):
594
+ Batch size.
595
+ """
596
+ if attention_mask is not None and attention_mask.dim() == 4:
597
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
598
+ causal_mask = attention_mask
599
+ else:
600
+ min_dtype = torch.finfo(dtype).min
601
+ causal_mask = torch.full(
602
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
603
+ )
604
+ if sequence_length != 1:
605
+ causal_mask = torch.triu(causal_mask, diagonal=1)
606
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
607
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
608
+ if attention_mask is not None:
609
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
610
+ mask_length = attention_mask.shape[-1]
611
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
612
+ causal_mask.device
613
+ )
614
+ padding_mask = padding_mask == 0
615
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
616
+ padding_mask, min_dtype
617
+ )
618
+
619
+ return causal_mask
620
+
621
+
622
+ __all__ = ["PaliGemmaForConditionalGeneration", "PaliGemmaPreTrainedModel", "PaliGemmaModel"]
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/transformers_replace/models/siglip/check.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import transformers
2
+
3
+ def check_whether_transformers_replace_is_installed_correctly():
4
+ return transformers.__version__ == "4.53.2"
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/models_pytorch/transformers_replace/models/siglip/modeling_siglip.py ADDED
@@ -0,0 +1,1237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Google AI and The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch Siglip model."""
16
+
17
+ import math
18
+ import warnings
19
+ from dataclasses import dataclass
20
+ from typing import Any, Callable, Optional, Union
21
+
22
+ import numpy as np
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+ from torch.nn.init import _calculate_fan_in_and_fan_out
28
+
29
+ from ...activations import ACT2FN
30
+ from ...modeling_attn_mask_utils import _prepare_4d_attention_mask
31
+ from ...modeling_layers import GradientCheckpointingLayer
32
+ from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
33
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
34
+ from ...utils import ModelOutput, auto_docstring, can_return_tuple, logging, torch_int
35
+ from .configuration_siglip import SiglipConfig, SiglipTextConfig, SiglipVisionConfig
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+
41
+ def _trunc_normal_(tensor, mean, std, a, b):
42
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
43
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
44
+ def norm_cdf(x):
45
+ # Computes standard normal cumulative distribution function
46
+ return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
47
+
48
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
49
+ warnings.warn(
50
+ "mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
51
+ "The distribution of values may be incorrect.",
52
+ stacklevel=2,
53
+ )
54
+
55
+ # Values are generated by using a truncated uniform distribution and
56
+ # then using the inverse CDF for the normal distribution.
57
+ # Get upper and lower cdf values
58
+ l = norm_cdf((a - mean) / std)
59
+ u = norm_cdf((b - mean) / std)
60
+
61
+ # Uniformly fill tensor with values from [l, u], then translate to
62
+ # [2l-1, 2u-1].
63
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
64
+
65
+ # Use inverse cdf transform for normal distribution to get truncated
66
+ # standard normal
67
+ tensor.erfinv_()
68
+
69
+ # Transform to proper mean, std
70
+ tensor.mul_(std * math.sqrt(2.0))
71
+ tensor.add_(mean)
72
+
73
+ # Clamp to ensure it's in the proper range
74
+ tensor.clamp_(min=a, max=b)
75
+
76
+
77
+ def trunc_normal_tf_(
78
+ tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0
79
+ ) -> torch.Tensor:
80
+ """Fills the input Tensor with values drawn from a truncated
81
+ normal distribution. The values are effectively drawn from the
82
+ normal distribution :math:`\\mathcal{N}(\text{mean}, \text{std}^2)`
83
+ with values outside :math:`[a, b]` redrawn until they are within
84
+ the bounds. The method used for generating the random values works
85
+ best when :math:`a \\leq \text{mean} \\leq b`.
86
+
87
+ NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the
88
+ bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0
89
+ and the result is subsequently scaled and shifted by the mean and std args.
90
+
91
+ Args:
92
+ tensor: an n-dimensional `torch.Tensor`
93
+ mean: the mean of the normal distribution
94
+ std: the standard deviation of the normal distribution
95
+ a: the minimum cutoff value
96
+ b: the maximum cutoff value
97
+ """
98
+ with torch.no_grad():
99
+ _trunc_normal_(tensor, 0, 1.0, a, b)
100
+ tensor.mul_(std).add_(mean)
101
+
102
+
103
+ def variance_scaling_(tensor, scale=1.0, mode="fan_in", distribution="normal"):
104
+ fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
105
+ if mode == "fan_in":
106
+ denom = fan_in
107
+ elif mode == "fan_out":
108
+ denom = fan_out
109
+ elif mode == "fan_avg":
110
+ denom = (fan_in + fan_out) / 2
111
+
112
+ variance = scale / denom
113
+
114
+ if distribution == "truncated_normal":
115
+ # constant is stddev of standard normal truncated to (-2, 2)
116
+ trunc_normal_tf_(tensor, std=math.sqrt(variance) / 0.87962566103423978)
117
+ elif distribution == "normal":
118
+ with torch.no_grad():
119
+ tensor.normal_(std=math.sqrt(variance))
120
+ elif distribution == "uniform":
121
+ bound = math.sqrt(3 * variance)
122
+ with torch.no_grad():
123
+ tensor.uniform_(-bound, bound)
124
+ else:
125
+ raise ValueError(f"invalid distribution {distribution}")
126
+
127
+
128
+ def lecun_normal_(tensor):
129
+ variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")
130
+
131
+
132
+ def default_flax_embed_init(tensor):
133
+ variance_scaling_(tensor, mode="fan_in", distribution="normal")
134
+
135
+
136
+ @dataclass
137
+ @auto_docstring(
138
+ custom_intro="""
139
+ Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
140
+ """
141
+ )
142
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->Siglip
143
+ class SiglipVisionModelOutput(ModelOutput):
144
+ r"""
145
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
146
+ The image embeddings obtained by applying the projection layer to the pooler_output.
147
+ """
148
+
149
+ image_embeds: Optional[torch.FloatTensor] = None
150
+ last_hidden_state: Optional[torch.FloatTensor] = None
151
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
152
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
153
+
154
+
155
+ @dataclass
156
+ @auto_docstring(
157
+ custom_intro="""
158
+ Base class for text model's outputs that also contains a pooling of the last hidden states.
159
+ """
160
+ )
161
+ # Copied from transformers.models.clip.modeling_clip.CLIPTextModelOutput with CLIP->Siglip
162
+ class SiglipTextModelOutput(ModelOutput):
163
+ r"""
164
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
165
+ The text embeddings obtained by applying the projection layer to the pooler_output.
166
+ """
167
+
168
+ text_embeds: Optional[torch.FloatTensor] = None
169
+ last_hidden_state: Optional[torch.FloatTensor] = None
170
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
171
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
172
+
173
+
174
+ @dataclass
175
+ @auto_docstring
176
+ # Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->Siglip
177
+ class SiglipOutput(ModelOutput):
178
+ r"""
179
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
180
+ Contrastive loss for image-text similarity.
181
+ logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
182
+ The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
183
+ similarity scores.
184
+ logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
185
+ The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
186
+ similarity scores.
187
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
188
+ The text embeddings obtained by applying the projection layer to the pooled output of [`SiglipTextModel`].
189
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
190
+ The image embeddings obtained by applying the projection layer to the pooled output of [`SiglipVisionModel`].
191
+ text_model_output (`BaseModelOutputWithPooling`):
192
+ The output of the [`SiglipTextModel`].
193
+ vision_model_output (`BaseModelOutputWithPooling`):
194
+ The output of the [`SiglipVisionModel`].
195
+ """
196
+
197
+ loss: Optional[torch.FloatTensor] = None
198
+ logits_per_image: Optional[torch.FloatTensor] = None
199
+ logits_per_text: Optional[torch.FloatTensor] = None
200
+ text_embeds: Optional[torch.FloatTensor] = None
201
+ image_embeds: Optional[torch.FloatTensor] = None
202
+ text_model_output: BaseModelOutputWithPooling = None
203
+ vision_model_output: BaseModelOutputWithPooling = None
204
+
205
+ def to_tuple(self) -> tuple[Any]:
206
+ return tuple(
207
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
208
+ for k in self.keys()
209
+ )
210
+
211
+
212
+ class SiglipVisionEmbeddings(nn.Module):
213
+ def __init__(self, config: SiglipVisionConfig):
214
+ super().__init__()
215
+ self.config = config
216
+ self.embed_dim = config.hidden_size
217
+ self.image_size = config.image_size
218
+ self.patch_size = config.patch_size
219
+
220
+ self.patch_embedding = nn.Conv2d(
221
+ in_channels=config.num_channels,
222
+ out_channels=self.embed_dim,
223
+ kernel_size=self.patch_size,
224
+ stride=self.patch_size,
225
+ padding="valid",
226
+ )
227
+
228
+ self.num_patches = (self.image_size // self.patch_size) ** 2
229
+ self.num_positions = self.num_patches
230
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
231
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
232
+
233
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
234
+ """
235
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
236
+ images. This method is also adapted to support torch.jit tracing and no class embeddings.
237
+
238
+ Adapted from:
239
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
240
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
241
+ """
242
+
243
+ num_patches = embeddings.shape[1]
244
+ num_positions = self.position_embedding.weight.shape[0]
245
+
246
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
247
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
248
+ return self.position_embedding(self.position_ids)
249
+
250
+ patch_pos_embed = self.position_embedding.weight.unsqueeze(0)
251
+
252
+ dim = embeddings.shape[-1]
253
+
254
+ new_height = height // self.patch_size
255
+ new_width = width // self.patch_size
256
+
257
+ sqrt_num_positions = torch_int(num_positions**0.5)
258
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
259
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
260
+
261
+ patch_pos_embed = nn.functional.interpolate(
262
+ patch_pos_embed,
263
+ size=(new_height, new_width),
264
+ mode="bicubic",
265
+ align_corners=False,
266
+ )
267
+
268
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
269
+ return patch_pos_embed
270
+
271
+ def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding=False) -> torch.Tensor:
272
+ _, _, height, width = pixel_values.shape
273
+ target_dtype = self.patch_embedding.weight.dtype
274
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
275
+ embeddings = patch_embeds.flatten(2).transpose(1, 2)
276
+
277
+ if interpolate_pos_encoding:
278
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
279
+ else:
280
+ embeddings = embeddings + self.position_embedding(self.position_ids)
281
+ return embeddings
282
+
283
+
284
+ # Copied from transformers.models.clip.modeling_clip.CLIPTextEmbeddings with CLIP->Siglip
285
+ class SiglipTextEmbeddings(nn.Module):
286
+ def __init__(self, config: SiglipTextConfig):
287
+ super().__init__()
288
+ embed_dim = config.hidden_size
289
+
290
+ self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
291
+ self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
292
+
293
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
294
+ self.register_buffer(
295
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
296
+ )
297
+
298
+ def forward(
299
+ self,
300
+ input_ids: Optional[torch.LongTensor] = None,
301
+ position_ids: Optional[torch.LongTensor] = None,
302
+ inputs_embeds: Optional[torch.FloatTensor] = None,
303
+ ) -> torch.Tensor:
304
+ seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
305
+ max_position_embedding = self.position_embedding.weight.shape[0]
306
+
307
+ if seq_length > max_position_embedding:
308
+ raise ValueError(
309
+ f"Sequence length must be less than max_position_embeddings (got `sequence length`: "
310
+ f"{seq_length} and max_position_embeddings: {max_position_embedding}"
311
+ )
312
+
313
+ if position_ids is None:
314
+ position_ids = self.position_ids[:, :seq_length]
315
+
316
+ if inputs_embeds is None:
317
+ inputs_embeds = self.token_embedding(input_ids)
318
+
319
+ position_embeddings = self.position_embedding(position_ids)
320
+ embeddings = inputs_embeds + position_embeddings
321
+
322
+ return embeddings
323
+
324
+
325
+ def eager_attention_forward(
326
+ module: nn.Module,
327
+ query: torch.Tensor,
328
+ key: torch.Tensor,
329
+ value: torch.Tensor,
330
+ attention_mask: Optional[torch.Tensor],
331
+ scaling: float,
332
+ dropout: float = 0.0,
333
+ **kwargs,
334
+ ):
335
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
336
+ if attention_mask is not None:
337
+ attn_weights = attn_weights + attention_mask
338
+
339
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
340
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
341
+
342
+ attn_output = torch.matmul(attn_weights, value)
343
+ attn_output = attn_output.transpose(1, 2).contiguous()
344
+
345
+ return attn_output, attn_weights
346
+
347
+
348
+ class SiglipAttention(nn.Module):
349
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
350
+
351
+ def __init__(self, config):
352
+ super().__init__()
353
+ self.config = config
354
+ self.embed_dim = config.hidden_size
355
+ self.num_heads = config.num_attention_heads
356
+ self.head_dim = self.embed_dim // self.num_heads
357
+ if self.head_dim * self.num_heads != self.embed_dim:
358
+ raise ValueError(
359
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
360
+ f" {self.num_heads})."
361
+ )
362
+ self.scale = self.head_dim**-0.5
363
+ self.dropout = config.attention_dropout
364
+ self.is_causal = False
365
+
366
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
367
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
368
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
369
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
370
+
371
+ def forward(
372
+ self,
373
+ hidden_states: torch.Tensor,
374
+ attention_mask: Optional[torch.Tensor] = None,
375
+ output_attentions: Optional[bool] = False,
376
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
377
+ """Input shape: Batch x Time x Channel"""
378
+
379
+ batch_size, seq_length, embed_dim = hidden_states.shape
380
+
381
+ queries = self.q_proj(hidden_states)
382
+ keys = self.k_proj(hidden_states)
383
+ values = self.v_proj(hidden_states)
384
+
385
+ queries = queries.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
386
+ keys = keys.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
387
+ values = values.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
388
+
389
+ attention_interface: Callable = eager_attention_forward
390
+ if self.config._attn_implementation != "eager":
391
+ if self.config._attn_implementation == "sdpa" and output_attentions:
392
+ logger.warning_once(
393
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
394
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
395
+ )
396
+ else:
397
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
398
+
399
+ attn_output, attn_weights = attention_interface(
400
+ self,
401
+ queries,
402
+ keys,
403
+ values,
404
+ attention_mask,
405
+ is_causal=self.is_causal,
406
+ scaling=self.scale,
407
+ dropout=0.0 if not self.training else self.dropout,
408
+ )
409
+
410
+ attn_output = attn_output.reshape(batch_size, seq_length, embed_dim).contiguous()
411
+ attn_output = self.out_proj(attn_output)
412
+
413
+ if not output_attentions:
414
+ attn_weights = None
415
+
416
+ return attn_output, attn_weights
417
+
418
+
419
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Siglip
420
+ class SiglipMLP(nn.Module):
421
+ def __init__(self, config):
422
+ super().__init__()
423
+ self.config = config
424
+ self.activation_fn = ACT2FN[config.hidden_act]
425
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
426
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
427
+
428
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
429
+ hidden_states = self.fc1(hidden_states)
430
+ hidden_states = self.activation_fn(hidden_states)
431
+ hidden_states = self.fc2(hidden_states)
432
+ return hidden_states
433
+
434
+
435
+ class SiglipEncoderLayer(GradientCheckpointingLayer):
436
+ def __init__(self, config: Union[SiglipVisionConfig, SiglipTextConfig]):
437
+ super().__init__()
438
+ self.embed_dim = config.hidden_size
439
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
440
+ self.self_attn = SiglipAttention(config)
441
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
442
+ self.mlp = SiglipMLP(config)
443
+
444
+ def forward(
445
+ self,
446
+ hidden_states: torch.Tensor,
447
+ attention_mask: torch.Tensor,
448
+ output_attentions: Optional[bool] = False,
449
+ ) -> tuple[torch.FloatTensor]:
450
+ """
451
+ Args:
452
+ hidden_states (`torch.FloatTensor`):
453
+ Input to the layer of shape `(batch, seq_len, embed_dim)`.
454
+ attention_mask (`torch.FloatTensor`):
455
+ Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
456
+ output_attentions (`bool`, *optional*, defaults to `False`):
457
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
458
+ returned tensors for more detail.
459
+ """
460
+ residual = hidden_states
461
+
462
+ hidden_states = self.layer_norm1(hidden_states)
463
+ hidden_states, attn_weights = self.self_attn(
464
+ hidden_states=hidden_states,
465
+ attention_mask=attention_mask,
466
+ output_attentions=output_attentions,
467
+ )
468
+ hidden_states = residual + hidden_states
469
+
470
+ residual = hidden_states
471
+ hidden_states = self.layer_norm2(hidden_states)
472
+ hidden_states = self.mlp(hidden_states)
473
+ hidden_states = residual + hidden_states
474
+
475
+ outputs = (hidden_states,)
476
+
477
+ if output_attentions:
478
+ outputs += (attn_weights,)
479
+
480
+ return outputs
481
+
482
+
483
+ @auto_docstring
484
+ class SiglipPreTrainedModel(PreTrainedModel):
485
+ config_class = SiglipConfig
486
+ base_model_prefix = "siglip"
487
+ supports_gradient_checkpointing = True
488
+
489
+ _no_split_modules = [
490
+ "SiglipTextEmbeddings",
491
+ "SiglipEncoderLayer",
492
+ "SiglipVisionEmbeddings",
493
+ "SiglipEncoderLayer",
494
+ "SiglipMultiheadAttentionPoolingHead",
495
+ ]
496
+ _supports_flash_attn_2 = True
497
+ _supports_sdpa = True
498
+ _supports_flex_attn = True
499
+ _supports_attention_backend = True
500
+
501
+ def _init_weights(self, module):
502
+ """Initialize the weights"""
503
+ if isinstance(module, SiglipVisionEmbeddings):
504
+ width = (
505
+ self.config.vision_config.hidden_size
506
+ if isinstance(self.config, SiglipConfig)
507
+ else self.config.hidden_size
508
+ )
509
+ nn.init.normal_(module.position_embedding.weight, std=1 / np.sqrt(width))
510
+ elif isinstance(module, nn.Embedding):
511
+ default_flax_embed_init(module.weight)
512
+ elif isinstance(module, SiglipAttention):
513
+ nn.init.xavier_uniform_(module.q_proj.weight)
514
+ nn.init.xavier_uniform_(module.k_proj.weight)
515
+ nn.init.xavier_uniform_(module.v_proj.weight)
516
+ nn.init.xavier_uniform_(module.out_proj.weight)
517
+ nn.init.zeros_(module.q_proj.bias)
518
+ nn.init.zeros_(module.k_proj.bias)
519
+ nn.init.zeros_(module.v_proj.bias)
520
+ nn.init.zeros_(module.out_proj.bias)
521
+ elif isinstance(module, SiglipMLP):
522
+ nn.init.xavier_uniform_(module.fc1.weight)
523
+ nn.init.xavier_uniform_(module.fc2.weight)
524
+ nn.init.normal_(module.fc1.bias, std=1e-6)
525
+ nn.init.normal_(module.fc2.bias, std=1e-6)
526
+ elif isinstance(module, SiglipMultiheadAttentionPoolingHead):
527
+ nn.init.xavier_uniform_(module.probe.data)
528
+ nn.init.xavier_uniform_(module.attention.in_proj_weight.data)
529
+ nn.init.zeros_(module.attention.in_proj_bias.data)
530
+ elif isinstance(module, SiglipModel):
531
+ logit_scale_init = torch.log(torch.tensor(1.0))
532
+ module.logit_scale.data.fill_(logit_scale_init)
533
+ module.logit_bias.data.zero_()
534
+ elif isinstance(module, SiglipForImageClassification):
535
+ nn.init.normal_(
536
+ module.classifier.weight,
537
+ std=self.config.vision_config.hidden_size**-0.5 * self.config.initializer_factor,
538
+ )
539
+ elif isinstance(module, (nn.Linear, nn.Conv2d)):
540
+ lecun_normal_(module.weight)
541
+ if module.bias is not None:
542
+ nn.init.zeros_(module.bias)
543
+ elif isinstance(module, nn.LayerNorm):
544
+ module.bias.data.zero_()
545
+ module.weight.data.fill_(1.0)
546
+
547
+
548
+ # Copied from transformers.models.altclip.modeling_altclip.AltCLIPEncoder with AltCLIP->Siglip
549
+ class SiglipEncoder(nn.Module):
550
+ """
551
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
552
+ [`SiglipEncoderLayer`].
553
+
554
+ Args:
555
+ config: SiglipConfig
556
+ """
557
+
558
+ def __init__(self, config: SiglipConfig):
559
+ super().__init__()
560
+ self.config = config
561
+ self.layers = nn.ModuleList([SiglipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
562
+ self.gradient_checkpointing = False
563
+
564
+ # Ignore copy
565
+ @can_return_tuple
566
+ def forward(
567
+ self,
568
+ inputs_embeds,
569
+ attention_mask: Optional[torch.Tensor] = None,
570
+ output_attentions: Optional[bool] = None,
571
+ output_hidden_states: Optional[bool] = None,
572
+ ) -> BaseModelOutput:
573
+ r"""
574
+ Args:
575
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
576
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
577
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
578
+ than the model's internal embedding lookup matrix.
579
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
580
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
581
+
582
+ - 1 for tokens that are **not masked**,
583
+ - 0 for tokens that are **masked**.
584
+
585
+ [What are attention masks?](../glossary#attention-mask)
586
+ output_attentions (`bool`, *optional*):
587
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
588
+ returned tensors for more detail.
589
+ output_hidden_states (`bool`, *optional*):
590
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
591
+ for more detail.
592
+ return_dict (`bool`, *optional*):
593
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
594
+ """
595
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
596
+ output_hidden_states = (
597
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
598
+ )
599
+
600
+ encoder_states = () if output_hidden_states else None
601
+ all_attentions = () if output_attentions else None
602
+
603
+ hidden_states = inputs_embeds
604
+ for encoder_layer in self.layers:
605
+ if output_hidden_states:
606
+ encoder_states = encoder_states + (hidden_states,)
607
+
608
+ layer_outputs = encoder_layer(
609
+ hidden_states,
610
+ attention_mask,
611
+ output_attentions=output_attentions,
612
+ )
613
+
614
+ hidden_states = layer_outputs[0]
615
+
616
+ if output_attentions:
617
+ all_attentions = all_attentions + (layer_outputs[1],)
618
+
619
+ if output_hidden_states:
620
+ encoder_states = encoder_states + (hidden_states,)
621
+
622
+ return BaseModelOutput(
623
+ last_hidden_state=hidden_states,
624
+ hidden_states=encoder_states,
625
+ attentions=all_attentions,
626
+ )
627
+
628
+
629
+ class SiglipTextTransformer(nn.Module):
630
+ def __init__(self, config: SiglipTextConfig):
631
+ super().__init__()
632
+ self.config = config
633
+ embed_dim = config.hidden_size
634
+ self.embeddings = SiglipTextEmbeddings(config)
635
+ self.encoder = SiglipEncoder(config)
636
+ self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
637
+
638
+ self.head = nn.Linear(embed_dim, config.projection_size)
639
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
640
+
641
+ @can_return_tuple
642
+ @auto_docstring
643
+ def forward(
644
+ self,
645
+ input_ids: Optional[torch.Tensor] = None,
646
+ attention_mask: Optional[torch.Tensor] = None,
647
+ position_ids: Optional[torch.Tensor] = None,
648
+ output_attentions: Optional[bool] = None,
649
+ output_hidden_states: Optional[bool] = None,
650
+ ) -> BaseModelOutputWithPooling:
651
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
652
+ output_hidden_states = (
653
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
654
+ )
655
+
656
+ if input_ids is None:
657
+ raise ValueError("You have to specify input_ids")
658
+
659
+ input_shape = input_ids.size()
660
+ input_ids = input_ids.view(-1, input_shape[-1])
661
+
662
+ hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
663
+
664
+ # note: SigLIP's text model does not use a causal mask, unlike the original CLIP model.
665
+ # expand attention_mask
666
+ if attention_mask is not None and not self._use_flash_attention_2:
667
+ # [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len]
668
+ attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
669
+
670
+ encoder_outputs: BaseModelOutput = self.encoder(
671
+ inputs_embeds=hidden_states,
672
+ attention_mask=attention_mask,
673
+ output_attentions=output_attentions,
674
+ output_hidden_states=output_hidden_states,
675
+ )
676
+
677
+ last_hidden_state = encoder_outputs.last_hidden_state
678
+ last_hidden_state = self.final_layer_norm(last_hidden_state)
679
+
680
+ # Assuming "sticky" EOS tokenization, last token is always EOS.
681
+ pooled_output = last_hidden_state[:, -1, :]
682
+ pooled_output = self.head(pooled_output)
683
+
684
+ return BaseModelOutputWithPooling(
685
+ last_hidden_state=last_hidden_state,
686
+ pooler_output=pooled_output,
687
+ hidden_states=encoder_outputs.hidden_states,
688
+ attentions=encoder_outputs.attentions,
689
+ )
690
+
691
+
692
+ @auto_docstring(
693
+ custom_intro="""
694
+ The text model from SigLIP without any head or projection on top.
695
+ """
696
+ )
697
+ class SiglipTextModel(SiglipPreTrainedModel):
698
+ config_class = SiglipTextConfig
699
+
700
+ def __init__(self, config: SiglipTextConfig):
701
+ super().__init__(config)
702
+ self.text_model = SiglipTextTransformer(config)
703
+ # Initialize weights and apply final processing
704
+ self.post_init()
705
+
706
+ def get_input_embeddings(self) -> nn.Module:
707
+ return self.text_model.embeddings.token_embedding
708
+
709
+ def set_input_embeddings(self, value):
710
+ self.text_model.embeddings.token_embedding = value
711
+
712
+ @can_return_tuple
713
+ @auto_docstring
714
+ def forward(
715
+ self,
716
+ input_ids: Optional[torch.Tensor] = None,
717
+ attention_mask: Optional[torch.Tensor] = None,
718
+ position_ids: Optional[torch.Tensor] = None,
719
+ output_attentions: Optional[bool] = None,
720
+ output_hidden_states: Optional[bool] = None,
721
+ ) -> BaseModelOutputWithPooling:
722
+ r"""
723
+ Examples:
724
+
725
+ ```python
726
+ >>> from transformers import AutoTokenizer, SiglipTextModel
727
+
728
+ >>> model = SiglipTextModel.from_pretrained("google/siglip-base-patch16-224")
729
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224")
730
+
731
+ >>> # important: make sure to set padding="max_length" as that's how the model was trained
732
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")
733
+
734
+ >>> outputs = model(**inputs)
735
+ >>> last_hidden_state = outputs.last_hidden_state
736
+ >>> pooled_output = outputs.pooler_output # pooled (EOS token) states
737
+ ```"""
738
+
739
+ return self.text_model(
740
+ input_ids=input_ids,
741
+ attention_mask=attention_mask,
742
+ position_ids=position_ids,
743
+ output_attentions=output_attentions,
744
+ output_hidden_states=output_hidden_states,
745
+ )
746
+
747
+
748
+ class SiglipVisionTransformer(nn.Module):
749
+ def __init__(self, config: SiglipVisionConfig):
750
+ super().__init__()
751
+ self.config = config
752
+ embed_dim = config.hidden_size
753
+
754
+ self.embeddings = SiglipVisionEmbeddings(config)
755
+ self.encoder = SiglipEncoder(config)
756
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
757
+ self.use_head = True if not hasattr(config, "vision_use_head") else config.vision_use_head
758
+ if self.use_head:
759
+ self.head = SiglipMultiheadAttentionPoolingHead(config)
760
+
761
+ @can_return_tuple
762
+ @auto_docstring
763
+ def forward(
764
+ self,
765
+ pixel_values,
766
+ output_attentions: Optional[bool] = None,
767
+ output_hidden_states: Optional[bool] = None,
768
+ interpolate_pos_encoding: Optional[bool] = False,
769
+ ) -> BaseModelOutputWithPooling:
770
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
771
+ output_hidden_states = (
772
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
773
+ )
774
+
775
+ hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
776
+ # Convert to bfloat16 if the encoder uses bfloat16
777
+ if len(self.encoder.layers) > 0 and self.encoder.layers[0].self_attn.q_proj.weight.dtype == torch.bfloat16:
778
+ hidden_states = hidden_states.to(torch.bfloat16)
779
+
780
+ encoder_outputs: BaseModelOutput = self.encoder(
781
+ inputs_embeds=hidden_states,
782
+ output_attentions=output_attentions,
783
+ output_hidden_states=output_hidden_states,
784
+ )
785
+
786
+ last_hidden_state = encoder_outputs.last_hidden_state
787
+ last_hidden_state = self.post_layernorm(last_hidden_state)
788
+
789
+ pooler_output = self.head(last_hidden_state) if self.use_head else None
790
+
791
+ return BaseModelOutputWithPooling(
792
+ last_hidden_state=last_hidden_state,
793
+ pooler_output=pooler_output,
794
+ hidden_states=encoder_outputs.hidden_states,
795
+ attentions=encoder_outputs.attentions,
796
+ )
797
+
798
+
799
+ class SiglipMultiheadAttentionPoolingHead(nn.Module):
800
+ """Multihead Attention Pooling."""
801
+
802
+ def __init__(self, config: SiglipVisionConfig):
803
+ super().__init__()
804
+
805
+ self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size))
806
+ self.attention = torch.nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, batch_first=True)
807
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
808
+ self.mlp = SiglipMLP(config)
809
+
810
+ def forward(self, hidden_state):
811
+ batch_size = hidden_state.shape[0]
812
+ probe = self.probe.repeat(batch_size, 1, 1)
813
+
814
+ hidden_state = self.attention(probe, hidden_state, hidden_state)[0]
815
+
816
+ residual = hidden_state
817
+ hidden_state = self.layernorm(hidden_state)
818
+ hidden_state = residual + self.mlp(hidden_state)
819
+
820
+ return hidden_state[:, 0]
821
+
822
+
823
+ @auto_docstring(
824
+ custom_intro="""
825
+ The vision model from SigLIP without any head or projection on top.
826
+ """
827
+ )
828
+ class SiglipVisionModel(SiglipPreTrainedModel):
829
+ config_class = SiglipVisionConfig
830
+ main_input_name = "pixel_values"
831
+
832
+ def __init__(self, config: SiglipVisionConfig):
833
+ super().__init__(config)
834
+
835
+ self.vision_model = SiglipVisionTransformer(config)
836
+
837
+ # Initialize weights and apply final processing
838
+ self.post_init()
839
+
840
+ def get_input_embeddings(self) -> nn.Module:
841
+ return self.vision_model.embeddings.patch_embedding
842
+
843
+ @can_return_tuple
844
+ @auto_docstring
845
+ def forward(
846
+ self,
847
+ pixel_values,
848
+ output_attentions: Optional[bool] = None,
849
+ output_hidden_states: Optional[bool] = None,
850
+ interpolate_pos_encoding: bool = False,
851
+ ) -> BaseModelOutputWithPooling:
852
+ r"""
853
+ Examples:
854
+
855
+ ```python
856
+ >>> from PIL import Image
857
+ >>> import requests
858
+ >>> from transformers import AutoProcessor, SiglipVisionModel
859
+
860
+ >>> model = SiglipVisionModel.from_pretrained("google/siglip-base-patch16-224")
861
+ >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
862
+
863
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
864
+ >>> image = Image.open(requests.get(url, stream=True).raw)
865
+
866
+ >>> inputs = processor(images=image, return_tensors="pt")
867
+
868
+ >>> outputs = model(**inputs)
869
+ >>> last_hidden_state = outputs.last_hidden_state
870
+ >>> pooled_output = outputs.pooler_output # pooled features
871
+ ```"""
872
+
873
+ return self.vision_model(
874
+ pixel_values=pixel_values,
875
+ output_attentions=output_attentions,
876
+ output_hidden_states=output_hidden_states,
877
+ interpolate_pos_encoding=interpolate_pos_encoding,
878
+ )
879
+
880
+
881
+ @auto_docstring
882
+ class SiglipModel(SiglipPreTrainedModel):
883
+ config_class = SiglipConfig
884
+
885
+ def __init__(self, config: SiglipConfig):
886
+ super().__init__(config)
887
+
888
+ if not isinstance(config.text_config, SiglipTextConfig):
889
+ raise TypeError(
890
+ "config.text_config is expected to be of type SiglipTextConfig but is of type"
891
+ f" {type(config.text_config)}."
892
+ )
893
+
894
+ if not isinstance(config.vision_config, SiglipVisionConfig):
895
+ raise TypeError(
896
+ "config.vision_config is expected to be of type SiglipVisionConfig but is of type"
897
+ f" {type(config.vision_config)}."
898
+ )
899
+
900
+ text_config = config.text_config
901
+ vision_config = config.vision_config
902
+
903
+ # First, initialize the text and vision models with proper attention implementation
904
+ text_model = SiglipTextModel._from_config(text_config)
905
+ vision_model = SiglipVisionModel._from_config(vision_config)
906
+
907
+ # Second, get the text and vision submodules (for backward compatibility)
908
+ self.text_model = text_model.text_model
909
+ self.vision_model = vision_model.vision_model
910
+
911
+ self.logit_scale = nn.Parameter(torch.randn(1))
912
+ self.logit_bias = nn.Parameter(torch.randn(1))
913
+
914
+ # Initialize weights and apply final processing
915
+ self.post_init()
916
+
917
+ @auto_docstring
918
+ def get_text_features(
919
+ self,
920
+ input_ids: Optional[torch.Tensor] = None,
921
+ attention_mask: Optional[torch.Tensor] = None,
922
+ position_ids: Optional[torch.Tensor] = None,
923
+ output_attentions: Optional[bool] = None,
924
+ output_hidden_states: Optional[bool] = None,
925
+ ) -> torch.FloatTensor:
926
+ r"""
927
+ Returns:
928
+ text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
929
+ applying the projection layer to the pooled output of [`SiglipTextModel`].
930
+
931
+ Examples:
932
+
933
+ ```python
934
+ >>> from transformers import AutoTokenizer, AutoModel
935
+ >>> import torch
936
+
937
+ >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
938
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224")
939
+
940
+ >>> # important: make sure to set padding="max_length" as that's how the model was trained
941
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")
942
+ >>> with torch.no_grad():
943
+ ... text_features = model.get_text_features(**inputs)
944
+ ```"""
945
+ # Use SigLIP model's config for some fields (if specified) instead of those of vision & text components.
946
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
947
+ output_hidden_states = (
948
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
949
+ )
950
+
951
+ text_outputs: BaseModelOutputWithPooling = self.text_model(
952
+ input_ids=input_ids,
953
+ attention_mask=attention_mask,
954
+ position_ids=position_ids,
955
+ output_attentions=output_attentions,
956
+ output_hidden_states=output_hidden_states,
957
+ )
958
+
959
+ pooled_output = text_outputs.pooler_output
960
+
961
+ return pooled_output
962
+
963
+ @auto_docstring
964
+ def get_image_features(
965
+ self,
966
+ pixel_values: Optional[torch.FloatTensor] = None,
967
+ output_attentions: Optional[bool] = None,
968
+ output_hidden_states: Optional[bool] = None,
969
+ interpolate_pos_encoding: bool = False,
970
+ ) -> torch.FloatTensor:
971
+ r"""
972
+ Returns:
973
+ image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
974
+ applying the projection layer to the pooled output of [`SiglipVisionModel`].
975
+
976
+ Examples:
977
+
978
+ ```python
979
+ >>> from PIL import Image
980
+ >>> import requests
981
+ >>> from transformers import AutoProcessor, AutoModel
982
+ >>> import torch
983
+
984
+ >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
985
+ >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
986
+
987
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
988
+ >>> image = Image.open(requests.get(url, stream=True).raw)
989
+
990
+ >>> inputs = processor(images=image, return_tensors="pt")
991
+
992
+ >>> with torch.no_grad():
993
+ ... image_features = model.get_image_features(**inputs)
994
+ ```"""
995
+ # Use SiglipModel's config for some fields (if specified) instead of those of vision & text components.
996
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
997
+ output_hidden_states = (
998
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
999
+ )
1000
+
1001
+ vision_outputs: BaseModelOutputWithPooling = self.vision_model(
1002
+ pixel_values=pixel_values,
1003
+ output_attentions=output_attentions,
1004
+ output_hidden_states=output_hidden_states,
1005
+ interpolate_pos_encoding=interpolate_pos_encoding,
1006
+ )
1007
+
1008
+ pooled_output = vision_outputs.pooler_output
1009
+
1010
+ return pooled_output
1011
+
1012
+ @can_return_tuple
1013
+ @auto_docstring
1014
+ def forward(
1015
+ self,
1016
+ input_ids: Optional[torch.LongTensor] = None,
1017
+ pixel_values: Optional[torch.FloatTensor] = None,
1018
+ attention_mask: Optional[torch.Tensor] = None,
1019
+ position_ids: Optional[torch.LongTensor] = None,
1020
+ return_loss: Optional[bool] = None,
1021
+ output_attentions: Optional[bool] = None,
1022
+ output_hidden_states: Optional[bool] = None,
1023
+ interpolate_pos_encoding: bool = False,
1024
+ ) -> SiglipOutput:
1025
+ r"""
1026
+ return_loss (`bool`, *optional*):
1027
+ Whether or not to return the contrastive loss.
1028
+
1029
+ Examples:
1030
+
1031
+ ```python
1032
+ >>> from PIL import Image
1033
+ >>> import requests
1034
+ >>> from transformers import AutoProcessor, AutoModel
1035
+ >>> import torch
1036
+
1037
+ >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
1038
+ >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")
1039
+
1040
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1041
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1042
+
1043
+ >>> texts = ["a photo of 2 cats", "a photo of 2 dogs"]
1044
+ >>> # important: we pass `padding=max_length` since the model was trained with this
1045
+ >>> inputs = processor(text=texts, images=image, padding="max_length", return_tensors="pt")
1046
+
1047
+ >>> with torch.no_grad():
1048
+ ... outputs = model(**inputs)
1049
+
1050
+ >>> logits_per_image = outputs.logits_per_image
1051
+ >>> probs = torch.sigmoid(logits_per_image) # these are the probabilities
1052
+ >>> print(f"{probs[0][0]:.1%} that image 0 is '{texts[0]}'")
1053
+ 31.9% that image 0 is 'a photo of 2 cats'
1054
+ ```"""
1055
+ # Use SigLIP model's config for some fields (if specified) instead of those of vision & text components.
1056
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1057
+ output_hidden_states = (
1058
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1059
+ )
1060
+
1061
+ vision_outputs: BaseModelOutputWithPooling = self.vision_model(
1062
+ pixel_values=pixel_values,
1063
+ output_attentions=output_attentions,
1064
+ output_hidden_states=output_hidden_states,
1065
+ interpolate_pos_encoding=interpolate_pos_encoding,
1066
+ )
1067
+
1068
+ text_outputs: BaseModelOutputWithPooling = self.text_model(
1069
+ input_ids=input_ids,
1070
+ attention_mask=attention_mask,
1071
+ position_ids=position_ids,
1072
+ output_attentions=output_attentions,
1073
+ output_hidden_states=output_hidden_states,
1074
+ )
1075
+
1076
+ image_embeds = vision_outputs.pooler_output
1077
+ text_embeds = text_outputs.pooler_output
1078
+
1079
+ # normalized features
1080
+ image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
1081
+ text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
1082
+
1083
+ # cosine similarity as logits
1084
+ logits_per_text = torch.matmul(text_embeds, image_embeds.t().to(text_embeds.device))
1085
+
1086
+ logit_scale, logit_bias = self.logit_scale.to(text_embeds.device), self.logit_bias.to(text_embeds.device)
1087
+ logits_per_text = logits_per_text * logit_scale.exp() + logit_bias
1088
+
1089
+ logits_per_image = logits_per_text.t()
1090
+
1091
+ loss = None
1092
+ if return_loss:
1093
+ # Adapted from https://github.com/google-research/big_vision/blob/01edb81a4716f93a48be43b3a4af14e29cdb3a7f/big_vision/trainers/proj/image_text/siglip.py#L287
1094
+ eye = torch.eye(logits_per_text.size(0), device=logits_per_text.device)
1095
+ m1_diag1 = -torch.ones_like(logits_per_text) + 2 * eye
1096
+ loglik = torch.nn.functional.logsigmoid(m1_diag1 * logits_per_text)
1097
+ nll = -torch.sum(loglik, dim=-1)
1098
+ loss = nll.mean()
1099
+
1100
+ return SiglipOutput(
1101
+ loss=loss,
1102
+ logits_per_image=logits_per_image,
1103
+ logits_per_text=logits_per_text,
1104
+ text_embeds=text_embeds,
1105
+ image_embeds=image_embeds,
1106
+ text_model_output=text_outputs,
1107
+ vision_model_output=vision_outputs,
1108
+ )
1109
+
1110
+
1111
+ @auto_docstring(
1112
+ custom_intro="""
1113
+ SigLIP vision encoder with an image classification head on top (a linear layer on top of the pooled final hidden states of
1114
+ the patch tokens) e.g. for ImageNet.
1115
+ """
1116
+ )
1117
+ class SiglipForImageClassification(SiglipPreTrainedModel):
1118
+ main_input_name = "pixel_values"
1119
+
1120
+ def __init__(self, config: SiglipConfig) -> None:
1121
+ super().__init__(config)
1122
+
1123
+ self.num_labels = config.num_labels
1124
+
1125
+ # Create the vision model with proper attention
1126
+ # and take only vision_model submodule (for backward compatibility)
1127
+ vision_model = SiglipVisionModel._from_config(config.vision_config)
1128
+ self.vision_model = vision_model.vision_model
1129
+
1130
+ # Classifier head
1131
+ self.classifier = (
1132
+ nn.Linear(config.vision_config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
1133
+ )
1134
+
1135
+ # Initialize weights and apply final processing
1136
+ self.post_init()
1137
+
1138
+ @can_return_tuple
1139
+ @auto_docstring
1140
+ def forward(
1141
+ self,
1142
+ pixel_values: Optional[torch.Tensor] = None,
1143
+ labels: Optional[torch.Tensor] = None,
1144
+ output_attentions: Optional[bool] = None,
1145
+ output_hidden_states: Optional[bool] = None,
1146
+ interpolate_pos_encoding: bool = False,
1147
+ ) -> ImageClassifierOutput:
1148
+ r"""
1149
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1150
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
1151
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1152
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1153
+
1154
+ Examples:
1155
+
1156
+ ```python
1157
+ >>> from transformers import AutoImageProcessor, SiglipForImageClassification
1158
+ >>> import torch
1159
+ >>> from PIL import Image
1160
+ >>> import requests
1161
+
1162
+ >>> torch.manual_seed(3) # doctest: +IGNORE_RESULT
1163
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1164
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1165
+
1166
+ >>> # note: we are loading a `SiglipModel` from the hub here,
1167
+ >>> # so the head will be randomly initialized, hence the predictions will be random if seed is not set above.
1168
+ >>> image_processor = AutoImageProcessor.from_pretrained("google/siglip-base-patch16-224")
1169
+ >>> model = SiglipForImageClassification.from_pretrained("google/siglip-base-patch16-224")
1170
+
1171
+ >>> inputs = image_processor(images=image, return_tensors="pt")
1172
+ >>> outputs = model(**inputs)
1173
+ >>> logits = outputs.logits
1174
+ >>> # model predicts one of the two classes
1175
+ >>> predicted_class_idx = logits.argmax(-1).item()
1176
+ >>> print("Predicted class:", model.config.id2label[predicted_class_idx])
1177
+ Predicted class: LABEL_1
1178
+ ```"""
1179
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1180
+ output_hidden_states = (
1181
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1182
+ )
1183
+
1184
+ outputs: BaseModelOutputWithPooling = self.vision_model(
1185
+ pixel_values,
1186
+ output_attentions=output_attentions,
1187
+ output_hidden_states=output_hidden_states,
1188
+ interpolate_pos_encoding=interpolate_pos_encoding,
1189
+ )
1190
+
1191
+ sequence_output = outputs.last_hidden_state
1192
+
1193
+ # average pool the patch tokens
1194
+ sequence_output = torch.mean(sequence_output, dim=1)
1195
+ # apply classifier
1196
+ logits = self.classifier(sequence_output)
1197
+
1198
+ loss = None
1199
+ if labels is not None:
1200
+ # move labels to correct device to enable model parallelism
1201
+ labels = labels.to(logits.device)
1202
+ if self.config.problem_type is None:
1203
+ if self.num_labels == 1:
1204
+ self.config.problem_type = "regression"
1205
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1206
+ self.config.problem_type = "single_label_classification"
1207
+ else:
1208
+ self.config.problem_type = "multi_label_classification"
1209
+
1210
+ if self.config.problem_type == "regression":
1211
+ loss_fct = MSELoss()
1212
+ if self.num_labels == 1:
1213
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1214
+ else:
1215
+ loss = loss_fct(logits, labels)
1216
+ elif self.config.problem_type == "single_label_classification":
1217
+ loss_fct = CrossEntropyLoss()
1218
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1219
+ elif self.config.problem_type == "multi_label_classification":
1220
+ loss_fct = BCEWithLogitsLoss()
1221
+ loss = loss_fct(logits, labels)
1222
+
1223
+ return ImageClassifierOutput(
1224
+ loss=loss,
1225
+ logits=logits,
1226
+ hidden_states=outputs.hidden_states,
1227
+ attentions=outputs.attentions,
1228
+ )
1229
+
1230
+
1231
+ __all__ = [
1232
+ "SiglipModel",
1233
+ "SiglipPreTrainedModel",
1234
+ "SiglipTextModel",
1235
+ "SiglipVisionModel",
1236
+ "SiglipForImageClassification",
1237
+ ]
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/aloha_policy.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ from typing import ClassVar
3
+
4
+ import einops
5
+ import numpy as np
6
+
7
+ from openpi import transforms
8
+
9
+
10
+ def make_aloha_example() -> dict:
11
+ """Creates a random input example for the Aloha policy."""
12
+ return {
13
+ "state": np.ones((14,)),
14
+ "images": {
15
+ "cam_high": np.random.randint(256, size=(3, 224, 224), dtype=np.uint8),
16
+ "cam_low": np.random.randint(256, size=(3, 224, 224), dtype=np.uint8),
17
+ "cam_left_wrist": np.random.randint(256, size=(3, 224, 224), dtype=np.uint8),
18
+ "cam_right_wrist": np.random.randint(256, size=(3, 224, 224), dtype=np.uint8),
19
+ },
20
+ "prompt": "do something",
21
+ }
22
+
23
+
24
+ def _make_image_mask(image: np.ndarray, valid: bool) -> np.ndarray | np.bool_:
25
+ if image.ndim == 4:
26
+ return np.full((image.shape[0],), valid, dtype=bool)
27
+ return np.bool_(valid)
28
+
29
+
30
+ @dataclasses.dataclass(frozen=True)
31
+ class AlohaInputs(transforms.DataTransformFn):
32
+ """Inputs for the Aloha policy.
33
+
34
+ Expected inputs:
35
+ - images: dict[name, img] where img is [channel, height, width]. name must be in EXPECTED_CAMERAS.
36
+ - state: [14]
37
+ - actions: [action_horizon, 14]
38
+ """
39
+
40
+ # If true, this will convert the joint and gripper values from the standard Aloha space to
41
+ # the space used by the pi internal runtime which was used to train the base model.
42
+ adapt_to_pi: bool = True
43
+
44
+ # The expected cameras names. All input cameras must be in this set. Missing cameras will be
45
+ # replaced with black images and the corresponding `image_mask` will be set to False.
46
+ EXPECTED_CAMERAS: ClassVar[tuple[str, ...]] = ("cam_high", "cam_low", "cam_left_wrist", "cam_right_wrist")
47
+
48
+ def __call__(self, data: dict) -> dict:
49
+ data = _decode_aloha(data, adapt_to_pi=self.adapt_to_pi)
50
+
51
+ in_images = data["images"]
52
+ if set(in_images) - set(self.EXPECTED_CAMERAS):
53
+ raise ValueError(f"Expected images to contain {self.EXPECTED_CAMERAS}, got {tuple(in_images)}")
54
+
55
+ # Assume that base image always exists.
56
+ base_image = in_images["cam_high"]
57
+
58
+ images = {
59
+ "base_0_rgb": base_image,
60
+ }
61
+ image_masks = {
62
+ "base_0_rgb": _make_image_mask(base_image, True),
63
+ }
64
+
65
+ # Add the extra images.
66
+ extra_image_names = {
67
+ "left_wrist_0_rgb": "cam_left_wrist",
68
+ "right_wrist_0_rgb": "cam_right_wrist",
69
+ }
70
+ for dest, source in extra_image_names.items():
71
+ if source in in_images:
72
+ images[dest] = in_images[source]
73
+ image_masks[dest] = _make_image_mask(in_images[source], True)
74
+ else:
75
+ images[dest] = np.zeros_like(base_image)
76
+ image_masks[dest] = _make_image_mask(base_image, False)
77
+
78
+ inputs = {
79
+ "image": images,
80
+ "image_mask": image_masks,
81
+ "state": data["state"],
82
+ }
83
+
84
+ # Actions are only available during training.
85
+ if "actions" in data:
86
+ actions = np.asarray(data["actions"])
87
+ actions = _encode_actions_inv(actions, adapt_to_pi=self.adapt_to_pi)
88
+ inputs["actions"] = actions
89
+
90
+ if "prompt" in data:
91
+ inputs["prompt"] = data["prompt"]
92
+
93
+ return inputs
94
+
95
+
96
+ @dataclasses.dataclass(frozen=True)
97
+ class AlohaOutputs(transforms.DataTransformFn):
98
+ """Outputs for the Aloha policy."""
99
+
100
+ # If true, this will convert the joint and gripper values from the standard Aloha space to
101
+ # the space used by the pi internal runtime which was used to train the base model.
102
+ adapt_to_pi: bool = True
103
+
104
+ def __call__(self, data: dict) -> dict:
105
+ # Only return the first 14 dims.
106
+ actions = np.asarray(data["actions"])[..., :14]
107
+ return {"actions": _encode_actions(actions, adapt_to_pi=self.adapt_to_pi)}
108
+
109
+
110
+ def _joint_flip_mask() -> np.ndarray:
111
+ """Used to convert between aloha and pi joint angles."""
112
+ return np.array([1, -1, -1, 1, 1, 1, 1, 1, -1, -1, 1, 1, 1, 1])
113
+
114
+
115
+ def _normalize(x, min_val, max_val):
116
+ return (x - min_val) / (max_val - min_val)
117
+
118
+
119
+ def _unnormalize(x, min_val, max_val):
120
+ return x * (max_val - min_val) + min_val
121
+
122
+
123
+ def _gripper_to_angular(value):
124
+ # Aloha transforms the gripper positions into a linear space. The following code
125
+ # reverses this transformation to be consistent with pi0 which is pretrained in
126
+ # angular space.
127
+ #
128
+ # These values are coming from the Aloha code:
129
+ # PUPPET_GRIPPER_POSITION_OPEN, PUPPET_GRIPPER_POSITION_CLOSED
130
+ value = _unnormalize(value, min_val=0.01844, max_val=0.05800)
131
+
132
+ # This is the inverse of the angular to linear transformation inside the Interbotix code.
133
+ def linear_to_radian(linear_position, arm_length, horn_radius):
134
+ value = (horn_radius**2 + linear_position**2 - arm_length**2) / (2 * horn_radius * linear_position)
135
+ return np.arcsin(np.clip(value, -1.0, 1.0))
136
+
137
+ # The constants are taken from the Interbotix code.
138
+ value = linear_to_radian(value, arm_length=0.036, horn_radius=0.022)
139
+
140
+ # pi0 gripper data is normalized (0, 1) between encoder counts (2405, 3110).
141
+ # There are 4096 total encoder counts and aloha uses a zero of 2048.
142
+ # Converting this to radians means that the normalized inputs are between (0.5476, 1.6296)
143
+ return _normalize(value, min_val=0.5476, max_val=1.6296)
144
+
145
+
146
+ def _gripper_from_angular(value):
147
+ # Convert from the gripper position used by pi0 to the gripper position that is used by Aloha.
148
+ # Note that the units are still angular but the range is different.
149
+
150
+ # We do not scale the output since the trossen model predictions are already in radians.
151
+ # See the comment in _gripper_to_angular for a derivation of the constant
152
+ value = value + 0.5476
153
+
154
+ # These values are coming from the Aloha code:
155
+ # PUPPET_GRIPPER_JOINT_OPEN, PUPPET_GRIPPER_JOINT_CLOSE
156
+ return _normalize(value, min_val=-0.6213, max_val=1.4910)
157
+
158
+
159
+ def _gripper_from_angular_inv(value):
160
+ # Directly inverts the gripper_from_angular function.
161
+ value = _unnormalize(value, min_val=-0.6213, max_val=1.4910)
162
+ return value - 0.5476
163
+
164
+
165
+ def _decode_aloha(data: dict, *, adapt_to_pi: bool = False) -> dict:
166
+ # state is [left_arm_joint_angles, left_arm_gripper, right_arm_joint_angles, right_arm_gripper]
167
+ # dim sizes: [6, 1, 6, 1]
168
+ state = np.asarray(data["state"])
169
+ state = _decode_state(state, adapt_to_pi=adapt_to_pi)
170
+
171
+ def convert_image(img):
172
+ img = np.asarray(img)
173
+ # Convert to uint8 if using float images.
174
+ if np.issubdtype(img.dtype, np.floating):
175
+ img = (255 * img).astype(np.uint8)
176
+ if img.ndim == 4:
177
+ return einops.rearrange(img, "b c h w -> b h w c")
178
+ return einops.rearrange(img, "c h w -> h w c")
179
+
180
+ images = data["images"]
181
+ images_dict = {name: convert_image(img) for name, img in images.items()}
182
+
183
+ data["images"] = images_dict
184
+ data["state"] = state
185
+ return data
186
+
187
+
188
+ def _decode_state(state: np.ndarray, *, adapt_to_pi: bool = False) -> np.ndarray:
189
+ if adapt_to_pi:
190
+ # Flip the joints.
191
+ state = _joint_flip_mask() * state
192
+ # Reverse the gripper transformation that is being applied by the Aloha runtime.
193
+ state[..., [6, 13]] = _gripper_to_angular(state[..., [6, 13]])
194
+ return state
195
+
196
+
197
+ def _encode_actions(actions: np.ndarray, *, adapt_to_pi: bool = False) -> np.ndarray:
198
+ if adapt_to_pi:
199
+ # Flip the joints.
200
+ actions = _joint_flip_mask() * actions
201
+ actions[..., [6, 13]] = _gripper_from_angular(actions[..., [6, 13]])
202
+ return actions
203
+
204
+
205
+ def _encode_actions_inv(actions: np.ndarray, *, adapt_to_pi: bool = False) -> np.ndarray:
206
+ if adapt_to_pi:
207
+ actions = _joint_flip_mask() * actions
208
+ actions[..., [6, 13]] = _gripper_from_angular_inv(actions[..., [6, 13]])
209
+ return actions
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/droid_policy.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+
3
+ import einops
4
+ import numpy as np
5
+
6
+ from openpi import transforms
7
+ from openpi.models import model as _model
8
+
9
+
10
+ def make_droid_example() -> dict:
11
+ """Creates a random input example for the Droid policy."""
12
+ return {
13
+ "observation/exterior_image_1_left": np.random.randint(256, size=(224, 224, 3), dtype=np.uint8),
14
+ "observation/wrist_image_left": np.random.randint(256, size=(224, 224, 3), dtype=np.uint8),
15
+ "observation/joint_position": np.random.rand(7),
16
+ "observation/gripper_position": np.random.rand(1),
17
+ "prompt": "do something",
18
+ }
19
+
20
+
21
+ def _parse_image(image) -> np.ndarray:
22
+ image = np.asarray(image)
23
+ if np.issubdtype(image.dtype, np.floating):
24
+ image = (255 * image).astype(np.uint8)
25
+ if image.shape[0] == 3:
26
+ image = einops.rearrange(image, "c h w -> h w c")
27
+ return image
28
+
29
+
30
+ @dataclasses.dataclass(frozen=True)
31
+ class DroidInputs(transforms.DataTransformFn):
32
+ # Determines which model will be used.
33
+ model_type: _model.ModelType
34
+
35
+ def __call__(self, data: dict) -> dict:
36
+ gripper_pos = np.asarray(data["observation/gripper_position"])
37
+ if gripper_pos.ndim == 0:
38
+ # Ensure gripper position is a 1D array, not a scalar, so we can concatenate with joint positions
39
+ gripper_pos = gripper_pos[np.newaxis]
40
+ state = np.concatenate([data["observation/joint_position"], gripper_pos])
41
+
42
+ # Possibly need to parse images to uint8 (H,W,C) since LeRobot automatically
43
+ # stores as float32 (C,H,W), gets skipped for policy inference
44
+ base_image = _parse_image(data["observation/exterior_image_1_left"])
45
+ wrist_image = _parse_image(data["observation/wrist_image_left"])
46
+
47
+ match self.model_type:
48
+ case _model.ModelType.PI0 | _model.ModelType.PI05:
49
+ names = ("base_0_rgb", "left_wrist_0_rgb", "right_wrist_0_rgb")
50
+ images = (base_image, wrist_image, np.zeros_like(base_image))
51
+ image_masks = (np.True_, np.True_, np.False_)
52
+ case _model.ModelType.PI0_FAST:
53
+ names = ("base_0_rgb", "base_1_rgb", "wrist_0_rgb")
54
+ # We don't mask out padding images for FAST models.
55
+ images = (base_image, np.zeros_like(base_image), wrist_image)
56
+ image_masks = (np.True_, np.True_, np.True_)
57
+ case _:
58
+ raise ValueError(f"Unsupported model type: {self.model_type}")
59
+
60
+ inputs = {
61
+ "state": state,
62
+ "image": dict(zip(names, images, strict=True)),
63
+ "image_mask": dict(zip(names, image_masks, strict=True)),
64
+ }
65
+
66
+ if "actions" in data:
67
+ inputs["actions"] = np.asarray(data["actions"])
68
+
69
+ if "prompt" in data:
70
+ if isinstance(data["prompt"], bytes):
71
+ data["prompt"] = data["prompt"].decode("utf-8")
72
+ inputs["prompt"] = data["prompt"]
73
+
74
+ return inputs
75
+
76
+
77
+ @dataclasses.dataclass(frozen=True)
78
+ class DroidOutputs(transforms.DataTransformFn):
79
+ def __call__(self, data: dict) -> dict:
80
+ # Only return the first 8 dims.
81
+ return {"actions": np.asarray(data["actions"][:, :8])}
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/libero_policy.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+
3
+ import einops
4
+ import numpy as np
5
+
6
+ from openpi import transforms
7
+ from openpi.models import model as _model
8
+
9
+
10
+ def make_libero_example() -> dict:
11
+ """Creates a random input example for the Libero policy."""
12
+ return {
13
+ "observation/state": np.random.rand(8),
14
+ "observation/image": np.random.randint(256, size=(224, 224, 3), dtype=np.uint8),
15
+ "observation/wrist_image": np.random.randint(256, size=(224, 224, 3), dtype=np.uint8),
16
+ "prompt": "do something",
17
+ }
18
+
19
+
20
+ def _parse_image(image) -> np.ndarray:
21
+ image = np.asarray(image)
22
+ if np.issubdtype(image.dtype, np.floating):
23
+ image = (255 * image).astype(np.uint8)
24
+ if image.shape[0] == 3:
25
+ image = einops.rearrange(image, "c h w -> h w c")
26
+ return image
27
+
28
+
29
+ @dataclasses.dataclass(frozen=True)
30
+ class LiberoInputs(transforms.DataTransformFn):
31
+ """
32
+ This class is used to convert inputs to the model to the expected format. It is used for both training and inference.
33
+
34
+ For your own dataset, you can copy this class and modify the keys based on the comments below to pipe
35
+ the correct elements of your dataset into the model.
36
+ """
37
+
38
+ # Determines which model will be used.
39
+ # Do not change this for your own dataset.
40
+ model_type: _model.ModelType
41
+
42
+ def __call__(self, data: dict) -> dict:
43
+ # Possibly need to parse images to uint8 (H,W,C) since LeRobot automatically
44
+ # stores as float32 (C,H,W), gets skipped for policy inference.
45
+ # Keep this for your own dataset, but if your dataset stores the images
46
+ # in a different key than "observation/image" or "observation/wrist_image",
47
+ # you should change it below.
48
+ # Pi0 models support three image inputs at the moment: one third-person view,
49
+ # and two wrist views (left and right). If your dataset does not have a particular type
50
+ # of image, e.g. wrist images, you can comment it out here and replace it with zeros like we do for the
51
+ # right wrist image below.
52
+ base_image = _parse_image(data["observation/image"])
53
+ wrist_image = _parse_image(data["observation/wrist_image"])
54
+
55
+ # Create inputs dict. Do not change the keys in the dict below.
56
+ inputs = {
57
+ "state": data["observation/state"],
58
+ "image": {
59
+ "base_0_rgb": base_image,
60
+ "left_wrist_0_rgb": wrist_image,
61
+ # Pad any non-existent images with zero-arrays of the appropriate shape.
62
+ "right_wrist_0_rgb": np.zeros_like(base_image),
63
+ },
64
+ "image_mask": {
65
+ "base_0_rgb": np.True_,
66
+ "left_wrist_0_rgb": np.True_,
67
+ # We only mask padding images for pi0 model, not pi0-FAST. Do not change this for your own dataset.
68
+ "right_wrist_0_rgb": np.True_ if self.model_type == _model.ModelType.PI0_FAST else np.False_,
69
+ },
70
+ }
71
+
72
+ # Pad actions to the model action dimension. Keep this for your own dataset.
73
+ # Actions are only available during training.
74
+ if "actions" in data:
75
+ inputs["actions"] = data["actions"]
76
+
77
+ # Pass the prompt (aka language instruction) to the model.
78
+ # Keep this for your own dataset (but modify the key if the instruction is not
79
+ # stored in "prompt"; the output dict always needs to have the key "prompt").
80
+ if "prompt" in data:
81
+ inputs["prompt"] = data["prompt"]
82
+
83
+ return inputs
84
+
85
+
86
+ @dataclasses.dataclass(frozen=True)
87
+ class LiberoOutputs(transforms.DataTransformFn):
88
+ """
89
+ This class is used to convert outputs from the model back the the dataset specific format. It is
90
+ used for inference only.
91
+
92
+ For your own dataset, you can copy this class and modify the action dimension based on the comments below.
93
+ """
94
+
95
+ def __call__(self, data: dict) -> dict:
96
+ # Only return the first N actions -- since we padded actions above to fit the model action
97
+ # dimension, we need to now parse out the correct number of actions in the return dict.
98
+ # For Libero, we only return the first 7 actions (since the rest is padding).
99
+ # For your own dataset, replace `7` with the action dimension of your dataset.
100
+ return {"actions": np.asarray(data["actions"][:, :7])}
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/pika_bimanual_policy.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Policy transforms for the dual-arm Pika T-shirt-folding dataset.
2
+
3
+ The LeRobot conversion stores two RGB streams only: ``cam_left_wrist`` is the
4
+ left Pika fisheye and ``cam_right_wrist`` is the right Pika fisheye. Pi0.5 has
5
+ three fixed image slots, so the unused third slot is explicitly masked out.
6
+
7
+ The raw 14-D state/action convention is left [xyz, rotvec_xyz, gripper]
8
+ followed by right [xyz, rotvec_xyz, gripper], with absolute next-step targets.
9
+ ``PikaBimanualInputs(relative_pose=True)`` instead maps state/action into the
10
+ current-frame SE(3) representation used by the relative Pi0.5 configuration.
11
+ """
12
+
13
+ import dataclasses
14
+
15
+ import einops
16
+ import numpy as np
17
+ from scipy.spatial.transform import Rotation
18
+
19
+ from openpi import transforms
20
+ from openpi.models import model as _model
21
+
22
+
23
+ PIKA_BIMANUAL_ACTION_DIM = 14
24
+
25
+
26
+ def _pose_matrix(pose: np.ndarray) -> np.ndarray:
27
+ """Convert one Pika ``xyz + rotvec`` pose to a homogeneous matrix."""
28
+ pose = np.asarray(pose, dtype=np.float32)
29
+ if pose.shape != (6,):
30
+ raise ValueError(f"Expected one 6-D Pika pose, got {pose.shape}.")
31
+ matrix = np.eye(4, dtype=np.float32)
32
+ matrix[:3, :3] = Rotation.from_rotvec(pose[3:]).as_matrix().astype(np.float32)
33
+ matrix[:3, 3] = pose[:3]
34
+ return matrix
35
+
36
+
37
+ def _pose_vector(matrix: np.ndarray) -> np.ndarray:
38
+ """Convert a homogeneous matrix to Pika ``xyz + rotvec`` pose."""
39
+ matrix = np.asarray(matrix, dtype=np.float32)
40
+ if matrix.shape != (4, 4):
41
+ raise ValueError(f"Expected a 4x4 pose matrix, got {matrix.shape}.")
42
+ return np.concatenate(
43
+ (matrix[:3, 3], Rotation.from_matrix(matrix[:3, :3]).as_rotvec().astype(np.float32))
44
+ ).astype(np.float32)
45
+
46
+
47
+ def absolute_state_to_relative(state: np.ndarray) -> np.ndarray:
48
+ """Express dual-Pika proprioception in the current left-Pika frame.
49
+
50
+ The left pose is deliberately identity. The right pose remains available as
51
+ ``T_left^-1 @ T_right`` so the policy can coordinate both hands without
52
+ learning a Lighthouse/world origin. Grippers remain absolute openness.
53
+ """
54
+ state = np.asarray(state, dtype=np.float32)
55
+ if state.shape != (PIKA_BIMANUAL_ACTION_DIM,):
56
+ raise ValueError(f"Expected a {PIKA_BIMANUAL_ACTION_DIM}-D Pika state, got shape {state.shape}.")
57
+ left_from_right = np.linalg.inv(_pose_matrix(state[:6])) @ _pose_matrix(state[7:13])
58
+ relative = np.zeros_like(state)
59
+ relative[6] = state[6]
60
+ relative[7:13] = _pose_vector(left_from_right)
61
+ relative[13] = state[13]
62
+ return relative
63
+
64
+
65
+ def absolute_actions_to_relative(state: np.ndarray, actions: np.ndarray) -> np.ndarray:
66
+ """Express absolute future Pika targets in each arm's current local frame.
67
+
68
+ For arm ``i`` and every action-horizon step ``k`` this returns
69
+ ``inverse(T_i,current) @ T_i,target[k]``. This is a full SE(3)
70
+ representation: translation is in the current local frame and rotation is
71
+ a local relative rotation. Gripper values intentionally remain absolute
72
+ normalized openings.
73
+ """
74
+ state = np.asarray(state, dtype=np.float32)
75
+ actions = np.asarray(actions, dtype=np.float32)
76
+ if state.shape != (PIKA_BIMANUAL_ACTION_DIM,):
77
+ raise ValueError(f"Expected a {PIKA_BIMANUAL_ACTION_DIM}-D Pika state, got shape {state.shape}.")
78
+ if actions.ndim != 2 or actions.shape[1] != PIKA_BIMANUAL_ACTION_DIM:
79
+ raise ValueError(
80
+ f"Expected Pika actions with shape (horizon, {PIKA_BIMANUAL_ACTION_DIM}), got {actions.shape}."
81
+ )
82
+ relative = actions.copy()
83
+ for offset in (0, 7):
84
+ current_from_world = np.linalg.inv(_pose_matrix(state[offset : offset + 6]))
85
+ for index, target in enumerate(actions[:, offset : offset + 6]):
86
+ relative[index, offset : offset + 6] = _pose_vector(current_from_world @ _pose_matrix(target))
87
+ return relative
88
+
89
+
90
+ def _parse_image(image: np.ndarray) -> np.ndarray:
91
+ """Return an already-decoded image as uint8 HWC, accepting CHW or HWC."""
92
+ image = np.asarray(image)
93
+ if image.ndim != 3:
94
+ raise ValueError(f"Expected an RGB image with 3 dimensions, got shape {image.shape}.")
95
+ if np.issubdtype(image.dtype, np.floating):
96
+ image = np.clip(image * 255, 0, 255).astype(np.uint8)
97
+ if image.shape[0] == 3 and image.shape[-1] != 3:
98
+ image = einops.rearrange(image, "c h w -> h w c")
99
+ if image.shape[-1] != 3:
100
+ raise ValueError(f"Expected an RGB image with 3 channels, got shape {image.shape}.")
101
+ return image
102
+
103
+
104
+ @dataclasses.dataclass(frozen=True)
105
+ class PikaBimanualInputs(transforms.DataTransformFn):
106
+ """Map Pika training/runtime inputs to Pi0.5's fixed observation schema."""
107
+
108
+ model_type: _model.ModelType
109
+ relative_pose: bool = False
110
+
111
+ def __call__(self, data: dict) -> dict:
112
+ state = np.asarray(data["observation/state"], dtype=np.float32)
113
+ if state.shape[-1] != PIKA_BIMANUAL_ACTION_DIM:
114
+ raise ValueError(
115
+ f"Expected a {PIKA_BIMANUAL_ACTION_DIM}-D Pika state, got shape {state.shape}."
116
+ )
117
+
118
+ left_fisheye = _parse_image(data["observation/image"])
119
+ right_fisheye = _parse_image(data["observation/wrist_image"])
120
+ if left_fisheye.shape != right_fisheye.shape:
121
+ raise ValueError(
122
+ "The two Pika fisheye frames must have the same shape; got "
123
+ f"{left_fisheye.shape} and {right_fisheye.shape}."
124
+ )
125
+
126
+ inputs = {
127
+ "state": absolute_state_to_relative(state) if self.relative_pose else state,
128
+ "image": {
129
+ "base_0_rgb": left_fisheye,
130
+ "left_wrist_0_rgb": right_fisheye,
131
+ "right_wrist_0_rgb": np.zeros_like(left_fisheye),
132
+ },
133
+ "image_mask": {
134
+ "base_0_rgb": np.True_,
135
+ "left_wrist_0_rgb": np.True_,
136
+ "right_wrist_0_rgb": np.False_,
137
+ },
138
+ }
139
+
140
+ if "actions" in data:
141
+ actions = np.asarray(data["actions"], dtype=np.float32)
142
+ if actions.shape[-1] != PIKA_BIMANUAL_ACTION_DIM:
143
+ raise ValueError(
144
+ f"Expected {PIKA_BIMANUAL_ACTION_DIM}-D Pika actions, got shape {actions.shape}."
145
+ )
146
+ inputs["actions"] = absolute_actions_to_relative(state, actions) if self.relative_pose else actions
147
+ if "prompt" in data:
148
+ inputs["prompt"] = data["prompt"]
149
+ return inputs
150
+
151
+
152
+ @dataclasses.dataclass(frozen=True)
153
+ class PikaBimanualOutputs(transforms.DataTransformFn):
154
+ """Validate and return the 14-D Pika action chunk at policy inference."""
155
+
156
+ def __call__(self, data: dict) -> dict:
157
+ actions = np.asarray(data["actions"])
158
+ if actions.shape[-1] != PIKA_BIMANUAL_ACTION_DIM:
159
+ raise ValueError(
160
+ f"Expected model output with {PIKA_BIMANUAL_ACTION_DIM} action dimensions, "
161
+ f"got shape {actions.shape}."
162
+ )
163
+ return {"actions": actions}
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/pika_bimanual_policy_test.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from openpi.models import model as _model
4
+ from openpi.policies import pika_bimanual_policy
5
+
6
+
7
+ def test_pika_bimanual_inputs_maps_two_fisheyes_and_masks_third_slot():
8
+ transform = pika_bimanual_policy.PikaBimanualInputs(_model.ModelType.PI05)
9
+ result = transform(
10
+ {
11
+ "observation/state": np.zeros(14, dtype=np.float32),
12
+ "observation/image": np.zeros((3, 4, 5), dtype=np.uint8),
13
+ "observation/wrist_image": np.ones((4, 5, 3), dtype=np.uint8),
14
+ "actions": np.zeros((16, 14), dtype=np.float32),
15
+ "prompt": "Fold the T-shirt.",
16
+ }
17
+ )
18
+
19
+ assert result["image"]["base_0_rgb"].shape == (4, 5, 3)
20
+ assert result["image"]["left_wrist_0_rgb"].shape == (4, 5, 3)
21
+ assert not result["image_mask"]["right_wrist_0_rgb"]
22
+ assert result["actions"].shape == (16, 14)
23
+
24
+
25
+ def test_pika_bimanual_outputs_rejects_wrong_action_dimension():
26
+ transform = pika_bimanual_policy.PikaBimanualOutputs()
27
+ with np.testing.assert_raises_regex(ValueError, "14"):
28
+ transform({"actions": np.zeros((16, 15), dtype=np.float32)})
29
+
30
+
31
+ def test_relative_pika_pose_transform_removes_global_frame_and_preserves_arm_relation():
32
+ state = np.array([1, 2, 3, 0, 0, np.pi / 2, 0.2, 2, 2, 3, 0, 0, np.pi / 2, 0.8], dtype=np.float32)
33
+ actions = np.stack((state.copy(), state.copy()))
34
+ actions[1, 0] += 0.1 # Pika-world x, which is current local y after the z rotation.
35
+
36
+ relative_state = pika_bimanual_policy.absolute_state_to_relative(state)
37
+ relative_actions = pika_bimanual_policy.absolute_actions_to_relative(state, actions)
38
+
39
+ np.testing.assert_allclose(relative_state[:6], 0.0, atol=1e-6)
40
+ np.testing.assert_allclose(relative_state[7:10], [0.0, -1.0, 0.0], atol=1e-6)
41
+ np.testing.assert_allclose(relative_state[[6, 13]], [0.2, 0.8], atol=1e-6)
42
+ np.testing.assert_allclose(relative_actions[0, :6], 0.0, atol=1e-6)
43
+ np.testing.assert_allclose(relative_actions[1, :3], [0.0, -0.1, 0.0], atol=1e-6)
44
+ np.testing.assert_allclose(relative_actions[:, [6, 13]], [[0.2, 0.8], [0.2, 0.8]], atol=1e-6)
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/policy.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Sequence
2
+ import logging
3
+ import pathlib
4
+ import time
5
+ from typing import Any, TypeAlias
6
+
7
+ import flax
8
+ import flax.traverse_util
9
+ import jax
10
+ import jax.numpy as jnp
11
+ import numpy as np
12
+ from openpi_client import base_policy as _base_policy
13
+ import torch
14
+ from typing_extensions import override
15
+
16
+ from openpi import transforms as _transforms
17
+ from openpi.models import model as _model
18
+ from openpi.shared import array_typing as at
19
+ from openpi.shared import nnx_utils
20
+
21
+ BasePolicy: TypeAlias = _base_policy.BasePolicy
22
+
23
+
24
+ class Policy(BasePolicy):
25
+ def __init__(
26
+ self,
27
+ model: _model.BaseModel,
28
+ *,
29
+ rng: at.KeyArrayLike | None = None,
30
+ transforms: Sequence[_transforms.DataTransformFn] = (),
31
+ output_transforms: Sequence[_transforms.DataTransformFn] = (),
32
+ sample_kwargs: dict[str, Any] | None = None,
33
+ metadata: dict[str, Any] | None = None,
34
+ pytorch_device: str = "cpu",
35
+ is_pytorch: bool = False,
36
+ ):
37
+ """Initialize the Policy.
38
+
39
+ Args:
40
+ model: The model to use for action sampling.
41
+ rng: Random number generator key for JAX models. Ignored for PyTorch models.
42
+ transforms: Input data transformations to apply before inference.
43
+ output_transforms: Output data transformations to apply after inference.
44
+ sample_kwargs: Additional keyword arguments to pass to model.sample_actions.
45
+ metadata: Additional metadata to store with the policy.
46
+ pytorch_device: Device to use for PyTorch models (e.g., "cpu", "cuda:0").
47
+ Only relevant when is_pytorch=True.
48
+ is_pytorch: Whether the model is a PyTorch model. If False, assumes JAX model.
49
+ """
50
+ self._model = model
51
+ self._input_transform = _transforms.compose(transforms)
52
+ self._output_transform = _transforms.compose(output_transforms)
53
+ self._sample_kwargs = sample_kwargs or {}
54
+ self._metadata = metadata or {}
55
+ self._is_pytorch_model = is_pytorch
56
+ self._pytorch_device = pytorch_device
57
+
58
+ if self._is_pytorch_model:
59
+ self._model = self._model.to(pytorch_device)
60
+ self._model.eval()
61
+ self._sample_actions = model.sample_actions
62
+ else:
63
+ # JAX model setup
64
+ self._sample_actions = nnx_utils.module_jit(model.sample_actions)
65
+ self._rng = rng or jax.random.key(0)
66
+
67
+ @override
68
+ def infer(self, obs: dict, *, noise: np.ndarray | None = None) -> dict: # type: ignore[misc]
69
+ # Make a copy since transformations may modify the inputs in place.
70
+ inputs = jax.tree.map(lambda x: x, obs)
71
+ inputs = self._input_transform(inputs)
72
+
73
+ is_batched = False
74
+ if "state" in inputs:
75
+ is_batched = np.asarray(inputs["state"]).ndim > 1
76
+ elif "image" in inputs and inputs["image"]:
77
+ first_image = next(iter(inputs["image"].values()))
78
+ is_batched = np.asarray(first_image).ndim > 3
79
+
80
+ if not self._is_pytorch_model:
81
+ if not is_batched:
82
+ inputs = jax.tree.map(lambda x: jnp.asarray(x)[np.newaxis, ...], inputs)
83
+ else:
84
+ inputs = jax.tree.map(jnp.asarray, inputs)
85
+ self._rng, sample_rng_or_pytorch_device = jax.random.split(self._rng)
86
+ else:
87
+ # Convert inputs to PyTorch tensors and move to correct device
88
+ if not is_batched:
89
+ inputs = jax.tree.map(
90
+ lambda x: torch.from_numpy(np.array(x)).to(self._pytorch_device)[None, ...], inputs
91
+ )
92
+ else:
93
+ inputs = jax.tree.map(lambda x: torch.from_numpy(np.array(x)).to(self._pytorch_device), inputs)
94
+ sample_rng_or_pytorch_device = self._pytorch_device
95
+
96
+ # Prepare kwargs for sample_actions
97
+ sample_kwargs = dict(self._sample_kwargs)
98
+ if noise is not None:
99
+ noise = torch.from_numpy(noise).to(self._pytorch_device) if self._is_pytorch_model else jnp.asarray(noise)
100
+
101
+ if not is_batched and noise.ndim == 2:
102
+ noise = noise[None, ...]
103
+ sample_kwargs["noise"] = noise
104
+
105
+ observation = _model.Observation.from_dict(inputs)
106
+ start_time = time.monotonic()
107
+ outputs = {
108
+ "state": inputs["state"],
109
+ "actions": self._sample_actions(sample_rng_or_pytorch_device, observation, **sample_kwargs),
110
+ }
111
+ model_time = time.monotonic() - start_time
112
+ if self._is_pytorch_model:
113
+ if not is_batched:
114
+ outputs = jax.tree.map(lambda x: np.asarray(x[0, ...].detach().cpu()), outputs)
115
+ else:
116
+ outputs = jax.tree.map(lambda x: np.asarray(x.detach().cpu()), outputs)
117
+ else:
118
+ if not is_batched:
119
+ outputs = jax.tree.map(lambda x: np.asarray(x[0, ...]), outputs)
120
+ else:
121
+ outputs = jax.tree.map(np.asarray, outputs)
122
+
123
+ outputs = self._output_transform(outputs)
124
+ outputs["policy_timing"] = {
125
+ "infer_ms": model_time * 1000,
126
+ }
127
+ return outputs
128
+
129
+ @property
130
+ def metadata(self) -> dict[str, Any]:
131
+ return self._metadata
132
+
133
+
134
+ class PolicyRecorder(_base_policy.BasePolicy):
135
+ """Records the policy's behavior to disk."""
136
+
137
+ def __init__(self, policy: _base_policy.BasePolicy, record_dir: str):
138
+ self._policy = policy
139
+
140
+ logging.info(f"Dumping policy records to: {record_dir}")
141
+ self._record_dir = pathlib.Path(record_dir)
142
+ self._record_dir.mkdir(parents=True, exist_ok=True)
143
+ self._record_step = 0
144
+
145
+ @override
146
+ def infer(self, obs: dict) -> dict: # type: ignore[misc]
147
+ results = self._policy.infer(obs)
148
+
149
+ data = {"inputs": obs, "outputs": results}
150
+ data = flax.traverse_util.flatten_dict(data, sep="/")
151
+
152
+ output_path = self._record_dir / f"step_{self._record_step}"
153
+ self._record_step += 1
154
+
155
+ np.save(output_path, np.asarray(data))
156
+ return results
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/policy_config.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import pathlib
4
+ from typing import Any
5
+
6
+ import jax.numpy as jnp
7
+
8
+ import openpi.models.model as _model
9
+ import openpi.policies.policy as _policy
10
+ import openpi.shared.download as download
11
+ from openpi.training import checkpoints as _checkpoints
12
+ from openpi.training import config as _config
13
+ import openpi.transforms as transforms
14
+
15
+
16
+ def create_trained_policy(
17
+ train_config: _config.TrainConfig,
18
+ checkpoint_dir: pathlib.Path | str,
19
+ *,
20
+ repack_transforms: transforms.Group | None = None,
21
+ sample_kwargs: dict[str, Any] | None = None,
22
+ default_prompt: str | None = None,
23
+ norm_stats: dict[str, transforms.NormStats] | None = None,
24
+ pytorch_device: str | None = None,
25
+ ) -> _policy.Policy:
26
+ """Create a policy from a trained checkpoint.
27
+
28
+ Args:
29
+ train_config: The training config to use to create the model.
30
+ checkpoint_dir: The directory to load the model from.
31
+ repack_transforms: Optional transforms that will be applied before any other transforms.
32
+ sample_kwargs: The kwargs to pass to the `sample_actions` method. If not provided, the default
33
+ kwargs will be used.
34
+ default_prompt: The default prompt to use for the policy. Will inject the prompt into the input
35
+ data if it doesn't already exist.
36
+ norm_stats: The norm stats to use for the policy. If not provided, the norm stats will be loaded
37
+ from the checkpoint directory.
38
+ pytorch_device: Device to use for PyTorch models (e.g., "cpu", "cuda", "cuda:0").
39
+ If None and is_pytorch=True, will use "cuda" if available, otherwise "cpu".
40
+
41
+ Note:
42
+ The function automatically detects whether the model is PyTorch-based by checking for the
43
+ presence of "model.safensors" in the checkpoint directory.
44
+ """
45
+ repack_transforms = repack_transforms or transforms.Group()
46
+ checkpoint_dir = download.maybe_download(str(checkpoint_dir))
47
+
48
+ # Check if this is a PyTorch model by looking for model.safetensors
49
+ weight_path = os.path.join(checkpoint_dir, "model.safetensors")
50
+ is_pytorch = os.path.exists(weight_path)
51
+
52
+ logging.info("Loading model...")
53
+ if is_pytorch:
54
+ model = train_config.model.load_pytorch(train_config, weight_path)
55
+ model.paligemma_with_expert.to_bfloat16_for_selected_params("bfloat16")
56
+ else:
57
+ model = train_config.model.load(_model.restore_params(checkpoint_dir / "params", dtype=jnp.bfloat16))
58
+ data_config = train_config.data.create(train_config.assets_dirs, train_config.model)
59
+ if norm_stats is None:
60
+ # We are loading the norm stats from the checkpoint instead of the config assets dir to make sure
61
+ # that the policy is using the same normalization stats as the original training process.
62
+ if data_config.asset_id is None:
63
+ raise ValueError("Asset id is required to load norm stats.")
64
+ norm_stats = _checkpoints.load_norm_stats(checkpoint_dir / "assets", data_config.asset_id)
65
+
66
+ # Determine the device to use for PyTorch models
67
+ if is_pytorch and pytorch_device is None:
68
+ try:
69
+ import torch
70
+
71
+ pytorch_device = "cuda" if torch.cuda.is_available() else "cpu"
72
+ except ImportError:
73
+ pytorch_device = "cpu"
74
+
75
+ return _policy.Policy(
76
+ model,
77
+ transforms=[
78
+ *repack_transforms.inputs,
79
+ transforms.InjectDefaultPrompt(default_prompt),
80
+ *data_config.data_transforms.inputs,
81
+ transforms.Normalize(norm_stats, use_quantiles=data_config.use_quantile_norm),
82
+ *data_config.model_transforms.inputs,
83
+ ],
84
+ output_transforms=[
85
+ *data_config.model_transforms.outputs,
86
+ transforms.Unnormalize(norm_stats, use_quantiles=data_config.use_quantile_norm),
87
+ *data_config.data_transforms.outputs,
88
+ *repack_transforms.outputs,
89
+ ],
90
+ sample_kwargs=sample_kwargs,
91
+ metadata=train_config.policy_metadata,
92
+ is_pytorch=is_pytorch,
93
+ pytorch_device=pytorch_device if is_pytorch else None,
94
+ )
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/policy_test.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openpi_client import action_chunk_broker
2
+ import pytest
3
+
4
+ from openpi.policies import aloha_policy
5
+ from openpi.policies import policy_config as _policy_config
6
+ from openpi.training import config as _config
7
+
8
+
9
+ @pytest.mark.manual
10
+ def test_infer():
11
+ config = _config.get_config("pi0_aloha_sim")
12
+ policy = _policy_config.create_trained_policy(config, "gs://openpi-assets/checkpoints/pi0_aloha_sim")
13
+
14
+ example = aloha_policy.make_aloha_example()
15
+ result = policy.infer(example)
16
+
17
+ assert result["actions"].shape == (config.model.action_horizon, 14)
18
+
19
+
20
+ @pytest.mark.manual
21
+ def test_broker():
22
+ config = _config.get_config("pi0_aloha_sim")
23
+ policy = _policy_config.create_trained_policy(config, "gs://openpi-assets/checkpoints/pi0_aloha_sim")
24
+
25
+ broker = action_chunk_broker.ActionChunkBroker(
26
+ policy,
27
+ # Only execute the first half of the chunk.
28
+ action_horizon=config.model.action_horizon // 2,
29
+ )
30
+
31
+ example = aloha_policy.make_aloha_example()
32
+ for _ in range(config.model.action_horizon):
33
+ outputs = broker.infer(example)
34
+ assert outputs["actions"].shape == (14,)
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/policies/wuji_policy.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Policy transforms for Tianji Marvin + dual Wuji Hand (Gen1).
2
+
3
+ Adapted from wuji-openpi. Action layout (54D):
4
+ left arm (7) + left hand (20) + right arm (7) + right hand (20)
5
+
6
+ Expected LeRobot fields:
7
+ - observation.state: 54 dims
8
+ - action: 54 dims
9
+ - observation.images.cam_left_wrist / cam_right_wrist
10
+ - observation.images.stereo_right (or cam_high via DataConfig repack)
11
+ """
12
+
13
+ import dataclasses
14
+
15
+ import einops
16
+ import numpy as np
17
+
18
+ from openpi import transforms
19
+ from openpi.models import model as _model
20
+
21
+ # Dual-arm + dual Wuji Hand Gen1
22
+ WUJI_ACTION_DIM = 54
23
+
24
+
25
+ def make_wuji_example() -> dict:
26
+ """Creates a random input example for the Wuji policy."""
27
+ return {
28
+ "observation/state": np.random.rand(WUJI_ACTION_DIM).astype(np.float32),
29
+ "observation/image": np.random.randint(256, size=(480, 640, 3), dtype=np.uint8),
30
+ "observation/left_wrist_image": np.random.randint(256, size=(480, 640, 3), dtype=np.uint8),
31
+ "observation/right_wrist_image": np.random.randint(256, size=(480, 640, 3), dtype=np.uint8),
32
+ "prompt": "pick up the object with both hands",
33
+ }
34
+
35
+
36
+ def _parse_image(image) -> np.ndarray:
37
+ """Parse image to uint8 (H, W, C) format."""
38
+ image = np.asarray(image)
39
+ if np.issubdtype(image.dtype, np.floating):
40
+ image = (255 * image).astype(np.uint8)
41
+ if image.shape[0] == 3:
42
+ image = einops.rearrange(image, "c h w -> h w c")
43
+ return image
44
+
45
+
46
+ @dataclasses.dataclass(frozen=True)
47
+ class WujiInputs(transforms.DataTransformFn):
48
+ """Convert Wuji dataset / runtime inputs to Pi0 model format."""
49
+
50
+ model_type: _model.ModelType
51
+
52
+ def __call__(self, data: dict) -> dict:
53
+ base_image = _parse_image(data["observation/image"])
54
+ left_wrist_image = _parse_image(data["observation/left_wrist_image"])
55
+ right_wrist_image = _parse_image(data["observation/right_wrist_image"])
56
+
57
+ inputs = {
58
+ "state": data["observation/state"],
59
+ "image": {
60
+ "base_0_rgb": base_image,
61
+ "left_wrist_0_rgb": left_wrist_image,
62
+ "right_wrist_0_rgb": right_wrist_image,
63
+ },
64
+ "image_mask": {
65
+ "base_0_rgb": np.True_,
66
+ "left_wrist_0_rgb": np.True_,
67
+ "right_wrist_0_rgb": np.True_,
68
+ },
69
+ }
70
+
71
+ if "actions" in data:
72
+ inputs["actions"] = data["actions"]
73
+
74
+ if "prompt" in data:
75
+ inputs["prompt"] = data["prompt"]
76
+
77
+ return inputs
78
+
79
+
80
+ @dataclasses.dataclass(frozen=True)
81
+ class WujiOutputs(transforms.DataTransformFn):
82
+ """Trim padded model actions back to the Wuji action dimension."""
83
+
84
+ action_dim: int = WUJI_ACTION_DIM
85
+
86
+ def __call__(self, data: dict) -> dict:
87
+ actions = np.asarray(data["actions"])
88
+ return {"actions": actions[:, : self.action_dim]}
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/checkpoints.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import concurrent.futures as futures
5
+ import dataclasses
6
+ import logging
7
+ from typing import Protocol
8
+
9
+ from etils import epath
10
+ import jax
11
+ import orbax.checkpoint as ocp
12
+ import orbax.checkpoint.future as future
13
+
14
+ from openpi.shared import array_typing as at
15
+ import openpi.shared.normalize as _normalize
16
+ import openpi.training.data_loader as _data_loader
17
+ import openpi.training.utils as training_utils
18
+
19
+
20
+ def initialize_checkpoint_dir(
21
+ checkpoint_dir: epath.Path | str, *, keep_period: int | None, overwrite: bool, resume: bool
22
+ ) -> tuple[ocp.CheckpointManager, bool]:
23
+ checkpoint_dir = epath.Path(checkpoint_dir).resolve()
24
+ resuming = False
25
+ if checkpoint_dir.exists():
26
+ if overwrite:
27
+ checkpoint_dir.rmtree()
28
+ checkpoint_dir.mkdir(parents=True, exist_ok=True)
29
+ logging.info(f"Wiped checkpoint directory {checkpoint_dir}")
30
+ elif resume:
31
+ resuming = True
32
+ else:
33
+ raise FileExistsError(
34
+ f"Checkpoint directory {checkpoint_dir} already exists. Use --overwrite or --resume "
35
+ "to indicate how to handle it."
36
+ )
37
+
38
+ checkpoint_dir.mkdir(parents=True, exist_ok=True)
39
+
40
+ mngr = ocp.CheckpointManager(
41
+ checkpoint_dir,
42
+ item_handlers={
43
+ "assets": CallbackHandler(),
44
+ "train_state": ocp.PyTreeCheckpointHandler(),
45
+ "params": ocp.PyTreeCheckpointHandler(),
46
+ },
47
+ options=ocp.CheckpointManagerOptions(
48
+ max_to_keep=1,
49
+ keep_period=keep_period,
50
+ create=False,
51
+ async_options=ocp.AsyncOptions(timeout_secs=7200),
52
+ ),
53
+ )
54
+
55
+ # Special case: the checkpoint directory exists and the user requests to resume training, but the training run did
56
+ # not get to the first checkpoint saved. In this case, we don't actually want the train script to try and restore a
57
+ # checkpoint, since it will fail.
58
+ if resuming and tuple(mngr.all_steps()) in [(), (0,)]:
59
+ logging.info("Checkpoint directory exists, but does not contain any checkpoints. Aborting resume.")
60
+ resuming = False
61
+
62
+ return mngr, resuming
63
+
64
+
65
+ def save_state(
66
+ checkpoint_manager: ocp.CheckpointManager,
67
+ state: training_utils.TrainState,
68
+ data_loader: _data_loader.DataLoader,
69
+ step: int,
70
+ ):
71
+ def save_assets(directory: epath.Path):
72
+ # Save the normalization stats.
73
+ data_config = data_loader.data_config()
74
+ norm_stats = data_config.norm_stats
75
+ if norm_stats is not None and data_config.asset_id is not None:
76
+ _normalize.save(directory / data_config.asset_id, norm_stats)
77
+
78
+ # Split params that can be used for inference into a separate item.
79
+ with at.disable_typechecking():
80
+ train_state, params = _split_params(state)
81
+ items = {
82
+ "assets": save_assets,
83
+ "train_state": train_state,
84
+ "params": {"params": params},
85
+ }
86
+ checkpoint_manager.save(step, items)
87
+
88
+
89
+ def restore_state(
90
+ checkpoint_manager: ocp.CheckpointManager,
91
+ state: training_utils.TrainState,
92
+ data_loader: _data_loader.DataLoader,
93
+ step: int | None = None,
94
+ ) -> training_utils.TrainState:
95
+ del data_loader
96
+
97
+ with at.disable_typechecking():
98
+ # Split params that can be used for inference into a separate item.
99
+ train_state, params = _split_params(state)
100
+ restored = checkpoint_manager.restore(
101
+ step,
102
+ items={
103
+ "train_state": train_state,
104
+ "params": {"params": params},
105
+ },
106
+ )
107
+ return _merge_params(restored["train_state"], restored["params"])
108
+
109
+
110
+ def load_norm_stats(assets_dir: epath.Path | str, asset_id: str) -> dict[str, _normalize.NormStats] | None:
111
+ norm_stats_dir = epath.Path(assets_dir) / asset_id
112
+ norm_stats = _normalize.load(norm_stats_dir)
113
+ logging.info(f"Loaded norm stats from {norm_stats_dir}")
114
+ return norm_stats
115
+
116
+
117
+ class Callback(Protocol):
118
+ def __call__(self, directory: epath.Path) -> None: ...
119
+
120
+
121
+ class CallbackHandler(ocp.AsyncCheckpointHandler):
122
+ """A CheckpointHandler for calling an arbitrary function asynchronously. Only for saving, not for restoring."""
123
+
124
+ def save(self, directory: epath.Path, args: CallbackSave):
125
+ if jax.process_index() == 0:
126
+ args.callback(directory)
127
+
128
+ async def async_save(self, directory: epath.Path, args: CallbackSave) -> list[futures.Future]:
129
+ return [future.CommitFutureAwaitingContractedSignals(asyncio.to_thread(self.save, directory, args))]
130
+
131
+ def restore(self, *args, **kwargs):
132
+ raise NotImplementedError("CallbackHandler does not support restore")
133
+
134
+
135
+ @ocp.args.register_with_handler(CallbackHandler, for_save=True)
136
+ @dataclasses.dataclass
137
+ class CallbackSave(ocp.args.CheckpointArgs):
138
+ callback: Callback
139
+
140
+
141
+ @ocp.args.register_with_handler(CallbackHandler, for_restore=True)
142
+ class CallbackRestore(ocp.args.CheckpointArgs): ...
143
+
144
+
145
+ def _split_params(state: training_utils.TrainState) -> tuple[training_utils.TrainState, at.Params]:
146
+ if state.ema_params is not None:
147
+ params = state.ema_params
148
+ train_state = dataclasses.replace(state, ema_params=None)
149
+ else:
150
+ params = state.params
151
+ train_state = dataclasses.replace(state, params={})
152
+ return train_state, params
153
+
154
+
155
+ def _merge_params(train_state: training_utils.TrainState, params: dict[str, at.Params]) -> training_utils.TrainState:
156
+ # Revert the logic inside `_split_params`. Assumes that existence of `params` means that EMA params were used during the split.
157
+ if train_state.params:
158
+ return dataclasses.replace(train_state, ema_params=params["params"])
159
+ return dataclasses.replace(train_state, params=params["params"])
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/config.py ADDED
@@ -0,0 +1,1026 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """See _CONFIGS for the list of available configs."""
2
+
3
+ import abc
4
+ from collections.abc import Sequence
5
+ import dataclasses
6
+ import difflib
7
+ import logging
8
+ import os
9
+ import pathlib
10
+ from typing import Any, Literal, Protocol, TypeAlias
11
+
12
+ import etils.epath as epath
13
+ import flax.nnx as nnx
14
+ from typing_extensions import override
15
+ import tyro
16
+
17
+ import openpi.models.model as _model
18
+ import openpi.models.pi0_config as pi0_config
19
+ import openpi.models.pi0_fast as pi0_fast
20
+ import openpi.models.tokenizer as _tokenizer
21
+ import openpi.policies.aloha_policy as aloha_policy
22
+ import openpi.policies.droid_policy as droid_policy
23
+ import openpi.policies.libero_policy as libero_policy
24
+ import openpi.policies.pika_bimanual_policy as pika_bimanual_policy
25
+ import openpi.policies.wuji_policy as wuji_policy
26
+ import openpi.shared.download as _download
27
+ import openpi.shared.nnx_utils as nnx_utils
28
+ import openpi.shared.normalize as _normalize
29
+ import openpi.training.droid_rlds_dataset as droid_rlds_dataset
30
+ import openpi.training.misc.polaris_config as polaris_config
31
+ import openpi.training.misc.roboarena_config as roboarena_config
32
+ import openpi.training.optimizer as _optimizer
33
+ import openpi.training.weight_loaders as weight_loaders
34
+ import openpi.transforms as _transforms
35
+
36
+ # RoboDojo normalization assets bundled with this adapter (openpi/assets/RoboDojo_assets).
37
+ _ROBODOJO_ASSETS_DIR = pathlib.Path(__file__).resolve().parents[3] / "assets" / "RoboDojo_assets"
38
+ # Norm stats for Tianji Marvin + Wuji Hand (written by compute_norm_stats).
39
+ _WUJI_ASSETS_DIR = pathlib.Path(__file__).resolve().parents[3] / "assets" / "Wuji_assets"
40
+
41
+ ModelType: TypeAlias = _model.ModelType
42
+ # Work around a tyro issue with using nnx.filterlib.Filter directly.
43
+ Filter: TypeAlias = nnx.filterlib.Filter
44
+
45
+
46
+ @dataclasses.dataclass(frozen=True)
47
+ class AssetsConfig:
48
+ """Determines the location of assets (e.g., norm stats) that will be used to set up the data pipeline.
49
+
50
+ These assets will be replicated inside the checkpoint under the `assets/asset_id` directory.
51
+
52
+ This can be used to load assets from a different checkpoint (e.g., base model checkpoint) or some other
53
+ centralized location. For example, to load the norm stats for the Trossen robot from the base model checkpoint
54
+ during fine-tuning, use:
55
+
56
+ ```
57
+ AssetsConfig(
58
+ assets_dir="gs://openpi-assets/checkpoints/pi0_base/assets",
59
+ asset_id="trossen",
60
+ )
61
+ ```
62
+ """
63
+
64
+ # Assets directory. If not provided, the config assets_dirs will be used. This is useful to load assets from
65
+ # a different checkpoint (e.g., base model checkpoint) or some other centralized location.
66
+ assets_dir: str | None = None
67
+
68
+ # Asset id. If not provided, the repo id will be used. This allows users to reference assets that describe
69
+ # different robot platforms.
70
+ asset_id: str | None = None
71
+
72
+
73
+ @dataclasses.dataclass(frozen=True)
74
+ class DataConfig:
75
+ # LeRobot repo id. If None, fake data will be created.
76
+ repo_id: str | None = None
77
+ # Optional physical root for a local LeRobot dataset. This avoids requiring
78
+ # the data to be placed below HF_LEROBOT_HOME/<repo_id>.
79
+ lerobot_root: str | None = None
80
+ # Optional subset of LeRobot episode indices, applied before sampling.
81
+ episode_indices: Sequence[int] | None = None
82
+ # Video decoder backend for LeRobot datasets. Forced to pyav by default because
83
+ # torchcodec is present in some environments but not fully functional at runtime.
84
+ video_backend: Literal["pyav", "torchcodec", "video_reader"] = "pyav"
85
+ # Directory within the assets directory containing the data assets.
86
+ asset_id: str | None = None
87
+ # Contains precomputed normalization stats. If None, normalization will not be performed.
88
+ norm_stats: dict[str, _transforms.NormStats] | None = None
89
+
90
+ # Used to adopt the inputs from a dataset specific format to a common format
91
+ # which is expected by the data transforms.
92
+ repack_transforms: _transforms.Group = dataclasses.field(default_factory=_transforms.Group)
93
+ # Data transforms, typically include robot specific transformations. Will be applied
94
+ # before the data is normalized. See `model.Observation` and `model.Actions` to learn about the
95
+ # normalized data.
96
+ data_transforms: _transforms.Group = dataclasses.field(default_factory=_transforms.Group)
97
+ # Model specific transforms. Will be applied after the data is normalized.
98
+ model_transforms: _transforms.Group = dataclasses.field(default_factory=_transforms.Group)
99
+ # If true, will use quantile normalization. Otherwise, normal z-score normalization will be used.
100
+ use_quantile_norm: bool = False
101
+
102
+ # Names of keys that will be used by the data loader to generate the action sequence. The length of the
103
+ # sequence is defined by the `action_horizon` field in the model config. This should be adjusted if your
104
+ # LeRobot dataset is using different keys to represent the action.
105
+ action_sequence_keys: Sequence[str] = ("actions",)
106
+
107
+ # If true, will use the LeRobot dataset task to define the prompt.
108
+ prompt_from_task: bool = False
109
+
110
+ # Only used for RLDS data loader (ie currently only used for DROID).
111
+ rlds_data_dir: str | None = None
112
+ # Action space for DROID dataset.
113
+ action_space: droid_rlds_dataset.DroidActionSpace | None = None
114
+ # List of datasets to sample from: name, version, weight, and optionally filter_dict_path
115
+ datasets: Sequence[droid_rlds_dataset.RLDSDataset] = ()
116
+
117
+
118
+ class GroupFactory(Protocol):
119
+ def __call__(self, model_config: _model.BaseModelConfig) -> _transforms.Group:
120
+ """Create a group."""
121
+
122
+
123
+ @dataclasses.dataclass(frozen=True)
124
+ class ModelTransformFactory(GroupFactory):
125
+ """Creates model transforms for standard pi0 models."""
126
+
127
+ # If provided, will determine the default prompt that be used by the model.
128
+ default_prompt: str | None = None
129
+
130
+ def __call__(self, model_config: _model.BaseModelConfig) -> _transforms.Group:
131
+ match model_config.model_type:
132
+ case _model.ModelType.PI0:
133
+ return _transforms.Group(
134
+ inputs=[
135
+ _transforms.InjectDefaultPrompt(self.default_prompt),
136
+ _transforms.ResizeImages(224, 224),
137
+ _transforms.TokenizePrompt(
138
+ _tokenizer.PaligemmaTokenizer(model_config.max_token_len),
139
+ ),
140
+ _transforms.PadStatesAndActions(model_config.action_dim),
141
+ ],
142
+ )
143
+ case _model.ModelType.PI05:
144
+ assert isinstance(model_config, pi0_config.Pi0Config)
145
+ return _transforms.Group(
146
+ inputs=[
147
+ _transforms.InjectDefaultPrompt(self.default_prompt),
148
+ _transforms.ResizeImages(224, 224),
149
+ _transforms.TokenizePrompt(
150
+ _tokenizer.PaligemmaTokenizer(model_config.max_token_len),
151
+ discrete_state_input=model_config.discrete_state_input,
152
+ ),
153
+ _transforms.PadStatesAndActions(model_config.action_dim),
154
+ ],
155
+ )
156
+ case _model.ModelType.PI0_FAST:
157
+ tokenizer_cls = (
158
+ _tokenizer.FASTTokenizer
159
+ if model_config.fast_model_tokenizer is None
160
+ else model_config.fast_model_tokenizer
161
+ )
162
+ tokenizer_kwargs = (
163
+ {} if model_config.fast_model_tokenizer_kwargs is None else model_config.fast_model_tokenizer_kwargs
164
+ )
165
+ return _transforms.Group(
166
+ inputs=[
167
+ _transforms.InjectDefaultPrompt(self.default_prompt),
168
+ _transforms.ResizeImages(224, 224),
169
+ _transforms.TokenizeFASTInputs(
170
+ tokenizer_cls(model_config.max_token_len, **tokenizer_kwargs),
171
+ ),
172
+ ],
173
+ outputs=[
174
+ _transforms.ExtractFASTActions(
175
+ tokenizer_cls(model_config.max_token_len, **tokenizer_kwargs),
176
+ action_horizon=model_config.action_horizon,
177
+ action_dim=model_config.action_dim,
178
+ )
179
+ ],
180
+ )
181
+
182
+
183
+ @dataclasses.dataclass(frozen=True)
184
+ class DataConfigFactory(abc.ABC):
185
+ # The LeRobot repo id.
186
+ repo_id: str = tyro.MISSING
187
+ # Determines how the assets will be loaded.
188
+ assets: AssetsConfig = dataclasses.field(default_factory=AssetsConfig)
189
+ # Base config that will be updated by the factory.
190
+ base_config: tyro.conf.Suppress[DataConfig | None] = None
191
+
192
+ @abc.abstractmethod
193
+ def create(self, assets_dirs: pathlib.Path, model_config: _model.BaseModelConfig) -> DataConfig:
194
+ """Create a data config."""
195
+
196
+ def create_base_config(self, assets_dirs: pathlib.Path, model_config: _model.BaseModelConfig) -> DataConfig:
197
+ repo_id = self.repo_id if self.repo_id is not tyro.MISSING else None
198
+ asset_id = self.assets.asset_id or repo_id
199
+ return dataclasses.replace(
200
+ self.base_config or DataConfig(),
201
+ repo_id=repo_id,
202
+ asset_id=asset_id,
203
+ norm_stats=self._load_norm_stats(epath.Path(self.assets.assets_dir or assets_dirs), asset_id),
204
+ use_quantile_norm=model_config.model_type != ModelType.PI0,
205
+ )
206
+
207
+ def _load_norm_stats(self, assets_dir: epath.Path, asset_id: str | None) -> dict[str, _transforms.NormStats] | None:
208
+ if asset_id is None:
209
+ return None
210
+ try:
211
+ data_assets_dir = str(assets_dir / asset_id)
212
+ norm_stats = _normalize.load(_download.maybe_download(data_assets_dir))
213
+ logging.info(f"Loaded norm stats from {data_assets_dir}")
214
+ return norm_stats
215
+ except FileNotFoundError:
216
+ logging.info(f"Norm stats not found in {data_assets_dir}, skipping.")
217
+ return None
218
+
219
+
220
+ @dataclasses.dataclass(frozen=True)
221
+ class FakeDataConfig(DataConfigFactory):
222
+ repo_id: str = "fake"
223
+
224
+ @override
225
+ def create(self, assets_dirs: pathlib.Path, model_config: _model.BaseModelConfig) -> DataConfig:
226
+ return DataConfig(repo_id=self.repo_id)
227
+
228
+
229
+ @dataclasses.dataclass(frozen=True)
230
+ class SimpleDataConfig(DataConfigFactory):
231
+ # Factory for the data transforms.
232
+ data_transforms: tyro.conf.Suppress[GroupFactory] = dataclasses.field(default_factory=GroupFactory)
233
+ # Factory for the model transforms.
234
+ model_transforms: tyro.conf.Suppress[GroupFactory] = dataclasses.field(default_factory=ModelTransformFactory)
235
+
236
+ @override
237
+ def create(self, assets_dirs: pathlib.Path, model_config: _model.BaseModelConfig) -> DataConfig:
238
+ return dataclasses.replace(
239
+ self.create_base_config(assets_dirs, model_config),
240
+ data_transforms=self.data_transforms(model_config),
241
+ model_transforms=self.model_transforms(model_config),
242
+ )
243
+
244
+
245
+ @dataclasses.dataclass(frozen=True)
246
+ class LeRobotAlohaDataConfig(DataConfigFactory):
247
+ # If true, will convert joint dimensions to deltas with respect to the current state before passing to the model.
248
+ # Gripper dimensions will remain in absolute values.
249
+ use_delta_joint_actions: bool = True
250
+ # If provided, will be injected into the input data if the "prompt" key is not present.
251
+ default_prompt: str | None = None
252
+ # If true, this will convert the joint and gripper values from the standard Aloha space to
253
+ # the space used by the pi internal runtime which was used to train the base model. People who
254
+ # use standard Aloha data should set this to true.
255
+ adapt_to_pi: bool = False
256
+
257
+ # Repack transforms.
258
+ repack_transforms: tyro.conf.Suppress[_transforms.Group] = dataclasses.field(
259
+ default=_transforms.Group(
260
+ inputs=[
261
+ _transforms.RepackTransform(
262
+ {
263
+ "images": {"cam_high": "observation.images.top"},
264
+ "state": "observation.state",
265
+ "actions": "action",
266
+ }
267
+ )
268
+ ]
269
+ )
270
+ )
271
+ # Action keys that will be used to read the action sequence from the dataset.
272
+ action_sequence_keys: Sequence[str] = ("action",)
273
+
274
+ @override
275
+ def create(self, assets_dirs: pathlib.Path, model_config: _model.BaseModelConfig) -> DataConfig:
276
+ data_transforms = _transforms.Group(
277
+ inputs=[aloha_policy.AlohaInputs(adapt_to_pi=self.adapt_to_pi)],
278
+ outputs=[aloha_policy.AlohaOutputs(adapt_to_pi=self.adapt_to_pi)],
279
+ )
280
+ if self.use_delta_joint_actions:
281
+ delta_action_mask = _transforms.make_bool_mask(6, -1, 6, -1)
282
+ data_transforms = data_transforms.push(
283
+ inputs=[_transforms.DeltaActions(delta_action_mask)],
284
+ outputs=[_transforms.AbsoluteActions(delta_action_mask)],
285
+ )
286
+
287
+ model_transforms = ModelTransformFactory(default_prompt=self.default_prompt)(model_config)
288
+
289
+ return dataclasses.replace(
290
+ self.create_base_config(assets_dirs, model_config),
291
+ repack_transforms=self.repack_transforms,
292
+ data_transforms=data_transforms,
293
+ model_transforms=model_transforms,
294
+ action_sequence_keys=self.action_sequence_keys,
295
+ )
296
+
297
+
298
+ @dataclasses.dataclass(frozen=True)
299
+ class LeRobotLiberoDataConfig(DataConfigFactory):
300
+ """
301
+ This config is used to configure transforms that are applied at various parts of the data pipeline.
302
+ For your own dataset, you can copy this class and modify the transforms to match your dataset based on the
303
+ comments below.
304
+ """
305
+
306
+ extra_delta_transform: bool = False
307
+
308
+ @override
309
+ def create(self, assets_dirs: pathlib.Path, model_config: _model.BaseModelConfig) -> DataConfig:
310
+ # The repack transform is *only* applied to the data coming from the dataset,
311
+ # and *not* during inference. We can use it to make inputs from the dataset look
312
+ # as close as possible to those coming from the inference environment (e.g. match the keys).
313
+ # Below, we match the keys in the dataset (which we defined in the data conversion script) to
314
+ # the keys we use in our inference pipeline (defined in the inference script for libero).
315
+ # For your own dataset, first figure out what keys your environment passes to the policy server
316
+ # and then modify the mappings below so your dataset's keys get matched to those target keys.
317
+ # The repack transform simply remaps key names here.
318
+ repack_transform = _transforms.Group(
319
+ inputs=[
320
+ _transforms.RepackTransform(
321
+ {
322
+ "observation/image": "image",
323
+ "observation/wrist_image": "wrist_image",
324
+ "observation/state": "state",
325
+ "actions": "actions",
326
+ "prompt": "prompt",
327
+ }
328
+ )
329
+ ]
330
+ )
331
+
332
+ # The data transforms are applied to the data coming from the dataset *and* during inference.
333
+ # Below, we define the transforms for data going into the model (``inputs``) and the transforms
334
+ # for data coming out of the model (``outputs``) (the latter is only used during inference).
335
+ # We defined these transforms in `libero_policy.py`. You can check the detailed comments there for
336
+ # how to modify the transforms to match your dataset. Once you created your own transforms, you can
337
+ # replace the transforms below with your own.
338
+ data_transforms = _transforms.Group(
339
+ inputs=[libero_policy.LiberoInputs(model_type=model_config.model_type)],
340
+ outputs=[libero_policy.LiberoOutputs()],
341
+ )
342
+
343
+ # One additional data transform: pi0 models are trained on delta actions (relative to the first
344
+ # state in each action chunk). IF your data has ``absolute`` actions (e.g. target joint angles)
345
+ # you can uncomment the following line to convert the actions to delta actions. The only exception
346
+ # is for the gripper actions which are always absolute.
347
+ # In the example below, we would apply the delta conversion to the first 6 actions (joints) and
348
+ # leave the 7th action (gripper) unchanged, i.e. absolute.
349
+ # In Libero, the raw actions in the dataset are already delta actions, so we *do not* need to
350
+ # apply a separate delta conversion (that's why it's commented out). Choose whether to apply this
351
+ # transform based on whether your dataset uses ``absolute`` or ``delta`` actions out of the box.
352
+
353
+ # LIBERO already represents actions as deltas, but we have some old Pi0 checkpoints that are trained with this
354
+ # extra delta transform.
355
+ if self.extra_delta_transform:
356
+ delta_action_mask = _transforms.make_bool_mask(6, -1)
357
+ data_transforms = data_transforms.push(
358
+ inputs=[_transforms.DeltaActions(delta_action_mask)],
359
+ outputs=[_transforms.AbsoluteActions(delta_action_mask)],
360
+ )
361
+
362
+ # Model transforms include things like tokenizing the prompt and action targets
363
+ # You do not need to change anything here for your own dataset.
364
+ model_transforms = ModelTransformFactory()(model_config)
365
+
366
+ # We return all data transforms for training and inference. No need to change anything here.
367
+ return dataclasses.replace(
368
+ self.create_base_config(assets_dirs, model_config),
369
+ repack_transforms=repack_transform,
370
+ data_transforms=data_transforms,
371
+ model_transforms=model_transforms,
372
+ )
373
+
374
+
375
+ @dataclasses.dataclass(frozen=True)
376
+ class LeRobotWujiDataConfig(DataConfigFactory):
377
+ """
378
+ Config for Tianji Marvin + dual Wuji Hand Gen1 (adapted from wuji-openpi).
379
+
380
+ Dataset features:
381
+ - observation.state: 54 dims (7 left arm + 20 left hand + 7 right arm + 20 right hand)
382
+ - action: 54 dims
383
+ - observation.images.cam_left_wrist / cam_right_wrist
384
+ - base camera: observation.images.stereo_right (default) or cam_high via base_image_key
385
+
386
+ Requires model.action_dim=54. Load pi05_base with PartialCheckpointWeightLoader.
387
+ """
388
+
389
+ extra_delta_transform: bool = False
390
+ # LeRobot key for the head / stereo base camera.
391
+ base_image_key: str = "observation.images.stereo_right"
392
+ action_sequence_keys: Sequence[str] = ("action",)
393
+
394
+ @override
395
+ def create(self, assets_dirs: pathlib.Path, model_config: _model.BaseModelConfig) -> DataConfig:
396
+ repack_transform = _transforms.Group(
397
+ inputs=[
398
+ _transforms.RepackTransform(
399
+ {
400
+ "observation/image": self.base_image_key,
401
+ "observation/left_wrist_image": "observation.images.cam_left_wrist",
402
+ "observation/right_wrist_image": "observation.images.cam_right_wrist",
403
+ "observation/state": "observation.state",
404
+ "actions": "action",
405
+ "prompt": "prompt",
406
+ }
407
+ )
408
+ ]
409
+ )
410
+
411
+ data_transforms = _transforms.Group(
412
+ inputs=[wuji_policy.WujiInputs(model_type=model_config.model_type)],
413
+ outputs=[wuji_policy.WujiOutputs(action_dim=model_config.action_dim)],
414
+ )
415
+
416
+ # Arms: delta; hands: absolute (same as wuji-openpi).
417
+ if self.extra_delta_transform:
418
+ delta_action_mask = _transforms.make_bool_mask(7, -20, 7, -20)
419
+ data_transforms = data_transforms.push(
420
+ inputs=[_transforms.DeltaActions(delta_action_mask)],
421
+ outputs=[_transforms.AbsoluteActions(delta_action_mask)],
422
+ )
423
+
424
+ model_transforms = ModelTransformFactory()(model_config)
425
+
426
+ return dataclasses.replace(
427
+ self.create_base_config(assets_dirs, model_config),
428
+ repack_transforms=repack_transform,
429
+ data_transforms=data_transforms,
430
+ model_transforms=model_transforms,
431
+ action_sequence_keys=self.action_sequence_keys,
432
+ )
433
+
434
+
435
+ @dataclasses.dataclass(frozen=True)
436
+ class LeRobotPikaBimanualDataConfig(DataConfigFactory):
437
+ """Local LeRobot configuration for two-fisheye, 14-D dual-arm Pika data.
438
+
439
+ The converter writes absolute next-state targets, therefore action deltas
440
+ deliberately remain disabled. ``PIKA_LEROBOT_ROOT`` points at the physical
441
+ local dataset root and can be overridden with ``local_dataset_root``.
442
+ """
443
+
444
+ local_dataset_root: str | None = None
445
+ episode_indices: Sequence[int] = tuple(range(50))
446
+ default_prompt: str = "Fold the T-shirt."
447
+ action_sequence_keys: Sequence[str] = ("action",)
448
+ # Relative mode removes the arbitrary Pika/Lighthouse world origin. State
449
+ # is anchored at the current left Pika and each action is a full local
450
+ # SE(3) transform from that arm's current pose to its future target.
451
+ relative_pose: bool = False
452
+
453
+ @override
454
+ def create(self, assets_dirs: pathlib.Path, model_config: _model.BaseModelConfig) -> DataConfig:
455
+ if model_config.action_dim != pika_bimanual_policy.PIKA_BIMANUAL_ACTION_DIM:
456
+ raise ValueError(
457
+ "Pika bimanual config requires model.action_dim="
458
+ f"{pika_bimanual_policy.PIKA_BIMANUAL_ACTION_DIM}, got {model_config.action_dim}."
459
+ )
460
+ dataset_root = self.local_dataset_root or os.environ.get("PIKA_LEROBOT_ROOT")
461
+ if not dataset_root:
462
+ raise ValueError(
463
+ "Set PIKA_LEROBOT_ROOT to the local converted LeRobot dataset, or set "
464
+ "data.local_dataset_root explicitly."
465
+ )
466
+
467
+ repack_transform = _transforms.Group(
468
+ inputs=[
469
+ _transforms.RepackTransform(
470
+ {
471
+ "observation/image": "observation.images.cam_left_wrist",
472
+ "observation/wrist_image": "observation.images.cam_right_wrist",
473
+ "observation/state": "observation.state",
474
+ "actions": "action",
475
+ "prompt": "prompt",
476
+ }
477
+ )
478
+ ]
479
+ )
480
+ data_transforms = _transforms.Group(
481
+ inputs=[
482
+ pika_bimanual_policy.PikaBimanualInputs(
483
+ model_type=model_config.model_type,
484
+ relative_pose=self.relative_pose,
485
+ )
486
+ ],
487
+ outputs=[pika_bimanual_policy.PikaBimanualOutputs()],
488
+ )
489
+
490
+ return dataclasses.replace(
491
+ self.create_base_config(assets_dirs, model_config),
492
+ lerobot_root=dataset_root,
493
+ episode_indices=self.episode_indices,
494
+ repack_transforms=repack_transform,
495
+ data_transforms=data_transforms,
496
+ model_transforms=ModelTransformFactory(default_prompt=self.default_prompt)(model_config),
497
+ action_sequence_keys=self.action_sequence_keys,
498
+ prompt_from_task=True,
499
+ )
500
+
501
+
502
+ @dataclasses.dataclass(frozen=True)
503
+ class RLDSDroidDataConfig(DataConfigFactory):
504
+ """
505
+ Config for training on DROID, using RLDS data format (for efficient training on larger datasets).
506
+ """
507
+
508
+ rlds_data_dir: str | None = None
509
+ action_space: droid_rlds_dataset.DroidActionSpace | None = None
510
+
511
+ # Filtering options. Can pass a path to a dictionary that maps episodes to timestep ranges
512
+ # to tuples denoting ranges of time steps to keep (start, end). Episodes are uniquely identified with
513
+ # f"{recording_folderpath}--{file_path}", both of which are present in the RLDS episode metadata.
514
+
515
+ # List of datasets to sample from: name, version, weight, and optionally filter_dict_path
516
+ datasets: Sequence[droid_rlds_dataset.RLDSDataset] = (
517
+ droid_rlds_dataset.RLDSDataset(
518
+ name="droid",
519
+ version="1.0.1",
520
+ weight=1.0,
521
+ filter_dict_path="gs://openpi-assets/droid/droid_sample_ranges_v1_0_1.json",
522
+ ),
523
+ )
524
+
525
+ @override
526
+ def create(self, assets_dirs: pathlib.Path, model_config: _model.BaseModelConfig) -> DataConfig:
527
+ repack_transform = _transforms.Group(
528
+ inputs=[
529
+ _transforms.RepackTransform(
530
+ {
531
+ "observation/exterior_image_1_left": "observation/image",
532
+ "observation/wrist_image_left": "observation/wrist_image",
533
+ "observation/joint_position": "observation/joint_position",
534
+ "observation/gripper_position": "observation/gripper_position",
535
+ "actions": "actions",
536
+ "prompt": "prompt",
537
+ }
538
+ )
539
+ ]
540
+ )
541
+
542
+ data_transforms = _transforms.Group(
543
+ inputs=[droid_policy.DroidInputs(model_type=model_config.model_type)],
544
+ outputs=[droid_policy.DroidOutputs()],
545
+ )
546
+
547
+ if self.action_space == droid_rlds_dataset.DroidActionSpace.JOINT_POSITION:
548
+ # Data loader returns absolute joint position actions -- convert to delta actions for training.
549
+ delta_action_mask = _transforms.make_bool_mask(7, -1)
550
+ data_transforms = data_transforms.push(
551
+ inputs=[_transforms.DeltaActions(delta_action_mask)],
552
+ outputs=[_transforms.AbsoluteActions(delta_action_mask)],
553
+ )
554
+
555
+ model_transforms = ModelTransformFactory()(model_config)
556
+
557
+ assert self.rlds_data_dir is not None, "Need to set rlds data dir for RLDS data loader."
558
+
559
+ return dataclasses.replace(
560
+ self.create_base_config(assets_dirs, model_config),
561
+ repack_transforms=repack_transform,
562
+ data_transforms=data_transforms,
563
+ model_transforms=model_transforms,
564
+ rlds_data_dir=self.rlds_data_dir,
565
+ action_space=self.action_space,
566
+ datasets=self.datasets,
567
+ )
568
+
569
+
570
+ @dataclasses.dataclass(frozen=True)
571
+ class LeRobotDROIDDataConfig(DataConfigFactory):
572
+ """
573
+ Example data config for custom DROID dataset in LeRobot format.
574
+ To convert your custom DROID dataset (<10s of hours) to LeRobot format, see examples/droid/convert_droid_data_to_lerobot.py
575
+ """
576
+
577
+ @override
578
+ def create(self, assets_dirs: pathlib.Path, model_config: _model.BaseModelConfig) -> DataConfig:
579
+ repack_transform = _transforms.Group(
580
+ inputs=[
581
+ _transforms.RepackTransform(
582
+ {
583
+ "observation/exterior_image_1_left": "exterior_image_1_left",
584
+ "observation/exterior_image_2_left": "exterior_image_2_left",
585
+ "observation/wrist_image_left": "wrist_image_left",
586
+ "observation/joint_position": "joint_position",
587
+ "observation/gripper_position": "gripper_position",
588
+ "actions": "actions",
589
+ "prompt": "prompt",
590
+ }
591
+ )
592
+ ]
593
+ )
594
+ # We assume joint *velocity* actions, so we should *not* apply an additional delta transform.
595
+ data_transforms = _transforms.Group(
596
+ inputs=[droid_policy.DroidInputs(model_type=model_config.model_type)],
597
+ outputs=[droid_policy.DroidOutputs()],
598
+ )
599
+ model_transforms = ModelTransformFactory()(model_config)
600
+
601
+ return dataclasses.replace(
602
+ self.create_base_config(assets_dirs, model_config),
603
+ repack_transforms=repack_transform,
604
+ data_transforms=data_transforms,
605
+ model_transforms=model_transforms,
606
+ )
607
+
608
+
609
+ @dataclasses.dataclass(frozen=True)
610
+ class TrainConfig:
611
+ # Name of the config. Must be unique. Will be used to reference this config.
612
+ name: tyro.conf.Suppress[str]
613
+ # Project name.
614
+ project_name: str = "openpi"
615
+ # Experiment name. Will be used to name the metadata and checkpoint directories.
616
+ exp_name: str = tyro.MISSING
617
+
618
+ # Defines the model config. Some attributes (action_dim, action_horizon, and max_token_len) are shared by all models
619
+ # -- see BaseModelConfig. Specific model implementations (e.g., Pi0Config) inherit from BaseModelConfig and may
620
+ # define additional attributes.
621
+ model: _model.BaseModelConfig = dataclasses.field(default_factory=pi0_config.Pi0Config)
622
+
623
+ # A weight loader can optionally load (possibly partial) weights from disk after the model is initialized.
624
+ weight_loader: weight_loaders.WeightLoader = dataclasses.field(default_factory=weight_loaders.NoOpWeightLoader)
625
+
626
+ # Optional path to a PyTorch checkpoint to load weights from.
627
+ pytorch_weight_path: str | None = None
628
+
629
+ # Precision for PyTorch training.
630
+ pytorch_training_precision: Literal["bfloat16", "float32"] = "bfloat16"
631
+
632
+ lr_schedule: _optimizer.LRScheduleConfig = dataclasses.field(default_factory=_optimizer.CosineDecaySchedule)
633
+ optimizer: _optimizer.OptimizerConfig = dataclasses.field(default_factory=_optimizer.AdamW)
634
+ ema_decay: float | None = 0.99
635
+
636
+ # Specifies which weights should be frozen.
637
+ freeze_filter: tyro.conf.Suppress[Filter] = dataclasses.field(default_factory=nnx.Nothing)
638
+
639
+ # Determines the data to be trained on.
640
+ data: DataConfigFactory = dataclasses.field(default_factory=FakeDataConfig)
641
+
642
+ # Base directory for config assets (e.g., norm stats).
643
+ assets_base_dir: str = "./assets"
644
+ # Base directory for checkpoints.
645
+ checkpoint_base_dir: str = "./checkpoints"
646
+ # Optional exact checkpoint directory. XPolicyLab train.sh uses this to
647
+ # keep policy checkpoints under policy/<name>/checkpoints/<6-tuple>.
648
+ checkpoint_dir_override: str | None = None
649
+
650
+ # Random seed that will be used by random generators during training.
651
+ seed: int = 42
652
+ # Global batch size.
653
+ batch_size: int = 32
654
+ # Number of workers to use for the data loader. Increasing this number will speed up data loading but
655
+ # will increase memory and CPU usage.
656
+ num_workers: int = 8
657
+ # Number of train steps (batches) to run.
658
+ num_train_steps: int = 30_000
659
+
660
+ # How often (in steps) to log training metrics.
661
+ log_interval: int = 100
662
+ # How often (in steps) to save checkpoints.
663
+ save_interval: int = 1000
664
+ # If set, any existing checkpoints matching step % keep_period == 0 will not be deleted.
665
+ keep_period: int | None = 5000
666
+
667
+ # If true, will overwrite the checkpoint directory if it already exists.
668
+ overwrite: bool = False
669
+ # If true, will resume training from the last checkpoint.
670
+ resume: bool = False
671
+
672
+ # If true, will enable wandb logging.
673
+ wandb_enabled: bool = True
674
+
675
+ # Used to pass metadata to the policy server.
676
+ policy_metadata: dict[str, Any] | None = None
677
+
678
+ # If the value is greater than 1, FSDP will be enabled and shard across number of specified devices; overall
679
+ # device memory will be reduced but training could potentially be slower.
680
+ # eg. if total device is 4 and fsdp devices is 2; then the model will shard to 2 devices and run
681
+ # data parallel between 2 groups of devices.
682
+ fsdp_devices: int = 1
683
+
684
+ @property
685
+ def assets_dirs(self) -> pathlib.Path:
686
+ """Get the assets directory for this config."""
687
+ return (pathlib.Path(self.assets_base_dir) / self.name).resolve()
688
+
689
+ @property
690
+ def checkpoint_dir(self) -> pathlib.Path:
691
+ """Get the checkpoint directory for this config."""
692
+ if not self.exp_name:
693
+ raise ValueError("--exp_name must be set")
694
+ if self.checkpoint_dir_override:
695
+ return pathlib.Path(self.checkpoint_dir_override).resolve()
696
+ return (pathlib.Path(self.checkpoint_base_dir) / self.name / self.exp_name).resolve()
697
+
698
+ @property
699
+ def trainable_filter(self) -> nnx.filterlib.Filter:
700
+ """Get the filter for the trainable parameters."""
701
+ return nnx.All(nnx.Param, nnx.Not(self.freeze_filter))
702
+
703
+ def __post_init__(self) -> None:
704
+ if self.resume and self.overwrite:
705
+ raise ValueError("Cannot resume and overwrite at the same time.")
706
+
707
+
708
+ # Use `get_config` if you need to get a config by name in your code.
709
+ _PIKA_BIMANUAL_LORA_MODEL = pi0_config.Pi0Config(
710
+ pi05=True,
711
+ action_dim=14,
712
+ action_horizon=16,
713
+ max_token_len=256,
714
+ # Train LoRA adapters in both the PaliGemma backbone and action expert.
715
+ paligemma_variant="gemma_2b_lora",
716
+ action_expert_variant="gemma_300m_lora",
717
+ )
718
+
719
+ _ALOHA_GARMENT_MODEL = pi0_config.Pi0Config(
720
+ pi05=True, paligemma_variant="gemma_2b_lora", action_expert_variant="gemma_300m_lora")
721
+ _ALOHA_GARMENT_ROOT = "/data2/wushuang/my_projects/Aloha2-CollectData-DeformableObject/policy_training"
722
+
723
+ def _aloha_garment_data(split: str) -> LeRobotAlohaDataConfig:
724
+ return LeRobotAlohaDataConfig(
725
+ repo_id=f"local/aloha_garment_{split}",
726
+ assets=AssetsConfig(asset_id="aloha_garment"),
727
+ base_config=DataConfig(lerobot_root=f"{_ALOHA_GARMENT_ROOT}/lerobot_{split}", prompt_from_task=True),
728
+ use_delta_joint_actions=False, adapt_to_pi=False,
729
+ repack_transforms=_transforms.Group(inputs=[_transforms.RepackTransform({
730
+ "images": {"cam_high": "observation.images.cam_high", "cam_left_wrist": "observation.images.cam_left_wrist", "cam_right_wrist": "observation.images.cam_right_wrist"},
731
+ "state": "observation.state", "actions": "action", "prompt": "prompt"})]),
732
+ )
733
+
734
+ _CONFIGS = [
735
+ TrainConfig(
736
+ name="pi05_aloha_garment_lora", model=_ALOHA_GARMENT_MODEL,
737
+ freeze_filter=nnx.Any(
738
+ _ALOHA_GARMENT_MODEL.get_freeze_filter(),
739
+ nnx_utils.PathRegex("PaliGemma/img/.*"),
740
+ ),
741
+ ema_decay=None,
742
+ data=_aloha_garment_data("train"),
743
+ weight_loader=weight_loaders.CheckpointWeightLoader("/data2/wushuang/.cache/openpi/openpi-assets/checkpoints/pi05_base/params"),
744
+ batch_size=2, num_workers=2, wandb_enabled=False,
745
+ ),
746
+ TrainConfig(
747
+ name="pi05_base_aloha_full_sim_arx-x5_seed_0",
748
+ model=pi0_config.Pi0Config(pi05=True),
749
+ data=LeRobotAlohaDataConfig(
750
+ repo_id="RoboDojo_sim_arx-x5_v30",
751
+ assets=AssetsConfig(
752
+ assets_dir=str(_ROBODOJO_ASSETS_DIR),
753
+ asset_id="arx_x5_sim",
754
+ ),
755
+ repack_transforms=_transforms.Group(
756
+ inputs=[
757
+ _transforms.RepackTransform(
758
+ {
759
+ "images": {
760
+ "cam_high": "observation.images.cam_high",
761
+ "cam_left_wrist": "observation.images.cam_left_wrist",
762
+ "cam_right_wrist": "observation.images.cam_right_wrist",
763
+ },
764
+ "state": "observation.state",
765
+ "actions": "action",
766
+ "prompt": "prompt",
767
+ }
768
+ )
769
+ ]
770
+ ),
771
+ base_config=DataConfig(
772
+ prompt_from_task=True, # Set to True for prompt by task_name
773
+ ),
774
+ ),
775
+ weight_loader=weight_loaders.CheckpointWeightLoader("gs://openpi-assets/checkpoints/pi05_base/params"),
776
+ seed=0,
777
+ batch_size=256,
778
+ fsdp_devices=2,
779
+ num_train_steps=60000,
780
+ ),
781
+ TrainConfig(
782
+ name="pi05_base_aloha_full_sim_arx-x5_seed_1",
783
+ model=pi0_config.Pi0Config(pi05=True),
784
+ data=LeRobotAlohaDataConfig(
785
+ repo_id="RoboDojo_sim_arx-x5_v30",
786
+ assets=AssetsConfig(
787
+ assets_dir=str(_ROBODOJO_ASSETS_DIR),
788
+ asset_id="arx_x5_sim",
789
+ ),
790
+ repack_transforms=_transforms.Group(
791
+ inputs=[
792
+ _transforms.RepackTransform(
793
+ {
794
+ "images": {
795
+ "cam_high": "observation.images.cam_high",
796
+ "cam_left_wrist": "observation.images.cam_left_wrist",
797
+ "cam_right_wrist": "observation.images.cam_right_wrist",
798
+ },
799
+ "state": "observation.state",
800
+ "actions": "action",
801
+ "prompt": "prompt",
802
+ }
803
+ )
804
+ ]
805
+ ),
806
+ base_config=DataConfig(
807
+ prompt_from_task=True, # Set to True for prompt by task_name
808
+ ),
809
+ ),
810
+ weight_loader=weight_loaders.CheckpointWeightLoader("gs://openpi-assets/checkpoints/pi05_base/params"),
811
+ seed=1,
812
+ batch_size=256,
813
+ fsdp_devices=2,
814
+ num_train_steps=60000,
815
+ ),
816
+ TrainConfig(
817
+ name="pi05_base_aloha_full_sim_arx-x5_seed_2",
818
+ model=pi0_config.Pi0Config(pi05=True),
819
+ data=LeRobotAlohaDataConfig(
820
+ repo_id="RoboDojo_sim_arx-x5_v30",
821
+ assets=AssetsConfig(
822
+ assets_dir=str(_ROBODOJO_ASSETS_DIR),
823
+ asset_id="arx_x5_sim",
824
+ ),
825
+ repack_transforms=_transforms.Group(
826
+ inputs=[
827
+ _transforms.RepackTransform(
828
+ {
829
+ "images": {
830
+ "cam_high": "observation.images.cam_high",
831
+ "cam_left_wrist": "observation.images.cam_left_wrist",
832
+ "cam_right_wrist": "observation.images.cam_right_wrist",
833
+ },
834
+ "state": "observation.state",
835
+ "actions": "action",
836
+ "prompt": "prompt",
837
+ }
838
+ )
839
+ ]
840
+ ),
841
+ base_config=DataConfig(
842
+ prompt_from_task=True, # Set to True for prompt by task_name
843
+ ),
844
+ ),
845
+ weight_loader=weight_loaders.CheckpointWeightLoader("gs://openpi-assets/checkpoints/pi05_base/params"),
846
+ seed=2,
847
+ batch_size=256,
848
+ fsdp_devices=2,
849
+ num_train_steps=60000,
850
+ ),
851
+ # Tianji Marvin + dual Wuji Hand Gen1 (54D). Set data.repo_id to your LeRobot dataset
852
+ # before compute_norm_stats / train. Skip RoboDojo process_data.py; use wuji mcap→LeRobot.
853
+ TrainConfig(
854
+ name="pi05_wuji_marvin_54d",
855
+ model=pi0_config.Pi0Config(pi05=True, action_dim=54, action_horizon=50, max_token_len=256),
856
+ data=LeRobotWujiDataConfig(
857
+ # Replace with your LeRobot repo id or local dataset id under HF_LEROBOT_HOME.
858
+ repo_id="tianji_marvin_wuji",
859
+ assets=AssetsConfig(
860
+ assets_dir=str(_WUJI_ASSETS_DIR),
861
+ asset_id="tianji_marvin_wuji",
862
+ ),
863
+ base_config=DataConfig(
864
+ prompt_from_task=True,
865
+ ),
866
+ extra_delta_transform=True,
867
+ # If your dataset uses cam_high instead of stereo_right, set:
868
+ # base_image_key="observation.images.cam_high",
869
+ ),
870
+ weight_loader=weight_loaders.PartialCheckpointWeightLoader(
871
+ "gs://openpi-assets/checkpoints/pi05_base/params"
872
+ ),
873
+ num_train_steps=30_000,
874
+ batch_size=64,
875
+ lr_schedule=_optimizer.CosineDecaySchedule(
876
+ warmup_steps=1_000,
877
+ peak_lr=5e-5,
878
+ decay_steps=30_000,
879
+ decay_lr=5e-6,
880
+ ),
881
+ ),
882
+ # Pika dual-arm T-shirt folding: 14-D absolute next-state targets at 10 Hz.
883
+ TrainConfig(
884
+ name="pi05_pika_bimanual_fisheye",
885
+ model=pi0_config.Pi0Config(pi05=True, action_dim=14, action_horizon=16, max_token_len=256),
886
+ data=LeRobotPikaBimanualDataConfig(
887
+ repo_id="pika/fold_cloth_0910_bimanual_fisheye",
888
+ # Must match compute_norm_stats.py, which writes below repo_id.
889
+ assets=AssetsConfig(asset_id="pika/fold_cloth_0910_bimanual_fisheye"),
890
+ ),
891
+ weight_loader=weight_loaders.PartialCheckpointWeightLoader(
892
+ "gs://openpi-assets/checkpoints/pi05_base/params"
893
+ ),
894
+ # The launchers set this to pika_manip/data/openpi_assets. Keeping the
895
+ # default permits a standalone OpenPI checkout to use ./assets instead.
896
+ assets_base_dir=os.environ.get("PIKA_OPENPI_ASSETS_BASE_DIR", "./assets"),
897
+ num_train_steps=30_000,
898
+ batch_size=64,
899
+ num_workers=4,
900
+ lr_schedule=_optimizer.CosineDecaySchedule(
901
+ warmup_steps=1_000,
902
+ peak_lr=5e-5,
903
+ decay_steps=30_000,
904
+ decay_lr=5e-6,
905
+ ),
906
+ ),
907
+ # Single-GPU-friendly LoRA alternative to the full Pika fine-tune above.
908
+ # It reuses the same local 50-episode train split and normalization stats.
909
+ TrainConfig(
910
+ name="pi05_pika_bimanual_fisheye_lora",
911
+ model=_PIKA_BIMANUAL_LORA_MODEL,
912
+ freeze_filter=nnx.Any(
913
+ _PIKA_BIMANUAL_LORA_MODEL.get_freeze_filter(),
914
+ # The ViT is not a LoRA module in OpenPI. Freeze it explicitly so
915
+ # this is adapter + Pika-projection tuning rather than an implicit
916
+ # full visual-backbone fine-tune.
917
+ nnx_utils.PathRegex("PaliGemma/img/.*"),
918
+ ),
919
+ data=LeRobotPikaBimanualDataConfig(
920
+ repo_id="pika/fold_cloth_0910_bimanual_fisheye",
921
+ # Reuse stats generated by prepare_pi05_pika_bimanual.sh for the
922
+ # full configuration; data semantics are identical.
923
+ assets=AssetsConfig(
924
+ assets_dir=os.path.join(
925
+ os.environ.get("PIKA_OPENPI_ASSETS_BASE_DIR", "./assets"),
926
+ "pi05_pika_bimanual_fisheye",
927
+ ),
928
+ asset_id="pika/fold_cloth_0910_bimanual_fisheye",
929
+ ),
930
+ ),
931
+ weight_loader=weight_loaders.PartialCheckpointWeightLoader(
932
+ "gs://openpi-assets/checkpoints/pi05_base/params"
933
+ ),
934
+ # EMA would update and retain a second copy of every frozen base weight
935
+ # on every step. It is prohibitively expensive for single-GPU LoRA and
936
+ # provides little value for this small, task-specific dataset.
937
+ ema_decay=None,
938
+ # Conservative starting point for one RTX 4090. The LoRA launcher
939
+ # defaults to this value but users may override BATCH_SIZE.
940
+ num_train_steps=30_000,
941
+ batch_size=4,
942
+ num_workers=4,
943
+ lr_schedule=_optimizer.CosineDecaySchedule(
944
+ warmup_steps=1_000,
945
+ peak_lr=5e-5,
946
+ decay_steps=30_000,
947
+ decay_lr=5e-6,
948
+ ),
949
+ ),
950
+ # Relative-pose Pika dual-arm configuration. The underlying LeRobot data
951
+ # deliberately remains lossless absolute pose data; the data transform
952
+ # converts it to a current-frame SE(3) representation before computing
953
+ # normalization statistics and before every training/inference call.
954
+ TrainConfig(
955
+ name="pi05_pika_bimanual_fisheye_relative",
956
+ model=pi0_config.Pi0Config(pi05=True, action_dim=14, action_horizon=16, max_token_len=256),
957
+ data=LeRobotPikaBimanualDataConfig(
958
+ repo_id="pika/fold_cloth_0910_bimanual_fisheye",
959
+ assets=AssetsConfig(asset_id="pika/fold_cloth_0910_bimanual_fisheye"),
960
+ relative_pose=True,
961
+ ),
962
+ weight_loader=weight_loaders.PartialCheckpointWeightLoader(
963
+ "gs://openpi-assets/checkpoints/pi05_base/params"
964
+ ),
965
+ assets_base_dir=os.environ.get("PIKA_OPENPI_ASSETS_BASE_DIR", "./assets"),
966
+ num_train_steps=30_000,
967
+ batch_size=64,
968
+ num_workers=4,
969
+ lr_schedule=_optimizer.CosineDecaySchedule(
970
+ warmup_steps=1_000,
971
+ peak_lr=5e-5,
972
+ decay_steps=30_000,
973
+ decay_lr=5e-6,
974
+ ),
975
+ ),
976
+ TrainConfig(
977
+ name="pi05_pika_bimanual_fisheye_relative_lora",
978
+ model=_PIKA_BIMANUAL_LORA_MODEL,
979
+ freeze_filter=nnx.Any(
980
+ _PIKA_BIMANUAL_LORA_MODEL.get_freeze_filter(),
981
+ nnx_utils.PathRegex("PaliGemma/img/.*"),
982
+ ),
983
+ data=LeRobotPikaBimanualDataConfig(
984
+ repo_id="pika/fold_cloth_0910_bimanual_fisheye",
985
+ assets=AssetsConfig(
986
+ assets_dir=os.path.join(
987
+ os.environ.get("PIKA_OPENPI_ASSETS_BASE_DIR", "./assets"),
988
+ "pi05_pika_bimanual_fisheye_relative",
989
+ ),
990
+ asset_id="pika/fold_cloth_0910_bimanual_fisheye",
991
+ ),
992
+ relative_pose=True,
993
+ ),
994
+ weight_loader=weight_loaders.PartialCheckpointWeightLoader(
995
+ "gs://openpi-assets/checkpoints/pi05_base/params"
996
+ ),
997
+ ema_decay=None,
998
+ num_train_steps=30_000,
999
+ batch_size=4,
1000
+ num_workers=4,
1001
+ lr_schedule=_optimizer.CosineDecaySchedule(
1002
+ warmup_steps=1_000,
1003
+ peak_lr=5e-5,
1004
+ decay_steps=30_000,
1005
+ decay_lr=5e-6,
1006
+ ),
1007
+ ),
1008
+ ]
1009
+
1010
+ if len({config.name for config in _CONFIGS}) != len(_CONFIGS):
1011
+ raise ValueError("Config names must be unique.")
1012
+ _CONFIGS_DICT = {config.name: config for config in _CONFIGS}
1013
+
1014
+
1015
+ def cli() -> TrainConfig:
1016
+ return tyro.extras.overridable_config_cli({k: (k, v) for k, v in _CONFIGS_DICT.items()})
1017
+
1018
+
1019
+ def get_config(config_name: str) -> TrainConfig:
1020
+ """Get a config by name."""
1021
+ if config_name not in _CONFIGS_DICT:
1022
+ closest = difflib.get_close_matches(config_name, _CONFIGS_DICT.keys(), n=1, cutoff=0.0)
1023
+ closest_str = f" Did you mean '{closest[0]}'? " if closest else ""
1024
+ raise ValueError(f"Config '{config_name}' not found.{closest_str}")
1025
+
1026
+ return _CONFIGS_DICT[config_name]
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/data_loader.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Iterator, Sequence
2
+ import logging
3
+ import multiprocessing
4
+ import os
5
+ import typing
6
+ from typing import Literal, Protocol, SupportsIndex, TypeVar
7
+
8
+ import jax
9
+ import jax.numpy as jnp
10
+ import numpy as np
11
+ import torch
12
+
13
+ try:
14
+ import lerobot.datasets.lerobot_dataset as lerobot_dataset
15
+ except ModuleNotFoundError as exc:
16
+ if exc.name != "lerobot.datasets":
17
+ raise
18
+ import lerobot.common.datasets.lerobot_dataset as lerobot_dataset
19
+
20
+ import openpi.models.model as _model
21
+ import openpi.training.config as _config
22
+ from openpi.training.droid_rlds_dataset import DroidRldsDataset
23
+ import openpi.transforms as _transforms
24
+
25
+ T_co = TypeVar("T_co", covariant=True)
26
+
27
+
28
+ class Dataset(Protocol[T_co]):
29
+ """Interface for a dataset with random access."""
30
+
31
+ def __getitem__(self, index: SupportsIndex) -> T_co:
32
+ raise NotImplementedError("Subclasses of Dataset should implement __getitem__.")
33
+
34
+ def __len__(self) -> int:
35
+ raise NotImplementedError("Subclasses of Dataset should implement __len__.")
36
+
37
+
38
+ class IterableDataset(Protocol[T_co]):
39
+ """Interface for an iterable dataset."""
40
+
41
+ def __iter__(self) -> Iterator[T_co]:
42
+ raise NotImplementedError("Subclasses of IterableDataset should implement __iter__.")
43
+
44
+ def __len__(self) -> int:
45
+ raise NotImplementedError("Subclasses of Dataset should implement __len__.")
46
+
47
+
48
+ class DataLoader(Protocol[T_co]):
49
+ """Interface for a data loader."""
50
+
51
+ def data_config(self) -> _config.DataConfig:
52
+ """Get the data config for this data loader."""
53
+ raise NotImplementedError("Subclasses of DataLoader should implement data_config.")
54
+
55
+ def __iter__(self) -> Iterator[T_co]:
56
+ raise NotImplementedError("Subclasses of DataLoader should implement __iter__.")
57
+
58
+
59
+ class TransformedDataset(Dataset[T_co]):
60
+ def __init__(self, dataset: Dataset, transforms: Sequence[_transforms.DataTransformFn]):
61
+ self._dataset = dataset
62
+ self._transform = _transforms.compose(transforms)
63
+
64
+ def __getitem__(self, index: SupportsIndex) -> T_co:
65
+ return self._transform(self._dataset[index])
66
+
67
+ def __len__(self) -> int:
68
+ return len(self._dataset)
69
+
70
+
71
+ class IterableTransformedDataset(IterableDataset[T_co]):
72
+ def __init__(
73
+ self,
74
+ dataset: IterableDataset,
75
+ transforms: Sequence[_transforms.DataTransformFn],
76
+ *,
77
+ is_batched: bool = False,
78
+ ):
79
+ self._dataset = dataset
80
+ self._transform = _transforms.compose(transforms)
81
+ self._is_batched = is_batched
82
+
83
+ def __iter__(self):
84
+ for sample in self._dataset:
85
+ if self._is_batched:
86
+ # Transforms are designed to be applied to individual samples. So we need to split the batch into
87
+ # individual samples and apply the transform to each sample individually.
88
+ batch_size = next(v.shape[0] for v in sample.values())
89
+
90
+ # Split batch into individual samples using tree_map
91
+ individual_samples = [jax.tree.map(lambda x: x[i], sample) for i in range(batch_size)] # noqa: B023
92
+
93
+ # Transform each sample
94
+ transformed = [self._transform(s) for s in individual_samples]
95
+
96
+ # Recombine batch with tree_map
97
+ yield jax.tree.map(lambda *x: np.stack(x, axis=0), *transformed)
98
+ else:
99
+ yield self._transform(sample)
100
+
101
+ def __len__(self) -> int:
102
+ return len(self._dataset)
103
+
104
+
105
+ class FakeDataset(Dataset):
106
+ def __init__(self, model_config: _model.BaseModelConfig, num_samples: int):
107
+ self._num_samples = num_samples
108
+ self._observation_spec, self._action_spec = model_config.inputs_spec()
109
+
110
+ def __getitem__(self, index: SupportsIndex) -> dict:
111
+ rng = jax.random.key(index.__index__())
112
+
113
+ def make_from_spec(spec: jax.ShapeDtypeStruct):
114
+ nonlocal rng
115
+ rng, data_rng = jax.random.split(rng)
116
+ # Remove the batch dimension.
117
+ shape = spec.shape[1:]
118
+ if spec.dtype == jnp.float32:
119
+ return jax.random.uniform(data_rng, shape=shape, minval=-1.0, maxval=1.0)
120
+ if spec.dtype == jnp.int32:
121
+ return jax.random.randint(data_rng, shape=shape, minval=0, maxval=2048)
122
+ return jnp.zeros(shape=shape, dtype=spec.dtype)
123
+
124
+ observation = jax.tree.map(make_from_spec, self._observation_spec)
125
+ action = jax.tree.map(make_from_spec, self._action_spec)
126
+
127
+ return {
128
+ **observation.to_dict(),
129
+ "actions": action,
130
+ }
131
+
132
+ def __len__(self) -> int:
133
+ return self._num_samples
134
+
135
+
136
+ def create_torch_dataset(
137
+ data_config: _config.DataConfig, action_horizon: int, model_config: _model.BaseModelConfig
138
+ ) -> Dataset:
139
+ """Create a dataset for training."""
140
+ repo_id = data_config.repo_id
141
+ if repo_id is None:
142
+ raise ValueError("Repo ID is not set. Cannot create dataset.")
143
+ if repo_id == "fake":
144
+ return FakeDataset(model_config, num_samples=1024)
145
+
146
+ dataset_meta = lerobot_dataset.LeRobotDatasetMetadata(repo_id, root=data_config.lerobot_root)
147
+ dataset = lerobot_dataset.LeRobotDataset(
148
+ data_config.repo_id,
149
+ root=data_config.lerobot_root,
150
+ episodes=list(data_config.episode_indices) if data_config.episode_indices is not None else None,
151
+ delta_timestamps={
152
+ key: [t / dataset_meta.fps for t in range(action_horizon)] for key in data_config.action_sequence_keys
153
+ },
154
+ video_backend=data_config.video_backend,
155
+ )
156
+
157
+ if data_config.prompt_from_task:
158
+ dataset = TransformedDataset(dataset, [_transforms.PromptFromLeRobotTask(dataset_meta.tasks)])
159
+
160
+ return dataset
161
+
162
+
163
+ def create_rlds_dataset(
164
+ data_config: _config.DataConfig,
165
+ action_horizon: int,
166
+ batch_size: int,
167
+ *,
168
+ shuffle: bool = False,
169
+ ) -> Dataset:
170
+ # At the moment, we only support DROID for RLDS datasets.
171
+ return DroidRldsDataset(
172
+ data_dir=data_config.rlds_data_dir,
173
+ batch_size=batch_size,
174
+ shuffle=shuffle,
175
+ action_chunk_size=action_horizon,
176
+ action_space=data_config.action_space,
177
+ datasets=data_config.datasets,
178
+ )
179
+
180
+
181
+ def transform_dataset(dataset: Dataset, data_config: _config.DataConfig, *, skip_norm_stats: bool = False) -> Dataset:
182
+ """Transform the dataset by applying the data transforms."""
183
+ norm_stats = {}
184
+ if data_config.repo_id != "fake" and not skip_norm_stats:
185
+ if data_config.norm_stats is None:
186
+ raise ValueError(
187
+ "Normalization stats not found. "
188
+ "Make sure to run `scripts/compute_norm_stats.py --config-name=<your-config>`."
189
+ )
190
+ norm_stats = data_config.norm_stats
191
+
192
+ return TransformedDataset(
193
+ dataset,
194
+ [
195
+ *data_config.repack_transforms.inputs,
196
+ *data_config.data_transforms.inputs,
197
+ _transforms.Normalize(norm_stats, use_quantiles=data_config.use_quantile_norm),
198
+ *data_config.model_transforms.inputs,
199
+ ],
200
+ )
201
+
202
+
203
+ def transform_iterable_dataset(
204
+ dataset: IterableDataset,
205
+ data_config: _config.DataConfig,
206
+ *,
207
+ skip_norm_stats: bool = False,
208
+ is_batched: bool = False,
209
+ ) -> IterableDataset:
210
+ """Transform the dataset by applying the data transforms."""
211
+ norm_stats = {}
212
+ if data_config.repo_id != "fake" and not skip_norm_stats:
213
+ if data_config.norm_stats is None:
214
+ raise ValueError(
215
+ "Normalization stats not found. "
216
+ "Make sure to run `scripts/compute_norm_stats.py --config-name=<your-config>`."
217
+ )
218
+ norm_stats = data_config.norm_stats
219
+
220
+ return IterableTransformedDataset(
221
+ dataset,
222
+ [
223
+ *data_config.repack_transforms.inputs,
224
+ *data_config.data_transforms.inputs,
225
+ _transforms.Normalize(norm_stats, use_quantiles=data_config.use_quantile_norm),
226
+ *data_config.model_transforms.inputs,
227
+ ],
228
+ is_batched=is_batched,
229
+ )
230
+
231
+
232
+ def create_data_loader(
233
+ config: _config.TrainConfig,
234
+ *,
235
+ sharding: jax.sharding.Sharding | None = None,
236
+ shuffle: bool = False,
237
+ num_batches: int | None = None,
238
+ skip_norm_stats: bool = False,
239
+ framework: Literal["jax", "pytorch"] = "jax",
240
+ ) -> DataLoader[tuple[_model.Observation, _model.Actions]]:
241
+ """Create a data loader for training.
242
+
243
+ Args:
244
+ config: The training configuration.
245
+ sharding: The sharding to use for the data loader (JAX only).
246
+ shuffle: Whether to shuffle the data.
247
+ num_batches: Determines the number of batches to return.
248
+ skip_norm_stats: Whether to skip data normalization.
249
+ framework: The framework to use ("jax" or "pytorch").
250
+ """
251
+ data_config = config.data.create(config.assets_dirs, config.model)
252
+ logging.info(f"data_config: {data_config}")
253
+
254
+ if data_config.rlds_data_dir is not None:
255
+ return create_rlds_data_loader(
256
+ data_config,
257
+ action_horizon=config.model.action_horizon,
258
+ batch_size=config.batch_size,
259
+ sharding=sharding,
260
+ shuffle=shuffle,
261
+ num_batches=num_batches,
262
+ skip_norm_stats=skip_norm_stats,
263
+ framework=framework,
264
+ )
265
+ return create_torch_data_loader(
266
+ data_config,
267
+ model_config=config.model,
268
+ action_horizon=config.model.action_horizon,
269
+ batch_size=config.batch_size,
270
+ sharding=sharding,
271
+ shuffle=shuffle,
272
+ num_batches=num_batches,
273
+ num_workers=config.num_workers,
274
+ seed=config.seed,
275
+ skip_norm_stats=skip_norm_stats,
276
+ framework=framework,
277
+ )
278
+
279
+
280
+ def create_torch_data_loader(
281
+ data_config: _config.DataConfig,
282
+ model_config: _model.BaseModelConfig,
283
+ action_horizon: int,
284
+ batch_size: int,
285
+ *,
286
+ sharding: jax.sharding.Sharding | None = None,
287
+ skip_norm_stats: bool = False,
288
+ shuffle: bool = False,
289
+ num_batches: int | None = None,
290
+ num_workers: int = 0,
291
+ seed: int = 0,
292
+ framework: str = "jax",
293
+ ) -> DataLoader[tuple[_model.Observation, _model.Actions]]:
294
+ """Create a data loader for training.
295
+
296
+ Args:
297
+ data_config: The data configuration.
298
+ action_horizon: The action horizon.
299
+ batch_size: The batch size.
300
+ sharding: The sharding to use for the data loader. If None, the data loader will
301
+ use a single device sharding.
302
+ skip_norm_stats: Whether to skip data normalization.
303
+ shuffle: Whether to shuffle the data.
304
+ num_batches: Determines the number of batches to return. If the number exceeds the
305
+ number of batches in the dataset, the data loader will loop over the dataset.
306
+ If not provided, will iterate over the dataset indefinitely.
307
+ num_workers: The number of worker processes to use. If zero, the data loader will
308
+ execute in the main process.
309
+ seed: The seed to use for shuffling the data.
310
+ """
311
+ dataset = create_torch_dataset(data_config, action_horizon, model_config)
312
+ dataset = transform_dataset(dataset, data_config, skip_norm_stats=skip_norm_stats)
313
+
314
+ # Use TorchDataLoader for both frameworks
315
+ # For PyTorch DDP, create DistributedSampler and divide batch size by world size
316
+ # For JAX, divide by process count
317
+ sampler = None
318
+ if framework == "pytorch":
319
+ if torch.distributed.is_initialized():
320
+ sampler = torch.utils.data.distributed.DistributedSampler(
321
+ dataset,
322
+ num_replicas=torch.distributed.get_world_size(),
323
+ rank=torch.distributed.get_rank(),
324
+ shuffle=shuffle,
325
+ drop_last=True,
326
+ )
327
+ local_batch_size = batch_size // torch.distributed.get_world_size()
328
+ else:
329
+ local_batch_size = batch_size
330
+ else:
331
+ local_batch_size = batch_size // jax.process_count()
332
+
333
+ logging.info(f"local_batch_size: {local_batch_size}")
334
+ data_loader = TorchDataLoader(
335
+ dataset,
336
+ local_batch_size=local_batch_size,
337
+ sharding=None if framework == "pytorch" else sharding,
338
+ shuffle=(sampler is None and shuffle), # Don't shuffle if using sampler
339
+ sampler=sampler,
340
+ num_batches=num_batches,
341
+ num_workers=num_workers,
342
+ seed=seed,
343
+ framework=framework,
344
+ )
345
+
346
+ return DataLoaderImpl(data_config, data_loader)
347
+
348
+
349
+ def create_rlds_data_loader(
350
+ data_config: _config.DataConfig,
351
+ action_horizon: int,
352
+ batch_size: int,
353
+ *,
354
+ sharding: jax.sharding.Sharding | None = None,
355
+ skip_norm_stats: bool = False,
356
+ shuffle: bool = False,
357
+ num_batches: int | None = None,
358
+ framework: str = "jax",
359
+ ) -> DataLoader[tuple[_model.Observation, _model.Actions]]:
360
+ """Create an RLDS data loader for training.
361
+
362
+ Note: This data loader requires some extra dependencies -- see examples/droid/README_train.md
363
+
364
+ Args:
365
+ data_config: The data configuration.
366
+ action_horizon: The action horizon.
367
+ batch_size: The batch size.
368
+ sharding: The sharding to use for the data loader. If None, the data loader will
369
+ use a single device sharding.
370
+ skip_norm_stats: Whether to skip data normalization.
371
+ shuffle: Whether to shuffle the data.
372
+ num_batches: Determines the number of batches to return. If the number exceeds the
373
+ number of batches in the dataset, the data loader will loop over the dataset.
374
+ If not provided, will iterate over the dataset indefinitely.
375
+ """
376
+ if framework == "pytorch":
377
+ raise NotImplementedError("PyTorch RLDS data loader is not supported yet")
378
+ dataset = create_rlds_dataset(data_config, action_horizon, batch_size, shuffle=shuffle)
379
+ dataset = transform_iterable_dataset(dataset, data_config, skip_norm_stats=skip_norm_stats, is_batched=True)
380
+
381
+ data_loader = RLDSDataLoader(
382
+ dataset,
383
+ sharding=sharding,
384
+ num_batches=num_batches,
385
+ )
386
+
387
+ return DataLoaderImpl(data_config, data_loader)
388
+
389
+
390
+ class TorchDataLoader:
391
+ """Torch data loader implementation."""
392
+
393
+ def __init__(
394
+ self,
395
+ dataset,
396
+ local_batch_size: int,
397
+ *,
398
+ sharding: jax.sharding.Sharding | None = None,
399
+ shuffle: bool = False,
400
+ sampler: torch.utils.data.Sampler | None = None,
401
+ num_batches: int | None = None,
402
+ num_workers: int = 0,
403
+ seed: int = 0,
404
+ framework: str = "jax",
405
+ ):
406
+ """Create a PyTorch data loader.
407
+
408
+ Args:
409
+ dataset: The dataset to load.
410
+ local_batch_size: The local batch size for each process.
411
+ sharding: The sharding to use for the data loader.
412
+ shuffle: Whether to shuffle the data.
413
+ num_batches: If provided, determines the number of returned batches. If the
414
+ number is larger than the number of batches in the dataset, the data loader
415
+ will loop over the dataset. If not provided, will iterate over the dataset
416
+ indefinitely.
417
+ num_workers: The number of worker processes to use. If zero, the data loader will
418
+ execute in the main process.
419
+ seed: The seed to use for shuffling the data.
420
+ """
421
+ if jax.process_count() > 1:
422
+ raise NotImplementedError("Data loading with multiple processes is not supported.")
423
+
424
+ if len(dataset) < local_batch_size:
425
+ raise ValueError(f"Local batch size ({local_batch_size}) is larger than the dataset size ({len(dataset)}).")
426
+
427
+ # Store sharding - None for PyTorch, JAX sharding for JAX
428
+ self._sharding = sharding
429
+ if sharding is None and framework == "jax":
430
+ # Use data parallel sharding by default for JAX only.
431
+ self._sharding = jax.sharding.NamedSharding(
432
+ jax.sharding.Mesh(jax.devices(), ("B",)),
433
+ jax.sharding.PartitionSpec("B"),
434
+ )
435
+ self._num_batches = num_batches
436
+
437
+ mp_context = None
438
+ if num_workers > 0:
439
+ mp_context = multiprocessing.get_context("spawn")
440
+
441
+ generator = torch.Generator()
442
+ generator.manual_seed(seed)
443
+ self._data_loader = torch.utils.data.DataLoader(
444
+ typing.cast(torch.utils.data.Dataset, dataset),
445
+ batch_size=local_batch_size,
446
+ shuffle=(sampler is None and shuffle), # Don't shuffle if using sampler
447
+ sampler=sampler,
448
+ num_workers=num_workers,
449
+ multiprocessing_context=mp_context,
450
+ persistent_workers=num_workers > 0,
451
+ collate_fn=_collate_fn,
452
+ worker_init_fn=_worker_init_fn,
453
+ drop_last=True,
454
+ generator=generator,
455
+ )
456
+
457
+ @property
458
+ def torch_loader(self) -> torch.utils.data.DataLoader:
459
+ return self._data_loader
460
+
461
+ def __iter__(self):
462
+ num_items = 0
463
+ while True:
464
+ data_iter = iter(self._data_loader)
465
+ while True:
466
+ if self._num_batches is not None and num_items >= self._num_batches:
467
+ return
468
+ try:
469
+ batch = next(data_iter)
470
+ except StopIteration:
471
+ break # We've exhausted the dataset. Create a new iterator and start over.
472
+ num_items += 1
473
+ # For JAX, convert to sharded arrays; for PyTorch, return torch tensors
474
+ if self._sharding is not None:
475
+ yield jax.tree.map(lambda x: jax.make_array_from_process_local_data(self._sharding, x), batch)
476
+ else:
477
+ yield jax.tree.map(torch.as_tensor, batch)
478
+
479
+
480
+ def _collate_fn(items):
481
+ """Collate the batch elements into batched numpy arrays."""
482
+ # Make sure to convert to numpy arrays before stacking since some of the incoming elements
483
+ # may be JAX arrays.
484
+ return jax.tree.map(lambda *xs: np.stack([np.asarray(x) for x in xs], axis=0), *items)
485
+
486
+
487
+ def _worker_init_fn(worker_id: int) -> None:
488
+ """Tell JAX inside the worker process not to preallocate the GPU memory."""
489
+ # NOTE: This is called after jax is imported inside the worker process. This
490
+ # means that this approach will not work for selecting the backend.
491
+ os.environ["XLA_PYTHON_CLIENT_PREALLOCATE"] = "false"
492
+ os.environ["XLA_PYTHON_CLIENT_ALLOCATOR"] = "platform"
493
+
494
+
495
+ class RLDSDataLoader:
496
+ """Shallow wrapper around the DROID data loader to make it compatible with openpi.
497
+
498
+ All batching already happens in the DROID dataset, so we don't need to do anything here.
499
+ """
500
+
501
+ def __init__(
502
+ self,
503
+ dataset: DroidRldsDataset,
504
+ *,
505
+ sharding: jax.sharding.Sharding | None = None,
506
+ num_batches: int | None = None,
507
+ ):
508
+ self._dataset = dataset
509
+ self._num_batches = num_batches
510
+
511
+ if jax.process_count() > 1:
512
+ raise NotImplementedError("Data loading with multiple processes is not supported.")
513
+
514
+ if sharding is None:
515
+ # Use data parallel sharding by default.
516
+ sharding = jax.sharding.NamedSharding(
517
+ jax.sharding.Mesh(jax.devices(), ("B",)),
518
+ jax.sharding.PartitionSpec("B"),
519
+ )
520
+
521
+ self._sharding = sharding
522
+ self._num_batches = num_batches
523
+
524
+ def __iter__(self):
525
+ num_items = 0
526
+ while True:
527
+ data_iter = iter(self._dataset)
528
+ while True:
529
+ if self._num_batches is not None and num_items >= self._num_batches:
530
+ return
531
+ try:
532
+ batch = next(data_iter)
533
+ except StopIteration:
534
+ break # We've exhausted the dataset. Create a new iterator and start over.
535
+ num_items += 1
536
+ yield jax.tree.map(lambda x: jax.make_array_from_process_local_data(self._sharding, x), batch)
537
+
538
+
539
+ class DataLoaderImpl(DataLoader):
540
+ def __init__(self, data_config: _config.DataConfig, data_loader: TorchDataLoader | RLDSDataLoader):
541
+ self._data_config = data_config
542
+ self._data_loader = data_loader
543
+
544
+ def data_config(self) -> _config.DataConfig:
545
+ return self._data_config
546
+
547
+ def __iter__(self):
548
+ for batch in self._data_loader:
549
+ yield _model.Observation.from_dict(batch), batch["actions"]
real_inference/source/XPolicyLab/policy/Pi_05/openpi/src/openpi/training/data_loader_test.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+
3
+ import jax
4
+
5
+ from openpi.models import pi0_config
6
+ from openpi.training import config as _config
7
+ from openpi.training import data_loader as _data_loader
8
+
9
+
10
+ def test_torch_data_loader():
11
+ config = pi0_config.Pi0Config(action_dim=24, action_horizon=50, max_token_len=48)
12
+ dataset = _data_loader.FakeDataset(config, 16)
13
+
14
+ loader = _data_loader.TorchDataLoader(
15
+ dataset,
16
+ local_batch_size=4,
17
+ num_batches=2,
18
+ )
19
+ batches = list(loader)
20
+
21
+ assert len(batches) == 2
22
+ for batch in batches:
23
+ assert all(x.shape[0] == 4 for x in jax.tree.leaves(batch))
24
+
25
+
26
+ def test_torch_data_loader_infinite():
27
+ config = pi0_config.Pi0Config(action_dim=24, action_horizon=50, max_token_len=48)
28
+ dataset = _data_loader.FakeDataset(config, 4)
29
+
30
+ loader = _data_loader.TorchDataLoader(dataset, local_batch_size=4)
31
+ data_iter = iter(loader)
32
+
33
+ for _ in range(10):
34
+ _ = next(data_iter)
35
+
36
+
37
+ def test_torch_data_loader_parallel():
38
+ config = pi0_config.Pi0Config(action_dim=24, action_horizon=50, max_token_len=48)
39
+ dataset = _data_loader.FakeDataset(config, 10)
40
+
41
+ loader = _data_loader.TorchDataLoader(dataset, local_batch_size=4, num_batches=2, num_workers=2)
42
+ batches = list(loader)
43
+
44
+ assert len(batches) == 2
45
+
46
+ for batch in batches:
47
+ assert all(x.shape[0] == 4 for x in jax.tree.leaves(batch))
48
+
49
+
50
+ def test_with_fake_dataset():
51
+ config = _config.get_config("debug")
52
+
53
+ loader = _data_loader.create_data_loader(config, skip_norm_stats=True, num_batches=2)
54
+ batches = list(loader)
55
+
56
+ assert len(batches) == 2
57
+
58
+ for batch in batches:
59
+ assert all(x.shape[0] == config.batch_size for x in jax.tree.leaves(batch))
60
+
61
+ for _, actions in batches:
62
+ assert actions.shape == (config.batch_size, config.model.action_horizon, config.model.action_dim)
63
+
64
+
65
+ def test_with_real_dataset():
66
+ config = _config.get_config("pi0_aloha_sim")
67
+ config = dataclasses.replace(config, batch_size=4)
68
+
69
+ loader = _data_loader.create_data_loader(
70
+ config,
71
+ # Skip since we may not have the data available.
72
+ skip_norm_stats=True,
73
+ num_batches=2,
74
+ shuffle=True,
75
+ )
76
+ # Make sure that we can get the data config.
77
+ assert loader.data_config().repo_id == config.data.repo_id
78
+
79
+ batches = list(loader)
80
+
81
+ assert len(batches) == 2
82
+
83
+ for _, actions in batches:
84
+ assert actions.shape == (config.batch_size, config.model.action_horizon, config.model.action_dim)