Scholar Cluster Setup Guide for CS373¶

📋 Overview¶

This guide will help you set up and use Purdue's Scholar cluster for CS373 assignments. The Scholar cluster provides access to high-performance GPUs and computing resources that you'll need for deep learning tasks.

By the end of this tutorial, you will:

  • Have a working Python environment on Scholar
  • Know how to submit and manage jobs
  • Be able to transfer files to/from the cluster
  • Understand best practices for cluster usage

🖥️ System Requirements¶

Software Requirements¶

  • Python 3.11
  • Anaconda (with numpy 1.26+)
  • PyTorch 2.1.2+ (for deep learning assignments)

Hardware Options¶

Option 1: Scholar Cluster (Recommended)¶

✅ We strongly recommend using the Scholar cluster - you should already have access as an enrolled student.

Option 2: Personal Machine (Optional)¶

If you choose to use your own machine, ensure it meets these specifications:

  • 4-core, 8-thread processor minimum
  • SSD with at least 10GB free space
  • NVIDIA GPU with at least 4GB VRAM (Pascal, Volta, Turing, Ampere, Hopper, or Lovelace architecture)
  • ⚠️ AMD and Intel GPUs are not supported in the course. Some AMD GPUs can be made to work with pytorch

🚀 Getting Started with Scholar¶

Step 1: Initial Access¶

Connect to the cluster via SSH:

ssh your_username@scholar.rcac.purdue.edu

Authentication Details:

  • Password format: PIN,DUO_PASSKEY (your PIN followed by comma and current Duo Pass Key)
    • You can also use PIN,push (if your Duo allows push notifications)
  • Example: If your PIN is 1234 and BoilerKey shows 567890, enter: 1234,567890
  • The system will show: Password: (PIN),(DUO_PASSKEY)

Alternatives to SSH (not recommended)

  1. Go to https://www.rcac.purdue.edu/compute/scholar
  2. Click on the "Launch" button under "Gateway", and log in
  3. On the top bar, open the "Clusters" dropdown and click "Scholar Shell Access" which will open a terminal in a new tab

Step 2: Check Your Access¶

Once logged in, verify your available queues:

slist

You should see output similar to this:

                      Current Number of Cores                       Node
Account           Total    Queue     Run    Free    Max Walltime    Type
==============  =================================  ==============  ======
debug                20        0       0      20        00:30:00     A,G
gpu                  64        0       0      64        04:00:00       G
long                100        0       0     100      3-00:00:00       A
scholar             424        3       0     424        04:00:00     A,G

Note: A = CPU nodes, G = GPU nodes


⚙️ Environment Setup¶

Step 3: Create Your Conda Environment¶

Important: Make sure you're on a GPU-enabled frontend (scholar-fe04, scholar-fe05, or scholar-fe06) for GPU setup.

# Load the Anaconda module
module load conda/2024.09

# Create a new environment for this class
conda create -n CS373 python=3.11 ipython ipykernel

Step 4: Install Essential Libraries¶

# Activate your new environment
conda activate CS373

# Install basic data science libraries
pip install matplotlib scikit-learn pandas numpy

Verify your environment is active: You should see (CS373) at the beginning of your command prompt.

Step 5: Install PyTorch with CUDA Support¶

# Make sure CS373 environment is activated
source activate CS373

# Install PyTorch with CUDA 12.1 support
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu128

⚠️ Troubleshooting: If conda installation fails, run conda clean --all and restart from Step 3.

Step 6: Set Up Jupyter Integration¶

# Add your environment to Jupyter
ipython kernel install --user --name CS373 --display-name "Python [CS373]"

Expected output:

Installed kernelspec CS373 in /home/your_username/.local/share/jupyter/kernels/CS373

📓 Using Jupyter Notebooks¶

Web Interface Access¶

  1. Navigate to: https://scholar.rcac.purdue.edu
  2. Click: "Launch Jupyter Hub"
  3. Log in with your standard Purdue password (not BoilerKey)
  4. Create a new notebook and select "Python [CS373]" as your kernel

Interface Overview¶

When you open Jupyter Hub, you'll see tabs for:

  • Upload: Upload files from your computer
  • New: Create new notebooks or text files
  • File browser: Navigate your Scholar home directory

⚠️ Important Limitation: Jupyter Hub cannot be used for parallel processing assignments - use batch jobs instead.


🔄 File Transfer Methods¶

