lsnu commited on
Commit
912c7e2
·
verified ·
1 Parent(s): e104169

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. .gitattributes +11 -0
  2. third_party/PointFlowMatch/.gitignore +10 -0
  3. third_party/PointFlowMatch/LICENSE +674 -0
  4. third_party/PointFlowMatch/README.md +79 -0
  5. third_party/PointFlowMatch/conf/collect_demos_train.yaml +12 -0
  6. third_party/PointFlowMatch/conf/collect_demos_valid.yaml +12 -0
  7. third_party/PointFlowMatch/conf/eval.yaml +20 -0
  8. third_party/PointFlowMatch/conf/model/flow_so3delta.yaml +29 -0
  9. third_party/PointFlowMatch/conf/model/flow_target.yaml +29 -0
  10. third_party/PointFlowMatch/conf/train.yaml +53 -0
  11. third_party/PointFlowMatch/conf/trainer_eval.yaml +5 -0
  12. third_party/PointFlowMatch/pfp/__init__.py +30 -0
  13. third_party/PointFlowMatch/pfp/__pycache__/__init__.cpython-310.pyc +0 -0
  14. third_party/PointFlowMatch/pfp/backbones/__pycache__/pointnet.cpython-310.pyc +0 -0
  15. third_party/PointFlowMatch/pfp/backbones/mlp_3dp.py +42 -0
  16. third_party/PointFlowMatch/pfp/backbones/pointmlp.py +503 -0
  17. third_party/PointFlowMatch/pfp/backbones/pointnet.py +237 -0
  18. third_party/PointFlowMatch/pfp/backbones/resnet_dp.py +33 -0
  19. third_party/PointFlowMatch/pfp/common/__pycache__/fm_utils.cpython-310.pyc +0 -0
  20. third_party/PointFlowMatch/pfp/common/__pycache__/o3d_utils.cpython-310.pyc +0 -0
  21. third_party/PointFlowMatch/pfp/common/__pycache__/se3_utils.cpython-310.pyc +0 -0
  22. third_party/PointFlowMatch/pfp/common/__pycache__/visualization.cpython-310.pyc +0 -0
  23. third_party/PointFlowMatch/pfp/common/fm_utils.py +17 -0
  24. third_party/PointFlowMatch/pfp/common/o3d_utils.py +37 -0
  25. third_party/PointFlowMatch/pfp/common/se3_utils.py +180 -0
  26. third_party/PointFlowMatch/pfp/common/visualization.py +178 -0
  27. third_party/PointFlowMatch/pfp/data/__pycache__/dataset_pcd.cpython-310.pyc +0 -0
  28. third_party/PointFlowMatch/pfp/data/__pycache__/replay_buffer.cpython-310.pyc +0 -0
  29. third_party/PointFlowMatch/pfp/data/dataset_images.py +61 -0
  30. third_party/PointFlowMatch/pfp/data/dataset_pcd.py +105 -0
  31. third_party/PointFlowMatch/pfp/data/replay_buffer.py +38 -0
  32. third_party/PointFlowMatch/pfp/envs/__pycache__/base_env.cpython-310.pyc +0 -0
  33. third_party/PointFlowMatch/pfp/envs/__pycache__/rlbench_env.cpython-310.pyc +0 -0
  34. third_party/PointFlowMatch/pfp/envs/__pycache__/rlbench_runner.cpython-310.pyc +0 -0
  35. third_party/PointFlowMatch/pfp/envs/base_env.py +23 -0
  36. third_party/PointFlowMatch/pfp/envs/rlbench_env.py +247 -0
  37. third_party/PointFlowMatch/pfp/envs/rlbench_runner.py +46 -0
  38. third_party/PointFlowMatch/pfp/policy/__pycache__/base_policy.cpython-310.pyc +0 -0
  39. third_party/PointFlowMatch/pfp/policy/__pycache__/fm_policy.cpython-310.pyc +0 -0
  40. third_party/PointFlowMatch/pfp/policy/base_policy.py +79 -0
  41. third_party/PointFlowMatch/pfp/policy/ddim_policy.py +237 -0
  42. third_party/PointFlowMatch/pfp/policy/fm_5p_policy.py +290 -0
  43. third_party/PointFlowMatch/pfp/policy/fm_policy.py +298 -0
  44. third_party/PointFlowMatch/pfp/policy/fm_se3_policy.py +270 -0
  45. third_party/PointFlowMatch/pfp/policy/fm_so3_policy.py +341 -0
  46. third_party/PointFlowMatch/pfp/policy/fm_so3delta_policy.py +332 -0
  47. third_party/PointFlowMatch/pfp/policy/fm_target_policy.py +326 -0
  48. third_party/PointFlowMatch/pyproject.toml +46 -0
  49. third_party/PointFlowMatch/sandbox/augmentation.py +62 -0
  50. third_party/PointFlowMatch/sandbox/learning_rate.py +27 -0
.gitattributes CHANGED
@@ -245,3 +245,14 @@ third_party/AnyBimanual/third_party/RLBench/rlbench/assets/chopping_board.ttm fi
245
  third_party/AnyBimanual/third_party/RLBench/rlbench/assets/door.ttm filter=lfs diff=lfs merge=lfs -text
246
  third_party/AnyBimanual/third_party/RLBench/rlbench/assets/carrot.ttm filter=lfs diff=lfs merge=lfs -text
247
  third_party/AnyBimanual/third_party/RLBench/rlbench/assets/banana.ttm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
245
  third_party/AnyBimanual/third_party/RLBench/rlbench/assets/door.ttm filter=lfs diff=lfs merge=lfs -text
246
  third_party/AnyBimanual/third_party/RLBench/rlbench/assets/carrot.ttm filter=lfs diff=lfs merge=lfs -text
247
  third_party/AnyBimanual/third_party/RLBench/rlbench/assets/banana.ttm filter=lfs diff=lfs merge=lfs -text
