reductionista commented on a change in pull request #355: Keras fit interface URL: https://github.com/apache/madlib/pull/355#discussion_r267594780
########## File path: src/ports/postgres/modules/deep_learning/test/unit_tests/test_madlib_keras.py_in ########## @@ -0,0 +1,196 @@ +# coding=utf-8 +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import sys +import numpy as np +from os import path +# Add convex module to the pythonpath. +sys.path.append(path.dirname(path.dirname(path.dirname(path.dirname(path.abspath(__file__)))))) +sys.path.append(path.dirname(path.dirname(path.dirname(path.abspath(__file__))))) + +import keras +from keras.models import * +from keras.layers import * +import unittest +from mock import * +import plpy_mock as plpy +from keras.models import * +from keras.layers import * + +m4_changequote(`<!', `!>') + +class MadlibKerasFitTestCase(unittest.TestCase): + def setUp(self): + self.plpy_mock = Mock(spec='error') + patches = { + 'plpy': plpy + } + + self.plpy_mock_execute = MagicMock() + plpy.execute = self.plpy_mock_execute + + self.module_patcher = patch.dict('sys.modules', patches) + self.module_patcher.start() + import madlib_keras + self.subject = madlib_keras + + self.model = Sequential() + self.model.add(Conv2D(2, kernel_size=(1, 1), activation='relu', + input_shape=(1,1,1,), padding='same')) + self.model.add(Flatten()) + + self.compile_params = "'optimizer'=SGD(lr=0.01, decay=1e-6, nesterov=True), 'loss'='categorical_crossentropy', 'metrics'=['accuracy']" + self.fit_params = "'batch_size'=1, 'epochs'=1" + self.model_weights = [3,4,5,6] + self.model_shapes = [] + for a in self.model.get_weights(): + self.model_shapes.append(a.shape) + + self.loss = 1.3 + self.accuracy = 0.34 + self.all_seg_ids = [0,1,2] + self.total_buffers_per_seg = [3,3,3] + + def tearDown(self): + self.module_patcher.stop() + + def test_fit_transition_first_buffer_pass(self): + #TODO should we mock tensorflow's close_session and keras' + # clear_session instead of mocking the function `clear_keras_session` + self.subject.K.set_session = Mock() + self.subject.clear_keras_session = Mock() + buffer_count = 0 + previous_state = [self.loss, self.accuracy, buffer_count] + previous_state.extend(self.model_weights) + previous_state = np.array(previous_state, dtype=np.float32) + + k = {'SD': {'buffer_count': buffer_count}} + new_model_state = self.subject.fit_transition( + None, [[0.5]] , [0], 1, 2, self.all_seg_ids, self.total_buffers_per_seg, + self.model.to_json(), self.compile_params, self.fit_params, False, + previous_state.tostring(), **k) + buffer_count = np.fromstring(new_model_state, dtype=np.float32)[2] + self.assertEqual(1, buffer_count) + # set_session must get called ONLY once, when its the first buffer + self.assertEqual(1, self.subject.K.set_session.call_count) + # Clear session and sess.close must not get called for the first buffer + self.assertEqual(0, self.subject.clear_keras_session.call_count) + self.assertEqual(1, k['SD']['buffer_count']) + self.assertTrue(k['SD']['segment_model']) + self.assertTrue(k['SD']['model_shapes']) + + def test_fit_transition_last_buffer_pass(self): + #TODO should we mock tensorflow's close_session and keras' + # clear_session instead of mocking the function `clear_keras_session` + self.subject.K.set_session = Mock() + self.subject.clear_keras_session = Mock() + + buffer_count = 2 + + state = [self.loss, self.accuracy, buffer_count] + state.extend(self.model_weights) + state = np.array(state, dtype=np.float32) + + self.subject.compile_and_set_weights(self.model, self.compile_params, + '/cpu:0', state.tostring(), self.model_shapes) + k = {'SD': {'buffer_count': buffer_count, + 'model_shapes': self.model_shapes}} + k['SD']['segment_model'] = self.model + new_model_state = self.subject.fit_transition( + state.tostring(), [[0.5]] , [0], 1, 2, self.all_seg_ids, self.total_buffers_per_seg, + self.model.to_json(), None, self.fit_params, False, 'dummy_previous_state', **k) + + buffer_count = np.fromstring(new_model_state, dtype=np.float32)[2] + self.assertEqual(3, buffer_count) + # set_session must get called ONLY once, when its the first buffer + self.assertEqual(0, self.subject.K.set_session.call_count) + # Clear session and sess.close must not get called for the first buffer + self.assertEqual(1, self.subject.clear_keras_session.call_count) + self.assertEqual(3, k['SD']['buffer_count']) + + def test_fit_transition_middle_buffer_pass(self): + #TODO should we mock tensorflow's close_session and keras' + # clear_session instead of mocking the function `clear_keras_session` + self.subject.K.set_session = Mock() + self.subject.clear_keras_session = Mock() + + buffer_count = 1 + + state = [self.loss, self.accuracy, buffer_count] + state.extend(self.model_weights) + state = np.array(state, dtype=np.float32) + + self.subject.compile_and_set_weights(self.model, self.compile_params, + '/cpu:0', state.tostring(), self.model_shapes) + k = {'SD': {'buffer_count': buffer_count, + 'model_shapes': self.model_shapes}} + k['SD']['segment_model'] = self.model + new_model_state = self.subject.fit_transition( + state.tostring(), [[0.5]] , [0], 1, 2, self.all_seg_ids, self.total_buffers_per_seg, + self.model.to_json(), None, self.fit_params, False, 'dummy_previous_state', **k) + + buffer_count = np.fromstring(new_model_state, dtype=np.float32)[2] + self.assertEqual(2, buffer_count) + # set_session must get called ONLY once, when its the first buffer + self.assertEqual(0, self.subject.K.set_session.call_count) + # Clear session and sess.close must not get called for the first buffer + self.assertEqual(0, self.subject.clear_keras_session.call_count) + self.assertEqual(2, k['SD']['buffer_count']) + + def test_get_device_name_for_keras(self): + import os + self.assertEqual('/gpu:0', self.subject.get_device_name_for_keras(True, 1, 3)) Review comment: Let's add `self.assertEqual('1', os.environ["CUDA_VISIBLE_DEVICES"] )` here. This will test to make sure we're only exposing GPU1 to this segment (segment 1 out of 3). ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected] With regards, Apache Git Services
