<jupyter_start><jupyter_text>Convert existing PyTorch code to Ray AIRIf you already have working PyTorch code, you don't have to start from scratch to utilize the benefits of Ray AIR. Instead, you can continue to use your existing code and incrementally add Ray AIR components as needed.Some of the benefits you'll get by using Ray AIR with your existing PyTorch training code:- Easy distributed data-parallel training on a cluster- Automatic checkpointing/fault tolerance and result tracking- Parallel data preprocessing- Seamless integration with hyperparameter tuning- Scalable batch prediction- Scalable model servingThis tutorial will show you how to start with Ray AIR from your existing PyTorch training code. We will learn how to **distribute your training** and do **scalable batch prediction**.  The example codeThe example code we'll be using is that of the [PyTorch quickstart tutorial](https://pytorch.org/tutorials/beginner/basics/quickstart_tutorial.html). This code trains a neural network classifier on the FashionMNIST dataset.You can find the code we used for this tutorial [here on GitHub](https://github.com/pytorch/tutorials/blob/8dddccc4c69116ca724aa82bd5f4596ef7ad119c/beginner_source/basics/quickstart_tutorial.py).  UnmodifiedLet's start with the unmodified code from the example. A thorough explanation of the parts is given in the full tutorial - we'll just focus on the code here.We start with some imports:<jupyter_code>import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor<jupyter_output><empty_output><jupyter_text>Then we download the data:<jupyter_code># Download training data from open datasets.
training_data = datasets.FashionMNIST(
    root="data",
    train=True,
    download=True,
    transform=ToTensor(),
)

# Download test data from open datasets.
test_data = datasets.FashionMNIST(
    root="data",
    train=False,
    download=True,
    transform=ToTensor(),
)<jupyter_output>/Users/kai/.pyenv/versions/3.7.7/lib/python3.7/site-packages/torchvision/datasets/mnist.py:498: UserWarning: The given NumPy array is not writeable, and PyTorch does not support non-writeable tensors. This means you can write to the underlying (supposedly non-writeable) NumPy array using the tensor. You may want to copy the array to protect its data or make it writeable before converting it to a tensor. This type of warning will be suppressed for the rest of this program. (Triggered internally at  ../torch/csrc/utils/tensor_numpy.cpp:180.)
  return torch.from_numpy(parsed.astype(m[2], copy=False)).view(*s)<jupyter_text>We can now define the dataloaders:<jupyter_code>batch_size = 64

# Create data loaders.
train_dataloader = DataLoader(training_data, batch_size=batch_size)
test_dataloader = DataLoader(test_data, batch_size=batch_size)<jupyter_output><empty_output><jupyter_text>We can then define and instantiate the neural network:<jupyter_code># Get cpu or gpu device for training.
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using {device} device")

# Define model
class NeuralNetwork(nn.Module):
    def __init__(self):
        super(NeuralNetwork, self).__init__()
        self.flatten = nn.Flatten()
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(28*28, 512),
            nn.ReLU(),
            nn.Linear(512, 512),
            nn.ReLU(),
            nn.Linear(512, 10)
        )

    def forward(self, x):
        x = self.flatten(x)
        logits = self.linear_relu_stack(x)
        return logits

model = NeuralNetwork().to(device)
print(model)<jupyter_output>Using cpu device
NeuralNetwork(
  (flatten): Flatten(start_dim=1, end_dim=-1)
  (linear_relu_stack): Sequential(
    (0): Linear(in_features=784, out_features=512, bias=True)
    (1): ReLU()
    (2): Linear(in_features=512, out_features=512, bias=True)
    (3): ReLU()
    (4): Linear(in_features=512, out_features=10, bias=True)
  )
)<jupyter_text>Define our optimizer and loss:<jupyter_code>loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)<jupyter_output><empty_output><jupyter_text>And finally our training loop. Note that we renamed the function from `train` to `train_epoch` to avoid conflicts with the Ray Train module later (which is also called `train`):<jupyter_code>def train_epoch(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)
    model.train()
    for batch, (X, y) in enumerate(dataloader):
        X, y = X.to(device), y.to(device)

        # Compute prediction error
        pred = model(X)
        loss = loss_fn(pred, y)

        # Backpropagation
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if batch % 100 == 0:
            loss, current = loss.item(), batch * len(X)
            print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")<jupyter_output><empty_output><jupyter_text>And while we're at it, here is our validation loop (note that we sneaked in a `return test_loss` statement and also renamed the function):<jupyter_code>def test_epoch(dataloader, model, loss_fn):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    model.eval()
    test_loss, correct = 0, 0
    with torch.no_grad():
        for X, y in dataloader:
            X, y = X.to(device), y.to(device)
            pred = model(X)
            test_loss += loss_fn(pred, y).item()
            correct += (pred.argmax(1) == y).type(torch.float).sum().item()
    test_loss /= num_batches
    correct /= size
    print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
    return test_loss<jupyter_output><empty_output><jupyter_text>Now we can trigger training and save a model:<jupyter_code>epochs = 5
