Add files using upload-large-folder tool
Browse files- real_inference/models/pi05/29999/_CHECKPOINT_METADATA +1 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/.gitignore +1 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/LICENSE +201 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/act_policy.py +216 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/detr.egg-info/PKG-INFO +7 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/detr.egg-info/SOURCES.txt +15 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/detr.egg-info/dependency_links.txt +1 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/detr.egg-info/top_level.txt +2 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/main.py +170 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/models/__init__.py +11 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/models/backbone.py +125 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/models/detr_vae.py +279 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/models/position_encoding.py +98 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/models/transformer.py +338 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/process_data.py +114 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/setup.py +9 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/util/__init__.py +1 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/util/box_ops.py +86 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/util/misc.py +481 -0
- real_inference/source/XPolicyLab/policy/ACT/detr/util/plot_utils.py +110 -0
real_inference/models/pi05/29999/_CHECKPOINT_METADATA
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"item_handlers": {"assets": "openpi.training.checkpoints.CallbackHandler", "params": "orbax.checkpoint._src.handlers.pytree_checkpoint_handler.PyTreeCheckpointHandler", "train_state": "orbax.checkpoint._src.handlers.pytree_checkpoint_handler.PyTreeCheckpointHandler"}, "metrics": {}, "performance_metrics": {}, "init_timestamp_nsecs": 1794052410651680243, "commit_timestamp_nsecs": 1794052471715227446, "custom_metadata": {}}
|
real_inference/source/XPolicyLab/policy/ACT/detr/.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
!models
|
real_inference/source/XPolicyLab/policy/ACT/detr/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright 2020 - present, Facebook, Inc
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
real_inference/source/XPolicyLab/policy/ACT/detr/act_policy.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
import os
|
| 3 |
+
import torch
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pickle
|
| 6 |
+
from torch.nn import functional as F
|
| 7 |
+
import torchvision.transforms as transforms
|
| 8 |
+
|
| 9 |
+
try:
|
| 10 |
+
from detr.main import (
|
| 11 |
+
build_ACT_model_and_optimizer,
|
| 12 |
+
build_CNNMLP_model_and_optimizer,
|
| 13 |
+
)
|
| 14 |
+
except:
|
| 15 |
+
from .main import (
|
| 16 |
+
build_ACT_model_and_optimizer,
|
| 17 |
+
build_CNNMLP_model_and_optimizer,
|
| 18 |
+
)
|
| 19 |
+
import IPython
|
| 20 |
+
|
| 21 |
+
e = IPython.embed
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class ACTPolicy(nn.Module):
|
| 25 |
+
|
| 26 |
+
def __init__(self, args_override, model_cfg=None):
|
| 27 |
+
super().__init__()
|
| 28 |
+
model, optimizer = build_ACT_model_and_optimizer(args_override, model_cfg)
|
| 29 |
+
self.model = model # CVAE decoder
|
| 30 |
+
self.optimizer = optimizer
|
| 31 |
+
self.kl_weight = args_override["kl_weight"]
|
| 32 |
+
|
| 33 |
+
def __call__(self, qpos, image, actions=None, is_pad=None):
|
| 34 |
+
env_state = None
|
| 35 |
+
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 36 |
+
image = normalize(image)
|
| 37 |
+
if actions is not None: # training time
|
| 38 |
+
actions = actions[:, :self.model.num_queries]
|
| 39 |
+
is_pad = is_pad[:, :self.model.num_queries]
|
| 40 |
+
a_hat, is_pad_hat, (mu, logvar) = self.model(qpos, image, env_state, actions, is_pad)
|
| 41 |
+
total_kld, dim_wise_kld, mean_kld = kl_divergence(mu, logvar)
|
| 42 |
+
loss_dict = dict()
|
| 43 |
+
all_l1 = F.l1_loss(actions, a_hat, reduction="none")
|
| 44 |
+
l1 = (all_l1 * ~is_pad.unsqueeze(-1)).mean()
|
| 45 |
+
loss_dict["l1"] = l1
|
| 46 |
+
loss_dict["kl"] = total_kld[0]
|
| 47 |
+
loss_dict["loss"] = loss_dict["l1"] + loss_dict["kl"] * self.kl_weight
|
| 48 |
+
return loss_dict
|
| 49 |
+
else: # inference time
|
| 50 |
+
a_hat, _, (_, _) = self.model(qpos, image, env_state) # no action, sample from prior
|
| 51 |
+
return a_hat
|
| 52 |
+
|
| 53 |
+
def configure_optimizers(self):
|
| 54 |
+
return self.optimizer
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class CNNMLPPolicy(nn.Module):
|
| 58 |
+
|
| 59 |
+
def __init__(self, args_override):
|
| 60 |
+
super().__init__()
|
| 61 |
+
model, optimizer = build_CNNMLP_model_and_optimizer(args_override)
|
| 62 |
+
self.model = model # decoder
|
| 63 |
+
self.optimizer = optimizer
|
| 64 |
+
|
| 65 |
+
def __call__(self, qpos, image, actions=None, is_pad=None):
|
| 66 |
+
env_state = None # TODO
|
| 67 |
+
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 68 |
+
image = normalize(image)
|
| 69 |
+
if actions is not None: # training time
|
| 70 |
+
actions = actions[:, 0]
|
| 71 |
+
a_hat = self.model(qpos, image, env_state, actions)
|
| 72 |
+
mse = F.mse_loss(actions, a_hat)
|
| 73 |
+
loss_dict = dict()
|
| 74 |
+
loss_dict["mse"] = mse
|
| 75 |
+
loss_dict["loss"] = loss_dict["mse"]
|
| 76 |
+
return loss_dict
|
| 77 |
+
else: # inference time
|
| 78 |
+
a_hat = self.model(qpos, image, env_state) # no action, sample from prior
|
| 79 |
+
return a_hat
|
| 80 |
+
|
| 81 |
+
def configure_optimizers(self):
|
| 82 |
+
return self.optimizer
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def kl_divergence(mu, logvar):
|
| 86 |
+
batch_size = mu.size(0)
|
| 87 |
+
assert batch_size != 0
|
| 88 |
+
if mu.data.ndimension() == 4:
|
| 89 |
+
mu = mu.view(mu.size(0), mu.size(1))
|
| 90 |
+
if logvar.data.ndimension() == 4:
|
| 91 |
+
logvar = logvar.view(logvar.size(0), logvar.size(1))
|
| 92 |
+
|
| 93 |
+
klds = -0.5 * (1 + logvar - mu.pow(2) - logvar.exp())
|
| 94 |
+
total_kld = klds.sum(1).mean(0, True)
|
| 95 |
+
dimension_wise_kld = klds.mean(0)
|
| 96 |
+
mean_kld = klds.mean(1).mean(0, True)
|
| 97 |
+
|
| 98 |
+
return total_kld, dimension_wise_kld, mean_kld
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class ACT:
|
| 102 |
+
|
| 103 |
+
def __init__(self, args_override=None, model_cfg=None):
|
| 104 |
+
if args_override is None:
|
| 105 |
+
args_override = {
|
| 106 |
+
"kl_weight": 0.1, # Default value, can be overridden
|
| 107 |
+
"device": "cuda:0",
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
self.camera_names = model_cfg.camera_names
|
| 111 |
+
|
| 112 |
+
self.policy = ACTPolicy(args_override, model_cfg)
|
| 113 |
+
self.device = torch.device(args_override["device"])
|
| 114 |
+
self.policy.to(self.device)
|
| 115 |
+
self.policy.eval()
|
| 116 |
+
|
| 117 |
+
# Temporal aggregation settings
|
| 118 |
+
self.temporal_agg = args_override.get("temporal_agg", False)
|
| 119 |
+
self.num_queries = args_override["chunk_size"]
|
| 120 |
+
self.state_dim = model_cfg.action_dim # Standard joint dimension for bimanual robot
|
| 121 |
+
self.max_timesteps = 5000 # Large enough for deployment
|
| 122 |
+
|
| 123 |
+
# Set query frequency based on temporal_agg - matching imitate_episodes.py logic
|
| 124 |
+
self.query_frequency = self.num_queries
|
| 125 |
+
if self.temporal_agg:
|
| 126 |
+
self.query_frequency = 1
|
| 127 |
+
# Initialize with zeros matching imitate_episodes.py format
|
| 128 |
+
self.all_time_actions = torch.zeros([
|
| 129 |
+
self.max_timesteps,
|
| 130 |
+
self.max_timesteps + self.num_queries,
|
| 131 |
+
self.state_dim,
|
| 132 |
+
]).to(self.device)
|
| 133 |
+
|
| 134 |
+
self.t = 0 # Current timestep
|
| 135 |
+
|
| 136 |
+
# Load statistics and policy weights. Missing files are fatal because
|
| 137 |
+
# running with an unnormalized/randomly initialized ACT policy is invalid.
|
| 138 |
+
ckpt_dir = args_override.get("ckpt_dir", "")
|
| 139 |
+
stats_path = os.path.join(ckpt_dir, "dataset_stats.pkl") if ckpt_dir else ""
|
| 140 |
+
ckpt_path = os.path.join(ckpt_dir, "policy_last.ckpt") if ckpt_dir else ""
|
| 141 |
+
if not ckpt_dir:
|
| 142 |
+
raise ValueError("ACT requires ckpt_dir during evaluation.")
|
| 143 |
+
if not os.path.isdir(ckpt_dir):
|
| 144 |
+
raise FileNotFoundError(f"ACT checkpoint directory not found: {ckpt_dir}")
|
| 145 |
+
|
| 146 |
+
if not os.path.isfile(stats_path):
|
| 147 |
+
raise FileNotFoundError(f"ACT dataset stats not found: {stats_path}")
|
| 148 |
+
with open(stats_path, "rb") as f:
|
| 149 |
+
self.stats = pickle.load(f)
|
| 150 |
+
|
| 151 |
+
if not os.path.isfile(ckpt_path):
|
| 152 |
+
raise FileNotFoundError(f"ACT policy checkpoint not found: {ckpt_path}")
|
| 153 |
+
self.policy.load_state_dict(torch.load(ckpt_path, map_location=self.device))
|
| 154 |
+
|
| 155 |
+
self.obs_cache = None
|
| 156 |
+
|
| 157 |
+
def pre_process(self, qpos):
|
| 158 |
+
"""Normalize input joint positions"""
|
| 159 |
+
if self.stats is not None:
|
| 160 |
+
return (qpos - self.stats["qpos_mean"]) / self.stats["qpos_std"]
|
| 161 |
+
return qpos
|
| 162 |
+
|
| 163 |
+
def post_process(self, action):
|
| 164 |
+
"""Denormalize model outputs"""
|
| 165 |
+
if self.stats is not None:
|
| 166 |
+
return action * self.stats["action_std"] + self.stats["action_mean"]
|
| 167 |
+
return action
|
| 168 |
+
|
| 169 |
+
def update_obs(self, obs):
|
| 170 |
+
self.obs_cache = obs
|
| 171 |
+
|
| 172 |
+
def get_action(self):
|
| 173 |
+
obs = self.obs_cache
|
| 174 |
+
|
| 175 |
+
# Convert observations to tensors and normalize qpos - matching imitate_episodes.py
|
| 176 |
+
qpos_numpy = np.array(obs["qpos"])
|
| 177 |
+
qpos_normalized = self.pre_process(qpos_numpy)
|
| 178 |
+
qpos = torch.from_numpy(qpos_normalized).float().to(self.device).unsqueeze(0)
|
| 179 |
+
|
| 180 |
+
# Prepare images following imitate_episodes.py pattern
|
| 181 |
+
# Stack images from all cameras
|
| 182 |
+
curr_images = []
|
| 183 |
+
for cam_name in self.camera_names:
|
| 184 |
+
curr_images.append(obs[cam_name])
|
| 185 |
+
curr_image = np.stack(curr_images, axis=0)
|
| 186 |
+
curr_image = torch.from_numpy(curr_image).float().to(self.device).unsqueeze(0)
|
| 187 |
+
|
| 188 |
+
with torch.no_grad():
|
| 189 |
+
# Only query the policy at specified intervals - exactly like imitate_episodes.py
|
| 190 |
+
if self.t % self.query_frequency == 0:
|
| 191 |
+
self.all_actions = self.policy(qpos, curr_image)
|
| 192 |
+
|
| 193 |
+
if self.temporal_agg:
|
| 194 |
+
# Match temporal aggregation exactly from imitate_episodes.py
|
| 195 |
+
self.all_time_actions[[self.t], self.t:self.t + self.num_queries] = (self.all_actions)
|
| 196 |
+
actions_for_curr_step = self.all_time_actions[:, self.t]
|
| 197 |
+
actions_populated = torch.all(actions_for_curr_step != 0, axis=1)
|
| 198 |
+
actions_for_curr_step = actions_for_curr_step[actions_populated]
|
| 199 |
+
|
| 200 |
+
# Use same weighting factor as in imitate_episodes.py
|
| 201 |
+
k = 0.01
|
| 202 |
+
exp_weights = np.exp(-k * np.arange(len(actions_for_curr_step)))
|
| 203 |
+
exp_weights = exp_weights / exp_weights.sum()
|
| 204 |
+
exp_weights = (torch.from_numpy(exp_weights).to(self.device).unsqueeze(dim=1))
|
| 205 |
+
|
| 206 |
+
raw_action = (actions_for_curr_step * exp_weights).sum(dim=0, keepdim=True)
|
| 207 |
+
else:
|
| 208 |
+
# Direct action selection, same as imitate_episodes.py
|
| 209 |
+
raw_action = self.all_actions[:, self.t % self.query_frequency]
|
| 210 |
+
|
| 211 |
+
# Denormalize action
|
| 212 |
+
raw_action = raw_action.cpu().numpy()
|
| 213 |
+
action = self.post_process(raw_action)
|
| 214 |
+
|
| 215 |
+
self.t += 1
|
| 216 |
+
return action
|
real_inference/source/XPolicyLab/policy/ACT/detr/detr.egg-info/PKG-INFO
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: detr
|
| 3 |
+
Version: 0.0.0
|
| 4 |
+
License: MIT License
|
| 5 |
+
License-File: LICENSE
|
| 6 |
+
Dynamic: license
|
| 7 |
+
Dynamic: license-file
|
real_inference/source/XPolicyLab/policy/ACT/detr/detr.egg-info/SOURCES.txt
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
LICENSE
|
| 2 |
+
setup.py
|
| 3 |
+
detr.egg-info/PKG-INFO
|
| 4 |
+
detr.egg-info/SOURCES.txt
|
| 5 |
+
detr.egg-info/dependency_links.txt
|
| 6 |
+
detr.egg-info/top_level.txt
|
| 7 |
+
models/__init__.py
|
| 8 |
+
models/backbone.py
|
| 9 |
+
models/detr_vae.py
|
| 10 |
+
models/position_encoding.py
|
| 11 |
+
models/transformer.py
|
| 12 |
+
util/__init__.py
|
| 13 |
+
util/box_ops.py
|
| 14 |
+
util/misc.py
|
| 15 |
+
util/plot_utils.py
|
real_inference/source/XPolicyLab/policy/ACT/detr/detr.egg-info/dependency_links.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
real_inference/source/XPolicyLab/policy/ACT/detr/detr.egg-info/top_level.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
models
|
| 2 |
+
util
|
real_inference/source/XPolicyLab/policy/ACT/detr/main.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
| 2 |
+
import argparse
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from .models import build_ACT_model, build_CNNMLP_model
|
| 8 |
+
|
| 9 |
+
import IPython
|
| 10 |
+
|
| 11 |
+
e = IPython.embed
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def get_args_parser():
|
| 15 |
+
parser = argparse.ArgumentParser("Set transformer detector", add_help=False)
|
| 16 |
+
parser.add_argument("--lr", default=1e-4, type=float) # will be overridden
|
| 17 |
+
parser.add_argument("--lr_backbone", default=1e-5, type=float) # will be overridden
|
| 18 |
+
parser.add_argument("--batch_size", default=2, type=int) # not used
|
| 19 |
+
parser.add_argument("--weight_decay", default=1e-4, type=float)
|
| 20 |
+
parser.add_argument("--epochs", default=300, type=int) # not used
|
| 21 |
+
parser.add_argument("--lr_drop", default=200, type=int) # not used
|
| 22 |
+
parser.add_argument(
|
| 23 |
+
"--clip_max_norm",
|
| 24 |
+
default=0.1,
|
| 25 |
+
type=float, # not used
|
| 26 |
+
help="gradient clipping max norm",
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# Model parameters
|
| 30 |
+
# * Backbone
|
| 31 |
+
parser.add_argument(
|
| 32 |
+
"--backbone",
|
| 33 |
+
default="resnet18",
|
| 34 |
+
type=str, # will be overridden
|
| 35 |
+
help="Name of the convolutional backbone to use",
|
| 36 |
+
)
|
| 37 |
+
parser.add_argument(
|
| 38 |
+
"--dilation",
|
| 39 |
+
action="store_true",
|
| 40 |
+
help="If true, we replace stride with dilation in the last convolutional block (DC5)",
|
| 41 |
+
)
|
| 42 |
+
parser.add_argument(
|
| 43 |
+
"--position_embedding",
|
| 44 |
+
default="sine",
|
| 45 |
+
type=str,
|
| 46 |
+
choices=("sine", "learned"),
|
| 47 |
+
help="Type of positional embedding to use on top of the image features",
|
| 48 |
+
)
|
| 49 |
+
parser.add_argument(
|
| 50 |
+
"--camera_names",
|
| 51 |
+
default=[],
|
| 52 |
+
type=list, # will be overridden
|
| 53 |
+
help="A list of camera names",
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
# * Transformer
|
| 57 |
+
parser.add_argument(
|
| 58 |
+
"--enc_layers",
|
| 59 |
+
default=4,
|
| 60 |
+
type=int, # will be overridden
|
| 61 |
+
help="Number of encoding layers in the transformer",
|
| 62 |
+
)
|
| 63 |
+
parser.add_argument(
|
| 64 |
+
"--dec_layers",
|
| 65 |
+
default=6,
|
| 66 |
+
type=int, # will be overridden
|
| 67 |
+
help="Number of decoding layers in the transformer",
|
| 68 |
+
)
|
| 69 |
+
parser.add_argument(
|
| 70 |
+
"--dim_feedforward",
|
| 71 |
+
default=2048,
|
| 72 |
+
type=int, # will be overridden
|
| 73 |
+
help="Intermediate size of the feedforward layers in the transformer blocks",
|
| 74 |
+
)
|
| 75 |
+
parser.add_argument(
|
| 76 |
+
"--hidden_dim",
|
| 77 |
+
default=256,
|
| 78 |
+
type=int, # will be overridden
|
| 79 |
+
help="Size of the embeddings (dimension of the transformer)",
|
| 80 |
+
)
|
| 81 |
+
parser.add_argument("--dropout", default=0.1, type=float, help="Dropout applied in the transformer")
|
| 82 |
+
parser.add_argument(
|
| 83 |
+
"--nheads",
|
| 84 |
+
default=8,
|
| 85 |
+
type=int, # will be overridden
|
| 86 |
+
help="Number of attention heads inside the transformer's attentions",
|
| 87 |
+
)
|
| 88 |
+
# parser.add_argument('--num_queries', required=True, type=int, # will be overridden
|
| 89 |
+
# help="Number of query slots")#AGGSIZE
|
| 90 |
+
parser.add_argument("--pre_norm", action="store_true")
|
| 91 |
+
|
| 92 |
+
# * Segmentation
|
| 93 |
+
parser.add_argument(
|
| 94 |
+
"--masks",
|
| 95 |
+
action="store_true",
|
| 96 |
+
help="Train segmentation head if the flag is provided",
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
# repeat args in imitate_episodes just to avoid error. Will not be used
|
| 100 |
+
parser.add_argument("--eval", action="store_true")
|
| 101 |
+
parser.add_argument("--onscreen_render", action="store_true")
|
| 102 |
+
parser.add_argument("--ckpt_dir", action="store", type=str, help="ckpt_dir", required=True)
|
| 103 |
+
parser.add_argument(
|
| 104 |
+
"--policy_class",
|
| 105 |
+
action="store",
|
| 106 |
+
type=str,
|
| 107 |
+
help="policy_class, capitalize",
|
| 108 |
+
required=True,
|
| 109 |
+
)
|
| 110 |
+
parser.add_argument("--bench_name", action="store", type=str, help="bench_name", required=True)
|
| 111 |
+
parser.add_argument("--task_name", action="store", type=str, help="task_name", required=True)
|
| 112 |
+
parser.add_argument("--seed", action="store", type=int, help="seed", required=True)
|
| 113 |
+
parser.add_argument("--num_epochs", action="store", type=int, help="num_epochs", required=True)
|
| 114 |
+
parser.add_argument("--kl_weight", action="store", type=int, help="KL Weight", required=False)
|
| 115 |
+
parser.add_argument("--chunk_size", action="store", type=int, help="chunk_size", required=False)
|
| 116 |
+
parser.add_argument("--ckpt_setting", action="store", type=str, help="chunk_size", required=False)
|
| 117 |
+
parser.add_argument("--temporal_agg", action="store_true")
|
| 118 |
+
parser.add_argument("--save_freq", action="store", type=int, help="save ckpt frequency", required=False, default=6000)
|
| 119 |
+
|
| 120 |
+
return parser
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def build_ACT_model_and_optimizer(args_override, model_cfg=None):
|
| 124 |
+
if model_cfg is None:
|
| 125 |
+
parser = argparse.ArgumentParser("DETR training and evaluation script", parents=[get_args_parser()])
|
| 126 |
+
args = parser.parse_args()
|
| 127 |
+
for k, v in args_override.items():
|
| 128 |
+
setattr(args, k, v)
|
| 129 |
+
else:
|
| 130 |
+
args = model_cfg
|
| 131 |
+
|
| 132 |
+
model = build_ACT_model(args)
|
| 133 |
+
model.cuda()
|
| 134 |
+
|
| 135 |
+
param_dicts = [
|
| 136 |
+
{
|
| 137 |
+
"params": [p for n, p in model.named_parameters() if "backbone" not in n and p.requires_grad]
|
| 138 |
+
},
|
| 139 |
+
{
|
| 140 |
+
"params": [p for n, p in model.named_parameters() if "backbone" in n and p.requires_grad],
|
| 141 |
+
"lr": args.lr_backbone,
|
| 142 |
+
},
|
| 143 |
+
]
|
| 144 |
+
optimizer = torch.optim.AdamW(param_dicts, lr=args.lr, weight_decay=args.weight_decay)
|
| 145 |
+
|
| 146 |
+
return model, optimizer
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def build_CNNMLP_model_and_optimizer(args_override):
|
| 150 |
+
parser = argparse.ArgumentParser("DETR training and evaluation script", parents=[get_args_parser()])
|
| 151 |
+
args = parser.parse_args()
|
| 152 |
+
|
| 153 |
+
for k, v in args_override.items():
|
| 154 |
+
setattr(args, k, v)
|
| 155 |
+
|
| 156 |
+
model = build_CNNMLP_model(args)
|
| 157 |
+
model.cuda()
|
| 158 |
+
|
| 159 |
+
param_dicts = [
|
| 160 |
+
{
|
| 161 |
+
"params": [p for n, p in model.named_parameters() if "backbone" not in n and p.requires_grad]
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"params": [p for n, p in model.named_parameters() if "backbone" in n and p.requires_grad],
|
| 165 |
+
"lr": args.lr_backbone,
|
| 166 |
+
},
|
| 167 |
+
]
|
| 168 |
+
optimizer = torch.optim.AdamW(param_dicts, lr=args.lr, weight_decay=args.weight_decay)
|
| 169 |
+
|
| 170 |
+
return model, optimizer
|
real_inference/source/XPolicyLab/policy/ACT/detr/models/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
| 2 |
+
from .detr_vae import build as build_vae
|
| 3 |
+
from .detr_vae import build_cnnmlp as build_cnnmlp
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def build_ACT_model(args):
|
| 7 |
+
return build_vae(args)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def build_CNNMLP_model(args):
|
| 11 |
+
return build_cnnmlp(args)
|
real_inference/source/XPolicyLab/policy/ACT/detr/models/backbone.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
| 2 |
+
"""
|
| 3 |
+
Backbone modules.
|
| 4 |
+
"""
|
| 5 |
+
import os
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
import torchvision
|
| 9 |
+
from torch import nn
|
| 10 |
+
from torchvision.models._utils import IntermediateLayerGetter
|
| 11 |
+
from typing import Dict, List
|
| 12 |
+
import sys
|
| 13 |
+
|
| 14 |
+
current_dir = os.path.dirname(os.path.abspath(__file__))
|
| 15 |
+
project_root = os.path.abspath(os.path.join(current_dir, '..'))
|
| 16 |
+
sys.path.append(project_root)
|
| 17 |
+
|
| 18 |
+
from util.misc import NestedTensor, is_main_process
|
| 19 |
+
|
| 20 |
+
from .position_encoding import build_position_encoding
|
| 21 |
+
|
| 22 |
+
import IPython
|
| 23 |
+
|
| 24 |
+
e = IPython.embed
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class FrozenBatchNorm2d(torch.nn.Module):
|
| 28 |
+
"""
|
| 29 |
+
BatchNorm2d where the batch statistics and the affine parameters are fixed.
|
| 30 |
+
|
| 31 |
+
Copy-paste from torchvision.misc.ops with added eps before rqsrt,
|
| 32 |
+
without which any other policy_models than torchvision.policy_models.resnet[18,34,50,101]
|
| 33 |
+
produce nans.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(self, n):
|
| 37 |
+
super(FrozenBatchNorm2d, self).__init__()
|
| 38 |
+
self.register_buffer("weight", torch.ones(n))
|
| 39 |
+
self.register_buffer("bias", torch.zeros(n))
|
| 40 |
+
self.register_buffer("running_mean", torch.zeros(n))
|
| 41 |
+
self.register_buffer("running_var", torch.ones(n))
|
| 42 |
+
|
| 43 |
+
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys,
|
| 44 |
+
error_msgs):
|
| 45 |
+
num_batches_tracked_key = prefix + 'num_batches_tracked'
|
| 46 |
+
if num_batches_tracked_key in state_dict:
|
| 47 |
+
del state_dict[num_batches_tracked_key]
|
| 48 |
+
|
| 49 |
+
super(FrozenBatchNorm2d, self)._load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys,
|
| 50 |
+
unexpected_keys, error_msgs)
|
| 51 |
+
|
| 52 |
+
def forward(self, x):
|
| 53 |
+
# move reshapes to the beginning
|
| 54 |
+
# to make it fuser-friendly
|
| 55 |
+
w = self.weight.reshape(1, -1, 1, 1)
|
| 56 |
+
b = self.bias.reshape(1, -1, 1, 1)
|
| 57 |
+
rv = self.running_var.reshape(1, -1, 1, 1)
|
| 58 |
+
rm = self.running_mean.reshape(1, -1, 1, 1)
|
| 59 |
+
eps = 1e-5
|
| 60 |
+
scale = w * (rv + eps).rsqrt()
|
| 61 |
+
bias = b - rm * scale
|
| 62 |
+
return x * scale + bias
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class BackboneBase(nn.Module):
|
| 66 |
+
|
| 67 |
+
def __init__(self, backbone: nn.Module, train_backbone: bool, num_channels: int, return_interm_layers: bool):
|
| 68 |
+
super().__init__()
|
| 69 |
+
# for name, parameter in backbone.named_parameters(): # only train later layers # TODO do we want this?
|
| 70 |
+
# if not train_backbone or 'layer2' not in name and 'layer3' not in name and 'layer4' not in name:
|
| 71 |
+
# parameter.requires_grad_(False)
|
| 72 |
+
if return_interm_layers:
|
| 73 |
+
return_layers = {"layer1": "0", "layer2": "1", "layer3": "2", "layer4": "3"}
|
| 74 |
+
else:
|
| 75 |
+
return_layers = {'layer4': "0"}
|
| 76 |
+
self.body = IntermediateLayerGetter(backbone, return_layers=return_layers)
|
| 77 |
+
self.num_channels = num_channels
|
| 78 |
+
|
| 79 |
+
def forward(self, tensor):
|
| 80 |
+
xs = self.body(tensor)
|
| 81 |
+
return xs
|
| 82 |
+
# out: Dict[str, NestedTensor] = {}
|
| 83 |
+
# for name, x in xs.items():
|
| 84 |
+
# m = tensor_list.mask
|
| 85 |
+
# assert m is not None
|
| 86 |
+
# mask = F.interpolate(m[None].float(), size=x.shape[-2:]).to(torch.bool)[0]
|
| 87 |
+
# out[name] = NestedTensor(x, mask)
|
| 88 |
+
# return out
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class Backbone(BackboneBase):
|
| 92 |
+
"""ResNet backbone with frozen BatchNorm."""
|
| 93 |
+
|
| 94 |
+
def __init__(self, name: str, train_backbone: bool, return_interm_layers: bool, dilation: bool):
|
| 95 |
+
backbone = getattr(torchvision.models,
|
| 96 |
+
name)(replace_stride_with_dilation=[False, False, dilation],
|
| 97 |
+
pretrained=is_main_process(),
|
| 98 |
+
norm_layer=FrozenBatchNorm2d) # pretrained # TODO do we want frozen batch_norm??
|
| 99 |
+
num_channels = 512 if name in ('resnet18', 'resnet34') else 2048
|
| 100 |
+
super().__init__(backbone, train_backbone, num_channels, return_interm_layers)
|
| 101 |
+
|
| 102 |
+
class Joiner(nn.Sequential):
|
| 103 |
+
|
| 104 |
+
def __init__(self, backbone, position_embedding):
|
| 105 |
+
super().__init__(backbone, position_embedding)
|
| 106 |
+
|
| 107 |
+
def forward(self, tensor_list: NestedTensor):
|
| 108 |
+
xs = self[0](tensor_list)
|
| 109 |
+
out: List[NestedTensor] = []
|
| 110 |
+
pos = []
|
| 111 |
+
for name, x in xs.items():
|
| 112 |
+
out.append(x)
|
| 113 |
+
# position encoding
|
| 114 |
+
pos.append(self[1](x).to(x.dtype))
|
| 115 |
+
|
| 116 |
+
return out, pos
|
| 117 |
+
|
| 118 |
+
def build_backbone(args):
|
| 119 |
+
position_embedding = build_position_encoding(args)
|
| 120 |
+
train_backbone = args.lr_backbone > 0
|
| 121 |
+
return_interm_layers = args.masks
|
| 122 |
+
backbone = Backbone(args.backbone, train_backbone, return_interm_layers, args.dilation)
|
| 123 |
+
model = Joiner(backbone, position_embedding)
|
| 124 |
+
model.num_channels = backbone.num_channels
|
| 125 |
+
return model
|
real_inference/source/XPolicyLab/policy/ACT/detr/models/detr_vae.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
| 2 |
+
"""
|
| 3 |
+
DETR model and criterion classes.
|
| 4 |
+
"""
|
| 5 |
+
import torch
|
| 6 |
+
from torch import nn
|
| 7 |
+
from torch.autograd import Variable
|
| 8 |
+
from .backbone import build_backbone
|
| 9 |
+
from .transformer import build_transformer, TransformerEncoder, TransformerEncoderLayer
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
import IPython
|
| 14 |
+
import os
|
| 15 |
+
|
| 16 |
+
e = IPython.embed
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def reparametrize(mu, logvar):
|
| 20 |
+
std = logvar.div(2).exp()
|
| 21 |
+
eps = Variable(std.data.new(std.size()).normal_())
|
| 22 |
+
return mu + std * eps
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def get_sinusoid_encoding_table(n_position, d_hid):
|
| 26 |
+
|
| 27 |
+
def get_position_angle_vec(position):
|
| 28 |
+
return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)]
|
| 29 |
+
|
| 30 |
+
sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)])
|
| 31 |
+
sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i
|
| 32 |
+
sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1
|
| 33 |
+
|
| 34 |
+
return torch.FloatTensor(sinusoid_table).unsqueeze(0)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class DETRVAE(nn.Module):
|
| 38 |
+
""" This is the DETR module that performs object detection """
|
| 39 |
+
|
| 40 |
+
def __init__(self, backbones, transformer, encoder, state_dim, num_queries, camera_names):
|
| 41 |
+
""" Initializes the model.
|
| 42 |
+
Parameters:
|
| 43 |
+
backbones: torch module of the backbone to be used. See backbone.py
|
| 44 |
+
transformer: torch module of the transformer architecture. See transformer.py
|
| 45 |
+
state_dim: robot state dimension of the environment
|
| 46 |
+
num_queries: number of object queries, ie detection slot. This is the maximal number of objects
|
| 47 |
+
DETR can detect in a single image. For COCO, we recommend 100 queries.
|
| 48 |
+
aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.
|
| 49 |
+
"""
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.num_queries = num_queries
|
| 52 |
+
self.camera_names = camera_names
|
| 53 |
+
self.transformer = transformer
|
| 54 |
+
self.encoder = encoder
|
| 55 |
+
hidden_dim = transformer.d_model
|
| 56 |
+
self.action_head = nn.Linear(hidden_dim, state_dim)
|
| 57 |
+
self.is_pad_head = nn.Linear(hidden_dim, 1)
|
| 58 |
+
self.query_embed = nn.Embedding(num_queries, hidden_dim)
|
| 59 |
+
if backbones is not None:
|
| 60 |
+
self.input_proj = nn.Conv2d(backbones[0].num_channels, hidden_dim, kernel_size=1)
|
| 61 |
+
self.backbones = nn.ModuleList(backbones)
|
| 62 |
+
self.input_proj_robot_state = nn.Linear(state_dim, hidden_dim)
|
| 63 |
+
else:
|
| 64 |
+
self.input_proj_robot_state = nn.Linear(state_dim, hidden_dim)
|
| 65 |
+
self.input_proj_env_state = nn.Linear(7, hidden_dim)
|
| 66 |
+
self.pos = torch.nn.Embedding(2, hidden_dim)
|
| 67 |
+
self.backbones = None
|
| 68 |
+
|
| 69 |
+
# encoder extra parameters
|
| 70 |
+
self.latent_dim = 32 # final size of latent z # TODO tune
|
| 71 |
+
self.cls_embed = nn.Embedding(1, hidden_dim) # extra cls token embedding
|
| 72 |
+
self.encoder_action_proj = nn.Linear(state_dim, hidden_dim) # project action to embedding
|
| 73 |
+
self.encoder_joint_proj = nn.Linear(state_dim, hidden_dim) # project qpos to embedding
|
| 74 |
+
self.latent_proj = nn.Linear(hidden_dim, self.latent_dim * 2) # project hidden state to latent std, var
|
| 75 |
+
self.register_buffer('pos_table', get_sinusoid_encoding_table(1 + 1 + num_queries,
|
| 76 |
+
hidden_dim)) # [CLS], qpos, a_seq
|
| 77 |
+
|
| 78 |
+
# decoder extra parameters
|
| 79 |
+
self.latent_out_proj = nn.Linear(self.latent_dim, hidden_dim) # project latent sample to embedding
|
| 80 |
+
self.additional_pos_embed = nn.Embedding(2, hidden_dim) # learned position embedding for proprio and latent
|
| 81 |
+
|
| 82 |
+
def forward(self, qpos, image, env_state, actions=None, is_pad=None):
|
| 83 |
+
"""
|
| 84 |
+
qpos: batch, qpos_dim
|
| 85 |
+
image: batch, num_cam, channel, height, width
|
| 86 |
+
env_state: None
|
| 87 |
+
actions: batch, seq, action_dim
|
| 88 |
+
"""
|
| 89 |
+
is_training = actions is not None # train or val
|
| 90 |
+
bs, _ = qpos.shape
|
| 91 |
+
### Obtain latent z from action sequence
|
| 92 |
+
if is_training:
|
| 93 |
+
# project action sequence to embedding dim, and concat with a CLS token
|
| 94 |
+
action_embed = self.encoder_action_proj(actions) # (bs, seq, hidden_dim)
|
| 95 |
+
qpos_embed = self.encoder_joint_proj(qpos) # (bs, hidden_dim)
|
| 96 |
+
qpos_embed = torch.unsqueeze(qpos_embed, axis=1) # (bs, 1, hidden_dim)
|
| 97 |
+
cls_embed = self.cls_embed.weight # (1, hidden_dim)
|
| 98 |
+
cls_embed = torch.unsqueeze(cls_embed, axis=0).repeat(bs, 1, 1) # (bs, 1, hidden_dim)
|
| 99 |
+
encoder_input = torch.cat([cls_embed, qpos_embed, action_embed], axis=1) # (bs, seq+1, hidden_dim)
|
| 100 |
+
encoder_input = encoder_input.permute(1, 0, 2) # (seq+1, bs, hidden_dim)
|
| 101 |
+
# do not mask cls token
|
| 102 |
+
cls_joint_is_pad = torch.full((bs, 2), False).to(qpos.device) # False: not a padding
|
| 103 |
+
is_pad = torch.cat([cls_joint_is_pad, is_pad], axis=1) # (bs, seq+1)
|
| 104 |
+
# obtain position embedding
|
| 105 |
+
pos_embed = self.pos_table.clone().detach()
|
| 106 |
+
pos_embed = pos_embed.permute(1, 0, 2) # (seq+1, 1, hidden_dim)
|
| 107 |
+
# query model
|
| 108 |
+
encoder_output = self.encoder(encoder_input, pos=pos_embed, src_key_padding_mask=is_pad)
|
| 109 |
+
encoder_output = encoder_output[0] # take cls output only
|
| 110 |
+
latent_info = self.latent_proj(encoder_output)
|
| 111 |
+
mu = latent_info[:, :self.latent_dim]
|
| 112 |
+
logvar = latent_info[:, self.latent_dim:]
|
| 113 |
+
latent_sample = reparametrize(mu, logvar)
|
| 114 |
+
latent_input = self.latent_out_proj(latent_sample)
|
| 115 |
+
else:
|
| 116 |
+
mu = logvar = None
|
| 117 |
+
latent_sample = torch.zeros([bs, self.latent_dim], dtype=torch.float32).to(qpos.device)
|
| 118 |
+
latent_input = self.latent_out_proj(latent_sample)
|
| 119 |
+
|
| 120 |
+
if self.backbones is not None:
|
| 121 |
+
# Image observation features and position embeddings
|
| 122 |
+
all_cam_features = []
|
| 123 |
+
all_cam_pos = []
|
| 124 |
+
# print("image.shape in detr_vae", image.shape,"camera_names", self.camera_names)
|
| 125 |
+
for cam_id, cam_name in enumerate(self.camera_names):
|
| 126 |
+
# print("cam_id", cam_id, "cam_name", cam_name)
|
| 127 |
+
features, pos = self.backbones[0](image[:, cam_id]) # HARDCODED
|
| 128 |
+
features = features[0] # take the last layer feature
|
| 129 |
+
pos = pos[0]
|
| 130 |
+
all_cam_features.append(self.input_proj(features))
|
| 131 |
+
all_cam_pos.append(pos)
|
| 132 |
+
# proprioception features
|
| 133 |
+
proprio_input = self.input_proj_robot_state(qpos)
|
| 134 |
+
# fold camera dimension into width dimension
|
| 135 |
+
src = torch.cat(all_cam_features, axis=3)
|
| 136 |
+
pos = torch.cat(all_cam_pos, axis=3)
|
| 137 |
+
hs = self.transformer(src, None, self.query_embed.weight, pos, latent_input, proprio_input,
|
| 138 |
+
self.additional_pos_embed.weight)[0]
|
| 139 |
+
else:
|
| 140 |
+
qpos = self.input_proj_robot_state(qpos)
|
| 141 |
+
env_state = self.input_proj_env_state(env_state)
|
| 142 |
+
transformer_input = torch.cat([qpos, env_state], axis=1) # seq length = 2
|
| 143 |
+
hs = self.transformer(transformer_input, None, self.query_embed.weight, self.pos.weight)[0]
|
| 144 |
+
a_hat = self.action_head(hs)
|
| 145 |
+
is_pad_hat = self.is_pad_head(hs)
|
| 146 |
+
return a_hat, is_pad_hat, [mu, logvar]
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class CNNMLP(nn.Module):
|
| 150 |
+
|
| 151 |
+
def __init__(self, backbones, state_dim, camera_names):
|
| 152 |
+
""" Initializes the model.
|
| 153 |
+
Parameters:
|
| 154 |
+
backbones: torch module of the backbone to be used. See backbone.py
|
| 155 |
+
transformer: torch module of the transformer architecture. See transformer.py
|
| 156 |
+
state_dim: robot state dimension of the environment
|
| 157 |
+
num_queries: number of object queries, ie detection slot. This is the maximal number of objects
|
| 158 |
+
DETR can detect in a single image. For COCO, we recommend 100 queries.
|
| 159 |
+
aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.
|
| 160 |
+
"""
|
| 161 |
+
super().__init__()
|
| 162 |
+
self.camera_names = camera_names
|
| 163 |
+
self.action_head = nn.Linear(1000, state_dim) # TODO add more
|
| 164 |
+
if backbones is not None:
|
| 165 |
+
self.backbones = nn.ModuleList(backbones)
|
| 166 |
+
backbone_down_projs = []
|
| 167 |
+
for backbone in backbones:
|
| 168 |
+
down_proj = nn.Sequential(nn.Conv2d(backbone.num_channels, 128, kernel_size=5),
|
| 169 |
+
nn.Conv2d(128, 64, kernel_size=5), nn.Conv2d(64, 32, kernel_size=5))
|
| 170 |
+
backbone_down_projs.append(down_proj)
|
| 171 |
+
self.backbone_down_projs = nn.ModuleList(backbone_down_projs)
|
| 172 |
+
|
| 173 |
+
mlp_in_dim = 768 * len(backbones) + int(os.environ.get("ACT_ACTION_DIM"))
|
| 174 |
+
self.mlp = mlp(input_dim=mlp_in_dim, hidden_dim=1024, output_dim=state_dim, hidden_depth=2)
|
| 175 |
+
else:
|
| 176 |
+
raise NotImplementedError
|
| 177 |
+
|
| 178 |
+
def forward(self, qpos, image, env_state, actions=None):
|
| 179 |
+
"""
|
| 180 |
+
qpos: batch, qpos_dim
|
| 181 |
+
image: batch, num_cam, channel, height, width
|
| 182 |
+
env_state: None
|
| 183 |
+
actions: batch, seq, action_dim
|
| 184 |
+
"""
|
| 185 |
+
is_training = actions is not None # train or val
|
| 186 |
+
bs, _ = qpos.shape
|
| 187 |
+
# Image observation features and position embeddings
|
| 188 |
+
all_cam_features = []
|
| 189 |
+
for cam_id, cam_name in enumerate(self.camera_names):
|
| 190 |
+
features, pos = self.backbones[cam_id](image[:, cam_id])
|
| 191 |
+
features = features[0] # take the last layer feature
|
| 192 |
+
pos = pos[0] # not used
|
| 193 |
+
all_cam_features.append(self.backbone_down_projs[cam_id](features))
|
| 194 |
+
# flatten everything
|
| 195 |
+
flattened_features = []
|
| 196 |
+
for cam_feature in all_cam_features:
|
| 197 |
+
flattened_features.append(cam_feature.reshape([bs, -1]))
|
| 198 |
+
flattened_features = torch.cat(flattened_features, axis=1) # 768 each
|
| 199 |
+
features = torch.cat([flattened_features, qpos], axis=1)
|
| 200 |
+
a_hat = self.mlp(features)
|
| 201 |
+
return a_hat
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def mlp(input_dim, hidden_dim, output_dim, hidden_depth):
|
| 205 |
+
if hidden_depth == 0:
|
| 206 |
+
mods = [nn.Linear(input_dim, output_dim)]
|
| 207 |
+
else:
|
| 208 |
+
mods = [nn.Linear(input_dim, hidden_dim), nn.ReLU(inplace=True)]
|
| 209 |
+
for i in range(hidden_depth - 1):
|
| 210 |
+
mods += [nn.Linear(hidden_dim, hidden_dim), nn.ReLU(inplace=True)]
|
| 211 |
+
mods.append(nn.Linear(hidden_dim, output_dim))
|
| 212 |
+
trunk = nn.Sequential(*mods)
|
| 213 |
+
return trunk
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def build_encoder(args):
|
| 217 |
+
d_model = args.hidden_dim # 256
|
| 218 |
+
dropout = args.dropout # 0.1
|
| 219 |
+
nhead = args.nheads # 8
|
| 220 |
+
dim_feedforward = args.dim_feedforward # 2048
|
| 221 |
+
num_encoder_layers = args.enc_layers # 4 # TODO shared with VAE decoder
|
| 222 |
+
normalize_before = args.pre_norm # False
|
| 223 |
+
activation = "relu"
|
| 224 |
+
|
| 225 |
+
encoder_layer = TransformerEncoderLayer(d_model, nhead, dim_feedforward, dropout, activation, normalize_before)
|
| 226 |
+
encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
|
| 227 |
+
encoder = TransformerEncoder(encoder_layer, num_encoder_layers, encoder_norm)
|
| 228 |
+
|
| 229 |
+
return encoder
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def build(args):
|
| 233 |
+
state_dim = int(os.environ.get("ACT_ACTION_DIM"))
|
| 234 |
+
|
| 235 |
+
# From state
|
| 236 |
+
# backbone = None # from state for now, no need for conv nets
|
| 237 |
+
# From image
|
| 238 |
+
backbones = []
|
| 239 |
+
backbone = build_backbone(args)
|
| 240 |
+
backbones.append(backbone)
|
| 241 |
+
|
| 242 |
+
transformer = build_transformer(args)
|
| 243 |
+
|
| 244 |
+
encoder = build_encoder(args)
|
| 245 |
+
|
| 246 |
+
model = DETRVAE(
|
| 247 |
+
backbones,
|
| 248 |
+
transformer,
|
| 249 |
+
encoder,
|
| 250 |
+
state_dim=state_dim,
|
| 251 |
+
num_queries=args.chunk_size,
|
| 252 |
+
camera_names=args.camera_names,
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 256 |
+
|
| 257 |
+
return model
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def build_cnnmlp(args):
|
| 261 |
+
state_dim = int(os.environ.get("ACT_ACTION_DIM"))
|
| 262 |
+
|
| 263 |
+
# From state
|
| 264 |
+
# backbone = None # from state for now, no need for conv nets
|
| 265 |
+
# From image
|
| 266 |
+
backbones = []
|
| 267 |
+
for _ in args.camera_names:
|
| 268 |
+
backbone = build_backbone(args)
|
| 269 |
+
backbones.append(backbone)
|
| 270 |
+
|
| 271 |
+
model = CNNMLP(
|
| 272 |
+
backbones,
|
| 273 |
+
state_dim=state_dim,
|
| 274 |
+
camera_names=args.camera_names,
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 278 |
+
|
| 279 |
+
return model
|
real_inference/source/XPolicyLab/policy/ACT/detr/models/position_encoding.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
| 2 |
+
"""
|
| 3 |
+
Various positional encodings for the transformer.
|
| 4 |
+
"""
|
| 5 |
+
import math
|
| 6 |
+
import torch
|
| 7 |
+
from torch import nn
|
| 8 |
+
|
| 9 |
+
from util.misc import NestedTensor
|
| 10 |
+
|
| 11 |
+
import IPython
|
| 12 |
+
|
| 13 |
+
e = IPython.embed
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class PositionEmbeddingSine(nn.Module):
|
| 17 |
+
"""
|
| 18 |
+
This is a more standard version of the position embedding, very similar to the one
|
| 19 |
+
used by the Attention is all you need paper, generalized to work on images.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None):
|
| 23 |
+
super().__init__()
|
| 24 |
+
self.num_pos_feats = num_pos_feats
|
| 25 |
+
self.temperature = temperature
|
| 26 |
+
self.normalize = normalize
|
| 27 |
+
if scale is not None and normalize is False:
|
| 28 |
+
raise ValueError("normalize should be True if scale is passed")
|
| 29 |
+
if scale is None:
|
| 30 |
+
scale = 2 * math.pi
|
| 31 |
+
self.scale = scale
|
| 32 |
+
|
| 33 |
+
def forward(self, tensor):
|
| 34 |
+
x = tensor
|
| 35 |
+
# mask = tensor_list.mask
|
| 36 |
+
# assert mask is not None
|
| 37 |
+
# not_mask = ~mask
|
| 38 |
+
|
| 39 |
+
not_mask = torch.ones_like(x[0, [0]])
|
| 40 |
+
y_embed = not_mask.cumsum(1, dtype=torch.float32)
|
| 41 |
+
x_embed = not_mask.cumsum(2, dtype=torch.float32)
|
| 42 |
+
if self.normalize:
|
| 43 |
+
eps = 1e-6
|
| 44 |
+
y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
|
| 45 |
+
x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
|
| 46 |
+
|
| 47 |
+
dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
|
| 48 |
+
dim_t = self.temperature**(2 * (dim_t // 2) / self.num_pos_feats)
|
| 49 |
+
|
| 50 |
+
pos_x = x_embed[:, :, :, None] / dim_t
|
| 51 |
+
pos_y = y_embed[:, :, :, None] / dim_t
|
| 52 |
+
pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
|
| 53 |
+
pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
|
| 54 |
+
pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
|
| 55 |
+
return pos
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class PositionEmbeddingLearned(nn.Module):
|
| 59 |
+
"""
|
| 60 |
+
Absolute pos embedding, learned.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
def __init__(self, num_pos_feats=256):
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.row_embed = nn.Embedding(50, num_pos_feats)
|
| 66 |
+
self.col_embed = nn.Embedding(50, num_pos_feats)
|
| 67 |
+
self.reset_parameters()
|
| 68 |
+
|
| 69 |
+
def reset_parameters(self):
|
| 70 |
+
nn.init.uniform_(self.row_embed.weight)
|
| 71 |
+
nn.init.uniform_(self.col_embed.weight)
|
| 72 |
+
|
| 73 |
+
def forward(self, tensor_list: NestedTensor):
|
| 74 |
+
x = tensor_list.tensors
|
| 75 |
+
h, w = x.shape[-2:]
|
| 76 |
+
i = torch.arange(w, device=x.device)
|
| 77 |
+
j = torch.arange(h, device=x.device)
|
| 78 |
+
x_emb = self.col_embed(i)
|
| 79 |
+
y_emb = self.row_embed(j)
|
| 80 |
+
pos = torch.cat([
|
| 81 |
+
x_emb.unsqueeze(0).repeat(h, 1, 1),
|
| 82 |
+
y_emb.unsqueeze(1).repeat(1, w, 1),
|
| 83 |
+
], dim=-1).permute(2, 0, 1).unsqueeze(0).repeat(x.shape[0], 1, 1, 1)
|
| 84 |
+
return pos
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def build_position_encoding(args):
|
| 88 |
+
# print(args.keys())
|
| 89 |
+
N_steps = args.hidden_dim // 2
|
| 90 |
+
if args.position_embedding in ('v2', 'sine'):
|
| 91 |
+
# TODO find a better way of exposing other arguments
|
| 92 |
+
position_embedding = PositionEmbeddingSine(N_steps, normalize=True)
|
| 93 |
+
elif args.position_embedding in ('v3', 'learned'):
|
| 94 |
+
position_embedding = PositionEmbeddingLearned(N_steps)
|
| 95 |
+
else:
|
| 96 |
+
raise ValueError(f"not supported {args.position_embedding}")
|
| 97 |
+
|
| 98 |
+
return position_embedding
|
real_inference/source/XPolicyLab/policy/ACT/detr/models/transformer.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
| 2 |
+
"""
|
| 3 |
+
DETR Transformer class.
|
| 4 |
+
|
| 5 |
+
Copy-paste from torch.nn.Transformer with modifications:
|
| 6 |
+
* positional encodings are passed in MHattention
|
| 7 |
+
* extra LN at the end of encoder is removed
|
| 8 |
+
* decoder returns a stack of activations from all decoding layers
|
| 9 |
+
"""
|
| 10 |
+
import copy
|
| 11 |
+
from typing import Optional, List
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
from torch import nn, Tensor
|
| 16 |
+
|
| 17 |
+
import IPython
|
| 18 |
+
|
| 19 |
+
e = IPython.embed
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Transformer(nn.Module):
|
| 23 |
+
|
| 24 |
+
def __init__(self,
|
| 25 |
+
d_model=512,
|
| 26 |
+
nhead=8,
|
| 27 |
+
num_encoder_layers=6,
|
| 28 |
+
num_decoder_layers=6,
|
| 29 |
+
dim_feedforward=2048,
|
| 30 |
+
dropout=0.1,
|
| 31 |
+
activation="relu",
|
| 32 |
+
normalize_before=False,
|
| 33 |
+
return_intermediate_dec=False):
|
| 34 |
+
super().__init__()
|
| 35 |
+
|
| 36 |
+
encoder_layer = TransformerEncoderLayer(d_model, nhead, dim_feedforward, dropout, activation, normalize_before)
|
| 37 |
+
encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
|
| 38 |
+
self.encoder = TransformerEncoder(encoder_layer, num_encoder_layers, encoder_norm)
|
| 39 |
+
|
| 40 |
+
decoder_layer = TransformerDecoderLayer(d_model, nhead, dim_feedforward, dropout, activation, normalize_before)
|
| 41 |
+
decoder_norm = nn.LayerNorm(d_model)
|
| 42 |
+
self.decoder = TransformerDecoder(decoder_layer,
|
| 43 |
+
num_decoder_layers,
|
| 44 |
+
decoder_norm,
|
| 45 |
+
return_intermediate=return_intermediate_dec)
|
| 46 |
+
|
| 47 |
+
self._reset_parameters()
|
| 48 |
+
|
| 49 |
+
self.d_model = d_model
|
| 50 |
+
self.nhead = nhead
|
| 51 |
+
|
| 52 |
+
def _reset_parameters(self):
|
| 53 |
+
for p in self.parameters():
|
| 54 |
+
if p.dim() > 1:
|
| 55 |
+
nn.init.xavier_uniform_(p)
|
| 56 |
+
|
| 57 |
+
def forward(self,
|
| 58 |
+
src,
|
| 59 |
+
mask,
|
| 60 |
+
query_embed,
|
| 61 |
+
pos_embed,
|
| 62 |
+
latent_input=None,
|
| 63 |
+
proprio_input=None,
|
| 64 |
+
additional_pos_embed=None):
|
| 65 |
+
# TODO flatten only when input has H and W
|
| 66 |
+
if len(src.shape) == 4: # has H and W
|
| 67 |
+
# flatten NxCxHxW to HWxNxC
|
| 68 |
+
bs, c, h, w = src.shape
|
| 69 |
+
src = src.flatten(2).permute(2, 0, 1)
|
| 70 |
+
pos_embed = pos_embed.flatten(2).permute(2, 0, 1).repeat(1, bs, 1)
|
| 71 |
+
query_embed = query_embed.unsqueeze(1).repeat(1, bs, 1)
|
| 72 |
+
# mask = mask.flatten(1)
|
| 73 |
+
|
| 74 |
+
additional_pos_embed = additional_pos_embed.unsqueeze(1).repeat(1, bs, 1) # seq, bs, dim
|
| 75 |
+
pos_embed = torch.cat([additional_pos_embed, pos_embed], axis=0)
|
| 76 |
+
|
| 77 |
+
addition_input = torch.stack([latent_input, proprio_input], axis=0)
|
| 78 |
+
src = torch.cat([addition_input, src], axis=0)
|
| 79 |
+
else:
|
| 80 |
+
assert len(src.shape) == 3
|
| 81 |
+
# flatten NxHWxC to HWxNxC
|
| 82 |
+
bs, hw, c = src.shape
|
| 83 |
+
src = src.permute(1, 0, 2)
|
| 84 |
+
pos_embed = pos_embed.unsqueeze(1).repeat(1, bs, 1)
|
| 85 |
+
query_embed = query_embed.unsqueeze(1).repeat(1, bs, 1)
|
| 86 |
+
|
| 87 |
+
tgt = torch.zeros_like(query_embed)
|
| 88 |
+
memory = self.encoder(src, src_key_padding_mask=mask, pos=pos_embed)
|
| 89 |
+
hs = self.decoder(tgt, memory, memory_key_padding_mask=mask, pos=pos_embed, query_pos=query_embed)
|
| 90 |
+
hs = hs.transpose(1, 2)
|
| 91 |
+
return hs
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class TransformerEncoder(nn.Module):
|
| 95 |
+
|
| 96 |
+
def __init__(self, encoder_layer, num_layers, norm=None):
|
| 97 |
+
super().__init__()
|
| 98 |
+
self.layers = _get_clones(encoder_layer, num_layers)
|
| 99 |
+
self.num_layers = num_layers
|
| 100 |
+
self.norm = norm
|
| 101 |
+
|
| 102 |
+
def forward(self,
|
| 103 |
+
src,
|
| 104 |
+
mask: Optional[Tensor] = None,
|
| 105 |
+
src_key_padding_mask: Optional[Tensor] = None,
|
| 106 |
+
pos: Optional[Tensor] = None):
|
| 107 |
+
output = src
|
| 108 |
+
|
| 109 |
+
for layer in self.layers:
|
| 110 |
+
output = layer(output, src_mask=mask, src_key_padding_mask=src_key_padding_mask, pos=pos)
|
| 111 |
+
|
| 112 |
+
if self.norm is not None:
|
| 113 |
+
output = self.norm(output)
|
| 114 |
+
|
| 115 |
+
return output
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class TransformerDecoder(nn.Module):
|
| 119 |
+
|
| 120 |
+
def __init__(self, decoder_layer, num_layers, norm=None, return_intermediate=False):
|
| 121 |
+
super().__init__()
|
| 122 |
+
self.layers = _get_clones(decoder_layer, num_layers)
|
| 123 |
+
self.num_layers = num_layers
|
| 124 |
+
self.norm = norm
|
| 125 |
+
self.return_intermediate = return_intermediate
|
| 126 |
+
|
| 127 |
+
def forward(self,
|
| 128 |
+
tgt,
|
| 129 |
+
memory,
|
| 130 |
+
tgt_mask: Optional[Tensor] = None,
|
| 131 |
+
memory_mask: Optional[Tensor] = None,
|
| 132 |
+
tgt_key_padding_mask: Optional[Tensor] = None,
|
| 133 |
+
memory_key_padding_mask: Optional[Tensor] = None,
|
| 134 |
+
pos: Optional[Tensor] = None,
|
| 135 |
+
query_pos: Optional[Tensor] = None):
|
| 136 |
+
output = tgt
|
| 137 |
+
|
| 138 |
+
intermediate = []
|
| 139 |
+
|
| 140 |
+
for layer in self.layers:
|
| 141 |
+
output = layer(output,
|
| 142 |
+
memory,
|
| 143 |
+
tgt_mask=tgt_mask,
|
| 144 |
+
memory_mask=memory_mask,
|
| 145 |
+
tgt_key_padding_mask=tgt_key_padding_mask,
|
| 146 |
+
memory_key_padding_mask=memory_key_padding_mask,
|
| 147 |
+
pos=pos,
|
| 148 |
+
query_pos=query_pos)
|
| 149 |
+
if self.return_intermediate:
|
| 150 |
+
intermediate.append(self.norm(output))
|
| 151 |
+
|
| 152 |
+
if self.norm is not None:
|
| 153 |
+
output = self.norm(output)
|
| 154 |
+
if self.return_intermediate:
|
| 155 |
+
intermediate.pop()
|
| 156 |
+
intermediate.append(output)
|
| 157 |
+
|
| 158 |
+
if self.return_intermediate:
|
| 159 |
+
return torch.stack(intermediate)
|
| 160 |
+
|
| 161 |
+
return output.unsqueeze(0)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class TransformerEncoderLayer(nn.Module):
|
| 165 |
+
|
| 166 |
+
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False):
|
| 167 |
+
super().__init__()
|
| 168 |
+
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
|
| 169 |
+
# Implementation of Feedforward model
|
| 170 |
+
self.linear1 = nn.Linear(d_model, dim_feedforward)
|
| 171 |
+
self.dropout = nn.Dropout(dropout)
|
| 172 |
+
self.linear2 = nn.Linear(dim_feedforward, d_model)
|
| 173 |
+
|
| 174 |
+
self.norm1 = nn.LayerNorm(d_model)
|
| 175 |
+
self.norm2 = nn.LayerNorm(d_model)
|
| 176 |
+
self.dropout1 = nn.Dropout(dropout)
|
| 177 |
+
self.dropout2 = nn.Dropout(dropout)
|
| 178 |
+
|
| 179 |
+
self.activation = _get_activation_fn(activation)
|
| 180 |
+
self.normalize_before = normalize_before
|
| 181 |
+
|
| 182 |
+
def with_pos_embed(self, tensor, pos: Optional[Tensor]):
|
| 183 |
+
return tensor if pos is None else tensor + pos
|
| 184 |
+
|
| 185 |
+
def forward_post(self,
|
| 186 |
+
src,
|
| 187 |
+
src_mask: Optional[Tensor] = None,
|
| 188 |
+
src_key_padding_mask: Optional[Tensor] = None,
|
| 189 |
+
pos: Optional[Tensor] = None):
|
| 190 |
+
q = k = self.with_pos_embed(src, pos)
|
| 191 |
+
src2 = self.self_attn(q, k, value=src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0]
|
| 192 |
+
src = src + self.dropout1(src2)
|
| 193 |
+
src = self.norm1(src)
|
| 194 |
+
src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))
|
| 195 |
+
src = src + self.dropout2(src2)
|
| 196 |
+
src = self.norm2(src)
|
| 197 |
+
return src
|
| 198 |
+
|
| 199 |
+
def forward_pre(self,
|
| 200 |
+
src,
|
| 201 |
+
src_mask: Optional[Tensor] = None,
|
| 202 |
+
src_key_padding_mask: Optional[Tensor] = None,
|
| 203 |
+
pos: Optional[Tensor] = None):
|
| 204 |
+
src2 = self.norm1(src)
|
| 205 |
+
q = k = self.with_pos_embed(src2, pos)
|
| 206 |
+
src2 = self.self_attn(q, k, value=src2, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0]
|
| 207 |
+
src = src + self.dropout1(src2)
|
| 208 |
+
src2 = self.norm2(src)
|
| 209 |
+
src2 = self.linear2(self.dropout(self.activation(self.linear1(src2))))
|
| 210 |
+
src = src + self.dropout2(src2)
|
| 211 |
+
return src
|
| 212 |
+
|
| 213 |
+
def forward(self,
|
| 214 |
+
src,
|
| 215 |
+
src_mask: Optional[Tensor] = None,
|
| 216 |
+
src_key_padding_mask: Optional[Tensor] = None,
|
| 217 |
+
pos: Optional[Tensor] = None):
|
| 218 |
+
if self.normalize_before:
|
| 219 |
+
return self.forward_pre(src, src_mask, src_key_padding_mask, pos)
|
| 220 |
+
return self.forward_post(src, src_mask, src_key_padding_mask, pos)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
class TransformerDecoderLayer(nn.Module):
|
| 224 |
+
|
| 225 |
+
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu", normalize_before=False):
|
| 226 |
+
super().__init__()
|
| 227 |
+
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
|
| 228 |
+
self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
|
| 229 |
+
# Implementation of Feedforward model
|
| 230 |
+
self.linear1 = nn.Linear(d_model, dim_feedforward)
|
| 231 |
+
self.dropout = nn.Dropout(dropout)
|
| 232 |
+
self.linear2 = nn.Linear(dim_feedforward, d_model)
|
| 233 |
+
|
| 234 |
+
self.norm1 = nn.LayerNorm(d_model)
|
| 235 |
+
self.norm2 = nn.LayerNorm(d_model)
|
| 236 |
+
self.norm3 = nn.LayerNorm(d_model)
|
| 237 |
+
self.dropout1 = nn.Dropout(dropout)
|
| 238 |
+
self.dropout2 = nn.Dropout(dropout)
|
| 239 |
+
self.dropout3 = nn.Dropout(dropout)
|
| 240 |
+
|
| 241 |
+
self.activation = _get_activation_fn(activation)
|
| 242 |
+
self.normalize_before = normalize_before
|
| 243 |
+
|
| 244 |
+
def with_pos_embed(self, tensor, pos: Optional[Tensor]):
|
| 245 |
+
return tensor if pos is None else tensor + pos
|
| 246 |
+
|
| 247 |
+
def forward_post(self,
|
| 248 |
+
tgt,
|
| 249 |
+
memory,
|
| 250 |
+
tgt_mask: Optional[Tensor] = None,
|
| 251 |
+
memory_mask: Optional[Tensor] = None,
|
| 252 |
+
tgt_key_padding_mask: Optional[Tensor] = None,
|
| 253 |
+
memory_key_padding_mask: Optional[Tensor] = None,
|
| 254 |
+
pos: Optional[Tensor] = None,
|
| 255 |
+
query_pos: Optional[Tensor] = None):
|
| 256 |
+
q = k = self.with_pos_embed(tgt, query_pos)
|
| 257 |
+
tgt2 = self.self_attn(q, k, value=tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0]
|
| 258 |
+
tgt = tgt + self.dropout1(tgt2)
|
| 259 |
+
tgt = self.norm1(tgt)
|
| 260 |
+
tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt, query_pos),
|
| 261 |
+
key=self.with_pos_embed(memory, pos),
|
| 262 |
+
value=memory,
|
| 263 |
+
attn_mask=memory_mask,
|
| 264 |
+
key_padding_mask=memory_key_padding_mask)[0]
|
| 265 |
+
tgt = tgt + self.dropout2(tgt2)
|
| 266 |
+
tgt = self.norm2(tgt)
|
| 267 |
+
tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt))))
|
| 268 |
+
tgt = tgt + self.dropout3(tgt2)
|
| 269 |
+
tgt = self.norm3(tgt)
|
| 270 |
+
return tgt
|
| 271 |
+
|
| 272 |
+
def forward_pre(self,
|
| 273 |
+
tgt,
|
| 274 |
+
memory,
|
| 275 |
+
tgt_mask: Optional[Tensor] = None,
|
| 276 |
+
memory_mask: Optional[Tensor] = None,
|
| 277 |
+
tgt_key_padding_mask: Optional[Tensor] = None,
|
| 278 |
+
memory_key_padding_mask: Optional[Tensor] = None,
|
| 279 |
+
pos: Optional[Tensor] = None,
|
| 280 |
+
query_pos: Optional[Tensor] = None):
|
| 281 |
+
tgt2 = self.norm1(tgt)
|
| 282 |
+
q = k = self.with_pos_embed(tgt2, query_pos)
|
| 283 |
+
tgt2 = self.self_attn(q, k, value=tgt2, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask)[0]
|
| 284 |
+
tgt = tgt + self.dropout1(tgt2)
|
| 285 |
+
tgt2 = self.norm2(tgt)
|
| 286 |
+
tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, query_pos),
|
| 287 |
+
key=self.with_pos_embed(memory, pos),
|
| 288 |
+
value=memory,
|
| 289 |
+
attn_mask=memory_mask,
|
| 290 |
+
key_padding_mask=memory_key_padding_mask)[0]
|
| 291 |
+
tgt = tgt + self.dropout2(tgt2)
|
| 292 |
+
tgt2 = self.norm3(tgt)
|
| 293 |
+
tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
|
| 294 |
+
tgt = tgt + self.dropout3(tgt2)
|
| 295 |
+
return tgt
|
| 296 |
+
|
| 297 |
+
def forward(self,
|
| 298 |
+
tgt,
|
| 299 |
+
memory,
|
| 300 |
+
tgt_mask: Optional[Tensor] = None,
|
| 301 |
+
memory_mask: Optional[Tensor] = None,
|
| 302 |
+
tgt_key_padding_mask: Optional[Tensor] = None,
|
| 303 |
+
memory_key_padding_mask: Optional[Tensor] = None,
|
| 304 |
+
pos: Optional[Tensor] = None,
|
| 305 |
+
query_pos: Optional[Tensor] = None):
|
| 306 |
+
if self.normalize_before:
|
| 307 |
+
return self.forward_pre(tgt, memory, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask,
|
| 308 |
+
pos, query_pos)
|
| 309 |
+
return self.forward_post(tgt, memory, tgt_mask, memory_mask, tgt_key_padding_mask, memory_key_padding_mask, pos,
|
| 310 |
+
query_pos)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def _get_clones(module, N):
|
| 314 |
+
return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def build_transformer(args):
|
| 318 |
+
return Transformer(
|
| 319 |
+
d_model=args.hidden_dim,
|
| 320 |
+
dropout=args.dropout,
|
| 321 |
+
nhead=args.nheads,
|
| 322 |
+
dim_feedforward=args.dim_feedforward,
|
| 323 |
+
num_encoder_layers=args.enc_layers,
|
| 324 |
+
num_decoder_layers=args.dec_layers,
|
| 325 |
+
normalize_before=args.pre_norm,
|
| 326 |
+
return_intermediate_dec=True,
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def _get_activation_fn(activation):
|
| 331 |
+
"""Return an activation function given a string"""
|
| 332 |
+
if activation == "relu":
|
| 333 |
+
return F.relu
|
| 334 |
+
if activation == "gelu":
|
| 335 |
+
return F.gelu
|
| 336 |
+
if activation == "glu":
|
| 337 |
+
return F.glu
|
| 338 |
+
raise RuntimeError(F"activation should be relu/gelu, not {activation}.")
|
real_inference/source/XPolicyLab/policy/ACT/detr/process_data.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import h5py
|
| 3 |
+
import numpy as np
|
| 4 |
+
import cv2
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
from XPolicyLab.utils.load_file import load_hdf5
|
| 9 |
+
from XPolicyLab.utils.process_data import pack_robot_state, get_robot_action_dim_info, decode_image_bit
|
| 10 |
+
|
| 11 |
+
def data_transform(path, episode_num, load_data_dir, save_dir, robot_action_dim_info):
|
| 12 |
+
begin = 0
|
| 13 |
+
floders = os.listdir(path)
|
| 14 |
+
assert episode_num <= len(floders), "data num not enough"
|
| 15 |
+
|
| 16 |
+
if not os.path.exists(save_dir):
|
| 17 |
+
os.makedirs(save_dir)
|
| 18 |
+
|
| 19 |
+
for current_episode in range(episode_num):
|
| 20 |
+
load_path = os.path.join(load_data_dir, f"data/episode_{current_episode:07d}.hdf5")
|
| 21 |
+
data = load_hdf5(load_path)
|
| 22 |
+
state_all = pack_robot_state(data, action_type, robot_action_dim_info, source_type="dataset", state_type="state")
|
| 23 |
+
action_all = pack_robot_state(data, action_type, robot_action_dim_info, source_type="dataset", state_type="action")
|
| 24 |
+
|
| 25 |
+
qpos = []
|
| 26 |
+
actions = []
|
| 27 |
+
cam_head_list = []
|
| 28 |
+
cam_left_wrist_list = []
|
| 29 |
+
cam_right_wrist_list = []
|
| 30 |
+
|
| 31 |
+
for j in range(state_all.shape[0]):
|
| 32 |
+
|
| 33 |
+
state, action = state_all[j], action_all[j]
|
| 34 |
+
|
| 35 |
+
state = state.astype(np.float32)
|
| 36 |
+
qpos.append(state)
|
| 37 |
+
|
| 38 |
+
cam_head_bit = data['vision']["cam_head"]['colors'][j]
|
| 39 |
+
cam_head = decode_image_bit(cam_head_bit)
|
| 40 |
+
cam_head_resized = cv2.resize(cam_head, (640, 480))
|
| 41 |
+
cam_head_list.append(cam_head_resized)
|
| 42 |
+
|
| 43 |
+
cam_left_wrist_bit = data['vision']['cam_left_wrist']['colors'][j]
|
| 44 |
+
cam_left_wrist =decode_image_bit(cam_left_wrist_bit)
|
| 45 |
+
cam_left_wrist_resized = cv2.resize(cam_left_wrist, (640, 480))
|
| 46 |
+
cam_left_wrist_list.append(cam_left_wrist_resized)
|
| 47 |
+
|
| 48 |
+
cam_right_wrist_bit = data['vision']['cam_right_wrist']['colors'][j]
|
| 49 |
+
cam_right_wrist = decode_image_bit(cam_right_wrist_bit)
|
| 50 |
+
cam_right_wrist_resized = cv2.resize(cam_right_wrist, (640, 480))
|
| 51 |
+
cam_right_wrist_list.append(cam_right_wrist_resized)
|
| 52 |
+
|
| 53 |
+
actions.append(action)
|
| 54 |
+
|
| 55 |
+
hdf5path = os.path.join(save_dir, f"episode_{current_episode}.hdf5")
|
| 56 |
+
|
| 57 |
+
with h5py.File(hdf5path, "w") as f:
|
| 58 |
+
f.create_dataset("action", data=np.array(actions, dtype=np.float32))
|
| 59 |
+
obs = f.create_group("observations")
|
| 60 |
+
obs.create_dataset("qpos", data=np.array(qpos, dtype=np.float32))
|
| 61 |
+
image = obs.create_group("images")
|
| 62 |
+
image.create_dataset("cam_head", data=np.stack(cam_head_list), dtype=np.uint8)
|
| 63 |
+
image.create_dataset("cam_left_wrist", data=np.stack(cam_left_wrist_list), dtype=np.uint8)
|
| 64 |
+
image.create_dataset("cam_right_wrist", data=np.stack(cam_right_wrist_list), dtype=np.uint8)
|
| 65 |
+
|
| 66 |
+
begin += 1
|
| 67 |
+
print(f"ACT: proccess episode {current_episode + 1} success!", end='\r')
|
| 68 |
+
|
| 69 |
+
return begin
|
| 70 |
+
|
| 71 |
+
if __name__ == "__main__":
|
| 72 |
+
parser = argparse.ArgumentParser(description="Process some episodes.")
|
| 73 |
+
parser.add_argument("bench_name", type=str, help="The name of the dataset (e.g., ACT)",)
|
| 74 |
+
parser.add_argument("ckpt_name", type=str, help="Run name; also selects raw task dir under data/<bench>/",)
|
| 75 |
+
parser.add_argument("env_cfg_type", type=str, help="The name of the environment config",)
|
| 76 |
+
parser.add_argument("action_type", type=str, help="The type of action to process (e.g., joint)",)
|
| 77 |
+
args = parser.parse_args()
|
| 78 |
+
|
| 79 |
+
bench_name = args.bench_name
|
| 80 |
+
ckpt_name = args.ckpt_name
|
| 81 |
+
env_cfg_type = args.env_cfg_type
|
| 82 |
+
action_type = args.action_type
|
| 83 |
+
|
| 84 |
+
save_dir = f"processed_data/{bench_name}/{ckpt_name}/{env_cfg_type}-{action_type}"
|
| 85 |
+
|
| 86 |
+
load_data_dir = os.path.join("../../../data", str(bench_name), str(ckpt_name), str(env_cfg_type))
|
| 87 |
+
|
| 88 |
+
robot_action_dim_info = get_robot_action_dim_info(env_cfg_type)
|
| 89 |
+
|
| 90 |
+
raw_episode_dir = os.path.join("../../../data/", bench_name, ckpt_name, env_cfg_type, 'data')
|
| 91 |
+
episode_num = len([name for name in os.listdir(raw_episode_dir)
|
| 92 |
+
if name.startswith("episode_") and name.endswith(".hdf5")])
|
| 93 |
+
|
| 94 |
+
begin = data_transform(raw_episode_dir, episode_num, load_data_dir, save_dir, robot_action_dim_info)
|
| 95 |
+
|
| 96 |
+
print()
|
| 97 |
+
|
| 98 |
+
TASK_CONFIGS_PATH = "./TASK_CONFIGS.json"
|
| 99 |
+
|
| 100 |
+
try:
|
| 101 |
+
with open(TASK_CONFIGS_PATH, "r") as f:
|
| 102 |
+
TASK_CONFIGS = json.load(f)
|
| 103 |
+
except Exception:
|
| 104 |
+
TASK_CONFIGS = {}
|
| 105 |
+
|
| 106 |
+
TASK_CONFIGS[f"{bench_name}-{ckpt_name}-{env_cfg_type}-{action_type}"] = {
|
| 107 |
+
"dataset_dir": save_dir,
|
| 108 |
+
"num_episodes": episode_num,
|
| 109 |
+
"episode_len": 5000,
|
| 110 |
+
"camera_names": ["cam_head", "cam_right_wrist", "cam_left_wrist"],
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
with open(TASK_CONFIGS_PATH, "w") as f:
|
| 114 |
+
json.dump(TASK_CONFIGS, f, indent=4)
|
real_inference/source/XPolicyLab/policy/ACT/detr/setup.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from distutils.core import setup
|
| 2 |
+
from setuptools import find_packages
|
| 3 |
+
|
| 4 |
+
setup(
|
| 5 |
+
name="detr",
|
| 6 |
+
version="0.0.0",
|
| 7 |
+
packages=find_packages(),
|
| 8 |
+
license="MIT License",
|
| 9 |
+
)
|
real_inference/source/XPolicyLab/policy/ACT/detr/util/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
real_inference/source/XPolicyLab/policy/ACT/detr/util/box_ops.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
| 2 |
+
"""
|
| 3 |
+
Utilities for bounding box manipulation and GIoU.
|
| 4 |
+
"""
|
| 5 |
+
import torch
|
| 6 |
+
from torchvision.ops.boxes import box_area
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def box_cxcywh_to_xyxy(x):
|
| 10 |
+
x_c, y_c, w, h = x.unbind(-1)
|
| 11 |
+
b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)]
|
| 12 |
+
return torch.stack(b, dim=-1)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def box_xyxy_to_cxcywh(x):
|
| 16 |
+
x0, y0, x1, y1 = x.unbind(-1)
|
| 17 |
+
b = [(x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0), (y1 - y0)]
|
| 18 |
+
return torch.stack(b, dim=-1)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# modified from torchvision to also return the union
|
| 22 |
+
def box_iou(boxes1, boxes2):
|
| 23 |
+
area1 = box_area(boxes1)
|
| 24 |
+
area2 = box_area(boxes2)
|
| 25 |
+
|
| 26 |
+
lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2]
|
| 27 |
+
rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2]
|
| 28 |
+
|
| 29 |
+
wh = (rb - lt).clamp(min=0) # [N,M,2]
|
| 30 |
+
inter = wh[:, :, 0] * wh[:, :, 1] # [N,M]
|
| 31 |
+
|
| 32 |
+
union = area1[:, None] + area2 - inter
|
| 33 |
+
|
| 34 |
+
iou = inter / union
|
| 35 |
+
return iou, union
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def generalized_box_iou(boxes1, boxes2):
|
| 39 |
+
"""
|
| 40 |
+
Generalized IoU from https://giou.stanford.edu/
|
| 41 |
+
|
| 42 |
+
The boxes should be in [x0, y0, x1, y1] format
|
| 43 |
+
|
| 44 |
+
Returns a [N, M] pairwise matrix, where N = len(boxes1)
|
| 45 |
+
and M = len(boxes2)
|
| 46 |
+
"""
|
| 47 |
+
# degenerate boxes gives inf / nan results
|
| 48 |
+
# so do an early check
|
| 49 |
+
assert (boxes1[:, 2:] >= boxes1[:, :2]).all()
|
| 50 |
+
assert (boxes2[:, 2:] >= boxes2[:, :2]).all()
|
| 51 |
+
iou, union = box_iou(boxes1, boxes2)
|
| 52 |
+
|
| 53 |
+
lt = torch.min(boxes1[:, None, :2], boxes2[:, :2])
|
| 54 |
+
rb = torch.max(boxes1[:, None, 2:], boxes2[:, 2:])
|
| 55 |
+
|
| 56 |
+
wh = (rb - lt).clamp(min=0) # [N,M,2]
|
| 57 |
+
area = wh[:, :, 0] * wh[:, :, 1]
|
| 58 |
+
|
| 59 |
+
return iou - (area - union) / area
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def masks_to_boxes(masks):
|
| 63 |
+
"""Compute the bounding boxes around the provided masks
|
| 64 |
+
|
| 65 |
+
The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions.
|
| 66 |
+
|
| 67 |
+
Returns a [N, 4] tensors, with the boxes in xyxy format
|
| 68 |
+
"""
|
| 69 |
+
if masks.numel() == 0:
|
| 70 |
+
return torch.zeros((0, 4), device=masks.device)
|
| 71 |
+
|
| 72 |
+
h, w = masks.shape[-2:]
|
| 73 |
+
|
| 74 |
+
y = torch.arange(0, h, dtype=torch.float)
|
| 75 |
+
x = torch.arange(0, w, dtype=torch.float)
|
| 76 |
+
y, x = torch.meshgrid(y, x)
|
| 77 |
+
|
| 78 |
+
x_mask = masks * x.unsqueeze(0)
|
| 79 |
+
x_max = x_mask.flatten(1).max(-1)[0]
|
| 80 |
+
x_min = x_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
|
| 81 |
+
|
| 82 |
+
y_mask = masks * y.unsqueeze(0)
|
| 83 |
+
y_max = y_mask.flatten(1).max(-1)[0]
|
| 84 |
+
y_min = y_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
|
| 85 |
+
|
| 86 |
+
return torch.stack([x_min, y_min, x_max, y_max], 1)
|
real_inference/source/XPolicyLab/policy/ACT/detr/util/misc.py
ADDED
|
@@ -0,0 +1,481 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
|
| 2 |
+
"""
|
| 3 |
+
Misc functions, including distributed helpers.
|
| 4 |
+
|
| 5 |
+
Mostly copy-paste from torchvision references.
|
| 6 |
+
"""
|
| 7 |
+
import os
|
| 8 |
+
import subprocess
|
| 9 |
+
import time
|
| 10 |
+
from collections import defaultdict, deque
|
| 11 |
+
import datetime
|
| 12 |
+
import pickle
|
| 13 |
+
from packaging import version
|
| 14 |
+
from typing import Optional, List
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.distributed as dist
|
| 18 |
+
from torch import Tensor
|
| 19 |
+
|
| 20 |
+
# needed due to empty tensor bug in pytorch and torchvision 0.5
|
| 21 |
+
import torchvision
|
| 22 |
+
|
| 23 |
+
if version.parse(torchvision.__version__) < version.parse("0.7"):
|
| 24 |
+
from torchvision.ops import _new_empty_tensor
|
| 25 |
+
from torchvision.ops.misc import _output_size
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class SmoothedValue(object):
|
| 29 |
+
"""Track a series of values and provide access to smoothed values over a
|
| 30 |
+
window or the global series average.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, window_size=20, fmt=None):
|
| 34 |
+
if fmt is None:
|
| 35 |
+
fmt = "{median:.4f} ({global_avg:.4f})"
|
| 36 |
+
self.deque = deque(maxlen=window_size)
|
| 37 |
+
self.total = 0.0
|
| 38 |
+
self.count = 0
|
| 39 |
+
self.fmt = fmt
|
| 40 |
+
|
| 41 |
+
def update(self, value, n=1):
|
| 42 |
+
self.deque.append(value)
|
| 43 |
+
self.count += n
|
| 44 |
+
self.total += value * n
|
| 45 |
+
|
| 46 |
+
def synchronize_between_processes(self):
|
| 47 |
+
"""
|
| 48 |
+
Warning: does not synchronize the deque!
|
| 49 |
+
"""
|
| 50 |
+
if not is_dist_avail_and_initialized():
|
| 51 |
+
return
|
| 52 |
+
t = torch.tensor([self.count, self.total], dtype=torch.float64, device="cuda")
|
| 53 |
+
dist.barrier()
|
| 54 |
+
dist.all_reduce(t)
|
| 55 |
+
t = t.tolist()
|
| 56 |
+
self.count = int(t[0])
|
| 57 |
+
self.total = t[1]
|
| 58 |
+
|
| 59 |
+
@property
|
| 60 |
+
def median(self):
|
| 61 |
+
d = torch.tensor(list(self.deque))
|
| 62 |
+
return d.median().item()
|
| 63 |
+
|
| 64 |
+
@property
|
| 65 |
+
def avg(self):
|
| 66 |
+
d = torch.tensor(list(self.deque), dtype=torch.float32)
|
| 67 |
+
return d.mean().item()
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def global_avg(self):
|
| 71 |
+
return self.total / self.count
|
| 72 |
+
|
| 73 |
+
@property
|
| 74 |
+
def max(self):
|
| 75 |
+
return max(self.deque)
|
| 76 |
+
|
| 77 |
+
@property
|
| 78 |
+
def value(self):
|
| 79 |
+
return self.deque[-1]
|
| 80 |
+
|
| 81 |
+
def __str__(self):
|
| 82 |
+
return self.fmt.format(
|
| 83 |
+
median=self.median,
|
| 84 |
+
avg=self.avg,
|
| 85 |
+
global_avg=self.global_avg,
|
| 86 |
+
max=self.max,
|
| 87 |
+
value=self.value,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def all_gather(data):
|
| 92 |
+
"""
|
| 93 |
+
Run all_gather on arbitrary picklable data (not necessarily tensors)
|
| 94 |
+
Args:
|
| 95 |
+
data: any picklable object
|
| 96 |
+
Returns:
|
| 97 |
+
list[data]: list of data gathered from each rank
|
| 98 |
+
"""
|
| 99 |
+
world_size = get_world_size()
|
| 100 |
+
if world_size == 1:
|
| 101 |
+
return [data]
|
| 102 |
+
|
| 103 |
+
# serialized to a Tensor
|
| 104 |
+
buffer = pickle.dumps(data)
|
| 105 |
+
storage = torch.ByteStorage.from_buffer(buffer)
|
| 106 |
+
tensor = torch.ByteTensor(storage).to("cuda")
|
| 107 |
+
|
| 108 |
+
# obtain Tensor size of each rank
|
| 109 |
+
local_size = torch.tensor([tensor.numel()], device="cuda")
|
| 110 |
+
size_list = [torch.tensor([0], device="cuda") for _ in range(world_size)]
|
| 111 |
+
dist.all_gather(size_list, local_size)
|
| 112 |
+
size_list = [int(size.item()) for size in size_list]
|
| 113 |
+
max_size = max(size_list)
|
| 114 |
+
|
| 115 |
+
# receiving Tensor from all ranks
|
| 116 |
+
# we pad the tensor because torch all_gather does not support
|
| 117 |
+
# gathering tensors of different shapes
|
| 118 |
+
tensor_list = []
|
| 119 |
+
for _ in size_list:
|
| 120 |
+
tensor_list.append(torch.empty((max_size, ), dtype=torch.uint8, device="cuda"))
|
| 121 |
+
if local_size != max_size:
|
| 122 |
+
padding = torch.empty(size=(max_size - local_size, ), dtype=torch.uint8, device="cuda")
|
| 123 |
+
tensor = torch.cat((tensor, padding), dim=0)
|
| 124 |
+
dist.all_gather(tensor_list, tensor)
|
| 125 |
+
|
| 126 |
+
data_list = []
|
| 127 |
+
for size, tensor in zip(size_list, tensor_list):
|
| 128 |
+
buffer = tensor.cpu().numpy().tobytes()[:size]
|
| 129 |
+
data_list.append(pickle.loads(buffer))
|
| 130 |
+
|
| 131 |
+
return data_list
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def reduce_dict(input_dict, average=True):
|
| 135 |
+
"""
|
| 136 |
+
Args:
|
| 137 |
+
input_dict (dict): all the values will be reduced
|
| 138 |
+
average (bool): whether to do average or sum
|
| 139 |
+
Reduce the values in the dictionary from all processes so that all processes
|
| 140 |
+
have the averaged results. Returns a dict with the same fields as
|
| 141 |
+
input_dict, after reduction.
|
| 142 |
+
"""
|
| 143 |
+
world_size = get_world_size()
|
| 144 |
+
if world_size < 2:
|
| 145 |
+
return input_dict
|
| 146 |
+
with torch.no_grad():
|
| 147 |
+
names = []
|
| 148 |
+
values = []
|
| 149 |
+
# sort the keys so that they are consistent across processes
|
| 150 |
+
for k in sorted(input_dict.keys()):
|
| 151 |
+
names.append(k)
|
| 152 |
+
values.append(input_dict[k])
|
| 153 |
+
values = torch.stack(values, dim=0)
|
| 154 |
+
dist.all_reduce(values)
|
| 155 |
+
if average:
|
| 156 |
+
values /= world_size
|
| 157 |
+
reduced_dict = {k: v for k, v in zip(names, values)}
|
| 158 |
+
return reduced_dict
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class MetricLogger(object):
|
| 162 |
+
|
| 163 |
+
def __init__(self, delimiter="\t"):
|
| 164 |
+
self.meters = defaultdict(SmoothedValue)
|
| 165 |
+
self.delimiter = delimiter
|
| 166 |
+
|
| 167 |
+
def update(self, **kwargs):
|
| 168 |
+
for k, v in kwargs.items():
|
| 169 |
+
if isinstance(v, torch.Tensor):
|
| 170 |
+
v = v.item()
|
| 171 |
+
assert isinstance(v, (float, int))
|
| 172 |
+
self.meters[k].update(v)
|
| 173 |
+
|
| 174 |
+
def __getattr__(self, attr):
|
| 175 |
+
if attr in self.meters:
|
| 176 |
+
return self.meters[attr]
|
| 177 |
+
if attr in self.__dict__:
|
| 178 |
+
return self.__dict__[attr]
|
| 179 |
+
raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, attr))
|
| 180 |
+
|
| 181 |
+
def __str__(self):
|
| 182 |
+
loss_str = []
|
| 183 |
+
for name, meter in self.meters.items():
|
| 184 |
+
loss_str.append("{}: {}".format(name, str(meter)))
|
| 185 |
+
return self.delimiter.join(loss_str)
|
| 186 |
+
|
| 187 |
+
def synchronize_between_processes(self):
|
| 188 |
+
for meter in self.meters.values():
|
| 189 |
+
meter.synchronize_between_processes()
|
| 190 |
+
|
| 191 |
+
def add_meter(self, name, meter):
|
| 192 |
+
self.meters[name] = meter
|
| 193 |
+
|
| 194 |
+
def log_every(self, iterable, print_freq, header=None):
|
| 195 |
+
i = 0
|
| 196 |
+
if not header:
|
| 197 |
+
header = ""
|
| 198 |
+
start_time = time.time()
|
| 199 |
+
end = time.time()
|
| 200 |
+
iter_time = SmoothedValue(fmt="{avg:.4f}")
|
| 201 |
+
data_time = SmoothedValue(fmt="{avg:.4f}")
|
| 202 |
+
space_fmt = ":" + str(len(str(len(iterable)))) + "d"
|
| 203 |
+
if torch.cuda.is_available():
|
| 204 |
+
log_msg = self.delimiter.join([
|
| 205 |
+
header,
|
| 206 |
+
"[{0" + space_fmt + "}/{1}]",
|
| 207 |
+
"eta: {eta}",
|
| 208 |
+
"{meters}",
|
| 209 |
+
"time: {time}",
|
| 210 |
+
"data: {data}",
|
| 211 |
+
"max mem: {memory:.0f}",
|
| 212 |
+
])
|
| 213 |
+
else:
|
| 214 |
+
log_msg = self.delimiter.join([
|
| 215 |
+
header,
|
| 216 |
+
"[{0" + space_fmt + "}/{1}]",
|
| 217 |
+
"eta: {eta}",
|
| 218 |
+
"{meters}",
|
| 219 |
+
"time: {time}",
|
| 220 |
+
"data: {data}",
|
| 221 |
+
])
|
| 222 |
+
MB = 1024.0 * 1024.0
|
| 223 |
+
for obj in iterable:
|
| 224 |
+
data_time.update(time.time() - end)
|
| 225 |
+
yield obj
|
| 226 |
+
iter_time.update(time.time() - end)
|
| 227 |
+
if i % print_freq == 0 or i == len(iterable) - 1:
|
| 228 |
+
eta_seconds = iter_time.global_avg * (len(iterable) - i)
|
| 229 |
+
eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
|
| 230 |
+
if torch.cuda.is_available():
|
| 231 |
+
print(
|
| 232 |
+
log_msg.format(
|
| 233 |
+
i,
|
| 234 |
+
len(iterable),
|
| 235 |
+
eta=eta_string,
|
| 236 |
+
meters=str(self),
|
| 237 |
+
time=str(iter_time),
|
| 238 |
+
data=str(data_time),
|
| 239 |
+
memory=torch.cuda.max_memory_allocated() / MB,
|
| 240 |
+
))
|
| 241 |
+
else:
|
| 242 |
+
print(
|
| 243 |
+
log_msg.format(
|
| 244 |
+
i,
|
| 245 |
+
len(iterable),
|
| 246 |
+
eta=eta_string,
|
| 247 |
+
meters=str(self),
|
| 248 |
+
time=str(iter_time),
|
| 249 |
+
data=str(data_time),
|
| 250 |
+
))
|
| 251 |
+
i += 1
|
| 252 |
+
end = time.time()
|
| 253 |
+
total_time = time.time() - start_time
|
| 254 |
+
total_time_str = str(datetime.timedelta(seconds=int(total_time)))
|
| 255 |
+
print("{} Total time: {} ({:.4f} s / it)".format(header, total_time_str, total_time / len(iterable)))
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def get_sha():
|
| 259 |
+
cwd = os.path.dirname(os.path.abspath(__file__))
|
| 260 |
+
|
| 261 |
+
def _run(command):
|
| 262 |
+
return subprocess.check_output(command, cwd=cwd).decode("ascii").strip()
|
| 263 |
+
|
| 264 |
+
sha = "N/A"
|
| 265 |
+
diff = "clean"
|
| 266 |
+
branch = "N/A"
|
| 267 |
+
try:
|
| 268 |
+
sha = _run(["git", "rev-parse", "HEAD"])
|
| 269 |
+
subprocess.check_output(["git", "diff"], cwd=cwd)
|
| 270 |
+
diff = _run(["git", "diff-index", "HEAD"])
|
| 271 |
+
diff = "has uncommited changes" if diff else "clean"
|
| 272 |
+
branch = _run(["git", "rev-parse", "--abbrev-ref", "HEAD"])
|
| 273 |
+
except Exception:
|
| 274 |
+
pass
|
| 275 |
+
message = f"sha: {sha}, status: {diff}, branch: {branch}"
|
| 276 |
+
return message
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def collate_fn(batch):
|
| 280 |
+
batch = list(zip(*batch))
|
| 281 |
+
batch[0] = nested_tensor_from_tensor_list(batch[0])
|
| 282 |
+
return tuple(batch)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def _max_by_axis(the_list):
|
| 286 |
+
# type: (List[List[int]]) -> List[int]
|
| 287 |
+
maxes = the_list[0]
|
| 288 |
+
for sublist in the_list[1:]:
|
| 289 |
+
for index, item in enumerate(sublist):
|
| 290 |
+
maxes[index] = max(maxes[index], item)
|
| 291 |
+
return maxes
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
class NestedTensor(object):
|
| 295 |
+
|
| 296 |
+
def __init__(self, tensors, mask: Optional[Tensor]):
|
| 297 |
+
self.tensors = tensors
|
| 298 |
+
self.mask = mask
|
| 299 |
+
|
| 300 |
+
def to(self, device):
|
| 301 |
+
# type: (Device) -> NestedTensor # noqa
|
| 302 |
+
cast_tensor = self.tensors.to(device)
|
| 303 |
+
mask = self.mask
|
| 304 |
+
if mask is not None:
|
| 305 |
+
assert mask is not None
|
| 306 |
+
cast_mask = mask.to(device)
|
| 307 |
+
else:
|
| 308 |
+
cast_mask = None
|
| 309 |
+
return NestedTensor(cast_tensor, cast_mask)
|
| 310 |
+
|
| 311 |
+
def decompose(self):
|
| 312 |
+
return self.tensors, self.mask
|
| 313 |
+
|
| 314 |
+
def __repr__(self):
|
| 315 |
+
return str(self.tensors)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def nested_tensor_from_tensor_list(tensor_list: List[Tensor]):
|
| 319 |
+
# TODO make this more general
|
| 320 |
+
if tensor_list[0].ndim == 3:
|
| 321 |
+
if torchvision._is_tracing():
|
| 322 |
+
# nested_tensor_from_tensor_list() does not export well to ONNX
|
| 323 |
+
# call _onnx_nested_tensor_from_tensor_list() instead
|
| 324 |
+
return _onnx_nested_tensor_from_tensor_list(tensor_list)
|
| 325 |
+
|
| 326 |
+
# TODO make it support different-sized images
|
| 327 |
+
max_size = _max_by_axis([list(img.shape) for img in tensor_list])
|
| 328 |
+
# min_size = tuple(min(s) for s in zip(*[img.shape for img in tensor_list]))
|
| 329 |
+
batch_shape = [len(tensor_list)] + max_size
|
| 330 |
+
b, c, h, w = batch_shape
|
| 331 |
+
dtype = tensor_list[0].dtype
|
| 332 |
+
device = tensor_list[0].device
|
| 333 |
+
tensor = torch.zeros(batch_shape, dtype=dtype, device=device)
|
| 334 |
+
mask = torch.ones((b, h, w), dtype=torch.bool, device=device)
|
| 335 |
+
for img, pad_img, m in zip(tensor_list, tensor, mask):
|
| 336 |
+
pad_img[:img.shape[0], :img.shape[1], :img.shape[2]].copy_(img)
|
| 337 |
+
m[:img.shape[1], :img.shape[2]] = False
|
| 338 |
+
else:
|
| 339 |
+
raise ValueError("not supported")
|
| 340 |
+
return NestedTensor(tensor, mask)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
# _onnx_nested_tensor_from_tensor_list() is an implementation of
|
| 344 |
+
# nested_tensor_from_tensor_list() that is supported by ONNX tracing.
|
| 345 |
+
@torch.jit.unused
|
| 346 |
+
def _onnx_nested_tensor_from_tensor_list(tensor_list: List[Tensor]) -> NestedTensor:
|
| 347 |
+
max_size = []
|
| 348 |
+
for i in range(tensor_list[0].dim()):
|
| 349 |
+
max_size_i = torch.max(torch.stack([img.shape[i] for img in tensor_list]).to(torch.float32)).to(torch.int64)
|
| 350 |
+
max_size.append(max_size_i)
|
| 351 |
+
max_size = tuple(max_size)
|
| 352 |
+
|
| 353 |
+
# work around for
|
| 354 |
+
# pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)
|
| 355 |
+
# m[: img.shape[1], :img.shape[2]] = False
|
| 356 |
+
# which is not yet supported in onnx
|
| 357 |
+
padded_imgs = []
|
| 358 |
+
padded_masks = []
|
| 359 |
+
for img in tensor_list:
|
| 360 |
+
padding = [(s1 - s2) for s1, s2 in zip(max_size, tuple(img.shape))]
|
| 361 |
+
padded_img = torch.nn.functional.pad(img, (0, padding[2], 0, padding[1], 0, padding[0]))
|
| 362 |
+
padded_imgs.append(padded_img)
|
| 363 |
+
|
| 364 |
+
m = torch.zeros_like(img[0], dtype=torch.int, device=img.device)
|
| 365 |
+
padded_mask = torch.nn.functional.pad(m, (0, padding[2], 0, padding[1]), "constant", 1)
|
| 366 |
+
padded_masks.append(padded_mask.to(torch.bool))
|
| 367 |
+
|
| 368 |
+
tensor = torch.stack(padded_imgs)
|
| 369 |
+
mask = torch.stack(padded_masks)
|
| 370 |
+
|
| 371 |
+
return NestedTensor(tensor, mask=mask)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def setup_for_distributed(is_master):
|
| 375 |
+
"""
|
| 376 |
+
This function disables printing when not in master process
|
| 377 |
+
"""
|
| 378 |
+
import builtins as __builtin__
|
| 379 |
+
|
| 380 |
+
builtin_print = __builtin__.print
|
| 381 |
+
|
| 382 |
+
def print(*args, **kwargs):
|
| 383 |
+
force = kwargs.pop("force", False)
|
| 384 |
+
if is_master or force:
|
| 385 |
+
builtin_print(*args, **kwargs)
|
| 386 |
+
|
| 387 |
+
__builtin__.print = print
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def is_dist_avail_and_initialized():
|
| 391 |
+
if not dist.is_available():
|
| 392 |
+
return False
|
| 393 |
+
if not dist.is_initialized():
|
| 394 |
+
return False
|
| 395 |
+
return True
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def get_world_size():
|
| 399 |
+
if not is_dist_avail_and_initialized():
|
| 400 |
+
return 1
|
| 401 |
+
return dist.get_world_size()
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def get_rank():
|
| 405 |
+
if not is_dist_avail_and_initialized():
|
| 406 |
+
return 0
|
| 407 |
+
return dist.get_rank()
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def is_main_process():
|
| 411 |
+
return get_rank() == 0
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def save_on_master(*args, **kwargs):
|
| 415 |
+
if is_main_process():
|
| 416 |
+
torch.save(*args, **kwargs)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def init_distributed_mode(args):
|
| 420 |
+
if "RANK" in os.environ and "WORLD_SIZE" in os.environ:
|
| 421 |
+
args.rank = int(os.environ["RANK"])
|
| 422 |
+
args.world_size = int(os.environ["WORLD_SIZE"])
|
| 423 |
+
args.gpu = int(os.environ["LOCAL_RANK"])
|
| 424 |
+
elif "SLURM_PROCID" in os.environ:
|
| 425 |
+
args.rank = int(os.environ["SLURM_PROCID"])
|
| 426 |
+
args.gpu = args.rank % torch.cuda.device_count()
|
| 427 |
+
else:
|
| 428 |
+
print("Not using distributed mode")
|
| 429 |
+
args.distributed = False
|
| 430 |
+
return
|
| 431 |
+
|
| 432 |
+
args.distributed = True
|
| 433 |
+
|
| 434 |
+
torch.cuda.set_device(args.gpu)
|
| 435 |
+
args.dist_backend = "nccl"
|
| 436 |
+
print("| distributed init (rank {}): {}".format(args.rank, args.dist_url), flush=True)
|
| 437 |
+
torch.distributed.init_process_group(
|
| 438 |
+
backend=args.dist_backend,
|
| 439 |
+
init_method=args.dist_url,
|
| 440 |
+
world_size=args.world_size,
|
| 441 |
+
rank=args.rank,
|
| 442 |
+
)
|
| 443 |
+
torch.distributed.barrier()
|
| 444 |
+
setup_for_distributed(args.rank == 0)
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
@torch.no_grad()
|
| 448 |
+
def accuracy(output, target, topk=(1, )):
|
| 449 |
+
"""Computes the precision@k for the specified values of k"""
|
| 450 |
+
if target.numel() == 0:
|
| 451 |
+
return [torch.zeros([], device=output.device)]
|
| 452 |
+
maxk = max(topk)
|
| 453 |
+
batch_size = target.size(0)
|
| 454 |
+
|
| 455 |
+
_, pred = output.topk(maxk, 1, True, True)
|
| 456 |
+
pred = pred.t()
|
| 457 |
+
correct = pred.eq(target.view(1, -1).expand_as(pred))
|
| 458 |
+
|
| 459 |
+
res = []
|
| 460 |
+
for k in topk:
|
| 461 |
+
correct_k = correct[:k].view(-1).float().sum(0)
|
| 462 |
+
res.append(correct_k.mul_(100.0 / batch_size))
|
| 463 |
+
return res
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def interpolate(input, size=None, scale_factor=None, mode="nearest", align_corners=None):
|
| 467 |
+
# type: (Tensor, Optional[List[int]], Optional[float], str, Optional[bool]) -> Tensor
|
| 468 |
+
"""
|
| 469 |
+
Equivalent to nn.functional.interpolate, but with support for empty batch sizes.
|
| 470 |
+
This will eventually be supported natively by PyTorch, and this
|
| 471 |
+
class can go away.
|
| 472 |
+
"""
|
| 473 |
+
if version.parse(torchvision.__version__) < version.parse("0.7"):
|
| 474 |
+
if input.numel() > 0:
|
| 475 |
+
return torch.nn.functional.interpolate(input, size, scale_factor, mode, align_corners)
|
| 476 |
+
|
| 477 |
+
output_shape = _output_size(2, input, size, scale_factor)
|
| 478 |
+
output_shape = list(input.shape[:-2]) + list(output_shape)
|
| 479 |
+
return _new_empty_tensor(input, output_shape)
|
| 480 |
+
else:
|
| 481 |
+
return torchvision.ops.misc.interpolate(input, size, scale_factor, mode, align_corners)
|
real_inference/source/XPolicyLab/policy/ACT/detr/util/plot_utils.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Plotting utilities to visualize training logs.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import numpy as np
|
| 8 |
+
import seaborn as sns
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
|
| 11 |
+
from pathlib import Path, PurePath
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def plot_logs(
|
| 15 |
+
logs,
|
| 16 |
+
fields=("class_error", "loss_bbox_unscaled", "mAP"),
|
| 17 |
+
ewm_col=0,
|
| 18 |
+
log_name="log.txt",
|
| 19 |
+
):
|
| 20 |
+
"""
|
| 21 |
+
Function to plot specific fields from training log(s). Plots both training and test results.
|
| 22 |
+
|
| 23 |
+
:: Inputs - logs = list containing Path objects, each pointing to individual dir with a log file
|
| 24 |
+
- fields = which results to plot from each log file - plots both training and test for each field.
|
| 25 |
+
- ewm_col = optional, which column to use as the exponential weighted smoothing of the plots
|
| 26 |
+
- log_name = optional, name of log file if different than default 'log.txt'.
|
| 27 |
+
|
| 28 |
+
:: Outputs - matplotlib plots of results in fields, color coded for each log file.
|
| 29 |
+
- solid lines are training results, dashed lines are test results.
|
| 30 |
+
|
| 31 |
+
"""
|
| 32 |
+
func_name = "plot_utils.py::plot_logs"
|
| 33 |
+
|
| 34 |
+
# verify logs is a list of Paths (list[Paths]) or single Pathlib object Path,
|
| 35 |
+
# convert single Path to list to avoid 'not iterable' error
|
| 36 |
+
|
| 37 |
+
if not isinstance(logs, list):
|
| 38 |
+
if isinstance(logs, PurePath):
|
| 39 |
+
logs = [logs]
|
| 40 |
+
print(f"{func_name} info: logs param expects a list argument, converted to list[Path].")
|
| 41 |
+
else:
|
| 42 |
+
raise ValueError(f"{func_name} - invalid argument for logs parameter.\n \
|
| 43 |
+
Expect list[Path] or single Path obj, received {type(logs)}")
|
| 44 |
+
|
| 45 |
+
# Quality checks - verify valid dir(s), that every item in list is Path object, and that log_name exists in each dir
|
| 46 |
+
for i, dir in enumerate(logs):
|
| 47 |
+
if not isinstance(dir, PurePath):
|
| 48 |
+
raise ValueError(f"{func_name} - non-Path object in logs argument of {type(dir)}: \n{dir}")
|
| 49 |
+
if not dir.exists():
|
| 50 |
+
raise ValueError(f"{func_name} - invalid directory in logs argument:\n{dir}")
|
| 51 |
+
# verify log_name exists
|
| 52 |
+
fn = Path(dir / log_name)
|
| 53 |
+
if not fn.exists():
|
| 54 |
+
print(f"-> missing {log_name}. Have you gotten to Epoch 1 in training?")
|
| 55 |
+
print(f"--> full path of missing log file: {fn}")
|
| 56 |
+
return
|
| 57 |
+
|
| 58 |
+
# load log file(s) and plot
|
| 59 |
+
dfs = [pd.read_json(Path(p) / log_name, lines=True) for p in logs]
|
| 60 |
+
|
| 61 |
+
fig, axs = plt.subplots(ncols=len(fields), figsize=(16, 5))
|
| 62 |
+
|
| 63 |
+
for df, color in zip(dfs, sns.color_palette(n_colors=len(logs))):
|
| 64 |
+
for j, field in enumerate(fields):
|
| 65 |
+
if field == "mAP":
|
| 66 |
+
coco_eval = (pd.DataFrame(np.stack(df.test_coco_eval_bbox.dropna().values)[:,
|
| 67 |
+
1]).ewm(com=ewm_col).mean())
|
| 68 |
+
axs[j].plot(coco_eval, c=color)
|
| 69 |
+
else:
|
| 70 |
+
df.interpolate().ewm(com=ewm_col).mean().plot(
|
| 71 |
+
y=[f"train_{field}", f"test_{field}"],
|
| 72 |
+
ax=axs[j],
|
| 73 |
+
color=[color] * 2,
|
| 74 |
+
style=["-", "--"],
|
| 75 |
+
)
|
| 76 |
+
for ax, field in zip(axs, fields):
|
| 77 |
+
ax.legend([Path(p).name for p in logs])
|
| 78 |
+
ax.set_title(field)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def plot_precision_recall(files, naming_scheme="iter"):
|
| 82 |
+
if naming_scheme == "exp_id":
|
| 83 |
+
# name becomes exp_id
|
| 84 |
+
names = [f.parts[-3] for f in files]
|
| 85 |
+
elif naming_scheme == "iter":
|
| 86 |
+
names = [f.stem for f in files]
|
| 87 |
+
else:
|
| 88 |
+
raise ValueError(f"not supported {naming_scheme}")
|
| 89 |
+
fig, axs = plt.subplots(ncols=2, figsize=(16, 5))
|
| 90 |
+
for f, color, name in zip(files, sns.color_palette("Blues", n_colors=len(files)), names):
|
| 91 |
+
data = torch.load(f)
|
| 92 |
+
# precision is n_iou, n_points, n_cat, n_area, max_det
|
| 93 |
+
precision = data["precision"]
|
| 94 |
+
recall = data["params"].recThrs
|
| 95 |
+
scores = data["scores"]
|
| 96 |
+
# take precision for all classes, all areas and 100 detections
|
| 97 |
+
precision = precision[0, :, :, 0, -1].mean(1)
|
| 98 |
+
scores = scores[0, :, :, 0, -1].mean(1)
|
| 99 |
+
prec = precision.mean()
|
| 100 |
+
rec = data["recall"][0, :, 0, -1].mean()
|
| 101 |
+
print(f"{naming_scheme} {name}: mAP@50={prec * 100: 05.1f}, " + f"score={scores.mean():0.3f}, " +
|
| 102 |
+
f"f1={2 * prec * rec / (prec + rec + 1e-8):0.3f}")
|
| 103 |
+
axs[0].plot(recall, precision, c=color)
|
| 104 |
+
axs[1].plot(recall, scores, c=color)
|
| 105 |
+
|
| 106 |
+
axs[0].set_title("Precision / Recall")
|
| 107 |
+
axs[0].legend(names)
|
| 108 |
+
axs[1].set_title("Scores / Recall")
|
| 109 |
+
axs[1].legend(names)
|
| 110 |
+
return fig, axs
|