Creates an optimizer training op.
(loss, init_lr, num_train_steps, num_warmup_steps, use_tpu)
| 23 | |
| 24 | |
| 25 | def create_optimizer(loss, init_lr, num_train_steps, num_warmup_steps, use_tpu): |
| 26 | """Creates an optimizer training op.""" |
| 27 | global_step = tf.train.get_or_create_global_step() |
| 28 | |
| 29 | learning_rate = tf.constant(value=init_lr, shape=[], dtype=tf.float32) |
| 30 | |
| 31 | # Implements linear decay of the learning rate. |
| 32 | learning_rate = tf.train.polynomial_decay( |
| 33 | learning_rate, |
| 34 | global_step, |
| 35 | num_train_steps, |
| 36 | end_learning_rate=0.0, |
| 37 | power=1.0, |
| 38 | cycle=False) |
| 39 | |
| 40 | # Implements linear warmup. I.e., if global_step < num_warmup_steps, the |
| 41 | # learning rate will be `global_step/num_warmup_steps * init_lr`. |
| 42 | if num_warmup_steps: |
| 43 | global_steps_int = tf.cast(global_step, tf.int32) |
| 44 | warmup_steps_int = tf.constant(num_warmup_steps, dtype=tf.int32) |
| 45 | |
| 46 | global_steps_float = tf.cast(global_steps_int, tf.float32) |
| 47 | warmup_steps_float = tf.cast(warmup_steps_int, tf.float32) |
| 48 | |
| 49 | warmup_percent_done = global_steps_float / warmup_steps_float |
| 50 | warmup_learning_rate = init_lr * warmup_percent_done |
| 51 | |
| 52 | is_warmup = tf.cast(global_steps_int < warmup_steps_int, tf.float32) |
| 53 | learning_rate = ( |
| 54 | (1.0 - is_warmup) * learning_rate + is_warmup * warmup_learning_rate) |
| 55 | |
| 56 | # It is recommended that you use this optimizer for fine tuning, since this |
| 57 | # is how the model was trained (note that the Adam m/v variables are NOT |
| 58 | # loaded from init_checkpoint.) |
| 59 | optimizer = AdamWeightDecayOptimizer( |
| 60 | learning_rate=learning_rate, |
| 61 | weight_decay_rate=0.01, |
| 62 | beta_1=0.9, |
| 63 | beta_2=0.999, |
| 64 | epsilon=1e-6, |
| 65 | exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"]) |
| 66 | |
| 67 | if use_tpu: |
| 68 | optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer) |
| 69 | |
| 70 | tvars = tf.trainable_variables() |
| 71 | grads = tf.gradients(loss, tvars) |
| 72 | |
| 73 | # This is how the model was pre-trained. |
| 74 | (grads, _) = tf.clip_by_global_norm(grads, clip_norm=1.0) |
| 75 | |
| 76 | train_op = optimizer.apply_gradients( |
| 77 | zip(grads, tvars), global_step=global_step) |
| 78 | |
| 79 | new_global_step = global_step + 1 |
| 80 | train_op = tf.group(train_op, [global_step.assign(new_global_step)]) |
| 81 | return train_op |
| 82 |
nothing calls this directly
no test coverage detected