for t in range(epochs):
    print(f"Epoch {t+1}\n-------------------------------")
    train_epoch(train_dataloader, model, loss_fn, optimizer)
    test_epoch(test_dataloader, model, loss_fn)
print("Done!")
torch.save(model.state_dict(), "model.pth")
print("Saved PyTorch Model State to model.pth")<jupyter_output>Saved PyTorch Model State to model.pth<jupyter_text>We'll cover the rest of the tutorial (loading the model and doing batch prediction) later!  Introducing a wrapper function (no Ray AIR, yet!)The notebook-style from the tutorial is great for tutorials, but in your production code you probably wrapped the actual training logic in a function. So let's do this here, too.Note that we do not add or alter any code here (apart from variable definitions) - we just take the loose bits of code in the current tutorial and put them into one function.<jupyter_code>def train_func():
    batch_size = 64
    lr = 1e-3
    epochs = 5
    
    # Create data loaders.
    train_dataloader = DataLoader(training_data, batch_size=batch_size)
    test_dataloader = DataLoader(test_data, batch_size=batch_size)
    
    # Get cpu or gpu device for training.
    device = "cuda" if torch.cuda.is_available() else "cpu"
    print(f"Using {device} device")
    
    model = NeuralNetwork().to(device)
    print(model)
    
    loss_fn = nn.CrossEntropyLoss()
    optimizer = torch.optim.SGD(model.parameters(), lr=lr)
    
    for t in range(epochs):
        print(f"Epoch {t+1}\n-------------------------------")
        train_epoch(train_dataloader, model, loss_fn, optimizer)
        test_epoch(test_dataloader, model, loss_fn)

    print("Done!")<jupyter_output><empty_output><jupyter_text>Let's see it in action again:<jupyter_code>train_func()<jupyter_output>Using cpu device
NeuralNetwork(
  (flatten): Flatten(start_dim=1, end_dim=-1)
  (linear_relu_stack): Sequential(
    (0): Linear(in_features=784, out_features=512, bias=True)
    (1): ReLU()
    (2): Linear(in_features=512, out_features=512, bias=True)
    (3): ReLU()
    (4): Linear(in_features=512, out_features=10, bias=True)
  )
)
Epoch 1
-------------------------------
loss: 2.300660  [    0/60000]
loss: 2.296696  [ 6400/60000]
loss: 2.275931  [12800/60000]
loss: 2.269738  [19200/60000]
loss: 2.264045  [25600/60000]
loss: 2.234024  [32000/60000]
loss: 2.238547  [38400/60000]
loss: 2.209435  [44800/60000]
loss: 2.214618  [51200/60000]
loss: 2.185344  [57600/60000]
Test Error: 
 Accuracy: 41.6%, Avg loss: 2.178503 