Method 1: Jupyter Hub Interface¶

  • Use the "Upload" button in the Jupyter interface for individual files
  • Drag and drop files directly into the file browser
  • Download files by right-clicking and selecting "Download"

Method 2: Command Line Tools¶

For Linux/Mac:

# Copy single file to cluster
scp local_file.py username@scholar.rcac.purdue.edu:~/

# Copy directory to cluster
scp -r local_directory/ username@scholar.rcac.purdue.edu:~/

# Copy file from cluster to local machine
scp username@scholar.rcac.purdue.edu:~/remote_file.py ./

For Windows:

  • Use WinSCP (GUI tool)
  • Or other tools recommended by RCAC

🎯 Running Jobs on the Cluster¶

Understanding the System¶

Frontend Nodes: Where you log in - use only for light tasks and job submission Backend Nodes: Where your actual computations run - accessed via job submission

⚠️ CRITICAL RULE: Never run resource-intensive code directly on frontend nodes - your process will be killed and you may be temporarily banned!

Example 1: Basic Python Script¶

Create a file called iris_example.py in your home directory:

In [1]:
# iris_example.py
# Required for cluster plotting (must be first!)
from matplotlib import use
use('Agg')
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
import numpy as np

print("Starting iris analysis...")

# Load iris dataset
data = load_iris()
X, y = data.data, data.target

print(f"Dataset shape: {X.shape}")
print(f"Classes: {data.target_names}")

# Create scatter plot
plt.figure(figsize=(10, 6))
colors = ['red', 'blue', 'green']

for value, name in enumerate(data.target_names):
    rows = (y == value)
    plt.scatter(X[rows, 2], X[rows, 3], 
                c=colors[value], label=name, alpha=0.7)

plt.title("Petal measurements for flowers in the Iris dataset", fontsize=14)
plt.xlabel(data.feature_names[2], fontsize=12)
plt.ylabel(data.feature_names[3], fontsize=12)
plt.legend()
plt.grid(True, alpha=0.3)

# Save plot
plt.savefig("iris_plot.png", dpi=300, bbox_inches='tight')
print("Plot saved as iris_plot.png")

# Print some statistics
print("\nDataset Statistics:")
for i, feature in enumerate(data.feature_names):
    print(f"{feature}: mean={X[:,i].mean():.2f}, std={X[:,i].std():.2f}")

print("Analysis complete!")
Starting iris analysis...
Dataset shape: (150, 4)
Classes: ['setosa' 'versicolor' 'virginica']
Plot saved as iris_plot.png

Dataset Statistics:
sepal length (cm): mean=5.84, std=0.83
sepal width (cm): mean=3.06, std=0.43
petal length (cm): mean=3.76, std=1.76
petal width (cm): mean=1.20, std=0.76
Analysis complete!

Example 2: Job Submission Scripts¶

For CPU-only jobs (cpu_job.sh):¶

In [2]:
#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=4
#SBATCH --time=30:00
#SBATCH --job-name=IrisCPU
#SBATCH --output=IrisCPU_%j.out
#SBATCH --error=IrisCPU_%j.err

echo "Job started at: $(date)"
echo "Running on node: $(hostname)"
echo "Job ID: $SLURM_JOB_ID"

# Load environment
module load conda/2024.09
source activate CS373

echo "Environment loaded successfully"
echo "Python version: $(python --version)"

# Run your code
python3 ~/iris_example.py

echo "Job completed at: $(date)"
  Cell In[2], line 9
    echo "Job started at: $(date)"
         ^
SyntaxError: invalid syntax

For GPU jobs (gpu_job.sh):¶

In [ ]:
#!/bin/bash
#SBATCH -A gpu
#SBATCH --nodes=1
#SBATCH --gres=gpu:1
#SBATCH --cpus-per-task=4
#SBATCH --time=30:00
#SBATCH --job-name=IrisGPU
#SBATCH --output=IrisGPU_%j.out
#SBATCH --error=IrisGPU_%j.err

echo "Job started at: $(date)"
echo "Running on node: $(hostname)"
echo "Job ID: $SLURM_JOB_ID"
echo "GPU assigned: $CUDA_VISIBLE_DEVICES"

# Load environment
module load conda/2024.09
source activate CS373

echo "Environment loaded successfully"
echo "Python version: $(python --version)"

# Check GPU availability
python3 -c "import torch; print(f'CUDA available: {torch.cuda.is_available()}'); print(f'GPU device: {torch.cuda.get_device_name(0) if torch.cuda.is_available() else "None"}')"

# Run your code
python3 ~/iris_example.py