248
+ third_party/diffusion_policy/diffusion_policy/env/kitchen/relay_policy_learning/adept_models/kitchen/textures/marble1.png filter=lfs diff=lfs merge=lfs -text
249
+ third_party/diffusion_policy/diffusion_policy/env/kitchen/relay_policy_learning/adept_models/kitchen/textures/wood1.png filter=lfs diff=lfs merge=lfs -text
250
+ third_party/diffusion_policy/diffusion_policy/env/kitchen/relay_policy_learning/third_party/franka/franka_panda.png filter=lfs diff=lfs merge=lfs -text
251
+ third_party/diffusion_policy/diffusion_policy/env/kitchen/relay_policy_learning/third_party/franka/meshes/visual/link7.stl filter=lfs diff=lfs merge=lfs -text
252
+ third_party/diffusion_policy/diffusion_policy/env/kitchen/relay_policy_learning/third_party/franka/meshes/visual/link6.stl filter=lfs diff=lfs merge=lfs -text
253
+ third_party/diffusion_policy/diffusion_policy/env/kitchen/relay_policy_learning/third_party/franka/meshes/visual/link5.stl filter=lfs diff=lfs merge=lfs -text
254
+ third_party/diffusion_policy/diffusion_policy/env/kitchen/relay_policy_learning/third_party/franka/meshes/visual/link4.stl filter=lfs diff=lfs merge=lfs -text
255
+ third_party/diffusion_policy/diffusion_policy/env/kitchen/relay_policy_learning/third_party/franka/meshes/visual/link3.stl filter=lfs diff=lfs merge=lfs -text
256
+ third_party/diffusion_policy/diffusion_policy/env/kitchen/relay_policy_learning/third_party/franka/meshes/visual/link2.stl filter=lfs diff=lfs merge=lfs -text
257
+ third_party/diffusion_policy/diffusion_policy/env/kitchen/relay_policy_learning/third_party/franka/meshes/visual/hand.stl filter=lfs diff=lfs merge=lfs -text
258
+ third_party/diffusion_policy/diffusion_policy/env/kitchen/relay_policy_learning/third_party/franka/meshes/visual/link1.stl filter=lfs diff=lfs merge=lfs -text
third_party/PointFlowMatch/.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ **/__pycache__/**
2
+ **/outputs/**
3
+ **/multirun/**
4
+ **/wandb/**
5
+ **/ckpt/**
6
+ **/demos/**
7
+ **.html
8
+ **/toy_circle/results/**
9
+ *plot.png
10
+ *.svg
third_party/PointFlowMatch/LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
third_party/PointFlowMatch/README.md ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PointFlowMatch: Learning Robotic Manipulation Policies from Point Clouds with Conditional Flow Matching
2
+
3
+ Repository providing the source code for the paper "Learning Robotic Manipulation Policies from Point Clouds with Conditional Flow Matching", see the [project website](http://pointflowmatch.cs.uni-freiburg.de/). Please cite the paper as follows:
4
+
5
+ @article{chisari2024learning,
6
+ title={Learning Robotic Manipulation Policies from Point Clouds with Conditional Flow Matching},
7
+ shorttile={PointFlowMatch},
8
+ author={Chisari, Eugenio and Heppert, Nick and Argus, Max and Welschehold, Tim and Brox, Thomas and Valada, Abhinav},
9
+ journal={Conference on Robot Learning (CoRL)},
10
+ year={2024}
11
+ }
12
+
13
+ ## Installation
14
+
15
+ - Add env variables to your `.bashrc`
16
+
17
+ ```bash
18
+ export COPPELIASIM_ROOT=${HOME}/CoppeliaSim
19
+ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$COPPELIASIM_ROOT
20
+ export QT_QPA_PLATFORM_PLUGIN_PATH=$COPPELIASIM_ROOT
21
+ ```
22
+
23
+ - Install dependencies
24
+
25
+ ```bash
26
+ conda create --name pfp_env python=3.10
27
+ conda activate pfp_env
28
+ bash bash/install_deps.sh
29
+ bash bash/install_rlbench.sh
30
+
31
+ # Get diffusion_policy from my branch
32
+ cd ..
33
+ git clone git@github.com:chisarie/diffusion_policy.git && cd diffusion_policy && git checkout develop/eugenio
34
+ pip install -e ../diffusion_policy
35
+
36
+ # 3dp install
37
+ cd ..
38
+ git clone git@github.com:YanjieZe/3D-Diffusion-Policy.git && cd 3D-Diffusion-Policy
39
+ cd 3D-Diffusion-Policy && pip install -e . && cd ..
40
+
41
+ # If locally (doesnt work on Ubuntu18):
42
+ pip install rerun-sdk==0.15.1
43
+ ```
44
+
45
+ ## Pretrained Weights Download
46
+
47
+ Here you can find the pretrained checkpoints of our PointFlowMatch policies for different RLBench environments. Download and unzip them in the `ckpt` folder.
48
+
49
+ | unplug charger | close door | open box | open fridge | frame hanger | open oven | books on shelf | shoes out of box |
50
+ | ------------- | ------------- | ------------- | ------------- | ------------- | ------------- | ------------- | ------------- |
51
+ | [1717446544-didactic-woodpecker](http://pointflowmatch.cs.uni-freiburg.de/download/1717446544-didactic-woodpecker.zip) | [1717446607-uppish-grebe](http://pointflowmatch.cs.uni-freiburg.de/download/1717446607-uppish-grebe.zip) | [1717446558-qualified-finch](http://pointflowmatch.cs.uni-freiburg.de/download/1717446558-qualified-finch.zip) | [1717446565-astute-stingray](http://pointflowmatch.cs.uni-freiburg.de/download/1717446565-astute-stingray.zip) | [1717446708-analytic-cuckoo](http://pointflowmatch.cs.uni-freiburg.de/download/1717446708-analytic-cuckoo.zip) | [1717446706-natural-scallop](http://pointflowmatch.cs.uni-freiburg.de/download/1717446706-natural-scallop.zip) | [1717446594-astute-panda](http://pointflowmatch.cs.uni-freiburg.de/download/1717446594-astute-panda.zip) | [1717447341-indigo-quokka](http://pointflowmatch.cs.uni-freiburg.de/download/1717447341-indigo-quokka.zip) |
52
+
53
+ ## Evaluation
54
+
55
+ To reproduce the results from the paper, run:
56
+
57
+ ```bash
58
+ python scripts/evaluate.py log_wandb=True env_runner.env_config.vis=False policy.ckpt_name=<ckpt_name>
59
+ ```
60
+
61
+ Where `<ckpt_name>` is the folder name of the selected checkpoint. Each checkpoint will be automatically evaluated on the correct environment.
62
+
63
+ ## Training
64
+
65
+ To train your own policies instead of using the pretrained checkpoints, you first need to collect demonstrations:
66
+
67
+ ```bash
68
+ bash bash/collect_data.sh
69
+ ```
70
+
71
+ Then, you can train your own policies:
72
+
73
+ ```bash
74
+ python scripts/train.py log_wandb=True dataloader.num_workers=8 task_name=<task_name> +experiment=<experiment_name>
75
+ ```
76
+
77
+ Valid task names are all those supported by RLBench. In this work, we used the following tasks: `unplug_charger`, `close_door`, `open_box`, `open_fridge`, `take_frame_off_hanger`, `open_oven`, `put_books_on_bookshelf`, `take_shoes_out_of_box`.
78
+
79
+ Valid experiment names are the following, and they represent the different baselines we tested: `adaflow`, `diffusion_policy`, `dp3`, `pointflowmatch`, `pointflowmatch_images`, `pointflowmatch_ddim`, `pointflowmatch_so3`.
third_party/PointFlowMatch/conf/collect_demos_train.yaml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ mode: train
2
+ seed: 1234
3
+ num_episodes: 100
4
+ save_data: False
5
+
6
+
7
+ env_config:
8
+ task_name: take_lid_off_saucepan
9
+ voxel_size: 0.01
10
+ n_points: 5500
11
+ headless: True
12
+ vis: True
third_party/PointFlowMatch/conf/collect_demos_valid.yaml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ mode: valid
2
+ seed: 5678
3
+ num_episodes: 10
4
+ save_data: False
5
+
6
+
7
+ env_config:
8
+ task_name: open_fridge
9
+ voxel_size: 0.01
10
+ n_points: 5500
11
+ headless: True
12
+ vis: False
third_party/PointFlowMatch/conf/eval.yaml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ seed: 5678
2
+ log_wandb: False
3
+
4
+ env_runner:
5
+ num_episodes: 100
6
+ max_episode_length: 200
7
+ verbose: True
8
+ env_config:
9
+ voxel_size: 0.01
10
+ headless: True
11
+ vis: True
12
+
13
+
14
+ policy:
15
+ ckpt_name: 1717446544-didactic-woodpecker
16
+ ckpt_episode: ep1500 # latest, ep1500, ep1000
17
+ num_k_infer: 50
18
+ # Uncomment the following to override settings used during training
19
+ # flow_schedule: linear # linear | cosine | exp
20
+ # exp_scale: 4.0
third_party/PointFlowMatch/conf/model/flow_so3delta.yaml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ _target_: pfp.policy.fm_so3delta_policy.FMSO3DeltaPolicy
2
+ x_dim: ${x_dim}
3
+ y_dim: ${y_dim}
4
+ n_obs_steps: ${n_obs_steps}
5
+ n_pred_steps: ${n_pred_steps}
6
+ num_k_infer: 10
7
+ norm_pcd_center: [0.4, 0.0, 1.4]
8
+ augment_data: False
9
+ loss_type: l2 # l2 | l1
10
+ flow_schedule: exp # linear | cosine | exp
11
+ exp_scale: 4.0
12
+
13
+ obs_encoder: ${backbone}
14
+
15
+ diffusion_net:
16
+ _target_: diffusion_policy.model.diffusion.conditional_unet1d.ConditionalUnet1D
17
+ input_dim: ${y_dim}
18
+ # output_dim: 10
19
+ global_cond_dim: "${eval: '${x_dim} * ${n_obs_steps}'}"
20
+ diffusion_step_embed_dim: 256
21
+ down_dims: [256, 512, 1024]
22
+ kernel_size: 5
23
+ n_groups: 8
24
+ cond_predict_scale: True
25
+
26
+ loss_weights:
27
+ xyz: 10.0
28
+ rot6d: 10.0
29
+ grip: 1.0
third_party/PointFlowMatch/conf/model/flow_target.yaml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ _target_: pfp.policy.fm_target_policy.FMTargetPolicy
2
+ x_dim: ${x_dim}
3
+ y_dim: ${y_dim}
4
+ n_obs_steps: ${n_obs_steps}
5
+ n_pred_steps: ${n_pred_steps}
6
+ num_k_infer: 10
7
+ time_conditioning: False
8
+ norm_pcd_center: [0.4, 0.0, 1.4]
9
+ augment_data: False
10
+ loss_type: l2 # l2 | l1
11
+ flow_schedule: exp # linear | cosine | exp
12
+ exp_scale: 4.0
13
+
14
+ obs_encoder: ${backbone}
15
+
16
+ diffusion_net:
17
+ _target_: diffusion_policy.model.diffusion.conditional_unet1d.ConditionalUnet1D
18
+ input_dim: ${y_dim}
19
+ global_cond_dim: "${eval: '${x_dim} * ${n_obs_steps}'}"
20
+ diffusion_step_embed_dim: "${eval: '256 if ${model.time_conditioning} else 0'}"
21
+ down_dims: [256, 512, 1024]
22
+ kernel_size: 5
23
+ n_groups: 8
24
+ cond_predict_scale: True
25
+
26
+ loss_weights:
27
+ xyz: 10.0
28
+ rot6d: 10.0
29
+ grip: 1.0
third_party/PointFlowMatch/conf/train.yaml ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ seed: 1234
2
+ epochs: 1500
3
+ log_wandb: False
4
+ task_name: unplug_charger
5
+ obs_features_dim: 256
6
+ y_dim: 10 # (xyz, rot6d, g)
7
+ x_dim: "${eval: '${obs_features_dim} + ${y_dim}'}"
8
+ n_obs_steps: 2
9
+ n_pred_steps: 32 # Must be divisible by 4
10
+ use_ema: True
11
+ save_each_n_epochs: 500
12
+ obs_mode: pcd # pcd | rgb
13
+ run_name: null # set this to continue training from previous ckpt
14
+
15
+
16
+ # env_runner:
17
+ # num_episodes: 20
18
+ # max_episode_length: 200
19
+ # task_name: ${task_name}
20
+ # env_config:
21
+ # seed: 1996
22
+ # lowdim_obs: False
23
+
24
+
25
+ dataset:
26
+ n_obs_steps: ${n_obs_steps}
27
+ n_pred_steps: ${n_pred_steps}
28
+ subs_factor: 3
29
+ use_pc_color: False
30
+ n_points: 4096
31
+
32
+
33
+ dataloader:
34
+ batch_size: 128
35
+ num_workers: 0
36
+ # pin_memory: True
37
+
38
+
39
+ optimizer:
40
+ _target_: torch.optim.AdamW
41
+ lr: 3.0e-5
42
+ betas: [0.95, 0.999]
43
+ eps: 1.0e-8
44
+ weight_decay: 1.0e-6
45
+
46
+ lr_scheduler:
47
+ name: cosine # constant | cosine | linear | ...
48
+ num_warmup_steps: 5000
49
+
50
+
51
+ defaults:
52
+ - model: flow
53
+ - backbone: pointnet
third_party/PointFlowMatch/conf/trainer_eval.yaml ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ seed: 5678
2
+ log_wandb: False
3
+ run_name: 1716560279-subtle-kestrel # previous ckpt
4
+ model:
5
+ num_k_infer: 5
third_party/PointFlowMatch/pfp/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import random
3
+ import pathlib
4
+ import numpy as np
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass
9
+ class DATA_DIRS:
10
+ ROOT = pathlib.Path(__file__).parents[1] / "demos"
11
+ PFP = ROOT / "sim"
12
+ PFP_REAL = ROOT / "real"
13
+
14
+
15
+ @dataclass
16
+ class REPO_DIRS:
17
+ ROOT = pathlib.Path(__file__).parents[1]
18
+ CKPT = ROOT / "ckpt"
19
+ URDFS = ROOT / "urdfs"
20
+
21
+
22
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
23
+
24
+
25
+ def set_seeds(seed=0):
26
+ """Sets all seeds."""
27
+ torch.manual_seed(seed)
28
+ torch.cuda.manual_seed_all(seed)
29
+ np.random.seed(seed)
30
+ random.seed(seed)
third_party/PointFlowMatch/pfp/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.09 kB). View file
 
third_party/PointFlowMatch/pfp/backbones/__pycache__/pointnet.cpython-310.pyc ADDED
Binary file (7.6 kB). View file
 
third_party/PointFlowMatch/pfp/backbones/mlp_3dp.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from diffusion_policy_3d.model.vision.pointnet_extractor import (
4
+ PointNetEncoderXYZRGB,
5
+ PointNetEncoderXYZ,
6
+ )
7
+
8
+
9
+ class MLP3DP(nn.Module):
10
+ def __init__(self, in_channels: int, out_channels: int):
11
+ super().__init__()
12
+ if in_channels == 3:
13
+ self.backbone = PointNetEncoderXYZ(
14
+ in_channels=in_channels,
15
+ out_channels=out_channels,
16
+ use_layernorm=True,
17
+ final_norm="layernorm",
18
+ normal_channel=False,
19
+ )
20
+ elif in_channels == 6:
21
+ self.backbone = PointNetEncoderXYZRGB(
22
+ in_channels=in_channels,
23
+ out_channels=out_channels,
24
+ use_layernorm=True,
25
+ final_norm="layernorm",
26
+ normal_channel=False,
27
+ )
28
+ else:
29
+ raise ValueError("Invalid number of input channels for MLP3DP")
30
+ return
31
+
32
+ def forward(self, pcd: torch.Tensor, robot_state_obs: torch.Tensor = None) -> torch.Tensor:
33
+ B = pcd.shape[0]
34
+ # Flatten the batch and time dimensions
35
+ pcd = pcd.float().reshape(-1, *pcd.shape[2:])
36
+ robot_state_obs = robot_state_obs.float().reshape(-1, *robot_state_obs.shape[2:])
37
+ # Encode all point clouds (across time steps and batch size)
38
+ encoded_pcd = self.backbone(pcd)
39
+ nx = torch.cat([encoded_pcd, robot_state_obs], dim=1)
40
+ # Reshape back to the batch dimension. Now the features of each time step are concatenated
41
+ nx = nx.reshape(B, -1)
42
+ return nx
third_party/PointFlowMatch/pfp/backbones/pointmlp.py ADDED
@@ -0,0 +1,503 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Adapted from https://github.com/ma-xu/pointMLP-pytorch/blob/main/classification_ScanObjectNN/models/pointmlp.py """
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ from pytorch3d.ops import sample_farthest_points, knn_points
7
+
8
+
9
+ def get_activation(activation):
10
+ if activation.lower() == "gelu":
11
+ return nn.GELU()
12
+ elif activation.lower() == "rrelu":
13
+ return nn.RReLU(inplace=True)
14
+ elif activation.lower() == "selu":
15
+ return nn.SELU(inplace=True)
16
+ elif activation.lower() == "silu":
17
+ return nn.SiLU(inplace=True)
18
+ elif activation.lower() == "hardswish":
19
+ return nn.Hardswish(inplace=True)
20
+ elif activation.lower() == "leakyrelu":
21
+ return nn.LeakyReLU(inplace=True)
22
+ else:
23
+ return nn.ReLU(inplace=True)
24
+
25
+
26
+ def square_distance(src, dst):
27
+ """
28
+ Calculate Euclid distance between each two points.
29
+ src^T * dst = xn * xm + yn * ym + zn * zm;
30
+ sum(src^2, dim=-1) = xn*xn + yn*yn + zn*zn;
31
+ sum(dst^2, dim=-1) = xm*xm + ym*ym + zm*zm;
32
+ dist = (xn - xm)^2 + (yn - ym)^2 + (zn - zm)^2
33
+ = sum(src**2,dim=-1)+sum(dst**2,dim=-1)-2*src^T*dst
34
+ Input:
35
+ src: source points, [B, N, C]
36
+ dst: target points, [B, M, C]
37
+ Output:
38
+ dist: per-point square distance, [B, N, M]
39
+ """
40
+ B, N, _ = src.shape
41
+ _, M, _ = dst.shape
42
+ dist = -2 * torch.matmul(src, dst.permute(0, 2, 1))
43
+ dist += torch.sum(src**2, -1).view(B, N, 1)
44
+ dist += torch.sum(dst**2, -1).view(B, 1, M)
45
+ return dist
46
+
47
+
48
+ def index_points(points, idx):
49
+ """
50
+ Input:
51
+ points: input points data, [B, N, C]
52
+ idx: sample index data, [B, S]
53
+ Return:
54
+ new_points:, indexed points data, [B, S, C]
55
+ """
56
+ device = points.device
57
+ B = points.shape[0]
58
+ view_shape = list(idx.shape)
59
+ view_shape[1:] = [1] * (len(view_shape) - 1)
60
+ repeat_shape = list(idx.shape)
61
+ repeat_shape[0] = 1
62
+ batch_indices = (
63
+ torch.arange(B, dtype=torch.long).to(device).view(view_shape).repeat(repeat_shape)
64
+ )
65
+ new_points = points[batch_indices, idx, :]
66
+ return new_points
67
+
68
+
69
+ def farthest_point_sample(xyz, npoint):
70
+ """
71
+ Input:
72
+ xyz: pointcloud data, [B, N, 3]
73
+ npoint: number of samples
74
+ Return:
75
+ centroids: sampled pointcloud index, [B, npoint]
76
+ """
77
+ device = xyz.device
78
+ B, N, C = xyz.shape
79
+ centroids = torch.zeros(B, npoint, dtype=torch.long).to(device)
80
+ distance = torch.ones(B, N).to(device) * 1e10
81
+ farthest = torch.randint(0, N, (B,), dtype=torch.long).to(device)
82
+ batch_indices = torch.arange(B, dtype=torch.long).to(device)
83
+ for i in range(npoint):
84
+ centroids[:, i] = farthest
85
+ centroid = xyz[batch_indices, farthest, :].view(B, 1, 3)
86
+ dist = torch.sum((xyz - centroid) ** 2, -1)
87
+ distance = torch.min(distance, dist)
88
+ farthest = torch.max(distance, -1)[1]
89
+ return centroids
90
+
91
+
92
+ def query_ball_point(radius, nsample, xyz, new_xyz):
93
+ """
94
+ Input:
95
+ radius: local region radius
96
+ nsample: max sample number in local region
97
+ xyz: all points, [B, N, 3]
98
+ new_xyz: query points, [B, S, 3]
99
+ Return:
100
+ group_idx: grouped points index, [B, S, nsample]
101
+ """
102
+ device = xyz.device
103
+ B, N, C = xyz.shape
104
+ _, S, _ = new_xyz.shape
105
+ group_idx = torch.arange(N, dtype=torch.long).to(device).view(1, 1, N).repeat([B, S, 1])
106
+ sqrdists = square_distance(new_xyz, xyz)
107
+ group_idx[sqrdists > radius**2] = N
108
+ group_idx = group_idx.sort(dim=-1)[0][:, :, :nsample]
109
+ group_first = group_idx[:, :, 0].view(B, S, 1).repeat([1, 1, nsample])
110
+ mask = group_idx == N
111
+ group_idx[mask] = group_first[mask]
112
+ return group_idx
113
+
114
+
115
+ def knn_point(nsample, xyz, new_xyz):
116
+ """
117
+ Input:
118
+ nsample: max sample number in local region
119
+ xyz: all points, [B, N, C]
120
+ new_xyz: query points, [B, S, C]
121
+ Return:
122
+ group_idx: grouped points index, [B, S, nsample]
123
+ """
124
+ sqrdists = square_distance(new_xyz, xyz)
125
+ _, group_idx = torch.topk(sqrdists, nsample, dim=-1, largest=False, sorted=False)
126
+ return group_idx
127
+
128
+
129
+ class LocalGrouper(nn.Module):
130
+ def __init__(self, channel, groups, kneighbors, use_xyz=True, normalize="center", **kwargs):
131
+ """
132
+ Give xyz[b,p,3] and fea[b,p,d], return new_xyz[b,g,3] and new_fea[b,g,k,d]
133
+ :param groups: groups number
134
+ :param kneighbors: k-nerighbors
135
+ :param kwargs: others
136
+ """
137
+ super(LocalGrouper, self).__init__()
138
+ self.groups = groups
139
+ self.kneighbors = kneighbors
140
+ self.use_xyz = use_xyz
141
+ if normalize is not None:
142
+ self.normalize = normalize.lower()
143
+ else:
144
+ self.normalize = None
145
+ if self.normalize not in ["center", "anchor"]:
146
+ print(
147
+ "Unrecognized normalize parameter (self.normalize), set to None. Should be one of [center, anchor]."
148
+ )
149
+ self.normalize = None
150
+ if self.normalize is not None:
151
+ add_channel = 3 if self.use_xyz else 0
152
+ self.affine_alpha = nn.Parameter(torch.ones([1, 1, 1, channel + add_channel]))
153
+ self.affine_beta = nn.Parameter(torch.zeros([1, 1, 1, channel + add_channel]))
154
+
155
+ def forward(self, xyz, points):
156
+ B, N, C = xyz.shape
157
+ S = self.groups
158
+ xyz = xyz.contiguous() # xyz [btach, points, xyz]
159
+
160
+ # fps_idx = torch.multinomial(torch.linspace(0, N - 1, steps=N).repeat(B, 1).to(xyz.device), num_samples=self.groups, replacement=False).long()
161
+ # fps_idx = farthest_point_sample(xyz, self.groups).long()
162
+ # fps_idx = pointnet2_utils.furthest_point_sample(xyz, self.groups).long() # [B, npoint]
163
+ new_xyz, fps_idx = sample_farthest_points(xyz, K=self.groups)
164
+ # new_xyz = index_points(xyz, fps_idx) # [B, npoint, 3]
165
+ new_points = index_points(points, fps_idx) # [B, npoint, d]
166
+
167
+ # idx = knn_point(self.kneighbors, xyz, new_xyz)
168
+ _, idx, _ = knn_points(new_xyz, xyz, K=self.kneighbors, return_nn=False)
169
+ # idx = query_ball_point(radius, nsample, xyz, new_xyz)
170
+ grouped_points = index_points(points, idx) # [B, npoint, k, d]
171
+ if self.use_xyz:
172
+ grouped_xyz = index_points(xyz, idx) # [B, npoint, k, 3]
173
+ grouped_points = torch.cat([grouped_points, grouped_xyz], dim=-1) # [B, npoint, k, d+3]
174
+ if self.normalize is not None:
175
+ if self.normalize == "center":
176
+ mean = torch.mean(grouped_points, dim=2, keepdim=True)
177
+ if self.normalize == "anchor":
178
+ mean = torch.cat([new_points, new_xyz], dim=-1) if self.use_xyz else new_points
179
+ mean = mean.unsqueeze(dim=-2) # [B, npoint, 1, d+3]
180
+ std = (
181
+ torch.std((grouped_points - mean).reshape(B, -1), dim=-1, keepdim=True)
182
+ .unsqueeze(dim=-1)
183
+ .unsqueeze(dim=-1)
184
+ )
185
+ grouped_points = (grouped_points - mean) / (std + 1e-5)
186
+ grouped_points = self.affine_alpha * grouped_points + self.affine_beta
187
+
188
+ new_points = torch.cat(
189
+ [grouped_points, new_points.view(B, S, 1, -1).repeat(1, 1, self.kneighbors, 1)], dim=-1
190
+ )
191
+ return new_xyz, new_points
192
+
193
+
194
+ class ConvBNReLU1D(nn.Module):
195
+ def __init__(self, in_channels, out_channels, kernel_size=1, bias=True, activation="relu"):
196
+ super(ConvBNReLU1D, self).__init__()
197
+ self.act = get_activation(activation)
198
+ self.net = nn.Sequential(
199
+ nn.Conv1d(
200
+ in_channels=in_channels,
201
+ out_channels=out_channels,
202
+ kernel_size=kernel_size,
203
+ bias=bias,
204
+ ),
205
+ nn.BatchNorm1d(out_channels),
206
+ self.act,
207
+ )
208
+
209
+ def forward(self, x):
210
+ return self.net(x)
211
+
212
+
213
+ class ConvBNReLURes1D(nn.Module):
214
+ def __init__(
215
+ self, channel, kernel_size=1, groups=1, res_expansion=1.0, bias=True, activation="relu"
216
+ ):
217
+ super(ConvBNReLURes1D, self).__init__()
218
+ self.act = get_activation(activation)
219
+ self.net1 = nn.Sequential(
220
+ nn.Conv1d(
221
+ in_channels=channel,
222
+ out_channels=int(channel * res_expansion),
223
+ kernel_size=kernel_size,
224
+ groups=groups,
225
+ bias=bias,
226
+ ),
227
+ nn.BatchNorm1d(int(channel * res_expansion)),
228
+ self.act,
229
+ )
230
+ if groups > 1:
231
+ self.net2 = nn.Sequential(
232
+ nn.Conv1d(
233
+ in_channels=int(channel * res_expansion),
234
+ out_channels=channel,
235
+ kernel_size=kernel_size,
236
+ groups=groups,
237
+ bias=bias,
238
+ ),
239
+ nn.BatchNorm1d(channel),
240
+ self.act,
241
+ nn.Conv1d(
242
+ in_channels=channel, out_channels=channel, kernel_size=kernel_size, bias=bias
243
+ ),
244
+ nn.BatchNorm1d(channel),
245
+ )
246
+ else:
247
+ self.net2 = nn.Sequential(
248
+ nn.Conv1d(
249
+ in_channels=int(channel * res_expansion),
250
+ out_channels=channel,
251
+ kernel_size=kernel_size,
252
+ bias=bias,
253
+ ),
254
+ nn.BatchNorm1d(channel),
255
+ )
256
+
257
+ def forward(self, x):
258
+ return self.act(self.net2(self.net1(x)) + x)
259
+
260
+
261
+ class PreExtraction(nn.Module):
262
+ def __init__(
263
+ self,
264
+ channels,
265
+ out_channels,
266
+ blocks=1,
267
+ groups=1,
268
+ res_expansion=1,
269
+ bias=True,
270
+ activation="relu",
271
+ use_xyz=True,
272
+ ):
273
+ """
274
+ input: [b,g,k,d]: output:[b,d,g]
275
+ :param channels:
276
+ :param blocks:
277
+ """
278
+ super(PreExtraction, self).__init__()
279
+ in_channels = 3 + 2 * channels if use_xyz else 2 * channels
280
+ self.transfer = ConvBNReLU1D(in_channels, out_channels, bias=bias, activation=activation)
281
+ operation = []
282
+ for _ in range(blocks):
283
+ operation.append(
284
+ ConvBNReLURes1D(
285
+ out_channels,
286
+ groups=groups,
287
+ res_expansion=res_expansion,
288
+ bias=bias,
289
+ activation=activation,
290
+ )
291
+ )
292
+ self.operation = nn.Sequential(*operation)
293
+
294
+ def forward(self, x):
295
+ b, n, s, d = x.size() # torch.Size([32, 512, 32, 6])
296
+ x = x.permute(0, 1, 3, 2)
297
+ x = x.reshape(-1, d, s)
298
+ x = self.transfer(x)
299
+ batch_size, _, _ = x.size()
300
+ x = self.operation(x) # [b, d, k]
301
+ x = F.adaptive_max_pool1d(x, 1).view(batch_size, -1)
302
+ x = x.reshape(b, n, -1).permute(0, 2, 1)
303
+ return x
304
+
305
+
306
+ class PosExtraction(nn.Module):
307
+ def __init__(self, channels, blocks=1, groups=1, res_expansion=1, bias=True, activation="relu"):
308
+ """
309
+ input[b,d,g]; output[b,d,g]
310
+ :param channels:
311
+ :param blocks:
312
+ """
313
+ super(PosExtraction, self).__init__()
314
+ operation = []
315
+ for _ in range(blocks):
316
+ operation.append(
317
+ ConvBNReLURes1D(
318
+ channels,
319
+ groups=groups,
320
+ res_expansion=res_expansion,
321
+ bias=bias,
322
+ activation=activation,
323
+ )
324
+ )
325
+ self.operation = nn.Sequential(*operation)
326
+
327
+ def forward(self, x): # [b, d, g]
328
+ return self.operation(x)
329
+
330
+
331
+ class Model(nn.Module):
332
+ def __init__(
333
+ self,
334
+ points=1024,
335
+ input_channels=3,
336
+ embed_dim=64,
337
+ groups=1,
338
+ res_expansion=1.0,
339
+ activation="relu",
340
+ bias=True,
341
+ use_xyz=True,
342
+ normalize="center",
343
+ dim_expansion=[2, 2, 2, 2],
344
+ pre_blocks=[2, 2, 2, 2],
345
+ pos_blocks=[2, 2, 2, 2],
346
+ k_neighbors=[32, 32, 32, 32],
347
+ reducers=[2, 2, 2, 2],
348
+ **kwargs,
349
+ ):
350
+ super(Model, self).__init__()
351
+ self.stages = len(pre_blocks)
352
+ self.points = points
353
+ self.embedding = ConvBNReLU1D(input_channels, embed_dim, bias=bias, activation=activation)
354
+ assert (
355
+ len(pre_blocks)
356
+ == len(k_neighbors)
357
+ == len(reducers)
358
+ == len(pos_blocks)
359
+ == len(dim_expansion)
360
+ ), "Please check stage number consistent for pre_blocks, pos_blocks k_neighbors, reducers."
361
+ self.local_grouper_list = nn.ModuleList()
362
+ self.pre_blocks_list = nn.ModuleList()
363
+ self.pos_blocks_list = nn.ModuleList()
364
+ last_channel = embed_dim
365
+ anchor_points = self.points
366
+ for i in range(len(pre_blocks)):
367
+ out_channel = last_channel * dim_expansion[i]
368
+ pre_block_num = pre_blocks[i]
369
+ pos_block_num = pos_blocks[i]
370
+ kneighbor = k_neighbors[i]
371
+ reduce = reducers[i]
372
+ anchor_points = anchor_points // reduce
373
+ # append local_grouper_list
374
+ local_grouper = LocalGrouper(
375
+ last_channel, anchor_points, kneighbor, use_xyz, normalize
376
+ ) # [b,g,k,d]
377
+ self.local_grouper_list.append(local_grouper)
378
+ # append pre_block_list
379
+ pre_block_module = PreExtraction(
380
+ last_channel,
381
+ out_channel,
382
+ pre_block_num,
383
+ groups=groups,
384
+ res_expansion=res_expansion,
385
+ bias=bias,
386
+ activation=activation,
387
+ use_xyz=use_xyz,
388
+ )
389
+ self.pre_blocks_list.append(pre_block_module)
390
+ # append pos_block_list
391
+ pos_block_module = PosExtraction(
392
+ out_channel,
393
+ pos_block_num,
394
+ groups=groups,
395
+ res_expansion=res_expansion,
396
+ bias=bias,
397
+ activation=activation,
398
+ )
399
+ self.pos_blocks_list.append(pos_block_module)
400
+
401
+ last_channel = out_channel
402
+
403
+ self.act = get_activation(activation)
404
+ return
405
+
406
+ def forward(self, x):
407
+ xyz = x.permute(0, 2, 1)
408
+ batch_size, _, _ = x.size()
409
+ x = self.embedding(x) # B,D,N
410
+ for i in range(self.stages):
411
+ # Give xyz[b, p, 3] and fea[b, p, d], return new_xyz[b, g, 3] and new_fea[b, g, k, d]
412
+ xyz, x = self.local_grouper_list[i](xyz, x.permute(0, 2, 1)) # [b,g,3] [b,g,k,d]
413
+ x = self.pre_blocks_list[i](x) # [b,d,g]
414
+ x = self.pos_blocks_list[i](x) # [b,d,g]
415
+
416
+ x = F.adaptive_max_pool1d(x, 1).squeeze(dim=-1)
417
+ return x
418
+
419
+
420
+ class PointMLP(Model):
421
+ def __init__(self, points: int, input_channels: int, embed_dim: int, **kwargs):
422
+ super().__init__()
423
+ assert input_channels == 3 or input_channels == 6, "Input channels must be 3 or 6"
424
+ self.backbone = Model(
425
+ points=points,
426
+ input_channels=input_channels,
427
+ embed_dim=embed_dim // 16,
428
+ groups=1,
429
+ res_expansion=1.0,
430
+ activation="relu",
431
+ bias=False,
432
+ use_xyz=False,
433
+ normalize="anchor",
434
+ dim_expansion=[2, 2, 2, 2],
435
+ pre_blocks=[2, 2, 2, 2],
436
+ pos_blocks=[2, 2, 2, 2],
437
+ k_neighbors=[24, 24, 24, 24],
438
+ reducers=[2, 2, 2, 2],
439
+ **kwargs,
440
+ )
441
+ return
442
+
443
+ def forward(self, pcd: torch.Tensor, robot_state_obs: torch.Tensor = None) -> torch.Tensor:
444
+ B = pcd.shape[0]
445
+ # Flatten the batch and time dimensions
446
+ pcd = pcd.float().reshape(-1, *pcd.shape[2:])
447
+ robot_state_obs = robot_state_obs.float().reshape(-1, *robot_state_obs.shape[2:])
448
+ # Permute [B, P, 3] -> [B, 3, P]
449
+ pcd = pcd.permute(0, 2, 1)
450
+ # Encode all point clouds (across time steps and batch size)
451
+ encoded_pcd = self.backbone(pcd)
452
+ nx = torch.cat([encoded_pcd, robot_state_obs], dim=1)
453
+ # Reshape back to the batch dimension. Now the features of each time step are concatenated
454
+ nx = nx.reshape(B, -1)
455
+ return nx
456
+
457
+
458
+ class PointMLPElite(nn.Module):
459
+ def __init__(self, points: int, input_channels: int, embed_dim: int, **kwargs):
460
+ super().__init__()
461
+ assert input_channels == 3 or input_channels == 6, "Input channels must be 3 or 6"
462
+ self.backbone = Model(
463
+ points=points,
464
+ input_channels=input_channels,
465
+ embed_dim=embed_dim // 16,
466
+ groups=1,
467
+ res_expansion=0.25,
468
+ activation="relu",
469
+ bias=False,
470
+ use_xyz=False,
471
+ normalize="anchor",
472
+ dim_expansion=[2, 2, 2, 1],
473
+ pre_blocks=[1, 1, 2, 1],
474
+ pos_blocks=[1, 1, 2, 1],
475
+ k_neighbors=[24, 24, 24, 24],
476
+ reducers=[2, 2, 2, 2],
477
+ **kwargs,
478
+ )
479
+ return
480
+
481
+ def forward(self, pcd: torch.Tensor, robot_state_obs: torch.Tensor = None) -> torch.Tensor:
482
+ B = pcd.shape[0]
483
+ # Flatten the batch and time dimensions
484
+ pcd = pcd.float().reshape(-1, *pcd.shape[2:])
485
+ robot_state_obs = robot_state_obs.float().reshape(-1, *robot_state_obs.shape[2:])
486
+ # Permute [B, P, 3] -> [B, 3, P]
487
+ pcd = pcd.permute(0, 2, 1)
488
+ # Encode all point clouds (across time steps and batch size)
489
+ encoded_pcd = self.backbone(pcd)
490
+ nx = torch.cat([encoded_pcd, robot_state_obs], dim=1)
491
+ # Reshape back to the batch dimension. Now the features of each time step are concatenated
492
+ nx = nx.reshape(B, -1)
493
+ return nx
494
+
495
+
496
+ if __name__ == "__main__":
497
+ num_points = 1024
498
+ embed_dim = 512
499
+ data = torch.rand(2, 3, num_points)
500
+ print("===> testing pointMLP ...")
501
+ model = PointMLP(num_points, embed_dim)
502
+ out = model.backbone(data)
503
+ print(out.shape)
third_party/PointFlowMatch/pfp/backbones/pointnet.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Adapted from https://github.com/dyson-ai/hdp/blob/main/rk_diffuser/models/pointnet.py """
2
+
3
+ import numpy as np
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ import torch.nn.parallel
8
+ import torch.utils.data
9
+ from torch.autograd import Variable
10
+ from diffusion_policy.common.pytorch_util import replace_submodules
11
+
12
+
13
+ class STN3d(nn.Module):
14
+ def __init__(self):
15
+ super(STN3d, self).__init__()
16
+ self.conv1 = torch.nn.Conv1d(3, 64, 1)
17
+ self.conv2 = torch.nn.Conv1d(64, 128, 1)
18
+ self.conv3 = torch.nn.Conv1d(128, 1024, 1)
19
+ self.fc1 = nn.Linear(1024, 512)
20
+ self.fc2 = nn.Linear(512, 256)
21
+ self.fc3 = nn.Linear(256, 9)
22
+ self.relu = nn.ReLU()
23
+
24
+ self.bn1 = nn.BatchNorm1d(64)
25
+ self.bn2 = nn.BatchNorm1d(128)
26
+ self.bn3 = nn.BatchNorm1d(1024)
27
+ # self.bn4 = nn.BatchNorm1d(512)
28
+ # self.bn5 = nn.BatchNorm1d(256)
29
+
30
+ self.bn4 = nn.LayerNorm(512)
31
+ self.bn5 = nn.LayerNorm(256)
32
+
33
+ def forward(self, x):
34
+ batchsize = x.size()[0]
35
+ x = F.relu(self.bn1(self.conv1(x)))
36
+ x = F.relu(self.bn2(self.conv2(x)))
37
+ x = F.relu(self.bn3(self.conv3(x)))
38
+ x = torch.max(x, 2, keepdim=True)[0]
39
+ x = x.view(-1, 1024)
40
+
41
+ x = F.relu(self.bn4(self.fc1(x)))
42
+ x = F.relu(self.bn5(self.fc2(x)))
43
+ x = self.fc3(x)
44
+
45
+ iden = (
46
+ Variable(torch.from_numpy(np.array([1, 0, 0, 0, 1, 0, 0, 0, 1]).astype(np.float32)))
47
+ .view(1, 9)
48
+ .repeat(batchsize, 1)
49
+ )
50
+ if x.is_cuda:
51
+ iden = iden.cuda()
52
+ x = x + iden
53
+ x = x.view(-1, 3, 3)
54
+ return x
55
+
56
+
57
+ class STNkd(nn.Module):
58
+ def __init__(self, k=64):
59
+ super(STNkd, self).__init__()
60
+ self.conv1 = torch.nn.Conv1d(k, 64, 1)
61
+ self.conv2 = torch.nn.Conv1d(64, 128, 1)
62
+ self.conv3 = torch.nn.Conv1d(128, 1024, 1)
63
+ self.fc1 = nn.Linear(1024, 512)
64
+ self.fc2 = nn.Linear(512, 256)
65
+ self.fc3 = nn.Linear(256, k * k)
66
+ self.relu = nn.ReLU()
67
+
68
+ self.bn1 = nn.BatchNorm1d(64)
69
+ self.bn2 = nn.BatchNorm1d(128)
70
+ self.bn3 = nn.BatchNorm1d(1024)
71
+ # self.bn4 = nn.BatchNorm1d(512)
72
+ # self.bn5 = nn.BatchNorm1d(256)
73
+
74
+ self.bn4 = nn.LayerNorm(512)
75
+ self.bn5 = nn.LayerNorm(256)
76
+
77
+ self.k = k
78
+
79
+ def forward(self, x):
80
+ batchsize = x.size()[0]
81
+ x = F.relu(self.bn1(self.conv1(x)))
82
+ x = F.relu(self.bn2(self.conv2(x)))
83
+ x = F.relu(self.bn3(self.conv3(x)))
84
+ x = torch.max(x, 2, keepdim=True)[0]
85
+ x = x.view(-1, 1024)
86
+
87
+ x = F.relu(self.bn4(self.fc1(x)))
88
+ x = F.relu(self.bn5(self.fc2(x)))
89
+ x = self.fc3(x)
90
+
91
+ iden = (
92
+ Variable(torch.from_numpy(np.eye(self.k).flatten().astype(np.float32)))
93
+ .view(1, self.k * self.k)
94
+ .repeat(batchsize, 1)
95
+ )
96
+ if x.is_cuda:
97
+ iden = iden.cuda()
98
+ x = x + iden
99
+ x = x.view(-1, self.k, self.k)
100
+ return x
101
+
102
+
103
+ class PointNetfeat(nn.Module):
104
+ def __init__(self, input_channels: int, input_transform: bool, feature_transform=False):
105
+ super(PointNetfeat, self).__init__()
106
+ self.input_transform = input_transform
107
+ if self.input_transform:
108
+ self.stn = STNkd(k=input_channels)
109
+ self.conv1 = torch.nn.Conv1d(input_channels, 64, 1)
110
+ self.conv2 = torch.nn.Conv1d(64, 128, 1)
111
+ self.conv3 = torch.nn.Conv1d(128, 1024, 1)
112
+ self.bn1 = nn.BatchNorm1d(64)
113
+ self.bn2 = nn.BatchNorm1d(128)
114
+ self.bn3 = nn.BatchNorm1d(1024)
115
+ self.feature_transform = feature_transform
116
+ if self.feature_transform:
117
+ self.fstn = STNkd(k=64)
118
+
119
+ def forward(self, x):
120
+ b = x.size(0)
121
+ if len(x.shape) == 4:
122
+ x = x.view(b, -1, 3).permute(0, 2, 1).contiguous()
123
+
124
+ if self.input_transform:
125
+ trans = self.stn(x)
126
+ x = x.transpose(2, 1)
127
+ x = torch.bmm(x, trans)
128
+ x = x.transpose(2, 1)
129
+ else:
130
+ trans = None
131
+
132
+ x = F.relu(self.bn1(self.conv1(x)))
133
+
134
+ if self.feature_transform:
135
+ trans_feat = self.fstn(x)
136
+ x = x.transpose(2, 1)
137
+ x = torch.bmm(x, trans_feat)
138
+ x = x.transpose(2, 1)
139
+ else:
140
+ trans_feat = None
141
+
142
+ x = F.relu(self.bn2(self.conv2(x)))
143
+ x = self.bn3(self.conv3(x))
144
+ x = torch.max(x, 2, keepdim=True)[0]
145
+ x = x.view(-1, 1024)
146
+ return x
147
+
148
+
149
+ class PointNetCls(nn.Module):
150
+ def __init__(self, k=2, feature_transform=False):
151
+ super(PointNetCls, self).__init__()
152
+ self.feature_transform = feature_transform
153
+ self.feat = PointNetfeat(global_feat=True, feature_transform=feature_transform)
154
+ self.fc1 = nn.Linear(1024, 512)
155
+ self.fc2 = nn.Linear(512, 256)
156
+ self.fc3 = nn.Linear(256, k)
157
+ self.dropout = nn.Dropout(p=0.3)
158
+ self.bn1 = nn.BatchNorm1d(512)
159
+ self.bn2 = nn.BatchNorm1d(256)
160
+ self.relu = nn.ReLU()
161
+
162
+ def forward(self, x):
163
+ x, trans, trans_feat = self.feat(x)
164
+ x = F.relu(self.bn1(self.fc1(x)))
165
+ x = F.relu(self.bn2(self.dropout(self.fc2(x))))
166
+ x = self.fc3(x)
167
+ return F.log_softmax(x, dim=1), trans, trans_feat
168
+
169
+
170
+ class PointNetDenseCls(nn.Module):
171
+ def __init__(self, k=2, feature_transform=False):
172
+ super(PointNetDenseCls, self).__init__()
173
+ self.k = k
174
+ self.feature_transform = feature_transform
175
+ self.feat = PointNetfeat(global_feat=False, feature_transform=feature_transform)
176
+ self.conv1 = torch.nn.Conv1d(1088, 512, 1)
177
+ self.conv2 = torch.nn.Conv1d(512, 256, 1)
178
+ self.conv3 = torch.nn.Conv1d(256, 128, 1)
179
+ self.conv4 = torch.nn.Conv1d(128, self.k, 1)
180
+ self.bn1 = nn.BatchNorm1d(512)
181
+ self.bn2 = nn.BatchNorm1d(256)
182
+ self.bn3 = nn.BatchNorm1d(128)
183
+
184
+ def forward(self, x):
185
+ batchsize = x.size()[0]
186
+ n_pts = x.size()[2]
187
+ x, trans, trans_feat = self.feat(x)
188
+ x = F.relu(self.bn1(self.conv1(x)))
189
+ x = F.relu(self.bn2(self.conv2(x)))
190
+ x = F.relu(self.bn3(self.conv3(x)))
191
+ x = self.conv4(x)
192
+ x = x.transpose(2, 1).contiguous()
193
+ x = F.log_softmax(x.view(-1, self.k), dim=-1)
194
+ x = x.view(batchsize, n_pts, self.k)
195
+ return x, trans, trans_feat
196
+
197
+
198
+ class PointNetBackbone(nn.Module):
199
+ def __init__(
200
+ self,
201
+ embed_dim: int,
202
+ input_channels: int,
203
+ input_transform: bool,
204
+ use_group_norm: bool = False,
205
+ ):
206
+ super().__init__()
207
+ assert input_channels in [3, 6], "Input channels must be 3 or 6"
208
+ self.backbone = nn.Sequential(
209
+ PointNetfeat(input_channels, input_transform),
210
+ nn.Mish(),
211
+ nn.Linear(1024, 512),
212
+ nn.Mish(),
213
+ nn.Linear(512, embed_dim),
214
+ )
215
+ if use_group_norm:
216
+ self.backbone = replace_submodules(
217
+ root_module=self.backbone,
218
+ predicate=lambda x: isinstance(x, nn.BatchNorm1d),
219
+ func=lambda x: nn.GroupNorm(
220
+ num_groups=x.num_features // 16, num_channels=x.num_features
221
+ ),
222
+ )
223
+ return
224
+
225
+ def forward(self, pcd: torch.Tensor, robot_state_obs: torch.Tensor = None) -> torch.Tensor:
226
+ B = pcd.shape[0]
227
+ # Flatten the batch and time dimensions
228
+ pcd = pcd.float().reshape(-1, *pcd.shape[2:])
229
+ robot_state_obs = robot_state_obs.float().reshape(-1, *robot_state_obs.shape[2:])
230
+ # Permute [B, P, C] -> [B, C, P]
231
+ pcd = pcd.permute(0, 2, 1)
232
+ # Encode all point clouds (across time steps and batch size)
233
+ encoded_pcd = self.backbone(pcd)
234
+ nx = torch.cat([encoded_pcd, robot_state_obs], dim=1)
235
+ # Reshape back to the batch dimension. Now the features of each time step are concatenated
236
+ nx = nx.reshape(B, -1)
237
+ return nx
third_party/PointFlowMatch/pfp/backbones/resnet_dp.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from diffusion_policy.model.vision.model_getter import get_resnet
4
+ from diffusion_policy.model.vision.multi_image_obs_encoder import MultiImageObsEncoder
5
+
6
+
7
+ class ResnetDP(nn.Module):
8
+ def __init__(self, shape_meta: dict):
9
+ super().__init__()
10
+ rgb_model = get_resnet(name="resnet18")
11
+ self.backbone = MultiImageObsEncoder(
12
+ shape_meta=shape_meta,
13
+ rgb_model=rgb_model,
14
+ crop_shape=(76, 76),
15
+ random_crop=True,
16
+ use_group_norm=True,
17
+ share_rgb_model=False,
18
+ imagenet_norm=True,
19
+ )
20
+ return
21
+
22
+ def forward(self, images: torch.Tensor, robot_state_obs: torch.Tensor = None) -> torch.Tensor:
23
+ B = images.shape[0]
24
+ # Flatten the batch and time dimensions
25
+ images = images.reshape(-1, *images.shape[2:]).permute(0, 1, 4, 2, 3)
26
+ robot_state_obs = robot_state_obs.float().reshape(-1, *robot_state_obs.shape[2:])
27
+ # Encode all observations (across time steps and batch size)
28
+ obs_dict = {f"img_{i}": images[:, i] for i in range(images.shape[1])}
29
+ obs_dict["robot_state"] = robot_state_obs
30
+ nx = self.backbone(obs_dict)
31
+ # Reshape back to the batch dimension. Now the features of each time step are concatenated
32
+ nx = nx.reshape(B, -1)
33
+ return nx
third_party/PointFlowMatch/pfp/common/__pycache__/fm_utils.cpython-310.pyc ADDED
Binary file (724 Bytes). View file
 
third_party/PointFlowMatch/pfp/common/__pycache__/o3d_utils.cpython-310.pyc ADDED
Binary file (1.46 kB). View file
 
third_party/PointFlowMatch/pfp/common/__pycache__/se3_utils.cpython-310.pyc ADDED
Binary file (6.09 kB). View file
 
third_party/PointFlowMatch/pfp/common/__pycache__/visualization.cpython-310.pyc ADDED
Binary file (7.11 kB). View file
 
third_party/PointFlowMatch/pfp/common/fm_utils.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ def get_timesteps(schedule: str, k_steps: int, exp_scale: float = 1.0):
5
+ t = torch.linspace(0, 1, k_steps + 1)[:-1]
6
+ if schedule == "linear":
7
+ dt = torch.ones(k_steps) / k_steps
8
+ elif schedule == "cosine":
9
+ dt = torch.cos(t * torch.pi) + 1
10
+ dt /= torch.sum(dt)
11
+ elif schedule == "exp":
12
+ dt = torch.exp(-t * exp_scale)
13
+ dt /= torch.sum(dt)
14
+ else:
15
+ raise ValueError(f"Invalid schedule: {schedule}")
16
+ t0 = torch.cat((torch.zeros(1), torch.cumsum(dt, dim=0)[:-1]))
17
+ return t0, dt
third_party/PointFlowMatch/pfp/common/o3d_utils.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import functools
3
+ import numpy as np
4
+ import open3d as o3d
5
+
6
+
7
+ def make_pcd(
8
+ xyz: np.ndarray,
9
+ rgb: np.ndarray,
10
+ ) -> o3d.geometry.PointCloud:
11
+ points = o3d.utility.Vector3dVector(xyz.reshape(-1, 3))
12
+ colors = o3d.utility.Vector3dVector(rgb.reshape(-1, 3).astype(np.float64) / 255)
13
+ pcd = o3d.geometry.PointCloud(points)
14
+ pcd.colors = colors
15
+ return pcd
16
+
17
+
18
+ def merge_pcds(
19
+ voxel_size: float,
20
+ n_points: int,
21
+ pcds: list[o3d.geometry.PointCloud],
22
+ ws_aabb: o3d.geometry.AxisAlignedBoundingBox,
23
+ ) -> o3d.geometry.PointCloud:
24
+ merged_pcd = functools.reduce(lambda a, b: a + b, pcds, o3d.geometry.PointCloud())
25
+ merged_pcd = merged_pcd.crop(ws_aabb)
26
+ downsampled_pcd = merged_pcd.voxel_down_sample(voxel_size=voxel_size)
27
+ if len(downsampled_pcd.points) > n_points:
28
+ ratio = n_points / len(downsampled_pcd.points)
29
+ downsampled_pcd = downsampled_pcd.random_down_sample(ratio)
30
+ if len(downsampled_pcd.points) < n_points:
31
+ # Append zeros to make the point cloud have the desired number of points
32
+ num_missing_points = n_points - len(downsampled_pcd.points)
33
+ zeros = np.zeros((num_missing_points, 3))
34
+ zeros_pcd = o3d.geometry.PointCloud(o3d.utility.Vector3dVector(zeros))
35
+ zeros_pcd.colors = o3d.utility.Vector3dVector(zeros)
36
+ downsampled_pcd += zeros_pcd
37
+ return downsampled_pcd
third_party/PointFlowMatch/pfp/common/se3_utils.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ from spatialmath.base import r2q
4
+ from spatialmath.base.transforms3d import isrot
5
+
6
+ try:
7
+ from pytorch3d.ops import corresponding_points_alignment
8
+ except ImportError:
9
+ print("pytorch3d not installed")
10
+ from pfp import DEVICE
11
+
12
+
13
+ def transform_th(transform: torch.Tensor, points: torch.Tensor) -> torch.Tensor:
14
+ """Apply a 4x4 transformation matrix to a set of points."""
15
+ new_points = points @ transform[..., :3, :3].mT + transform[..., :3, 3]
16
+ return new_points
17
+
18
+
19
+ def vec_projection_np(v: np.ndarray, e: np.ndarray) -> np.ndarray:
20
+ """Project vector v onto unit vector e."""
21
+ proj = np.sum(v * e, axis=-1, keepdims=True) * e
22
+ return proj
23
+
24
+
25
+ def vec_projection_th(v: torch.Tensor, e: torch.Tensor) -> torch.Tensor:
26
+ """Project vector v onto unit vector e."""
27
+ proj = torch.sum(v * e, dim=-1, keepdim=True) * e
28
+ return proj
29
+
30
+
31
+ def grahm_schmidt_np(v1: np.ndarray, v2: np.ndarray) -> np.ndarray:
32
+ """Compute orthonormal basis from two vectors."""
33
+ v1 = v1.astype(np.float64)
34
+ v2 = v2.astype(np.float64)
35
+ u1 = v1
36
+ e1 = u1 / np.linalg.norm(u1, axis=-1, keepdims=True)
37
+ u2 = v2 - vec_projection_np(v2, e1)
38
+ e2 = u2 / np.linalg.norm(u2, axis=-1, keepdims=True)
39
+ e3 = np.cross(e1, e2, axis=-1)
40
+ rot_matrix = np.concatenate([e1[..., None], e2[..., None], e3[..., None]], axis=-1)
41
+ return rot_matrix
42
+
43
+
44
+ def grahm_schmidt_th(v1: torch.Tensor, v2: torch.Tensor) -> torch.Tensor:
45
+ """Compute orthonormal basis from two vectors."""
46
+ u1 = v1
47
+ e1 = u1 / torch.norm(u1, dim=-1, keepdim=True)
48
+ u2 = v2 - vec_projection_th(v2, e1)
49
+ e2 = u2 / torch.norm(u2, dim=-1, keepdim=True)
50
+ e3 = torch.cross(e1, e2, dim=-1)
51
+ rot_matrix = torch.cat(
52
+ [e1.unsqueeze(dim=-1), e2.unsqueeze(dim=-1), e3.unsqueeze(dim=-1)], dim=-1
53
+ )
54
+ return rot_matrix
55
+
56
+
57
+ def pfp_to_pose_np(robot_states: np.ndarray) -> np.ndarray:
58
+ """Convert pfp state (T, 10) to 4x4 poses (T, 4, 4)."""
59
+ T = robot_states.shape[0]
60
+ poses = np.eye(4)[np.newaxis, ...]
61
+ poses = np.tile(poses, (T, 1, 1))
62
+ poses[:, :3, 3] = robot_states[:, :3]
63
+ poses[:, :3, :3] = grahm_schmidt_np(robot_states[:, 3:6], robot_states[:, 6:9])
64
+ return poses
65
+
66
+
67
+ def pfp_to_pose_th(robot_states: torch.Tensor) -> torch.Tensor:
68
+ """Convert pfp state (B, T, 10) to 4x4 poses (B, T, 4, 4) and gripper (B, T, 1)."""
69
+ B = robot_states.shape[0]
70
+ T = robot_states.shape[1]
71
+ poses = (
72
+ torch.eye(4, device=robot_states.device)
73
+ .unsqueeze(0)
74
+ .unsqueeze(0)
75
+ .expand(B, T, 4, 4)
76
+ .contiguous()
77
+ )
78
+ poses[..., :3, 3] = robot_states[..., :3]
79
+ poses[..., :3, :3] = grahm_schmidt_th(robot_states[..., 3:6], robot_states[..., 6:9])
80
+ gripper = robot_states[..., -1:]
81
+ return poses, gripper
82
+
83
+
84
+ def rot6d_to_quat_np(rot6d: np.ndarray, order: str = "xyzs") -> np.ndarray:
85
+ """Convert 6d rotation matrix to quaternion."""
86
+ rot = grahm_schmidt_np(rot6d[:3], rot6d[3:])
87
+ quat = r2q(rot, order=order)
88
+ return quat
89
+
90
+
91
+ def rot6d_to_rot_np(rot6d: np.ndarray) -> np.ndarray:
92
+ """Convert 6d rotation matrix to 3x3 rotation matrix."""
93
+ rot = grahm_schmidt_np(rot6d[:3], rot6d[3:])
94
+ return rot
95
+
96
+
97
+ def check_valid_rot(rot: np.ndarray) -> bool:
98
+ """Check if the 3x3 rotation matrix is valid."""
99
+ valid = isrot(rot, check=True, tol=1e10)
100
+ return valid
101
+
102
+
103
+ def get_canonical_5p_th() -> torch.Tensor:
104
+ """Return the (5,3) canonical 5points representation of the franka hand."""
105
+ gripper_width = 0.08
106
+ left_y = 0.5 * gripper_width
107
+ right_y = -0.5 * gripper_width
108
+ mid_z = -0.041
109
+ top_z = -0.1034
110
+ a = [0, 0, top_z]
111
+ b = [0, left_y, mid_z]
112
+ c = [0, right_y, mid_z]
113
+ d = [0, left_y, 0]
114
+ e = [0, right_y, 0]
115
+ pose_5p = torch.tensor([a, b, c, d, e])
116
+ return pose_5p
117
+
118
+
119
+ def pfp_to_state5p_th(robot_states: torch.Tensor) -> torch.Tensor:
120
+ """
121
+ Convert pfp state (B, T, 10) to 5points representation (B, T, 16).
122
+ 5p: [x0, y0, z0, x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4, gripper]
123
+ """
124
+ device = robot_states.device
125
+ poses, gripper = pfp_to_pose_th(robot_states)
126
+ canonical_5p = get_canonical_5p_th().to(device)
127
+ canonical_5p_homog = torch.cat([canonical_5p, torch.ones(5, 1, device=device)], dim=-1)
128
+ poses_5p_homog = (poses @ canonical_5p_homog.mT).mT
129
+ poses_5p = poses_5p_homog[..., :3].contiguous().flatten(start_dim=-2)
130
+ state5p = torch.cat([poses_5p, gripper], dim=-1)
131
+ return state5p
132
+
133
+
134
+ def state5p_to_pfp_th(state5p: torch.Tensor) -> torch.Tensor:
135
+ """
136
+ Convert 5points representation (B, T, 16) to pfp state (B, T, 10) using svd projection.
137
+ """
138
+ device = state5p.device
139
+ leading_dims = state5p.shape[0:2]
140
+ # Flatten the batch and time dimensions
141
+ state5p = state5p.reshape(-1, *state5p.shape[2:])
142
+ poses_5p, gripper = state5p[..., :-1], state5p[..., -1:]
143
+ poses_5p = poses_5p.reshape(-1, 5, 3)
144
+ canonical_5p = get_canonical_5p_th().expand(poses_5p.shape[0], 5, 3).to(device)
145
+ with torch.cuda.amp.autocast(enabled=False):
146
+ result = corresponding_points_alignment(canonical_5p, poses_5p)
147
+ rotations = result.R.mT
148
+ translations = result.T
149
+ pfp_state = torch.cat([translations, rotations[..., 0], rotations[..., 1], gripper], dim=-1)
150
+ # Reshape back to the batch and time dimensions
151
+ pfp_state = pfp_state.reshape(*leading_dims, -1)
152
+ return pfp_state
153
+
154
+
155
+ def init_random_traj_th(B: int, T: int, noise_scale: float) -> torch.Tensor:
156
+ """
157
+ B: batch size
158
+ T: number of time steps
159
+ """
160
+ # Position
161
+ random_xyz = torch.randn((B, 1, 3), device=DEVICE) * noise_scale
162
+ direction = torch.randn((B, 1, 3), device=DEVICE)
163
+ direction = direction / torch.norm(direction, dim=-1, keepdim=True)
164
+ t = torch.linspace(0, 1, T, device=DEVICE).unsqueeze(0).unsqueeze(-1)
165
+ random_xyz = random_xyz + t * direction
166
+
167
+ # Rotation 6d
168
+ random_r1 = torch.randn((B, 1, 3), device=DEVICE)
169
+ random_r1 = random_r1 / torch.norm(random_r1, dim=-1, keepdim=True)
170
+ random_r2 = torch.randn((B, 1, 3), device=DEVICE)
171
+ random_r2 = random_r2 - vec_projection_th(random_r2, random_r1)
172
+ random_r2 = random_r2 / torch.norm(random_r2, dim=-1, keepdim=True)
173
+ random_r6d = torch.cat([random_r1, random_r2], dim=-1)
174
+ random_r6d = random_r6d.expand(B, T, 6)
175
+
176
+ # Gripper
177
+ gripper = torch.ones((B, T, 1), device=DEVICE)
178
+
179
+ random_traj = torch.cat([random_xyz, random_r6d, gripper], dim=-1)
180
+ return random_traj
third_party/PointFlowMatch/pfp/common/visualization.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import trimesh
3
+ import numpy as np
4
+ import open3d as o3d
5
+ from yourdfpy.urdf import URDF
6
+ from pfp.common.se3_utils import pfp_to_pose_np
7
+
8
+ try:
9
+ import rerun as rr
10
+ except ImportError:
11
+ print("WARNING: Rerun not installed. Visualization will not work.")
12
+
13
+
14
+ class RerunViewer:
15
+ def __init__(self, name: str, addr: str = None):
16
+ rr.init(name)
17
+ if addr is None:
18
+ addr = "127.0.0.1"
19
+ port = ":9876"
20
+ rr.connect(addr + port)
21
+ RerunViewer.clear()
22
+ return
23
+
24
+ @staticmethod
25
+ def add_obs_dict(obs_dict: dict, timestep: int = None):
26
+ if timestep is not None:
27
+ rr.set_time_sequence("timestep", timestep)
28
+ RerunViewer.add_rgb("rgb", obs_dict["image"])
29
+ RerunViewer.add_depth("depth", obs_dict["depth"])
30
+ RerunViewer.add_np_pointcloud(
31
+ "vis/pointcloud",
32
+ points=obs_dict["point_cloud"][:, :3],
33
+ colors_uint8=obs_dict["point_cloud"][:, 3:],
34
+ )
35
+ return
36
+
37
+ @staticmethod
38
+ def add_o3d_pointcloud(name: str, pointcloud: o3d.geometry.PointCloud, radii: float = None):
39
+ points = np.asanyarray(pointcloud.points)
40
+ colors = np.asanyarray(pointcloud.colors) if pointcloud.has_colors() else None
41
+ colors_uint8 = (colors * 255).astype(np.uint8) if pointcloud.has_colors() else None
42
+ RerunViewer.add_np_pointcloud(name, points, colors_uint8, radii)
43
+ return
44
+
45
+ @staticmethod
46
+ def add_np_pointcloud(
47
+ name: str, points: np.ndarray, colors_uint8: np.ndarray = None, radii: float = None
48
+ ):
49
+ rr_points = rr.Points3D(positions=points, colors=colors_uint8, radii=radii)
50
+ rr.log(name, rr_points)
51
+ return
52
+
53
+ @staticmethod
54
+ def add_axis(name: str, pose: np.ndarray, size: float = 0.004, timeless: bool = False):
55
+ mesh = trimesh.creation.axis(origin_size=size, transform=pose)
56
+ RerunViewer.add_mesh_trimesh(name, mesh, timeless)
57
+ return
58
+
59
+ @staticmethod
60
+ def add_aabb(name: str, centers: np.ndarray, extents: np.ndarray, timeless=False):
61
+ rr.log(name, rr.Boxes3D(centers=centers, sizes=extents), timeless=timeless)
62
+ return
63
+
64
+ @staticmethod
65
+ def add_mesh_trimesh(name: str, mesh: trimesh.Trimesh, timeless: bool = False):
66
+ # Handle colors
67
+ if mesh.visual.kind in ["vertex", "face"]:
68
+ vertex_colors = mesh.visual.vertex_colors
69
+ elif mesh.visual.kind == "texture":
70
+ vertex_colors = mesh.visual.to_color().vertex_colors
71
+ else:
72
+ vertex_colors = None
73
+ # Log mesh
74
+ rr_mesh = rr.Mesh3D(
75
+ vertex_positions=mesh.vertices,
76
+ vertex_colors=vertex_colors,
77
+ vertex_normals=mesh.vertex_normals,
78
+ indices=mesh.faces,
79
+ )
80
+ rr.log(name, rr_mesh, timeless=timeless)
81
+ return
82
+
83
+ @staticmethod
84
+ def add_mesh_list_trimesh(name: str, meshes: list[trimesh.Trimesh]):
85
+ for i, mesh in enumerate(meshes):
86
+ RerunViewer.add_mesh_trimesh(name + f"/{i}", mesh)
87
+ return
88
+
89
+ @staticmethod
90
+ def add_rgb(name: str, rgb_uint8: np.ndarray):
91
+ if rgb_uint8.shape[0] == 3:
92
+ # CHW -> HWC
93
+ rgb_uint8 = np.transpose(rgb_uint8, (1, 2, 0))
94
+ rr.log(name, rr.Image(rgb_uint8))
95
+
96
+ @staticmethod
97
+ def add_depth(name: str, detph: np.ndarray):
98
+ rr.log(name, rr.DepthImage(detph))
99
+
100
+ @staticmethod
101
+ def add_traj(name: str, traj: np.ndarray):
102
+ """
103
+ name: str
104
+ traj: np.ndarray (T, 10)
105
+ """
106
+ poses = pfp_to_pose_np(traj)
107
+ for i, pose in enumerate(poses):
108
+ RerunViewer.add_axis(name + f"/{i}t", pose)
109
+ return
110
+
111
+ @staticmethod
112
+ def clear():
113
+ rr.log("vis", rr.Clear(recursive=True))
114
+ return
115
+
116
+
117
+ class RerunTraj:
118
+ def __init__(self) -> None:
119
+ self.traj_shape = None
120
+ return
121
+
122
+ def add_traj(self, name: str, traj: np.ndarray, size: float = 0.004):
123
+ """
124
+ name: str
125
+ traj: np.ndarray (T, 10)
126
+ """
127
+ if self.traj_shape is None or self.traj_shape != traj.shape:
128
+ self.traj_shape = traj.shape
129
+ for i in range(traj.shape[0]):
130
+ RerunViewer.add_axis(name + f"/{i}t", np.eye(4), size)
131
+ poses = pfp_to_pose_np(traj)
132
+ for i, pose in enumerate(poses):
133
+ rr.log(
134
+ name + f"/{i}t",
135
+ rr.Transform3D(mat3x3=pose[:3, :3], translation=pose[:3, 3]),
136
+ )
137
+ return
138
+
139
+
140
+ class RerunURDF:
141
+ def __init__(self, name: str, urdf_path: str, meshes_root: str):
142
+ self.name = name
143
+ self.urdf: URDF = URDF.load(urdf_path, mesh_dir=meshes_root)
144
+ return
145
+
146
+ def update_vis(
147
+ self,
148
+ joint_state: list | np.ndarray,
149
+ root_pose: np.ndarray = np.eye(4),
150
+ name_suffix: str = "",
151
+ ):
152
+ self._update_joints(joint_state)
153
+ scene = self.urdf.scene
154
+ trimeshes = self._scene_to_trimeshes(scene)
155
+ trimeshes = [t.apply_transform(root_pose) for t in trimeshes]
156
+ RerunViewer.add_mesh_list_trimesh(self.name + name_suffix, trimeshes)
157
+ return
158
+
159
+ def _update_joints(self, joint_state: list | np.ndarray):
160
+ assert len(joint_state) == len(self.urdf.actuated_joints), "Wrong number of joint values."
161
+ self.urdf.update_cfg(joint_state)
162
+ return
163
+
164
+ def _scene_to_trimeshes(self, scene: trimesh.Scene) -> list[trimesh.Trimesh]:
165
+ """
166
+ Convert a trimesh.Scene to a list of trimesh.Trimesh.
167
+
168
+ Skips objects that are not an instance of trimesh.Trimesh.
169
+ """
170
+ trimeshes = []
171
+ scene_dump = scene.dump()
172
+ geometries = [scene_dump] if not isinstance(scene_dump, list) else scene_dump
173
+ for geometry in geometries:
174
+ if isinstance(geometry, trimesh.Trimesh):
175
+ trimeshes.append(geometry)
176
+ elif isinstance(geometry, trimesh.Scene):
177
+ trimeshes.extend(self._scene_to_trimeshes(geometry))
178
+ return trimeshes
third_party/PointFlowMatch/pfp/data/__pycache__/dataset_pcd.cpython-310.pyc ADDED
Binary file (3.68 kB). View file
 
third_party/PointFlowMatch/pfp/data/__pycache__/replay_buffer.cpython-310.pyc ADDED
Binary file (2.92 kB). View file
 
third_party/PointFlowMatch/pfp/data/dataset_images.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import torch
3
+ import numpy as np
4
+ from diffusion_policy.common.sampler import SequenceSampler
5
+ from pfp.data.replay_buffer import RobotReplayBuffer
6
+ from pfp import DATA_DIRS
7
+
8
+
9
+ class RobotDatasetImages(torch.utils.data.Dataset):
10
+ def __init__(
11
+ self,
12
+ data_path: str,
13
+ n_obs_steps: int,
14
+ n_pred_steps: int,
15
+ subs_factor: int = 1, # 1 means no subsampling
16
+ **kwargs,
17
+ ) -> None:
18
+ """
19
+ To me it makes sense that sequence_length == n_obs_steps + n_prediction_steps
20
+ """
21
+ replay_buffer = RobotReplayBuffer.create_from_path(data_path, mode="r")
22
+ data_keys = ["robot_state", "images"]
23
+ data_key_first_k = {"images": n_obs_steps * subs_factor}
24
+ self.sampler = SequenceSampler(
25
+ replay_buffer=replay_buffer,
26
+ sequence_length=(n_obs_steps + n_pred_steps) * subs_factor - (subs_factor - 1),
27
+ pad_before=(n_obs_steps - 1) * subs_factor,
28
+ pad_after=(n_pred_steps - 1) * subs_factor + (subs_factor - 1),
29
+ keys=data_keys,
30
+ key_first_k=data_key_first_k,
31
+ )
32
+ self.n_obs_steps = n_obs_steps
33
+ self.n_prediction_steps = n_pred_steps
34
+ self.subs_factor = subs_factor
35
+ self.rng = np.random.default_rng()
36
+ return
37
+
38
+ def __len__(self) -> int:
39
+ return len(self.sampler)
40
+
41
+ def __getitem__(self, idx: int) -> tuple[torch.Tensor, ...]:
42
+ sample: dict[str, np.ndarray] = self.sampler.sample_sequence(idx)
43
+ cur_step_i = self.n_obs_steps * self.subs_factor
44
+ images = sample["images"][: cur_step_i : self.subs_factor]
45
+ robot_state_obs = sample["robot_state"][: cur_step_i : self.subs_factor]
46
+ robot_state_pred = sample["robot_state"][cur_step_i :: self.subs_factor]
47
+ return images, robot_state_obs, robot_state_pred
48
+
49
+
50
+ if __name__ == "__main__":
51
+ dataset = RobotDatasetImages(
52
+ data_path=DATA_DIRS.PFP / "open_fridge" / "train",
53
+ n_obs_steps=2,
54
+ n_pred_steps=8,
55
+ subs_factor=5,
56
+ )
57
+ i = 20
58
+ obs, robot_state_obs, robot_state_pred = dataset[i]
59
+ print("robot_state_obs: ", robot_state_obs)
60
+ print("robot_state_pred: ", robot_state_pred)
61
+ print("done")
third_party/PointFlowMatch/pfp/data/dataset_pcd.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import torch
3
+ import numpy as np
4
+ import pypose as pp
5
+ from diffusion_policy.common.sampler import SequenceSampler
6
+ from pfp.data.replay_buffer import RobotReplayBuffer
7
+ from pfp.common.se3_utils import transform_th
8
+ from pfp import DATA_DIRS
9
+
10
+
11
+ def rand_range(low: float, high: float, size: tuple[int], device) -> torch.Tensor:
12
+ return torch.rand(size, device=device) * (high - low) + low
13
+
14
+
15
+ def augment_pcd_data(batch: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
16
+ pcd, robot_state_obs, robot_state_pred = batch
17
+ BT_robot_obs = robot_state_obs.shape[:-1]
18
+ BT_robot_pred = robot_state_pred.shape[:-1]
19
+
20
+ # sigma=(sigma_transl, sigma_rot_rad)
21
+ transform = pp.randn_SE3(sigma=(0.1, 0.2), device=pcd.device).matrix()
22
+
23
+ pcd[..., :3] = transform_th(transform, pcd[..., :3])
24
+ robot_obs_pseudoposes = robot_state_obs[..., :9].reshape(*BT_robot_obs, 3, 3)
25
+ robot_pred_pseudoposes = robot_state_pred[..., :9].reshape(*BT_robot_pred, 3, 3)
26
+ robot_obs_pseudoposes = transform_th(transform, robot_obs_pseudoposes)
27
+ robot_pred_pseudoposes = transform_th(transform, robot_pred_pseudoposes)
28
+ robot_state_obs[..., :9] = robot_obs_pseudoposes.reshape(*BT_robot_obs, 9)
29
+ robot_state_pred[..., :9] = robot_pred_pseudoposes.reshape(*BT_robot_pred, 9)
30
+
31
+ # We shuffle the points, i.e. shuffle pcd along dim=2 (B, T, P, 3)
32
+ idx = torch.randperm(pcd.shape[2])
33
+ pcd = pcd[:, :, idx, :]
34
+ return pcd, robot_state_obs, robot_state_pred
35
+
36
+
37
+ class RobotDatasetPcd(torch.utils.data.Dataset):
38
+ def __init__(
39
+ self,
40
+ data_path: str,
41
+ n_obs_steps: int,
42
+ n_pred_steps: int,
43
+ use_pc_color: bool,
44
+ n_points: int,
45
+ subs_factor: int = 1, # 1 means no subsampling
46
+ ) -> None:
47
+ """
48
+ To me it makes sense that sequence_length == n_obs_steps + n_prediction_steps
49
+ """
50
+ replay_buffer = RobotReplayBuffer.create_from_path(data_path, mode="r")
51
+ data_keys = ["robot_state", "pcd_xyz"]
52
+ data_key_first_k = {"pcd_xyz": n_obs_steps * subs_factor}
53
+ if use_pc_color:
54
+ data_keys.append("pcd_color")
55
+ data_key_first_k["pcd_color"] = n_obs_steps * subs_factor
56
+ self.sampler = SequenceSampler(
57
+ replay_buffer=replay_buffer,
58
+ sequence_length=(n_obs_steps + n_pred_steps) * subs_factor - (subs_factor - 1),
59
+ pad_before=(n_obs_steps - 1) * subs_factor,
60
+ pad_after=(n_pred_steps - 1) * subs_factor + (subs_factor - 1),
61
+ keys=data_keys,
62
+ key_first_k=data_key_first_k,
63
+ )
64
+ self.n_obs_steps = n_obs_steps
65
+ self.n_prediction_steps = n_pred_steps
66
+ self.subs_factor = subs_factor
67
+ self.use_pc_color = use_pc_color
68
+ self.n_points = n_points
69
+ self.rng = np.random.default_rng()
70
+ return
71
+
72
+ def __len__(self) -> int:
73
+ return len(self.sampler)
74
+
75
+ def __getitem__(self, idx: int) -> tuple[torch.Tensor, ...]:
76
+ sample: dict[str, np.ndarray] = self.sampler.sample_sequence(idx)
77
+ cur_step_i = self.n_obs_steps * self.subs_factor
78
+ pcd = sample["pcd_xyz"][: cur_step_i : self.subs_factor]
79
+ if self.use_pc_color:
80
+ pcd_color = sample["pcd_color"][: cur_step_i : self.subs_factor]
81
+ pcd_color = pcd_color.astype(np.float32) / 255.0
82
+ pcd = np.concatenate([pcd, pcd_color], axis=-1)
83
+ robot_state_obs = sample["robot_state"][: cur_step_i : self.subs_factor].astype(np.float32)
84
+ robot_state_pred = sample["robot_state"][cur_step_i :: self.subs_factor].astype(np.float32)
85
+ # Random sample pcd points
86
+ if pcd.shape[1] > self.n_points:
87
+ random_indices = np.random.choice(pcd.shape[1], self.n_points, replace=False)
88
+ pcd = pcd[:, random_indices]
89
+ return pcd, robot_state_obs, robot_state_pred
90
+
91
+
92
+ if __name__ == "__main__":
93
+ dataset = RobotDatasetPcd(
94
+ data_path=DATA_DIRS.PFP / "open_fridge" / "train",
95
+ n_obs_steps=2,
96
+ n_pred_steps=8,
97
+ subs_factor=5,
98
+ use_pc_color=False,
99
+ n_points=4096,
100
+ )
101
+ i = 20
102
+ obs, robot_state_obs, robot_state_pred = dataset[i]
103
+ print("robot_state_obs: ", robot_state_obs)
104
+ print("robot_state_pred: ", robot_state_pred)
105
+ print("done")
third_party/PointFlowMatch/pfp/data/replay_buffer.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import zarr
3
+ import numpy as np
4
+ from diffusion_policy.common.replay_buffer import ReplayBuffer
5
+ from diffusion_policy.codecs.imagecodecs_numcodecs import register_codec, Jpeg2k
6
+
7
+ register_codec(Jpeg2k)
8
+
9
+
10
+ class RobotReplayBuffer(ReplayBuffer):
11
+ def __init__(self, root: zarr.Group):
12
+ super().__init__(root)
13
+ self.jpeg_compressor = Jpeg2k()
14
+ return
15
+
16
+ def add_episode_from_list(self, data_list: list[dict[str, np.ndarray]], **kwargs):
17
+ """
18
+ data_list is a list of dictionaries, where each dictionary contains the data for one step.
19
+ """
20
+ data_dict = dict()
21
+ for key in data_list[0].keys():
22
+ data_dict[key] = np.stack([x[key] for x in data_list])
23
+ self.add_episode(data_dict, **kwargs)
24
+ return
25
+
26
+ def add_episode_from_list_compressed(self, data_list: list[dict[str, np.ndarray]], **kwargs):
27
+ """
28
+ data_list is a list of dictionaries, where each dictionary contains the data for one step.
29
+ WARNING: decoding (i.e. reading) is broken.
30
+ """
31
+ data_dict = {key: np.stack([x[key] for x in data_list]) for key in data_list[0].keys()}
32
+ # get the keys starting with 'rgb*'
33
+ rgb_keys = [key for key in data_dict.keys() if key.startswith("rgb")]
34
+ rgb_shapes = [data_list[0][key].shape for key in rgb_keys]
35
+ chunks = {rgb_keys[i]: (1, *rgb_shapes[i]) for i in range(len(rgb_keys))}
36
+ compressors = {key: self.jpeg_compressor for key in rgb_keys}
37
+ self.add_episode(data_dict, chunks, compressors, **kwargs)
38
+ return
third_party/PointFlowMatch/pfp/envs/__pycache__/base_env.cpython-310.pyc ADDED
Binary file (907 Bytes). View file
 
third_party/PointFlowMatch/pfp/envs/__pycache__/rlbench_env.cpython-310.pyc ADDED
Binary file (7.99 kB). View file
 
third_party/PointFlowMatch/pfp/envs/__pycache__/rlbench_runner.cpython-310.pyc ADDED
Binary file (1.6 kB). View file
 
third_party/PointFlowMatch/pfp/envs/base_env.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+
3
+
4
+ class BaseEnv(ABC):
5
+ """
6
+ The base abstract class for all envs.
7
+ """
8
+
9
+ @abstractmethod
10
+ def reset(self):
11
+ pass
12
+
13
+ @abstractmethod
14
+ def reset_rng(self):
15
+ pass
16
+
17
+ @abstractmethod
18
+ def step(self, action):
19
+ pass
20
+
21
+ @abstractmethod
22
+ def get_obs(self):
23
+ pass
third_party/PointFlowMatch/pfp/envs/rlbench_env.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import numpy as np
3
+ import open3d as o3d
4
+ import spatialmath.base as sm
5
+ from pyrep.const import RenderMode
6
+ from pfp.envs.base_env import BaseEnv
7
+ from pyrep.errors import IKError
8
+ from rlbench.environment import Environment
9
+ from rlbench.backend.observation import Observation
10
+ from rlbench.backend.exceptions import InvalidActionError
11
+ from rlbench.action_modes.action_mode import MoveArmThenGripper
12
+ from rlbench.action_modes.gripper_action_modes import Discrete
13
+ from rlbench.action_modes.arm_action_modes import EndEffectorPoseViaPlanning
14
+ from rlbench.observation_config import ObservationConfig, CameraConfig
15
+ from rlbench.utils import name_to_task_class
16
+ from pfp.common.visualization import RerunViewer as RV
17
+ from pfp.common.o3d_utils import make_pcd, merge_pcds
18
+ from pfp.common.se3_utils import rot6d_to_quat_np, pfp_to_pose_np
19
+
20
+ try:
21
+ import rerun as rr
22
+ except ImportError:
23
+ print("WARNING: Rerun not installed. Visualization will not work.")
24
+
25
+
26
+ class RLBenchEnv(BaseEnv):
27
+ """
28
+ DT = 0.05 (50ms/20Hz)
29
+ robot_state = [px, py, pz, r00, r10, r20, r01, r11, r21, gripper]
30
+ The pose is the ttip frame, with x pointing backwards, y pointing left, and z pointing down.
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ task_name: str,
36
+ voxel_size: float,
37
+ n_points: int,
38
+ use_pc_color: bool,
39
+ headless: bool,
40
+ vis: bool,
41
+ obs_mode: str = "pcd",
42
+ ):
43
+ assert obs_mode in ["pcd", "rgb"], "Invalid obs_mode"
44
+ self.obs_mode = obs_mode
45
+ # image_size=(128, 128)
46
+ self.voxel_size = voxel_size
47
+ self.n_points = n_points
48
+ self.use_pc_color = use_pc_color
49
+ camera_config = CameraConfig(
50
+ rgb=True,
51
+ depth=False,
52
+ mask=False,
53
+ point_cloud=True,
54
+ image_size=(128, 128),
55
+ render_mode=RenderMode.OPENGL,
56
+ )
57
+ obs_config = ObservationConfig(
58
+ camera_configs={
59
+ "over_shoulder_left": camera_config,
60
+ "over_shoulder_right": camera_config,
61
+ "overhead": camera_config,
62
+ "wrist": camera_config,
63
+ "front": camera_config,
64
+ },
65
+ gripper_matrix=True,
66
+ gripper_joint_positions=True,
67
+ )
68
+ # EE pose is (X,Y,Z,Qx,Qy,Qz,Qw)
69
+ action_mode = MoveArmThenGripper(
70
+ arm_action_mode=EndEffectorPoseViaPlanning(), gripper_action_mode=Discrete()
71
+ )
72
+ self.env = Environment(
73
+ action_mode,
74
+ obs_config=obs_config,
75
+ headless=headless,
76
+ )
77
+ self.env.launch()
78
+ self.task = self.env.get_task(name_to_task_class(task_name))
79
+ self.robot_position = self.env._robot.arm.get_position()
80
+ self.ws_aabb = o3d.geometry.AxisAlignedBoundingBox(
81
+ min_bound=(self.robot_position[0] + 0.1, -0.65, self.robot_position[2] - 0.05),
82
+ max_bound=(1, 0.65, 2),
83
+ )
84
+ self.vis = vis
85
+ self.last_obs = None
86
+ if self.vis:
87
+ RV.add_axis("vis/origin", np.eye(4), size=0.01, timeless=True)
88
+ RV.add_aabb(
89
+ "vis/ws_aabb", self.ws_aabb.get_center(), self.ws_aabb.get_extent(), timeless=True
90
+ )
91
+ return
92
+
93
+ def reset(self):
94
+ self.task.reset()
95
+ return
96
+
97
+ def reset_rng(self):
98
+ return
99
+
100
+ def step(self, robot_state: np.ndarray):
101
+ ee_position = robot_state[:3]
102
+ ee_quat = rot6d_to_quat_np(robot_state[3:9])
103
+ gripper = robot_state[-1:]
104
+ action = np.concatenate([ee_position, ee_quat, gripper])
105
+ reward, terminate = self._step_safe(action)
106
+ return reward, terminate
107
+
108
+ def _step_safe(self, action: np.ndarray, recursion_depth=0):
109
+ if recursion_depth > 15:
110
+ print("Warning: Recursion depth limit reached.")
111
+ return 0.0, True
112
+ try:
113
+ _, reward, terminate = self.task.step(action)
114
+ except (IKError, InvalidActionError, AttributeError, RuntimeError) as e:
115
+ print(e)
116
+ cur_position = self.last_obs.gripper_pose[:3]
117
+ des_position = action[:3]
118
+ new_position = cur_position + (des_position - cur_position) * 0.25
119
+
120
+ cur_quat = self.last_obs.gripper_pose[3:]
121
+ cur_quat = np.array([cur_quat[3], cur_quat[0], cur_quat[1], cur_quat[2]])
122
+ des_quat = action[3:7]
123
+ des_quat = np.array([des_quat[3], des_quat[0], des_quat[1], des_quat[2]])
124
+ new_quat = sm.qslerp(cur_quat, des_quat, 0.25, shortest=True)
125
+ new_quat = np.array([new_quat[1], new_quat[2], new_quat[3], new_quat[0]])
126
+
127
+ new_action = np.concatenate([new_position, new_quat, action[-1:]])
128
+ reward, terminate = self._step_safe(new_action, recursion_depth + 1)
129
+ return reward, terminate
130
+
131
+ def get_obs(self) -> tuple[np.ndarray, ...]:
132
+ obs_rlbench = self.task.get_observation()
133
+ self.last_obs = obs_rlbench
134
+ robot_state = self.get_robot_state(obs_rlbench)
135
+ if self.obs_mode == "pcd":
136
+ pcd_o3d = self.get_pcd(obs_rlbench)
137
+ pcd = np.asarray(pcd_o3d.points)
138
+ if self.use_pc_color:
139
+ pcd_color = np.asarray(pcd_o3d.colors, dtype=np.float32)
140
+ pcd = np.concatenate([pcd, pcd_color], axis=-1)
141
+ obs = pcd
142
+ elif self.obs_mode == "rgb":
143
+ obs = self.get_images(obs_rlbench)
144
+ return robot_state, obs
145
+
146
+ def get_robot_state(self, obs: Observation) -> np.ndarray:
147
+ ee_position = obs.gripper_matrix[:3, 3]
148
+ ee_rot6d = obs.gripper_matrix[:3, :2].flatten(order="F")
149
+ gripper = np.array([obs.gripper_open])
150
+ robot_state = np.concatenate([ee_position, ee_rot6d, gripper])
151
+ return robot_state
152
+
153
+ def get_pcd(self, obs: Observation) -> o3d.geometry.PointCloud:
154
+ perception = obs.perception_data
155
+ right_pcd = make_pcd(
156
+ perception["over_shoulder_right_point_cloud"], perception["over_shoulder_right_rgb"]
157
+ )
158
+ left_pcd = make_pcd(
159
+ perception["over_shoulder_left_point_cloud"], perception["over_shoulder_left_rgb"]
160
+ )
161
+ overhead_pcd = make_pcd(perception["overhead_point_cloud"], perception["overhead_rgb"])
162
+ front_pcd = make_pcd(perception["front_point_cloud"], perception["front_rgb"])
163
+ wrist_pcd = make_pcd(perception["wrist_point_cloud"], perception["wrist_rgb"])
164
+ pcd_list = [right_pcd, left_pcd, overhead_pcd, front_pcd, wrist_pcd]
165
+ pcd = merge_pcds(self.voxel_size, self.n_points, pcd_list, self.ws_aabb)
166
+ return pcd
167
+
168
+ def get_images(self, obs: Observation) -> np.ndarray:
169
+ perception = obs.perception_data
170
+ images = np.stack(
171
+ (
172
+ perception["over_shoulder_right_rgb"],
173
+ perception["over_shoulder_left_rgb"],
174
+ perception["overhead_rgb"],
175
+ perception["front_rgb"],
176
+ perception["wrist_rgb"],
177
+ )
178
+ )
179
+ return images
180
+
181
+ def vis_step(self, robot_state: np.ndarray, obs: np.ndarray, prediction: np.ndarray = None):
182
+ """
183
+ robot_state: the current robot state (10,)
184
+ obs: either pcd or images
185
+ - pcd: the current point cloud (N, 6) or (N, 3)
186
+ - images: the current images (5, H, W, 3)
187
+ prediction: the full trajectory of robot states (T, 10)
188
+ """
189
+ VIS_FLOW = False
190
+ if not self.vis:
191
+ return
192
+ rr.set_time_seconds("time", time.time())
193
+
194
+ # Point cloud
195
+ if self.obs_mode == "pcd":
196
+ pcd = obs
197
+ pcd_xyz = pcd[:, :3]
198
+ pcd_color = (pcd[:, 3:6] * 255).astype(np.uint8) if self.use_pc_color else None
199
+ RV.add_np_pointcloud("vis/pcd_obs", points=pcd_xyz, colors_uint8=pcd_color, radii=0.003)
200
+
201
+ # RGB images
202
+ elif self.obs_mode == "rgb":
203
+ images = obs
204
+ for i, img in enumerate(images):
205
+ RV.add_rgb(f"vis/rgb_obs_{i}", img)
206
+
207
+ # EE State
208
+ ee_pose = pfp_to_pose_np(robot_state[np.newaxis, ...]).squeeze()
209
+ RV.add_axis("vis/ee_state", ee_pose)
210
+ rr.log("plot/gripper_state", rr.Scalar(robot_state[-1]))
211
+
212
+ if prediction is None:
213
+ return
214
+
215
+ # EE predictions
216
+ final_pred = prediction[-1]
217
+ if VIS_FLOW:
218
+ for traj in prediction:
219
+ RV.add_traj("vis/traj_k", traj)
220
+ else:
221
+ RV.add_traj("vis/ee_pred", final_pred)
222
+
223
+ # Gripper action prediction
224
+ rr.log("plot/gripper_pred", rr.Scalar(final_pred[0, -1]))
225
+ return
226
+
227
+ def close(self):
228
+ self.env.shutdown()
229
+ return
230
+
231
+
232
+ if __name__ == "__main__":
233
+ env = RLBenchEnv(
234
+ "close_microwave",
235
+ voxel_size=0.01,
236
+ n_points=5500,
237
+ use_pc_color=False,
238
+ headless=True,
239
+ vis=True,
240
+ )
241
+ env.reset()
242
+ for i in range(1000):
243
+ robot_state, pcd = env.get_obs()
244
+ next_robot_state = robot_state.copy()
245
+ next_robot_state[:3] += np.array([-0.005, 0.005, 0.0])
246
+ env.step(next_robot_state)
247
+ env.close()
third_party/PointFlowMatch/pfp/envs/rlbench_runner.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import wandb
2
+ from tqdm import tqdm
3
+ from pfp.envs.rlbench_env import RLBenchEnv
4
+ from pfp.policy.base_policy import BasePolicy
5
+
6
+
7
+ class RLBenchRunner:
8
+ def __init__(
9
+ self,
10
+ num_episodes: int,
11
+ max_episode_length: int,
12
+ env_config: dict,
13
+ verbose=False,
14
+ ) -> None:
15
+ self.env: RLBenchEnv = RLBenchEnv(**env_config)
16
+ self.num_episodes = num_episodes
17
+ self.max_episode_length = max_episode_length
18
+ self.verbose = verbose
19
+ return
20
+
21
+ def run(self, policy: BasePolicy):
22
+ wandb.define_metric("success", summary="mean")
23
+ wandb.define_metric("steps", summary="mean")
24
+ success_list: list[bool] = []
25
+ steps_list: list[int] = []
26
+ self.env.reset_rng()
27
+ for episode in tqdm(range(self.num_episodes)):
28
+ policy.reset_obs()
29
+ self.env.reset()
30
+ for step in range(self.max_episode_length):
31
+ robot_state, obs = self.env.get_obs()
32
+ prediction = policy.predict_action(obs, robot_state)
33
+ self.env.vis_step(robot_state, obs, prediction)
34
+ next_robot_state = prediction[-1, 0] # Last K step, first T step
35
+ reward, terminate = self.env.step(next_robot_state)
36
+ success = bool(reward)
37
+ if success or terminate:
38
+ break
39
+ success_list.append(success)
40
+ if success:
41
+ steps_list.append(step)
42
+ if self.verbose:
43
+ print(f"Steps: {step}")
44
+ print(f"Success: {success}")
45
+ wandb.log({"episode": episode, "success": int(success), "steps": step})
46
+ return success_list, steps_list
third_party/PointFlowMatch/pfp/policy/__pycache__/base_policy.cpython-310.pyc ADDED
Binary file (3.05 kB). View file
 
third_party/PointFlowMatch/pfp/policy/__pycache__/fm_policy.cpython-310.pyc ADDED
Binary file (9.49 kB). View file
 
third_party/PointFlowMatch/pfp/policy/base_policy.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ from collections import deque
4
+ from abc import ABC, abstractmethod
5
+ from pfp import DEVICE
6
+
7
+
8
+ class BasePolicy(ABC):
9
+ """
10
+ The base abstract class for all policies.
11
+ """
12
+
13
+ def __init__(self, n_obs_steps: int, subs_factor: int = 1) -> None:
14
+ maxlen = n_obs_steps * subs_factor - (subs_factor - 1)
15
+ self.obs_list = deque(maxlen=maxlen)
16
+ self.robot_state_list = deque(maxlen=maxlen)
17
+ self.subs_factor = subs_factor
18
+ return
19
+
20
+ def reset_obs(self):
21
+ self.obs_list.clear()
22
+ self.robot_state_list.clear()
23
+ return
24
+
25
+ def update_obs_lists(self, obs: np.ndarray, robot_state: np.ndarray):
26
+ self.obs_list.append(obs)
27
+ if len(self.obs_list) < self.obs_list.maxlen:
28
+ self.obs_list.extendleft(
29
+ [self.obs_list[0]] * (self.obs_list.maxlen - len(self.obs_list))
30
+ )
31
+ self.robot_state_list.append(robot_state)
32
+ if len(self.robot_state_list) < self.robot_state_list.maxlen:
33
+ n = self.robot_state_list.maxlen - len(self.robot_state_list)
34
+ self.robot_state_list.extendleft([self.robot_state_list[0]] * n)
35
+ return
36
+
37
+ def sample_stacked_obs(self) -> tuple[np.ndarray, ...]:
38
+ obs_stacked = np.stack(self.obs_list, axis=0)[:: self.subs_factor]
39
+ robot_state_stacked = np.stack(self.robot_state_list, axis=0)[:: self.subs_factor]
40
+ return obs_stacked, robot_state_stacked
41
+
42
+ def predict_action(self, obs: np.ndarray, robot_state: np.ndarray) -> np.ndarray:
43
+ self.update_obs_lists(obs, robot_state)
44
+ obs_stacked, robot_state_stacked = self.sample_stacked_obs()
45
+ action = self.infer_from_np(obs_stacked, robot_state_stacked)
46
+ return action
47
+
48
+ def infer_from_np(self, obs: np.ndarray, robot_state: np.ndarray) -> np.ndarray:
49
+ obs_th = torch.tensor(obs, device=DEVICE).unsqueeze(0)
50
+ robot_state_th = torch.tensor(robot_state, device=DEVICE).unsqueeze(0)
51
+ obs_th = self._norm_obs(obs_th)
52
+ robot_state_th = self._norm_robot_state(robot_state_th)
53
+ ny = self.infer_y(
54
+ obs_th,
55
+ robot_state_th,
56
+ return_traj=True,
57
+ )
58
+ ny = self._denorm_robot_state(ny)
59
+ ny = ny.squeeze().detach().cpu().numpy()
60
+ # Return the full trajectory (both integration time K and horizon T)
61
+ return ny # (K, T, 10)
62
+
63
+ @abstractmethod
64
+ def _norm_obs(self, obs: torch.Tensor) -> torch.Tensor:
65
+ pass
66
+
67
+ @abstractmethod
68
+ def _norm_robot_state(self, robot_state: torch.Tensor) -> torch.Tensor:
69
+ pass
70
+
71
+ @abstractmethod
72
+ def _denorm_robot_state(self, robot_state: torch.Tensor) -> torch.Tensor:
73
+ pass
74
+
75
+ @abstractmethod
76
+ def infer_y(
77
+ self, obs: torch.Tensor, robot_state: torch.Tensor, return_traj: bool
78
+ ) -> torch.Tensor:
79
+ pass
third_party/PointFlowMatch/pfp/policy/ddim_policy.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import copy
3
+ import hydra
4
+ import torch
5
+ import torch.nn as nn
6
+ from omegaconf import OmegaConf
7
+ from composer.models import ComposerModel
8
+ from diffusers.schedulers.scheduling_ddim import DDIMScheduler
9
+ from pfp.policy.base_policy import BasePolicy
10
+ from pfp import DEVICE, REPO_DIRS
11
+
12
+
13
+ class DDIMPolicy(ComposerModel, BasePolicy):
14
+ """Class to train the DDIM diffusion model"""
15
+
16
+ def __init__(
17
+ self,
18
+ x_dim: int,
19
+ y_dim: int,
20
+ n_obs_steps: int,
21
+ n_pred_steps: int,
22
+ num_k_train: int,
23
+ num_k_infer: int,
24
+ obs_encoder: nn.Module,
25
+ diffusion_net: nn.Module,
26
+ noise_scheduler_train: DDIMScheduler,
27
+ augment_data: bool = False,
28
+ loss_weights: dict[int] = None,
29
+ norm_pcd_center: list = None,
30
+ ) -> None:
31
+ ComposerModel.__init__(self)
32
+ BasePolicy.__init__(self, n_obs_steps)
33
+ self.x_dim = x_dim
34
+ self.y_dim = y_dim
35
+ self.n_obs_steps = n_obs_steps
36
+ self.n_pred_steps = n_pred_steps
37
+ self.num_k_train = num_k_train
38
+ self.num_k_infer = num_k_infer
39
+ self.obs_encoder = obs_encoder
40
+ self.diffusion_net = diffusion_net
41
+ self.norm_pcd_center = norm_pcd_center
42
+ self.augment_data = augment_data
43
+ # It's easier to have two different schedulers for training and eval/inference
44
+ self.noise_scheduler_train = noise_scheduler_train
45
+ self.noise_scheduler_infer = copy.deepcopy(noise_scheduler_train)
46
+ self.noise_scheduler_infer.set_timesteps(num_k_infer)
47
+ self.ny_shape = (n_pred_steps, y_dim)
48
+ self.l_w = loss_weights
49
+ return
50
+
51
+ def set_num_k_infer(self, num_k_infer: int):
52
+ self.num_k_infer = num_k_infer
53
+ self.noise_scheduler_infer.set_timesteps(num_k_infer)
54
+ return
55
+
56
+ def _norm_obs(self, pcd: torch.Tensor) -> torch.Tensor:
57
+ # I only do centering here, no scaling, to keep the relative distances and interpretability
58
+ pcd[..., :3] -= torch.tensor(self.norm_pcd_center, device=DEVICE)
59
+ return pcd
60
+
61
+ def _norm_robot_state(self, robot_state: torch.Tensor) -> torch.Tensor:
62
+ # I only do centering here, no scaling, to keep the relative distances and interpretability
63
+ robot_state[..., :3] -= torch.tensor(self.norm_pcd_center, device=DEVICE)
64
+ robot_state[..., 9] -= torch.tensor(0.5, device=DEVICE)
65
+ return robot_state
66
+
67
+ def _denorm_robot_state(self, robot_state: torch.Tensor) -> torch.Tensor:
68
+ robot_state[..., :3] += torch.tensor(self.norm_pcd_center, device=DEVICE)
69
+ robot_state[..., 9] += torch.tensor(0.5, device=DEVICE)
70
+ return robot_state
71
+
72
+ def _norm_data(self, batch: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
73
+ pcd, robot_state_obs, robot_state_pred = batch
74
+ pcd = self._norm_obs(pcd)
75
+ robot_state_obs = self._norm_robot_state(robot_state_obs)
76
+ robot_state_pred = self._norm_robot_state(robot_state_pred)
77
+ return pcd, robot_state_obs, robot_state_pred
78
+
79
+ def _rand_range(self, low: float, high: float, size: tuple[int]) -> torch.Tensor:
80
+ return torch.rand(size, device=DEVICE) * (high - low) + low
81
+
82
+ def _augment_data(self, batch: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
83
+ pcd, robot_state_obs, robot_state_pred = batch
84
+
85
+ # xyz1 = self._rand_range(low=0.8, high=1.2, size=(3,))
86
+ xyz2 = self._rand_range(low=-0.2, high=0.2, size=(3,))
87
+ pcd[..., :3] = pcd[..., :3] + xyz2 # * xyz1 + xyz2
88
+ robot_state_obs[..., :3] = robot_state_obs[..., :3] + xyz2 # * xyz1 + xyz2
89
+ robot_state_pred[..., :3] = robot_state_pred[..., :3] + xyz2 # * xyz1 + xyz2
90
+
91
+ # We shuffle the points, i.e. shuffle pcd along dim=2 (B, T, P, 3)
92
+ idx = torch.randperm(pcd.shape[2])
93
+ pcd = pcd[:, :, idx, :]
94
+ return pcd, robot_state_obs, robot_state_pred
95
+
96
+ # ########### TRAIN ###########
97
+
98
+ def forward(self, batch):
99
+ """batch: the output of the dataloader"""
100
+ return 0
101
+
102
+ def loss(self, outputs, batch: tuple[torch.Tensor, ...]) -> torch.Tensor:
103
+ """
104
+ outputs: the output of the forward pass
105
+ batch: the output of the dataloader
106
+ """
107
+ with torch.no_grad():
108
+ batch = self._norm_data(batch)
109
+ if self.augment_data:
110
+ batch = self._augment_data(batch)
111
+ pcd, robot_state_obs, robot_state_pred = batch
112
+ noise_pred, noise = self.train_noise(pcd, robot_state_obs, robot_state_pred)
113
+ loss_xyz = nn.functional.mse_loss(noise_pred[..., :3], noise[..., :3])
114
+ loss_rot6d = nn.functional.mse_loss(noise_pred[..., 3:9], noise[..., 3:9])
115
+ loss_grip = nn.functional.mse_loss(noise_pred[..., 9], noise[..., 9])
116
+ loss = (
117
+ self.l_w["xyz"] * loss_xyz
118
+ + self.l_w["rot6d"] * loss_rot6d
119
+ + self.l_w["grip"] * loss_grip
120
+ )
121
+ self.logger.log_metrics(
122
+ {
123
+ "loss/train/xyz": loss_xyz.item(),
124
+ "loss/train/rot6d": loss_rot6d.item(),
125
+ "loss/train/grip": loss_grip.item(),
126
+ }
127
+ )
128
+ return loss
129
+
130
+ def train_noise(
131
+ self, pcd: torch.Tensor, robot_state_obs: torch.Tensor, robot_state_pred: torch.Tensor
132
+ ) -> tuple[torch.Tensor, ...]:
133
+ nx: torch.Tensor = self.obs_encoder(pcd, robot_state_obs)
134
+ ny: torch.Tensor = robot_state_pred
135
+ B = nx.shape[0]
136
+ noise = torch.randn(ny.shape).to(DEVICE)
137
+ timesteps = torch.randint(0, self.num_k_train, (B,)).long().to(DEVICE)
138
+ noisy_y = self.noise_scheduler_train.add_noise(ny, noise, timesteps)
139
+ noise_pred = self.diffusion_net(noisy_y, timesteps.float(), global_cond=nx)
140
+ return noise_pred, noise
141
+
142
+ # ########### EVAL ###########
143
+
144
+ def eval_forward(self, batch: tuple[torch.Tensor, ...], outputs=None) -> torch.Tensor:
145
+ """
146
+ batch: the output of the eval dataloader
147
+ outputs: the output of the forward pass
148
+ """
149
+ batch = self._norm_data(batch)
150
+ pcd, robot_state_obs, robot_state_pred = batch
151
+ pred_y = self.infer_y(pcd, robot_state_obs)
152
+ mse_xyz = nn.functional.mse_loss(pred_y[..., :3], robot_state_pred[..., :3])
153
+ mse_rot6d = nn.functional.mse_loss(pred_y[..., 3:9], robot_state_pred[..., 3:9])
154
+ mse_grip = nn.functional.mse_loss(pred_y[..., 9], robot_state_pred[..., 9])
155
+ self.logger.log_metrics(
156
+ {
157
+ "metrics/eval/mse_xyz": mse_xyz.item(),
158
+ "metrics/eval/mse_rot6d": mse_rot6d.item(),
159
+ "metrics/eval/mse_grip": mse_grip.item(),
160
+ }
161
+ )
162
+ return pred_y
163
+
164
+ def infer_y(
165
+ self,
166
+ pcd: torch.Tensor,
167
+ robot_state_obs: torch.Tensor,
168
+ noise=None,
169
+ return_traj=False,
170
+ ) -> torch.Tensor:
171
+ nx: torch.Tensor = self.obs_encoder(pcd, robot_state_obs)
172
+ if noise is None:
173
+ B = nx.shape[0]
174
+ noise = torch.randn((B, *self.ny_shape), device=DEVICE)
175
+
176
+ ny = noise
177
+ traj = [ny]
178
+ for k in self.noise_scheduler_infer.timesteps:
179
+ noise_pred = self.diffusion_net(ny, k, global_cond=nx)
180
+ if self.num_k_infer == 1:
181
+ print("one step generation")
182
+ ny = self.noise_scheduler_infer.step(
183
+ model_output=noise_pred,
184
+ timestep=k,
185
+ sample=ny,
186
+ ).pred_original_sample
187
+ else:
188
+ ny = self.noise_scheduler_infer.step(
189
+ model_output=noise_pred,
190
+ timestep=k,
191
+ sample=ny,
192
+ ).prev_sample
193
+ traj.append(ny)
194
+ if return_traj:
195
+ return torch.stack(traj)
196
+ return traj[-1]
197
+
198
+ @classmethod
199
+ def load_from_checkpoint(
200
+ cls,
201
+ ckpt_name: str,
202
+ ckpt_episode: str,
203
+ num_k_infer: int = None,
204
+ **kwargs,
205
+ ):
206
+ ckpt_dir = REPO_DIRS.CKPT / ckpt_name
207
+ ckpt_path_list = list(ckpt_dir.glob(f"{ckpt_episode}*"))
208
+ assert len(ckpt_path_list) > 0, f"No checkpoint found in {ckpt_dir} with {ckpt_episode}"
209
+ assert len(ckpt_path_list) < 2, f"Multiple ckpts found in {ckpt_dir} with {ckpt_episode}"
210
+ ckpt_fpath = ckpt_path_list[0]
211
+
212
+ state_dict = torch.load(ckpt_fpath, map_location=DEVICE)
213
+ cfg = OmegaConf.load(ckpt_dir / "config.yaml")
214
+ assert cfg.model._target_.split(".")[-1] == cls.__name__
215
+ model: DDIMPolicy = hydra.utils.instantiate(cfg.model)
216
+ model.load_state_dict(state_dict["state"]["model"])
217
+ model.to(DEVICE)
218
+ model.eval()
219
+ if num_k_infer is not None:
220
+ model.set_num_k_infer(num_k_infer)
221
+ return model
222
+
223
+
224
+ class DDIMPolicyImage(DDIMPolicy):
225
+
226
+ def _norm_obs(self, image: torch.Tensor) -> torch.Tensor:
227
+ """
228
+ Image normalization is already done in the backbone, so here we just make it float
229
+ """
230
+ image = image.float() / 255.0
231
+ return image
232
+
233
+
234
+ if __name__ == "__main__":
235
+ ckpt_name = "1714199471-peculiar-earthworm"
236
+ model = DDIMPolicy.load_from_checkpoint(ckpt_name, num_k_infer=10)
237
+ print(model.obs_list)
third_party/PointFlowMatch/pfp/policy/fm_5p_policy.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import hydra
3
+ import torch
4
+ import torch.nn as nn
5
+ import pypose as pp
6
+ from omegaconf import OmegaConf
7
+ from composer.models import ComposerModel
8
+ from pfp.policy.base_policy import BasePolicy
9
+ from pfp import DEVICE, REPO_DIRS
10
+ from pfp.common.fm_utils import get_timesteps
11
+ from pfp.common.se3_utils import pfp_to_state5p_th, state5p_to_pfp_th
12
+
13
+
14
+ class FM5PPolicy(ComposerModel, BasePolicy):
15
+ def __init__(
16
+ self,
17
+ x_dim: int,
18
+ y_dim: int,
19
+ n_obs_steps: int,
20
+ n_pred_steps: int,
21
+ num_k_infer: int,
22
+ time_conditioning: bool,
23
+ obs_encoder: nn.Module,
24
+ diffusion_net: nn.Module,
25
+ augment_data: bool = False,
26
+ loss_weights: dict[int] = None,
27
+ pos_emb_scale: int = 20,
28
+ norm_pcd_center: list = None,
29
+ noise_type: str = "gaussian",
30
+ noise_scale: float = 1.0,
31
+ loss_type: str = "l2",
32
+ flow_schedule: str = "linear",
33
+ exp_scale: float = None,
34
+ ) -> None:
35
+ ComposerModel.__init__(self)
36
+ BasePolicy.__init__(self, n_obs_steps)
37
+ self.x_dim = x_dim
38
+ self.y_dim = y_dim
39
+ self.n_obs_steps = n_obs_steps
40
+ self.n_pred_steps = n_pred_steps
41
+ self.pos_emb_scale = pos_emb_scale
42
+ self.num_k_infer = num_k_infer
43
+ self.time_conditioning = time_conditioning
44
+ self.obs_encoder = obs_encoder
45
+ self.diffusion_net = diffusion_net
46
+ self.norm_pcd_center = norm_pcd_center
47
+ self.augment_data = augment_data
48
+ self.noise_type = noise_type
49
+ self.noise_scale = noise_scale
50
+ self.ny_shape = (n_pred_steps, y_dim)
51
+ self.l_w = loss_weights
52
+ self.flow_schedule = flow_schedule
53
+ self.exp_scale = exp_scale
54
+ if loss_type == "l2":
55
+ self.loss_fun = nn.MSELoss()
56
+ elif loss_type == "l1":
57
+ self.loss_fun = nn.L1Loss()
58
+ else:
59
+ raise NotImplementedError
60
+ return
61
+
62
+ def set_num_k_infer(self, num_k_infer: int):
63
+ self.num_k_infer = num_k_infer
64
+ return
65
+
66
+ def set_flow_schedule(self, flow_schedule: str, exp_scale: float):
67
+ self.flow_schedule = flow_schedule
68
+ self.exp_scale = exp_scale
69
+ return
70
+
71
+ def _norm_obs(self, pcd: torch.Tensor) -> torch.Tensor:
72
+ # I only do centering here, no scaling, to keep the relative distances and interpretability
73
+ pcd[..., :3] -= torch.tensor(self.norm_pcd_center, device=DEVICE)
74
+ return pcd
75
+
76
+ def _norm_robot_state(self, robot_state: torch.Tensor) -> torch.Tensor:
77
+ # I only do centering here, no scaling, to keep the relative distances and interpretability
78
+ robot_state[..., :3] -= torch.tensor(self.norm_pcd_center, device=DEVICE)
79
+ robot_state[..., 9] -= torch.tensor(0.5, device=DEVICE)
80
+ return robot_state
81
+
82
+ def _denorm_robot_state(self, robot_state: torch.Tensor) -> torch.Tensor:
83
+ robot_state[..., :3] += torch.tensor(self.norm_pcd_center, device=DEVICE)
84
+ robot_state[..., 9] += torch.tensor(0.5, device=DEVICE)
85
+ return robot_state
86
+
87
+ def _norm_data(self, batch: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
88
+ pcd, robot_state_obs, robot_state_pred = batch
89
+ pcd = self._norm_obs(pcd)
90
+ robot_state_obs = self._norm_robot_state(robot_state_obs)
91
+ robot_state_pred = self._norm_robot_state(robot_state_pred)
92
+ return pcd, robot_state_obs, robot_state_pred
93
+
94
+ def _rand_range(self, low: float, high: float, size: tuple[int]) -> torch.Tensor:
95
+ return torch.rand(size, device=DEVICE) * (high - low) + low
96
+
97
+ def _augment_data(self, batch: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
98
+ pcd, robot_state_obs, robot_state_pred = batch
99
+
100
+ # xyz1 = self._rand_range(low=0.8, high=1.2, size=(3,))
101
+ xyz2 = self._rand_range(low=-0.2, high=0.2, size=(3,))
102
+ pcd[..., :3] = pcd[..., :3] + xyz2 # * xyz1 + xyz2
103
+ robot_state_obs[..., :3] = robot_state_obs[..., :3] + xyz2 # * xyz1 + xyz2
104
+ robot_state_pred[..., :3] = robot_state_pred[..., :3] + xyz2 # * xyz1 + xyz2
105
+
106
+ # We shuffle the points, i.e. shuffle pcd along dim=2 (B, T, P, 3)
107
+ idx = torch.randperm(pcd.shape[2])
108
+ pcd = pcd[:, :, idx, :]
109
+ return pcd, robot_state_obs, robot_state_pred
110
+
111
+ def _init_noise(self, batch_size: int) -> torch.Tensor:
112
+ B = batch_size
113
+ T = self.n_pred_steps
114
+ noise_poses = pp.randn_SE3((B, T), device=DEVICE).matrix()
115
+ noise_gripper = torch.randn((B, T, 1), device=DEVICE)
116
+ noise_pfp = torch.cat(
117
+ [
118
+ noise_poses[..., :3, 3],
119
+ noise_poses[..., :3, 0],
120
+ noise_poses[..., :3, 1],
121
+ noise_gripper,
122
+ ],
123
+ dim=-1,
124
+ )
125
+ noise_5p = pfp_to_state5p_th(noise_pfp)
126
+ return noise_5p
127
+
128
+ def _init_target(self, ny: torch.Tensor) -> torch.Tensor:
129
+ """
130
+ ny: (B, T, 10) -> xyz, rot6d, grip
131
+ """
132
+ target_5p = pfp_to_state5p_th(ny)
133
+ return target_5p
134
+
135
+ # ############### Training ################
136
+
137
+ def forward(self, batch):
138
+ """batch is the output of the dataloader"""
139
+ return 0
140
+
141
+ def loss(self, outputs, batch: tuple[torch.Tensor, ...]) -> torch.Tensor:
142
+ """
143
+ outputs: the output of the forward pass
144
+ batch: the output of the dataloader
145
+ """
146
+ with torch.no_grad():
147
+ batch = self._norm_data(batch)
148
+ if self.augment_data:
149
+ batch = self._augment_data(batch)
150
+ pcd, robot_state_obs, robot_state_pred = batch
151
+ loss_5p, loss_grip = self.calculate_loss(pcd, robot_state_obs, robot_state_pred)
152
+ loss = self.l_w["5p"] * loss_5p + self.l_w["grip"] * loss_grip
153
+ self.logger.log_metrics(
154
+ {
155
+ "loss/train/5p": loss_5p.item(),
156
+ "loss/train/grip": loss_grip.item(),
157
+ }
158
+ )
159
+ return loss
160
+
161
+ def calculate_loss(
162
+ self, pcd: torch.Tensor, robot_state_obs: torch.Tensor, robot_state_pred: torch.Tensor
163
+ ):
164
+ nx: torch.Tensor = self.obs_encoder(pcd, robot_state_obs)
165
+ ny: torch.Tensor = robot_state_pred
166
+
167
+ B = ny.shape[0]
168
+ T = ny.shape[1]
169
+
170
+ # Sample random time step
171
+ t_shape = [1] * len(ny.shape)
172
+ t_shape[0] = ny.shape[0] # B
173
+ t = torch.rand(t_shape, device=DEVICE)
174
+
175
+ # Initialize start and end poses + gripper state
176
+ z0_5p = self._init_noise(B)
177
+ z1_5p = self._init_target(ny)
178
+
179
+ # Move to intermediate step
180
+ z_t = t * z1_5p + (1.0 - t) * z0_5p
181
+
182
+ # Calculate relative change between them
183
+ target_vel = z1_5p - z0_5p
184
+
185
+ # Do prediction
186
+ timesteps = t.squeeze() * self.pos_emb_scale if self.time_conditioning else None
187
+ pred_vel = self.diffusion_net(z_t, timesteps, global_cond=nx)
188
+ assert pred_vel.shape == (B, T, 16)
189
+
190
+ # Calculate loss
191
+ loss_5p = self.loss_fun(pred_vel[..., :15], target_vel[..., :15])
192
+ loss_grip = self.loss_fun(pred_vel[..., 15], target_vel[..., 15])
193
+ return loss_5p, loss_grip
194
+
195
+ # ############### Inference ################
196
+
197
+ def eval_forward(self, batch: tuple[torch.Tensor, ...], outputs=None) -> torch.Tensor:
198
+ """
199
+ batch: the output of the eval dataloader
200
+ outputs: the output of the forward pass
201
+ """
202
+ batch = self._norm_data(batch)
203
+ pcd, robot_state_obs, robot_state_pred = batch
204
+
205
+ # Eval loss
206
+ loss_5p, loss_grip = self.calculate_loss(pcd, robot_state_obs, robot_state_pred)
207
+ loss_total = self.l_w["5p"] * loss_5p + self.l_w["grip"] * loss_grip
208
+ self.logger.log_metrics(
209
+ {
210
+ "loss/eval/5p": loss_5p.item(),
211
+ "loss/eval/grip": loss_grip.item(),
212
+ "loss/eval/total": loss_total.item(),
213
+ }
214
+ )
215
+
216
+ # Eval metrics
217
+ pred_y = self.infer_y(pcd, robot_state_obs)
218
+ mse_xyz = nn.functional.mse_loss(pred_y[..., :3], robot_state_pred[..., :3])
219
+ mse_rot6d = nn.functional.mse_loss(pred_y[..., 3:9], robot_state_pred[..., 3:9])
220
+ mse_grip = nn.functional.mse_loss(pred_y[..., 9], robot_state_pred[..., 9])
221
+ self.logger.log_metrics(
222
+ {
223
+ "metrics/eval/mse_xyz": mse_xyz.item(),
224
+ "metrics/eval/mse_rot6d": mse_rot6d.item(),
225
+ "metrics/eval/mse_grip": mse_grip.item(),
226
+ }
227
+ )
228
+ return pred_y
229
+
230
+ def infer_y(
231
+ self,
232
+ pcd: torch.Tensor,
233
+ robot_state_obs: torch.Tensor,
234
+ noise=None,
235
+ return_traj=False,
236
+ ) -> torch.Tensor:
237
+ nx: torch.Tensor = self.obs_encoder(pcd, robot_state_obs)
238
+ B = nx.shape[0]
239
+ z = self._init_noise(B) if noise is None else noise
240
+ traj = [state5p_to_pfp_th(z)]
241
+ t0, dt = get_timesteps(self.flow_schedule, self.num_k_infer, exp_scale=self.exp_scale)
242
+ for i in range(self.num_k_infer):
243
+ timesteps = torch.ones((B), device=DEVICE) * t0[i]
244
+ timesteps *= self.pos_emb_scale
245
+ vel_pred = self.diffusion_net(z, timesteps, global_cond=nx)
246
+ z = z.detach().clone() + vel_pred * dt[i]
247
+ traj.append(state5p_to_pfp_th(z))
248
+
249
+ if return_traj:
250
+ return torch.stack(traj)
251
+ return traj[-1]
252
+
253
+ @classmethod
254
+ def load_from_checkpoint(
255
+ cls,
256
+ ckpt_name: str,
257
+ ckpt_episode: str,
258
+ num_k_infer: int,
259
+ flow_schedule: str = None,
260
+ exp_scale: float = None,
261
+ ):
262
+ ckpt_dir = REPO_DIRS.CKPT / ckpt_name
263
+ ckpt_path_list = list(ckpt_dir.glob(f"{ckpt_episode}*"))
264
+ assert len(ckpt_path_list) > 0, f"No checkpoint found in {ckpt_dir} with {ckpt_episode}"
265
+ assert len(ckpt_path_list) < 2, f"Multiple ckpts found in {ckpt_dir} with {ckpt_episode}"
266
+ ckpt_fpath = ckpt_path_list[0]
267
+
268
+ state_dict = torch.load(ckpt_fpath, map_location=DEVICE)
269
+ cfg = OmegaConf.load(ckpt_dir / "config.yaml")
270
+ # cfg.model.obs_encoder.encoder.random_crop = False
271
+ assert cfg.model._target_.split(".")[-1] == cls.__name__
272
+ model: FM5PPolicy = hydra.utils.instantiate(cfg.model)
273
+ model.load_state_dict(state_dict["state"]["model"])
274
+ model.to(DEVICE)
275
+ model.eval()
276
+ if flow_schedule is not None:
277
+ model.set_flow_schedule(flow_schedule, exp_scale)
278
+ if num_k_infer is not None:
279
+ model.set_num_k_infer(num_k_infer)
280
+ return model
281
+
282
+
283
+ class FM5PPolicyImage(FM5PPolicy):
284
+
285
+ def _norm_obs(self, image: torch.Tensor) -> torch.Tensor:
286
+ """
287
+ Image normalization is already done in the backbone, so here we just make it float
288
+ """
289
+ image = image.float() / 255.0
290
+ return image
third_party/PointFlowMatch/pfp/policy/fm_policy.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import hydra
3
+ import torch
4
+ import torch.nn as nn
5
+ import pypose as pp
6
+ from omegaconf import OmegaConf
7
+ from pfp.policy.base_policy import BasePolicy
8
+ from pfp import DEVICE, REPO_DIRS
9
+ from pfp.common.se3_utils import init_random_traj_th
10
+ from pfp.common.fm_utils import get_timesteps
11
+ from pfp.data.dataset_pcd import augment_pcd_data
12
+
13
+ try:
14
+ from composer.models import ComposerModel
15
+ except Exception:
16
+ class _NullLogger:
17
+ def log_metrics(self, *args, **kwargs):
18
+ return
19
+
20
+ class ComposerModel(nn.Module):
21
+ def __init__(self):
22
+ super().__init__()
23
+ self.logger = _NullLogger()
24
+
25
+
26
+ class FMPolicy(ComposerModel, BasePolicy):
27
+ def __init__(
28
+ self,
29
+ x_dim: int,
30
+ y_dim: int,
31
+ n_obs_steps: int,
32
+ n_pred_steps: int,
33
+ num_k_infer: int,
34
+ time_conditioning: bool,
35
+ obs_encoder: nn.Module,
36
+ diffusion_net: nn.Module,
37
+ augment_data: bool = False,
38
+ loss_weights: dict[int] = None,
39
+ pos_emb_scale: int = 20,
40
+ norm_pcd_center: list = None,
41
+ noise_type: str = "gaussian",
42
+ noise_scale: float = 1.0,
43
+ loss_type: str = "l2",
44
+ flow_schedule: str = "linear",
45
+ exp_scale: float = None,
46
+ snr_sampler: str = "uniform",
47
+ subs_factor: int = 1,
48
+ ) -> None:
49
+ ComposerModel.__init__(self)
50
+ BasePolicy.__init__(self, n_obs_steps, subs_factor)
51
+ self.x_dim = x_dim
52
+ self.y_dim = y_dim
53
+ self.n_obs_steps = n_obs_steps
54
+ self.n_pred_steps = n_pred_steps
55
+ self.pos_emb_scale = pos_emb_scale
56
+ self.num_k_infer = num_k_infer
57
+ self.time_conditioning = time_conditioning
58
+ self.obs_encoder = obs_encoder
59
+ self.diffusion_net = diffusion_net
60
+ self.norm_pcd_center = norm_pcd_center
61
+ self.augment_data = augment_data
62
+ self.noise_type = noise_type
63
+ self.noise_scale = noise_scale
64
+ self.ny_shape = (n_pred_steps, y_dim)
65
+ self.l_w = loss_weights
66
+ self.flow_schedule = flow_schedule
67
+ self.exp_scale = exp_scale
68
+ self.snr_sampler = snr_sampler
69
+ if loss_type == "l2":
70
+ self.loss_fun = nn.MSELoss()
71
+ elif loss_type == "l1":
72
+ self.loss_fun = nn.L1Loss()
73
+ else:
74
+ raise NotImplementedError
75
+ return
76
+
77
+ def set_num_k_infer(self, num_k_infer: int):
78
+ self.num_k_infer = num_k_infer
79
+ return
80
+
81
+ def set_flow_schedule(self, flow_schedule: str, exp_scale: float):
82
+ self.flow_schedule = flow_schedule
83
+ self.exp_scale = exp_scale
84
+ return
85
+
86
+ def _norm_obs(self, pcd: torch.Tensor) -> torch.Tensor:
87
+ # I only do centering here, no scaling, to keep the relative distances and interpretability
88
+ pcd[..., :3] -= torch.tensor(self.norm_pcd_center, device=DEVICE)
89
+ return pcd
90
+
91
+ def _norm_robot_state(self, robot_state: torch.Tensor) -> torch.Tensor:
92
+ # I only do centering here, no scaling, to keep the relative distances and interpretability
93
+ robot_state[..., :3] -= torch.tensor(self.norm_pcd_center, device=DEVICE)
94
+ robot_state[..., 9] -= torch.tensor(0.5, device=DEVICE)
95
+ return robot_state
96
+
97
+ def _denorm_robot_state(self, robot_state: torch.Tensor) -> torch.Tensor:
98
+ robot_state[..., :3] += torch.tensor(self.norm_pcd_center, device=DEVICE)
99
+ robot_state[..., 9] += torch.tensor(0.5, device=DEVICE)
100
+ return robot_state
101
+
102
+ def _norm_data(self, batch: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
103
+ pcd, robot_state_obs, robot_state_pred = batch
104
+ pcd = self._norm_obs(pcd)
105
+ robot_state_obs = self._norm_robot_state(robot_state_obs)
106
+ robot_state_pred = self._norm_robot_state(robot_state_pred)
107
+ return pcd, robot_state_obs, robot_state_pred
108
+
109
+ def _augment_data(self, batch: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
110
+ return augment_pcd_data(batch)
111
+
112
+ def _init_noise(self, batch_size: int) -> torch.Tensor:
113
+ B = batch_size
114
+ T = self.n_pred_steps
115
+ if self.noise_type == "gaussian":
116
+ noise = torch.randn((batch_size, *self.ny_shape), device=DEVICE)
117
+ return noise * self.noise_scale
118
+ elif self.noise_type == "trajectory":
119
+ return init_random_traj_th(batch_size, self.n_pred_steps, self.noise_scale)
120
+ elif self.noise_type == "igso3":
121
+ noise_pos = torch.randn((B, T, 3), device=DEVICE)
122
+ noise_rot = pp.randn_SO3((B, T), device=DEVICE).matrix()
123
+ noise_gripper = torch.randn((B, T, 1), device=DEVICE)
124
+ noise = torch.cat(
125
+ [noise_pos, noise_rot[..., :3, 0], noise_rot[..., :3, 1], noise_gripper], dim=-1
126
+ )
127
+ return noise
128
+ else:
129
+ raise NotImplementedError
130
+
131
+ def _sample_snr(self, batch_size: int) -> torch.Tensor:
132
+ if self.snr_sampler == "uniform":
133
+ return torch.rand((batch_size, 1, 1), device=DEVICE)
134
+ elif self.snr_sampler == "logit_normal":
135
+ return torch.sigmoid(torch.randn((batch_size, 1, 1), device=DEVICE))
136
+ else:
137
+ raise NotImplementedError
138
+
139
+ # ############### Training ################
140
+
141
+ def forward(self, batch):
142
+ """batch is the output of the dataloader"""
143
+ return 0
144
+
145
+ def loss(self, outputs, batch: tuple[torch.Tensor, ...]) -> torch.Tensor:
146
+ """
147
+ outputs: the output of the forward pass
148
+ batch: the output of the dataloader
149
+ """
150
+ with torch.no_grad():
151
+ batch = self._norm_data(batch)
152
+ if self.augment_data:
153
+ batch = self._augment_data(batch)
154
+ pcd, robot_state_obs, robot_state_pred = batch
155
+ loss_xyz, loss_rot6d, loss_grip = self.calculate_loss(
156
+ pcd, robot_state_obs, robot_state_pred
157
+ )
158
+ loss = (
159
+ self.l_w["xyz"] * loss_xyz
160
+ + self.l_w["rot6d"] * loss_rot6d
161
+ + self.l_w["grip"] * loss_grip
162
+ )
163
+ self.logger.log_metrics(
164
+ {
165
+ "loss/train/xyz": loss_xyz.item(),
166
+ "loss/train/rot6d": loss_rot6d.item(),
167
+ "loss/train/grip": loss_grip.item(),
168
+ }
169
+ )
170
+ return loss
171
+
172
+ def calculate_loss(
173
+ self, pcd: torch.Tensor, robot_state_obs: torch.Tensor, robot_state_pred: torch.Tensor
174
+ ):
175
+ nx: torch.Tensor = self.obs_encoder(pcd, robot_state_obs)
176
+ ny: torch.Tensor = robot_state_pred
177
+
178
+ B = ny.shape[0]
179
+ t = self._sample_snr(B)
180
+ z0 = self._init_noise(ny.shape[0])
181
+ z1 = ny
182
+ z_t = t * z1 + (1.0 - t) * z0
183
+ target_vel = z1 - z0
184
+ timesteps = t.squeeze() * self.pos_emb_scale if self.time_conditioning else None
185
+ pred_vel = self.diffusion_net(z_t, timesteps, global_cond=nx)
186
+ loss_xyz = self.loss_fun(pred_vel[..., :3], target_vel[..., :3])
187
+ loss_rot6d = self.loss_fun(pred_vel[..., 3:9], target_vel[..., 3:9])
188
+ loss_grip = self.loss_fun(pred_vel[..., 9], target_vel[..., 9])
189
+ return loss_xyz, loss_rot6d, loss_grip
190
+
191
+ # ############### Inference ################
192
+
193
+ def eval_forward(self, batch: tuple[torch.Tensor, ...], outputs=None) -> torch.Tensor:
194
+ """
195
+ batch: the output of the eval dataloader
196
+ outputs: the output of the forward pass
197
+ """
198
+ batch = self._norm_data(batch)
199
+ pcd, robot_state_obs, robot_state_pred = batch
200
+
201
+ # Eval loss
202
+ loss_xyz, loss_rot6d, loss_grip = self.calculate_loss(
203
+ pcd, robot_state_obs, robot_state_pred
204
+ )
205
+ loss_total = (
206
+ self.l_w["xyz"] * loss_xyz
207
+ + self.l_w["rot6d"] * loss_rot6d
208
+ + self.l_w["grip"] * loss_grip
209
+ )
210
+ self.logger.log_metrics(
211
+ {
212
+ "loss/eval/xyz": loss_xyz.item(),
213
+ "loss/eval/rot6d": loss_rot6d.item(),
214
+ "loss/eval/grip": loss_grip.item(),
215
+ "loss/eval/total": loss_total.item(),
216
+ }
217
+ )
218
+
219
+ # Eval metrics
220
+ pred_y = self.infer_y(pcd, robot_state_obs)
221
+ mse_xyz = nn.functional.mse_loss(pred_y[..., :3], robot_state_pred[..., :3])
222
+ mse_rot6d = nn.functional.mse_loss(pred_y[..., 3:9], robot_state_pred[..., 3:9])
223
+ mse_grip = nn.functional.mse_loss(pred_y[..., 9], robot_state_pred[..., 9])
224
+ self.logger.log_metrics(
225
+ {
226
+ "metrics/eval/mse_xyz": mse_xyz.item(),
227
+ "metrics/eval/mse_rot6d": mse_rot6d.item(),
228
+ "metrics/eval/mse_grip": mse_grip.item(),
229
+ }
230
+ )
231
+ return pred_y
232
+
233
+ def infer_y(
234
+ self,
235
+ pcd: torch.Tensor,
236
+ robot_state_obs: torch.Tensor,
237
+ noise=None,
238
+ return_traj=False,
239
+ ) -> torch.Tensor:
240
+ nx: torch.Tensor = self.obs_encoder(pcd, robot_state_obs)
241
+ B = nx.shape[0]
242
+ z = self._init_noise(B) if noise is None else noise
243
+ traj = [z]
244
+ t0, dt = get_timesteps(self.flow_schedule, self.num_k_infer, exp_scale=self.exp_scale)
245
+ for i in range(self.num_k_infer):
246
+ timesteps = torch.ones((B), device=DEVICE) * t0[i]
247
+ timesteps *= self.pos_emb_scale
248
+ vel_pred = self.diffusion_net(z, timesteps, global_cond=nx)
249
+ z = z.detach().clone() + vel_pred * dt[i]
250
+ traj.append(z)
251
+
252
+ if return_traj:
253
+ return torch.stack(traj)
254
+ return traj[-1]
255
+
256
+ @classmethod
257
+ def load_from_checkpoint(
258
+ cls,
259
+ ckpt_name: str,
260
+ ckpt_episode: str,
261
+ num_k_infer: int,
262
+ flow_schedule: str = None,
263
+ exp_scale: float = None,
264
+ subs_factor: int = 1,
265
+ ):
266
+ ckpt_dir = REPO_DIRS.CKPT / ckpt_name
267
+ ckpt_path_list = list(ckpt_dir.glob(f"{ckpt_episode}*"))
268
+ assert len(ckpt_path_list) > 0, f"No checkpoint found in {ckpt_dir} with {ckpt_episode}"
269
+ assert len(ckpt_path_list) < 2, f"Multiple ckpts found in {ckpt_dir} with {ckpt_episode}"
270
+ ckpt_fpath = ckpt_path_list[0]
271
+
272
+ state_dict = torch.load(ckpt_fpath, map_location=DEVICE, weights_only=False)
273
+ cfg = OmegaConf.load(ckpt_dir / "config.yaml")
274
+ # cfg.model.obs_encoder.encoder.random_crop = False
275
+ cfg.model.subs_factor = subs_factor
276
+ assert cfg.model._target_.split(".")[-1] == cls.__name__
277
+ model: FMPolicy = hydra.utils.instantiate(cfg.model)
278
+ model.load_state_dict(state_dict["state"]["model"])
279
+ model.to(DEVICE)
280
+ model.eval()
281
+ if flow_schedule is not None:
282
+ model.set_flow_schedule(flow_schedule, exp_scale)
283
+ if num_k_infer is not None:
284
+ model.set_num_k_infer(num_k_infer)
285
+ return model
286
+
287
+
288
+ class FMPolicyImage(FMPolicy):
289
+
290
+ def _norm_obs(self, image: torch.Tensor) -> torch.Tensor:
291
+ """
292
+ Image normalization is already done in the backbone, so here we just make it float
293
+ """
294
+ image = image.float() / 255.0
295
+ return image
296
+
297
+ def _augment_data(self, batch: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
298
+ raise NotImplementedError
third_party/PointFlowMatch/pfp/policy/fm_se3_policy.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import hydra
3
+ import torch
4
+ import torch.nn as nn
5
+ import pypose as pp
6
+ from omegaconf import OmegaConf
7
+ from composer.models import ComposerModel
8
+ from pfp.policy.base_policy import BasePolicy
9
+ from pfp import DEVICE, REPO_DIRS
10
+ from pfp.common.se3_utils import pfp_to_pose_th
11
+ from pfp.common.fm_utils import get_timesteps
12
+
13
+
14
+ class FMSE3Policy(ComposerModel, BasePolicy):
15
+ def __init__(
16
+ self,
17
+ x_dim: int,
18
+ y_dim: int,
19
+ n_obs_steps: int,
20
+ n_pred_steps: int,
21
+ num_k_infer: int,
22
+ obs_encoder: nn.Module,
23
+ diffusion_net: nn.Module,
24
+ augment_data: bool,
25
+ loss_weights: dict[int],
26
+ norm_pcd_center: list,
27
+ loss_type: str,
28
+ pos_emb_scale: int = 20,
29
+ flow_schedule: str = "linear",
30
+ exp_scale: float = None,
31
+ ) -> None:
32
+ ComposerModel.__init__(self)
33
+ BasePolicy.__init__(self, n_obs_steps)
34
+ self.x_dim = x_dim
35
+ self.y_dim = y_dim
36
+ self.n_obs_steps = n_obs_steps
37
+ self.n_pred_steps = n_pred_steps
38
+ self.pos_emb_scale = pos_emb_scale
39
+ self.num_k_infer = num_k_infer
40
+ self.obs_encoder = obs_encoder
41
+ self.diffusion_net = diffusion_net
42
+ self.norm_pcd_center = norm_pcd_center
43
+ self.augment_data = augment_data
44
+ self.ny_shape = (n_pred_steps, y_dim)
45
+ self.l_w = loss_weights
46
+ self.flow_schedule = flow_schedule
47
+ self.exp_scale = exp_scale
48
+ if loss_type == "l2":
49
+ self.loss_fun = nn.MSELoss()
50
+ elif loss_type == "l1":
51
+ self.loss_fun = nn.L1Loss()
52
+ else:
53
+ raise NotImplementedError
54
+ return
55
+
56
+ def set_num_k_infer(self, num_k_infer: int):
57
+ self.num_k_infer = num_k_infer
58
+ return
59
+
60
+ def set_flow_schedule(self, flow_schedule: str, exp_scale: float):
61
+ self.flow_schedule = flow_schedule
62
+ self.exp_scale = exp_scale
63
+ return
64
+
65
+ def _norm_obs(self, pcd: torch.Tensor) -> torch.Tensor:
66
+ # I only do centering here, no scaling, to keep the relative distances and interpretability
67
+ pcd[..., :3] -= torch.tensor(self.norm_pcd_center, device=DEVICE)
68
+ return pcd
69
+
70
+ def _norm_robot_state(self, robot_state: torch.Tensor) -> torch.Tensor:
71
+ # I only do centering here, no scaling, to keep the relative distances and interpretability
72
+ robot_state[..., :3] -= torch.tensor(self.norm_pcd_center, device=DEVICE)
73
+ robot_state[..., 9] -= torch.tensor(0.5, device=DEVICE)
74
+ return robot_state
75
+
76
+ def _denorm_robot_state(self, robot_state: torch.Tensor) -> torch.Tensor:
77
+ robot_state[..., :3] += torch.tensor(self.norm_pcd_center, device=DEVICE)
78
+ robot_state[..., 9] += torch.tensor(0.5, device=DEVICE)
79
+ return robot_state
80
+
81
+ def _norm_data(self, batch: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
82
+ pcd, robot_state_obs, robot_state_pred = batch
83
+ pcd = self._norm_obs(pcd)
84
+ robot_state_obs = self._norm_robot_state(robot_state_obs)
85
+ robot_state_pred = self._norm_robot_state(robot_state_pred)
86
+ return pcd, robot_state_obs, robot_state_pred
87
+
88
+ def _rand_range(self, low: float, high: float, size: tuple[int]) -> torch.Tensor:
89
+ return torch.rand(size, device=DEVICE) * (high - low) + low
90
+
91
+ def _augment_data(self, batch: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
92
+ pcd, robot_state_obs, robot_state_pred = batch
93
+
94
+ # xyz1 = self._rand_range(low=0.8, high=1.2, size=(3,))
95
+ xyz2 = self._rand_range(low=-0.2, high=0.2, size=(3,))
96
+ pcd[..., :3] = pcd[..., :3] + xyz2 # * xyz1 + xyz2
97
+ robot_state_obs[..., :3] = robot_state_obs[..., :3] + xyz2 # * xyz1 + xyz2
98
+ robot_state_pred[..., :3] = robot_state_pred[..., :3] + xyz2 # * xyz1 + xyz2
99
+
100
+ # We shuffle the points, i.e. shuffle pcd along dim=2 (B, T, P, 3)
101
+ idx = torch.randperm(pcd.shape[2])
102
+ pcd = pcd[:, :, idx, :]
103
+ return pcd, robot_state_obs, robot_state_pred
104
+
105
+ def _init_noise(self, batch_size: int) -> tuple[pp.SE3, torch.Tensor]:
106
+ B = batch_size
107
+ T = self.n_pred_steps
108
+ noise_pp = pp.randn_SE3((B, T), device=DEVICE)
109
+ noise_gripper = torch.zeros((B, T, 1), device=DEVICE)
110
+ return noise_pp, noise_gripper
111
+
112
+ def _init_target(self, ny: torch.Tensor) -> tuple[pp.SE3, torch.Tensor]:
113
+ """
114
+ ny: (B, T, 10) -> xyz, rot6d, grip
115
+ """
116
+ poses_th, gripper_th = pfp_to_pose_th(ny) # (B, T, 4, 4)
117
+ poses_pp = pp.mat2SE3(poses_th, check=False) # (B, T, 7)
118
+ return poses_pp, gripper_th
119
+
120
+ def _pp_to_pfp(self, z_pp: pp.SE3, z_gripper: torch.Tensor) -> torch.Tensor:
121
+ """
122
+ Args:
123
+ z_pp: (B, T, 7) pp.SE3 pose
124
+ z_gripper: (B, T, 1) gripper
125
+ Returns:
126
+ z: (B, T, 10) pfp state
127
+ """
128
+ z = torch.zeros((*z_pp.shape[:-1], 10), device=DEVICE)
129
+ pose = pp.matrix(z_pp)
130
+ z[..., :3] = pose[..., :3, 3]
131
+ z[..., 3:9] = pose[..., :3, :2].mT.flatten(start_dim=-2)
132
+ z[..., 9:] = z_gripper
133
+ return z
134
+
135
+ # ############### Training ################
136
+
137
+ def forward(self, batch):
138
+ """batch is the output of the dataloader"""
139
+ return 0
140
+
141
+ def loss(self, outputs, batch: tuple[torch.Tensor, ...]) -> torch.Tensor:
142
+ """
143
+ outputs: the output of the forward pass
144
+ batch: the output of the dataloader
145
+ """
146
+ with torch.no_grad():
147
+ batch = self._norm_data(batch)
148
+ if self.augment_data:
149
+ batch = self._augment_data(batch)
150
+ pcd, robot_state_obs, robot_state_pred = batch
151
+ nx: torch.Tensor = self.obs_encoder(pcd, robot_state_obs)
152
+ ny: torch.Tensor = robot_state_pred
153
+
154
+ B = ny.shape[0]
155
+ T = ny.shape[1]
156
+
157
+ # Sample random time step
158
+ t_shape = (B, 1, 1)
159
+ t = torch.rand(t_shape, device=DEVICE)
160
+
161
+ # Initialize start and end poses + gripper state
162
+ z0_pp, z0_gripper = self._init_noise(B)
163
+ z1_pp, z1_gripper = self._init_target(ny)
164
+
165
+ # Calculate relative change between them
166
+ target_vel_pp = pp.Log(pp.Inv(z0_pp) @ z1_pp)
167
+ target_vel_gripper = z1_gripper - z0_gripper
168
+
169
+ # Move to intermediate step
170
+ zt_pp: pp.SE3 = z0_pp @ pp.Exp(target_vel_pp * t)
171
+ zt_gripper: torch.Tensor = z0_gripper + target_vel_gripper * t
172
+ # Convert to pfp network input representation
173
+ zt_pfp = self._pp_to_pfp(zt_pp, zt_gripper)
174
+ timesteps = t.squeeze() * self.pos_emb_scale
175
+
176
+ # Do prediction
177
+ pred_vel_pfp = self.diffusion_net(zt_pfp, timesteps, global_cond=nx)
178
+ assert pred_vel_pfp.shape == (B, T, 7)
179
+ pred_vel_pp = pred_vel_pfp[..., :6]
180
+ pred_vel_gripper = pred_vel_pfp[..., 6:]
181
+
182
+ # Calculate loss
183
+ loss_twist = self.loss_fun(pred_vel_pp, target_vel_pp)
184
+ loss_grip = self.loss_fun(pred_vel_gripper, target_vel_gripper)
185
+ loss = self.l_w["twist"] * loss_twist + self.l_w["grip"] * loss_grip
186
+ self.logger.log_metrics(
187
+ {
188
+ "loss/train/twist": loss_twist.item(),
189
+ "loss/train/grip": loss_grip.item(),
190
+ }
191
+ )
192
+ return loss
193
+
194
+ # ############### Inference ################
195
+
196
+ def eval_forward(self, batch: tuple[torch.Tensor, ...], outputs=None) -> torch.Tensor:
197
+ """
198
+ batch: the output of the eval dataloader
199
+ outputs: the output of the forward pass
200
+ """
201
+ batch = self._norm_data(batch)
202
+ pcd, robot_state_obs, robot_state_pred = batch
203
+ pred_y = self.infer_y(pcd, robot_state_obs)
204
+ mse_xyz = nn.functional.mse_loss(pred_y[..., :3], robot_state_pred[..., :3])
205
+ mse_rot6d = nn.functional.mse_loss(pred_y[..., 3:9], robot_state_pred[..., 3:9])
206
+ mse_grip = nn.functional.mse_loss(pred_y[..., 9], robot_state_pred[..., 9])
207
+ self.logger.log_metrics(
208
+ {
209
+ "metrics/eval/mse_xyz": mse_xyz.item(),
210
+ "metrics/eval/mse_rot6d": mse_rot6d.item(),
211
+ "metrics/eval/mse_grip": mse_grip.item(),
212
+ }
213
+ )
214
+ return pred_y
215
+
216
+ def infer_y(
217
+ self,
218
+ pcd: torch.Tensor,
219
+ robot_state_obs: torch.Tensor,
220
+ noise=None,
221
+ return_traj=False,
222
+ ) -> torch.Tensor:
223
+ nx: torch.Tensor = self.obs_encoder(pcd, robot_state_obs)
224
+ B = nx.shape[0]
225
+ z_pp, z_gripper = self._init_noise(B) if noise is None else noise
226
+ z = self._pp_to_pfp(z_pp, z_gripper)
227
+ traj = [z]
228
+ t0, dt = get_timesteps(self.flow_schedule, self.num_k_infer, exp_scale=self.exp_scale)
229
+ for i in range(self.num_k_infer):
230
+ t = torch.ones((B), device=DEVICE) * t0[i]
231
+ timesteps = t * self.pos_emb_scale
232
+ pred_vel_pfp = self.diffusion_net(z, timesteps, global_cond=nx)
233
+ pred_vel_pp = pp.se3(pred_vel_pfp[..., :6])
234
+ pred_vel_gripper = pred_vel_pfp[..., 6:]
235
+
236
+ z_pp = z_pp @ pp.Exp(pred_vel_pp * dt[i])
237
+ z_gripper = z_gripper + pred_vel_gripper * dt[i]
238
+
239
+ z = self._pp_to_pfp(z_pp, z_gripper)
240
+ traj.append(z)
241
+ return torch.stack(traj) if return_traj else traj[-1]
242
+
243
+ @classmethod
244
+ def load_from_checkpoint(
245
+ cls,
246
+ ckpt_name: str,
247
+ ckpt_episode: str,
248
+ num_k_infer: int,
249
+ flow_schedule: str = None,
250
+ exp_scale: float = None,
251
+ ):
252
+ ckpt_dir = REPO_DIRS.CKPT / ckpt_name
253
+ ckpt_path_list = list(ckpt_dir.glob(f"{ckpt_episode}*"))
254
+ assert len(ckpt_path_list) > 0, f"No checkpoint found in {ckpt_dir} with {ckpt_episode}"
255
+ assert len(ckpt_path_list) < 2, f"Multiple ckpts found in {ckpt_dir} with {ckpt_episode}"
256
+ ckpt_fpath = ckpt_path_list[0]
257
+
258
+ state_dict = torch.load(ckpt_fpath, map_location=DEVICE)
259
+ cfg = OmegaConf.load(ckpt_dir / "config.yaml")
260
+ # cfg.model.obs_encoder.encoder.random_crop = False
261
+ assert cfg.model._target_.split(".")[-1] == cls.__name__
262
+ model: FMSE3Policy = hydra.utils.instantiate(cfg.model)
263
+ model.load_state_dict(state_dict["state"]["model"])
264
+ model.to(DEVICE)
265
+ model.eval()
266
+ if flow_schedule is not None:
267
+ model.set_flow_schedule(flow_schedule, exp_scale)
268
+ if num_k_infer is not None:
269
+ model.set_num_k_infer(num_k_infer)
270
+ return model
third_party/PointFlowMatch/pfp/policy/fm_so3_policy.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import hydra
3
+ import torch
4
+ import torch.nn as nn
5
+ import pypose as pp
6
+ from omegaconf import OmegaConf
7
+ from composer.models import ComposerModel
8
+ from pfp.policy.base_policy import BasePolicy
9
+ from pfp import DEVICE, REPO_DIRS
10
+ from pfp.common.se3_utils import pfp_to_pose_th
11
+ from pfp.common.fm_utils import get_timesteps
12
+
13
+
14
+ class FMSO3Policy(ComposerModel, BasePolicy):
15
+ def __init__(
16
+ self,
17
+ x_dim: int,
18
+ y_dim: int,
19
+ n_obs_steps: int,
20
+ n_pred_steps: int,
21
+ num_k_infer: int,
22
+ obs_encoder: nn.Module,
23
+ diffusion_net: nn.Module,
24
+ augment_data: bool,
25
+ loss_weights: dict[int],
26
+ norm_pcd_center: list,
27
+ loss_type: str,
28
+ pos_emb_scale: int = 20,
29
+ flow_schedule: str = "linear",
30
+ exp_scale: float = None,
31
+ snr_sampler: str = "uniform",
32
+ noise_type: str = "uniform", # uniform | biased
33
+ ) -> None:
34
+ ComposerModel.__init__(self)
35
+ BasePolicy.__init__(self, n_obs_steps)
36
+ self.x_dim = x_dim
37
+ self.y_dim = y_dim
38
+ self.n_obs_steps = n_obs_steps
39
+ self.n_pred_steps = n_pred_steps
40
+ self.pos_emb_scale = pos_emb_scale
41
+ self.num_k_infer = num_k_infer
42
+ self.obs_encoder = obs_encoder
43
+ self.diffusion_net = diffusion_net
44
+ self.norm_pcd_center = norm_pcd_center
45
+ self.augment_data = augment_data
46
+ self.ny_shape = (n_pred_steps, y_dim)
47
+ self.l_w = loss_weights
48
+ self.flow_schedule = flow_schedule
49
+ self.exp_scale = exp_scale
50
+ self.snr_sampler = snr_sampler
51
+ self.noise_type = noise_type
52
+ if loss_type == "l2":
53
+ self.loss_fun = nn.MSELoss()
54
+ elif loss_type == "l1":
55
+ self.loss_fun = nn.L1Loss()
56
+ else:
57
+ raise NotImplementedError
58
+ return
59
+
60
+ def set_num_k_infer(self, num_k_infer: int):
61
+ self.num_k_infer = num_k_infer
62
+ return
63
+
64
+ def set_flow_schedule(self, flow_schedule: str, exp_scale: float):
65
+ self.flow_schedule = flow_schedule
66
+ self.exp_scale = exp_scale
67
+ return
68
+
69
+ def _norm_obs(self, pcd: torch.Tensor) -> torch.Tensor:
70
+ # I only do centering here, no scaling, to keep the relative distances and interpretability
71
+ pcd[..., :3] -= torch.tensor(self.norm_pcd_center, device=DEVICE)
72
+ return pcd
73
+
74
+ def _norm_robot_state(self, robot_state: torch.Tensor) -> torch.Tensor:
75
+ # I only do centering here, no scaling, to keep the relative distances and interpretability
76
+ robot_state[..., :3] -= torch.tensor(self.norm_pcd_center, device=DEVICE)
77
+ robot_state[..., 9] -= torch.tensor(0.5, device=DEVICE)
78
+ return robot_state
79
+
80
+ def _denorm_robot_state(self, robot_state: torch.Tensor) -> torch.Tensor:
81
+ robot_state[..., :3] += torch.tensor(self.norm_pcd_center, device=DEVICE)
82
+ robot_state[..., 9] += torch.tensor(0.5, device=DEVICE)
83
+ return robot_state
84
+
85
+ def _norm_data(self, batch: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
86
+ pcd, robot_state_obs, robot_state_pred = batch
87
+ pcd = self._norm_obs(pcd)
88
+ robot_state_obs = self._norm_robot_state(robot_state_obs)
89
+ robot_state_pred = self._norm_robot_state(robot_state_pred)
90
+ return pcd, robot_state_obs, robot_state_pred
91
+
92
+ def _rand_range(self, low: float, high: float, size: tuple[int]) -> torch.Tensor:
93
+ return torch.rand(size, device=DEVICE) * (high - low) + low
94
+
95
+ def _augment_data(self, batch: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
96
+ pcd, robot_state_obs, robot_state_pred = batch
97
+
98
+ # xyz1 = self._rand_range(low=0.8, high=1.2, size=(3,))
99
+ xyz2 = self._rand_range(low=-0.2, high=0.2, size=(3,))
100
+ pcd[..., :3] = pcd[..., :3] + xyz2 # * xyz1 + xyz2
101
+ robot_state_obs[..., :3] = robot_state_obs[..., :3] + xyz2 # * xyz1 + xyz2
102
+ robot_state_pred[..., :3] = robot_state_pred[..., :3] + xyz2 # * xyz1 + xyz2
103
+
104
+ # We shuffle the points, i.e. shuffle pcd along dim=2 (B, T, P, 3)
105
+ idx = torch.randperm(pcd.shape[2])
106
+ pcd = pcd[:, :, idx, :]
107
+ return pcd, robot_state_obs, robot_state_pred
108
+
109
+ def _init_noise(
110
+ self, batch_size: int, robot_state_obs: torch.Tensor
111
+ ) -> tuple[torch.Tensor, pp.SO3, torch.Tensor]:
112
+ B = batch_size
113
+ T = self.n_pred_steps
114
+ noise_xyz = torch.randn((B, T, 3), device=DEVICE)
115
+ noise_gripper = torch.randn((B, T, 1), device=DEVICE)
116
+ if self.noise_type == "uniform":
117
+ noise_SO3 = pp.randn_SO3((B, T), device=DEVICE)
118
+ elif self.noise_type == "biased":
119
+ random_euler = torch.FloatTensor(B, T, 3).uniform_(-torch.pi / 2, torch.pi / 2)
120
+ random_so3 = pp.Log(pp.euler2SO3(random_euler.to(DEVICE)))
121
+ _, cur_SO3, _ = self._pfp_to_pp(robot_state_obs)
122
+ start_SO3 = cur_SO3[:, -1:, :].expand(B, T, 4) # Just take the current pose
123
+ noise_SO3 = start_SO3 @ pp.Exp(random_so3)
124
+ else:
125
+ raise NotImplementedError
126
+ return noise_xyz, noise_SO3, noise_gripper
127
+
128
+ def _pfp_to_pp(self, pfp_state: torch.Tensor) -> tuple[pp.SE3, torch.Tensor]:
129
+ """
130
+ pfp_state: (B, T, 10) -> xyz, rot6d, grip
131
+ """
132
+ poses_th, gripper_th = pfp_to_pose_th(pfp_state) # (B, T, 4, 4)
133
+ xyz = poses_th[..., :3, 3]
134
+ rot_SO3 = pp.mat2SO3(poses_th[..., :3, :3], check=False) # (B, T, 4)
135
+ gripper = gripper_th
136
+ return xyz, rot_SO3, gripper
137
+
138
+ def _sample_snr(self, batch_size: int) -> torch.Tensor:
139
+ if self.snr_sampler == "uniform":
140
+ return torch.rand((batch_size, 1, 1), device=DEVICE)
141
+ elif self.snr_sampler == "logit_normal":
142
+ return torch.sigmoid(torch.randn((batch_size, 1, 1), device=DEVICE))
143
+ else:
144
+ raise NotImplementedError
145
+
146
+ def _pp_to_pfp(
147
+ self, z_xyz: torch.Tensor, z_SO3: pp.SO3, z_gripper: torch.Tensor
148
+ ) -> torch.Tensor:
149
+ """
150
+ Args:
151
+ z_xyz: (B, T, 3) xyz
152
+ z_SO3: (B, T, 4) pp.SO3 rotation
153
+ z_gripper: (B, T, 1) gripper
154
+ Returns:
155
+ z: (B, T, 10) pfp state
156
+ """
157
+ B, T, _ = z_xyz.shape
158
+ z = torch.zeros((B, T, 10), device=DEVICE)
159
+ rot = pp.matrix(z_SO3)
160
+ z[..., :3] = z_xyz
161
+ z[..., 3:9] = rot[..., :3, :2].mT.flatten(start_dim=-2)
162
+ z[..., 9:] = z_gripper
163
+ return z
164
+
165
+ # ############### Training ################
166
+
167
+ def forward(self, batch):
168
+ """batch is the output of the dataloader"""
169
+ return 0
170
+
171
+ def loss(self, outputs, batch: tuple[torch.Tensor, ...]) -> torch.Tensor:
172
+ """
173
+ outputs: the output of the forward pass
174
+ batch: the output of the dataloader
175
+ """
176
+ with torch.no_grad():
177
+ batch = self._norm_data(batch)
178
+ if self.augment_data:
179
+ batch = self._augment_data(batch)
180
+ pcd, robot_state_obs, robot_state_pred = batch
181
+ loss_xyz, loss_so3, loss_grip = self.calculate_loss(pcd, robot_state_obs, robot_state_pred)
182
+ loss = (
183
+ self.l_w["xyz"] * loss_xyz + self.l_w["so3"] * loss_so3 + self.l_w["grip"] * loss_grip
184
+ )
185
+ self.logger.log_metrics(
186
+ {
187
+ "loss/train/xyz": loss_xyz.item(),
188
+ "loss/train/so3": loss_so3.item(),
189
+ "loss/train/grip": loss_grip.item(),
190
+ }
191
+ )
192
+ return loss
193
+
194
+ def calculate_loss(
195
+ self, pcd: torch.Tensor, robot_state_obs: torch.Tensor, robot_state_pred: torch.Tensor
196
+ ):
197
+ nx: torch.Tensor = self.obs_encoder(pcd, robot_state_obs)
198
+ ny: torch.Tensor = robot_state_pred
199
+
200
+ B = ny.shape[0]
201
+ T = ny.shape[1]
202
+
203
+ # Sample random time step
204
+ t = self._sample_snr(B)
205
+
206
+ # Initialize start and end poses + gripper state
207
+ z0_xyz, z0_SO3, z0_gripper = self._init_noise(B, robot_state_obs)
208
+ z1_xyz, z1_SO3, z1_gripper = self._pfp_to_pp(ny)
209
+
210
+ # Calculate relative change between them
211
+ target_vel_xyz = z1_xyz - z0_xyz
212
+ target_vel_so3 = pp.Log(pp.Inv(z0_SO3) @ z1_SO3)
213
+ target_vel_gripper = z1_gripper - z0_gripper
214
+
215
+ # Move to intermediate step
216
+ zt_xyz = z0_xyz + target_vel_xyz * t
217
+ zt_SO3: pp.SO3 = z0_SO3 @ pp.Exp(target_vel_so3 * t)
218
+ zt_gripper: torch.Tensor = z0_gripper + target_vel_gripper * t
219
+
220
+ # Convert to pfp network input representation
221
+ zt_pfp = self._pp_to_pfp(zt_xyz, zt_SO3, zt_gripper)
222
+ timesteps = t.squeeze() * self.pos_emb_scale
223
+
224
+ # Do prediction
225
+ pred_vel_pfp = self.diffusion_net(zt_pfp, timesteps, global_cond=nx)
226
+ assert pred_vel_pfp.shape == (B, T, 7)
227
+ pred_vel_xyz = pred_vel_pfp[..., :3]
228
+ pred_vel_so3 = pred_vel_pfp[..., 3:6]
229
+ pred_vel_gripper = pred_vel_pfp[..., 6:]
230
+
231
+ # Calculate loss
232
+ loss_xyz = self.loss_fun(pred_vel_xyz, target_vel_xyz)
233
+ loss_so3 = self.loss_fun(pred_vel_so3, target_vel_so3)
234
+ loss_grip = self.loss_fun(pred_vel_gripper, target_vel_gripper)
235
+ return loss_xyz, loss_so3, loss_grip
236
+
237
+ # ############### Inference ################
238
+
239
+ def eval_forward(self, batch: tuple[torch.Tensor, ...], outputs=None) -> torch.Tensor:
240
+ """
241
+ batch: the output of the eval dataloader
242
+ outputs: the output of the forward pass
243
+ """
244
+ batch = self._norm_data(batch)
245
+ pcd, robot_state_obs, robot_state_pred = batch
246
+
247
+ # Eval loss
248
+ loss_xyz, loss_so3, loss_grip = self.calculate_loss(pcd, robot_state_obs, robot_state_pred)
249
+ loss_total = (
250
+ self.l_w["xyz"] * loss_xyz + self.l_w["so3"] * loss_so3 + self.l_w["grip"] * loss_grip
251
+ )
252
+ self.logger.log_metrics(
253
+ {
254
+ "loss/eval/xyz": loss_xyz.item(),
255
+ "loss/eval/so3": loss_so3.item(),
256
+ "loss/eval/grip": loss_grip.item(),
257
+ "loss/eval/total": loss_total.item(),
258
+ }
259
+ )
260
+
261
+ # Eval metrics
262
+ pred_y = self.infer_y(pcd, robot_state_obs)
263
+ mse_xyz = nn.functional.mse_loss(pred_y[..., :3], robot_state_pred[..., :3])
264
+ mse_rot6d = nn.functional.mse_loss(pred_y[..., 3:9], robot_state_pred[..., 3:9])
265
+ mse_grip = nn.functional.mse_loss(pred_y[..., 9], robot_state_pred[..., 9])
266
+ self.logger.log_metrics(
267
+ {
268
+ "metrics/eval/mse_xyz": mse_xyz.item(),
269
+ "metrics/eval/mse_rot6d": mse_rot6d.item(),
270
+ "metrics/eval/mse_grip": mse_grip.item(),
271
+ }
272
+ )
273
+ return pred_y
274
+
275
+ def infer_y(
276
+ self,
277
+ pcd: torch.Tensor,
278
+ robot_state_obs: torch.Tensor,
279
+ noise=None,
280
+ return_traj=False,
281
+ ) -> torch.Tensor:
282
+ nx: torch.Tensor = self.obs_encoder(pcd, robot_state_obs)
283
+ B = nx.shape[0]
284
+ z_xyz, z_SO3, z_gripper = self._init_noise(B, robot_state_obs) if noise is None else noise
285
+ z = self._pp_to_pfp(z_xyz, z_SO3, z_gripper)
286
+ traj = [z]
287
+ t0, dt = get_timesteps(self.flow_schedule, self.num_k_infer, exp_scale=self.exp_scale)
288
+ for i in range(self.num_k_infer):
289
+ t = torch.ones((B), device=DEVICE) * t0[i]
290
+ timesteps = t * self.pos_emb_scale
291
+ pred_vel_pfp = self.diffusion_net(z, timesteps, global_cond=nx)
292
+ pred_vel_xyz = pred_vel_pfp[..., :3]
293
+ pred_vel_so3 = pp.so3(pred_vel_pfp[..., 3:6])
294
+ pred_vel_gripper = pred_vel_pfp[..., 6:]
295
+
296
+ z_xyz = z_xyz + pred_vel_xyz * dt[i]
297
+ z_SO3 = z_SO3 @ pp.Exp(pred_vel_so3 * dt[i])
298
+ z_gripper = z_gripper + pred_vel_gripper * dt[i]
299
+
300
+ z = self._pp_to_pfp(z_xyz, z_SO3, z_gripper)
301
+ traj.append(z)
302
+ return torch.stack(traj) if return_traj else traj[-1]
303
+
304
+ @classmethod
305
+ def load_from_checkpoint(
306
+ cls,
307
+ ckpt_name: str,
308
+ ckpt_episode: str,
309
+ num_k_infer: int,
310
+ flow_schedule: str = None,
311
+ exp_scale: float = None,
312
+ ):
313
+ ckpt_dir = REPO_DIRS.CKPT / ckpt_name
314
+ ckpt_path_list = list(ckpt_dir.glob(f"{ckpt_episode}*"))
315
+ assert len(ckpt_path_list) > 0, f"No checkpoint found in {ckpt_dir} with {ckpt_episode}"
316
+ assert len(ckpt_path_list) < 2, f"Multiple ckpts found in {ckpt_dir} with {ckpt_episode}"
317
+ ckpt_fpath = ckpt_path_list[0]
318
+
319
+ state_dict = torch.load(ckpt_fpath, map_location=DEVICE)
320
+ cfg = OmegaConf.load(ckpt_dir / "config.yaml")
321
+ # cfg.model.obs_encoder.encoder.random_crop = False
322
+ assert cfg.model._target_.split(".")[-1] == cls.__name__
323
+ model: FMSO3Policy = hydra.utils.instantiate(cfg.model)
324
+ model.load_state_dict(state_dict["state"]["model"])
325
+ model.to(DEVICE)
326
+ model.eval()
327
+ if flow_schedule is not None:
328
+ model.set_flow_schedule(flow_schedule, exp_scale)
329
+ if num_k_infer is not None:
330
+ model.set_num_k_infer(num_k_infer)
331
+ return model
332
+
333
+
334
+ class FMSO3PolicyImage(FMSO3Policy):
335
+
336
+ def _norm_obs(self, image: torch.Tensor) -> torch.Tensor:
337
+ """
338
+ Image normalization is already done in the backbone, so here we just make it float
339
+ """
340
+ image = image.float() / 255.0
341
+ return image
third_party/PointFlowMatch/pfp/policy/fm_so3delta_policy.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import hydra
3
+ import torch
4
+ import torch.nn as nn
5
+ import pypose as pp
6
+ from omegaconf import OmegaConf
7
+ from composer.models import ComposerModel
8
+ from pfp.policy.base_policy import BasePolicy
9
+ from pfp import DEVICE, REPO_DIRS
10
+ from pfp.common.se3_utils import pfp_to_pose_th, grahm_schmidt_th
11
+ from pfp.common.fm_utils import get_timesteps
12
+
13
+
14
+ class FMSO3DeltaPolicy(ComposerModel, BasePolicy):
15
+ def __init__(
16
+ self,
17
+ x_dim: int,
18
+ y_dim: int,
19
+ n_obs_steps: int,
20
+ n_pred_steps: int,
21
+ num_k_infer: int,
22
+ obs_encoder: nn.Module,
23
+ diffusion_net: nn.Module,
24
+ augment_data: bool,
25
+ loss_weights: dict[int],
26
+ norm_pcd_center: list,
27
+ loss_type: str,
28
+ pos_emb_scale: int = 20,
29
+ flow_schedule: str = "linear",
30
+ exp_scale: float = None,
31
+ ) -> None:
32
+ ComposerModel.__init__(self)
33
+ BasePolicy.__init__(self, n_obs_steps)
34
+ self.x_dim = x_dim
35
+ self.y_dim = y_dim
36
+ self.n_obs_steps = n_obs_steps
37
+ self.n_pred_steps = n_pred_steps
38
+ self.pos_emb_scale = pos_emb_scale
39
+ self.num_k_infer = num_k_infer
40
+ self.obs_encoder = obs_encoder
41
+ self.diffusion_net = diffusion_net
42
+ self.norm_pcd_center = norm_pcd_center
43
+ self.augment_data = augment_data
44
+ self.ny_shape = (n_pred_steps, y_dim)
45
+ self.l_w = loss_weights
46
+ self.flow_schedule = flow_schedule
47
+ self.exp_scale = exp_scale
48
+ if loss_type == "l2":
49
+ self.loss_fun = nn.MSELoss()
50
+ elif loss_type == "l1":
51
+ self.loss_fun = nn.L1Loss()
52
+ else:
53
+ raise NotImplementedError
54
+ return
55
+
56
+ def set_num_k_infer(self, num_k_infer: int):
57
+ self.num_k_infer = num_k_infer
58
+ return
59
+
60
+ def set_flow_schedule(self, flow_schedule: str, exp_scale: float):
61
+ self.flow_schedule = flow_schedule
62
+ self.exp_scale = exp_scale
63
+ return
64
+
65
+ def _norm_obs(self, pcd: torch.Tensor) -> torch.Tensor:
66
+ # I only do centering here, no scaling, to keep the relative distances and interpretability
67
+ pcd[..., :3] -= torch.tensor(self.norm_pcd_center, device=DEVICE)
68
+ return pcd
69
+
70
+ def _norm_robot_state(self, robot_state: torch.Tensor) -> torch.Tensor:
71
+ # I only do centering here, no scaling, to keep the relative distances and interpretability
72
+ robot_state[..., :3] -= torch.tensor(self.norm_pcd_center, device=DEVICE)
73
+ robot_state[..., 9] -= torch.tensor(0.5, device=DEVICE)
74
+ return robot_state
75
+
76
+ def _denorm_robot_state(self, robot_state: torch.Tensor) -> torch.Tensor:
77
+ robot_state[..., :3] += torch.tensor(self.norm_pcd_center, device=DEVICE)
78
+ robot_state[..., 9] += torch.tensor(0.5, device=DEVICE)
79
+ return robot_state
80
+
81
+ def _norm_data(self, batch: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
82
+ pcd, robot_state_obs, robot_state_pred = batch
83
+ pcd = self._norm_obs(pcd)
84
+ robot_state_obs = self._norm_robot_state(robot_state_obs)
85
+ robot_state_pred = self._norm_robot_state(robot_state_pred)
86
+ return pcd, robot_state_obs, robot_state_pred
87
+
88
+ def _rand_range(self, low: float, high: float, size: tuple[int]) -> torch.Tensor:
89
+ return torch.rand(size, device=DEVICE) * (high - low) + low
90
+
91
+ def _augment_data(self, batch: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
92
+ pcd, robot_state_obs, robot_state_pred = batch
93
+
94
+ # xyz1 = self._rand_range(low=0.8, high=1.2, size=(3,))
95
+ xyz2 = self._rand_range(low=-0.2, high=0.2, size=(3,))
96
+ pcd[..., :3] = pcd[..., :3] + xyz2 # * xyz1 + xyz2
97
+ robot_state_obs[..., :3] = robot_state_obs[..., :3] + xyz2 # * xyz1 + xyz2
98
+ robot_state_pred[..., :3] = robot_state_pred[..., :3] + xyz2 # * xyz1 + xyz2
99
+
100
+ # We shuffle the points, i.e. shuffle pcd along dim=2 (B, T, P, 3)
101
+ idx = torch.randperm(pcd.shape[2])
102
+ pcd = pcd[:, :, idx, :]
103
+ return pcd, robot_state_obs, robot_state_pred
104
+
105
+ def _init_noise(self, batch_size: int) -> tuple[torch.Tensor, pp.SO3, torch.Tensor]:
106
+ B = batch_size
107
+ T = self.n_pred_steps
108
+ noise_xyz = torch.randn((B, T, 3), device=DEVICE)
109
+ noise_SO3 = pp.randn_SO3((B, T), device=DEVICE)
110
+ noise_gripper = torch.randn((B, T, 1), device=DEVICE)
111
+ return noise_xyz, noise_SO3, noise_gripper
112
+
113
+ def _init_target(self, ny: torch.Tensor) -> tuple[pp.SE3, torch.Tensor]:
114
+ """
115
+ ny: (B, T, 10) -> xyz, rot6d, grip
116
+ """
117
+ poses_th, gripper_th = pfp_to_pose_th(ny) # (B, T, 4, 4)
118
+ target_xyz = poses_th[..., :3, 3]
119
+ target_SO3 = pp.mat2SO3(poses_th[..., :3, :3], check=False) # (B, T, 4)
120
+ target_gripper = gripper_th
121
+ return target_xyz, target_SO3, target_gripper
122
+
123
+ def _pp_to_pfp(
124
+ self, z_xyz: torch.Tensor, z_SO3: pp.SO3, z_gripper: torch.Tensor
125
+ ) -> torch.Tensor:
126
+ """
127
+ Args:
128
+ z_xyz: (B, T, 3) xyz
129
+ z_SO3: (B, T, 4) pp.SO3 rotation
130
+ z_gripper: (B, T, 1) gripper
131
+ Returns:
132
+ z: (B, T, 10) pfp state
133
+ """
134
+ B, T, _ = z_xyz.shape
135
+ z = torch.zeros((B, T, 10), device=DEVICE)
136
+ rot = pp.matrix(z_SO3)
137
+ z[..., :3] = z_xyz
138
+ z[..., 3:9] = rot[..., :3, :2].mT.flatten(start_dim=-2)
139
+ z[..., 9:] = z_gripper
140
+ return z
141
+
142
+ # ############### Training ################
143
+
144
+ def forward(self, batch):
145
+ """batch is the output of the dataloader"""
146
+ return 0
147
+
148
+ def loss(self, outputs, batch: tuple[torch.Tensor, ...]) -> torch.Tensor:
149
+ """
150
+ outputs: the output of the forward pass
151
+ batch: the output of the dataloader
152
+ """
153
+ with torch.no_grad():
154
+ batch = self._norm_data(batch)
155
+ if self.augment_data:
156
+ batch = self._augment_data(batch)
157
+ pcd, robot_state_obs, robot_state_pred = batch
158
+ loss_xyz, loss_rot6d, loss_grip = self.calculate_loss(
159
+ pcd, robot_state_obs, robot_state_pred
160
+ )
161
+ loss = (
162
+ self.l_w["xyz"] * loss_xyz
163
+ + self.l_w["rot6d"] * loss_rot6d
164
+ + self.l_w["grip"] * loss_grip
165
+ )
166
+ self.logger.log_metrics(
167
+ {
168
+ "loss/train/xyz": loss_xyz.item(),
169
+ "loss/train/rot6d": loss_rot6d.item(),
170
+ "loss/train/grip": loss_grip.item(),
171
+ }
172
+ )
173
+ return loss
174
+
175
+ def calculate_loss(
176
+ self, pcd: torch.Tensor, robot_state_obs: torch.Tensor, robot_state_pred: torch.Tensor
177
+ ):
178
+ nx: torch.Tensor = self.obs_encoder(pcd, robot_state_obs)
179
+ ny: torch.Tensor = robot_state_pred
180
+
181
+ B = ny.shape[0]
182
+ T = ny.shape[1]
183
+
184
+ # Sample random time step
185
+ t_shape = (B, 1, 1)
186
+ t = torch.rand(t_shape, device=DEVICE)
187
+
188
+ # Initialize start and end poses + gripper state
189
+ z0_xyz, z0_SO3, z0_gripper = self._init_noise(B)
190
+ z1_xyz, z1_SO3, z1_gripper = self._init_target(ny)
191
+
192
+ # Calculate relative change between them
193
+ target_vel_xyz = z1_xyz - z0_xyz
194
+ target_delta_SO3 = pp.Inv(z0_SO3) @ z1_SO3
195
+ target_delta_R = pp.matrix(target_delta_SO3)[..., :3, :2].mT.flatten(start_dim=-2)
196
+ target_vel_so3 = pp.Log(target_delta_SO3)
197
+ target_vel_gripper = z1_gripper - z0_gripper
198
+
199
+ # Move to intermediate step
200
+ zt_xyz = z0_xyz + target_vel_xyz * t
201
+ zt_SO3: pp.SO3 = z0_SO3 @ pp.Exp(target_vel_so3 * t)
202
+ zt_gripper: torch.Tensor = z0_gripper + target_vel_gripper * t
203
+
204
+ # Convert to pfp network input representation
205
+ zt_pfp = self._pp_to_pfp(zt_xyz, zt_SO3, zt_gripper)
206
+ timesteps = t.squeeze() * self.pos_emb_scale
207
+
208
+ # Do prediction
209
+ pred_vel_pfp = self.diffusion_net(zt_pfp, timesteps, global_cond=nx)
210
+ assert pred_vel_pfp.shape == (B, T, 10)
211
+ pred_vel_xyz = pred_vel_pfp[..., :3]
212
+ pred_delta_R = pred_vel_pfp[..., 3:9]
213
+ # TODO: you could do gram schmidt here as well
214
+ pred_vel_gripper = pred_vel_pfp[..., 9:]
215
+
216
+ # Calculate loss
217
+ loss_xyz = self.loss_fun(pred_vel_xyz, target_vel_xyz)
218
+ loss_rot6d = self.loss_fun(pred_delta_R, target_delta_R)
219
+ loss_grip = self.loss_fun(pred_vel_gripper, target_vel_gripper)
220
+ return loss_xyz, loss_rot6d, loss_grip
221
+
222
+ # ############### Inference ################
223
+
224
+ def eval_forward(self, batch: tuple[torch.Tensor, ...], outputs=None) -> torch.Tensor:
225
+ """
226
+ batch: the output of the eval dataloader
227
+ outputs: the output of the forward pass
228
+ """
229
+ batch = self._norm_data(batch)
230
+ pcd, robot_state_obs, robot_state_pred = batch
231
+
232
+ # Eval loss
233
+ loss_xyz, loss_rot6d, loss_grip = self.calculate_loss(
234
+ pcd, robot_state_obs, robot_state_pred
235
+ )
236
+ loss_total = (
237
+ self.l_w["xyz"] * loss_xyz
238
+ + self.l_w["rot6d"] * loss_rot6d
239
+ + self.l_w["grip"] * loss_grip
240
+ )
241
+ self.logger.log_metrics(
242
+ {
243
+ "loss/eval/xyz": loss_xyz.item(),
244
+ "loss/eval/rot6d": loss_rot6d.item(),
245
+ "loss/eval/grip": loss_grip.item(),
246
+ "loss/eval/total": loss_total.item(),
247
+ }
248
+ )
249
+
250
+ # Eval metrics
251
+ pred_y = self.infer_y(pcd, robot_state_obs)
252
+ mse_xyz = nn.functional.mse_loss(pred_y[..., :3], robot_state_pred[..., :3])
253
+ mse_rot6d = nn.functional.mse_loss(pred_y[..., 3:9], robot_state_pred[..., 3:9])
254
+ mse_grip = nn.functional.mse_loss(pred_y[..., 9], robot_state_pred[..., 9])
255
+ self.logger.log_metrics(
256
+ {
257
+ "metrics/eval/mse_xyz": mse_xyz.item(),
258
+ "metrics/eval/mse_rot6d": mse_rot6d.item(),
259
+ "metrics/eval/mse_grip": mse_grip.item(),
260
+ }
261
+ )
262
+ return pred_y
263
+
264
+ def infer_y(
265
+ self,
266
+ pcd: torch.Tensor,
267
+ robot_state_obs: torch.Tensor,
268
+ noise=None,
269
+ return_traj=False,
270
+ ) -> torch.Tensor:
271
+ nx: torch.Tensor = self.obs_encoder(pcd, robot_state_obs)
272
+ B = nx.shape[0]
273
+ z_xyz, z_SO3, z_gripper = self._init_noise(B) if noise is None else noise
274
+ z = self._pp_to_pfp(z_xyz, z_SO3, z_gripper)
275
+ traj = [z]
276
+ t0, dt = get_timesteps(self.flow_schedule, self.num_k_infer, exp_scale=self.exp_scale)
277
+ for i in range(self.num_k_infer):
278
+ t = torch.ones((B), device=DEVICE) * t0[i]
279
+ timesteps = t * self.pos_emb_scale
280
+ pred_vel_pfp = self.diffusion_net(z, timesteps, global_cond=nx)
281
+ pred_vel_xyz = pred_vel_pfp[..., :3]
282
+ pred_delta_R = grahm_schmidt_th(pred_vel_pfp[..., 3:6], pred_vel_pfp[..., 6:9])
283
+ pred_delta_SO3 = pp.mat2SO3(pred_delta_R, check=False)
284
+ pred_vel_so3 = pp.Log(pred_delta_SO3)
285
+ pred_vel_gripper = pred_vel_pfp[..., 9:]
286
+
287
+ z_xyz = z_xyz + pred_vel_xyz * dt[i]
288
+ z_SO3 = z_SO3 @ pp.Exp(pred_vel_so3 * dt[i])
289
+ z_gripper = z_gripper + pred_vel_gripper * dt[i]
290
+
291
+ z = self._pp_to_pfp(z_xyz, z_SO3, z_gripper)
292
+ traj.append(z)
293
+ return torch.stack(traj) if return_traj else traj[-1]
294
+
295
+ @classmethod
296
+ def load_from_checkpoint(
297
+ cls,
298
+ ckpt_name: str,
299
+ ckpt_episode: str,
300
+ num_k_infer: int,
301
+ flow_schedule: str = None,
302
+ exp_scale: float = None,
303
+ ):
304
+ ckpt_dir = REPO_DIRS.CKPT / ckpt_name
305
+ ckpt_path_list = list(ckpt_dir.glob(f"{ckpt_episode}*"))
306
+ assert len(ckpt_path_list) > 0, f"No checkpoint found in {ckpt_dir} with {ckpt_episode}"
307
+ assert len(ckpt_path_list) < 2, f"Multiple ckpts found in {ckpt_dir} with {ckpt_episode}"
308
+ ckpt_fpath = ckpt_path_list[0]
309
+
310
+ state_dict = torch.load(ckpt_fpath, map_location=DEVICE)
311
+ cfg = OmegaConf.load(ckpt_dir / "config.yaml")
312
+ # cfg.model.obs_encoder.encoder.random_crop = False
313
+ assert cfg.model._target_.split(".")[-1] == cls.__name__
314
+ model: FMSO3DeltaPolicy = hydra.utils.instantiate(cfg.model)
315
+ model.load_state_dict(state_dict["state"]["model"])
316
+ model.to(DEVICE)
317
+ model.eval()
318
+ if flow_schedule is not None:
319
+ model.set_flow_schedule(flow_schedule, exp_scale)
320
+ if num_k_infer is not None:
321
+ model.set_num_k_infer(num_k_infer)
322
+ return model
323
+
324
+
325
+ class FMSO3DeltaPolicyImage(FMSO3DeltaPolicy):
326
+
327
+ def _norm_obs(self, image: torch.Tensor) -> torch.Tensor:
328
+ """
329
+ Image normalization is already done in the backbone, so here we just make it float
330
+ """
331
+ image = image.float() / 255.0
332
+ return image
third_party/PointFlowMatch/pfp/policy/fm_target_policy.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import hydra
3
+ import torch
4
+ import torch.nn as nn
5
+ import pypose as pp
6
+ from omegaconf import OmegaConf
7
+ from composer.models import ComposerModel
8
+ from pfp.policy.base_policy import BasePolicy
9
+ from pfp import DEVICE, REPO_DIRS
10
+ from pfp.common.se3_utils import pfp_to_pose_th
11
+ from pfp.common.fm_utils import get_timesteps
12
+
13
+
14
+ class FMTargetPolicy(ComposerModel, BasePolicy):
15
+ def __init__(
16
+ self,
17
+ x_dim: int,
18
+ y_dim: int,
19
+ n_obs_steps: int,
20
+ n_pred_steps: int,
21
+ num_k_infer: int,
22
+ time_conditioning: bool,
23
+ obs_encoder: nn.Module,
24
+ diffusion_net: nn.Module,
25
+ augment_data: bool,
26
+ loss_weights: dict[int],
27
+ norm_pcd_center: list,
28
+ loss_type: str,
29
+ pos_emb_scale: int = 20,
30
+ flow_schedule: str = "linear",
31
+ exp_scale: float = None,
32
+ ) -> None:
33
+ ComposerModel.__init__(self)
34
+ BasePolicy.__init__(self, n_obs_steps)
35
+ self.x_dim = x_dim
36
+ self.y_dim = y_dim
37
+ self.n_obs_steps = n_obs_steps
38
+ self.n_pred_steps = n_pred_steps
39
+ self.pos_emb_scale = pos_emb_scale
40
+ self.num_k_infer = num_k_infer
41
+ self.time_conditioning = time_conditioning
42
+ self.obs_encoder = obs_encoder
43
+ self.diffusion_net = diffusion_net
44
+ self.norm_pcd_center = norm_pcd_center
45
+ self.augment_data = augment_data
46
+ self.ny_shape = (n_pred_steps, y_dim)
47
+ self.l_w = loss_weights
48
+ self.flow_schedule = flow_schedule
49
+ self.exp_scale = exp_scale
50
+ if loss_type == "l2":
51
+ self.loss_fun = nn.MSELoss()
52
+ elif loss_type == "l1":
53
+ self.loss_fun = nn.L1Loss()
54
+ else:
55
+ raise NotImplementedError
56
+ return
57
+
58
+ def set_num_k_infer(self, num_k_infer: int):
59
+ self.num_k_infer = num_k_infer
60
+ return
61
+
62
+ def set_flow_schedule(self, flow_schedule: str, exp_scale: float):
63
+ self.flow_schedule = flow_schedule
64
+ self.exp_scale = exp_scale
65
+ return
66
+
67
+ def _norm_obs(self, pcd: torch.Tensor) -> torch.Tensor:
68
+ # I only do centering here, no scaling, to keep the relative distances and interpretability
69
+ pcd[..., :3] -= torch.tensor(self.norm_pcd_center, device=DEVICE)
70
+ return pcd
71
+
72
+ def _norm_robot_state(self, robot_state: torch.Tensor) -> torch.Tensor:
73
+ # I only do centering here, no scaling, to keep the relative distances and interpretability
74
+ robot_state[..., :3] -= torch.tensor(self.norm_pcd_center, device=DEVICE)
75
+ robot_state[..., 9] -= torch.tensor(0.5, device=DEVICE)
76
+ return robot_state
77
+
78
+ def _denorm_robot_state(self, robot_state: torch.Tensor) -> torch.Tensor:
79
+ robot_state[..., :3] += torch.tensor(self.norm_pcd_center, device=DEVICE)
80
+ robot_state[..., 9] += torch.tensor(0.5, device=DEVICE)
81
+ return robot_state
82
+
83
+ def _norm_data(self, batch: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
84
+ pcd, robot_state_obs, robot_state_pred = batch
85
+ pcd = self._norm_obs(pcd)
86
+ robot_state_obs = self._norm_robot_state(robot_state_obs)
87
+ robot_state_pred = self._norm_robot_state(robot_state_pred)
88
+ return pcd, robot_state_obs, robot_state_pred
89
+
90
+ def _rand_range(self, low: float, high: float, size: tuple[int]) -> torch.Tensor:
91
+ return torch.rand(size, device=DEVICE) * (high - low) + low
92
+
93
+ def _augment_data(self, batch: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]:
94
+ pcd, robot_state_obs, robot_state_pred = batch
95
+
96
+ # xyz1 = self._rand_range(low=0.8, high=1.2, size=(3,))
97
+ xyz2 = self._rand_range(low=-0.2, high=0.2, size=(3,))
98
+ pcd[..., :3] = pcd[..., :3] + xyz2 # * xyz1 + xyz2
99
+ robot_state_obs[..., :3] = robot_state_obs[..., :3] + xyz2 # * xyz1 + xyz2
100
+ robot_state_pred[..., :3] = robot_state_pred[..., :3] + xyz2 # * xyz1 + xyz2
101
+
102
+ # We shuffle the points, i.e. shuffle pcd along dim=2 (B, T, P, 3)
103
+ idx = torch.randperm(pcd.shape[2])
104
+ pcd = pcd[:, :, idx, :]
105
+ return pcd, robot_state_obs, robot_state_pred
106
+
107
+ def _init_noise(self, batch_size: int) -> tuple[torch.Tensor, pp.SO3, torch.Tensor]:
108
+ B = batch_size
109
+ T = self.n_pred_steps
110
+ noise_xyz = torch.randn((B, T, 3), device=DEVICE)
111
+ noise_SO3 = pp.randn_SO3((B, T), device=DEVICE)
112
+ noise_gripper = torch.randn((B, T, 1), device=DEVICE)
113
+ return noise_xyz, noise_SO3, noise_gripper
114
+
115
+ def _pfp_to_pp(self, pfp_state: torch.Tensor) -> tuple[pp.SE3, torch.Tensor]:
116
+ """
117
+ pfp_state: (B, T, 10) -> xyz, rot6d, grip
118
+ """
119
+ poses_th, gripper_th = pfp_to_pose_th(pfp_state) # (B, T, 4, 4)
120
+ xyz = poses_th[..., :3, 3]
121
+ rot_SO3 = pp.mat2SO3(poses_th[..., :3, :3], check=False) # (B, T, 4)
122
+ gripper = gripper_th
123
+ return xyz, rot_SO3, gripper
124
+
125
+ def _pp_to_pfp(
126
+ self, z_xyz: torch.Tensor, z_SO3: pp.SO3, z_gripper: torch.Tensor
127
+ ) -> torch.Tensor:
128
+ """
129
+ Args:
130
+ z_xyz: (B, T, 3) xyz
131
+ z_SO3: (B, T, 4) pp.SO3 rotation
132
+ z_gripper: (B, T, 1) gripper
133
+ Returns:
134
+ z: (B, T, 10) pfp state
135
+ """
136
+ B, T, _ = z_xyz.shape
137
+ z = torch.zeros((B, T, 10), device=DEVICE)
138
+ rot = pp.matrix(z_SO3)
139
+ z[..., :3] = z_xyz
140
+ z[..., 3:9] = rot[..., :3, :2].mT.flatten(start_dim=-2)
141
+ z[..., 9:] = z_gripper
142
+ return z
143
+
144
+ # ############### Training ################
145
+
146
+ def forward(self, batch):
147
+ """batch is the output of the dataloader"""
148
+ return 0
149
+
150
+ def loss(self, outputs, batch: tuple[torch.Tensor, ...]) -> torch.Tensor:
151
+ """
152
+ outputs: the output of the forward pass
153
+ batch: the output of the dataloader
154
+ """
155
+ with torch.no_grad():
156
+ batch = self._norm_data(batch)
157
+ if self.augment_data:
158
+ batch = self._augment_data(batch)
159
+ pcd, robot_state_obs, robot_state_pred = batch
160
+ loss_xyz, loss_rot6d, loss_grip = self.calculate_loss(
161
+ pcd, robot_state_obs, robot_state_pred
162
+ )
163
+ loss = (
164
+ self.l_w["xyz"] * loss_xyz
165
+ + self.l_w["rot6d"] * loss_rot6d
166
+ + self.l_w["grip"] * loss_grip
167
+ )
168
+ self.logger.log_metrics(
169
+ {
170
+ "loss/train/xyz": loss_xyz.item(),
171
+ "loss/train/rot6d": loss_rot6d.item(),
172
+ "loss/train/grip": loss_grip.item(),
173
+ }
174
+ )
175
+ return loss
176
+
177
+ def calculate_loss(
178
+ self, pcd: torch.Tensor, robot_state_obs: torch.Tensor, robot_state_pred: torch.Tensor
179
+ ):
180
+ nx: torch.Tensor = self.obs_encoder(pcd, robot_state_obs)
181
+ ny: torch.Tensor = robot_state_pred
182
+
183
+ B = ny.shape[0]
184
+ # T = ny.shape[1]
185
+
186
+ # Sample random time step
187
+ t_shape = (B, 1, 1)
188
+ t = torch.rand(t_shape, device=DEVICE)
189
+
190
+ # Initialize start and end poses + gripper state
191
+ z0_xyz, z0_SO3, z0_gripper = self._init_noise(B)
192
+ z1_xyz, z1_SO3, z1_gripper = self._pfp_to_pp(ny)
193
+ target_pfp = ny
194
+
195
+ # Calculate relative change between them
196
+ target_vel_xyz = z1_xyz - z0_xyz
197
+ target_vel_so3 = pp.Log(pp.Inv(z0_SO3) @ z1_SO3)
198
+ target_vel_gripper = z1_gripper - z0_gripper
199
+
200
+ # Move to intermediate step
201
+ zt_xyz = z0_xyz + target_vel_xyz * t
202
+ zt_SO3: pp.SO3 = z0_SO3 @ pp.Exp(target_vel_so3 * t)
203
+ zt_gripper: torch.Tensor = z0_gripper + target_vel_gripper * t
204
+
205
+ # Convert to pfp network input representation
206
+ zt_pfp = self._pp_to_pfp(zt_xyz, zt_SO3, zt_gripper)
207
+ timesteps = t.squeeze() * self.pos_emb_scale if self.time_conditioning else None
208
+
209
+ # Do prediction
210
+ pred_pfp = self.diffusion_net(zt_pfp, timesteps, global_cond=nx)
211
+ assert pred_pfp.shape == zt_pfp.shape
212
+ # TODO: you could do procrustes here
213
+
214
+ # Calculate loss
215
+ loss_xyz = self.loss_fun(pred_pfp[..., :3], target_pfp[..., :3])
216
+ loss_rot6d = self.loss_fun(pred_pfp[..., 3:9], target_pfp[..., 3:9])
217
+ loss_grip = self.loss_fun(pred_pfp[..., 9], target_pfp[..., 9])
218
+ return loss_xyz, loss_rot6d, loss_grip
219
+
220
+ # ############### Inference ################
221
+
222
+ def eval_forward(self, batch: tuple[torch.Tensor, ...], outputs=None) -> torch.Tensor:
223
+ """
224
+ batch: the output of the eval dataloader
225
+ outputs: the output of the forward pass
226
+ """
227
+ batch = self._norm_data(batch)
228
+ pcd, robot_state_obs, robot_state_pred = batch
229
+
230
+ # Eval loss
231
+ loss_xyz, loss_rot6d, loss_grip = self.calculate_loss(
232
+ pcd, robot_state_obs, robot_state_pred
233
+ )
234
+ loss_total = (
235
+ self.l_w["xyz"] * loss_xyz
236
+ + self.l_w["rot6d"] * loss_rot6d
237
+ + self.l_w["grip"] * loss_grip
238
+ )
239
+ self.logger.log_metrics(
240
+ {
241
+ "loss/eval/xyz": loss_xyz.item(),
242
+ "loss/eval/rot6d": loss_rot6d.item(),
243
+ "loss/eval/grip": loss_grip.item(),
244
+ "loss/eval/total": loss_total.item(),
245
+ }
246
+ )
247
+
248
+ # Eval metrics
249
+ pred_y = self.infer_y(pcd, robot_state_obs)
250
+ mse_xyz = nn.functional.mse_loss(pred_y[..., :3], robot_state_pred[..., :3])
251
+ mse_rot6d = nn.functional.mse_loss(pred_y[..., 3:9], robot_state_pred[..., 3:9])
252
+ mse_grip = nn.functional.mse_loss(pred_y[..., 9], robot_state_pred[..., 9])
253
+ self.logger.log_metrics(
254
+ {
255
+ "metrics/eval/mse_xyz": mse_xyz.item(),
256
+ "metrics/eval/mse_rot6d": mse_rot6d.item(),
257
+ "metrics/eval/mse_grip": mse_grip.item(),
258
+ }
259
+ )
260
+ return pred_y
261
+
262
+ def infer_y(
263
+ self,
264
+ pcd: torch.Tensor,
265
+ robot_state_obs: torch.Tensor,
266
+ noise=None,
267
+ return_traj=False,
268
+ ) -> torch.Tensor:
269
+ nx: torch.Tensor = self.obs_encoder(pcd, robot_state_obs)
270
+ B = nx.shape[0]
271
+ z_xyz, z_SO3, z_gripper = self._init_noise(B) if noise is None else noise
272
+ z = self._pp_to_pfp(z_xyz, z_SO3, z_gripper)
273
+ traj = [z]
274
+ t0, dt = get_timesteps(self.flow_schedule, self.num_k_infer, exp_scale=self.exp_scale)
275
+ for i in range(self.num_k_infer):
276
+ t = torch.ones((B), device=DEVICE) * t0[i]
277
+ timesteps = t * self.pos_emb_scale if self.time_conditioning else None
278
+ pred_final_pfp = self.diffusion_net(z, timesteps, global_cond=nx)
279
+ z1_xyz, z1_SO3, z1_gripper = self._pfp_to_pp(pred_final_pfp)
280
+
281
+ z_xyz = z_xyz + (z1_xyz - z_xyz) * dt[i]
282
+ z_SO3 = z_SO3 @ pp.Exp(pp.Log(pp.Inv(z_SO3) @ z1_SO3) * dt[i])
283
+ z_gripper = z_gripper + (z1_gripper - z_gripper) * dt[i]
284
+
285
+ z = self._pp_to_pfp(z_xyz, z_SO3, z_gripper)
286
+ traj.append(z)
287
+ return torch.stack(traj) if return_traj else traj[-1]
288
+
289
+ @classmethod
290
+ def load_from_checkpoint(
291
+ cls,
292
+ ckpt_name: str,
293
+ ckpt_episode: str,
294
+ num_k_infer: int,
295
+ flow_schedule: str = None,
296
+ exp_scale: float = None,
297
+ ):
298
+ ckpt_dir = REPO_DIRS.CKPT / ckpt_name
299
+ ckpt_path_list = list(ckpt_dir.glob(f"{ckpt_episode}*"))
300
+ assert len(ckpt_path_list) > 0, f"No checkpoint found in {ckpt_dir} with {ckpt_episode}"
301
+ assert len(ckpt_path_list) < 2, f"Multiple ckpts found in {ckpt_dir} with {ckpt_episode}"
302
+ ckpt_fpath = ckpt_path_list[0]
303
+
304
+ state_dict = torch.load(ckpt_fpath, map_location=DEVICE)
305
+ cfg = OmegaConf.load(ckpt_dir / "config.yaml")
306
+ # cfg.model.obs_encoder.encoder.random_crop = False
307
+ assert cfg.model._target_.split(".")[-1] == cls.__name__
308
+ model: FMTargetPolicy = hydra.utils.instantiate(cfg.model)
309
+ model.load_state_dict(state_dict["state"]["model"])
310
+ model.to(DEVICE)
311
+ model.eval()
312
+ if flow_schedule is not None:
313
+ model.set_flow_schedule(flow_schedule, exp_scale)
314
+ if num_k_infer is not None:
315
+ model.set_num_k_infer(num_k_infer)
316
+ return model
317
+
318
+
319
+ class FMTargetPolicyImage(FMTargetPolicy):
320
+
321
+ def _norm_obs(self, image: torch.Tensor) -> torch.Tensor:
322
+ """
323
+ Image normalization is already done in the backbone, so here we just make it float
324
+ """
325
+ image = image.float() / 255.0
326
+ return image
third_party/PointFlowMatch/pyproject.toml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # https://packaging.python.org/en/latest/specifications/declaring-project-metadata/#declaring-project-metadata
2
+ # https://packaging.python.org/en/latest/tutorials/packaging-projects/
3
+
4
+ [build-system]
5
+ requires = ["hatchling"]
6
+ build-backend = "hatchling.build"
7
+
8
+ [tool.setuptools]
9
+ py-modules = ["pfp"]
10
+
11
+ [tool.black]
12
+ line-length = 100
13
+
14
+ [project]
15
+ name = "pfp"
16
+ version = "0.0.1"
17
+ authors = [{ name = "Eugenio Chisari", email = "eugenio.chisari@gmail.com" }]
18
+ description = ""
19
+ readme = "README.md"
20
+ requires-python = ">=3.8"
21
+ dependencies = [
22
+ "numpy==1.23.5",
23
+ "spatialmath-python==1.1.9",
24
+ "prompt-toolkit==3.0.36",
25
+ "ipython<=8.17.2",
26
+ "trimesh==4.3.2",
27
+ "open3d==0.18.0",
28
+ "numba<=0.59.1",
29
+ "zarr<=2.17.2",
30
+ "matplotlib<=3.8.4",
31
+ "torch<=2.1.2",
32
+ "torchvision<=0.16.2",
33
+ "einops==0.7.0",
34
+ "diffusers==0.27.2",
35
+ "composer<=0.21.3",
36
+ "hydra-core==1.3.2",
37
+ "wandb<=0.17.3",
38
+ "av==8.1.0",
39
+ "yourdfpy==0.0.56",
40
+ "geomstats[pytorch]==2.7.0",
41
+ "imagecodecs"
42
+ ]
43
+
44
+
45
+ [project.optional-dependencies]
46
+ dev = []
third_party/PointFlowMatch/sandbox/augmentation.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import numpy as np
3
+ from torch.utils.data import DataLoader
4
+ from pfp import DATA_DIRS
5
+ from pfp.data.dataset_pcd import RobotDatasetPcd, augment_pcd_data
6
+ from pfp.common.visualization import RerunViewer as RV
7
+ from pfp.common.visualization import RerunTraj
8
+ import rerun as rr
9
+
10
+ rr_traj = {
11
+ "original_robot_obs": RerunTraj(),
12
+ "augmented_robot_obs": RerunTraj(),
13
+ "original_prediction": RerunTraj(),
14
+ "augmented_prediction": RerunTraj(),
15
+ }
16
+
17
+
18
+ def vis_batch(name, batch):
19
+ pcd, robot_state_obs, robot_state_pred = batch
20
+ pcd = pcd[0, -1].cpu().numpy()
21
+ robot_state_obs = robot_state_obs[0].cpu().numpy()
22
+ robot_state_pred = robot_state_pred[0].cpu().numpy()
23
+ RV.add_np_pointcloud(
24
+ f"vis/{name}_pcd", points=pcd[:, :3], colors_uint8=(pcd[:, 3:6] * 255).astype(np.uint8)
25
+ )
26
+ rr_traj[f"{name}_robot_obs"].add_traj(f"{name}_robot_obs", robot_state_obs, size=0.008)
27
+ rr_traj[f"{name}_prediction"].add_traj(f"{name}_prediction", robot_state_pred)
28
+ return
29
+
30
+
31
+ RV("augmentation_vis")
32
+ RV.add_axis("vis/origin", np.eye(4), timeless=True)
33
+
34
+ task_name = "sponge_on_plate"
35
+
36
+ data_path_train = DATA_DIRS.PFP_REAL / task_name / "train"
37
+ dataset_train = RobotDatasetPcd(
38
+ data_path_train,
39
+ n_obs_steps=2,
40
+ n_pred_steps=32,
41
+ subs_factor=3,
42
+ use_pc_color=False,
43
+ n_points=4096,
44
+ )
45
+ dataloader_train = DataLoader(
46
+ dataset_train,
47
+ shuffle=False,
48
+ batch_size=1,
49
+ persistent_workers=False,
50
+ )
51
+
52
+ for i, batch in enumerate(dataloader_train):
53
+ rr.set_time_sequence("step", i)
54
+ original_batch = copy.deepcopy(batch)
55
+ vis_batch("original", original_batch)
56
+
57
+ augmented_batch = copy.deepcopy(batch)
58
+ augmented_batch = augment_pcd_data(augmented_batch)
59
+ vis_batch("augmented", augmented_batch)
60
+
61
+ if i > 500:
62
+ break
third_party/PointFlowMatch/sandbox/learning_rate.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.optim import AdamW
3
+ from torch.optim.lr_scheduler import LambdaLR
4
+ from diffusion_policy.model.common.lr_scheduler import get_scheduler
5
+
6
+
7
+ epochs = 2000
8
+ len_dataset = 10000
9
+
10
+ params = torch.Tensor(1, 1, 1, 1)
11
+ optimizer = AdamW([params], lr=1.0e-4, betas=[0.95, 0.999], eps=1.0e-8, weight_decay=1.0e-6)
12
+ lr_scheduler: LambdaLR = get_scheduler(
13
+ "cosine",
14
+ optimizer=optimizer,
15
+ num_warmup_steps=500,
16
+ num_training_steps=(len_dataset * epochs),
17
+ # pytorch assumes stepping LRScheduler every epoch
18
+ # however huggingface diffusers steps it every batch
19
+ )
20
+
21
+ for epoch in range(epochs):
22
+ # for _ in range(len_dataset):
23
+ lr_scheduler.step()
24
+ # print(lr_scheduler.get_last_lr())
25
+
26
+ if epoch % 100 == 0:
27
+ print(f"Epoch: {epoch}, LR: {lr_scheduler.get_last_lr()}")