This guide provides a complete, step-by-step workflow for setting up a powerful and reproducible machine learning environment on a Lambda Labs GPU instance. We will cover:
- Initial Server Setup: Requesting an instance, attaching storage, and connecting via SSH.
- Core Software Installation: Installing Miniconda, NVM, Google Cloud CLI, and Wandb.
- Docker Environment: Creating a portable and reproducible environment with Docker.
- Running Experiments: Integrating OpenAI APIs and tracking with Weights & Biases.
- Model Checkpointing: Saving your work and uploading it to Google Cloud Storage.
1. Initial Lambda Labs Setup
Your goal here is to get a running cloud GPU instance that you can securely access and that has persistent storage for your data.
A. Launch an Instance and Attach Storage
- Log into Lambda Labs: Navigate to the Cloud Dashboard.
- Launch an Instance: Click “Launch new instance”.
- Select GPU Type: Choose a GPU that fits your budget and performance needs (e.g., an
A10is great for starting). - Select Region: Pick a region geographically close to you for lower latency.
- Attach Persistent Storage: In the “File Systems” section, select your
memory-1storage. This is critical. It ensures your data, models, and code are not lost when you stop the instance. - Add SSH Key: In the “SSH Keys” section, add your public SSH key. This is the secure way to log in without a password. If you don’t have one, you can generate it on your local machine.
- Launch: Click “Launch instance”. It will take a few minutes to provision.
B. Connect via SSH
Once the instance is running, you’ll see its IP address in the dashboard.
-
Copy the IP Address (e.g.,
192.222.53.193). -
Open a Terminal on your local computer.
-
Connect: The default username is
ubuntu. Use the following command:ssh ubuntu@YOUR_INSTANCE_IP # Example: ssh ubuntu@192.222.53.193
You are now logged into your remote GPU machine!
2. Core Software Installation (On the Host)
Before we get to Docker, we’ll install some essential command-line tools on the host machine. This only needs to be done once.
A. Use tmux for Persistent Sessions
Your SSH connection can drop. tmux keeps your session alive.
# Update package lists
sudo apt-get update
# Install tmux
sudo apt-get install -y tmux
# Start a new tmux session
tmux new -s main
How to use tmux:
- Detach (keep running in background):
Ctrl+bthend- Re-attach to the last session:
tmux attach
B. Install Miniconda
Miniconda is a minimal installer for conda, used for managing Python environments.
# Navigate to your home directory
cd ~
# Download the installer
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
# Run the installer script
bash Miniconda3-latest-Linux-x86_64.sh
# Accept the license and default location. When it asks "Do you wish the installer to initialize...", say YES.
# Apply the changes to your current shell
source ~/.bashrc
C. Install NVM and Node.js
NVM (Node Version Manager) is used to manage Node.js versions, which might be needed for tools like the Anthropic/Claude SDK.
# Download and run the NVM installation script
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
# Apply the changes to your current shell
source ~/.bashrc
# Install the latest Long-Term Support (LTS) version of Node.js
nvm install --lts
D. Install Weights & Biases and Google Cloud CLI
# Install the wandb library
pip install wandb
# Install the Google Cloud CLI
curl -O https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-cli-468.0.0-linux-x86_64.tar.gz
tar -xf google-cloud-cli-468.0.0-linux-x86_64.tar.gz
./google-cloud-sdk/install.sh
# Apply changes to your shell
source ~/.bashrc
# Initialize gcloud (this will open a browser link for you to log in)
gcloud init
3. Setting Up the Docker Environment
This is the core of our reproducible setup. We’ll define an environment in a Dockerfile and run it.
A. Grant Docker Permissions
First, allow your ubuntu user to run Docker commands without sudo.
sudo usermod -aG docker ${USER}
# Apply the new group membership (log out and log back in, or run this)
newgrp docker
B. Structure Your Project
Your ~/memory-1 directory is perfectly structured. We’ll use it.
~/memory-1/
├── data/ # For datasets
├── models/ # For saved model checkpoints & caches
└── repos/ # For your code repositories
-
Clone Your Project:
cd ~/memory-1/repos git clone https://github.com/your-username/your-project.git cd your-project -
Create a
Dockerfile: Inside your project directory (~/memory-1/repos/your-project), create a file namedDockerfilewith the following content. This file defines your environment.# Start from an official NVIDIA base image with CUDA and cuDNN pre-installed FROM nvidia/cuda:12.1.1-cudnn8-devel-ubuntu22.04 # Avoid prompts during package installation ENV DEBIAN_FRONTEND=noninteractive # Install system dependencies, including Python and Git RUN apt-get update && apt-get install -y \ python3.10 \ python3-pip \ git \ curl \ && rm -rf /var/lib/apt/lists/* # Set the working directory inside the container WORKDIR /workspace # Copy your project's requirements file into the container COPY requirements.txt . # Install Python packages RUN pip install --no-cache-dir -r requirements.txt # Copy the rest of your project code into the container COPY . . # Make the container runnable (optional, but good practice) CMD ["/bin/bash"] -
Create a
requirements.txtfile: In the same directory, list your Python dependencies.torch==2.1.0 torchvision==0.16.0 transformers datasets openai wandb google-cloud-storage # Add any other packages you need
C. Build and Run the Docker Container
-
Build the Image: From your project directory, build the Docker image.
docker build -t my-llm-exp . -
Run the Container: This is the key command that connects everything.
# Ensure you are in your project directory: ~/memory-1/repos/your-project docker run -it --rm --gpus all --ipc=host \ -e OPENAI_API_KEY="YOUR_OPENAI_KEY" \ -v $(pwd):/workspace \ -v ~/memory-1/data:/data \ -v ~/memory-1/models:/models \ -v ~/memory-1/models/cache/huggingface:/root/.cache/huggingface \ my-llm-expBreakdown of the command:
docker run -it --rm: Runs an interactive container and removes it when you exit.--gpus all: Gives the container access to all GPUs.--ipc=host: Optimizes memory sharing for tools like PyTorch.-e OPENAI_API_KEY="...": Securely passes your API key as an environment variable.-v $(pwd):/workspace: Mounts your project code into/workspace.-v ~/memory-1/data:/data: Mounts your data folder.-v ~/memory-1/models:/models: Mounts your models folder for saving checkpoints.-v ~/memory-1/models/cache/...: Mounts a cache for Hugging Face models.my-llm-exp: The name of the image you built.
You are now inside your container, with all tools installed and all files linked!
4. Running Experiments
Inside the container, you can now run your experiments.
A. Log into Wandb
# Run this inside the container
wandb login
It will ask for your Wandb API key.
B. Example Python Script (main.py)
Here is a sample script showing how to use the OpenAI API, log to Wandb, and save a dummy model.
import os
import openai
import wandb
# 1. Initialize Weights & Biases
# It will automatically pick up the project name from the directory
wandb.init(
project="openai-prompt-experiments",
config={
"model": "gpt-4",
"temperature": 0.7,
}
)
# Load API key from environment variable passed by Docker
openai.api_key = os.getenv("OPENAI_API_KEY")
# 2. Run your experiment (e.g., call OpenAI API)
try:
prompt = "Write a tagline for a company that sells smart dog collars."
response = openai.chat.completions.create(
model=wandb.config.model,
messages=[{"role": "user", "content": prompt}],
temperature=wandb.config.temperature,
)
result_text = response.choices[0].message.content
print(f"Prompt: {prompt}")
print(f"Result: {result_text}")
# 3. Log results to Wandb
wandb.log({
"prompt": prompt,
"result": result_text,
})
except Exception as e:
print(f"An error occurred: {e}")
wandb.log({"error": str(e)})
# 4. Save a "model checkpoint"
# In a real scenario, this would be model weights (e.g., torch.save)
checkpoint_path = "/models/my_experiment_checkpoint.txt"
with open(checkpoint_path, "w") as f:
f.write(f"Experiment successful. Result: {result_text}")
print(f"Checkpoint saved to {checkpoint_path}")
wandb.finish()
C. Run the script
# Inside the container
python main.py
You can now go to your Wandb dashboard to see the logged results live!
5. Saving Checkpoints to Google Cloud
Your checkpoint is saved to ~/memory-1/models on the host machine. You can upload it from the host or from inside the container.
A. Authenticate Google Cloud (if not done already)
If you didn’t run gcloud init on the host, you’ll need to authenticate.
# Run on the host machine
gcloud auth application-default login
B. Upload to a GCS Bucket
Use the gcloud storage command to copy your files.
# Run on the host machine
# Replace 'your-gcs-bucket-name' with your actual bucket name
gcloud storage cp ~/memory-1/models/my_experiment_checkpoint.txt gs://your-gcs-bucket-name/checkpoints/
Summary & Daily Workflow
- Start: Launch your Lambda Labs instance from the dashboard.
- Connect:
ssh ubuntu@YOUR_IP - Persist:
tmux attach(ortmux new -s main) - Navigate:
cd ~/memory-1/repos/your-project - Develop: Run the
docker run ...command to enter your environment. - Experiment: Run your Python scripts.
- Save: Commit code changes with
git push. Upload final models withgcloud storage cp. - STOP: Always stop your instance from the Lambda Labs dashboard to save money!