echo "Job completed at: $(date)"

Job Submission and Management Commands¶

# Submit your job
sbatch cpu_job.sh
# Output: Submitted batch job 12345678

# Check job status
squeue -u your_username

# Check specific job details
scontrol show job 12345678

# View job output while it's running
tail -f IrisCPU_12345678.out

# Cancel a specific job
scancel 12345678

# Cancel all your jobs
scancel -u your_username

# Cancel all pending jobs
scancel -t PENDING -u your_username

🔧 Advanced Features¶

Interactive Jobs¶

For development and debugging, request an interactive session:

# Request interactive CPU session (4 hours max)
sinteractive -A scholar --time=2:00:00

# Request interactive GPU session (4 hours max)
sinteractive -A gpu --gres=gpu:1 --time=2:00:00

# Quick debug session (30 minutes max)
sinteractive -A debug --time=15:00

When to use interactive jobs:

  • Debugging code that fails in batch jobs
  • Testing new libraries or installations
  • Exploring data interactively
  • Short development sessions

Available Queues Reference¶

Queue Max Time GPU Access CPU Cores Best For Priority
debug 30 minutes Yes 20 Quick testing High
scholar 4 hours Yes 424 Most assignments Medium
gpu 4 hours Yes 64 GPU-specific tasks Medium
long 72 hours No 100 Extended CPU jobs Low

Queue Selection Tips:

  • Use debug for quick tests (< 30 minutes)
  • Use gpu when you specifically need GPU resources
  • Use scholar for most coursework
  • Use long only for jobs that truly need > 4 hours

🆘 Troubleshooting¶

Common Issues and Solutions¶

Issue: "conda: command not found"¶

Solution: Load the anaconda module first

module load conda/2024.09

Issue: Job killed immediately¶

Possible causes:

  • Running on frontend (use job submission instead)
  • Requesting too many resources
  • Syntax error in submission script

Solution: Check job output files (.out and .err)

Issue: "No space left on device"¶

Solutions:

# Clean conda cache
conda clean --all

