google-research
51 строка · 1.7 Кб
1# coding=utf-8
2# Copyright 2024 The Google Research 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
16"""Tests for optimization."""
17
18from __future__ import absolute_import19from __future__ import division20from __future__ import print_function21
22import tensorflow.compat.v1 as tf23from mobilebert import optimization24
25
26class OptimizationTest(tf.test.TestCase):27
28def test_adam(self):29with self.test_session() as sess:30w = tf.get_variable(31"w",32shape=[3],33initializer=tf.constant_initializer([0.1, -0.2, -0.1]))34x = tf.constant([0.4, 0.2, -0.5])35loss = tf.reduce_mean(tf.square(x - w))36tvars = tf.trainable_variables()37grads = tf.gradients(loss, tvars)38global_step = tf.train.get_or_create_global_step()39optimizer = optimization.AdamWeightDecayOptimizer(learning_rate=0.2)40train_op = optimizer.apply_gradients(zip(grads, tvars), global_step)41init_op = tf.group(tf.global_variables_initializer(),42tf.local_variables_initializer())43sess.run(init_op)44for _ in range(100):45sess.run(train_op)46w_np = sess.run(w)47self.assertAllClose(w_np.flat, [0.4, 0.2, -0.5], rtol=1e-2, atol=1e-2)48
49
50if __name__ == "__main__":51tf.test.main()52