Exemple #1
0
 def test_log_metric(self):
     submarine.log_metric("name_1", 5)
     submarine.log_metric("name_1", 6)
     # Validate params
     with self.store.ManagedSessionMaker() as session:
         metrics = session.query(SqlMetric).options().filter(
             SqlMetric.id == JOB_ID).all()
         assert len(metrics) == 2
         assert metrics[0].key == "name_1"
         assert metrics[0].value == 5
         assert metrics[0].id == JOB_ID
         assert metrics[1].value == 6
 def test_log_metric(self):
     submarine.log_metric("name_1", 5, "worker-1")
     submarine.log_metric("name_1", 6, "worker-2")
     # Validate params
     with self.store.ManagedSessionMaker() as session:
         metrics = session \
             .query(SqlMetric) \
             .options() \
             .filter(SqlMetric.job_name == JOB_NAME).all()
         assert len(metrics) == 2
         assert metrics[0].key == "name_1"
         assert metrics[0].value == 5
         assert metrics[0].worker_index == "worker-1"
         assert metrics[0].job_name == JOB_NAME
         assert metrics[1].value == 6
         assert metrics[1].worker_index == "worker-2"
def train(args, model, device, train_loader, optimizer, epoch, writer):
    model.train()
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(device), target.to(device)
        optimizer.zero_grad()
        output = model(data)
        loss = F.nll_loss(output, target)
        loss.backward()
        optimizer.step()
        if batch_idx % args.log_interval == 0:
            print("Train Epoch: {} [{}/{} ({:.0f}%)]\tloss={:.4f}".format(
                epoch,
                batch_idx * len(data),
                len(train_loader.dataset),
                100.0 * batch_idx / len(train_loader),
                loss.item(),
            ))
            niter = epoch * len(train_loader) + batch_idx
            writer.add_scalar("loss", loss.item(), niter)
            submarine.log_metric("loss", loss.item(), niter)
def test_log_metric(tracking_uri_mock):
    environ["SUBMARINE_JOB_NAME"] = JOB_NAME
    submarine.log_metric("name_1", 5, "worker-1")
    submarine.log_metric("name_1", 6, "worker-2")

    tracking_uri = utils.get_tracking_uri()
    store = utils.get_sqlalchemy_store(tracking_uri)

    # Validate params
    with store.ManagedSessionMaker() as session:
        metrics = session \
            .query(SqlMetric) \
            .options() \
            .filter(SqlMetric.job_name == JOB_NAME).all()
        assert len(metrics) == 2
        assert metrics[0].key == "name_1"
        assert metrics[0].value == 5
        assert metrics[0].worker_index == "worker-1"
        assert metrics[0].job_name == JOB_NAME
        assert metrics[1].value == 6
        assert metrics[1].worker_index == "worker-2"
def test(args, model, device, test_loader, writer, epoch):
    model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            output = model(data)
            test_loss += F.nll_loss(
                output, target, reduction="sum").item()  # sum up batch loss
            pred = output.max(
                1, keepdim=True)[1]  # get the index of the max log-probability
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)
    print("\naccuracy={:.4f}\n".format(
        float(correct) / len(test_loader.dataset)))
    writer.add_scalar("accuracy",
                      float(correct) / len(test_loader.dataset), epoch)
    submarine.log_metric("accuracy",
                         float(correct) / len(test_loader.dataset), epoch)
Exemple #6
0
# 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 numpy as np
from os import environ
from sklearn.linear_model import LogisticRegression
import submarine

if __name__ == "__main__":
    # note: SUBMARINE_JOB_NAME should be set by submarine submitter
    environ["SUBMARINE_JOB_NAME"] = "application_1234"
    X = np.array([-2, -1, 0, 1, 2, 1]).reshape(-1, 1)
    y = np.array([0, 0, 1, 1, 1, 0])
    lr = LogisticRegression(solver='liblinear', max_iter=100)
    submarine.log_param("max_iter", 100, "worker-1")
    lr.fit(X, y)
    score = lr.score(X, y)
    print("Score: %s" % score)
    submarine.log_metric("score", score, "worker-1")
