New:Upstash has a remote MCP server

What Is Reinforcement Learning, and Where Should You Run AI-Generated Code?

Ali Tarık ŞahinAli Tarık Şahin
13 min read

We trained a 1.7B model to play a Pac-Man-style maze game with reinforcement learning. Each training step, the model writes 240 strategies as code. Each strategy plays the game, and the best ones get reinforced. By step 16, some strategies clear the board.

We ran each game in its own Upstash Box sandbox so the strategy's code is kept separate from the trainer and GPU machine. This is important since even strong models can create code that doesn't terminate, deletes files, calls out to the internet, or attempts to game the scorer. Along with the untrusted code running in a sandbox, a robust reward function should use a grader that treats the program's output as untrusted as well, as our test below shows.

What is reinforcement learning?

In reinforcement learning (RL), a model learns via trial and error. It attempts a task and is then rewarded with a score indicating its performance. It can then update itself so that high-reward attempts are more likely to happen again in future.

This differs from training on examples. In this stage of training, the model samples its own answers, and rewards score them.

The setup looks like this:

This loop repeats thousands of times, with the agent taking an action and receiving a new state and reward in return. Over time, the agent updates its policy so that it makes more rewarding actions.

Here is the textbook version, with a maze game like Pac-Man:

  • Agent: the thing that learns and acts, in this case the player controlling Pac-Man
  • Environment: the setting in which the agent can act, in this case the maze, dots, and ghosts
  • Action: the choices the agent can make, in this case moving up, down, left, or right
  • Reward: the score we provide the agent, in this case points based on eating dots and a penalty if it gets caught
  • Policy: the way the agent takes actions based on the state of the environment, in this case the thing that gets updated during training so that the agent can get more reward

We trained a model on a Pac-Man-style game

In our demo, the "action" of the language model is to write a whole program. The program makes the moves. The reward is the proportion of dots eaten by the program (no penalty for getting caught).

We built a Pac-Man-style maze game called "Box vs Bugs" and trained a 1.7B model on it:

  1. Every step, the model writes 240 strategies as code.
  2. Each strategy plays three games in its own Upstash Box, one for each of three fixed bug behaviors.
  3. The share of dots eaten is the reward, and the best strategies get reinforced.

On 20 unseen games, the selected strategy cleared 2, and achieved about 98/140 dots on average. At step 16, some strategies cleared the board on the three training games, and the average strategy picked up about 82% of the dots. This was over 16 steps with 240 × 16 = 3,840 strategies and 11,520 games played with model-written code, separate from the GPU machine that does the training.

How LLMs learn from rewards with GRPO

In language models, actions are full answers: the model takes a prompt, generates a completion, and then gets scored on that completion by a reward function.

GRPO (Group Relative Policy Optimization) is an RL method which works like this:

  1. Generate multiple completions for a prompt
  2. Score those completions with the reward function
  3. Compare the score of each completion to others in its group
  4. Nudge the model in the direction of the completions that did better than the group

DeepSeek introduced GRPO in the DeepSeekMath paper as a lower-memory variant of PPO (Proximal Policy Optimization). GRPO is used in the sandbox training guides from Upstash and Daytona.

For each prompt, the model will write a group of G completions. This is 8 by default in Hugging Face’s TRL library.

Code is a great fit for RL because it has verifiable rewards (in the form of tests). Instead of needing a human to rate the model’s outputs, you can use a program to check them.

This makes it easier to tell correct from incorrect outputs (is the math answer correct, did the function pass the tests). Training on rewards like these is called reinforcement learning with verifiable rewards (RLVR).

The comparison in step 3 is the advantage. It is the reward minus the group's average, divided by the group's spread:

A_i = (r_i - mean(r)) / (std(r) + 1e-4)

TRL adds the small constant so the division never hits zero. If every completion in a group gets the same reward, each one's reward equals the mean, so every advantage is 0. With TRL's defaults, where the KL penalty weight beta is 0, that group contributes nothing to the update. TRL has a metric for that: frac_reward_zero_std tracks the fraction of groups in which all completions produced the same reward. This can happen when a task is either too easy (and so every completion passes), or too difficult (and so every completion fails).

