google-research
55 строк · 1.6 Кб
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 task_set.variable_replace."""
17
18import sonnet as snt
19
20from task_set import variable_replace
21import tensorflow.compat.v1 as tf
22
23
24class VaraibleReplaceTest(tf.test.TestCase):
25
26def test_variable_replace_getter(self):
27with self.test_session() as sess:
28context = variable_replace.VariableReplaceGetter()
29mod = snt.Linear(1, custom_getter=context)
30
31inp_data = tf.ones([10, 1])
32with context.use_variables():
33y1 = mod(inp_data)
34sess.run(tf.initialize_all_variables())
35np_y1 = sess.run(y1)
36
37values = context.get_variable_dict()
38
39new_values = {k: v + 1 for k, v in values.items()}
40
41with context.use_value_dict(new_values):
42np_y2 = mod(inp_data).eval()
43
44self.assertNear((np_y2 - np_y1)[0], 2, 1e-8)
45
46for v in values.values():
47v.assign(v + 1).eval()
48
49with context.use_variables():
50np_y3 = mod(inp_data).eval()
51self.assertNear((np_y3 - np_y2)[0], 0, 1e-8)
52
53
54if __name__ == '__main__':
55tf.test.main()
56