opensportslib 0.0.1.dev2__py3-none-any.whl

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.
Files changed (73) hide show
  1. opensportslib/__init__.py +18 -0
  2. opensportslib/apis/__init__.py +21 -0
  3. opensportslib/apis/classification.py +361 -0
  4. opensportslib/apis/localization.py +228 -0
  5. opensportslib/config/classification.yaml +104 -0
  6. opensportslib/config/classification_tracking.yaml +103 -0
  7. opensportslib/config/graph_tracking_classification/avgpool.yaml +79 -0
  8. opensportslib/config/graph_tracking_classification/gin.yaml +79 -0
  9. opensportslib/config/graph_tracking_classification/graphconv.yaml +79 -0
  10. opensportslib/config/graph_tracking_classification/graphsage.yaml +79 -0
  11. opensportslib/config/graph_tracking_classification/maxpool.yaml +79 -0
  12. opensportslib/config/graph_tracking_classification/noedges.yaml +79 -0
  13. opensportslib/config/localization.yaml +132 -0
  14. opensportslib/config/sngar_frames.yaml +98 -0
  15. opensportslib/core/__init__.py +0 -0
  16. opensportslib/core/loss/__init__.py +0 -0
  17. opensportslib/core/loss/builder.py +40 -0
  18. opensportslib/core/loss/calf.py +258 -0
  19. opensportslib/core/loss/ce.py +23 -0
  20. opensportslib/core/loss/combine.py +42 -0
  21. opensportslib/core/loss/nll.py +25 -0
  22. opensportslib/core/optimizer/__init__.py +0 -0
  23. opensportslib/core/optimizer/builder.py +38 -0
  24. opensportslib/core/sampler/weighted_sampler.py +104 -0
  25. opensportslib/core/scheduler/__init__.py +0 -0
  26. opensportslib/core/scheduler/builder.py +77 -0
  27. opensportslib/core/trainer/__init__.py +0 -0
  28. opensportslib/core/trainer/classification_trainer.py +1131 -0
  29. opensportslib/core/trainer/localization_trainer.py +1009 -0
  30. opensportslib/core/utils/checkpoint.py +238 -0
  31. opensportslib/core/utils/config.py +199 -0
  32. opensportslib/core/utils/data.py +85 -0
  33. opensportslib/core/utils/ddp.py +77 -0
  34. opensportslib/core/utils/default_args.py +110 -0
  35. opensportslib/core/utils/load_annotations.py +485 -0
  36. opensportslib/core/utils/seed.py +26 -0
  37. opensportslib/core/utils/video_processing.py +389 -0
  38. opensportslib/core/utils/wandb.py +110 -0
  39. opensportslib/datasets/__init__.py +0 -0
  40. opensportslib/datasets/builder.py +42 -0
  41. opensportslib/datasets/classification_dataset.py +582 -0
  42. opensportslib/datasets/localization_dataset.py +813 -0
  43. opensportslib/datasets/utils/__init__.py +15 -0
  44. opensportslib/datasets/utils/tracking.py +615 -0
  45. opensportslib/metrics/classification_metric.py +176 -0
  46. opensportslib/metrics/localization_metric.py +1482 -0
  47. opensportslib/models/__init__.py +0 -0
  48. opensportslib/models/backbones/builder.py +590 -0
  49. opensportslib/models/base/e2e.py +252 -0
  50. opensportslib/models/base/tracking.py +73 -0
  51. opensportslib/models/base/vars.py +29 -0
  52. opensportslib/models/base/video.py +130 -0
  53. opensportslib/models/base/video_mae.py +60 -0
  54. opensportslib/models/builder.py +43 -0
  55. opensportslib/models/heads/builder.py +266 -0
  56. opensportslib/models/neck/builder.py +210 -0
  57. opensportslib/models/utils/common.py +176 -0
  58. opensportslib/models/utils/impl/__init__.py +0 -0
  59. opensportslib/models/utils/impl/asformer.py +390 -0
  60. opensportslib/models/utils/impl/calf.py +74 -0
  61. opensportslib/models/utils/impl/gsm.py +112 -0
  62. opensportslib/models/utils/impl/gtad.py +347 -0
  63. opensportslib/models/utils/impl/tsm.py +123 -0
  64. opensportslib/models/utils/litebase.py +59 -0
  65. opensportslib/models/utils/modules.py +120 -0
  66. opensportslib/models/utils/shift.py +135 -0
  67. opensportslib/models/utils/utils.py +276 -0
  68. opensportslib-0.0.1.dev2.dist-info/METADATA +566 -0
  69. opensportslib-0.0.1.dev2.dist-info/RECORD +73 -0
  70. opensportslib-0.0.1.dev2.dist-info/WHEEL +5 -0
  71. opensportslib-0.0.1.dev2.dist-info/licenses/LICENSE +661 -0
  72. opensportslib-0.0.1.dev2.dist-info/licenses/LICENSE-COMMERCIAL +5 -0
  73. opensportslib-0.0.1.dev2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,347 @@
