Skip to content

PyTorch Basic

In this guide, you will learn how to use PyTorch in a Jupyter notebook using Rafay's MLOps platform based on Kubeflow. You can think of PyTorch as a Python-based scientific computing package serving two broad purposes:

  • A replacement for NumPy to use the power of GPUs and other accelerators.
  • An automatic differentiation library that is useful to implement neural networks.

Tired of the complexities of installing PyTorch in Jupyter Notebook? Try Rafay's MLOps for free and to set up your data science environment effortlessly!


Launch Notebook

In this step, we will create and launch a Jupyter notebook with the PyTorch image.

  • Login into your Kubeflow workspace
  • Click on the Notebooks menu
  • Create New Notebook and provide a friendly name
  • For the Image, ensure you select either "jupyter-pytorch-full" or "jupyter-pytorch-cuda-full"
  • Use the defaults for everything else for now
  • Click on launch to start the notebook

New PyTorch Notebook

Note

Since we will be performing a very simple test, we will not requesting access to a GPU.

It can take a few minutes for the notebook to be ready (esp. if the container image has not been already downloaded and cached on the cluster). The image below shows what a successful notebook creation should look like.

Ready PyTorch Notebook


Connect to Notebook

Click on Connect to connect to your notebook. This will launch a new web browser tab and you will have access to the Launcher menu. To verify if PyTorch and related packages are preinstalled, you can type the following command in a cell and run. Alternatively, you can also type this in a Terminal in the notebook.

pip list | grep "torch"

This should print results similar to the one below

torch                         2.1.0+cpu
torchaudio                    2.1.0+cpu
torchvision                   0.16.0+cpu

Add PyTorch Code

In this guide, we will perform an extremely basic set of operations using PyTorch

  • Create a Tensor directly from data
  • Print the values of the Tensor

Note

Tensors are a specialized data structure that are very similar to arrays and matrices. In PyTorch, we use tensors to encode the inputs and outputs of a model, as well as the model’s parameters. Tensors are similar to NumPy’s ndarrays, except that tensors can run on GPUs or other specialized hardware to accelerate computing.

In your new notebook,

  • Click on "Python 3" notebook
  • Copy/paste the following code
import torch

data = [[1, 2], [3, 4]]
x_data = torch.tensor(data)

print(f"Data in Tensor: \n {x_data} \n")

Your notebook should print results like the example below.

PyTorch Results


Next Steps

By following these simple steps, you can start building and training machine learning models using PyTorch in a Jupyter Notebook. Here are some resources you can use to try advanced scenarios: