# Batch inference with Ray Data on GPUs

How to run a model over a dataset on every GPU of an Eugo cluster with Ray Data: a callable class that loads the model once, map_batches with an actor pool, num_gpus and batch_size.

Source: https://docs.eugo.io/docs/guides/batch-inference-ray-data/

---

To run a model over a dataset on your Eugo cluster's GPUs, write the model as a callable class that loads it once in `__init__`, then pass the class (not an instance) to `map_batches` with `compute=ActorPoolStrategy(size=n)`, `num_gpus=1` and an explicit integer `batch_size`. Ray Data starts one actor per GPU, loads the model once in each, and keeps every GPU fed with batches.

> **Applies to:** the EugoLab image, November 2026.

## What you will build

A notebook that classifies a list of texts on the cluster's GPUs with a Hugging Face model, one actor per GPU, and returns the predictions as a pandas DataFrame.

## Requirements

- A workspace in EugoLab.
- A running cluster with a **General Purpose GPUs (ECU-G)** worker pool in the **Eugo HPC Clusters** panel. [Cluster settings](/docs/guides/cluster-settings.md) lists each size's CPUs, memory and GPUs.

PyTorch and Hugging Face Transformers are installed in the image, so the example needs no installs.

## Step 1: Connect the notebook to the cluster

Connect first. Without Connect, the first Ray Data call starts a private local Ray inside the notebook instead of using the cluster's GPUs.

1. In EugoLab, open a new notebook.
2. In the **Eugo HPC Clusters** panel, on your cluster's card, in the **Notebook** tab, select **Connect this notebook**. EugoLab gives the notebook's kernel the cluster's token without showing it, then adds and runs this cell:

   ```python
   import eugo.hpc
   eugo.hpc.init(address="ray://<head>:10001");
   ```

   The card now offers **Disconnect** where **Connect this notebook** was.

3. Check how many GPUs the cluster has free:

   ```python
   num_gpus = int(eugo.hpc.available_resources().get("GPU", 0))
   print(num_gpus)
   ```

You will use this number as the size of the actor pool, so that every GPU gets an actor. It counts only the GPU workers that are running now, and it must be at least 1: a pool of size 0 raises `ValueError: ('size must be >= 1', 0)`.

An ECU-G pool's **Min Nodes** is 0 by default, so on a new cluster the cell can print `0`. Reading the count does not start a GPU worker, so waiting does not change it. Before you go on:

1. Set the ECU-G pool's **Min Nodes** to the number of GPU nodes you want, so they start and stay running (see [Scaling](/docs/guides/cluster-settings.md#scaling); on a running cluster, use **Scale cluster**, see [Changing a running cluster](/docs/guides/cluster-settings.md#changing-a-running-cluster)).
2. When the nodes have started, run the cell again and check that it prints at least `1`.

## Step 2: Define the predictor class

Write the model as a class: `__init__` loads the model once per actor, and `__call__` runs one batch.

1. In a new cell, define the class:

   ```python
   from typing import Dict
   import numpy as np

   MODEL_ID = "distilbert/distilbert-base-uncased-finetuned-sst-2-english"

   class SentimentPredictor:
       def __init__(self, model_id: str):
           from transformers import pipeline
           # Runs once per actor; the actor's GPU is device 0 inside it.
           self.classifier = pipeline("text-classification", model=model_id, device=0)

       def __call__(self, batch: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]:
           outputs = self.classifier(list(batch["text"]))
           batch["label"] = np.array([o["label"] for o in outputs])
           batch["score"] = np.array([o["score"] for o in outputs])
           return batch
   ```

The model downloads to a cache on the cluster's shared drive, so it downloads once per cluster, not once per node. If the cluster has no shared drive, each worker downloads it to its own disk.

## Step 3: Run the pipeline inside a task

From a connected notebook, run the Ray Data pipeline inside a task decorated with `@eugo.hpc.distribute`, not directly in the notebook: some Ray Data calls, such as `.take()` and `.to_pandas()`, fail when made straight from a connected notebook.

1. Define the task that builds and runs the pipeline:

   ```python
   @eugo.hpc.distribute
   def run_batch_inference(texts, pool_size):
       ds = eugo.hpc.data.from_items([{"text": t} for t in texts])
       predictions = ds.map_batches(
           SentimentPredictor,                                       # the class, not an instance
           fn_constructor_kwargs={"model_id": MODEL_ID},
           compute=eugo.hpc.data.ActorPoolStrategy(size=pool_size),  # one actor per GPU
           num_gpus=1,                                               # each actor reserves one GPU
           batch_size=64,                                            # required when num_gpus is set
       )
       return predictions.to_pandas()
   ```

2. Run it on some texts:

   ```python
   texts = ["The results were excellent.", "This was a waste of time."] * 500
   result = eugo.hpc.get(run_batch_inference.remote(texts, pool_size=num_gpus))
   print(result.shape)
   ```

   ```text
   (1000, 3)
   ```

   `result` is a pandas DataFrame with the columns `text`, `label` (`POSITIVE` or `NEGATIVE`) and `score`. Its rows need not be in the order of `texts`.

What each argument does:

