Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

optimization.py 6.1 KB

You have to be logged in to leave a comment. Sign In
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
  1. # coding=utf-8
  2. # Copyright 2018 The Google AI Language Team Authors.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Functions and classes related to optimization (weight updates)."""
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. import re
  20. import tensorflow as tf
  21. def create_optimizer(loss, init_lr, num_train_steps, num_warmup_steps, use_tpu):
  22. """Creates an optimizer training op."""
  23. global_step = tf.train.get_or_create_global_step()
  24. learning_rate = tf.constant(value=init_lr, shape=[], dtype=tf.float32)
  25. # Implements linear decay of the learning rate.
  26. learning_rate = tf.train.polynomial_decay(
  27. learning_rate,
  28. global_step,
  29. num_train_steps,
  30. end_learning_rate=0.0,
  31. power=1.0,
  32. cycle=False)
  33. # Implements linear warmup. I.e., if global_step < num_warmup_steps, the
  34. # learning rate will be `global_step/num_warmup_steps * init_lr`.
  35. if num_warmup_steps:
  36. global_steps_int = tf.cast(global_step, tf.int32)
  37. warmup_steps_int = tf.constant(num_warmup_steps, dtype=tf.int32)
  38. global_steps_float = tf.cast(global_steps_int, tf.float32)
  39. warmup_steps_float = tf.cast(warmup_steps_int, tf.float32)
  40. warmup_percent_done = global_steps_float / warmup_steps_float
  41. warmup_learning_rate = init_lr * warmup_percent_done
  42. is_warmup = tf.cast(global_steps_int < warmup_steps_int, tf.float32)
  43. learning_rate = (
  44. (1.0 - is_warmup) * learning_rate + is_warmup * warmup_learning_rate)
  45. # It is recommended that you use this optimizer for fine tuning, since this
  46. # is how the model was trained (note that the Adam m/v variables are NOT
  47. # loaded from init_checkpoint.)
  48. optimizer = AdamWeightDecayOptimizer(
  49. learning_rate=learning_rate,
  50. weight_decay_rate=0.01,
  51. beta_1=0.9,
  52. beta_2=0.999,
  53. epsilon=1e-6,
  54. exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"])
  55. if use_tpu:
  56. optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer)
  57. tvars = tf.trainable_variables()
  58. grads = tf.gradients(loss, tvars)
  59. # This is how the model was pre-trained.
  60. (grads, _) = tf.clip_by_global_norm(grads, clip_norm=1.0)
  61. train_op = optimizer.apply_gradients(
  62. zip(grads, tvars), global_step=global_step)
  63. # Normally the global step update is done inside of `apply_gradients`.
  64. # However, `AdamWeightDecayOptimizer` doesn't do this. But if you use
  65. # a different optimizer, you should probably take this line out.
  66. new_global_step = global_step + 1
  67. train_op = tf.group(train_op, [global_step.assign(new_global_step)])
  68. return train_op
  69. class AdamWeightDecayOptimizer(tf.train.Optimizer):
  70. """A basic Adam optimizer that includes "correct" L2 weight decay."""
  71. def __init__(self,
  72. learning_rate,
  73. weight_decay_rate=0.0,
  74. beta_1=0.9,
  75. beta_2=0.999,
  76. epsilon=1e-6,
  77. exclude_from_weight_decay=None,
  78. name="AdamWeightDecayOptimizer"):
  79. """Constructs a AdamWeightDecayOptimizer."""
  80. super(AdamWeightDecayOptimizer, self).__init__(False, name)
  81. self.learning_rate = learning_rate
  82. self.weight_decay_rate = weight_decay_rate
  83. self.beta_1 = beta_1
  84. self.beta_2 = beta_2
  85. self.epsilon = epsilon
  86. self.exclude_from_weight_decay = exclude_from_weight_decay
  87. def apply_gradients(self, grads_and_vars, global_step=None, name=None):
  88. """See base class."""
  89. assignments = []
  90. for (grad, param) in grads_and_vars:
  91. if grad is None or param is None:
  92. continue
  93. param_name = self._get_variable_name(param.name)
  94. m = tf.get_variable(
  95. name=param_name + "/adam_m",
  96. shape=param.shape.as_list(),
  97. dtype=tf.float32,
  98. trainable=False,
  99. initializer=tf.zeros_initializer())
  100. v = tf.get_variable(
  101. name=param_name + "/adam_v",
  102. shape=param.shape.as_list(),
  103. dtype=tf.float32,
  104. trainable=False,
  105. initializer=tf.zeros_initializer())
  106. # Standard Adam update.
  107. next_m = (
  108. tf.multiply(self.beta_1, m) + tf.multiply(1.0 - self.beta_1, grad))
  109. next_v = (
  110. tf.multiply(self.beta_2, v) + tf.multiply(1.0 - self.beta_2,
  111. tf.square(grad)))
  112. update = next_m / (tf.sqrt(next_v) + self.epsilon)
  113. # Just adding the square of the weights to the loss function is *not*
  114. # the correct way of using L2 regularization/weight decay with Adam,
  115. # since that will interact with the m and v parameters in strange ways.
  116. #
  117. # Instead we want ot decay the weights in a manner that doesn't interact
  118. # with the m/v parameters. This is equivalent to adding the square
  119. # of the weights to the loss with plain (non-momentum) SGD.
  120. if self._do_use_weight_decay(param_name):
  121. update += self.weight_decay_rate * param
  122. update_with_lr = self.learning_rate * update
  123. next_param = param - update_with_lr
  124. assignments.extend(
  125. [param.assign(next_param),
  126. m.assign(next_m),
  127. v.assign(next_v)])
  128. return tf.group(*assignments, name=name)
  129. def _do_use_weight_decay(self, param_name):
  130. """Whether to use L2 weight decay for `param_name`."""
  131. if not self.weight_decay_rate:
  132. return False
  133. if self.exclude_from_weight_decay:
  134. for r in self.exclude_from_weight_decay:
  135. if re.search(r, param_name) is not None:
  136. return False
  137. return True
  138. def _get_variable_name(self, param_name):
  139. """Get the variable name from the tensor name."""
  140. m = re.match("^(.*):\\d+$", param_name)
  141. if m is not None:
  142. param_name = m.group(1)
  143. return param_name
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...