> ## Documentation Index
> Fetch the complete documentation index at: https://docs.reactor.inc/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> To build and serve your own model, start at /deploy/development/quickstart and /deploy/development/overview. Authenticate with reactor auth login, scaffold with reactor init, then run reactor deploy production from the workspace. Deploy builds remotely by default, creates a missing workspace project and its production environment, and waits for rollout. No local Docker or model.version bump is needed. Projects own images and weight sets; environments select the image, weights, GPU, instance count, and variables. Create staging explicitly with reactor environment create staging before deploying to it. Use reactor scale for capacity and reactor rollback for an earlier revision’s image and weights. See /deploy/platform/projects and /deploy/platform/deploy. Client SDK modelName remains account-qualified and selects production by default. Model code imports reactor_runtime; Python client code imports reactor_sdk. Local testing is optional; /deploy/development/local-testing covers reactor run, which needs Docker.
> Reactor hosts multiple models, each with its own connect slug (modelName) and command/event schema. The video model catalog — slug, typed SDK package, and links to its schema — is at /model-api-reference/overview. Robotics policy documentation starts at /robotics/overview; The launch policies are Cosmos Nano DROID (/robotics/cosmos/nano-policy-droid/), DreamZero DROID (/robotics/dreamzero/droid/), and FLUX Action DROID (/robotics/flux-action/droid/), organized by model family and embodiment. Some models expose one slug per experience (e.g. HappyOyster); always take the slug from the model's own pages, never guess it.
> Fastest path to a working app: `npx create-reactor-app my-app --model=<slug>` scaffolds a complete app with secure auth wired up. Typed TypeScript SDKs are published as @reactor-models/<model>; Python uses the base reactor-sdk package.
> Auth: exchange an API key (rk_...) for a JWT via POST https://api.reactor.inc/tokens from your server. Never put the API key in client-side code.
> Append .md to any docs URL for clean Markdown. Search these docs via the MCP server at https://docs.reactor.inc/mcp.

# Serve several sessions

> Serve several sessions from one instance: the model server loads the weights once, and every session uses that one copy.

By default, each session gets its own instance, with its own GPUs and its own copy of the weights.
You can also serve several sessions from one instance. Do this when one copy of the weights fills
most of the GPU's memory, or when one session leaves the GPU partly idle.

The instance then runs one **model server** and several **session runtimes**:

* The model server loads the weights once and holds the GPU.
* Each session runtime serves one session. It runs your application code, and it has no GPU.
* At each step, a session runtime sends one **request** to the model server, and waits for the
  result.