# Check your disk usage
du -sh ~/*

# Remove unnecessary files
rm -rf ~/.cache/

Issue: "Permission denied" for job script¶

Solution: Make script executable

chmod +x your_job_script.sh

Issue: Can't activate conda environment¶

Solutions:

# Try conda activate instead of source activate
conda activate CS373

# Or initialize conda first
conda init bash
# Then logout and log back in

Getting Help¶

Follow this hierarchy:

  1. First: Check this guide and try common solutions
  2. Second: Ask your TA or post on course forum
  3. Third: Ask your instructor
  4. Last resort: Contact ITaP support at rcac-help@purdue.edu

When asking for help, include:

  • Exact error message
  • Commands you ran
  • Contents of .out and .err files
  • Your job submission script

✅ Quick Verification Test¶

Run this verification script to test your setup:

In [ ]:
# Save this as test_setup.py and run on Scholar
import sys
import torch
import matplotlib
import sklearn
import numpy as np
import pandas as pd

print("🔍 CS373 Environment Verification")
print("=" * 40)

# Python version
print(f"✅ Python version: {sys.version.split()[0]}")

# Package versions
print(f"✅ NumPy version: {np.__version__}")
print(f"✅ PyTorch version: {torch.__version__}")
print(f"✅ Scikit-learn version: {sklearn.__version__}")
print(f"✅ Matplotlib version: {matplotlib.__version__}")
print(f"✅ Pandas version: {pd.__version__}")

# CUDA availability
print(f"\n🖥️ CUDA available: {torch.cuda.is_available()}")
if torch.cuda.is_available():
    print(f"🎮 GPU device: {torch.cuda.get_device_name(0)}")
    print(f"💾 GPU memory: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB")
else:
    print("ℹ️ Running on CPU (this is normal for CPU jobs)")

# Test basic operations
try:
    # NumPy test
    arr = np.random.randn(100)
    print(f"\n🧮 NumPy test: array mean = {arr.mean():.3f}")
    
    # PyTorch test
    tensor = torch.randn(10, 10)
    print(f"🔥 PyTorch test: tensor shape = {tensor.shape}")
    
    print("\n🎉 All packages imported and tested successfully!")
    print("🚀 Your Scholar environment is ready for CS373!")
    
except Exception as e:
    print(f"❌ Error during testing: {e}")
    print("Please check your environment setup.")

To run the verification:

# SSH to Scholar
ssh your_username@scholar.rcac.purdue.edu

# Load environment
module load conda/2024.09
source activate CS373

# Run verification
python3 test_setup.py

📚 Additional Resources¶

Python Learning Resources¶

  • Course Python Tutorial - CS373-specific tutorial
  • Interactive Python Tutorial - Learn by doing
  • Official Python Tutorial - Comprehensive reference
  • Pandas Documentation - Data manipulation

Scholar Cluster Documentation¶

  • Scholar User Guide - Official documentation
  • Job Examples - SLURM script examples
  • Queue Information - Detailed queue specs
  • RCAC Help - General support

Alternative Computing Options¶

Google Colab (Optional)¶

  • Access: colab.research.google.com
  • Pros: Free GPU access, no setup required
  • Cons: Limited session time, Scholar required for some assignments
  • Best for: Experimentation and learning

Local Development (Optional)¶

  • Setup: Install Anaconda locally
  • Pros: Full control, no network dependency
  • Cons: Limited GPU access, storage requirements
  • Best for: Development and testing before cluster submission

🎯 Quick Reference Commands¶

Daily Workflow Commands¶

# Connect to Scholar
ssh username@scholar.rcac.purdue.edu

# Load your environment
module load conda/2024.09
source activate CS373

# Submit a job
sbatch my_job.sh

# Check job status
squeue -u username

# View job output
tail -f jobname_12345.out

Emergency Commands¶

# Cancel all your jobs
scancel -u username

# Check disk usage
du -sh ~/*

# Clean conda cache
conda clean --all

# Check queue status
qlist

🎉 Congratulations!¶

You now have:

  • ✅ A fully configured Python environment on Scholar
  • ✅ Knowledge of job submission and management
  • ✅ Understanding of file transfer methods
  • ✅ Troubleshooting skills for common issues
  • ✅ Access to comprehensive resources and documentation

Your Scholar cluster environment is ready for CS373 assignments!

Next Steps:¶

  1. Practice by running the verification script
  2. Experiment with the iris example to understand job submission
  3. Bookmark this notebook for quick reference
  4. Ask questions early if you encounter issues

Pro Tips for Success:¶

  • Always test your code with small datasets first
  • Use descriptive job names to track your work
  • Keep your home directory organized
  • Monitor your disk usage regularly
  • Save your work frequently

Remember: The key to success with Scholar is understanding the difference between frontend and backend usage. When in doubt, submit a job rather than running code directly!

Happy computing! 🚀


📝 Assignment Checklist¶

Use this checklist for each assignment:

Before Starting:¶

  • SSH connection to Scholar works
  • CS373 environment activates properly
  • Required data files uploaded to cluster
  • Job submission script prepared

During Development:¶

  • Code tested locally or in interactive session
  • Matplotlib backend set to 'Agg' for cluster plots
  • File paths use relative or home directory references
  • Resource requirements estimated (time, memory, GPU)

Before Submission:¶

  • Job script includes proper SBATCH directives
  • Output and error files have unique names
  • Job tested with small dataset first
  • Results files will be saved to accessible location

After Job Completion:¶

  • Check .out and .err files for issues
  • Verify output files were created
  • Download results if needed
  • Clean up temporary files

🔍 Appendix: Advanced Topics¶

SSH Key Setup (Optional)¶

To avoid typing your BoilerKey every time (Linux/Mac only):

# On your local machine
mkdir -p ~/.ssh
ssh-keygen -t rsa -b 4096
ssh-copy-id -i ~/.ssh/id_rsa username@scholar.rcac.purdue.edu

# Now you can connect with:
ssh -i ~/.ssh/id_rsa username@scholar.rcac.purdue.edu

Environment Modules System¶

Scholar uses the modules system to manage software:

# List available modules
module avail

# List loaded modules
module list

# Load a specific module
module load conda/2024.09

# Unload a module
module unload anaconda

# Get help about a module
module help anaconda

Custom Conda Environments¶

For specific projects, you might want additional environments:

# Create environment from file
conda env create -f environment.yml

# Export your environment
conda env export > my_environment.yml

# Clone an existing environment
conda create --name CS373_backup --clone CS373

# Remove an environment
conda env remove --name old_environment

Monitoring Job Resources¶

To see how much resources your jobs actually use:

# Check job efficiency after completion
seff job_id

# Monitor running job resources
sstat -j job_id --format=AveCPU,AvePages,AveRSS,AveVMSize

# Get detailed job information
sacct -j job_id --format=JobID,JobName,MaxRSS,Elapsed,State