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,104 @@
1
+ from torch.utils.data import DataLoader, WeightedRandomSampler
2
+ from transformers import Trainer as HFTrainer
3
+ import torch
4
+
5
+ class WeightedTrainer(HFTrainer):
6
+ def __init__(self, *args, config=None, **kwargs):
7
+ super().__init__(*args, **kwargs)
8
+ self.config = config
9
+ # --- Weighted training loader ---
10
+ def get_train_dataloader(self):
11
+ if self.train_dataset is None:
12
+ raise ValueError("Trainer: training requires a train_dataset.")
13
+
14
+ weights = self.train_dataset.get_sample_weights()
15
+ #print(f"Sample weights: {max(weights)} {min(weights)}")
16
+ sampler = WeightedRandomSampler(weights, num_samples=len(weights), replacement=True)
17
+
18
+ return DataLoader(
19
+ self.train_dataset,
20
+ batch_size=self.args.per_device_train_batch_size, # per-device batch size
21
+ sampler=sampler,
22
+ num_workers=self.args.dataloader_num_workers if hasattr(self.args, "dataloader_num_workers") else 0,
23
+ pin_memory=True,
24
+ )
25
+
26
+ def get_eval_dataloader(self, eval_dataset=None):
27
+ eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset
28
+ if eval_dataset is None:
29
+ raise ValueError("Trainer: evaluation requires an eval_dataset.")
30
+
31
+ return DataLoader(
32
+ eval_dataset,
33
+ batch_size=self.args.per_device_eval_batch_size, # validation batch size
34
+ shuffle=False, # do not shuffle evaluation
35
+ num_workers=self.args.dataloader_num_workers if hasattr(self.args, "dataloader_num_workers") else 0,
36
+ pin_memory=True,
37
+ )
38
+
39
+ def create_optimizer(self):
40
+ if self.optimizer is not None:
41
+ return self.optimizer
42
+
43
+ model = self.model
44
+
45
+ optimizer_grouped_parameters = []
46
+ print("Weighted trainer ", self.config.TRAIN.optimizer.head_lr, self.config.TRAIN.optimizer.backbone_lr)
47
+ # ---- Classifier head ----
48
+ if self.config.MODEL.unfreeze_head:
49
+ optimizer_grouped_parameters.append({
50
+ "params": model.classifier.parameters(),
51
+ "lr": self.config.TRAIN.optimizer.head_lr,
52
+ })
53
+
54
+ # ---- Backbone (last N layers) ----
55
+ n = self.config.MODEL.unfreeze_last_n_layers
56
+ if n > 0:
57
+ optimizer_grouped_parameters.append({
58
+ "params": model.videomae.encoder.layer[-n:].parameters(),
59
+ "lr": self.config.TRAIN.optimizer.backbone_lr,
60
+ })
61
+
62
+ self.optimizer = torch.optim.AdamW(
63
+ optimizer_grouped_parameters,
64
+ weight_decay=self.config.TRAIN.optimizer.weight_decay,
65
+ )
66
+
67
+ return self.optimizer
68
+
69
+ from transformers.optimization import get_scheduler
70
+ class VideoMAETrainer(HFTrainer):
71
+ def __init__(self, *args, config=None, **kwargs):
72
+ super().__init__(*args, **kwargs)
73
+ self.config = config
74
+
75
+ def create_optimizer(self):
76
+ if self.optimizer is not None:
77
+ return self.optimizer
78
+
79
+ model = self.model
80
+
81
+ optimizer_grouped_parameters = []
82
+ print(type(self.config.TRAIN.optimizer.head_lr), type(self.config.TRAIN.optimizer.backbone_lr))
83
+ # ---- Classifier head ----
84
+ if self.config.MODEL.unfreeze_head:
85
+ optimizer_grouped_parameters.append({
86
+ "params": model.classifier.parameters(),
87
+ "lr": self.config.TRAIN.optimizer.head_lr,
88
+ })
89
+
90
+ # ---- Backbone (last N layers) ----
91
+ n = self.config.MODEL.unfreeze_last_n_layers
92
+ if n > 0:
93
+ optimizer_grouped_parameters.append({
94
+ "params": model.videomae.encoder.layer[-n:].parameters(),
95
+ "lr": self.config.TRAIN.optimizer.backbone_lr,
96
+ })
97
+
98
+ self.optimizer = torch.optim.AdamW(
99
+ optimizer_grouped_parameters,
100
+ weight_decay=self.config.TRAIN.optimizer.weight_decay,
101
+ )
102
+
103
+ return self.optimizer
104
+
File without changes
@@ -0,0 +1,77 @@
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 torch
31
+ from torch.optim.lr_scheduler import ChainedScheduler, LinearLR, CosineAnnealingLR
32
+ import logging
33
+
34
+
35
+ def build_scheduler(optimizer, cfg, default_args=None):
36
+ """Build a scheduler from config dict.
37
+
38
+ Args:
39
+ cfg (dict): Config dict. It should at least contain the key "type".
40
+ default_args (dict | None, optional): Default initialization arguments.
41
+ Default: None.
42
+
43
+ Returns:
44
+ scheduler: The constructed scheduler.
45
+ """
46
+ if cfg.type == "ReduceLROnPlateau":
47
+ scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
48
+ optimizer, mode=cfg.mode, patience=cfg.patience,
49
+ factor=getattr(cfg, "factor", 0.1),
50
+ min_lr=getattr(cfg, "min_lr", 0),
51
+ )
52
+ logging.info("Using ReduceLROnPlateau")
53
+ elif cfg.type == "ChainedSchedulerE2E":
54
+ # Warmup schedule
55
+ num_steps_per_epoch = default_args["len_train_loader"] // cfg.acc_grad_iter
56
+ cosine_epochs = cfg.num_epochs - cfg.warm_up_epochs
57
+ scheduler = ChainedScheduler(
58
+ [
59
+ LinearLR(
60
+ optimizer,
61
+ start_factor=0.01,
62
+ end_factor=1.0,
63
+ total_iters=cfg.warm_up_epochs * num_steps_per_epoch,
64
+ ),
65
+ CosineAnnealingLR(optimizer, num_steps_per_epoch * cosine_epochs),
66
+ ]
67
+ )
68
+ logging.info(
69
+ "Using Linear Warmup ({}) + Cosine Annealing LR ({})".format(
70
+ cfg.warm_up_epochs, cosine_epochs
71
+ )
72
+ )
73
+ elif cfg.type == "StepLR":
74
+ scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=cfg.step_size, gamma=cfg.gamma)
75
+ else:
76
+ scheduler = None
77
+ return scheduler
File without changes