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 5.9 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
  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. new_global_step = global_step + 1
  64. train_op = tf.group(train_op, [global_step.assign(new_global_step)])
  65. return train_op
  66. class AdamWeightDecayOptimizer(tf.train.Optimizer):
  67. """A basic Adam optimizer that includes "correct" L2 weight decay."""
  68. def __init__(self,
  69. learning_rate,
  70. weight_decay_rate=0.0,
  71. beta_1=0.9,
  72. beta_2=0.999,
  73. epsilon=1e-6,
  74. exclude_from_weight_decay=None,
  75. name="AdamWeightDecayOptimizer"):
  76. """Constructs a AdamWeightDecayOptimizer."""
  77. super(AdamWeightDecayOptimizer, self).__init__(False, name)
  78. self.learning_rate = learning_rate
  79. self.weight_decay_rate = weight_decay_rate
  80. self.beta_1 = beta_1
  81. self.beta_2 = beta_2
  82. self.epsilon = epsilon
  83. self.exclude_from_weight_decay = exclude_from_weight_decay
  84. def apply_gradients(self, grads_and_vars, global_step=None, name=None):
  85. """See base class."""
  86. assignments = []
  87. for (grad, param) in grads_and_vars:
  88. if grad is None or param is None:
  89. continue
  90. param_name = self._get_variable_name(param.name)
  91. m = tf.get_variable(
  92. name=param_name + "/adam_m",
  93. shape=param.shape.as_list(),
  94. dtype=tf.float32,
  95. trainable=False,
  96. initializer=tf.zeros_initializer())
  97. v = tf.get_variable(
  98. name=param_name + "/adam_v",
  99. shape=param.shape.as_list(),
  100. dtype=tf.float32,
  101. trainable=False,
  102. initializer=tf.zeros_initializer())
  103. # Standard Adam update.
  104. next_m = (
  105. tf.multiply(self.beta_1, m) + tf.multiply(1.0 - self.beta_1, grad))
  106. next_v = (
  107. tf.multiply(self.beta_2, v) + tf.multiply(1.0 - self.beta_2,
  108. tf.square(grad)))
  109. update = next_m / (tf.sqrt(next_v) + self.epsilon)
  110. # Just adding the square of the weights to the loss function is *not*
  111. # the correct way of using L2 regularization/weight decay with Adam,
  112. # since that will interact with the m and v parameters in strange ways.
  113. #
  114. # Instead we want ot decay the weights in a manner that doesn't interact
  115. # with the m/v parameters. This is equivalent to adding the square
  116. # of the weights to the loss with plain (non-momentum) SGD.
  117. if self._do_use_weight_decay(param_name):
  118. update += self.weight_decay_rate * param
  119. update_with_lr = self.learning_rate * update
  120. next_param = param - update_with_lr
  121. assignments.extend(
  122. [param.assign(next_param),
  123. m.assign(next_m),
  124. v.assign(next_v)])
  125. return tf.group(*assignments, name=name)
  126. def _do_use_weight_decay(self, param_name):
  127. """Whether to use L2 weight decay for `param_name`."""
  128. if not self.weight_decay_rate:
  129. return False
  130. if self.exclude_from_weight_decay:
  131. for r in self.exclude_from_weight_decay:
  132. if re.search(r, param_name) is not None:
  133. return False
  134. return True
  135. def _get_variable_name(self, param_name):
  136. """Get the variable name from the tensor name."""
  137. m = re.match("^(.*):\\d+$", param_name)
  138. if m is not None:
  139. param_name = m.group(1)
  140. return param_name
Tip!

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

Comments

Loading...