openpoints 0.1.0__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 (184) hide show
  1. openpoints/__init__.py +3 -0
  2. openpoints/cpp/__init__.py +6 -0
  3. openpoints/cpp/chamfer_dist/__init__.py +110 -0
  4. openpoints/cpp/chamfer_dist/setup.py +19 -0
  5. openpoints/cpp/chamfer_dist/test.py +34 -0
  6. openpoints/cpp/emd/__init__.py +3 -0
  7. openpoints/cpp/emd/emd.py +88 -0
  8. openpoints/cpp/emd/setup.py +27 -0
  9. openpoints/cpp/emd/test_emd_loss.py +45 -0
  10. openpoints/cpp/pointnet2_batch/__init__.py +24 -0
  11. openpoints/cpp/pointnet2_batch/setup.py +23 -0
  12. openpoints/cpp/pointops/__init__.py +0 -0
  13. openpoints/cpp/pointops/functions/__init__.py +0 -0
  14. openpoints/cpp/pointops/functions/pointops.py +314 -0
  15. openpoints/cpp/pointops/setup.py +37 -0
  16. openpoints/cpp/pointops/src/__init__.py +0 -0
  17. openpoints/dataset/__init__.py +10 -0
  18. openpoints/dataset/atom3d/__init__.py +1 -0
  19. openpoints/dataset/atom3d/psr.py +38 -0
  20. openpoints/dataset/build.py +98 -0
  21. openpoints/dataset/data_util.py +192 -0
  22. openpoints/dataset/datalist.py +67 -0
  23. openpoints/dataset/dataset_base.py +96 -0
  24. openpoints/dataset/graph_dataset/__init__.py +3 -0
  25. openpoints/dataset/graph_dataset/graph_dataset.py +93 -0
  26. openpoints/dataset/graph_dataset/stack_with_pad.py +91 -0
  27. openpoints/dataset/graph_dataset/structural_dataset.py +73 -0
  28. openpoints/dataset/graph_dataset/svd_encodings_dataset.py +110 -0
  29. openpoints/dataset/grid_sample.py +21 -0
  30. openpoints/dataset/matterport3d/__init__.py +1 -0
  31. openpoints/dataset/matterport3d/category_mapping.tsv +1660 -0
  32. openpoints/dataset/matterport3d/matterport3d.py +210 -0
  33. openpoints/dataset/matterport3d/matterport3d_dataprocessing.py +105 -0
  34. openpoints/dataset/modelnet/__init__.py +3 -0
  35. openpoints/dataset/modelnet/modelnet40_normal_resampled_loader.py +124 -0
  36. openpoints/dataset/modelnet/modelnet40_ply_2048_loader.py +160 -0
  37. openpoints/dataset/molhiv/__init__.py +1 -0
  38. openpoints/dataset/molhiv/data.py +59 -0
  39. openpoints/dataset/molpcba/__init__.py +1 -0
  40. openpoints/dataset/molpcba/data.py +59 -0
  41. openpoints/dataset/parsers/__init__.py +1 -0
  42. openpoints/dataset/parsers/class_map.py +19 -0
  43. openpoints/dataset/parsers/constants.py +1 -0
  44. openpoints/dataset/parsers/parser.py +17 -0
  45. openpoints/dataset/parsers/parser_factory.py +29 -0
  46. openpoints/dataset/parsers/parser_image_folder.py +69 -0
  47. openpoints/dataset/parsers/parser_image_in_tar.py +222 -0
  48. openpoints/dataset/parsers/parser_image_tar.py +72 -0
  49. openpoints/dataset/parsers/parser_tfds.py +297 -0
  50. openpoints/dataset/pcqm4m/__init__.py +1 -0
  51. openpoints/dataset/pcqm4m/data.py +62 -0
  52. openpoints/dataset/pcqm4mv2/__init__.py +1 -0
  53. openpoints/dataset/pcqm4mv2/data.py +87 -0
  54. openpoints/dataset/s3dis/__init__.py +2 -0
  55. openpoints/dataset/s3dis/s3dis.py +156 -0
  56. openpoints/dataset/s3dis/s3dis_block.py +96 -0
  57. openpoints/dataset/s3dis/s3dis_sphere.py +349 -0
  58. openpoints/dataset/scannetv2/__init__.py +1 -0
  59. openpoints/dataset/scannetv2/scannet.py +176 -0
  60. openpoints/dataset/scanobjectnn/__init__.py +3 -0
  61. openpoints/dataset/scanobjectnn/scanobjectnn.py +110 -0
  62. openpoints/dataset/semantic_kitti/__init__.py +1 -0
  63. openpoints/dataset/semantic_kitti/helper_tool.py +286 -0
  64. openpoints/dataset/semantic_kitti/label_mapping.yaml +211 -0
  65. openpoints/dataset/semantic_kitti/semantickitti.py +229 -0
  66. openpoints/dataset/semantic_kitti/utils/meta/anno_paths.txt +272 -0
  67. openpoints/dataset/semantic_kitti/utils/meta/class_names.txt +13 -0
  68. openpoints/dataset/semantic_kitti/utils/semantic-kitti.yaml +211 -0
  69. openpoints/dataset/shapenet/__init__.py +1 -0
  70. openpoints/dataset/shapenet/shapenet55.py +76 -0
  71. openpoints/dataset/shapenet/shapenetpart.py +121 -0
  72. openpoints/dataset/shapenetpart/__init__.py +1 -0
  73. openpoints/dataset/shapenetpart/shapenet55.py +75 -0
  74. openpoints/dataset/shapenetpart/shapenetpart.py +388 -0
  75. openpoints/dataset/vis2d.py +17 -0
  76. openpoints/dataset/vis3d.py +153 -0
  77. openpoints/loss/__init__.py +3 -0
  78. openpoints/loss/build.py +281 -0
  79. openpoints/loss/cross_entropy.py +38 -0
  80. openpoints/loss/distill_loss.py +76 -0
  81. openpoints/models/__init__.py +10 -0
  82. openpoints/models/backbone/Stratified_transformer.py +558 -0
  83. openpoints/models/backbone/__init__.py +11 -0
  84. openpoints/models/backbone/baafnet.py +527 -0
  85. openpoints/models/backbone/ball_dgcnn.py +123 -0
  86. openpoints/models/backbone/curvenet.py +793 -0
  87. openpoints/models/backbone/debug_invvit.py +114 -0
  88. openpoints/models/backbone/deepgcn.py +143 -0
  89. openpoints/models/backbone/dgcnn.py +119 -0
  90. openpoints/models/backbone/graphvit3d.py +134 -0
  91. openpoints/models/backbone/grouppointnet.py +100 -0
  92. openpoints/models/backbone/pct.py +163 -0
  93. openpoints/models/backbone/pointmlp.py +417 -0
  94. openpoints/models/backbone/pointnet.py +199 -0
  95. openpoints/models/backbone/pointnetv2.py +511 -0
  96. openpoints/models/backbone/pointnext.py +663 -0
  97. openpoints/models/backbone/pointnextPyG.py +555 -0
  98. openpoints/models/backbone/pointtransformer.py +293 -0
  99. openpoints/models/backbone/pointvector.py +853 -0
  100. openpoints/models/backbone/pointvit.py +392 -0
  101. openpoints/models/backbone/pointvit_inv.py +942 -0
  102. openpoints/models/backbone/pointvit_inv_old.py +784 -0
  103. openpoints/models/backbone/randlenet.py +318 -0
  104. openpoints/models/backbone/resnet.py +342 -0
  105. openpoints/models/backbone/simpleview.py +153 -0
  106. openpoints/models/backbone/simpleview_util.py +292 -0
  107. openpoints/models/build.py +13 -0
  108. openpoints/models/classification/__init__.py +5 -0
  109. openpoints/models/classification/cls_base.py +136 -0
  110. openpoints/models/classification/point_bert.py +154 -0
  111. openpoints/models/layers/__init__.py +14 -0
  112. openpoints/models/layers/activation.py +57 -0
  113. openpoints/models/layers/attention.py +103 -0
  114. openpoints/models/layers/conv.py +167 -0
  115. openpoints/models/layers/drop.py +164 -0
  116. openpoints/models/layers/graph_conv.py +122 -0
  117. openpoints/models/layers/group.py +415 -0
  118. openpoints/models/layers/group_embed.py +286 -0
  119. openpoints/models/layers/helpers.py +43 -0
  120. openpoints/models/layers/kmeans.py +119 -0
  121. openpoints/models/layers/knn.py +110 -0
  122. openpoints/models/layers/local_aggregation.py +286 -0
  123. openpoints/models/layers/mlp.py +129 -0
  124. openpoints/models/layers/norm.py +106 -0
  125. openpoints/models/layers/padding.py +56 -0
  126. openpoints/models/layers/patch_embed.py +37 -0
  127. openpoints/models/layers/registry.py +168 -0
  128. openpoints/models/layers/subsample.py +185 -0
  129. openpoints/models/layers/upsampling.py +106 -0
  130. openpoints/models/layers/weight_init.py +89 -0
  131. openpoints/models/reconstruction/__init__.py +8 -0
  132. openpoints/models/reconstruction/base_recontruct.py +216 -0
  133. openpoints/models/reconstruction/maskedpoint.py +116 -0
  134. openpoints/models/reconstruction/maskedpointgroup.py +168 -0
  135. openpoints/models/reconstruction/maskedpointvit.py +253 -0
  136. openpoints/models/reconstruction/nodeshuffle.py +11 -0
  137. openpoints/models/registry.py +149 -0
  138. openpoints/models/segmentation/__init__.py +6 -0
  139. openpoints/models/segmentation/base_seg.py +278 -0
  140. openpoints/models/segmentation/vit_seg.py +126 -0
  141. openpoints/optim/__init__.py +15 -0
  142. openpoints/optim/adabelief.py +201 -0
  143. openpoints/optim/adafactor.py +167 -0
  144. openpoints/optim/adahessian.py +156 -0
  145. openpoints/optim/adamp.py +105 -0
  146. openpoints/optim/adamw.py +122 -0
  147. openpoints/optim/lamb.py +192 -0
  148. openpoints/optim/lars.py +135 -0
  149. openpoints/optim/lookahead.py +61 -0
  150. openpoints/optim/madgrad.py +184 -0
  151. openpoints/optim/nadam.py +92 -0
  152. openpoints/optim/nvnovograd.py +120 -0
  153. openpoints/optim/optim_factory.py +306 -0
  154. openpoints/optim/radam.py +89 -0
  155. openpoints/optim/rmsprop_tf.py +139 -0
  156. openpoints/optim/sgdp.py +70 -0
  157. openpoints/scheduler/__init__.py +8 -0
  158. openpoints/scheduler/cosine_lr.py +124 -0
  159. openpoints/scheduler/multistep_lr.py +65 -0
  160. openpoints/scheduler/plateau_lr.py +113 -0
  161. openpoints/scheduler/poly_lr.py +116 -0
  162. openpoints/scheduler/scheduler.py +110 -0
  163. openpoints/scheduler/scheduler_factory.py +118 -0
  164. openpoints/scheduler/step_lr.py +65 -0
  165. openpoints/scheduler/tanh_lr.py +117 -0
  166. openpoints/transforms/__init__.py +7 -0
  167. openpoints/transforms/point_transform_cpu.py +332 -0
  168. openpoints/transforms/point_transformer_gpu.py +764 -0
  169. openpoints/transforms/transforms_factory.py +60 -0
  170. openpoints/utils/__init__.py +8 -0
  171. openpoints/utils/ckpt_util.py +438 -0
  172. openpoints/utils/config.py +113 -0
  173. openpoints/utils/dist_utils.py +54 -0
  174. openpoints/utils/logger.py +170 -0
  175. openpoints/utils/metrics.py +311 -0
  176. openpoints/utils/random.py +16 -0
  177. openpoints/utils/registry.py +294 -0
  178. openpoints/utils/str2bool.py +11 -0
  179. openpoints/utils/wandb.py +88 -0
  180. openpoints-0.1.0.dist-info/METADATA +150 -0
  181. openpoints-0.1.0.dist-info/RECORD +184 -0
  182. openpoints-0.1.0.dist-info/WHEEL +5 -0
  183. openpoints-0.1.0.dist-info/licenses/LICENSE +21 -0
  184. openpoints-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,192 @@
