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.
- openpoints/__init__.py +3 -0
- openpoints/cpp/__init__.py +6 -0
- openpoints/cpp/chamfer_dist/__init__.py +110 -0
- openpoints/cpp/chamfer_dist/setup.py +19 -0
- openpoints/cpp/chamfer_dist/test.py +34 -0
- openpoints/cpp/emd/__init__.py +3 -0
- openpoints/cpp/emd/emd.py +88 -0
- openpoints/cpp/emd/setup.py +27 -0
- openpoints/cpp/emd/test_emd_loss.py +45 -0
- openpoints/cpp/pointnet2_batch/__init__.py +24 -0
- openpoints/cpp/pointnet2_batch/setup.py +23 -0
- openpoints/cpp/pointops/__init__.py +0 -0
- openpoints/cpp/pointops/functions/__init__.py +0 -0
- openpoints/cpp/pointops/functions/pointops.py +314 -0
- openpoints/cpp/pointops/setup.py +37 -0
- openpoints/cpp/pointops/src/__init__.py +0 -0
- openpoints/dataset/__init__.py +10 -0
- openpoints/dataset/atom3d/__init__.py +1 -0
- openpoints/dataset/atom3d/psr.py +38 -0
- openpoints/dataset/build.py +98 -0
- openpoints/dataset/data_util.py +192 -0
- openpoints/dataset/datalist.py +67 -0
- openpoints/dataset/dataset_base.py +96 -0
- openpoints/dataset/graph_dataset/__init__.py +3 -0
- openpoints/dataset/graph_dataset/graph_dataset.py +93 -0
- openpoints/dataset/graph_dataset/stack_with_pad.py +91 -0
- openpoints/dataset/graph_dataset/structural_dataset.py +73 -0
- openpoints/dataset/graph_dataset/svd_encodings_dataset.py +110 -0
- openpoints/dataset/grid_sample.py +21 -0
- openpoints/dataset/matterport3d/__init__.py +1 -0
- openpoints/dataset/matterport3d/category_mapping.tsv +1660 -0
- openpoints/dataset/matterport3d/matterport3d.py +210 -0
- openpoints/dataset/matterport3d/matterport3d_dataprocessing.py +105 -0
- openpoints/dataset/modelnet/__init__.py +3 -0
- openpoints/dataset/modelnet/modelnet40_normal_resampled_loader.py +124 -0
- openpoints/dataset/modelnet/modelnet40_ply_2048_loader.py +160 -0
- openpoints/dataset/molhiv/__init__.py +1 -0
- openpoints/dataset/molhiv/data.py +59 -0
- openpoints/dataset/molpcba/__init__.py +1 -0
- openpoints/dataset/molpcba/data.py +59 -0
- openpoints/dataset/parsers/__init__.py +1 -0
- openpoints/dataset/parsers/class_map.py +19 -0
- openpoints/dataset/parsers/constants.py +1 -0
- openpoints/dataset/parsers/parser.py +17 -0
- openpoints/dataset/parsers/parser_factory.py +29 -0
- openpoints/dataset/parsers/parser_image_folder.py +69 -0
- openpoints/dataset/parsers/parser_image_in_tar.py +222 -0
- openpoints/dataset/parsers/parser_image_tar.py +72 -0
- openpoints/dataset/parsers/parser_tfds.py +297 -0
- openpoints/dataset/pcqm4m/__init__.py +1 -0
- openpoints/dataset/pcqm4m/data.py +62 -0
- openpoints/dataset/pcqm4mv2/__init__.py +1 -0
- openpoints/dataset/pcqm4mv2/data.py +87 -0
- openpoints/dataset/s3dis/__init__.py +2 -0
- openpoints/dataset/s3dis/s3dis.py +156 -0
- openpoints/dataset/s3dis/s3dis_block.py +96 -0
- openpoints/dataset/s3dis/s3dis_sphere.py +349 -0
- openpoints/dataset/scannetv2/__init__.py +1 -0
- openpoints/dataset/scannetv2/scannet.py +176 -0
- openpoints/dataset/scanobjectnn/__init__.py +3 -0
- openpoints/dataset/scanobjectnn/scanobjectnn.py +110 -0
- openpoints/dataset/semantic_kitti/__init__.py +1 -0
- openpoints/dataset/semantic_kitti/helper_tool.py +286 -0
- openpoints/dataset/semantic_kitti/label_mapping.yaml +211 -0
- openpoints/dataset/semantic_kitti/semantickitti.py +229 -0
- openpoints/dataset/semantic_kitti/utils/meta/anno_paths.txt +272 -0
- openpoints/dataset/semantic_kitti/utils/meta/class_names.txt +13 -0
- openpoints/dataset/semantic_kitti/utils/semantic-kitti.yaml +211 -0
- openpoints/dataset/shapenet/__init__.py +1 -0
- openpoints/dataset/shapenet/shapenet55.py +76 -0
- openpoints/dataset/shapenet/shapenetpart.py +121 -0
- openpoints/dataset/shapenetpart/__init__.py +1 -0
- openpoints/dataset/shapenetpart/shapenet55.py +75 -0
- openpoints/dataset/shapenetpart/shapenetpart.py +388 -0
- openpoints/dataset/vis2d.py +17 -0
- openpoints/dataset/vis3d.py +153 -0
- openpoints/loss/__init__.py +3 -0
- openpoints/loss/build.py +281 -0
- openpoints/loss/cross_entropy.py +38 -0
- openpoints/loss/distill_loss.py +76 -0
- openpoints/models/__init__.py +10 -0
- openpoints/models/backbone/Stratified_transformer.py +558 -0
- openpoints/models/backbone/__init__.py +11 -0
- openpoints/models/backbone/baafnet.py +527 -0
- openpoints/models/backbone/ball_dgcnn.py +123 -0
- openpoints/models/backbone/curvenet.py +793 -0
- openpoints/models/backbone/debug_invvit.py +114 -0
- openpoints/models/backbone/deepgcn.py +143 -0
- openpoints/models/backbone/dgcnn.py +119 -0
- openpoints/models/backbone/graphvit3d.py +134 -0
- openpoints/models/backbone/grouppointnet.py +100 -0
- openpoints/models/backbone/pct.py +163 -0
- openpoints/models/backbone/pointmlp.py +417 -0
- openpoints/models/backbone/pointnet.py +199 -0
- openpoints/models/backbone/pointnetv2.py +511 -0
- openpoints/models/backbone/pointnext.py +663 -0
- openpoints/models/backbone/pointnextPyG.py +555 -0
- openpoints/models/backbone/pointtransformer.py +293 -0
- openpoints/models/backbone/pointvector.py +853 -0
- openpoints/models/backbone/pointvit.py +392 -0
- openpoints/models/backbone/pointvit_inv.py +942 -0
- openpoints/models/backbone/pointvit_inv_old.py +784 -0
- openpoints/models/backbone/randlenet.py +318 -0
- openpoints/models/backbone/resnet.py +342 -0
- openpoints/models/backbone/simpleview.py +153 -0
- openpoints/models/backbone/simpleview_util.py +292 -0
- openpoints/models/build.py +13 -0
- openpoints/models/classification/__init__.py +5 -0
- openpoints/models/classification/cls_base.py +136 -0
- openpoints/models/classification/point_bert.py +154 -0
- openpoints/models/layers/__init__.py +14 -0
- openpoints/models/layers/activation.py +57 -0
- openpoints/models/layers/attention.py +103 -0
- openpoints/models/layers/conv.py +167 -0
- openpoints/models/layers/drop.py +164 -0
- openpoints/models/layers/graph_conv.py +122 -0
- openpoints/models/layers/group.py +415 -0
- openpoints/models/layers/group_embed.py +286 -0
- openpoints/models/layers/helpers.py +43 -0
- openpoints/models/layers/kmeans.py +119 -0
- openpoints/models/layers/knn.py +110 -0
- openpoints/models/layers/local_aggregation.py +286 -0
- openpoints/models/layers/mlp.py +129 -0
- openpoints/models/layers/norm.py +106 -0
- openpoints/models/layers/padding.py +56 -0
- openpoints/models/layers/patch_embed.py +37 -0
- openpoints/models/layers/registry.py +168 -0
- openpoints/models/layers/subsample.py +185 -0
- openpoints/models/layers/upsampling.py +106 -0
- openpoints/models/layers/weight_init.py +89 -0
- openpoints/models/reconstruction/__init__.py +8 -0
- openpoints/models/reconstruction/base_recontruct.py +216 -0
- openpoints/models/reconstruction/maskedpoint.py +116 -0
- openpoints/models/reconstruction/maskedpointgroup.py +168 -0
- openpoints/models/reconstruction/maskedpointvit.py +253 -0
- openpoints/models/reconstruction/nodeshuffle.py +11 -0
- openpoints/models/registry.py +149 -0
- openpoints/models/segmentation/__init__.py +6 -0
- openpoints/models/segmentation/base_seg.py +278 -0
- openpoints/models/segmentation/vit_seg.py +126 -0
- openpoints/optim/__init__.py +15 -0
- openpoints/optim/adabelief.py +201 -0
- openpoints/optim/adafactor.py +167 -0
- openpoints/optim/adahessian.py +156 -0
- openpoints/optim/adamp.py +105 -0
- openpoints/optim/adamw.py +122 -0
- openpoints/optim/lamb.py +192 -0
- openpoints/optim/lars.py +135 -0
- openpoints/optim/lookahead.py +61 -0
- openpoints/optim/madgrad.py +184 -0
- openpoints/optim/nadam.py +92 -0
- openpoints/optim/nvnovograd.py +120 -0
- openpoints/optim/optim_factory.py +306 -0
- openpoints/optim/radam.py +89 -0
- openpoints/optim/rmsprop_tf.py +139 -0
- openpoints/optim/sgdp.py +70 -0
- openpoints/scheduler/__init__.py +8 -0
- openpoints/scheduler/cosine_lr.py +124 -0
- openpoints/scheduler/multistep_lr.py +65 -0
- openpoints/scheduler/plateau_lr.py +113 -0
- openpoints/scheduler/poly_lr.py +116 -0
- openpoints/scheduler/scheduler.py +110 -0
- openpoints/scheduler/scheduler_factory.py +118 -0
- openpoints/scheduler/step_lr.py +65 -0
- openpoints/scheduler/tanh_lr.py +117 -0
- openpoints/transforms/__init__.py +7 -0
- openpoints/transforms/point_transform_cpu.py +332 -0
- openpoints/transforms/point_transformer_gpu.py +764 -0
- openpoints/transforms/transforms_factory.py +60 -0
- openpoints/utils/__init__.py +8 -0
- openpoints/utils/ckpt_util.py +438 -0
- openpoints/utils/config.py +113 -0
- openpoints/utils/dist_utils.py +54 -0
- openpoints/utils/logger.py +170 -0
- openpoints/utils/metrics.py +311 -0
- openpoints/utils/random.py +16 -0
- openpoints/utils/registry.py +294 -0
- openpoints/utils/str2bool.py +11 -0
- openpoints/utils/wandb.py +88 -0
- openpoints-0.1.0.dist-info/METADATA +150 -0
- openpoints-0.1.0.dist-info/RECORD +184 -0
- openpoints-0.1.0.dist-info/WHEEL +5 -0
- openpoints-0.1.0.dist-info/licenses/LICENSE +21 -0
- openpoints-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
""" Nvidia NovoGrad Optimizer.
|
|
2
|
+
Original impl by Nvidia from Jasper example:
|
|
3
|
+
- https://github.com/NVIDIA/DeepLearningExamples/blob/master/PyTorch/SpeechRecognition/Jasper
|
|
4
|
+
Paper: `Stochastic Gradient Methods with Layer-wise Adaptive Moments for Training of Deep Networks`
|
|
5
|
+
- https://arxiv.org/abs/1905.11286
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
from torch.optim.optimizer import Optimizer
|
|
10
|
+
import math
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class NvNovoGrad(Optimizer):
|
|
14
|
+
"""
|
|
15
|
+
Implements Novograd algorithm.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
params (iterable): iterable of parameters to optimize or dicts defining
|
|
19
|
+
parameter groups
|
|
20
|
+
lr (float, optional): learning rate (default: 1e-3)
|
|
21
|
+
betas (Tuple[float, float], optional): coefficients used for computing
|
|
22
|
+
running averages of gradient and its square (default: (0.95, 0.98))
|
|
23
|
+
eps (float, optional): term added to the denominator to improve
|
|
24
|
+
numerical stability (default: 1e-8)
|
|
25
|
+
weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
|
|
26
|
+
grad_averaging: gradient averaging
|
|
27
|
+
amsgrad (boolean, optional): whether to use the AMSGrad variant of this
|
|
28
|
+
algorithm from the paper `On the Convergence of Adam and Beyond`_
|
|
29
|
+
(default: False)
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(self, params, lr=1e-3, betas=(0.95, 0.98), eps=1e-8,
|
|
33
|
+
weight_decay=0, grad_averaging=False, amsgrad=False):
|
|
34
|
+
if not 0.0 <= lr:
|
|
35
|
+
raise ValueError("Invalid learning rate: {}".format(lr))
|
|
36
|
+
if not 0.0 <= eps:
|
|
37
|
+
raise ValueError("Invalid epsilon value: {}".format(eps))
|
|
38
|
+
if not 0.0 <= betas[0] < 1.0:
|
|
39
|
+
raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0]))
|
|
40
|
+
if not 0.0 <= betas[1] < 1.0:
|
|
41
|
+
raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1]))
|
|
42
|
+
defaults = dict(lr=lr, betas=betas, eps=eps,
|
|
43
|
+
weight_decay=weight_decay,
|
|
44
|
+
grad_averaging=grad_averaging,
|
|
45
|
+
amsgrad=amsgrad)
|
|
46
|
+
|
|
47
|
+
super(NvNovoGrad, self).__init__(params, defaults)
|
|
48
|
+
|
|
49
|
+
def __setstate__(self, state):
|
|
50
|
+
super(NvNovoGrad, self).__setstate__(state)
|
|
51
|
+
for group in self.param_groups:
|
|
52
|
+
group.setdefault('amsgrad', False)
|
|
53
|
+
|
|
54
|
+
@torch.no_grad()
|
|
55
|
+
def step(self, closure=None):
|
|
56
|
+
"""Performs a single optimization step.
|
|
57
|
+
|
|
58
|
+
Arguments:
|
|
59
|
+
closure (callable, optional): A closure that reevaluates the model
|
|
60
|
+
and returns the loss.
|
|
61
|
+
"""
|
|
62
|
+
loss = None
|
|
63
|
+
if closure is not None:
|
|
64
|
+
with torch.enable_grad():
|
|
65
|
+
loss = closure()
|
|
66
|
+
|
|
67
|
+
for group in self.param_groups:
|
|
68
|
+
for p in group['params']:
|
|
69
|
+
if p.grad is None:
|
|
70
|
+
continue
|
|
71
|
+
grad = p.grad
|
|
72
|
+
if grad.is_sparse:
|
|
73
|
+
raise RuntimeError('Sparse gradients are not supported.')
|
|
74
|
+
amsgrad = group['amsgrad']
|
|
75
|
+
|
|
76
|
+
state = self.state[p]
|
|
77
|
+
|
|
78
|
+
# State initialization
|
|
79
|
+
if len(state) == 0:
|
|
80
|
+
state['step'] = 0
|
|
81
|
+
# Exponential moving average of gradient values
|
|
82
|
+
state['exp_avg'] = torch.zeros_like(p)
|
|
83
|
+
# Exponential moving average of squared gradient values
|
|
84
|
+
state['exp_avg_sq'] = torch.zeros([]).to(state['exp_avg'].device)
|
|
85
|
+
if amsgrad:
|
|
86
|
+
# Maintains max of all exp. moving avg. of sq. grad. values
|
|
87
|
+
state['max_exp_avg_sq'] = torch.zeros([]).to(state['exp_avg'].device)
|
|
88
|
+
|
|
89
|
+
exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']
|
|
90
|
+
if amsgrad:
|
|
91
|
+
max_exp_avg_sq = state['max_exp_avg_sq']
|
|
92
|
+
beta1, beta2 = group['betas']
|
|
93
|
+
|
|
94
|
+
state['step'] += 1
|
|
95
|
+
|
|
96
|
+
norm = torch.sum(torch.pow(grad, 2))
|
|
97
|
+
|
|
98
|
+
if exp_avg_sq == 0:
|
|
99
|
+
exp_avg_sq.copy_(norm)
|
|
100
|
+
else:
|
|
101
|
+
exp_avg_sq.mul_(beta2).add_(norm, alpha=1 - beta2)
|
|
102
|
+
|
|
103
|
+
if amsgrad:
|
|
104
|
+
# Maintains the maximum of all 2nd moment running avg. till now
|
|
105
|
+
torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)
|
|
106
|
+
# Use the max. for normalizing running avg. of gradient
|
|
107
|
+
denom = max_exp_avg_sq.sqrt().add_(group['eps'])
|
|
108
|
+
else:
|
|
109
|
+
denom = exp_avg_sq.sqrt().add_(group['eps'])
|
|
110
|
+
|
|
111
|
+
grad.div_(denom)
|
|
112
|
+
if group['weight_decay'] != 0:
|
|
113
|
+
grad.add_(p, alpha=group['weight_decay'])
|
|
114
|
+
if group['grad_averaging']:
|
|
115
|
+
grad.mul_(1 - beta1)
|
|
116
|
+
exp_avg.mul_(beta1).add_(grad)
|
|
117
|
+
|
|
118
|
+
p.add_(exp_avg, alpha=-group['lr'])
|
|
119
|
+
|
|
120
|
+
return loss
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
""" Optimizer Factory w/ Custom Weight Decay
|
|
2
|
+
Borrowed from Ross Wightman (https://www.github.com/timm)
|
|
3
|
+
"""
|
|
4
|
+
from typing import Optional
|
|
5
|
+
import copy
|
|
6
|
+
|
|
7
|
+
import torch
|
|
8
|
+
import torch.nn as nn
|
|
9
|
+
import torch.optim as optim
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
|
|
13
|
+
from .adabelief import AdaBelief
|
|
14
|
+
from .adafactor import Adafactor
|
|
15
|
+
from .adahessian import Adahessian
|
|
16
|
+
from .adamp import AdamP
|
|
17
|
+
from .lamb import Lamb
|
|
18
|
+
from .lars import Lars
|
|
19
|
+
from .lookahead import Lookahead
|
|
20
|
+
from .madgrad import MADGRAD
|
|
21
|
+
from .nadam import Nadam
|
|
22
|
+
from .nvnovograd import NvNovoGrad
|
|
23
|
+
from .radam import RAdam
|
|
24
|
+
from .rmsprop_tf import RMSpropTF
|
|
25
|
+
from .sgdp import SGDP
|
|
26
|
+
|
|
27
|
+
import logging
|
|
28
|
+
|
|
29
|
+
try:
|
|
30
|
+
from apex.optimizers import FusedNovoGrad, FusedAdam, FusedLAMB, FusedSGD
|
|
31
|
+
|
|
32
|
+
has_apex = True
|
|
33
|
+
except ImportError:
|
|
34
|
+
has_apex = False
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def get_num_layer_for_vit(var_name, num_max_layer):
|
|
38
|
+
# remove module, and encoder.
|
|
39
|
+
var_name = copy.deepcopy(var_name)
|
|
40
|
+
var_name = var_name.replace('module.', '')
|
|
41
|
+
var_name = var_name.replace('encoder.', '')
|
|
42
|
+
|
|
43
|
+
if any(key in var_name for key in {"cls_token", "mask_token", "cls_pos", "pos_embed", "patch_embed"}):
|
|
44
|
+
return 0
|
|
45
|
+
elif "rel_pos_bias" in var_name:
|
|
46
|
+
return num_max_layer - 1
|
|
47
|
+
|
|
48
|
+
elif var_name.startswith("blocks"):
|
|
49
|
+
layer_id = int(var_name.split('.')[1])
|
|
50
|
+
return layer_id + 1
|
|
51
|
+
else:
|
|
52
|
+
return num_max_layer - 1
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class LayerDecayValueAssigner(object):
|
|
56
|
+
def __init__(self, values):
|
|
57
|
+
self.values = values
|
|
58
|
+
|
|
59
|
+
def get_scale(self, layer_id):
|
|
60
|
+
return self.values[layer_id]
|
|
61
|
+
|
|
62
|
+
def get_layer_id(self, var_name):
|
|
63
|
+
return get_num_layer_for_vit(var_name, len(self.values))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def get_parameter_groups(model, weight_decay=1e-5, skip_list=(), get_num_layer=None, get_layer_scale=None,
|
|
67
|
+
filter_by_modules_names=None,
|
|
68
|
+
):
|
|
69
|
+
parameter_group_names = {}
|
|
70
|
+
parameter_group_vars = {}
|
|
71
|
+
|
|
72
|
+
for name, param in model.named_parameters():
|
|
73
|
+
if not param.requires_grad:
|
|
74
|
+
continue # frozen weights
|
|
75
|
+
|
|
76
|
+
if len(param.shape) == 1 or name.endswith(".bias") or any(key in name for key in skip_list):
|
|
77
|
+
group_name = "no_decay"
|
|
78
|
+
this_weight_decay = 0.
|
|
79
|
+
else:
|
|
80
|
+
group_name = "decay"
|
|
81
|
+
this_weight_decay = weight_decay
|
|
82
|
+
|
|
83
|
+
if get_num_layer is not None:
|
|
84
|
+
layer_id = get_num_layer(name)
|
|
85
|
+
group_name = "layer_%d_%s" % (layer_id, group_name)
|
|
86
|
+
else:
|
|
87
|
+
layer_id = None
|
|
88
|
+
|
|
89
|
+
if get_layer_scale is not None:
|
|
90
|
+
scale = get_layer_scale(layer_id) * scale
|
|
91
|
+
else:
|
|
92
|
+
scale = 1.0
|
|
93
|
+
|
|
94
|
+
if filter_by_modules_names is not None:
|
|
95
|
+
filter_exist = False
|
|
96
|
+
for module_name in filter_by_modules_names.keys():
|
|
97
|
+
filter_exist = module_name in name
|
|
98
|
+
if filter_exist:
|
|
99
|
+
break
|
|
100
|
+
if filter_exist:
|
|
101
|
+
group_name = module_name + '_' + group_name
|
|
102
|
+
this_weight_decay = filter_by_modules_names[module_name].get('weight_decay', this_weight_decay)
|
|
103
|
+
scale = filter_by_modules_names[module_name].get('lr_scale', 1.0) * scale
|
|
104
|
+
|
|
105
|
+
if group_name not in parameter_group_names:
|
|
106
|
+
parameter_group_names[group_name] = {
|
|
107
|
+
"weight_decay": this_weight_decay,
|
|
108
|
+
"params": [],
|
|
109
|
+
"lr_scale": scale
|
|
110
|
+
}
|
|
111
|
+
parameter_group_vars[group_name] = {
|
|
112
|
+
"weight_decay": this_weight_decay,
|
|
113
|
+
"params": [],
|
|
114
|
+
"lr_scale": scale
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
parameter_group_vars[group_name]["params"].append(param)
|
|
118
|
+
parameter_group_names[group_name]["params"].append(name)
|
|
119
|
+
logging.info("Param groups = %s" % json.dumps(parameter_group_names, indent=2))
|
|
120
|
+
return list(parameter_group_vars.values())
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def add_weight_decay(model, weight_decay=1e-5, skip_list=()):
|
|
124
|
+
decay = []
|
|
125
|
+
no_decay = []
|
|
126
|
+
for name, param in model.named_parameters():
|
|
127
|
+
if not param.requires_grad:
|
|
128
|
+
continue # frozen weights
|
|
129
|
+
if len(param.shape) == 1 or name.endswith(".bias") or name in skip_list:
|
|
130
|
+
no_decay.append(param)
|
|
131
|
+
else:
|
|
132
|
+
decay.append(param)
|
|
133
|
+
return [
|
|
134
|
+
{'params': no_decay, 'weight_decay': 0.},
|
|
135
|
+
{'params': decay, 'weight_decay': weight_decay}]
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def optimizer_kwargs(cfg):
|
|
139
|
+
""" cfg/argparse to kwargs helper
|
|
140
|
+
Convert optimizer args in argparse args or cfg like object to keyword args for updated create fn.
|
|
141
|
+
"""
|
|
142
|
+
kwargs = dict(
|
|
143
|
+
opt=cfg.opt,
|
|
144
|
+
lr=cfg.lr,
|
|
145
|
+
weight_decay=cfg.weight_decay,
|
|
146
|
+
momentum=cfg.momentum)
|
|
147
|
+
if getattr(cfg, 'opt_eps', None) is not None:
|
|
148
|
+
kwargs['eps'] = cfg.opt_eps
|
|
149
|
+
if getattr(cfg, 'opt_betas', None) is not None:
|
|
150
|
+
kwargs['betas'] = cfg.opt_betas
|
|
151
|
+
if getattr(cfg, 'opt_args', None) is not None:
|
|
152
|
+
kwargs.update(cfg.opt_args)
|
|
153
|
+
return kwargs
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def build_optimizer_from_cfg(
|
|
157
|
+
model,
|
|
158
|
+
NAME: str = 'sgd',
|
|
159
|
+
lr: Optional[float] = None,
|
|
160
|
+
weight_decay: float = 0.,
|
|
161
|
+
momentum: float = 0.9,
|
|
162
|
+
filter_bias_and_bn: bool = True,
|
|
163
|
+
filter_by_modules_names=None,
|
|
164
|
+
**kwargs):
|
|
165
|
+
""" Create an optimizer.
|
|
166
|
+
Args:
|
|
167
|
+
model (nn.Module): model containing parameters to optimize
|
|
168
|
+
NAME: name of optimizer to create
|
|
169
|
+
lr: initial learning rate
|
|
170
|
+
weight_decay: weight decay to apply in optimizer
|
|
171
|
+
momentum: momentum for momentum based optimizers (others may use betas via kwargs)
|
|
172
|
+
filter_bias_and_bn: filter out bias, bn and other 1d params from weight decay
|
|
173
|
+
**kwargs: extra optimizer specific kwargs to pass through
|
|
174
|
+
Returns:
|
|
175
|
+
Optimizer
|
|
176
|
+
"""
|
|
177
|
+
# layer lr decay
|
|
178
|
+
layer_decay = kwargs.get('layer_decay', 0)
|
|
179
|
+
if 0. < layer_decay < 1.0:
|
|
180
|
+
num_layers = model.get_num_layers()
|
|
181
|
+
assigner = LayerDecayValueAssigner(
|
|
182
|
+
list(layer_decay ** (num_layers + 1 - i) for i in range(num_layers + 2)))
|
|
183
|
+
get_num_layer = assigner.get_layer_id
|
|
184
|
+
get_layer_scale = assigner.get_scale
|
|
185
|
+
else:
|
|
186
|
+
get_num_layer, get_layer_scale = None, None
|
|
187
|
+
|
|
188
|
+
assert isinstance(model, nn.Module)
|
|
189
|
+
# a model was passed in, extract parameters and add weight decays to appropriate layers
|
|
190
|
+
if weight_decay and filter_bias_and_bn:
|
|
191
|
+
skip = {}
|
|
192
|
+
if hasattr(model, 'module'):
|
|
193
|
+
if hasattr(model.module, 'no_weight_decay'):
|
|
194
|
+
skip = model.module.no_weight_decay()
|
|
195
|
+
else:
|
|
196
|
+
if hasattr(model, 'no_weight_decay'):
|
|
197
|
+
skip = model.module.no_weight_decay()
|
|
198
|
+
parameters = get_parameter_groups(model, weight_decay, skip, get_num_layer, get_layer_scale,
|
|
199
|
+
filter_by_modules_names
|
|
200
|
+
)
|
|
201
|
+
weight_decay = 0.
|
|
202
|
+
else:
|
|
203
|
+
parameters = model.parameters()
|
|
204
|
+
|
|
205
|
+
opt_lower = NAME.lower()
|
|
206
|
+
opt_split = opt_lower.split('_')
|
|
207
|
+
opt_lower = opt_split[-1]
|
|
208
|
+
if 'fused' in opt_lower:
|
|
209
|
+
assert has_apex and torch.cuda.is_available(), 'APEX and CUDA required for fused optimizers'
|
|
210
|
+
|
|
211
|
+
opt_args = dict(weight_decay=weight_decay, **kwargs)
|
|
212
|
+
if lr is not None:
|
|
213
|
+
opt_args.setdefault('lr', lr)
|
|
214
|
+
|
|
215
|
+
# basic SGD & related
|
|
216
|
+
if opt_lower == 'sgd' or opt_lower == 'nesterov':
|
|
217
|
+
# NOTE 'sgd' refers to SGD + nesterov momentum for legacy / backwards compat reasons
|
|
218
|
+
opt_args.pop('eps', None)
|
|
219
|
+
optimizer = optim.SGD(parameters, momentum=momentum, nesterov=True, **opt_args)
|
|
220
|
+
elif opt_lower == 'momentum':
|
|
221
|
+
opt_args.pop('eps', None)
|
|
222
|
+
optimizer = optim.SGD(parameters, momentum=momentum, nesterov=False, **opt_args)
|
|
223
|
+
elif opt_lower == 'sgdp':
|
|
224
|
+
optimizer = SGDP(parameters, momentum=momentum, nesterov=True, **opt_args)
|
|
225
|
+
|
|
226
|
+
# adaptive
|
|
227
|
+
elif opt_lower == 'adam':
|
|
228
|
+
optimizer = optim.Adam(parameters, **opt_args)
|
|
229
|
+
elif opt_lower == 'adamw':
|
|
230
|
+
optimizer = optim.AdamW(parameters, **opt_args)
|
|
231
|
+
elif opt_lower == 'adamp':
|
|
232
|
+
optimizer = AdamP(parameters, wd_ratio=0.01, nesterov=True, **opt_args)
|
|
233
|
+
elif opt_lower == 'nadam':
|
|
234
|
+
try:
|
|
235
|
+
# NOTE PyTorch >= 1.10 should have native NAdam
|
|
236
|
+
optimizer = optim.Nadam(parameters, **opt_args)
|
|
237
|
+
except AttributeError:
|
|
238
|
+
optimizer = Nadam(parameters, **opt_args)
|
|
239
|
+
elif opt_lower == 'radam':
|
|
240
|
+
optimizer = RAdam(parameters, **opt_args)
|
|
241
|
+
elif opt_lower == 'adamax':
|
|
242
|
+
optimizer = optim.Adamax(parameters, **opt_args)
|
|
243
|
+
elif opt_lower == 'adabelief':
|
|
244
|
+
optimizer = AdaBelief(parameters, rectify=False, **opt_args)
|
|
245
|
+
elif opt_lower == 'radabelief':
|
|
246
|
+
optimizer = AdaBelief(parameters, rectify=True, **opt_args)
|
|
247
|
+
elif opt_lower == 'adadelta':
|
|
248
|
+
optimizer = optim.Adadelta(parameters, **opt_args)
|
|
249
|
+
elif opt_lower == 'adagrad':
|
|
250
|
+
opt_args.setdefault('eps', 1e-8)
|
|
251
|
+
optimizer = optim.Adagrad(parameters, **opt_args)
|
|
252
|
+
elif opt_lower == 'adafactor':
|
|
253
|
+
optimizer = Adafactor(parameters, **opt_args)
|
|
254
|
+
elif opt_lower == 'lamb':
|
|
255
|
+
optimizer = Lamb(parameters, **opt_args)
|
|
256
|
+
elif opt_lower == 'lambc':
|
|
257
|
+
optimizer = Lamb(parameters, trust_clip=True, **opt_args)
|
|
258
|
+
elif opt_lower == 'larc':
|
|
259
|
+
optimizer = Lars(parameters, momentum=momentum, trust_clip=True, **opt_args)
|
|
260
|
+
elif opt_lower == 'lars':
|
|
261
|
+
optimizer = Lars(parameters, momentum=momentum, **opt_args)
|
|
262
|
+
elif opt_lower == 'nlarc':
|
|
263
|
+
optimizer = Lars(parameters, momentum=momentum, trust_clip=True, nesterov=True, **opt_args)
|
|
264
|
+
elif opt_lower == 'nlars':
|
|
265
|
+
optimizer = Lars(parameters, momentum=momentum, nesterov=True, **opt_args)
|
|
266
|
+
elif opt_lower == 'madgrad':
|
|
267
|
+
optimizer = MADGRAD(parameters, momentum=momentum, **opt_args)
|
|
268
|
+
elif opt_lower == 'madgradw':
|
|
269
|
+
optimizer = MADGRAD(parameters, momentum=momentum, decoupled_decay=True, **opt_args)
|
|
270
|
+
elif opt_lower == 'novograd' or opt_lower == 'nvnovograd':
|
|
271
|
+
optimizer = NvNovoGrad(parameters, **opt_args)
|
|
272
|
+
elif opt_lower == 'rmsprop':
|
|
273
|
+
optimizer = optim.RMSprop(parameters, alpha=0.9, momentum=momentum, **opt_args)
|
|
274
|
+
elif opt_lower == 'rmsproptf':
|
|
275
|
+
optimizer = RMSpropTF(parameters, alpha=0.9, momentum=momentum, **opt_args)
|
|
276
|
+
|
|
277
|
+
# second order
|
|
278
|
+
elif opt_lower == 'adahessian':
|
|
279
|
+
optimizer = Adahessian(parameters, **opt_args)
|
|
280
|
+
|
|
281
|
+
# NVIDIA fused optimizers, require APEX to be installed
|
|
282
|
+
elif opt_lower == 'fusedsgd':
|
|
283
|
+
opt_args.pop('eps', None)
|
|
284
|
+
optimizer = FusedSGD(parameters, momentum=momentum, nesterov=True, **opt_args)
|
|
285
|
+
elif opt_lower == 'fusedmomentum':
|
|
286
|
+
opt_args.pop('eps', None)
|
|
287
|
+
optimizer = FusedSGD(parameters, momentum=momentum, nesterov=False, **opt_args)
|
|
288
|
+
elif opt_lower == 'fusedadam':
|
|
289
|
+
optimizer = FusedAdam(parameters, adam_w_mode=False, **opt_args)
|
|
290
|
+
elif opt_lower == 'fusedadamw':
|
|
291
|
+
optimizer = FusedAdam(parameters, adam_w_mode=True, **opt_args)
|
|
292
|
+
elif opt_lower == 'fusedlamb':
|
|
293
|
+
optimizer = FusedLAMB(parameters, **opt_args)
|
|
294
|
+
elif opt_lower == 'fusednovograd':
|
|
295
|
+
opt_args.setdefault('betas', (0.95, 0.98))
|
|
296
|
+
optimizer = FusedNovoGrad(parameters, **opt_args)
|
|
297
|
+
|
|
298
|
+
else:
|
|
299
|
+
assert False and "Invalid optimizer"
|
|
300
|
+
raise ValueError
|
|
301
|
+
|
|
302
|
+
if len(opt_split) > 1:
|
|
303
|
+
if opt_split[0] == 'lookahead':
|
|
304
|
+
optimizer = Lookahead(optimizer)
|
|
305
|
+
|
|
306
|
+
return optimizer
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""RAdam Optimizer.
|
|
2
|
+
Implementation lifted from: https://github.com/LiyuanLucasLiu/RAdam
|
|
3
|
+
Paper: `On the Variance of the Adaptive Learning Rate and Beyond` - https://arxiv.org/abs/1908.03265
|
|
4
|
+
"""
|
|
5
|
+
import math
|
|
6
|
+
import torch
|
|
7
|
+
from torch.optim.optimizer import Optimizer
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class RAdam(Optimizer):
|
|
11
|
+
|
|
12
|
+
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0):
|
|
13
|
+
defaults = dict(
|
|
14
|
+
lr=lr, betas=betas, eps=eps, weight_decay=weight_decay,
|
|
15
|
+
buffer=[[None, None, None] for _ in range(10)])
|
|
16
|
+
super(RAdam, self).__init__(params, defaults)
|
|
17
|
+
|
|
18
|
+
def __setstate__(self, state):
|
|
19
|
+
super(RAdam, self).__setstate__(state)
|
|
20
|
+
|
|
21
|
+
@torch.no_grad()
|
|
22
|
+
def step(self, closure=None):
|
|
23
|
+
loss = None
|
|
24
|
+
if closure is not None:
|
|
25
|
+
with torch.enable_grad():
|
|
26
|
+
loss = closure()
|
|
27
|
+
|
|
28
|
+
for group in self.param_groups:
|
|
29
|
+
|
|
30
|
+
for p in group['params']:
|
|
31
|
+
if p.grad is None:
|
|
32
|
+
continue
|
|
33
|
+
grad = p.grad.float()
|
|
34
|
+
if grad.is_sparse:
|
|
35
|
+
raise RuntimeError('RAdam does not support sparse gradients')
|
|
36
|
+
|
|
37
|
+
p_fp32 = p.float()
|
|
38
|
+
|
|
39
|
+
state = self.state[p]
|
|
40
|
+
|
|
41
|
+
if len(state) == 0:
|
|
42
|
+
state['step'] = 0
|
|
43
|
+
state['exp_avg'] = torch.zeros_like(p_fp32)
|
|
44
|
+
state['exp_avg_sq'] = torch.zeros_like(p_fp32)
|
|
45
|
+
else:
|
|
46
|
+
state['exp_avg'] = state['exp_avg'].type_as(p_fp32)
|
|
47
|
+
state['exp_avg_sq'] = state['exp_avg_sq'].type_as(p_fp32)
|
|
48
|
+
|
|
49
|
+
exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']
|
|
50
|
+
beta1, beta2 = group['betas']
|
|
51
|
+
|
|
52
|
+
exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)
|
|
53
|
+
exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1)
|
|
54
|
+
|
|
55
|
+
state['step'] += 1
|
|
56
|
+
buffered = group['buffer'][int(state['step'] % 10)]
|
|
57
|
+
if state['step'] == buffered[0]:
|
|
58
|
+
num_sma, step_size = buffered[1], buffered[2]
|
|
59
|
+
else:
|
|
60
|
+
buffered[0] = state['step']
|
|
61
|
+
beta2_t = beta2 ** state['step']
|
|
62
|
+
num_sma_max = 2 / (1 - beta2) - 1
|
|
63
|
+
num_sma = num_sma_max - 2 * state['step'] * beta2_t / (1 - beta2_t)
|
|
64
|
+
buffered[1] = num_sma
|
|
65
|
+
|
|
66
|
+
# more conservative since it's an approximated value
|
|
67
|
+
if num_sma >= 5:
|
|
68
|
+
step_size = group['lr'] * math.sqrt(
|
|
69
|
+
(1 - beta2_t) *
|
|
70
|
+
(num_sma - 4) / (num_sma_max - 4) *
|
|
71
|
+
(num_sma - 2) / num_sma *
|
|
72
|
+
num_sma_max / (num_sma_max - 2)) / (1 - beta1 ** state['step'])
|
|
73
|
+
else:
|
|
74
|
+
step_size = group['lr'] / (1 - beta1 ** state['step'])
|
|
75
|
+
buffered[2] = step_size
|
|
76
|
+
|
|
77
|
+
if group['weight_decay'] != 0:
|
|
78
|
+
p_fp32.add_(p_fp32, alpha=-group['weight_decay'] * group['lr'])
|
|
79
|
+
|
|
80
|
+
# more conservative since it's an approximated value
|
|
81
|
+
if num_sma >= 5:
|
|
82
|
+
denom = exp_avg_sq.sqrt().add_(group['eps'])
|
|
83
|
+
p_fp32.addcdiv_(exp_avg, denom, value=-step_size)
|
|
84
|
+
else:
|
|
85
|
+
p_fp32.add_(exp_avg, alpha=-step_size)
|
|
86
|
+
|
|
87
|
+
p.copy_(p_fp32)
|
|
88
|
+
|
|
89
|
+
return loss
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
""" RMSProp modified to behave like Tensorflow impl
|
|
2
|
+
|
|
3
|
+
Originally cut & paste from PyTorch RMSProp
|
|
4
|
+
https://github.com/pytorch/pytorch/blob/063946d2b3f3f1e953a2a3b54e0b34f1393de295/torch/optim/rmsprop.py
|
|
5
|
+
Licensed under BSD-Clause 3 (ish), https://github.com/pytorch/pytorch/blob/master/LICENSE
|
|
6
|
+
|
|
7
|
+
Modifications Copyright 2021 Ross Wightman
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import torch
|
|
11
|
+
from torch.optim import Optimizer
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class RMSpropTF(Optimizer):
|
|
15
|
+
"""Implements RMSprop algorithm (TensorFlow style epsilon)
|
|
16
|
+
|
|
17
|
+
NOTE: This is a direct cut-and-paste of PyTorch RMSprop with eps applied before sqrt
|
|
18
|
+
and a few other modifications to closer match Tensorflow for matching hyper-params.
|
|
19
|
+
|
|
20
|
+
Noteworthy changes include:
|
|
21
|
+
1. Epsilon applied inside square-root
|
|
22
|
+
2. square_avg initialized to ones
|
|
23
|
+
3. LR scaling of update accumulated in momentum buffer
|
|
24
|
+
|
|
25
|
+
Proposed by G. Hinton in his
|
|
26
|
+
`course <http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf>`_.
|
|
27
|
+
|
|
28
|
+
The centered version first appears in `Generating Sequences
|
|
29
|
+
With Recurrent Neural Networks <https://arxiv.org/pdf/1308.0850v5.pdf>`_.
|
|
30
|
+
|
|
31
|
+
Arguments:
|
|
32
|
+
params (iterable): iterable of parameters to optimize or dicts defining
|
|
33
|
+
parameter groups
|
|
34
|
+
lr (float, optional): learning rate (default: 1e-2)
|
|
35
|
+
momentum (float, optional): momentum factor (default: 0)
|
|
36
|
+
alpha (float, optional): smoothing (decay) constant (default: 0.9)
|
|
37
|
+
eps (float, optional): term added to the denominator to improve
|
|
38
|
+
numerical stability (default: 1e-10)
|
|
39
|
+
centered (bool, optional) : if ``True``, compute the centered RMSProp,
|
|
40
|
+
the gradient is normalized by an estimation of its variance
|
|
41
|
+
weight_decay (float, optional): weight decay (L2 penalty) (default: 0)
|
|
42
|
+
decoupled_decay (bool, optional): decoupled weight decay as per https://arxiv.org/abs/1711.05101
|
|
43
|
+
lr_in_momentum (bool, optional): learning rate scaling is included in the momentum buffer
|
|
44
|
+
update as per defaults in Tensorflow
|
|
45
|
+
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, params, lr=1e-2, alpha=0.9, eps=1e-10, weight_decay=0, momentum=0., centered=False,
|
|
49
|
+
decoupled_decay=False, lr_in_momentum=True):
|
|
50
|
+
if not 0.0 <= lr:
|
|
51
|
+
raise ValueError("Invalid learning rate: {}".format(lr))
|
|
52
|
+
if not 0.0 <= eps:
|
|
53
|
+
raise ValueError("Invalid epsilon value: {}".format(eps))
|
|
54
|
+
if not 0.0 <= momentum:
|
|
55
|
+
raise ValueError("Invalid momentum value: {}".format(momentum))
|
|
56
|
+
if not 0.0 <= weight_decay:
|
|
57
|
+
raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
|
|
58
|
+
if not 0.0 <= alpha:
|
|
59
|
+
raise ValueError("Invalid alpha value: {}".format(alpha))
|
|
60
|
+
|
|
61
|
+
defaults = dict(
|
|
62
|
+
lr=lr, momentum=momentum, alpha=alpha, eps=eps, centered=centered, weight_decay=weight_decay,
|
|
63
|
+
decoupled_decay=decoupled_decay, lr_in_momentum=lr_in_momentum)
|
|
64
|
+
super(RMSpropTF, self).__init__(params, defaults)
|
|
65
|
+
|
|
66
|
+
def __setstate__(self, state):
|
|
67
|
+
super(RMSpropTF, self).__setstate__(state)
|
|
68
|
+
for group in self.param_groups:
|
|
69
|
+
group.setdefault('momentum', 0)
|
|
70
|
+
group.setdefault('centered', False)
|
|
71
|
+
|
|
72
|
+
@torch.no_grad()
|
|
73
|
+
def step(self, closure=None):
|
|
74
|
+
"""Performs a single optimization step.
|
|
75
|
+
|
|
76
|
+
Arguments:
|
|
77
|
+
closure (callable, optional): A closure that reevaluates the model
|
|
78
|
+
and returns the loss.
|
|
79
|
+
"""
|
|
80
|
+
loss = None
|
|
81
|
+
if closure is not None:
|
|
82
|
+
with torch.enable_grad():
|
|
83
|
+
loss = closure()
|
|
84
|
+
|
|
85
|
+
for group in self.param_groups:
|
|
86
|
+
for p in group['params']:
|
|
87
|
+
if p.grad is None:
|
|
88
|
+
continue
|
|
89
|
+
grad = p.grad
|
|
90
|
+
if grad.is_sparse:
|
|
91
|
+
raise RuntimeError('RMSprop does not support sparse gradients')
|
|
92
|
+
state = self.state[p]
|
|
93
|
+
|
|
94
|
+
# State initialization
|
|
95
|
+
if len(state) == 0:
|
|
96
|
+
state['step'] = 0
|
|
97
|
+
state['square_avg'] = torch.ones_like(p) # PyTorch inits to zero
|
|
98
|
+
if group['momentum'] > 0:
|
|
99
|
+
state['momentum_buffer'] = torch.zeros_like(p)
|
|
100
|
+
if group['centered']:
|
|
101
|
+
state['grad_avg'] = torch.zeros_like(p)
|
|
102
|
+
|
|
103
|
+
square_avg = state['square_avg']
|
|
104
|
+
one_minus_alpha = 1. - group['alpha']
|
|
105
|
+
|
|
106
|
+
state['step'] += 1
|
|
107
|
+
|
|
108
|
+
if group['weight_decay'] != 0:
|
|
109
|
+
if group['decoupled_decay']:
|
|
110
|
+
p.mul_(1. - group['lr'] * group['weight_decay'])
|
|
111
|
+
else:
|
|
112
|
+
grad = grad.add(p, alpha=group['weight_decay'])
|
|
113
|
+
|
|
114
|
+
# Tensorflow order of ops for updating squared avg
|
|
115
|
+
square_avg.add_(grad.pow(2) - square_avg, alpha=one_minus_alpha)
|
|
116
|
+
# square_avg.mul_(alpha).addcmul_(grad, grad, value=1 - alpha) # PyTorch original
|
|
117
|
+
|
|
118
|
+
if group['centered']:
|
|
119
|
+
grad_avg = state['grad_avg']
|
|
120
|
+
grad_avg.add_(grad - grad_avg, alpha=one_minus_alpha)
|
|
121
|
+
avg = square_avg.addcmul(grad_avg, grad_avg, value=-1).add(group['eps']).sqrt_() # eps in sqrt
|
|
122
|
+
# grad_avg.mul_(alpha).add_(grad, alpha=1 - alpha) # PyTorch original
|
|
123
|
+
else:
|
|
124
|
+
avg = square_avg.add(group['eps']).sqrt_() # eps moved in sqrt
|
|
125
|
+
|
|
126
|
+
if group['momentum'] > 0:
|
|
127
|
+
buf = state['momentum_buffer']
|
|
128
|
+
# Tensorflow accumulates the LR scaling in the momentum buffer
|
|
129
|
+
if group['lr_in_momentum']:
|
|
130
|
+
buf.mul_(group['momentum']).addcdiv_(grad, avg, value=group['lr'])
|
|
131
|
+
p.add_(-buf)
|
|
132
|
+
else:
|
|
133
|
+
# PyTorch scales the param update by LR
|
|
134
|
+
buf.mul_(group['momentum']).addcdiv_(grad, avg)
|
|
135
|
+
p.add_(buf, alpha=-group['lr'])
|
|
136
|
+
else:
|
|
137
|
+
p.addcdiv_(grad, avg, value=-group['lr'])
|
|
138
|
+
|
|
139
|
+
return loss
|