Connecting a Python notebook on Visual Studio Code to a GPU node
Introduction
You may be familiar with developing projects in the Visual Studio Code environment, but have started to wish that you had a more powerful machine with advanced GPUs on which to run your code... VCU has such machines available in the HPRC, and this page will help you to get started using your Jupyter notebook in VSCode to connect to a GPU node in the Athena cluster to do some work.
If you are familiar with the process of logging into a head node on a cluster, and submitting jobs from there, this process is somewhat related, but a bit more involved. There are several steps involved in the connection process, but first, you may want to start with some other basic steps to assure that you are ready to connect to the cluster in this fashion and do some work.
First, do the preliminary steps if you need to set up things to get started; you can use the Table of Contents above to skip to any part of the page that is new material for you.
Preliminary Steps
Check ssh
First, you will need to make sure that you can ssh to the Athena head node, that your Athena account is setup and things are working in it OK. If you don't have a Athena account yet, there is information on this page to help you to get your account created, and links to more information about using it.
With your Athena account created, make sure you can ssh to it and login. In the account creation process, you should have received information about using the VPN. If you have connected to that, use your favorite means to ssh to another machine, such as the PuTTY program, or the ssh command at a Windows PowerShell prompt, or in a Linux terminal, etc., to ssh to Athena.
If you are able to login and everything looks OK, then you are ready to proceed with the rest of this page's instructions.
Passwordless-ssh
If you haven't already gotten tired of having to enter your password a lot, you certainly will in the process of setting up VSCode to connect to a remote node on the cluster...! If you have never done this before, it may be a bit confusing, but the idea is to set up something called a public key to be used to let the remote host know that you are really you when you try to log in, so that it doesn't need to ask you for a password, it can just trust the keys that are set up. We will look at doing this under Windows as well as Linux, Apple users are hopefully able to follow the Linux instructions.
Linux:
On your local machine, first backup the contents of your .ssh directory, in case something may get overwritten that shouldn't... Then, run the following command at a command prompt:
ssh-keygen -t rsaThis actually generates two keys, that will be stored in your ~/.ssh/ directory. There are a lot of ways to setup these keys, for more information, you can explore https://www.ssh.com/academy/ssh/keygen for instance for much more information. If you look at the contents of your .ssh directory now, there should be 2 new files, id_rsa, and id_rsa.pub. The .pub file is the one that you will want to use to set up passwordless ssh-ing.
Now that the "public key" id_rsa.pub has been created, you will need to copy its contents to be used on the head node of Athena; first, output the file:
cat ~/.ssh/id_rsa.pubCopy that output.
In a terminal where you are logged into the Athena headnode, edit ~/.ssh/authorized_keys, paste that line from the id_rsa.pub on your local machine to a new line in ~/.ssh/authorized_keys on Athena.
Save the file and exit the editor.
Next time you ssh to Athena, you shouldn't need to enter a password!
To test it, simply log out and back in, or try a new log in from another terminal window.
Now, you want to do something similar so that you won't need to enter a password to use the tunnel to a GPU compute node that you will set up later in these instructions.
On the Athena head node, do the same thing with the file, ~/.ssh/id_rsa.pub (create it if there is none), edit the file and add a new line just like you did for the authorized_keys file, with the public key from your local machine.
Save and exit the file.
Now, you should be able to ssh and tunnel to the compute nodes, without having to enter a password!
Windows:
The process under Windows is actually pretty similar to setting up passwordless-ssh under Linux. Assuming, that is, that you have VSCode (discussed next section) running. You can do everything in a terminal inside of VSCode.
So, open VSCode, and then open a terminal (Terminal → New Terminal)
Enter the command
ssh-keygen -t rsasave in the default location given when asked.
Enter blank for passphrase when asked, enter blank again for passphrase when asked the second time. "Blank" means, just hit the enter key to accept an empty passphrase, the goal is passwordless!
Copy the saved key to the clipboard. For example, assuming the key was saved to "C:\Users\user\.ssh\id_rsa.pub", do
cat C:\Users\user\.ssh\id_rsa.pubCopy the output of this command.
ssh to the Athena head node.
Make a backup copy of your .ssh directory if you want, in case something goes wrong in this process.
Edit .ssh/authorized_keys, add a new line and paste the key; save the file and exit. This will let you login to the head node without entering a password.
Edit .ssh/id_rsa.pub, add a new line, and paste the key; save the file and exit. This will let you login to the compute nodes with no password.
Log out of the head node; next login, you won't need a password!
Now that you have done the setup under Linux or Windows to allow for passwordless SSH-ing to Athena, you can try the tunnel command if you have a Jupyter server running on a node holding a port open, and if you have the port number to use to make the connection with the ssh-command. This will be explored in sections below.
Prepare Visual Studio Code
If need be, install Visual Studio Code on your local machine which you are using to connect to Athena. The author of this page used visual-studio-code-bin (proprietary version), installed under Linux, for this tutorial, as well as the Windows version, under Windows of course. If you are running Linux, check to see what varieties of VSCode are available, in case you'd rather use a non-proprietary (open source) version, such as "code". The Windows version can be found here: get VSCode.
Once you have your desired flavor of VSCode installed, install the Remote-SSH extension if you haven't already. This can be done by clicking the "Extensions" icon (or hitting Ctrl+Shift+X) and then searching for "ssh". Choose "Remote-SSH" and click "install". Another way is to do "Quick Open" (Ctrl+P) and enter the command: "ext install ms-vscode-remote.remote-ssh".
Now you should test out a connection to the Athena head node again:
Hit 'F1' to enter a command and enter:
"Remote-SSH: Connect to Host"
Or look for it in the list of commands, it may say "Open SSH Host" or something else instead; lower-case is OK if typing this command.Enter your user name and the host to connect to in this fashion:
<username>@athena1.vcu.edu
and then enter your password when it is requested in the next window that pops up.You may see some messages about software that needs updating or other things, just ignore that while you're working through this tutorial if you like.
If all went well, you should have access to your Athena account, in the VSCode window, at this point! You can explore the options under the "Start" heading, to navigate your directories or open files.
When you are done, click the blue button in the lower left corner of the window, labeled "SSH: athena1.vcu.edu". In the options that pop up, choose "Close Remote Connection" to end the session on Athena.
Working with a Jupyter notebook in VSCode:
First, choose/enter "Create: New Jupyter Notebook" in the Command Palette (Ctrl+Shift+P), or do "File→New File..." and choose "Jupyter Notebook .ipynb support" from the drop-down that appears.
Choose a kernel by using the "kernel picker" in the upper right corner of the window, it says "Select Kernel".
There should now be a tab in the VSCode window labeled "Untitled-1.ipynb" or something similar. You can enter some simple code here in the "code cell" that is presented to try out:
2 days from now
from datetime import datetime from datetime import timedelta # print today's date print("Today is " + str(datetime.now()) + ".") # 2 days from now: print(str(2) + " days from now is " + \ str(datetime.now() + timedelta(days=2)))To run the code, click the little triangular "play" symbol to the upper left of the code cell. If everything goes well, there should be output similar to this:
Output of days from now code
Today is 2023-10-10 13:55:50.441737. 2 days from now is 2023-10-12 13:55:50.441794You can choose "File -> Save As" and other options from the menu system to save the code, the notebook, and so on. Likewise, you can also export to different formats (Python code, PDF, etc.).
Prepare your Athena account
Now that you have VSCode installed and have some experience with creating a notebook and running some code from a code cell in it, you also need to prepare you account on Athena to help you to connect VSCode to a GPU node. These steps will help you to install miniconda in your account on Athena so that you have a conda environment there to work with. This will help you to install software to your account (which will be very helpful if you wish to try the PyTorch example, below), and launch a Jupyter notebook server on a GPU node to connect to. So, to install miniconda please follow these steps, by entering the following commands once you're logged into your Athena account:
mkdir -p ~/miniconda3
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O ~/miniconda3/miniconda.sh
bash ~/miniconda3/miniconda.sh -b -u -p ~/miniconda3 (This step takes a while!)
rm -f miniconda3/miniconda.sh
Setup conda to interact with bash shell:
~/miniconda3/bin/conda init bash
For zsh shell:
~/miniconda3/bin/conda init zsh
and so on.
Create an environment if you need one, to contain the packages "python" and "jupyter", here it's called "test_env"; we'll use this environment to create and maintain the connection:
Create a conda environment
conda create -n test_env python jupyter
Now your account is finally ready to be connected to from your local machine, that's in the next section. Though the account is ready, there's still just a little more to do.
Connect to a GPU node on the Athena cluster
To make the connection from your local machine to the remote GPU node, you will need to get a URL for VSCode to use, to create a "tunnel" into the node. In your account on Athena, create a script like this (of course feel free to just copy and paste this one!):
This is using the conda environment after activating it to keep a Jupyter notebook server running for 2 hours. The commands in this script will run on the remote GPU node that the Slurm software chooses for the job. Save this say as "jupyter_lab.sh" and submit this as a Slurm job, for example with the command:
It may take several minutes for this to run; look for the output in the "*.e" file. You can enter this command to watch for the output you need, for this job with job ID 71047, the command would be like:
watch grep lab jupyter_lab.e71047When the "*.e" file has output, look for the line with the URL to use to connect to the GPU node:
There should be something like that in the output; the line of interest is line 9:
http://127.0.0.1:8888/lab?token=8a6eab885b3c8b4bca444b938a0539d3c43f87232fb570e7
Copy the line from your output to be pasted into VSCode in just a bit.
Now open a terminal in VSCode (Terminal → New Terminal), or use xterm, konsole, PowerShell, or whatever you like, and enter the following command (substitute your login ID for "<username>") to the GPU node:
You should now be logged into the GPU node (in this case, athena44) where the Slurm script is running! You can use the "top" command to check to make sure you see your Slurm and Python processes, and so on. You should see "jupyter-lab" running. In top, you can type "u" and then your username to show only your own processes.
Now that you have opened a tunnel to the node, you can finally connect to it from VSCode.
If need be, open a new Jupyter notebook: File → New File... → Jupyter Notebook
Then click the "kernel picker" on the upper right of the VSCode window labeled "Select Kernel".
In the drop-down that appears, choose "Select Another Kernel..."
Then choose "Existing Jupyter Server..."
Then choose "Enter the URL of the running Jupyter Server.."
Now paste the URL line from the job's output, and hit enter. In the example above, it was line 9 of the ".e" file. You will be given a chance to change the Server Display Name, and then hit enter. Now choose a kernel from the server, and you're all done. You should now be connected to your Jupyter server!
To test this, here is a simple example program to enter into a code cell (Shift+Enter):
Days from now example
from datetime import datetime from datetime import timedelta import socket # print today's date print("Today is " + str(datetime.now()) + ".") # 2 days from now: print(str(2) + " days from now is " + \ str(datetime.now() + timedelta(days=2))) print("I'm running on " + socket.gethostname())Here is a sample output, to show what to expect:
Output of Days From Now example
Today is 2023-10-10 13:55:50.441737. 2 days from now is 2023-10-12 13:55:50.441794 I'm running on athena44
A PyTorch Example – run PyTorch code on the GPU
Let's look at a more interesting example. Here PyTorch, the machine learning framework, will be used.
First, install PyTorch under your account using the conda environment once it's activated. From a login on Athena, run this command:
conda install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidiaWhen PyTorch is installed, you might want to test the PyTorch install, enter this in a code cell:
import torch
torch.cuda.is_available()which will print out "True" if CUDA libraries are available for the PyTorch software to use, "False" if not.
Here is a more meaningful example:
which will produce output like this:
If you like, you can monitor this from the terminal where you opened the tunnel from, with the command:
watch -n0.1 nvidia-smiHit Ctrl+C to get out of the watch command when you're done. You should see some of the data in the nvidia-smi output change as the GPU takes on the PyTorch code.
References and Examples
https://www.codeease.net/programming/python/use-gpu-for-python-code-in-vscode
Further help
https://research.vcu.edu/cores/hprc/
In case you are interested in learning more about CUDA development, here is a very useful link: https://developer.nvidia.com/blog/even-easier-introduction-cuda/.
And always feel free to read about the HPRC.Back to Top
Acknowledgement
If you benefit from HPRC resources, please consider adding the following acknowledgement to papers.
"High Performance Computing resources provided by the High Performance Research Computing (HPRC) core facility at Virginia Commonwealth University (https://hprc.vcu.edu ) were used for conducting the research reported in this work."