Post-Training Optimization for Long-Horizon Agents: An Engineering Playbook
This article provides a vendor-neutral engineering playbook for teams performing post-training on large models and preparing long-horizon agents for production. It covers baseline measurement, overlap scheduling for rollout and training, sandbox reliability checks, long-context inference scheduling, acceptance criteria, and a practical debugging checklist. All recommended thresholds are starting points that must be recalibrated on your own hardware, models, and data.
This article is written for engineering teams working on post-training of large models and preparing long-horizon agents for production deployment. It covers general methods only and does not depend on any specific vendor’s product. All numerical values in this article are starting points for inspection; actual thresholds must be re-measured on your own hardware, models, and data.
1. Measurement and Throughput Baseline
Reinforcement learning training typically consists of two phases: rollout, where the model generates samples using the current policy, and training, where reward signals are used to update parameters. If these two phases wait on each other, GPU cycles are wasted. The first step to improving throughput is measurement, not directly modifying code.
1.1 Fields to Log Each Step
| Field | Meaning | Unit | Collection Frequency |
|---|---|---|---|
| t_rollout | Time spent on sampling | seconds | per step |
| t_reward | Time spent on reward computation | seconds | per step |
| t_fwdbwd | Time spent on forward and backward passes | seconds | per step |
| t_sync | Time spent on parameter synchronization | seconds | per step |
| t_replay_io | Time spent writing and reading replay data | seconds | per step |
| t_step | Total duration of a single step | seconds | per step |
| gpu_util | GPU utilization | % | 1 second or shorter |
Calculate the proportion of each segment relative to t_step. Optimize the segment with the largest share first.
1.2 Statistical Methodology
- Measurement window: Collect 50 consecutive steps of steady-state data as a starting point, skipping the first 10 steps of cold start.
- Report median and P95, not just the mean.
- Average GPU utilization alone can mask periodic idle periods. Also save a utilization time-series chart and check whether the valleys occur at fixed intervals.
- Fix the random seed during measurement and disable unrelated monitoring. Repeat each configuration at least 3 times and take the median.
1.3 Baseline Checklist
- All fields are logged and can be exported per step
- Cold start and steady state are distinguished
- Hardware, framework version, model size, batch size, sequence length, and samples per step are recorded in the experiment log
- Utilization time-series chart is saved
Example for illustration: a hypothetical experiment uses 8 GPUs of the same model, a 7B-parameter model, a batch of 64 trajectories, a maximum sequence length of 4096, and 4 sampling rounds per step. These configurations are for documentation purposes only; the values should not be carried over to your environment directly.
2. Overlap Scheduling for Rollout and Training
2.1 Overlap Ratio Definition
Overlap duration = max(0, t_rollout + t_train − t_step)
Overlap ratio = overlap duration / min(t_rollout, t_train)
If the two phases are fully serial, the overlap duration is 0 and the overlap ratio is 0. If the two phases are fully pipelined, the overlap ratio approaches 1. Here t_train refers to t_fwdbwd plus the data loading time on the training side.
2.2 Asynchronous Queue Implementation
The rollout side writes trajectories into a bounded queue, and the training side consumes data from the queue. Each sample must carry the policy version number under which it was generated. The training side checks the staleness of each sample; samples that exceed the allowed staleness threshold are discarded or down-weighted.
| Parameter | Meaning | Suggested Starting Point |
|---|---|---|
| queue_capacity | Queue capacity, in number of batches | 2 to 4 |
| max_staleness | Max number of policy versions a sample may lag behind | Start at 1; tune based on evaluation results |
| put_timeout_s | Write timeout | Set based on the P95 rollout duration |
| get_timeout_s | Read timeout | Set based on the P95 training duration |
An oversized queue increases stale samples and may undermine training stability. When a timeout occurs, log it and fall back to serial mode according to a predefined policy.
2.3 Acceptance Criteria
- The median overlap ratio is higher than before the change.
- The reward curve and evaluation metrics stay within reasonable variance from baseline.
- A queue that is persistently full or persistently empty indicates a mismatch between production and consumption rates; adjust capacity or concurrency accordingly.
3. Sandbox Inspection Process
Agent tool calls often execute code, read/write files, or access the network inside a sandbox. Sandbox reliability directly affects training data quality.
3.1 Least Privilege
- External network access is denied by default. Domains that require access are placed on an allowlist.
- Only mount the directories required for the task, preferably as read-only.
- Do not inject production secrets into the sandbox. Secrets are delivered on demand via environment variables or a key management service, never written into code or logs.
- Allocate dedicated CPU, memory, and disk quotas for each sandbox, and set an execution timeout.
3.2 Data Isolation
- Training data, evaluation data, and sandbox runtime data must be stored in separate directories.
- Evaluation sets must not be mixed with training data, or evaluation scores will be misleading.
3.3 Checklist
- Network policy is verified: requests outside the allowlist are rejected
- Processes are reaped after timeout; no residual processes remain
- Audit logs record commands, exit codes, and durations without sensitive information
- When resource quotas are triggered, a clear error code is returned
- Sandbox timeout rate, abnormal exit rate, and policy-blocked count are included in daily reports
4. Long-Context Inference Scheduling
4.1 Bucketing by Sequence Length
Mixing long and short requests in the same batch causes padding waste, and short requests can be slowed down by long ones. Bucketing requests by sequence length and then batching within each bucket typically reduces this waste.
4.2 KV Cache Budget
KV cache occupancy grows linearly with sequence length and concurrency. Estimate before deployment:
KV cache per request ≈ 2 × num_layers × num_kv_heads × head_dim × seq_len × bytes_per_element
This is an approximation; measure actual usage with your framework.
4.3 Scheduling Parameters
| Parameter | Meaning | Suggested Starting Point |
|---|---|---|
| max_seq_len | Maximum length per request | Set based on the P99 of the task length distribution |
| max_concurrency | Number of concurrent requests | Start with a limit that keeps memory usage under 85% |
| prefill_chunk | Prefill chunk size | Tune based on latency targets |
5. Acceptance Metrics and Common Issue Debugging
5.1 Acceptance Metrics
| Metric | Definition | Pass Condition |
|---|---|---|
| step_time P50 / P95 | Steady-state step duration | Median decreases; P95 does not worsen |
| gpu_util_mean | Steady-state mean utilization | Higher than baseline |
| overlap_ratio | See Section 2.1 | Median meets the team’s predefined target |
| sandbox_timeout_rate | Timeouts divided by total calls | Below the predefined ceiling |
| task_success_rate | Success rate on a fixed evaluation set | Not below baseline minus the predefined tolerance |
When comparing before/after results, use the same random seed, the same data window, and the same evaluation set.
Rollback condition: if any quality metric declines across multiple consecutive evaluations beyond tolerance, roll back immediately to the previous stable configuration. Keep logs from both versions for comparison.
5.2 Common Issue Debugging
Periodic GPU idle
- Inspect the utilization time-series chart to see whether valleys coincide with checkpoint saving or evaluation cycles.
- Check whether evaluation and checkpointing block the main training loop; move blocking parts to asynchronous execution.
Replay write is the bottleneck
- Compare the share of t_replay_io. If it is high, inspect the serialization format, compression method, and storage backend IOPS.
- Merge small files and switch to batched writes.
Parameter synchronization blocks progress
- Check whether synchronization is full-state. Prioritize sharded or incremental sync.
- Inspect network bandwidth and sync topology.
Reward computation queuing
- Observe the concurrency and queue length of the reward service.
- Batch reward items that are cacheable or batchable, while retaining timeout protection.
Sandbox timeouts
- First distinguish whether the task itself takes too long or the resource quota is too tight.
- Keep log samples of timed-out tasks and analyze them by category. Do not simply raise the timeout duration.
6. Implementation Order
- Complete measurement first to establish a reproducible baseline record.
- Optimize one item at a time, starting with the segment with the largest share.
- After each change, compare results using the same random seed, data window, and evaluation set before proceeding to the next optimization.
- When all targets are met, run a longer stability test to confirm that the improvement persists over time, and document the final configuration as the new baseline.