1
+ """
2
+ Copyright 2022 James Hong, Haotian Zhang, Matthew Fisher, Michael Gharbi,
3
+ Kayvon Fatahalian
4
+
5
+ Redistribution and use in source and binary forms, with or without modification,
6
+ are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation and/or
13
+ other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its contributors
16
+ may be used to endorse or promote products derived from this software without
17
+ specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
23
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
26
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
+ """
30
+ # Adapted from: https://github.com/frostinassiky/gtad
31
+ # Original license for GTAD
32
+ """
33
+ Apache License
34
+ Version 2.0, January 2004
35
+ http://www.apache.org/licenses/
36
+
37
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
38
+
39
+ 1. Definitions.
40
+
41
+ "License" shall mean the terms and conditions for use, reproduction,
42
+ and distribution as defined by Sections 1 through 9 of this document.
43
+
44
+ "Licensor" shall mean the copyright owner or entity authorized by
45
+ the copyright owner that is granting the License.
46
+
47
+ "Legal Entity" shall mean the union of the acting entity and all
48
+ other entities that control, are controlled by, or are under common
49
+ control with that entity. For the purposes of this definition,
50
+ "control" means (i) the power, direct or indirect, to cause the
51
+ direction or management of such entity, whether by contract or
52
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
53
+ outstanding shares, or (iii) beneficial ownership of such entity.
54
+
55
+ "You" (or "Your") shall mean an individual or Legal Entity
56
+ exercising permissions granted by this License.
57
+
58
+ "Source" form shall mean the preferred form for making modifications,
59
+ including but not limited to software source code, documentation
60
+ source, and configuration files.
61
+
62
+ "Object" form shall mean any form resulting from mechanical
63
+ transformation or translation of a Source form, including but
64
+ not limited to compiled object code, generated documentation,
65
+ and conversions to other media types.
66
+
67
+ "Work" shall mean the work of authorship, whether in Source or
68
+ Object form, made available under the License, as indicated by a
69
+ copyright notice that is included in or attached to the work
70
+ (an example is provided in the Appendix below).
71
+
72
+ "Derivative Works" shall mean any work, whether in Source or Object
73
+ form, that is based on (or derived from) the Work and for which the
74
+ editorial revisions, annotations, elaborations, or other modifications
75
+ represent, as a whole, an original work of authorship. For the purposes
76
+ of this License, Derivative Works shall not include works that remain
77
+ separable from, or merely link (or bind by name) to the interfaces of,
78
+ the Work and Derivative Works thereof.
79
+
80
+ "Contribution" shall mean any work of authorship, including
81
+ the original version of the Work and any modifications or additions
82
+ to that Work or Derivative Works thereof, that is intentionally
83
+ submitted to Licensor for inclusion in the Work by the copyright owner
84
+ or by an individual or Legal Entity authorized to submit on behalf of
85
+ the copyright owner. For the purposes of this definition, "submitted"
86
+ means any form of electronic, verbal, or written communication sent
87
+ to the Licensor or its representatives, including but not limited to
88
+ communication on electronic mailing lists, source code control systems,
89
+ and issue tracking systems that are managed by, or on behalf of, the
90
+ Licensor for the purpose of discussing and improving the Work, but
91
+ excluding communication that is conspicuously marked or otherwise
92
+ designated in writing by the copyright owner as "Not a Contribution."
93
+
94
+ "Contributor" shall mean Licensor and any individual or Legal Entity
95
+ on behalf of whom a Contribution has been received by Licensor and
96
+ subsequently incorporated within the Work.
97
+
98
+ 2. Grant of Copyright License. Subject to the terms and conditions of
99
+ this License, each Contributor hereby grants to You a perpetual,
100
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
101
+ copyright license to reproduce, prepare Derivative Works of,
102
+ publicly display, publicly perform, sublicense, and distribute the
103
+ Work and such Derivative Works in Source or Object form.
104
+
105
+ 3. Grant of Patent License. Subject to the terms and conditions of
106
+ this License, each Contributor hereby grants to You a perpetual,
107
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
108
+ (except as stated in this section) patent license to make, have made,
109
+ use, offer to sell, sell, import, and otherwise transfer the Work,
110
+ where such license applies only to those patent claims licensable
111
+ by such Contributor that are necessarily infringed by their
112
+ Contribution(s) alone or by combination of their Contribution(s)
113
+ with the Work to which such Contribution(s) was submitted. If You
114
+ institute patent litigation against any entity (including a
115
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
116
+ or a Contribution incorporated within the Work constitutes direct
117
+ or contributory patent infringement, then any patent licenses
118
+ granted to You under this License for that Work shall terminate
119
+ as of the date such litigation is filed.
120
+
121
+ 4. Redistribution. You may reproduce and distribute copies of the
122
+ Work or Derivative Works thereof in any medium, with or without
123
+ modifications, and in Source or Object form, provided that You
124
+ meet the following conditions:
125
+
126
+ (a) You must give any other recipients of the Work or
127
+ Derivative Works a copy of this License; and
128
+
129
+ (b) You must cause any modified files to carry prominent notices
130
+ stating that You changed the files; and
131
+
132
+ (c) You must retain, in the Source form of any Derivative Works
133
+ that You distribute, all copyright, patent, trademark, and
134
+ attribution notices from the Source form of the Work,
135
+ excluding those notices that do not pertain to any part of
136
+ the Derivative Works; and
137
+
138
+ (d) If the Work includes a "NOTICE" text file as part of its
139
+ distribution, then any Derivative Works that You distribute must
140
+ include a readable copy of the attribution notices contained
141
+ within such NOTICE file, excluding those notices that do not
142
+ pertain to any part of the Derivative Works, in at least one
143
+ of the following places: within a NOTICE text file distributed
144
+ as part of the Derivative Works; within the Source form or
145
+ documentation, if provided along with the Derivative Works; or,
146
+ within a display generated by the Derivative Works, if and
147
+ wherever such third-party notices normally appear. The contents
148
+ of the NOTICE file are for informational purposes only and
149
+ do not modify the License. You may add Your own attribution
150
+ notices within Derivative Works that You distribute, alongside
151
+ or as an addendum to the NOTICE text from the Work, provided
152
+ that such additional attribution notices cannot be construed
153
+ as modifying the License.
154
+
155
+ You may add Your own copyright statement to Your modifications and
156
+ may provide additional or different license terms and conditions
157
+ for use, reproduction, or distribution of Your modifications, or
158
+ for any such Derivative Works as a whole, provided Your use,
159
+ reproduction, and distribution of the Work otherwise complies with
160
+ the conditions stated in this License.
161
+
162
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
163
+ any Contribution intentionally submitted for inclusion in the Work
164
+ by You to the Licensor shall be under the terms and conditions of
165
+ this License, without any additional terms or conditions.
166
+ Notwithstanding the above, nothing herein shall supersede or modify
167
+ the terms of any separate license agreement you may have executed
168
+ with Licensor regarding such Contributions.
169
+
170
+ 6. Trademarks. This License does not grant permission to use the trade
171
+ names, trademarks, service marks, or product names of the Licensor,
172
+ except as required for reasonable and customary use in describing the
173
+ origin of the Work and reproducing the content of the NOTICE file.
174
+
175
+ 7. Disclaimer of Warranty. Unless required by applicable law or
176
+ agreed to in writing, Licensor provides the Work (and each
177
+ Contributor provides its Contributions) on an "AS IS" BASIS,
178
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
179
+ implied, including, without limitation, any warranties or conditions
180
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
181
+ PARTICULAR PURPOSE. You are solely responsible for determining the
182
+ appropriateness of using or redistributing the Work and assume any
183
+ risks associated with Your exercise of permissions under this License.
184
+
185
+ 8. Limitation of Liability. In no event and under no legal theory,
186
+ whether in tort (including negligence), contract, or otherwise,
187
+ unless required by applicable law (such as deliberate and grossly
188
+ negligent acts) or agreed to in writing, shall any Contributor be
189
+ liable to You for damages, including any direct, indirect, special,
190
+ incidental, or consequential damages of any character arising as a
191
+ result of this License or out of the use or inability to use the
192
+ Work (including but not limited to damages for loss of goodwill,
193
+ work stoppage, computer failure or malfunction, or any and all
194
+ other commercial damages or losses), even if such Contributor
195
+ has been advised of the possibility of such damages.
196
+
197
+ 9. Accepting Warranty or Additional Liability. While redistributing
198
+ the Work or Derivative Works thereof, You may choose to offer,
199
+ and charge a fee for, acceptance of support, warranty, indemnity,
200
+ or other liability obligations and/or rights consistent with this
201
+ License. However, in accepting such obligations, You may act only
202
+ on Your own behalf and on Your sole responsibility, not on behalf
203
+ of any other Contributor, and only if You agree to indemnify,
204
+ defend, and hold each Contributor harmless for any liability
205
+ incurred by, or claims asserted against, such Contributor by reason
206
+ of your accepting any such warranty or additional liability.
207
+
208
+ END OF TERMS AND CONDITIONS
209
+
210
+ APPENDIX: How to apply the Apache License to your work.
211
+
212
+ To apply the Apache License to your work, attach the following
213
+ boilerplate notice, with the fields enclosed by brackets "[]"
214
+ replaced with your own identifying information. (Don't include
215
+ the brackets!) The text should be enclosed in the appropriate
216
+ comment syntax for the file format. We also recommend that a
217
+ file or class name and description of purpose be included on the
218
+ same "printed page" as the copyright notice for easier
219
+ identification within third-party archives.
220
+
221
+ Copyright [yyyy] [name of copyright owner]
222
+
223
+ Licensed under the Apache License, Version 2.0 (the "License");
224
+ you may not use this file except in compliance with the License.
225
+ You may obtain a copy of the License at
226
+
227
+ http://www.apache.org/licenses/LICENSE-2.0
228
+
229
+ Unless required by applicable law or agreed to in writing, software
230
+ distributed under the License is distributed on an "AS IS" BASIS,
231
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
232
+ See the License for the specific language governing permissions and
233
+ limitations under the License.
234
+ """
235
+
236
+ import math
237
+ import numpy as np
238
+ import torch
239
+ import torch.nn as nn
240
+
241
+
242
+ # dynamic graph from knn
243
+ def knn(x, y=None, k=10):
244
+ """
245
+ :param x: BxCxN
246
+ :param y: BxCxM
247
+ :param k: scalar
248
+ :return: BxMxk
249
+ """
250
+ if y is None:
251
+ y = x
252
+ # logging.info('Size in KNN: {} - {}'.format(x.size(), y.size()))
253
+ inner = -2 * torch.matmul(y.transpose(2, 1), x)
254
+ xx = torch.sum(x ** 2, dim=1, keepdim=True)
255
+ yy = torch.sum(y ** 2, dim=1, keepdim=True)
256
+ pairwise_distance = -xx - inner - yy.transpose(2, 1)
257
+ _, idx = pairwise_distance.topk(k=k, dim=-1) # (batch_size, num_points, k)
258
+ return idx
259
+
260
+
261
+ # get graph feature
262
+ def get_graph_feature(x, prev_x=None, k=20, idx_knn=None, r=-1, style=0):
263
+ """
264
+ :param x:
265
+ :param prev_x:
266
+ :param k:
267
+ :param idx:
268
+ :param r: output downsampling factor (-1 for no downsampling)
269
+ :param style: method to get graph feature
270
+ :return:
271
+ """
272
+ batch_size = x.size(0)
273
+ num_points = x.size(2) # if prev_x is None else prev_x.size(2)
274
+ x = x.view(batch_size, -1, num_points)
275
+ if idx_knn is None:
276
+ idx_knn = knn(x=x, y=prev_x, k=k) # (batch_size, num_points, k)
277
+ else:
278
+ k = idx_knn.shape[-1]
279
+ # print(idx_knn.shape)
280
+ device = x.device # torch.device('cuda')
281
+ idx_base = torch.arange(0, batch_size, device=device).view(-1, 1, 1) * num_points
282
+ idx = idx_knn + idx_base
283
+ idx = idx.view(-1)
284
+ _, num_dims, _ = x.size()
285
+ x = x.transpose(2, 1).contiguous() # (batch_size, num_points, num_dims) -> (batch_size*num_points, num_dims)
286
+ feature = x.view(batch_size * num_points, -1)[idx, :]
287
+ feature = feature.view(batch_size, num_points, k, num_dims)
288
+ x = x.view(batch_size, num_points, 1, num_dims).repeat(1, 1, k, 1)
289
+ if style == 0: # use offset as feature
290
+ feature = torch.cat((feature - x, x), dim=3).permute(0, 3, 1, 2)
291
+ elif style == 1: # use feature as feature
292
+ feature = torch.cat((feature, x), dim=3).permute(0, 3, 1, 2)
293
+ else: # style == 2:
294
+ feature = feature.permute(0,3,1,2)
295
+ # downsample if needed
296
+ if r != -1:
297
+ select_idx = torch.from_numpy(np.random.choice(feature.size(2), feature.size(2) // r,
298
+ replace=False)).to(device=device)
299
+ feature = feature[:, :, select_idx, :]
300
+ return feature, idx_knn
301
+
302
+
303
+ # basic block
304
+ class GCNeXt(nn.Module):
305
+ def __init__(self, channel_in, channel_out, k=3, norm_layer=None,
306
+ groups=32, width_group=4, idx=None):
307
+ super(GCNeXt, self).__init__()
308
+ self.k = k
309
+ self.groups = groups
310
+
311
+ if norm_layer is None:
312
+ norm_layer = nn.BatchNorm1d
313
+ width = width_group * groups
314
+ self.tconvs = nn.Sequential(
315
+ nn.Conv1d(channel_in, width, kernel_size=1), nn.ReLU(True),
316
+ nn.Conv1d(width, width, kernel_size=3, groups=groups, padding=1), nn.ReLU(True),
317
+ nn.Conv1d(width, channel_out, kernel_size=1),
318
+ ) # temporal graph
319
+
320
+ self.sconvs = nn.Sequential(
321
+ nn.Conv2d(channel_in * 2, width, kernel_size=1), nn.ReLU(True),
322
+ nn.Conv2d(width, width, kernel_size=1, groups=groups), nn.ReLU(True),
323
+ nn.Conv2d(width, channel_out, kernel_size=1),
324
+ ) # semantic graph
325
+
326
+ self.relu = nn.ReLU(True)
327
+ self.idx_list = idx
328
+
329
+ def forward(self, x):
330
+ identity = x # residual
331
+ tout = self.tconvs(x) # conv on temporal graph
332
+
333
+
334
+ if self.k < 1:
335
+ k = math.ceil(x.shape[-1] * self.k)
336
+ else:
337
+ k = self.k
338
+
339
+ x_f, idx = get_graph_feature(x, k=k, style=1) # (bs,ch,100) -> (bs, 2ch, 100, k)
340
+
341
+ sout = self.sconvs(x_f) # conv on semantic graph
342
+ sout = sout.max(dim=-1, keepdim=False)[0] # (bs, ch, 100, k) -> (bs, ch, 100)
343
+
344
+ out = tout + identity + sout # fusion
345
+ if not self.idx_list is None:
346
+ self.idx_list.append(idx)
347
+ return self.relu(out)
@@ -0,0 +1,123 @@
1
+ """
2
+ Copyright 2022 James Hong, Haotian Zhang, Matthew Fisher, Michael Gharbi,
3
+ Kayvon Fatahalian
4
+
5
+ Redistribution and use in source and binary forms, with or without modification,
6
+ are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation and/or
13
+ other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its contributors
16
+ may be used to endorse or promote products derived from this software without
17
+ specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
23
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
26
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
+ """
30
+ # TSM code adapted from: https://github.com/mit-han-lab/temporal-shift-module/blob/master/ops/temporal_shift.py
31
+ # Original license for TSM
32
+ """
33
+ MIT License
34
+
35
+ Copyright (c) 2021 MIT HAN Lab
36
+
37
+ Permission is hereby granted, free of charge, to any person obtaining a copy
38
+ of this software and associated documentation files (the "Software"), to deal
39
+ in the Software without restriction, including without limitation the rights
40
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
41
+ copies of the Software, and to permit persons to whom the Software is
42
+ furnished to do so, subject to the following conditions:
43
+
44
+ The above copyright notice and this permission notice shall be included in all
45
+ copies or substantial portions of the Software.
46
+
47
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
48
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
49
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
50
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
51
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
52
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
53
+ SOFTWARE.
54
+ """
55
+
56
+ import torch
57
+ import torch.nn as nn
58
+
59
+
60
+ class TemporalShift(nn.Module):
61
+ def __init__(self, net, n_segment, n_div, inplace=True):
62
+ super(TemporalShift, self).__init__()
63
+ self.net = net
64
+ self.n_segment = n_segment
65
+ self.fold_div = n_div
66
+ self.inplace = inplace
67
+ if inplace:
68
+ print('=> Using TSM, in-place shift...')
69
+ print('=> Using TSM, fold div: {}'.format(self.fold_div))
70
+
71
+ def forward(self, x):
72
+ x = self.shift(x, self.n_segment, fold_div=self.fold_div,
73
+ inplace=self.inplace)
74
+ return self.net(x)
75
+
76
+ @staticmethod
77
+ def shift(x, n_segment, fold_div=3, inplace=False):
78
+ nt, c, h, w = x.size()
79
+ n_batch = nt // n_segment
80
+ x = x.view(n_batch, n_segment, c, h, w)
81
+
82
+ fold = c // fold_div
83
+ if inplace:
84
+ # Due to some out of order error when performing parallel computing.
85
+ # May need to write a CUDA kernel.
86
+ out = InplaceShift.apply(x, fold)
87
+ else:
88
+ out = torch.zeros_like(x)
89
+ out[:, :-1, :fold] = x[:, 1:, :fold] # shift left
90
+ out[:, 1:, fold: 2 * fold] = x[:, :-1, fold: 2 * fold] # shift right
91
+ out[:, :, 2 * fold:] = x[:, :, 2 * fold:] # not shift
92
+
93
+ return out.view(nt, c, h, w)
94
+
95
+
96
+ class InplaceShift(torch.autograd.Function):
97
+ # Special thanks to @raoyongming for the help to this function
98
+ @staticmethod
99
+ def forward(ctx, input, fold):
100
+ # not support higher order gradient
101
+ # input = input.detach_()
102
+ ctx.fold_ = fold
103
+ n, t, c, h, w = input.size()
104
+ buffer = input.data.new(n, t, fold, h, w).zero_()
105
+ buffer[:, :-1] = input.data[:, 1:, :fold]
106
+ input.data[:, :, :fold] = buffer
107
+ buffer.zero_()
108
+ buffer[:, 1:] = input.data[:, :-1, fold: 2 * fold]
109
+ input.data[:, :, fold: 2 * fold] = buffer
110
+ return input
111
+
112
+ @staticmethod
113
+ def backward(ctx, grad_output):
114
+ # grad_output = grad_output.detach_()
115
+ fold = ctx.fold_
116
+ n, t, c, h, w = grad_output.size()
117
+ buffer = grad_output.data.new(n, t, fold, h, w).zero_()
118
+ buffer[:, 1:] = grad_output.data[:, :-1, :fold]
119
+ grad_output.data[:, :, :fold] = buffer
120
+ buffer.zero_()
121
+ buffer[:, :-1] = grad_output.data[:, 1:, fold: 2 * fold]
122
+ grad_output.data[:, :, fold: 2 * fold] = buffer
123
+ return grad_output, None
@@ -0,0 +1,59 @@
1
+ import logging
2
+ import pytorch_lightning as pl
3
+
4
+ import time
5
+ from SoccerNet.Evaluation.utils import AverageMeter
6
+
7
+ from oslactionspotting.core.loss.builder import build_criterion
8
+ from oslactionspotting.core.scheduler.builder import build_scheduler
9
+ from oslactionspotting.core.optimizer.builder import build_optimizer
10
+
11
+
12
+ class LiteBaseModel(pl.LightningModule):
13
+ """Parent class for lightning module.
14
+ Args:
15
+ cfg_train (dict): Dict of config.
16
+ """
17
+
18
+ def __init__(self, cfg_train):
19
+
20
+ super().__init__()
21
+
22
+ if cfg_train:
23
+ logging.info('Build criterion')
24
+ self.criterion = build_criterion(cfg_train.criterion)
25
+ logging.info(self.criterion)
26
+ self.cfg_train = cfg_train
27
+
28
+ self.best_loss = 9e99
29
+
30
+ def forward(self, inputs):
31
+ return self.model(inputs)
32
+
33
+ def on_train_epoch_start(self):
34
+ self.batch_time, self.data_time, self.losses, self.end = self.pre_loop()
35
+
36
+ def on_validation_epoch_start(self):
37
+ self.batch_time, self.data_time, self.losses, self.end = self.pre_loop()
38
+
39
+ def on_train_epoch_end(self):
40
+ print("")
41
+ self.losses_avg = self.losses.avg
42
+
43
+ def on_fit_end(self) -> None:
44
+ return self.best_state
45
+
46
+ def configure_optimizers(self):
47
+ logging.info('Build optimizer')
48
+ self.optimizer = build_optimizer(self.parameters(), self.cfg_train.optimizer)
49
+ logging.info(self.optimizer)
50
+ logging.info('Build Scheduler')
51
+ self.scheduler = build_scheduler(self.optimizer, self.cfg_train.scheduler)
52
+ return self.optimizer
53
+
54
+ def pre_loop(self):
55
+ batch_time = AverageMeter()
56
+ data_time = AverageMeter()
57
+ losses = AverageMeter()
58
+ end = time.time()
59
+ return batch_time, data_time, losses, end
@@ -0,0 +1,120 @@
1
+ """
2
+ Copyright 2022 James Hong, Haotian Zhang, Matthew Fisher, Michael Gharbi,
3
+ Kayvon Fatahalian
4
+
5
+ Redistribution and use in source and binary forms, with or without modification,
6
+ are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation and/or
13
+ other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its contributors
16
+ may be used to endorse or promote products derived from this software without
17
+ specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
23
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
26
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
+ """
30
+ import math
31
+ import torch
32
+ import torch.nn as nn
33
+ import torch.nn.functional as F
34
+
35
+ from opensportslib.models.utils.common import SingleStageTCN
36
+ from .impl.asformer import MyTransformer
37
+
38
+
39
+ class FCPrediction(nn.Module):
40
+
41
+ def __init__(self, feat_dim, num_classes):
42
+ super().__init__()
43
+ self._fc_out = nn.Linear(feat_dim, num_classes)
44
+
45
+ def forward(self, x):
46
+ batch_size, clip_len, _ = x.shape
47
+ return self._fc_out(x.reshape(batch_size * clip_len, -1)).view(
48
+ batch_size, clip_len, -1
49
+ )
50
+
51
+
52
+ class GRUPrediction(nn.Module):
53
+
54
+ def __init__(self, feat_dim, num_classes, hidden_dim, num_layers=1):
55
+ super().__init__()
56
+ self._gru = nn.GRU(
57
+ feat_dim,
58
+ hidden_dim,
59
+ num_layers=num_layers,
60
+ batch_first=True,
61
+ bidirectional=True,
62
+ )
63
+ self._fc_out = FCPrediction(2 * hidden_dim, num_classes)
64
+ self._dropout = nn.Dropout()
65
+
66
+ def forward(self, x):
67
+ y, _ = self._gru(x)
68
+ return self._fc_out(self._dropout(y))
69
+
70
+
71
+ class TCNPrediction(nn.Module):
72
+
73
+ def __init__(self, feat_dim, num_classes, num_stages=1, num_layers=5):
74
+ super().__init__()
75
+
76
+ self._tcn = SingleStageTCN(feat_dim, 256, num_classes, num_layers, True)
77
+ self._stages = None
78
+ if num_stages > 1:
79
+ self._stages = nn.ModuleList(
80
+ [
81
+ SingleStageTCN(num_classes, 256, num_classes, num_layers, True)
82
+ for _ in range(num_stages - 1)
83
+ ]
84
+ )
85
+
86
+ def forward(self, x):
87
+ x = self._tcn(x)
88
+ if self._stages is None:
89
+ return x
90
+ else:
91
+ outputs = [x]
92
+ for stage in self._stages:
93
+ x = stage(F.softmax(x, dim=2))
94
+ outputs.append(x)
95
+ return torch.stack(outputs, dim=0)
96
+
97
+
98
+ class ASFormerPrediction(nn.Module):
99
+
100
+ def __init__(self, feat_dim, num_classes, num_decoders=3, num_layers=5):
101
+ super().__init__()
102
+
103
+ r1, r2 = 2, 2
104
+ num_f_maps = 64
105
+ self._net = MyTransformer(
106
+ num_decoders,
107
+ num_layers,
108
+ r1,
109
+ r2,
110
+ num_f_maps,
111
+ feat_dim,
112
+ num_classes,
113
+ channel_masking_rate=0.3,
114
+ )
115
+
116
+ def forward(self, x):
117
+ B, T, D = x.shape
118
+ return self._net(
119
+ x.permute(0, 2, 1), torch.ones((B, 1, T), device=x.device)
120
+ ).permute(0, 1, 3, 2)