- **The class, not an instance:** Ray Data creates the instances on the cluster, one per actor. An instance passed with `compute=ActorPoolStrategy(...)` is refused with a `ValueError` (see [Troubleshooting](#troubleshooting)).
- **`fn_constructor_kwargs`:** arguments for `__init__` (or `fn_constructor_args` for positional ones). Per-call arguments for `__call__` go in `fn_kwargs` or `fn_args`.
- **`compute=ActorPoolStrategy(size=n)`:** a fixed pool of `n` actors. `ActorPoolStrategy(min_size=m, max_size=n)` autoscales between `m` and `n`, and `initial_size=` sets where it starts. A plain function runs as tasks instead; `TaskPoolStrategy(size=n)` caps how many.
- **`num_gpus=1`:** each actor reserves one GPU. A GPU worker that does not set `num_cpus` also reserves 1 CPU; pass `num_cpus=0` to opt out.
- **`batch_size`:** must be an integer when `num_gpus` is set. Use the largest batch that does not run the GPU out of memory. When blocks are smaller than `batch_size`, Ray Data bundles them up to it, and a batch can be smaller when `batch_size` does not divide a block.

Always use `compute=` to size the pool: the older `concurrency=` argument of `map_batches` is deprecated. Pass Ray options such as `num_cpus`, `num_gpus`, `memory` and `runtime_env` as named arguments of `map_batches`; passing them through `**ray_remote_args` is deprecated.

## Step 4: Watch the job in the Ray dashboard

1. On the cluster card, select **Open Dashboard**. The cluster's Ray dashboard opens, signed in, in a new tab.

## Troubleshooting

### Error: ValueError: You must provide batch_size to map_batches when requesting GPUs

**Cause:** `num_gpus` is set and `batch_size` is missing, `None` or `"auto"`.

**Fix:**

1. Pass an integer `batch_size` to `map_batches`, for example `batch_size=64`.
2. If the GPU runs out of memory, lower it.

A `batch_size` below 1 raises `ValueError: Batch size can't be negative or 0`.

### Error: ValueError: ('size must be >= 1', 0)

Inside the task, the error arrives as `RayTaskError(ValueError)` with this line at the end.

**Cause:** the actor pool size was 0. `pool_size` came from a free GPU count of `0`, because no GPU worker was running when Step 1 read it.

**Fix:**

1. Set the ECU-G pool's **Min Nodes** to the number of GPU nodes you want (see [Changing a running cluster](/docs/guides/cluster-settings.md#changing-a-running-cluster)).
2. When the nodes have started, run the Step 1 check again until it prints at least `1`.
3. Run Step 3 again.

### Error: ValueError: You specified the function ... as your UDF with the compute ActorPoolStrategy(...), but Ray Data can't schedule regular functions with the actor pool strategy

The message names your object, for example `<__main__.SentimentPredictor object at 0x...>`, and ends: "To fix this error, pass a TaskPoolStrategy to compute or None to use the default compute strategy."

**Cause:** you passed an instance of the predictor class, such as `SentimentPredictor(MODEL_ID)`, together with `compute=ActorPoolStrategy(...)`. Ray Data treats an instance as a plain function, and plain functions cannot run in an actor pool.

**Fix:**

1. Pass the class itself: `map_batches(SentimentPredictor, ...)`.
2. Move the constructor arguments to `fn_constructor_kwargs`.

Do not follow the message's own suggestion of dropping `compute=`: without an actor pool, Ray Data must pickle the instance, and one whose state cannot be pickled fails with `TypeError: Could not serialize the put value`.

### map_batches uses only one of my GPUs

**Cause:** the actor pool is smaller than the number of GPUs.

**Fix:**

1. Check that all the GPU nodes you want are running, then read the free GPU count with `eugo.hpc.available_resources()`.
2. Set `compute=ActorPoolStrategy(size=n)` to that count, with `num_gpus=1`.

### My GPU task or actor never starts

**Cause:** the code asks for a GPU the cluster does not have. Some upstream examples set `accelerator_type="A10G"`, a GPU that Eugo's worker pools do not have, so the work never schedules.

**Fix:**

1. Remove `accelerator_type` from `map_batches` or the task.
2. Run the cell again.

### This notebook is already running Ray, started by a cell rather than through Connect

**Cause:** a cell ran work before you connected, so the notebook started its own Ray.

**Fix:**

1. Stop the notebook's own Ray: on the cluster card, select **Disconnect**, or restart the notebook's kernel.
2. On the cluster card, in the **Notebook** tab, select **Connect this notebook**.
3. Run your cells again.

### My work ran in the notebook, not on the cluster

**Cause:** the notebook was not connected, so the first Ray Data call started a private local Ray.

**Fix:**

1. Stop the notebook's own Ray: on the cluster card, select **Disconnect**, or restart the notebook's kernel.
2. On the cluster card, in the **Notebook** tab, select **Connect this notebook**.
3. Run your cells again.

## Summary

- Connect the notebook first, then run the Ray Data pipeline inside a task.
- Pass the predictor class, not an instance, with `compute=ActorPoolStrategy(size=n)`, `num_gpus=1` and an integer `batch_size`.
- Have the GPU nodes running first (the pool's **Min Nodes**), then size the pool to the free GPU count, at least 1, so every GPU is busy. Leave `accelerator_type` unset.

## Next steps

- [Distributed Python on a GPU cluster](/docs/guides/distributed-python.md)
- [Running tasks in parallel](/docs/guides/parallel-tasks.md)
- Ray: [End-to-end: Offline Batch Inference](https://docs.ray.io/en/latest/data/batch-inference.html)
- Example notebooks: [actor-pool batch inference](https://github.com/eugo-inc/ganymede/blob/main/ray_patterns/data/21_data-actor-pool-batch-inference.ipynb)
