Ray tune fail to start to run

Viewed 180

I just run a python script as is shown on https://docs.ray.io/en/latest/tune/tutorials/tune-pytorch-cifar.html

However, when runing the script, it seems that no change happened for a long time. When Interrupting it with ctrl+c, it shows below. I have no idea what have happened and what to do.

The script

from functools import partial
import numpy as np
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import random_split
import torchvision
import torchvision.transforms as transforms
from ray import tune
from ray.tune import CLIReporter
from ray.tune.schedulers import ASHAScheduler


def load_data(data_dir="./data"):
    transform = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
    ])

    trainset = torchvision.datasets.CIFAR10(
        root=data_dir, train=True, download=True, transform=transform)

    testset = torchvision.datasets.CIFAR10(
        root=data_dir, train=False, download=True, transform=transform)

    return trainset, testset

class Net(nn.Module):
    def __init__(self, l1=120, l2=84):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, l1)
        self.fc2 = nn.Linear(l1, l2)
        self.fc3 = nn.Linear(l2, 10)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

def train_cifar(config, checkpoint_dir=None, data_dir=None):
    net = Net(config["l1"], config["l2"])

    device = "cpu"
    if torch.cuda.is_available():
        device = "cuda:0"
        if torch.cuda.device_count() > 1:
            net = nn.DataParallel(net)
    net.to(device)

    criterion = nn.CrossEntropyLoss()
    optimizer = optim.SGD(net.parameters(), lr=config["lr"], momentum=0.9)

    if checkpoint_dir:
        model_state, optimizer_state = torch.load(
            os.path.join(checkpoint_dir, "checkpoint"))
        net.load_state_dict(model_state)
        optimizer.load_state_dict(optimizer_state)

    trainset, testset = load_data(data_dir)

    test_abs = int(len(trainset) * 0.8)
    train_subset, val_subset = random_split(
        trainset, [test_abs, len(trainset) - test_abs])

    trainloader = torch.utils.data.DataLoader(
        train_subset,
        batch_size=int(config["batch_size"]),
        shuffle=True,
        num_workers=8)
    valloader = torch.utils.data.DataLoader(
        val_subset,
        batch_size=int(config["batch_size"]),
        shuffle=True,
        num_workers=8)

    for epoch in range(10):  # loop over the dataset multiple times
        running_loss = 0.0
        epoch_steps = 0
        for i, data in enumerate(trainloader, 0):
            # get the inputs; data is a list of [inputs, labels]
            inputs, labels = data
            inputs, labels = inputs.to(device), labels.to(device)

            # zero the parameter gradients
            optimizer.zero_grad()

            # forward + backward + optimize
            outputs = net(inputs)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()

            # print statistics
            running_loss += loss.item()
            epoch_steps += 1
            if i % 2000 == 1999:  # print every 2000 mini-batches
                print("[%d, %5d] loss: %.3f" % (epoch + 1, i + 1,
                                                running_loss / epoch_steps))
                running_loss = 0.0

        # Validation loss
        val_loss = 0.0
        val_steps = 0
        total = 0
        correct = 0
        for i, data in enumerate(valloader, 0):
            with torch.no_grad():
                inputs, labels = data
                inputs, labels = inputs.to(device), labels.to(device)

                outputs = net(inputs)
                _, predicted = torch.max(outputs.data, 1)
                total += labels.size(0)
                correct += (predicted == labels).sum().item()

                loss = criterion(outputs, labels)
                val_loss += loss.cpu().numpy()
                val_steps += 1

        with tune.checkpoint_dir(epoch) as checkpoint_dir:
            path = os.path.join(checkpoint_dir, "checkpoint")
            torch.save((net.state_dict(), optimizer.state_dict()), path)

        tune.report(loss=(val_loss / val_steps), accuracy=correct / total)
    print("Finished Training")

def test_accuracy(net, device="cpu"):
    trainset, testset = load_data()

    testloader = torch.utils.data.DataLoader(
        testset, batch_size=4, shuffle=False, num_workers=2)

    correct = 0
    total = 0
    with torch.no_grad():
        for data in testloader:
            images, labels = data
            images, labels = images.to(device), labels.to(device)
            outputs = net(images)
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()

    return correct / total


def main(num_samples=10, max_num_epochs=10, gpus_per_trial=2):
    data_dir = os.path.abspath("./data")
    load_data(data_dir)
    config = {
        "l1": tune.sample_from(lambda _: 2 ** np.random.randint(2, 9)),
        "l2": tune.sample_from(lambda _: 2 ** np.random.randint(2, 9)),
        "lr": tune.loguniform(1e-4, 1e-1),
        "batch_size": tune.choice([2, 4, 8, 16])
    }
    scheduler = ASHAScheduler(
        metric="loss",
        mode="min",
        max_t=max_num_epochs,
        grace_period=1,
        reduction_factor=2)
    reporter = CLIReporter(
        # parameter_columns=["l1", "l2", "lr", "batch_size"],
        metric_columns=["loss", "accuracy", "training_iteration"])
    result = tune.run(
        partial(train_cifar, data_dir=data_dir),
        resources_per_trial={"cpu": 2, "gpu": gpus_per_trial},
        config=config,
        num_samples=num_samples,
        scheduler=scheduler,
        progress_reporter=reporter)

    best_trial = result.get_best_trial("loss", "min", "last")
    print("Best trial config: {}".format(best_trial.config))
    print("Best trial final validation loss: {}".format(
        best_trial.last_result["loss"]))
    print("Best trial final validation accuracy: {}".format(
        best_trial.last_result["accuracy"]))

    best_trained_model = Net(best_trial.config["l1"], best_trial.config["l2"])
    device = "cpu"
    if torch.cuda.is_available():
        device = "cuda:0"
        if gpus_per_trial > 1:
            best_trained_model = nn.DataParallel(best_trained_model)
    best_trained_model.to(device)

    best_checkpoint_dir = best_trial.checkpoint.value
    model_state, optimizer_state = torch.load(os.path.join(
        best_checkpoint_dir, "checkpoint"))
    best_trained_model.load_state_dict(model_state)

    test_acc = test_accuracy(best_trained_model, device)
    print("Best trial test set accuracy: {}".format(test_acc))