Epoch 2
-------------------------------
loss: 2.183002  [    0/60000]
loss: 2.178075  [ 6400/60000]
loss: 2.126900  [12800/60000]
loss: 2.142223  [19200/60000]
loss: 2.095714  [25600/60000]
loss: 2.040030  [32000/60000]
loss: 2.066279  [38400/60000]
loss: 1.993092  [44800[...]<jupyter_text>The output should look very similar to the previous ouput.  Starting with Ray AIR: Distribute the trainingAs a first step, we want to distribute the training across multiple workers. For this we want to1. Use data-parallel training by sharding the training data2. Setup the model to communicate gradient updates across machines3. Report the results back to Ray Train.To facilitate this, we only need a few changes to the code:1. We import Ray Train:```pythonimport ray.train as train```2. We use a `config` dict to configure some hyperparameters (this is not strictly needed but good practice, especially if you want to o hyperparameter tuning later):```pythondef train_func(config: dict):    batch_size = config["batch_size"]    lr = config["lr"]    epochs = config["epochs"]```3. We dynamically adjust the worker batch size according to the number of workers:```python    batch_size_per_worker = batch_size // train.world_size()```4. We prepare the data loader for distributed data sharding:```python    train_dataloader = train.torch.prepare_data_loader(train_dataloader)    test_dataloader = train.torch.prepare_data_loader(test_dataloader)```5. We prepare the model for distributed gradient updates:```python    model = train.torch.prepare_model(model)```Note that `train.torch.prepare_model()` also automatically takes care of setting up devices (e.g. GPU training) - so we can get rid of those lines in our current code!6. We capture the validation loss and report it to Ray train:```python        test_loss = test(test_dataloader, model, loss_fn)        train.report(loss=test_loss)```7. In the `train_epoch()` and `test_epoch()` functions we divide the `size` by the world size:```python    size = len(dataloader.dataset) // train.world_size()   Divide by word size```8. In the `train_epoch()` function we can get rid of the device mapping. Ray Train does this for us:```python         We don't need this anymore! Ray Train does this automatically:         X, y = X.to(device), y.to(device) ```That's it - you need less than 10 lines of Ray Train-specific code and can otherwise continue to use your original code.Let's take a look at the resulting code. First the `train_epoch()` function (2 lines changed, and we also commented out the print statement):<jupyter_code>def train_epoch(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset) // train.world_size()  # Divide by word size
    model.train()
    for batch, (X, y) in enumerate(dataloader):
        # We don't need this anymore! Ray Train does this automatically:
        # X, y = X.to(device), y.to(device)  

        # Compute prediction error
        pred = model(X)
        loss = loss_fn(pred, y)

        # Backpropagation
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if batch % 100 == 0:
            loss, current = loss.item(), batch * len(X)
            # print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")<jupyter_output><empty_output><jupyter_text>Then the `test_epoch()` function (1 line changed, and we also commented out the print statement):<jupyter_code>def test_epoch(dataloader, model, loss_fn):
    size = len(dataloader.dataset) // train.world_size()  # Divide by word size
    num_batches = len(dataloader)
    model.eval()
    test_loss, correct = 0, 0
    with torch.no_grad():
        for X, y in dataloader:
            X, y = X.to(device), y.to(device)
            pred = model(X)
            test_loss += loss_fn(pred, y).item()
            correct += (pred.argmax(1) == y).type(torch.float).sum().item()
    test_loss /= num_batches
    correct /= size
    # print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
    return test_loss<jupyter_output><empty_output><jupyter_text>And lastly, the wrapping `train_func()` where we added 4 lines and modified 2 (apart from the config dict):<jupyter_code>import ray.train as train


def train_func(config: dict):
    batch_size = config["batch_size"]
    lr = config["lr"]
    epochs = config["epochs"]
    
    batch_size_per_worker = batch_size // train.world_size()
    
    # Create data loaders.
    train_dataloader = DataLoader(training_data, batch_size=batch_size_per_worker)
    test_dataloader = DataLoader(test_data, batch_size=batch_size_per_worker)
    
    train_dataloader = train.torch.prepare_data_loader(train_dataloader)
    test_dataloader = train.torch.prepare_data_loader(test_dataloader)
    
    model = NeuralNetwork()
    model = train.torch.prepare_model(model)
    
    loss_fn = nn.CrossEntropyLoss()
    optimizer = torch.optim.SGD(model.parameters(), lr=lr)
    
    for t in range(epochs):
        train_epoch(train_dataloader, model, loss_fn, optimizer)
        test_loss = test_epoch(test_dataloader, model, loss_fn)
        train.report(loss=test_loss)

    print("Done!")<jupyter_output><empty_output><jupyter_text>Now we'll use Ray Train's TorchTrainer to kick off the training. Note that we can set the hyperparmameters here! In the `scaling_config` we can also configure how many parallel workers to use and if we want to enable GPU training or not.<jupyter_code>from ray.train.torch import TorchTrainer


trainer = TorchTrainer(
    train_loop_per_worker=train_func,
    train_loop_config={"lr": 1e-3, "batch_size": 64, "epochs": 4},
    scaling_config={"num_workers": 2, "use_gpu": False},
)
result = trainer.fit()
print(f"Last result: {result.metrics}")<jupyter_output>2022-06-14 13:02:53,006	INFO services.py:1483 -- View the Ray dashboard at [1m[32mhttp://127.0.0.1:8265[39m[22m<jupyter_text>Great, this works! You're now training your model in parallel. You could now scale this up to more nodes and workers on your Ray cluster.But there are a few improvements we can make to the code in order to get the most of the system. For one, we should enable **checkpointing** to get access to the trained model afterwards. Additionally, we should optimize the **data loading** to take place within the workers.  Enabling checkpointing to retrieve the modelEnabling checkpointing is pretty easy - we just need to call the `train.save_checkpoint()` API and pass the model state to it:```python    train.save_checkpoint(epoch=t, model=model.module.state_dict())```Note that the `model.module` part is needed because the model gets wrapped in `torch.nn.DistributedDataParallel` by `train.torch.prepare_model`. Move the data loader to the training functionYou may have noticed a warning: `Warning: The actor TrainTrainable is very large (52 MiB). Check that its definition is not implicitly capturing a large array or other object in scope. Tip: use ray.put() to put large objects in the Ray object store.`.This is because we load the data outside the training function. Ray then serializes it to make it accessible to the remote tasks (that may get executed on a remote node!). This is not too bad with just 52 MB of data, but imagine this were a full image dataset - you wouldn't want to ship this around the cluster unnecessarily. Instead, you should move the dataset loading part into the `train_func()`. This will then download the data *to disk* once per machine and result in much more efficient data loading.The result looks like this:<jupyter_code>def load_data():
    # Download training data from open datasets.
    training_data = datasets.FashionMNIST(
        root="data",
        train=True,
        download=True,
        transform=ToTensor(),
    )

    # Download test data from open datasets.
    test_data = datasets.FashionMNIST(
        root="data",
        train=False,
        download=True,
        transform=ToTensor(),
    )
    return training_data, test_data


def train_func(config: dict):
    batch_size = config["batch_size"]
    lr = config["lr"]
    epochs = config["epochs"]
    
    batch_size_per_worker = batch_size // train.world_size()
    
    training_data, test_data = load_data()  # <- this is new!
    
    # Create data loaders.
    train_dataloader = DataLoader(training_data, batch_size=batch_size_per_worker)
    test_dataloader = DataLoader(test_data, batch_size=batch_size_per_worker)
    
    train_dataloader = train.torch.prepare_data_loader(train_dataloader)
    test_dataloader = train.torch.prepare_data_loader(test_dataloader)
    
    model = NeuralNetwork()
    model = train.torch.prepare_model(model)
    
    loss_fn = nn.CrossEntropyLoss()
    optimizer = torch.optim.SGD(model.parameters(), lr=lr)
    
    for t in range(epochs):
        train_epoch(train_dataloader, model, loss_fn, optimizer)
        test_loss = test_epoch(test_dataloader, model, loss_fn)
        train.save_checkpoint(epoch=t, model=model.module.state_dict())  # <- this is new!
        train.report(loss=test_loss)

    print("Done!")<jupyter_output><empty_output><jupyter_text>Let's train again:<jupyter_code>trainer = TorchTrainer(
    train_loop_per_worker=train_func,
    train_loop_config={"lr": 1e-3, "batch_size": 64, "epochs": 4},
    scaling_config={"num_workers": 2, "use_gpu": False},
)
result = trainer.fit()<jupyter_output><empty_output><jupyter_text>We can see our results here:<jupyter_code>print(f"Last result: {result.metrics}")
print(f"Checkpoint: {result.checkpoint}")<jupyter_output>Last result: {'loss': 1.2226136068629612, '_timestamp': 1655204673, '_time_this_iter_s': 9.941093921661377, '_training_iteration': 4, 'time_this_iter_s': 9.953102111816406, 'should_checkpoint': True, 'done': True, 'timesteps_total': None, 'episodes_total': None, 'training_iteration': 4, 'trial_id': 'a9dda_00000', 'experiment_id': '1f001dea6bd948c39235e589f07fcd8f', 'date': '2022-06-14_13-04-33', 'timestamp': 1655204673, 'time_total_s': 41.98633909225464, 'pid': 7485, 'hostname': 'Kais-MacBook-Pro.fritz.box', 'node_ip': '127.0.0.1', 'config': {}, 'time_since_restore': 41.98633909225464, 'timesteps_since_restore': 0, 'iterations_since_restore': 4, 'warmup_time': 0.0025289058685302734, 'experiment_tag': '0'}
Checkpoint: <ray.air.checkpoint.Checkpoint object at 0x1bd3cdcd0><jupyter_text>Loading the model for predictionYou may have noticed that we skipped one part of the original tutorial - loading the model and using it for inference. The original code looks like this (we've wrapped it in a function):<jupyter_code>def predict_from_model(model):
    classes = [
        "T-shirt/top",
        "Trouser",
        "Pullover",
        "Dress",
        "Coat",
        "Sandal",
        "Shirt",
        "Sneaker",
        "Bag",
        "Ankle boot",
    ]

    model.eval()
    x, y = test_data[0][0], test_data[0][1]
    with torch.no_grad():
        pred = model(x)
        predicted, actual = classes[pred[0].argmax(0)], classes[y]
        print(f'Predicted: "{predicted}", Actual: "{actual}"')<jupyter_output><empty_output><jupyter_text>We can use our saved model with the existing code to do prediction:<jupyter_code>from ray.train.torch import load_checkpoint

model, _ = load_checkpoint(result.checkpoint, NeuralNetwork())

predict_from_model(model)<jupyter_output>Predicted: "Ankle boot", Actual: "Ankle boot"<jupyter_text>To predict more than one example, we can use a loop:<jupyter_code>classes = [
    "T-shirt/top",
    "Trouser",
    "Pullover",
    "Dress",
    "Coat",
    "Sandal",
    "Shirt",
    "Sneaker",
    "Bag",
    "Ankle boot",
]

def predict_from_model(model, data):
    model.eval()
    with torch.no_grad():
        for x, y in data:
            pred = model(x)
            predicted, actual = classes[pred[0].argmax(0)], classes[y]
            print(f'Predicted: "{predicted}", Actual: "{actual}"')

predict_from_model(model, [test_data[i] for i in range(10)])<jupyter_output>Predicted: "Ankle boot", Actual: "Ankle boot"
Predicted: "Pullover", Actual: "Pullover"
Predicted: "Trouser", Actual: "Trouser"
Predicted: "Trouser", Actual: "Trouser"
Predicted: "Pullover", Actual: "Shirt"
Predicted: "Trouser", Actual: "Trouser"
Predicted: "Coat", Actual: "Coat"
Predicted: "Coat", Actual: "Shirt"
Predicted: "Sneaker", Actual: "Sandal"
Predicted: "Sneaker", Actual: "Sneaker"<jupyter_text>Using Ray AIR for scalable batch predictionHowever, we can also use Ray AIRs `BatchPredictor` class to do scalable prediction.<jupyter_code>from ray.air import BatchPredictor
from ray.air.predictors.integrations.torch import TorchPredictor

batch_predictor = BatchPredictor.from_checkpoint(result.checkpoint, TorchPredictor, model=NeuralNetwork())<jupyter_output><empty_output><jupyter_text>Batch predictors work with Ray Datasets. Here we convert our test dataset into a Ray Dataset - note that this is not very efficient, and you can look at our {ref}`other tutorials ` to see more efficient ways to generate a Ray Dataset.<jupyter_code>import ray.data

ds = ray.data.from_items([x for x, y in test_data])<jupyter_output><empty_output><jupyter_text>We can then trigger prediction with two workers:<jupyter_code>results = batch_predictor.predict(ds, min_scoring_workers=2)<jupyter_output>Map Progress (2 actors 1 pending): 100%|██████████████████████████████████████████████████████████████████████████| 200/200 [00:04<00:00, 44.83it/s]<jupyter_text>`results` is another Ray Dataset. We can use `results.to_pandas()` to see our prediction results:<jupyter_code>results.to_pandas()<jupyter_output><empty_output><jupyter_text>If we want to convert these predictions into class names (as in the original example), we can use a `map` function to do this:<jupyter_code>predicted_classes = results.map_batches(
    lambda batch: [classes[pred.argmax(0)] for pred in batch["predictions"]], 
    batch_format="pandas")<jupyter_output>Map_Batches: 100%|███████████████████████████████████████████████████████████████████████████████████████████████| 200/200 [00:01<00:00, 117.68it/s]<jupyter_text>To compare this with the actual labels, let's create a Ray dataset for these and zip it together with the predicted classes:<jupyter_code>real_classes = ray.data.from_items([classes[y] for x, y in test_data])
merged = predicted_classes.zip(real_classes)<jupyter_output><empty_output><jupyter_text>Let's examine our results:<jupyter_code>merged.to_pandas()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11931617906238985, 'fraction_numerical': 0.03317765244977088, 'mean_word_length': 4.274692075296305, 'pattern_counts': {'":': 10, '<': 104, '<?xml version=': 0, '>': 110, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '27', 'dir': 'jupyter-structured-clean-dedup', 'id': '607882', 'license': 'Apache-2.0', 'n_tokens_mistral': 7996, 'n_tokens_neox': 7369, 'n_words': 2132, 'path': 'doc/source/ray-air/examples/convert_existing_pytorch_code_to_ray_air.ipynb', 'repo_name': 'jianoaix/ray', 'size': '22696'}