-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathoptimizer.py
129 lines (108 loc) · 5.6 KB
/
optimizer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
"""
Entropy-SGD TensorFlow implementation
Original paper: arXiv 1611.01838
Justin Tan 2017
"""
import tensorflow as tf
import numpy as np
from tensorflow.python.framework import ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.training import optimizer
from tensorflow.python.training import training_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import state_ops
from network import Network
from sgld import local_entropy_sgld
from config import config_train
class EntropySGD(optimizer.Optimizer):
def __init__(self, iterator, training_phase, sgld_global_step, config={},
use_locking=False, name='EntropySGD'):
# Construct entropy-sgd optimizer - ref. arXiv 1611.01838
defaults = dict(lr=1e-3, gamma=1e-3, momentum=0, damp=0, weight_decay=0,
nesterov=True, L=2, epsilon=1e-4, g0=3e-2, g1=1e-3,
alpha=0.75, lr_prime=0.1)
for k in defaults:
if config.get(k, None) is None:
config[k] = defaults[k]
super(EntropySGD, self).__init__(use_locking, name)
self.config = config
self.iterator = iterator
self.training_phase = training_phase
self.sgld_global_step = sgld_global_step
self._learning_rate = config['lr']
self._gamma = config['gamma']
# Scalar parameter tensors
self._lr_tensor = None
self._gamma_tensor = None
self._lr_prime_tensor = None
self._epsilon_tensor = None
self._g0_tensor = None
self._g1_tensor = None
self._alpha_tensor = None
self._wd_tensor = None
self._momentum_tensor = None
self.sgld_opt = local_entropy_sgld(eta_prime=config['lr_prime'],
epsilon=config['epsilon'], gamma=self._gamma, alpha=config['alpha'],
momentum=config['momentum'], L=config['L'],
sgld_global_step=self.sgld_global_step)
def _prepare(self):
self._lr_tensor = ops.convert_to_tensor(self._learning_rate,
name="learning_rate")
self._gamma_tensor = ops.convert_to_tensor(self._gamma,
name="gamma")
self._lr_prime_tensor = ops.convert_to_tensor(self.config['lr_prime'],
name="learning_rate_prime")
self._epsilon_tensor = ops.convert_to_tensor(self.config['epsilon'],
name="epsilon")
self._g0_tensor = ops.convert_to_tensor(self.config['g0'], name="gamma_0")
self._g1_tensor = ops.convert_to_tensor(self.config['g1'], name="gamma_1")
self._alpha_tensor = ops.convert_to_tensor(self.config['alpha'],
name="alpha")
self._wd_tensor = ops.convert_to_tensor(self.config['weight_decay'],
name="decay")
self._momentum_tensor = ops.convert_to_tensor(self.config['momentum'],
name="momentum")
def _create_slots(self, var_list):
# Manage variables that accumulate updates
# Creates slots for x', the expectation μ = <x'> and current weights
for v in var_list:
mu = self._zeros_slot(v, "mu", self._name)
def _langevin_ops(self, l):
self.example, self.labels = self.iterator.get_next()
self.logits = Network.cnn(self.example, config_train, self.training_phase, reuse=True)
self.cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.logits,
labels=self.labels))
self.inner = self.sgld_opt.minimize(self.cost, global_step=self.sgld_global_step)
def _apply_dense(self, grad, var):
# Apply weight updates
lr_t = math_ops.cast(self._lr_tensor, var.dtype.base_dtype)
gamma_t = math_ops.cast(self._gamma_tensor, var.dtype.base_dtype)
lr_prime_t = math_ops.cast(self._lr_prime_tensor, var.dtype.base_dtype)
eps_t = math_ops.cast(self._epsilon_tensor, var.dtype.base_dtype)
g0_t = math_ops.cast(self._g0_tensor, var.dtype.base_dtype)
g1_t = math_ops.cast(self._g1_tensor, var.dtype.base_dtype)
alpha_t = math_ops.cast(self._alpha_tensor, var.dtype.base_dtype)
mu = self.get_slot(var, 'mu')
# mu_t = mu.assign((1-alpha_t)*mu + alpha_t*var)
# gamma_t = g0_t*tf.pow(1.0+g1_t, tf.cast(self.global_step), tf.float32)
# gamma_t = gamma.assign(g0_t*tf.pow((1+g1_t), self.global_step))
# gs_t = gs.assign(gs+1)
for l in range(self.config['L']):
# print(l)
self._langevin_ops(l)
# run L iterations of SGLD
# for l in range(L):
# self.example, self.labels = self.iterator.get_next()
# self.logits = Network.cnn(self.example, config_train, self.training_phase)
# self.cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.logits,
# labels=self.labels))
# g, v = self.compute_gradients(self.cost, var_list=[var])
#print(self.sgld_opt.get_slot_names())
#print(var)
mu_t = mu.assign(self.sgld_opt.get_slot(var, 'mu'))
var_update = state_ops.assign_sub(var, lr_t*gamma_t*(var-mu_t))
return control_flow_ops.group(*[var_update, mu_t])
def _apply_sparse(self, grad, var_list):
raise NotImplementedError("Optimizer does not yet support sparse gradient updates.")