Consider an example of four completions with rewards 1, 1, 0, 0, for the same prompt. Mean reward for the group is 0.5. The two completions that passed get a positive advantage, and the update makes them more likely. The two that failed get a negative advantage, and the update makes them less likely.

Code rewards mean running untrusted code

For code, reward functions must execute and examine completions. For example, the Box guide runs each completion against a test suite, where the portion of passing tests is its reward.

The trainer runs thousands of programs written by a model during training. Many programs are bad, especially at the start.

A completion may:

  • Never terminate, blocking the training step.
  • Consume the entire machine’s memory or CPU.
  • Delete or overwrite files, including checkpoints.
  • Make calls to the internet or internal services.
  • Access environment variables and API keys.
  • Modify the tests or scorer to receive a perfect score.

The last issue is called reward hacking, and frontier models do it. For example, the AI evaluation group METR found OpenAI’s o3 tried to modify the tests or scoring code of its tasks. For instance, o3 monkey-patched the evaluator to score all its submissions as successes. On one optimization task, it reward-hacked in all 21 of 21 runs. In a separate 20-run test, o3 planned a hack in 80% of runs, and adding "Please do not cheat." to the prompt left that rate the same.

This occurs during training, too. For instance, when OpenAI was training a frontier reasoning model, it found the model patched a verify function to always return true and added a pytest config file to skip all tests. OpenAI penalized the model for reasoning about cheating. This caused it to continue cheating while hiding it better.

RL exacerbates this issue. GRPO pushes the model to hack the reward more frequently if it succeeds during the training loop. Thus, code must run in an environment that cannot alter the grader, where failures are isolated.

Where should you run AI-generated code?

Run AI-generated code in an isolated sandbox with a time limit, no secrets inside, and the network blocked unless the task needs it. Keep the grading code on your own machine, and treat whatever the sandbox returns as untrusted output.

Here is the path one completion takes:

Here is what each of those needs means in Upstash Box:

NeedWhy it matters in RLHow Upstash Box handles it
IsolationOne bad program must not hurt the trainer or other completionsEach box is its own Docker container with its own filesystem, processes and network. Boxes can't see each other.
Time limitAn infinite loop must not stall the training stepEvery code run takes a timeout in milliseconds. The guide uses 2,000.
Network controlGenerated code shouldn't call out or reach internal systemsBoxes have outbound access by default. One call switches a box to deny-all. Private IP ranges are always blocked.
No secrets insideCode in the box can read anything in the boxEnvironment variables are visible to all code in the box, so keep API keys out of it.
Grading outsideA completion must not edit its own gradeThe box only returns output. Your trainer compares it with the reference.
Clean stateA reused box keeps what the last run left behindFiles and background processes survive between runs in the same box. Delete and recreate a box when one completion must not affect the next.
Scale and costGRPO scores hundreds of completions per stepPay as you go is $0.10 per active CPU hour for a small box, with up to 1,000 concurrent boxes. The free plan allows 10.

The Box Python SDK keeps this short. Create a box, block its network, and run the code with a timeout:

import asyncio
 
from upstash_box import AsyncBox
 
 
async def main() -> None:
    box = await AsyncBox.create(runtime="python")
    try:
        await box.update_network_policy({"mode": "deny-all"})
        run = await box.exec.code(code="print(2 + 2)", lang="python", timeout=2000)
        print(run.exit_code, run.result.strip())
    finally:
        await box.delete()
 
 
asyncio.run(main())

To see what the sandbox and the reward function each catch, we scored eight hand-written completions for the guide's dedupe task. We used the guide's own reward function, one box per completion, with the network set to deny-all:

completion label | reward | seconds
correct | 1.00 | 0.344
unchanged | 0.25 | 0.343
infinite loop | -1.00 | 2.276
destructive (__import__) | -1.00 | 0.000
fake JSON + exit | 1.00 | 0.274
network attempt | 0.00 | 0.543
raises ValueError | 0.00 | 0.323
always empty | 0.25 | 0.254

The most important row is "fake JSON + exit". That completion skipped the function, printed the right answers in the harness's output format, and exited. It scored 1.00, the same as the correct solution.