if __name__ == "__main__":
    # You can change the number of GPUs per trial here:
    main(num_samples=10, max_num_epochs=10, gpus_per_trial=0)

The Feedback

(ch36) ch@ICRC-Station:~/Ray$ python train.py
Files already downloaded and verified
Files already downloaded and verified
^CTraceback (most recent call last):
  File "train.py", line 207, in <module>
    main(num_samples=10, max_num_epochs=10, gpus_per_trial=0)
  File "train.py", line 179, in main
    scheduler=scheduler)
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/tune/tune.py", line 316, in run
    _ray_auto_init()
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/tune/tune.py", line 754, in _ray_auto_init
    ray.init()
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/_private/client_mode_hook.py", line 105, in wrapper
    return func(*args, **kwargs)
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/worker.py", line 912, in init
    ray_params=ray_params)
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/node.py", line 215, in __init__
    self.start_head_processes()
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/node.py", line 902, in start_head_processes
    self.start_redis()
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/node.py", line 717, in start_redis
    port_denylist=self._ray_params.reserved_ports)
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/_private/services.py", line 942, in start_redis
    listen_to_localhost_only=(node_ip_address == "127.0.0.1"))
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/_private/services.py", line 1097, in _start_redis_instance
    wait_for_redis_to_start("127.0.0.1", port, password=password)
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/_private/services.py", line 715, in wait_for_redis_to_start
    redis_client.client_list()
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/redis/commands/core.py", line 399, in client_list
    return self.execute_command('CLIENT LIST', *args)
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/redis/client.py", line 1068, in execute_command
    conn = self.connection or pool.get_connection(command_name, **options)
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/redis/connection.py", line 1173, in get_connection
    connection.connect()
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/redis/connection.py", line 567, in connect
    sock = self._connect()
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/redis/connection.py", line 613, in _connect
    sock.connect(socket_address)
KeyboardInterrupt

1 Answers

Then I wait for a longer time shown as below:

Traceback (most recent call last):
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/redis/connection.py", line 567, in connect
    sock = self._connect()
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/redis/connection.py", line 625, in _connect
    raise err
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/redis/connection.py", line 613, in _connect
    sock.connect(socket_address)
TimeoutError: [Errno 110] Connection timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/_private/services.py", line 715, in wait_for_redis_to_start
    redis_client.client_list()
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/redis/commands/core.py", line 399, in client_list
    return self.execute_command('CLIENT LIST', *args)
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/redis/client.py", line 1068, in execute_command
    conn = self.connection or pool.get_connection(command_name, **options)
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/redis/connection.py", line 1173, in get_connection
    connection.connect()
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/redis/connection.py", line 571, in connect
    raise ConnectionError(self._error_message(e))
redis.exceptions.ConnectionError: Error 110 connecting to 127.0.0.1:6379. Connection timed out.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "DeepCell_train_modify.py", line 803, in <module>
    progress_reporter=reporter)
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/tune/tune.py", line 316, in run
    _ray_auto_init()
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/tune/tune.py", line 754, in _ray_auto_init
    ray.init()
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/_private/client_mode_hook.py", line 105, in wrapper
    return func(*args, **kwargs)
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/worker.py", line 912, in init
    ray_params=ray_params)
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/node.py", line 215, in __init__
    self.start_head_processes()
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/node.py", line 902, in start_head_processes
    self.start_redis()
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/node.py", line 717, in start_redis
    port_denylist=self._ray_params.reserved_ports)
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/_private/services.py", line 942, in start_redis
    listen_to_localhost_only=(node_ip_address == "127.0.0.1"))
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/_private/services.py", line 1097, in _start_redis_instance
    wait_for_redis_to_start("127.0.0.1", port, password=password)
  File "/home/ch/anaconda3/envs/ch36/lib/python3.6/site-packages/ray/_private/services.py", line 737, in wait_for_redis_to_start
    " attempts to ping the Redis server.") from connEx
RuntimeError: Unable to connect to Redis at 127.0.0.1:6379 after 16 retries. Check that 127.0.0.1:6379 is reachable from this machine. If it is not, your firewall may be blocking this port. If the problem is a flaky connection, try setting the environment variable `RAY_START_REDIS_WAIT_RETRIES` to increase the number of attempts to ping the Redis server.

Clear that there is something wrong about network port.

Related