![On the left, three clients each connect to their own instance, and each instance has its own GPU and weights. On the right, three clients connect to three session runtimes inside one instance. All three session runtimes send their requests to one model server, which holds the only GPU and the only copy of the weights.](https://mintcdn.com/reactortechnologiesinc/ZA-8Z0yimHMXyE_Q/diagrams/concurrent-sessions.svg?fit=max\&auto=format\&n=ZA-8Z0yimHMXyE_Q\&q=85\&s=eb9acc93b523040549b721fe0856d236)

Left: by default, each session has its own instance, GPU, and copy of the weights. Right: with several sessions in one instance, one model server holds the GPU and the weights for every session.

Every session in an instance runs the same model and the same image. You need
`reactor-runtime` 3.12.0 or later, and an up-to-date `reactor` CLI, which sends the sessions when it
deploys.

## What changes in an existing model

Three things change. Your inputs, outputs and clients stay the same.

1. The code that uses the GPU moves into a `ModelServer` subclass. It has `load()`, and a `step()`
   that takes a list of requests.
2. Your `ReactorApp` keeps its inputs and outputs. In place of the model, it holds a `ModelClient`
   and calls `step()` on it.
3. `reactor.yaml` names the `ModelServer` in `runtime.model_server`, and sets the number of
   sessions in `model.resources.sessions.count`.

## Does this fit your model?

It is a good fit when one of these is true:

* One copy of the weights fills most of the GPU's memory, so only one copy fits.
* One session uses only part of the GPU's time, for example a small model at 24 frames per second.

It is a poor fit when:

* One session already keeps the GPU busy. More sessions then only wait longer.
* One `step()` takes most of the frame period, so a second session misses its frames, and the
  model cannot [batch](https://docs.reactor.inc/deploy/development/reactor-app/batching.md) requests.
* The application half needs the GPU. A session runtime has no GPU.

### What you give up

* **GPU time is shared.** The sessions take turns on one GPU, so each extra session adds to every
  session's wait for its frame. [Choose the number of sessions](#choose-the-number-of-sessions)
  shows how to size this.
* **A model server restart interrupts every session in the instance.** Each one gets
  `ModelServerLost`, as [the failure table](#what-a-failure-ends) shows. With one session per
  instance, a crash affects one session.
* **Requests and results cross processes.** The runtime copies them through shared memory each step,
  so keep them small: send parameters, not tensors, when you can.

## How the halves split

Your model is split in two halves, as
[Writing a good model](https://docs.reactor.inc/deploy/development/reactor-app/application-and-model.md) describes. Here, the
two halves run in different processes:

| Half | Class | Runs in |
| - | - | - |
| Model | a `ModelServer` subclass | the model server, one per instance |
| Application | your `ReactorApp` | a session runtime, one per session |

A session has at most one request on the model server at a time. The model server takes the
requests in the order they arrive.

## Build the model

This section builds a complete example: a small network that draws a 256×256 animated frame for
each session. Each session sets its own `seed`, `speed`, and `warmth`. Four sessions share one
model server, and they take turns: the model server runs one request at a time. If your model can
run several requests in one forward pass, [Batch requests](https://docs.reactor.inc/deploy/development/reactor-app/batching.md)
shows the one change that makes the sessions step together.

Put these files in one folder: `lava_types.py`, `lava_model.py`, `lava_net.py`, `lava.py`,
`requirements.txt`, and `reactor.yaml`.

**1. Define the data that crosses between the halves**

The two halves run in different processes, so the runtime pickles each request and each result.
Use plain data: frozen dataclasses of numbers, strings, and NumPy arrays. Do not send a CUDA
tensor. A session runtime has no GPU, so it cannot rebuild one.

Put the types in a module that both halves import. Keep torch out of it.

```python lava_types.py theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}}
from dataclasses import dataclass

import numpy as np


@dataclass(frozen=True)
class LavaRequest:
    seed: int      # picks the scene
    t: float       # scene time in seconds
    warmth: float  # 0 cool to 1 warm


@dataclass(frozen=True)
class LavaFrame:
    frame: np.ndarray  # uint8 (256, 256, 3) RGB
    batch_size: int    # requests in the forward pass
```

**2. Write the model half**

Subclass `ModelServer` from `reactor_runtime.model_server`. The model server calls `load()`
once, before any session runtime connects. `self.device` is `"cuda"` when torch sees a GPU. The
runtime checks this when it builds your class, so torch must be imported by then. Here
`lava_model.py` imports `lava_net.py`, which imports torch.

The model server calls `step()` with a list of requests. Each request has a `payload`, which is
the `LavaRequest` that one session sent. Return one output per request, in the same order. On
this page the list holds one request. The same code runs batches on
[Batch requests](https://docs.reactor.inc/deploy/development/reactor-app/batching.md). `self.max_batch` is the most
requests one step takes. It is 1 on this page, and the batching page raises it.

```python lava_model.py theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}}
import logging
from pathlib import Path

from lava_net import build_net, render
from lava_types import LavaFrame, LavaRequest
from reactor_runtime.model_server import (
    ModelServer,
    ServerRequest,
)

log = logging.getLogger(__name__)


class LavaModel(ModelServer[LavaRequest, LavaFrame]):
    def load(self, config_path: Path | None) -> None:
        self.net = build_net(self.device)
        # Warm up, so that the first frame is not slow.
        warm = [LavaRequest(0, 0.0, 0.5)] * self.max_batch
        render(self.net, warm, self.device)
        self.steps = 0
        self.requests = 0

    def step(
        self, requests: list[ServerRequest[LavaRequest]]
    ) -> list[LavaFrame]:
        # One forward pass for every request in the batch.
        payloads = [r.payload for r in requests]
        frames = render(self.net, payloads, self.device)
        self.steps += 1
        self.requests += len(requests)
        if self.steps % 240 == 0:
            mean = self.requests / self.steps
            log.info("mean batch size %.2f", mean)
        size = len(requests)
        return [LavaFrame(f, size) for f in frames]
```

`render()` stacks every request into one tensor and runs the network once. It returns a uint8
array with one frame per request. The network is ordinary PyTorch code. This one is a small
decoder with fixed random weights, so the example needs no weight files. Copy it as it is; nothing
in it is specific to Reactor.

> [accordion] lava\_net.py: the network
>
> ```python lava_net.py theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}}
> import numpy as np
> import torch
> from torch import nn
>
> from lava_types import LavaRequest
>
> LATENT = 64
>
>
> def build_net(device: str) -> nn.Module:
>     """Latent (B, 64) to RGB (B, 3, 256, 256)."""
>     layers: list[nn.Module] = [
>         nn.Linear(LATENT, 128 * 8 * 8),
>         nn.Unflatten(1, (128, 8, 8)),
>     ]
>     chans = [128, 96, 64, 48, 32, 24]
>     for c_in, c_out in zip(chans, chans[1:]):
>         layers += [
>             nn.Upsample(scale_factor=2, mode="bilinear"),
>             nn.Conv2d(c_in, c_out, 3, padding=1),
>             nn.GELU(),
>             nn.Conv2d(c_out, c_out, 3, padding=1),
>             nn.Tanh(),
>         ]
>     layers += [nn.Conv2d(chans[-1], 3, 1), nn.Sigmoid()]
>     net = nn.Sequential(*layers).eval()
>     # Fixed random weights, the same on every machine.
>     gen = torch.Generator().manual_seed(7)
>     for m in net.modules():
>         if isinstance(m, (nn.Conv2d, nn.Linear)):
>             std = 1.6 / m.weight[0].numel() ** 0.5
>             nn.init.normal_(m.weight, std=std, generator=gen)
>             nn.init.zeros_(m.bias)
>     net = net.to(device)
>     return net.half() if device == "cuda" else net
>
>
> def latent(req: LavaRequest) -> np.ndarray:
>     """The seed's path: 64 slow sine waves, at time t."""
>     rng = np.random.default_rng(req.seed)
>     freq = rng.uniform(0.05, 0.6, LATENT)
>     phase = rng.uniform(0, 2 * np.pi, LATENT)
>     return 1.5 * np.sin(freq * req.t + phase)
>
>
> @torch.inference_mode()
> def render(net, requests, device) -> np.ndarray:
>     """One forward pass: uint8 (B, 256, 256, 3)."""
>     dtype = next(net.parameters()).dtype
>     z = np.stack([latent(r) for r in requests])
>     rgb = net(torch.from_numpy(z).to(device, dtype))
>     w = [r.warmth for r in requests]
>     warm = torch.tensor(w, device=device, dtype=dtype)
>     warm = warm.view(-1, 1, 1, 1)
>     red = 0.75 + 0.5 * warm   # warm frames lean red
>     green = torch.full_like(warm, 0.95)
>     blue = 1.25 - 0.5 * warm  # cool frames lean blue
>     tint = torch.cat([red, green, blue], dim=1)
>     rgb = (rgb * tint).clamp(0, 1)
>     out = (rgb * 255).round().to(torch.uint8)
>     out = out.permute(0, 2, 3, 1).contiguous()
>     return out.cpu().numpy()
> ```

This model keeps no state for a session. Each request carries everything the model needs. When
your model keeps state for each session, see [Keep state for each session](#keep-state-for-each-session).

**3. Write the application half**

The application half is a normal `ReactorApp`, with one change. It holds a `ModelClient` in
place of the model, and `generate()` calls `step()` on the client.

```python lava.py theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}}
from pathlib import Path

from lava_types import LavaFrame, LavaRequest
from reactor_runtime import (
    InputField,
    InputState,
    Output,
    ReactorApp,
    StepOutcome,
    Video,
    session_started,
)
from reactor_runtime.model_server import ModelClient

FPS = 24


class LavaOutput(Output):
    main_video: Video


class LavaState(InputState):
    seed: int = InputField(
        default=1, ge=0, le=2**31 - 1,
        description="Which scene to show.",
    )
    speed: float = InputField(
        default=1.0, ge=0.0, le=8.0,
        description="Scene speed.",
    )
    warmth: float = InputField(
        default=0.5, ge=0.0, le=1.0,
        description="Colour grade.",
    )
    _t: float = 0.0  # private: clients never see it


class Lava(ReactorApp):
    state: LavaState
    fps = FPS

    def load(self, config_path: Path | None) -> None:
        self.model = ModelClient.connect(
            on_lost=self.crash
        )

    @session_started
    def begin(self) -> None:
        self.model.reset()

    async def process_input(self) -> LavaRequest:
        s = self.state
        request = LavaRequest(
            seed=s.seed, t=s._t, warmth=s.warmth
        )
        s._t += s.speed / FPS
        return request

    def generate(self, input: LavaRequest) -> LavaFrame:
        return self.model.step(input)

    async def process_output(
        self, outcome: StepOutcome
    ) -> LavaOutput:
        if outcome.error is not None:
            raise outcome.error
        return LavaOutput(main_video=outcome.result.frame)
```

Three calls do the work:

* `ModelClient.connect()` in `load()` waits until the model server is ready. `on_lost=self.crash`
  ends the session runtime if the link to the model server breaks while no step runs.
* `self.model.reset()` in the `@session_started` hook gives each new session a clean start on
  the model server. Until the application calls it, `step()` raises `ResetRequired`.
* `self.model.step(input)` sends this session's request and waits for its result.

The runtime builds a fresh `LavaState` for each session, so `_t` starts at 0 every time.

**4. Name the model server in reactor.yaml**

Name your `ModelServer` in `runtime.model_server`, and set the number of sessions in
`model.resources.sessions.count`. List the dependencies in `requirements.txt`. Both halves run
from the same image.

```text requirements.txt theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}}
numpy
torch>=2.4
```

```yaml reactor.yaml theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}}
$schema: reactor/v2

model:
  name: your-org/lava
  resources:
    sessions:
      count: 4  # four sessions share the model server

runtime:
  import: lava:Lava
  model_server:
    import: lava_model:LavaModel

build:
  runtime_version: "3.12.0"
  cuda_version: "12.9.1"
```

The `sessions` block has defaults for everything else, and they fit most models. A session's
CPU, memory and shared memory are in the
[reactor.yaml reference](https://docs.reactor.inc/deploy/platform/reactor-yaml.md#modelresourcessessions), if a step
ever reports that it needs more.

**5. Deploy and test**

Deploy from the folder, as you deploy any model. The first deploy names the GPU; later deploys
keep it:

```sh theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}}
reactor deploy production --gpu NVIDIA_B200x1  # any GPU type your account can use
```

The deploy builds the folder's code and sends `model.resources.sessions` as the sessions of the
environment it deploys, so each environment, such as staging, can serve its own number.

Each instance runs one model server and four session runtimes. Reactor sends each new session to
a free session runtime. To test, connect several clients at the same time, as in the
[quickstart](https://docs.reactor.inc/deploy/development/quickstart.md#connect-a-client). Then read the model's logs:

```sh theme={"theme":{"light":"github-light","dark":"github-dark-high-contrast"}}
reactor logs production --follow
```

The `mean batch size` lines come from `LavaModel.step()`. Here they show 1.00, because the
sessions take turns.

Lines that your model logs from `step()` name no session. Read them in the model's logs, as
above, not in the view of one session (`--session`).

## Choose the number of sessions

Every session needs a frame in each frame period. At 24 frames per second, the period is about 42
ms. The sessions take turns, so with N sessions, a session can wait for N steps for its frame. Keep N
step times under the frame period.

1. Measure how long one `step()` takes.
2. Find the largest N that meets the rule above. Also make sure the session runtimes fit in the
   instance's CPU and memory.
3. Set `model.resources.sessions.count` to N.
4. Deploy, connect that many clients, and read the logs.

If N comes out small, check whether your model can batch. A batch serves several sessions in about
the time of one step. See [Batch requests](https://docs.reactor.inc/deploy/development/reactor-app/batching.md).

## What a failure ends

| What fails | What happens |
| - | - |
| `step()` returns an exception in place of one output | That session's `process_output()` gets the exception. The other sessions in that step get their results. |
| `step()` raises, or returns the wrong number of outputs | Every session in that step gets a `BatchFailed` that carries the error. The model server keeps serving. |
| A step gets no answer in time | That session gets a `StepTimedOut` error after 30 seconds by default. The link stays up. |
| The model server stops, or the deployment restarts it | Every session runtime gets `ModelServerLost`. A session runtime with no step running gets it through `on_lost`. When your application re-raises it, the session runtime ends. The deployment restarts it, and it waits in `load()` for the model server. |

The example re-raises every error in `process_output()`, so a failed step ends its session. To
recover from an error your model knows, handle that error in `process_output()` and re-raise the
rest.

The model server already reports itself unhealthy when a step stops making progress, and the
deployment then restarts it. To report your model's own failures as well, override `health()` on
your `ModelServer` and return a `Health` from `reactor_runtime.core`. It runs on the health check's
thread, so keep it quick and do not block on the step.

## Keep state for each session

A model that keeps state for each session, such as a cache, stores that state by slot. Each request
has a `slot`, from 0 to the number of sessions minus one, and a `generation`. The generation changes
when a session runtime connects and at every reset. Two hooks run between steps, on the same thread
as `step()`:

* `session_opened(slot, generation)` sets up the state for a slot. It runs when a session runtime
  connects, and again at every reset.
* `session_closed(slot, generation)` drops that state. It runs when a session runtime disconnects,
  and before a reset opens the slot again.

So the state of a session that ended stays until the next session on that slot resets, or until the
session runtime disconnects.

## Next

> [card] [Batch requests](https://docs.reactor.inc/deploy/development/reactor-app/batching.md)
>
> Step several sessions together in one forward pass.

> [card] [Writing a good model](https://docs.reactor.inc/deploy/development/reactor-app/application-and-model.md)
>
> The application and model halves, and the rules that keep them apart.

> [card] [reactor.yaml reference](https://docs.reactor.inc/deploy/platform/reactor-yaml.md#modelresourcessessions)
>
> Every key of `model.resources.sessions` and `runtime.model_server`.

> [card] [Multi-GPU inference](https://docs.reactor.inc/deploy/development/distributed-workers.md)
>
> Run one session across several GPUs, the opposite direction.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.