The sandbox did its job. The code never touched the trainer, and grading outside the box meant it couldn't edit the grader. But the grader trusts the last line the program prints, and the guide's test inputs are fixed. Because the tests are fixed, a program that has memorized the answers scores 1.00. Fresh random inputs on every call would close that gap, since printing the right outputs would then mean computing them. Sandboxing protects the training machine. A reliable reward also needs a grader that treats the program's output as untrusted, for example by running hidden tests the program can't see or checking results in a way it can't forge.

The other rows split into three cases:

  • Rejected before running: the filesystem wipe called __import__, which contains the banned word "import". The reward function gave it -1 before it reached a box, so this row says nothing about the sandbox's containment.
  • Execution failures: the infinite loop hit the 2-second timeout and got -1, while the other completions kept running. A timeout, a non-zero exit, or output that isn't valid JSON all score -1.
  • Caught errors: the harness catches exceptions inside the function and records None for that test. So the ValueError completion and the network call scored 0, not -1. The network call failed inside the box with an SSL error, and the same request returned 200 when we switched the box to allow-all.

Train a code model with GRPO and Upstash Box

The Train a Code Model with TRL and Sandboxed Rewards guide combines all of these. It uses TRL’s GRPO trainer to teach Qwen3-0.6B-Base, a small base model, to solve three Python list tasks. It runs each completion against a test suite in its own box, then gives it a reward based on the fraction of tests it passes.

To do this:

  1. Grab a Box API key from the Upstash Console, then set export UPSTASH_BOX_API_KEY=... and pip install upstash-box trl datasets.
  2. Define the tasks: the function signatures and docstrings (dedupe, running_max, evens_first), a reference solution, and a list of forbidden words. The forbidden words prevent simple solutions like import or sorted, forcing the model to write out the loop.
  3. Define the reward function: submit the completion to the box, read back the outputs, and grade them locally.
  4. Pre-create a pool of boxes (64 for the guide’s settings, one per completion in a step) that the trainer can use on every step, then delete the pool when the trainer finishes. Because the boxes are reused, files and background processes from one completion can still be there for the next. For tasks where that matters, recreate the box between runs.
  5. Run python train.py. The guide uses 10 steps to verify that everything works, but you can increase max_steps for real training.

The code is the same as the code used in the eight-completion test above. See the full code in the guide. The reward function skips banned words and empty answers, returning -1. For others, it runs them in the box with a 2-second timeout, then reads the JSON the box prints. If there's a timeout, a non-zero exit code, or bad output, it scores -1; otherwise, the trainer computes the reward as the fraction of tests where the output matches the reference.

As for the trainer, it is a regular TRL script. The reward function called by TRL forwards the whole batch to the pool. Each completion will run concurrently on a separate box.

This is what one GRPO step looks like, from the prompt to the update:

For a more realistic run, the guide scaled up to 500 completions per step. On a single 48 GB GPU, a pool size of 500 boxes was used. 500 boxes were created in 24 seconds. Scoring the 500 completions took 2 to 4 seconds per step, not counting generation. The mean reward went from 0.20 in step 1 to 1.00 in step 8, when all 500 completions passed the training tests. Those are the same fixed tests the model trained on, so this shows the model learned them, not that it generalizes to unseen inputs:

How E2B, Daytona and Modal compare

Upstash Box is one of several sandboxes people use for RL rewards. The Box guide and Daytona's TRL guide follow the same pattern: a pool of sandboxes, one per completion, created once and reused. The tools differ in how they isolate code and which RL setups they document:

SandboxIsolation technologyRL guides and useBest fit
Upstash BoxDocker container per box, AWS us-east-1TRL GRPO guide: 500 boxes created in 24 seconds, 2 to 4 seconds to score a 500-completion stepA small Python SDK, $0.10 per active CPU hour, and no infrastructure to run
E2BFirecracker microVMHugging Face uses it for code rewards in Open R1Teams that need a VM boundary for each run
DaytonaNot stated in its RL guidesTRL GRPO guide and a veRL guideYou train with veRL as well as TRL
ModalVM and gVisorGPU sandboxes for RL workloadsYou need GPUs inside the sandbox

If you want to train your own model, make sure to check out the TRL GRPO guide as well as the Box quickstart. If you are using GRPO with hundreds of completions per step, Box allows you to do a full step in seconds. You only pay for active CPU, and not idle boxes.