SRT-H 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,36 @@
1
+ # This workflow will upload a Python Package using Twine when a release is created
2
+ # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries
3
+
4
+ # This workflow uses actions that are not certified by GitHub.
5
+ # They are provided by a third-party and are governed by
6
+ # separate terms of service, privacy policy, and support
7
+ # documentation.
8
+
9
+ name: Upload Python Package
10
+
11
+ on:
12
+ release:
13
+ types: [published]
14
+
15
+ jobs:
16
+ deploy:
17
+
18
+ runs-on: ubuntu-latest
19
+
20
+ steps:
21
+ - uses: actions/checkout@v2
22
+ - name: Set up Python
23
+ uses: actions/setup-python@v2
24
+ with:
25
+ python-version: '3.x'
26
+ - name: Install dependencies
27
+ run: |
28
+ python -m pip install --upgrade pip
29
+ pip install build
30
+ - name: Build package
31
+ run: python -m build
32
+ - name: Publish package
33
+ uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
34
+ with:
35
+ user: __token__
36
+ password: ${{ secrets.PYPI_API_TOKEN }}
@@ -0,0 +1,21 @@
1
+ name: Pytest
2
+ on: [push, pull_request]
3
+
4
+ jobs:
5
+ build:
6
+
7
+ runs-on: ubuntu-latest
8
+
9
+ steps:
10
+ - uses: actions/checkout@v4
11
+ - name: Set up Python 3.10
12
+ uses: actions/setup-python@v5
13
+ with:
14
+ python-version: "3.10"
15
+ - name: Install dependencies
16
+ run: |
17
+ python -m pip install --upgrade pip
18
+ python -m pip install -e .[test]
19
+ - name: Test with pytest
20
+ run: |
21
+ python -m pytest tests/
srt_h-0.0.1/.gitignore ADDED
@@ -0,0 +1,207 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ #pdm.lock
116
+ #pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ #pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # SageMath parsed files
135
+ *.sage.py
136
+
137
+ # Environments
138
+ .env
139
+ .envrc
140
+ .venv
141
+ env/
142
+ venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Abstra
179
+ # Abstra is an AI-powered process automation framework.
180
+ # Ignore directories containing user credentials, local state, and settings.
181
+ # Learn more at https://abstra.io/docs
182
+ .abstra/
183
+
184
+ # Visual Studio Code
185
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
186
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
187
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
188
+ # you could uncomment the following to ignore the entire vscode folder
189
+ # .vscode/
190
+
191
+ # Ruff stuff:
192
+ .ruff_cache/
193
+
194
+ # PyPI configuration file
195
+ .pypirc
196
+
197
+ # Cursor
198
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
199
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
200
+ # refer to https://docs.cursor.com/context/ignore-files
201
+ .cursorignore
202
+ .cursorindexingignore
203
+
204
+ # Marimo
205
+ marimo/_static/
206
+ marimo/_lsp/
207
+ __marimo__/
srt_h-0.0.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Phil Wang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
srt_h-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,103 @@
1
+ Metadata-Version: 2.4
2
+ Name: SRT-H
3
+ Version: 0.0.1
4
+ Summary: MMDiT
5
+ Project-URL: Homepage, https://pypi.org/project/SRT-H/
6
+ Project-URL: Repository, https://github.com/lucidrains/SRT-H
7
+ Author-email: Phil Wang <lucidrains@gmail.com>
8
+ License: MIT License
9
+
10
+ Copyright (c) 2025 Phil Wang
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+ License-File: LICENSE
30
+ Keywords: artificial intelligence,attention mechanism,deep learning,surgical-robotics,transformers
31
+ Classifier: Development Status :: 4 - Beta
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: License :: OSI Approved :: MIT License
34
+ Classifier: Programming Language :: Python :: 3.9
35
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
36
+ Requires-Python: >=3.9
37
+ Requires-Dist: bidirectional-cross-attention>=0.1.0
38
+ Requires-Dist: einops>=0.8.0
39
+ Requires-Dist: einx>=0.3.0
40
+ Requires-Dist: requests
41
+ Requires-Dist: torch>=2.0
42
+ Requires-Dist: validators
43
+ Requires-Dist: vit-pytorch>=1.11.4
44
+ Requires-Dist: x-transformers>=2.5.6
45
+ Provides-Extra: examples
46
+ Provides-Extra: test
47
+ Requires-Dist: pytest; extra == 'test'
48
+ Description-Content-Type: text/markdown
49
+
50
+ <img src="./fig2.png" width="450px"></img>
51
+
52
+ ## SRT-H (wip)
53
+
54
+ Implementation of the model architecture for [SRT-H](https://h-surgical-robot-transformer.github.io/) out of Johns Hopkins
55
+
56
+ ## Citations
57
+
58
+ ```bibtex
59
+ @misc{kim2025srthhierarchicalframeworkautonomous,
60
+ title = {SRT-H: A Hierarchical Framework for Autonomous Surgery via Language Conditioned Imitation Learning},
61
+ author = {Ji Woong Kim and Juo-Tung Chen and Pascal Hansen and Lucy X. Shi and Antony Goldenberg and Samuel Schmidgall and Paul Maria Scheikl and Anton Deguet and Brandon M. White and De Ru Tsai and Richard Cha and Jeffrey Jopling and Chelsea Finn and Axel Krieger},
62
+ year = {2025},
63
+ eprint = {2505.10251},
64
+ archivePrefix = {arXiv},
65
+ primaryClass = {cs.RO},
66
+ url = {https://arxiv.org/abs/2505.10251},
67
+ }
68
+ ```
69
+
70
+ ```bibtex
71
+ @article{Kim2024SurgicalRT,
72
+ title = {Surgical Robot Transformer (SRT): Imitation Learning for Surgical Tasks},
73
+ author = {Ji Woong Kim and Tony Zhao and Samuel Schmidgall and Anton Deguet and Marin Kobilarov and Chelsea Finn and Axel Krieger},
74
+ journal = {ArXiv},
75
+ year = {2024},
76
+ volume = {abs/2407.12998},
77
+ url = {https://api.semanticscholar.org/CorpusID:271270134}
78
+ }
79
+ ```
80
+
81
+ ```bibtex
82
+ @misc{zhao2023learningfinegrainedbimanualmanipulation,
83
+ title = {Learning Fine-Grained Bimanual Manipulation with Low-Cost Hardware},
84
+ author = {Tony Z. Zhao and Vikash Kumar and Sergey Levine and Chelsea Finn},
85
+ year = {2023},
86
+ eprint = {2304.13705},
87
+ archivePrefix = {arXiv},
88
+ primaryClass = {cs.RO},
89
+ url = {https://arxiv.org/abs/2304.13705},
90
+ }
91
+ ```
92
+
93
+ ```bibtex
94
+ @misc{heng2025vitacformerlearningcrossmodalrepresentation,
95
+ title = {ViTacFormer: Learning Cross-Modal Representation for Visuo-Tactile Dexterous Manipulation},
96
+ author = {Liang Heng and Haoran Geng and Kaifeng Zhang and Pieter Abbeel and Jitendra Malik},
97
+ year = {2025},
98
+ eprint = {2506.15953},
99
+ archivePrefix = {arXiv},
100
+ primaryClass = {cs.RO},
101
+ url = {https://arxiv.org/abs/2506.15953},
102
+ }
103
+ ```
srt_h-0.0.1/README.md ADDED
@@ -0,0 +1,54 @@
1
+ <img src="./fig2.png" width="450px"></img>
2
+
3
+ ## SRT-H (wip)
4
+
5
+ Implementation of the model architecture for [SRT-H](https://h-surgical-robot-transformer.github.io/) out of Johns Hopkins
6
+
7
+ ## Citations
8
+
9
+ ```bibtex
10
+ @misc{kim2025srthhierarchicalframeworkautonomous,
11
+ title = {SRT-H: A Hierarchical Framework for Autonomous Surgery via Language Conditioned Imitation Learning},
12
+ author = {Ji Woong Kim and Juo-Tung Chen and Pascal Hansen and Lucy X. Shi and Antony Goldenberg and Samuel Schmidgall and Paul Maria Scheikl and Anton Deguet and Brandon M. White and De Ru Tsai and Richard Cha and Jeffrey Jopling and Chelsea Finn and Axel Krieger},
13
+ year = {2025},
14
+ eprint = {2505.10251},
15
+ archivePrefix = {arXiv},
16
+ primaryClass = {cs.RO},
17
+ url = {https://arxiv.org/abs/2505.10251},
18
+ }
19
+ ```
20
+
21
+ ```bibtex
22
+ @article{Kim2024SurgicalRT,
23
+ title = {Surgical Robot Transformer (SRT): Imitation Learning for Surgical Tasks},
24
+ author = {Ji Woong Kim and Tony Zhao and Samuel Schmidgall and Anton Deguet and Marin Kobilarov and Chelsea Finn and Axel Krieger},
25
+ journal = {ArXiv},
26
+ year = {2024},
27
+ volume = {abs/2407.12998},
28
+ url = {https://api.semanticscholar.org/CorpusID:271270134}
29
+ }
30
+ ```
31
+
32
+ ```bibtex
33
+ @misc{zhao2023learningfinegrainedbimanualmanipulation,
34
+ title = {Learning Fine-Grained Bimanual Manipulation with Low-Cost Hardware},
35
+ author = {Tony Z. Zhao and Vikash Kumar and Sergey Levine and Chelsea Finn},
36
+ year = {2023},
37
+ eprint = {2304.13705},
38
+ archivePrefix = {arXiv},
39
+ primaryClass = {cs.RO},
40
+ url = {https://arxiv.org/abs/2304.13705},
41
+ }
42
+ ```
43
+
44
+ ```bibtex
45
+ @misc{heng2025vitacformerlearningcrossmodalrepresentation,
46
+ title = {ViTacFormer: Learning Cross-Modal Representation for Visuo-Tactile Dexterous Manipulation},
47
+ author = {Liang Heng and Haoran Geng and Kaifeng Zhang and Pieter Abbeel and Jitendra Malik},
48
+ year = {2025},
49
+ eprint = {2506.15953},
50
+ archivePrefix = {arXiv},
51
+ primaryClass = {cs.RO},
52
+ url = {https://arxiv.org/abs/2506.15953},
53
+ }
54
+ ```
@@ -0,0 +1,354 @@
1
+ from __future__ import annotations
2
+ from collections import namedtuple
3
+
4
+ import torch
5
+ from torch import nn, cat, stack, Tensor, is_tensor
6
+ from torch.nn import Module, ModuleList, Parameter, Identity, Linear, Sequential
7
+
8
+ from x_transformers import Encoder, Attention, AttentionPool
9
+
10
+ from einops import rearrange, repeat
11
+ from einops.layers.torch import Rearrange
12
+
13
+ from vit_pytorch.accept_video_wrapper import AcceptVideoWrapper
14
+
15
+ from bidirectional_cross_attention import BidirectionalCrossAttentionTransformer as BiCrossAttnTransformer
16
+
17
+ # helpers
18
+
19
+ def exists(v):
20
+ return v is not None
21
+
22
+ def default(v, d):
23
+ return v if exists(v) else d
24
+
25
+ # pretrained model related
26
+ # they successfully apply
27
+
28
+ # 1. efficient net for low level vision
29
+ # 2. swin t for high level vision
30
+ # 3. distilbert for clinician language feedback
31
+
32
+ class AcceptVideoSwin(Module):
33
+ def __init__(
34
+ self,
35
+ hub_url = 'SharanSMenon/swin-transformer-hub',
36
+ model_name = 'swin_tiny_patch4_window7_224',
37
+ dim_model = 768,
38
+ max_time_seq_len = 8 # say 8 frames
39
+ ):
40
+ super().__init__()
41
+ swin = torch.hub.load(hub_url, model_name, pretrained = True)
42
+ swin.avgpool = Identity()
43
+ swin.head = Rearrange('b (d n) -> b n d', d = dim_model)
44
+
45
+ self.model = AcceptVideoWrapper(
46
+ swin,
47
+ add_time_pos_emb = True,
48
+ time_seq_len = max_time_seq_len,
49
+ dim_emb = dim_model
50
+ )
51
+
52
+ def forward(
53
+ self,
54
+ video
55
+ ):
56
+ embeds = self.model(video)
57
+ return rearrange(embeds, 'b t n d -> b (t n) d')
58
+
59
+ # ACT - Action Chunking Transformer - Zhou et al.
60
+
61
+ Losses = namedtuple('Losses', ('action_recon', 'vae_kl_div'))
62
+
63
+ class ACT(Module):
64
+ def __init__(
65
+ self,
66
+ dim,
67
+ *,
68
+ dim_joint_state,
69
+ action_chunk_len,
70
+ dim_action = 20,
71
+ dim_head = 64,
72
+ dim_style_vector = None,
73
+ dim_lang_condition = None,
74
+ heads = 8,
75
+ vae_encoder_depth = 3,
76
+ encoder_depth = 6,
77
+ decoder_depth = 6,
78
+ vae_encoder_kwargs: dict = dict(),
79
+ vae_encoder_attn_pool_depth = 2,
80
+ encoder_kwargs: dict = dict(),
81
+ decoder: dict = dict(),
82
+ image_model: Module | None = None,
83
+ image_model_dim_emb = None,
84
+ dim_tactile_input = None,
85
+ tactile_self_attn_depth = 2,
86
+ tactile_image_fusion_cross_attn_depth = 2, # ViTacFormer
87
+ max_num_image_frames = 32,
88
+ vae_kl_loss_weight = 1.,
89
+ action_loss_fn = nn.L1Loss()
90
+ ):
91
+ super().__init__()
92
+
93
+ self.dim = dim
94
+
95
+ # style vector dimension related
96
+
97
+ dim_style_vector = default(dim_style_vector, dim)
98
+ need_style_proj = dim_style_vector != dim
99
+
100
+ self.dim_style_vector = dim_style_vector
101
+
102
+ # projections
103
+
104
+ self.joint_to_token = nn.Linear(dim_joint_state, dim)
105
+ self.action_to_vae_tokens = nn.Linear(dim_action, dim)
106
+
107
+ # for the cvae and style vector
108
+
109
+ self.vae_encoder = Encoder(
110
+ dim = dim,
111
+ depth = vae_encoder_depth,
112
+ heads = heads,
113
+ attn_dim_head = dim_head,
114
+ use_rmsnorm = True
115
+ )
116
+
117
+ self.attn_pooler = AttentionPool(dim = dim, depth = vae_encoder_attn_pool_depth, heads = heads, dim_head = dim_head)
118
+
119
+ self.to_style_vector_mean_log_variance = Sequential(
120
+ Linear(dim, dim_style_vector * 2, bias = False),
121
+ Rearrange('... (d mean_log_var) -> mean_log_var ... d', mean_log_var = 2)
122
+ )
123
+
124
+ self.style_vector_to_token = nn.Linear(dim_style_vector, dim) if need_style_proj else nn.Identity()
125
+
126
+ # detr like
127
+
128
+ self.encoder = Encoder(
129
+ dim = dim,
130
+ depth = vae_encoder_depth,
131
+ heads = heads,
132
+ attn_dim_head = dim_head,
133
+ use_rmsnorm = True
134
+ )
135
+
136
+ self.action_queries = Parameter(torch.randn(action_chunk_len, dim) * 1e-2)
137
+
138
+ self.decoder = Encoder(
139
+ dim = dim,
140
+ depth = vae_encoder_depth,
141
+ heads = heads,
142
+ attn_dim_head = dim_head,
143
+ cross_attend = True,
144
+ use_rmsnorm = True,
145
+ rotary_pos_emb = True
146
+ )
147
+
148
+ self.decoder_embed_to_actions = nn.Linear(dim, dim_action)
149
+
150
+ # image model
151
+
152
+ image_model_dim_emb = default(image_model_dim_emb, dim)
153
+ need_image_to_state_proj = image_model_dim_emb != dim
154
+
155
+ # they used efficient net in the paper, but allow for others
156
+
157
+ if not exists(image_model):
158
+ efficientnet = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_efficientnet_b0', pretrained = True)
159
+ utils = torch.hub.load('NVIDIA/DeepLearningExamples:torchhub', 'nvidia_convnets_processing_utils')
160
+
161
+ image_model_dim_emb = 1280
162
+ efficientnet.classifier = Rearrange('b d h w -> b (h w) d') # replace the classifier layer in efficient net
163
+
164
+ image_model = efficientnet
165
+
166
+ # set the image model and the projection to image tokens (state tokens)
167
+
168
+ self.image_model = image_model
169
+ self.to_state_tokens = nn.Linear(image_model_dim_emb, dim) if exists(image_model) and need_image_to_state_proj else nn.Identity()
170
+
171
+ if exists(image_model):
172
+ self.accept_video_wrapper = AcceptVideoWrapper(image_model, add_time_pos_emb = True, time_seq_len = max_num_image_frames, dim_emb = image_model_dim_emb)
173
+
174
+ # tactile
175
+
176
+ self.to_tactile_tokens = nn.Linear(dim_tactile_input, dim) if exists(dim_tactile_input) else None
177
+
178
+ self.tactile_self_attn = Encoder(
179
+ dim = dim,
180
+ depth = tactile_self_attn_depth,
181
+ heads = heads,
182
+ attn_dim_head = dim_head,
183
+ pre_norm_has_final_norm = False
184
+ )
185
+
186
+ self.tactile_fuse = BiCrossAttnTransformer(
187
+ dim = dim,
188
+ context_dim = dim,
189
+ heads = heads,
190
+ depth = tactile_image_fusion_cross_attn_depth
191
+ )
192
+
193
+ # take care of clinician feedback which is conditioning the state tokens with FiLM
194
+
195
+ self.to_film_scale_offset = None
196
+
197
+ if exists(dim_lang_condition):
198
+ self.to_film_scale_offset = nn.Linear(dim_lang_condition, dim * 2, bias = False)
199
+ nn.init.zeros_(self.film.weight)
200
+
201
+ # loss related
202
+
203
+ self.action_loss_fn = action_loss_fn
204
+ self.vae_kl_loss_weight = vae_kl_loss_weight
205
+
206
+ def forward(
207
+ self,
208
+ *,
209
+ joint_state, # (d)
210
+ video = None, # (b c t h w)
211
+ state_tokens = None, # (b n d)
212
+ tactile_input = None, # (b nt dt)
213
+ tactile_tokens = None, # (b nt d)
214
+ actions = None, # (b na da)
215
+ style_vector = None, # (d) | (b d)
216
+ lang_condition = None, # (b d)
217
+ return_loss_breakdown = False
218
+ ):
219
+
220
+ # take care of video -> image tokens
221
+
222
+ assert exists(state_tokens) or exists(video), '`video` or its encoded `state_tokens` must be passed in'
223
+ assert not (exists(video) and not exists(self.image_model)), '`video` cannot be passed in if `image_model` is not set'
224
+
225
+ if exists(video):
226
+ assert video.ndim == 5
227
+
228
+ images_embeds = self.accept_video_wrapper(video, eval_with_no_grad = True)
229
+ state_tokens = self.to_state_tokens(images_embeds)
230
+
231
+ state_tokens = rearrange(state_tokens, 'b t n d -> b (t n) d')
232
+
233
+ # if tactile tokens are presented, fuse it with cross attention, as proposed by ViTacFormer - force feedback is becoming a thing
234
+
235
+ if exists(tactile_input):
236
+ assert not exists(tactile_tokens) and exists(self.to_tactile_tokens)
237
+
238
+ tactile_tokens = self.to_tactile_tokens(tactile_input)
239
+
240
+ if exists(tactile_tokens):
241
+ tactile_tokens = self.tactile_self_attn(tactile_tokens)
242
+
243
+ state_tokens, tactile_tokens = self.tactile_fuse(state_tokens, tactile_tokens)
244
+
245
+ # maybe condition state tokens
246
+
247
+ if exists(lang_condition):
248
+ assert exists(self.to_film_scale_offset), f'`dim_lang_condition` must be set if doing further conditioning (clinician feedback in this paper)'
249
+
250
+ scale, offset = self.to_film_scale_offset(lang_condition).chunk(2, dim = -1)
251
+
252
+ scale, offset = tuple(rearrange(t, 'b d -> b 1 d'), (scale, offset))
253
+
254
+ state_tokens = state_tokens * (scale + 1.) + offset
255
+
256
+ # variables
257
+
258
+ batch, device = state_tokens.shape[0], state_tokens.device
259
+
260
+ is_training = exists(actions)
261
+ is_sampling = not is_training
262
+
263
+ assert not (is_training and exists(style_vector)), 'style vector z cannot be set during training'
264
+
265
+ # joint token
266
+
267
+ joint_tokens = self.joint_to_token(joint_state)
268
+ joint_tokens = rearrange(joint_tokens, 'b d -> b 1 d')
269
+
270
+ # take care of the needed style token during training
271
+
272
+ if is_training:
273
+ action_vae_tokens = self.action_to_vae_tokens(actions)
274
+
275
+ vae_input = cat((action_vae_tokens, joint_tokens), dim = 1)
276
+
277
+ vae_encoder_embed = self.vae_encoder(vae_input)
278
+
279
+ # cross attention pool
280
+
281
+ pooled_vae_embed = self.attn_pooler(vae_encoder_embed)
282
+
283
+ style_mean, style_log_variance = self.to_style_vector_mean_log_variance(pooled_vae_embed)
284
+
285
+ # reparam
286
+
287
+ style_std = (0.5 * style_log_variance).exp()
288
+
289
+ noise = torch.randn_like(style_mean)
290
+
291
+ style_vector = style_mean + style_std * noise
292
+
293
+ elif exists(style_vector) and style_vector.ndim == 1:
294
+
295
+ style_vector = repeat(style_vector, 'd -> b 1 d', b = batch)
296
+
297
+ else:
298
+ # or just zeros during inference, as in the paper
299
+
300
+ style_vector = torch.zeros((batch, 1, self.dim_style_vector), device = device)
301
+
302
+ style_token = self.style_vector_to_token(style_vector)
303
+
304
+ # detr like encoder / decoder
305
+
306
+ encoder_input = cat((style_token, state_tokens, joint_tokens), dim = 1)
307
+
308
+ encoded = self.encoder(encoder_input)
309
+
310
+ decoder_input = repeat(self.action_queries, 'na d -> b na d', b = batch)
311
+
312
+ decoded = self.decoder(decoder_input, context = encoded)
313
+
314
+ pred_actions = self.decoder_embed_to_actions(decoded)
315
+
316
+ if not is_training:
317
+ return pred_actions
318
+
319
+ # take care of training loss
320
+
321
+ action_recon_loss = self.action_loss_fn(pred_actions, actions)
322
+
323
+ vae_kl_loss = (0.5 * (
324
+ style_log_variance.exp()
325
+ + style_mean.square()
326
+ - style_log_variance
327
+ - 1.
328
+ )).sum(dim = -1).mean()
329
+
330
+ loss_breakdown = Losses(action_recon_loss, vae_kl_loss)
331
+
332
+ total_loss = (
333
+ action_recon_loss +
334
+ vae_kl_loss * self.vae_kl_loss_weight
335
+ )
336
+
337
+ if not return_loss_breakdown:
338
+ return total_loss
339
+
340
+ return total_loss, loss_breakdown
341
+
342
+ # classes
343
+
344
+ class SRT(Module):
345
+ def __init__(
346
+ self
347
+ ):
348
+ super().__init__()
349
+
350
+ def forward(
351
+ self,
352
+ state
353
+ ):
354
+ raise NotImplementedError
@@ -0,0 +1,4 @@
1
+ from SRT_H.SRT_H import (
2
+ ACT,
3
+ SRT
4
+ )
srt_h-0.0.1/fig2.png ADDED
Binary file
@@ -0,0 +1,65 @@
1
+ [project]
2
+ name = "SRT-H"
3
+ version = "0.0.1"
4
+ description = "MMDiT"
5
+ authors = [
6
+ { name = "Phil Wang", email = "lucidrains@gmail.com" }
7
+ ]
8
+ readme = "README.md"
9
+ requires-python = ">= 3.9"
10
+ license = { file = "LICENSE" }
11
+ keywords = [
12
+ 'artificial intelligence',
13
+ 'deep learning',
14
+ 'surgical-robotics',
15
+ 'transformers',
16
+ 'attention mechanism'
17
+ ]
18
+
19
+ classifiers=[
20
+ 'Development Status :: 4 - Beta',
21
+ 'Intended Audience :: Developers',
22
+ 'Topic :: Scientific/Engineering :: Artificial Intelligence',
23
+ 'License :: OSI Approved :: MIT License',
24
+ 'Programming Language :: Python :: 3.9',
25
+ ]
26
+
27
+ dependencies = [
28
+ "bidirectional-cross-attention>=0.1.0",
29
+ "einx>=0.3.0",
30
+ "einops>=0.8.0",
31
+ "requests",
32
+ "torch>=2.0",
33
+ "validators",
34
+ "vit-pytorch>=1.11.4",
35
+ "x-transformers>=2.5.6",
36
+ ]
37
+
38
+ [project.urls]
39
+ Homepage = "https://pypi.org/project/SRT-H/"
40
+ Repository = "https://github.com/lucidrains/SRT-H"
41
+
42
+ [project.optional-dependencies]
43
+ examples = []
44
+ test = [
45
+ "pytest"
46
+ ]
47
+
48
+ [tool.pytest.ini_options]
49
+ pythonpath = [
50
+ "."
51
+ ]
52
+
53
+ [build-system]
54
+ requires = ["hatchling"]
55
+ build-backend = "hatchling.build"
56
+
57
+ [tool.rye]
58
+ managed = true
59
+ dev-dependencies = []
60
+
61
+ [tool.hatch.metadata]
62
+ allow-direct-references = true
63
+
64
+ [tool.hatch.build.targets.wheel]
65
+ packages = ["SRT_H"]
@@ -0,0 +1,94 @@
1
+ import torch
2
+
3
+ import pytest
4
+ param = pytest.mark.parametrize
5
+
6
+ @param('pass_custom_style', (False, True))
7
+ def test_act(
8
+ pass_custom_style
9
+ ):
10
+ from SRT_H.SRT_H import ACT
11
+
12
+ act = ACT(
13
+ dim = 512,
14
+ dim_joint_state = 17,
15
+ action_chunk_len = 16
16
+ )
17
+
18
+ states = torch.randn(3, 512, 512)
19
+ joint_state = torch.randn(3, 17)
20
+
21
+ actions = torch.randn(3, 16, 20)
22
+
23
+ loss = act(
24
+ state_tokens = states,
25
+ joint_state = joint_state,
26
+ actions = actions
27
+ )
28
+
29
+ loss.backward()
30
+
31
+ # after a lot of data and training ...
32
+
33
+ style_vector = torch.ones(512) if pass_custom_style else None
34
+
35
+ sampled_actions = act(state_tokens = states, joint_state = joint_state, style_vector = style_vector) # (3, 16, 20)
36
+
37
+ assert sampled_actions.shape == (3, 16, 20)
38
+
39
+ @param('tactile', (False, True))
40
+ @param('efficient_net', (False, True))
41
+ def test_act_with_image_model(
42
+ tactile,
43
+ efficient_net
44
+ ):
45
+
46
+ from SRT_H.SRT_H import ACT
47
+
48
+ from vit_pytorch import ViT
49
+ from vit_pytorch.extractor import Extractor
50
+
51
+ v = ViT(
52
+ image_size = 256,
53
+ patch_size = 32,
54
+ num_classes = 1000,
55
+ dim = 1024,
56
+ depth = 6,
57
+ heads = 16,
58
+ mlp_dim = 2048,
59
+ dropout = 0.1,
60
+ emb_dropout = 0.1
61
+ )
62
+
63
+ v = Extractor(v, return_embeddings_only = True)
64
+
65
+ act = ACT(
66
+ image_model = v if not efficient_net else None,
67
+ image_model_dim_emb = 1024,
68
+ dim = 512,
69
+ dim_joint_state = 17,
70
+ action_chunk_len = 16,
71
+ dim_tactile_input = 37
72
+ )
73
+
74
+ states = torch.randn(3, 512, 512)
75
+ joint_state = torch.randn(3, 17)
76
+
77
+ tactile_input = torch.randn(3, 16, 37) if tactile else None
78
+
79
+ actions = torch.randn(3, 16, 20)
80
+
81
+ video = torch.randn(3, 3, 2, 224, 224)
82
+
83
+ loss = act(
84
+ video = video,
85
+ joint_state = joint_state,
86
+ tactile_input = tactile_input,
87
+ actions = actions
88
+ )
89
+
90
+ loss.backward()
91
+
92
+ # after a lot of data and training ...
93
+
94
+ sampled_actions = act(state_tokens = states, joint_state = joint_state) # (3, 16, 20)