GPU clusters.
Pick a GPU type and how many machines. GPU.ai rents them, joins them on an encrypted private network as one Kubernetes cluster, and installs Ray and the Run:ai scheduler.
§ 25.1Create a cluster¶
In the console, open Clusters and choose New cluster. The form lists the machines that can start now, 8-GPU machines included, with the price per machine and the regions that have stock, and picks the cheapest one in stock. When the machines in stock differ in price the form shows the range: each machine starts on the cheapest one left when it is placed, so a cluster's machines can cost different amounts. The form also shows what the cluster costs per hour at its minimum and at its maximum number of machines. A cluster has 1 to 8 machines, and one is enough to try it. The first machine runs Ray work on its own GPUs, and GPU.ai adds machines up to the maximum when work waits. From the CLI or the API:
gpu clusters gpu-types
gpu clusters create demo --gpu rtx_a6000 --min-nodes 1 --max-nodes 4 --idle-timeout 600
gpu clusters get democurl -X POST https://api.gpu.ai/v1/clusters \
-H "Authorization: Bearer $GPUAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name": "demo", "gpu_type": "rtx_a6000", "min_nodes": 1, "max_nodes": 4, "idle_timeout": 600}'The cluster is ready in about 5 to 10 minutes. Set placement to spread to place machines on different suppliers where possible. A machine with none in stock is refused with no_capacity, which names the nearest one in stock.
§ 25.2Run a Ray job¶
The example Ray job is batch inference on every GPU. The script below embeds 200,000 texts with a sentence-transformers model, one share per GPU, then answers 20 questions against the whole corpus. Each answer sits in a different share, so the answers come back right only if every GPU did its share. It ends with RESULT: PASS and exits non-zero on any failure. In the console, open the cluster and choose Run example job to run it on every GPU and see the result, or Open Ray dashboard. From your computer, start a local gateway to the Ray dashboard and job API. It adds your API key to each request.
gpu clusters dashboard demo
# in another terminal, with batch_inference.py (below) in this folder:
pip install "ray[default]==2.41.0"
ray job submit --address http://127.0.0.1:8265 --working-dir . -- python batch_inference.py 2
# ...
# RESULT: PASS, 200,000 texts on 2 of 2 GPUs, 20 of 20 questions right# batch_inference.py: batch embedding inference on every GPU in the cluster.
#
# The job embeds a corpus of texts with a sentence-transformers model, one
# shard per GPU, then answers a set of questions against the whole corpus.
# Each question has one right answer hidden in a different shard, so the
# answers come back right only if every GPU embedded its shard. It checks:
# - every GPU in the cluster did a shard (distinct GPU UUIDs),
# - every text was embedded exactly once,
# - every question found its answer (top-1 over the whole corpus),
# - every GPU computes the same embeddings for the same probe texts.
# The last line is "RESULT: PASS ..." and the job exits non-zero on a failure.
#
# python batch_inference.py 4 # 4 GPUs (machines x GPUs per machine)
# python batch_inference.py 4 --texts 1000000 # a bigger corpus
#
# Pass the number of GPUs you expect: the job reserves one Ray worker per GPU
# first (the cluster adds machines up to max_nodes if it has to), then runs.
# Without it, it uses the GPUs Ray has now. Each worker installs PyTorch and
# sentence-transformers through a Ray runtime_env on its first job (a few
# minutes); warm workers reuse them.
import argparse, math, random, socket, subprocess, sys, time
import ray
from ray.util.placement_group import placement_group
from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy
MODEL = "sentence-transformers/all-MiniLM-L6-v2"
PACKAGES = ["torch==2.5.1", "sentence-transformers==3.3.1"]
# Questions and the one text in the corpus that answers each.
QA = [
("How do I reset a forgotten password?", "To reset a forgotten password, click 'Forgot password' on the sign-in page and follow the emailed link."),
("What is the boiling point of water at sea level?", "At sea level, water boils at 100 degrees Celsius."),
("Which planet is known as the red planet?", "Mars is called the red planet because of the iron oxide on its surface."),
("How many legs does a spider have?", "Spiders have eight legs."),
("Who wrote the play Romeo and Juliet?", "Romeo and Juliet is a tragedy written by William Shakespeare."),
("What is the capital city of Japan?", "Tokyo is the capital of Japan."),
("How do vaccines protect people from disease?", "Vaccines train the immune system to recognise a germ, so the body can fight it off later."),
("What does a GPU do in a computer?", "A graphics processing unit runs many simple calculations in parallel, for graphics and machine learning."),
("How long does the Earth take to orbit the Sun?", "The Earth goes around the Sun once every 365.25 days."),
("What gas do plants absorb from the air?", "Plants take in carbon dioxide from the air and release oxygen."),
("How should I store fresh basil?", "Keep fresh basil like a bouquet, stems in a glass of water at room temperature."),
("What is the largest ocean on Earth?", "The Pacific is the largest and deepest of the world's oceans."),
("How do I change a flat bicycle tire?", "To fix a flat bike tire, remove the wheel, lever off the tire, and replace or patch the inner tube."),
("What language is spoken in Brazil?", "Most people in Brazil speak Portuguese."),
("Why is the sky blue?", "The sky looks blue because air scatters blue sunlight more than red light."),
("How many players are on a soccer team on the field?", "A soccer team has eleven players on the field, including the goalkeeper."),
("What is the chemical symbol for gold?", "Gold's chemical symbol is Au, from the Latin word aurum."),
("When did humans first land on the Moon?", "Apollo 11 landed the first people on the Moon in July 1969."),
("How can I fall asleep faster?", "Keeping a regular bedtime and avoiding screens before bed helps you fall asleep sooner."),
("What is the tallest mountain in the world?", "Mount Everest, at 8,849 metres, is the highest mountain above sea level."),
]
# Probe texts every GPU embeds, to check they all compute the same thing.
PROBES = [q for q, _ in QA[:8]]
WORDS = ("ledger quarterly invoice shipment warehouse pallet forklift tariff audit vendor "
"spreadsheet margin freight customs dock inventory batch lot serial barcode "
"routing carrier manifest depot procurement contract clause renewal ticket "
"escalation backlog sprint roadmap milestone budget forecast headcount payroll "
"compliance policy filing archive record schedule rota shift overtime").split()
def filler(i):
"""Corpus text i: deterministic office-style filler, unrelated to the questions."""
r = random.Random(i)
return "Record %d: %s." % (i, " ".join(r.choice(WORDS) for _ in range(r.randint(10, 24))))
def answer_index(q, total):
"""Where answer q sits: spread so each shard holds some of the answers."""
per = total // len(QA)
return q * per + per // 2
def corpus_text(i, answers):
a = answers.get(i)
return QA[a][1] if a is not None else filler(i)
@ray.remote(num_gpus=1, num_cpus=1)
class Embedder:
def __init__(self):
import torch
from sentence_transformers import SentenceTransformer
assert torch.cuda.is_available(), "no GPU in this Ray worker"
t = time.time()
self.model = SentenceTransformer(MODEL, device="cuda")
self.load_s = time.time() - t
self.torch = torch
def info(self):
uuid = subprocess.check_output(["nvidia-smi", "--query-gpu=uuid,name", "--format=csv,noheader"], text=True).strip().splitlines()[0]
return {"host": socket.gethostname(), "ip": ray.util.get_node_ip_address(), "gpu": uuid}
def run(self, lo, hi, answers, batch):
torch = self.torch
q = self.model.encode([x for x, _ in QA], batch_size=64, convert_to_tensor=True, normalize_embeddings=True)
best = torch.full((len(QA),), -2.0, device="cuda")
best_i = torch.full((len(QA),), -1, dtype=torch.long, device="cuda")
n, t = 0, time.time()
for start in range(lo, hi, batch):
ids = range(start, min(start + batch, hi))
e = self.model.encode([corpus_text(i, answers) for i in ids], batch_size=256,
convert_to_tensor=True, normalize_embeddings=True)
s = q @ e.T # questions x texts, cosine similarity
v, j = s.max(dim=1)
better = v > best
best = torch.where(better, v, best)
best_i = torch.where(better, j + start, best_i)
n += len(ids)
torch.cuda.synchronize()
secs = time.time() - t
probes = self.model.encode(PROBES, batch_size=64, normalize_embeddings=True).tolist()
return {"texts": n, "lo": lo, "hi": hi, "seconds": secs, "load_seconds": self.load_s,
"best": best.tolist(), "best_i": best_i.tolist(), "probes": probes, **self.info()}
def main():
p = argparse.ArgumentParser()
p.add_argument("gpus", nargs="?", type=int, default=0)
p.add_argument("--texts", type=int, default=200_000)
p.add_argument("--batch", type=int, default=8192)
a = p.parse_args()
ray.init()
gpus = a.gpus or int(ray.cluster_resources().get("GPU", 0)) or 1
total = max(a.texts, 100 * len(QA))
answers = {answer_index(qi, total): qi for qi in range(len(QA))}
print("Embedding %d texts with %s on %d GPUs" % (total, MODEL, gpus), flush=True)
t0 = time.time()
pg = placement_group([{"GPU": 1, "CPU": 1}] * gpus, strategy="STRICT_SPREAD")
ray.get(pg.ready(), timeout=1800)
env = {"pip": PACKAGES}
workers = [Embedder.options(runtime_env=env, scheduling_strategy=PlacementGroupSchedulingStrategy(
pg, placement_group_bundle_index=i)).remote() for i in range(gpus)]
infos = ray.get([w.info.remote() for w in workers], timeout=3600)
print("Workers ready in %.0f s" % (time.time() - t0), flush=True)
per = math.ceil(total / gpus)
t1 = time.time()
shards = ray.get([w.run.remote(i * per, min((i + 1) * per, total), answers, a.batch)
for i, w in enumerate(workers)])
wall = time.time() - t1
for s in shards:
print(" %-12s %-40s %s texts %7d to %7d %7.0f texts/s" % (
s["ip"], s["gpu"], format(s["texts"], ","), s["lo"], s["hi"], s["texts"] / max(s["seconds"], 1e-9)), flush=True)
# Combine: the best match for each question over every shard.
found = 0
for qi in range(len(QA)):
score, idx = max((s["best"][qi], s["best_i"][qi]) for s in shards)
ok = answers.get(idx) == qi
found += ok
if not ok:
print(" MISS %r -> text %d (score %.3f)" % (QA[qi][0], idx, score))
# Every GPU must compute the same probe embeddings.
ref = shards[0]["probes"]
worst = min(sum(x * y for x, y in zip(u, v)) for s in shards for u, v in zip(ref, s["probes"]))
distinct = len({s["gpu"].split(",")[0] for s in shards})
embedded = sum(s["texts"] for s in shards)
covered = sorted((s["lo"], s["hi"]) for s in shards)
contiguous = covered[0][0] == 0 and covered[-1][1] == total and all(
covered[i][1] == covered[i + 1][0] for i in range(len(covered) - 1))
print("GPUs answered: %d of %d" % (distinct, gpus))
print("Texts embedded: %s of %s in %.1f s (%s texts/s)" % (
format(embedded, ","), format(total, ","), wall, format(int(embedded / max(wall, 1e-9)), ",")))
print("Questions answered correctly: %d of %d" % (found, len(QA)))
print("Same embeddings on every GPU: %s (lowest cosine %.6f)" % ("yes" if worst > 0.999 else "no", worst))
ok = distinct == gpus and embedded == total and contiguous and found == len(QA) and worst > 0.999
print("RESULT: %s, %s texts on %d of %d GPUs, %d of %d questions right" % (
"PASS" if ok else "FAIL", format(embedded, ","), distinct, gpus, found, len(QA)))
sys.exit(0 if ok else 1)
if __name__ == "__main__":
main()Pass the number of GPUs you expect (machines times GPUs per machine). Each Ray GPU worker installs PyTorch on its first job, which takes a few minutes; workers stay warm for the idle period, so the next job starts at once. When the job needs more GPUs than the cluster has, GPU.ai adds machines up to the maximum.
A Ray job's log, including what its tasks print on every worker, is kept on the head machine, which autoscaling never removes. Read it with ray job logs or under Ray jobs in the console, also after the machines the job ran on are gone. kubectl logs reads a pod's log from its machine, so it has nothing once that machine is removed.
§ 25.3Run a Kubernetes job through the scheduler¶
gpu clusters kubeconfig demo > kubeconfig.yaml
export KUBECONFIG=$PWD/kubeconfig.yaml
gpu clusters queues set demo research --gpu-limit 1
kubectl apply -f job.yaml && kubectl logs -f job/matmul
# NVIDIA RTX A6000 sum 549755813888 PASSapiVersion: batch/v1
kind: Job
metadata:
name: matmul
spec:
template:
metadata:
labels:
kai.scheduler/queue: research
spec:
schedulerName: kai-scheduler
restartPolicy: Never
containers:
- name: matmul
image: pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime
command: ["python", "-c", "import torch; a = torch.ones(8192, 8192, device='cuda'); s = int((a @ a).sum(dtype=torch.float64).item()); print(torch.cuda.get_device_name(0), 'sum', s, 'PASS' if s == 8192 ** 3 else 'FAIL')"]
resources:
limits:
nvidia.com/gpu: 1§ 25.4Queues, priorities and quotas¶
A pod picks a queue with the label kai.scheduler/queue and schedulerName: kai-scheduler. gpu_quota is the GPUs a queue is guaranteed and gpu_limit the most it may use. Work over the limit waits until the queue's own work frees GPUs, and never adds machines. Pods can set the priority class gpuai-low, gpuai-normal or gpuai-high.
§ 25.5Autoscaling and billing¶
GPU.ai keeps the minimum number of machines, adds machines when GPU work has waited about 90 seconds (up to the maximum), and removes a machine that ran no GPU work for the idle period (down to the minimum). Each machine is billed like an instance; the cluster shows its price per hour and its cost so far, and each machine appears in your usage. Deleting the cluster stops every machine and its billing.
Links between suppliers are slower than inside one data center, so clusters spread across suppliers suit parallel work such as batch inference and data processing, not training that splits one model across machines.