Exemple #7
0
"""
 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 random
import time

import submarine

if __name__ == "__main__":
    submarine.log_param("learning_rate", random.random())
    for i in range(100):
        time.sleep(1)
        submarine.log_metric("mse", random.random() * 100, i)
        submarine.log_metric("acc", random.random(), i)
Exemple #8
0
working_dir = "/tmp/my_working_dir"
log_dir = os.path.join(working_dir, "log")
ckpt_filepath = os.path.join(working_dir, "ckpt")
backup_dir = os.path.join(working_dir, "backup")

callbacks = [
    tf.keras.callbacks.TensorBoard(log_dir=log_dir),
    tf.keras.callbacks.ModelCheckpoint(filepath=ckpt_filepath),
    tf.keras.callbacks.experimental.BackupAndRestore(backup_dir=backup_dir),
]

# Define the checkpoint directory to store the checkpoints.
checkpoint_dir = "./training_checkpoints"

model.fit(dc, epochs=5, steps_per_epoch=20, callbacks=callbacks)
if __name__ == "__main__":
    EPOCHS = 5
    hist = model.fit(dc,
                     epochs=EPOCHS,
                     steps_per_epoch=20,
                     callbacks=callbacks)
    for i in range(EPOCHS):
        submarine.log_metric("val_loss", hist.history["loss"][i], i)
        submarine.log_metric("Val_accuracy", hist.history["accuracy"][i], i)
    model.load_weights(tf.train.latest_checkpoint(checkpoint_dir))
"""
Reference:
https://www.tensorflow.org/tutorials/distribute/parameter_server_training
"""
Exemple #9
0
# 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 numpy as np
from sklearn.linear_model import LogisticRegression

import submarine

if __name__ == "__main__":
    X = np.array([-2, -1, 0, 1, 2, 1]).reshape(-1, 1)
    y = np.array([0, 0, 1, 1, 1, 0])
    lr = LogisticRegression(solver="liblinear", max_iter=100)
    submarine.log_param("max_iter", 100)
    lr.fit(X, y)
    score = lr.score(X, y)
    print("Score: %s" % score)
    submarine.log_metric("score", score)
Exemple #10
0
 def on_epoch_end(self, epoch, logs=None):
     # monitor the loss and accuracy
     print(logs)
     submarine.log_metric("loss", logs["loss"], epoch)
     submarine.log_metric("accuracy", logs["accuracy"], epoch)
 def on_epoch_end(self, epoch, logs=None):
     print("\nLearning rate for epoch {} is {}".format(
         epoch + 1, model.optimizer.lr.numpy()))
     submarine.log_metric("lr", model.optimizer.lr.numpy())
     submarine.save_model(model, "tensorflow", "mnist-tf")
Exemple #12
0
    submarine.set_tracking_uri(
        "mysql+pymysql://submarine:password@submarine-database/submarine")

    print("TF_CONFIG", env.get_env("TF_CONFIG"))
    print("JOB_NAME: ", env.get_env("JOB_NAME"))
    print("TYPE: ", env.get_env("TPYE"))
    print("TASK_INDEX: ", env.get_env("TASK_INDEX"))
    print("CLUSTER_SPEC: ", env.get_env("CLUSTER_SPEC"))
    print("RANK: ", env.get_env("RANK"))

    submarine.log_param("max_iter", 100)
    submarine.log_param("learning_rate", 0.0001)
    submarine.log_param("alpha", 20)
    submarine.log_param("batch_size", 256)

    submarine.log_metric("score", 2)
    submarine.log_metric("score", 5)
    submarine.log_metric("score", 8)
    submarine.log_metric("score", 5)
    submarine.log_metric("score", 10)

    submarine.log_metric("AUC", 0.62)
    submarine.log_metric("AUC", 0.68)
    submarine.log_metric("AUC", 0.75)
    submarine.log_metric("AUC", 0.64)
    submarine.log_metric("AUC", 0.79)
    submarine.log_metric("AUC", 0.86)

    submarine.log_metric("loss", 0.50)
    submarine.log_metric("loss", 0.36)
    submarine.log_metric("loss", 0.68)