1
+ """ PyTorch Lamb optimizer w/ behaviour similar to NVIDIA FusedLamb
2
+
3
+ This optimizer code was adapted from the following (starting with latest)
4
+ * https://github.com/HabanaAI/Model-References/blob/2b435114fe8e31f159b1d3063b8280ae37af7423/PyTorch/nlp/bert/pretraining/lamb.py
5
+ * https://github.com/NVIDIA/DeepLearningExamples/blob/master/PyTorch/LanguageModeling/Transformer-XL/pytorch/lamb.py
6
+ * https://github.com/cybertronai/pytorch-lamb
7
+
8
+ Use FusedLamb if you can (GPU). The reason for including this variant of Lamb is to have a version that is
9
+ similar in behaviour to APEX FusedLamb if you aren't using NVIDIA GPUs or cannot install/use APEX.
10
+
11
+ In addition to some cleanup, this Lamb impl has been modified to support PyTorch XLA and has been tested on TPU.
12
+
13
+ Original copyrights for above sources are below.
14
+
15
+ Modifications Copyright 2021 Ross Wightman
16
+ """
17
+ # Copyright (c) 2021, Habana Labs Ltd. All rights reserved.
18
+
19
+ # Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
20
+ #
21
+ # Licensed under the Apache License, Version 2.0 (the "License");
22
+ # you may not use this file except in compliance with the License.
23
+ # You may obtain a copy of the License at
24
+ #
25
+ # http://www.apache.org/licenses/LICENSE-2.0
26
+ #
27
+ # Unless required by applicable law or agreed to in writing, software
28
+ # distributed under the License is distributed on an "AS IS" BASIS,
29
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
30
+ # See the License for the specific language governing permissions and
31
+ # limitations under the License.
32
+
33
+ # MIT License
34
+ #
35
+ # Copyright (c) 2019 cybertronai
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
+ import math
55
+
56
+ import torch
57
+ from torch.optim import Optimizer
58
+
59
+
60
+ class Lamb(Optimizer):
61
+ """Implements a pure pytorch variant of FuseLAMB (NvLamb variant) optimizer from apex.optimizers.FusedLAMB
62
+ reference: https://github.com/NVIDIA/DeepLearningExamples/blob/master/PyTorch/LanguageModeling/Transformer-XL/pytorch/lamb.py
63
+
64
+ LAMB was proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_.
65
+
66
+ Arguments:
67
+ params (iterable): iterable of parameters to optimize or dicts defining parameter groups.
68
+ lr (float, optional): learning rate. (default: 1e-3)
69
+ betas (Tuple[float, float], optional): coefficients used for computing
70
+ running averages of gradient and its norm. (default: (0.9, 0.999))
71
+ eps (float, optional): term added to the denominator to improve
72
+ numerical stability. (default: 1e-8)
73
+ weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
74
+ grad_averaging (bool, optional): whether apply (1-beta2) to grad when
75
+ calculating running averages of gradient. (default: True)
76
+ max_grad_norm (float, optional): value used to clip global grad norm (default: 1.0)
77
+ trust_clip (bool): enable LAMBC trust ratio clipping (default: False)
78
+ always_adapt (boolean, optional): Apply adaptive learning rate to 0.0
79
+ weight decay parameter (default: False)
80
+
81
+ .. _Large Batch Optimization for Deep Learning - Training BERT in 76 minutes:
82
+ https://arxiv.org/abs/1904.00962
83
+ .. _On the Convergence of Adam and Beyond:
84
+ https://openreview.net/forum?id=ryQu7f-RZ
85
+ """
86
+
87
+ def __init__(
88
+ self, params, lr=1e-3, bias_correction=True, betas=(0.9, 0.999), eps=1e-6,
89
+ weight_decay=0.01, grad_averaging=True, max_grad_norm=1.0, trust_clip=False, always_adapt=False):
90
+ defaults = dict(
91
+ lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay,
92
+ grad_averaging=grad_averaging, max_grad_norm=max_grad_norm,
93
+ trust_clip=trust_clip, always_adapt=always_adapt)
94
+ super().__init__(params, defaults)
95
+
96
+ @torch.no_grad()
97
+ def step(self, closure=None):
98
+ """Performs a single optimization step.
99
+ Arguments:
100
+ closure (callable, optional): A closure that reevaluates the model
101
+ and returns the loss.
102
+ """
103
+ loss = None
104
+ if closure is not None:
105
+ with torch.enable_grad():
106
+ loss = closure()
107
+
108
+ device = self.param_groups[0]['params'][0].device
109
+ one_tensor = torch.tensor(1.0, device=device) # because torch.where doesn't handle scalars correctly
110
+ global_grad_norm = torch.zeros(1, device=device)
111
+ for group in self.param_groups:
112
+ for p in group['params']:
113
+ if p.grad is None:
114
+ continue
115
+ grad = p.grad
116
+ if grad.is_sparse:
117
+ raise RuntimeError('Lamb does not support sparse gradients, consider SparseAdam instad.')
118
+ global_grad_norm.add_(grad.pow(2).sum())
119
+
120
+ global_grad_norm = torch.sqrt(global_grad_norm)
121
+ # FIXME it'd be nice to remove explicit tensor conversion of scalars when torch.where promotes
122
+ # scalar types properly https://github.com/pytorch/pytorch/issues/9190
123
+ max_grad_norm = torch.tensor(self.defaults['max_grad_norm'], device=device)
124
+ clip_global_grad_norm = torch.where(
125
+ global_grad_norm > max_grad_norm,
126
+ global_grad_norm / max_grad_norm,
127
+ one_tensor)
128
+
129
+ for group in self.param_groups:
130
+ bias_correction = 1 if group['bias_correction'] else 0
131
+ beta1, beta2 = group['betas']
132
+ grad_averaging = 1 if group['grad_averaging'] else 0
133
+ beta3 = 1 - beta1 if grad_averaging else 1.0
134
+
135
+ # assume same step across group now to simplify things
136
+ # per parameter step can be easily support by making it tensor, or pass list into kernel
137
+ if 'step' in group:
138
+ group['step'] += 1
139
+ else:
140
+ group['step'] = 1
141
+
142
+ if bias_correction:
143
+ bias_correction1 = 1 - beta1 ** group['step']
144
+ bias_correction2 = 1 - beta2 ** group['step']
145
+ else:
146
+ bias_correction1, bias_correction2 = 1.0, 1.0
147
+
148
+ for p in group['params']:
149
+ if p.grad is None:
150
+ continue
151
+ grad = p.grad.div_(clip_global_grad_norm)
152
+ state = self.state[p]
153
+
154
+ # State initialization
155
+ if len(state) == 0:
156
+ # Exponential moving average of gradient valuesa
157
+ state['exp_avg'] = torch.zeros_like(p)
158
+ # Exponential moving average of squared gradient values
159
+ state['exp_avg_sq'] = torch.zeros_like(p)
160
+
161
+ exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']
162
+
163
+ # Decay the first and second moment running average coefficient
164
+ exp_avg.mul_(beta1).add_(grad, alpha=beta3) # m_t
165
+ exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2) # v_t
166
+
167
+ denom = (exp_avg_sq.sqrt() / math.sqrt(bias_correction2)).add_(group['eps'])
168
+ update = (exp_avg / bias_correction1).div_(denom)
169
+
170
+ weight_decay = group['weight_decay']
171
+ if weight_decay != 0:
172
+ update.add_(p, alpha=weight_decay)
173
+
174
+ if weight_decay != 0 or group['always_adapt']:
175
+ # Layer-wise LR adaptation. By default, skip adaptation on parameters that are
176
+ # excluded from weight decay, unless always_adapt == True, then always enabled.
177
+ w_norm = p.norm(2.0)
178
+ g_norm = update.norm(2.0)
179
+ # FIXME nested where required since logical and/or not working in PT XLA
180
+ trust_ratio = torch.where(
181
+ w_norm > 0,
182
+ torch.where(g_norm > 0, w_norm / g_norm, one_tensor),
183
+ one_tensor,
184
+ )
185
+ if group['trust_clip']:
186
+ # LAMBC trust clipping, upper bound fixed at one
187
+ trust_ratio = torch.minimum(trust_ratio, one_tensor)
188
+ update.mul_(trust_ratio)
189
+
190
+ p.add_(update, alpha=-group['lr'])
191
+
192
+ return loss
@@ -0,0 +1,135 @@
1
+ """ PyTorch LARS / LARC Optimizer
2
+
3
+ An implementation of LARS (SGD) + LARC in PyTorch
4
+
5
+ Based on:
6
+ * PyTorch SGD: https://github.com/pytorch/pytorch/blob/1.7/torch/optim/sgd.py#L100
7
+ * NVIDIA APEX LARC: https://github.com/NVIDIA/apex/blob/master/apex/parallel/LARC.py
8
+
9
+ Additional cleanup and modifications to properly support PyTorch XLA.
10
+
11
+ Copyright 2021 Ross Wightman
12
+ """
13
+ import torch
14
+ from torch.optim.optimizer import Optimizer
15
+
16
+
17
+ class Lars(Optimizer):
18
+ """ LARS for PyTorch
19
+
20
+ Paper: `Large batch training of Convolutional Networks` - https://arxiv.org/pdf/1708.03888.pdf
21
+
22
+ Args:
23
+ params (iterable): iterable of parameters to optimize or dicts defining parameter groups.
24
+ lr (float, optional): learning rate (default: 1.0).
25
+ momentum (float, optional): momentum factor (default: 0)
26
+ weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
27
+ dampening (float, optional): dampening for momentum (default: 0)
28
+ nesterov (bool, optional): enables Nesterov momentum (default: False)
29
+ trust_coeff (float): trust coefficient for computing adaptive lr / trust_ratio (default: 0.001)
30
+ eps (float): eps for division denominator (default: 1e-8)
31
+ trust_clip (bool): enable LARC trust ratio clipping (default: False)
32
+ always_adapt (bool): always apply LARS LR adapt, otherwise only when group weight_decay != 0 (default: False)
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ params,
38
+ lr=1.0,
39
+ momentum=0,
40
+ dampening=0,
41
+ weight_decay=0,
42
+ nesterov=False,
43
+ trust_coeff=0.001,
44
+ eps=1e-8,
45
+ trust_clip=False,
46
+ always_adapt=False,
47
+ ):
48
+ if lr < 0.0:
49
+ raise ValueError(f"Invalid learning rate: {lr}")
50
+ if momentum < 0.0:
51
+ raise ValueError(f"Invalid momentum value: {momentum}")
52
+ if weight_decay < 0.0:
53
+ raise ValueError(f"Invalid weight_decay value: {weight_decay}")
54
+ if nesterov and (momentum <= 0 or dampening != 0):
55
+ raise ValueError("Nesterov momentum requires a momentum and zero dampening")
56
+
57
+ defaults = dict(
58
+ lr=lr,
59
+ momentum=momentum,
60
+ dampening=dampening,
61
+ weight_decay=weight_decay,
62
+ nesterov=nesterov,
63
+ trust_coeff=trust_coeff,
64
+ eps=eps,
65
+ trust_clip=trust_clip,
66
+ always_adapt=always_adapt,
67
+ )
68
+ super().__init__(params, defaults)
69
+
70
+ def __setstate__(self, state):
71
+ super().__setstate__(state)
72
+ for group in self.param_groups:
73
+ group.setdefault("nesterov", False)
74
+
75
+ @torch.no_grad()
76
+ def step(self, closure=None):
77
+ """Performs a single optimization step.
78
+
79
+ Args:
80
+ closure (callable, optional): A closure that reevaluates the model and returns the loss.
81
+ """
82
+ loss = None
83
+ if closure is not None:
84
+ with torch.enable_grad():
85
+ loss = closure()
86
+
87
+ device = self.param_groups[0]['params'][0].device
88
+ one_tensor = torch.tensor(1.0, device=device) # because torch.where doesn't handle scalars correctly
89
+
90
+ for group in self.param_groups:
91
+ weight_decay = group['weight_decay']
92
+ momentum = group['momentum']
93
+ dampening = group['dampening']
94
+ nesterov = group['nesterov']
95
+ trust_coeff = group['trust_coeff']
96
+ eps = group['eps']
97
+
98
+ for p in group['params']:
99
+ if p.grad is None:
100
+ continue
101
+ grad = p.grad
102
+
103
+ # apply LARS LR adaptation, LARC clipping, weight decay
104
+ # ref: https://github.com/NVIDIA/apex/blob/master/apex/parallel/LARC.py
105
+ if weight_decay != 0 or group['always_adapt']:
106
+ w_norm = p.norm(2.0)
107
+ g_norm = grad.norm(2.0)
108
+ trust_ratio = trust_coeff * w_norm / (g_norm + w_norm * weight_decay + eps)
109
+ # FIXME nested where required since logical and/or not working in PT XLA
110
+ trust_ratio = torch.where(
111
+ w_norm > 0,
112
+ torch.where(g_norm > 0, trust_ratio, one_tensor),
113
+ one_tensor,
114
+ )
115
+ if group['trust_clip']:
116
+ trust_ratio = torch.minimum(trust_ratio / group['lr'], one_tensor)
117
+ grad.add(p, alpha=weight_decay)
118
+ grad.mul_(trust_ratio)
119
+
120
+ # apply SGD update https://github.com/pytorch/pytorch/blob/1.7/torch/optim/sgd.py#L100
121
+ if momentum != 0:
122
+ param_state = self.state[p]
123
+ if 'momentum_buffer' not in param_state:
124
+ buf = param_state['momentum_buffer'] = torch.clone(grad).detach()
125
+ else:
126
+ buf = param_state['momentum_buffer']
127
+ buf.mul_(momentum).add_(grad, alpha=1. - dampening)
128
+ if nesterov:
129
+ grad = grad.add(buf, alpha=momentum)
130
+ else:
131
+ grad = buf
132
+
133
+ p.add_(grad, alpha=-group['lr'])
134
+
135
+ return loss
@@ -0,0 +1,61 @@
1
+ """ Lookahead Optimizer Wrapper.
2
+ Implementation modified from: https://github.com/alphadl/lookahead.pytorch
3
+ Paper: `Lookahead Optimizer: k steps forward, 1 step back` - https://arxiv.org/abs/1907.08610
4
+
5
+ Hacked together by / Copyright 2020 Ross Wightman
6
+ """
7
+ import torch
8
+ from torch.optim.optimizer import Optimizer
9
+ from collections import defaultdict
10
+
11
+
12
+ class Lookahead(Optimizer):
13
+ def __init__(self, base_optimizer, alpha=0.5, k=6):
14
+ # NOTE super().__init__() not called on purpose
15
+ if not 0.0 <= alpha <= 1.0:
16
+ raise ValueError(f'Invalid slow update rate: {alpha}')
17
+ if not 1 <= k:
18
+ raise ValueError(f'Invalid lookahead steps: {k}')
19
+ defaults = dict(lookahead_alpha=alpha, lookahead_k=k, lookahead_step=0)
20
+ self._base_optimizer = base_optimizer
21
+ self.param_groups = base_optimizer.param_groups
22
+ self.defaults = base_optimizer.defaults
23
+ self.defaults.update(defaults)
24
+ self.state = defaultdict(dict)
25
+ # manually add our defaults to the param groups
26
+ for name, default in defaults.items():
27
+ for group in self._base_optimizer.param_groups:
28
+ group.setdefault(name, default)
29
+
30
+ @torch.no_grad()
31
+ def update_slow(self, group):
32
+ for fast_p in group["params"]:
33
+ if fast_p.grad is None:
34
+ continue
35
+ param_state = self._base_optimizer.state[fast_p]
36
+ if 'lookahead_slow_buff' not in param_state:
37
+ param_state['lookahead_slow_buff'] = torch.empty_like(fast_p)
38
+ param_state['lookahead_slow_buff'].copy_(fast_p)
39
+ slow = param_state['lookahead_slow_buff']
40
+ slow.add_(fast_p - slow, alpha=group['lookahead_alpha'])
41
+ fast_p.copy_(slow)
42
+
43
+ def sync_lookahead(self):
44
+ for group in self._base_optimizer.param_groups:
45
+ self.update_slow(group)
46
+
47
+ @torch.no_grad()
48
+ def step(self, closure=None):
49
+ loss = self._base_optimizer.step(closure)
50
+ for group in self._base_optimizer.param_groups:
51
+ group['lookahead_step'] += 1
52
+ if group['lookahead_step'] % group['lookahead_k'] == 0:
53
+ self.update_slow(group)
54
+ return loss
55
+
56
+ def state_dict(self):
57
+ return self._base_optimizer.state_dict()
58
+
59
+ def load_state_dict(self, state_dict):
60
+ self._base_optimizer.load_state_dict(state_dict)
61
+ self.param_groups = self._base_optimizer.param_groups
@@ -0,0 +1,184 @@
1
+ """ PyTorch MADGRAD optimizer
2
+
3
+ MADGRAD: https://arxiv.org/abs/2101.11075
4
+
5
+ Code from: https://github.com/facebookresearch/madgrad
6
+ """
7
+ # Copyright (c) Facebook, Inc. and its affiliates.
8
+ #
9
+ # This source code is licensed under the MIT license found in the
10
+ # LICENSE file in the root directory of this source tree.
11
+
12
+ import math
13
+ from typing import TYPE_CHECKING, Any, Callable, Optional
14
+
15
+ import torch
16
+ import torch.optim
17
+
18
+ if TYPE_CHECKING:
19
+ from torch.optim.optimizer import _params_t
20
+ else:
21
+ _params_t = Any
22
+
23
+
24
+ class MADGRAD(torch.optim.Optimizer):
25
+ """
26
+ MADGRAD_: A Momentumized, Adaptive, Dual Averaged Gradient Method for Stochastic
27
+ Optimization.
28
+
29
+ .. _MADGRAD: https://arxiv.org/abs/2101.11075
30
+
31
+ MADGRAD is a general purpose optimizer that can be used in place of SGD or
32
+ Adam may converge faster and generalize better. Currently GPU-only.
33
+ Typically, the same learning rate schedule that is used for SGD or Adam may
34
+ be used. The overall learning rate is not comparable to either method and
35
+ should be determined by a hyper-parameter sweep.
36
+
37
+ MADGRAD requires less weight decay than other methods, often as little as
38
+ zero. Momentum values used for SGD or Adam's beta1 should work here also.
39
+
40
+ On sparse problems both weight_decay and momentum should be set to 0.
41
+
42
+ Arguments:
43
+ params (iterable):
44
+ Iterable of parameters to optimize or dicts defining parameter groups.
45
+ lr (float):
46
+ Learning rate (default: 1e-2).
47
+ momentum (float):
48
+ Momentum value in the range [0,1) (default: 0.9).
49
+ weight_decay (float):
50
+ Weight decay, i.e. a L2 penalty (default: 0).
51
+ eps (float):
52
+ Term added to the denominator outside of the root operation to improve numerical stability. (default: 1e-6).
53
+ """
54
+
55
+ def __init__(
56
+ self,
57
+ params: _params_t,
58
+ lr: float = 1e-2,
59
+ momentum: float = 0.9,
60
+ weight_decay: float = 0,
61
+ eps: float = 1e-6,
62
+ decoupled_decay: bool = False,
63
+ ):
64
+ if momentum < 0 or momentum >= 1:
65
+ raise ValueError(f"Momentum {momentum} must be in the range [0,1]")
66
+ if lr <= 0:
67
+ raise ValueError(f"Learning rate {lr} must be positive")
68
+ if weight_decay < 0:
69
+ raise ValueError(f"Weight decay {weight_decay} must be non-negative")
70
+ if eps < 0:
71
+ raise ValueError(f"Eps must be non-negative")
72
+
73
+ defaults = dict(
74
+ lr=lr, eps=eps, momentum=momentum, weight_decay=weight_decay, decoupled_decay=decoupled_decay)
75
+ super().__init__(params, defaults)
76
+
77
+ @property
78
+ def supports_memory_efficient_fp16(self) -> bool:
79
+ return False
80
+
81
+ @property
82
+ def supports_flat_params(self) -> bool:
83
+ return True
84
+
85
+ @torch.no_grad()
86
+ def step(self, closure: Optional[Callable[[], float]] = None) -> Optional[float]:
87
+ """Performs a single optimization step.
88
+
89
+ Arguments:
90
+ closure (callable, optional): A closure that reevaluates the model and returns the loss.
91
+ """
92
+ loss = None
93
+ if closure is not None:
94
+ with torch.enable_grad():
95
+ loss = closure()
96
+
97
+ for group in self.param_groups:
98
+ eps = group['eps']
99
+ lr = group['lr'] + eps
100
+ weight_decay = group['weight_decay']
101
+ momentum = group['momentum']
102
+ ck = 1 - momentum
103
+
104
+ for p in group["params"]:
105
+ if p.grad is None:
106
+ continue
107
+ grad = p.grad
108
+ if momentum != 0.0 and grad.is_sparse:
109
+ raise RuntimeError("momentum != 0 is not compatible with sparse gradients")
110
+
111
+ state = self.state[p]
112
+ if len(state) == 0:
113
+ state['step'] = 0
114
+ state['grad_sum_sq'] = torch.zeros_like(p)
115
+ state['s'] = torch.zeros_like(p)
116
+ if momentum != 0:
117
+ state['x0'] = torch.clone(p).detach()
118
+
119
+ state['step'] += 1
120
+ grad_sum_sq = state['grad_sum_sq']
121
+ s = state['s']
122
+ lamb = lr * math.sqrt(state['step'])
123
+
124
+ # Apply weight decay
125
+ if weight_decay != 0:
126
+ if group['decoupled_decay']:
127
+ p.mul_(1.0 - group['lr'] * weight_decay)
128
+ else:
129
+ if grad.is_sparse:
130
+ raise RuntimeError("weight_decay option is not compatible with sparse gradients")
131
+ grad.add_(p, alpha=weight_decay)
132
+
133
+ if grad.is_sparse:
134
+ grad = grad.coalesce()
135
+ grad_val = grad._values()
136
+
137
+ p_masked = p.sparse_mask(grad)
138
+ grad_sum_sq_masked = grad_sum_sq.sparse_mask(grad)
139
+ s_masked = s.sparse_mask(grad)
140
+
141
+ # Compute x_0 from other known quantities
142
+ rms_masked_vals = grad_sum_sq_masked._values().pow(1 / 3).add_(eps)
143
+ x0_masked_vals = p_masked._values().addcdiv(s_masked._values(), rms_masked_vals, value=1)
144
+
145
+ # Dense + sparse op
146
+ grad_sq = grad * grad
147
+ grad_sum_sq.add_(grad_sq, alpha=lamb)
148
+ grad_sum_sq_masked.add_(grad_sq, alpha=lamb)
149
+
150
+ rms_masked_vals = grad_sum_sq_masked._values().pow_(1 / 3).add_(eps)
151
+
152
+ s.add_(grad, alpha=lamb)
153
+ s_masked._values().add_(grad_val, alpha=lamb)
154
+
155
+ # update masked copy of p
156
+ p_kp1_masked_vals = x0_masked_vals.addcdiv(s_masked._values(), rms_masked_vals, value=-1)
157
+ # Copy updated masked p to dense p using an add operation
158
+ p_masked._values().add_(p_kp1_masked_vals, alpha=-1)
159
+ p.add_(p_masked, alpha=-1)
160
+ else:
161
+ if momentum == 0:
162
+ # Compute x_0 from other known quantities
163
+ rms = grad_sum_sq.pow(1 / 3).add_(eps)
164
+ x0 = p.addcdiv(s, rms, value=1)
165
+ else:
166
+ x0 = state['x0']
167
+
168
+ # Accumulate second moments
169
+ grad_sum_sq.addcmul_(grad, grad, value=lamb)
170
+ rms = grad_sum_sq.pow(1 / 3).add_(eps)
171
+
172
+ # Update s
173
+ s.add_(grad, alpha=lamb)
174
+
175
+ # Step
176
+ if momentum == 0:
177
+ p.copy_(x0.addcdiv(s, rms, value=-1))
178
+ else:
179
+ z = x0.addcdiv(s, rms, value=-1)
180
+
181
+ # p is a moving average of z
182
+ p.mul_(1 - ck).add_(z, alpha=ck)
183
+
184
+ return loss
@@ -0,0 +1,92 @@
1
+ import math
2
+
3
+ import torch
4
+ from torch.optim.optimizer import Optimizer
5
+
6
+
7
+ class Nadam(Optimizer):
8
+ """Implements Nadam algorithm (a variant of Adam based on Nesterov momentum).
9
+
10
+ It has been proposed in `Incorporating Nesterov Momentum into Adam`__.
11
+
12
+ Arguments:
13
+ params (iterable): iterable of parameters to optimize or dicts defining
14
+ parameter groups
15
+ lr (float, optional): learning rate (default: 2e-3)
16
+ betas (Tuple[float, float], optional): coefficients used for computing
17
+ running averages of gradient and its square
18
+ eps (float, optional): term added to the denominator to improve
19
+ numerical stability (default: 1e-8)
20
+ weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
21
+ schedule_decay (float, optional): momentum schedule decay (default: 4e-3)
22
+
23
+ __ http://cs229.stanford.edu/proj2015/054_report.pdf
24
+ __ http://www.cs.toronto.edu/~fritz/absps/momentum.pdf
25
+
26
+ Originally taken from: https://github.com/pytorch/pytorch/pull/1408
27
+ NOTE: Has potential issues but does work well on some problems.
28
+ """
29
+
30
+ def __init__(self, params, lr=2e-3, betas=(0.9, 0.999), eps=1e-8,
31
+ weight_decay=0, schedule_decay=4e-3):
32
+ if not 0.0 <= lr:
33
+ raise ValueError("Invalid learning rate: {}".format(lr))
34
+ defaults = dict(
35
+ lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, schedule_decay=schedule_decay)
36
+ super(Nadam, self).__init__(params, defaults)
37
+
38
+ @torch.no_grad()
39
+ def step(self, closure=None):
40
+ """Performs a single optimization step.
41
+
42
+ Arguments:
43
+ closure (callable, optional): A closure that reevaluates the model
44
+ and returns the loss.
45
+ """
46
+ loss = None
47
+ if closure is not None:
48
+ with torch.enable_grad():
49
+ loss = closure()
50
+
51
+ for group in self.param_groups:
52
+ for p in group['params']:
53
+ if p.grad is None:
54
+ continue
55
+ grad = p.grad
56
+ state = self.state[p]
57
+
58
+ # State initialization
59
+ if len(state) == 0:
60
+ state['step'] = 0
61
+ state['m_schedule'] = 1.
62
+ state['exp_avg'] = torch.zeros_like(p)
63
+ state['exp_avg_sq'] = torch.zeros_like(p)
64
+
65
+ # Warming momentum schedule
66
+ m_schedule = state['m_schedule']
67
+ schedule_decay = group['schedule_decay']
68
+ exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']
69
+ beta1, beta2 = group['betas']
70
+ eps = group['eps']
71
+ state['step'] += 1
72
+ t = state['step']
73
+ bias_correction2 = 1 - beta2 ** t
74
+
75
+ if group['weight_decay'] != 0:
76
+ grad = grad.add(p, alpha=group['weight_decay'])
77
+
78
+ momentum_cache_t = beta1 * (1. - 0.5 * (0.96 ** (t * schedule_decay)))
79
+ momentum_cache_t_1 = beta1 * (1. - 0.5 * (0.96 ** ((t + 1) * schedule_decay)))
80
+ m_schedule_new = m_schedule * momentum_cache_t
81
+ m_schedule_next = m_schedule * momentum_cache_t * momentum_cache_t_1
82
+ state['m_schedule'] = m_schedule_new
83
+
84
+ # Decay the first and second moment running average coefficient
85
+ exp_avg.mul_(beta1).add_(grad, alpha=1. - beta1)
86
+ exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1. - beta2)
87
+
88
+ denom = (exp_avg_sq.sqrt() / math.sqrt(bias_correction2)).add_(eps)
89
+ p.addcdiv_(grad, denom, value=-group['lr'] * (1. - momentum_cache_t) / (1. - m_schedule_new))
90
+ p.addcdiv_(exp_avg, denom, value=-group['lr'] * momentum_cache_t_1 / (1. - m_schedule_next))
91
+
92
+ return loss