Post-Training Engineering for Large Models: Long-Horizon Agents and Code Generation

    This article provides an engineering-focused breakdown of key stages in post-training large language models, with an emphasis on practical, measurable approaches. It covers reinforcement learning with reliable reward signals, long-context training and inference with memory estimation, sandbox design for safe code execution, reproducible evaluation of long-horizon agents, reasoning acceleration via speculative decoding and quantization, and deployment monitoring. All examples are illustrative and require validation on your own hardware and tasks.

    Why Post-Training Is Gaining Attention

    As pretraining scales up, the performance gain per unit of compute diminishes—a widely observed trend. Post-training adapts a base model to follow instructions, complete multi-step tasks, and improve in domains like code and mathematics where correctness can be automatically verified. For developers, the value lies in shaping a foundation model to fit a specific business context.

    Reinforcement Learning: Validate Reward Signals First

    Two major challenges dominate the RL stage: training throughput and reward quality.

    In RLHF, the common Proximal Policy Optimization (PPO) algorithm requires samples from the current policy (or very close to it). If you place old samples directly into an experience replay buffer, policy updates rely on stale data, which can destabilize training. Alternatives include asynchronous sampling, limiting sample staleness, and using Generalized Advantage Estimation (GAE).

    For code and math tasks, rewards can come from unit tests, compilation results, or answer comparison. Such rewards are automatically computable but can be gamed—for example, a model may learn to hard-code test case outputs instead of solving the underlying problem. Consequently, the reward function should be paired with a hidden test set, and generated outputs should be periodically spot-checked by humans.

    Before rollout, verify the following:

    • Sampling throughput (tokens generated per second) matches training throughput to avoid one side waiting on the other.
    • Save checkpoints at fixed intervals so recovery from node failures is possible from the latest checkpoint.
    • Reward accuracy on a hidden test set is close to that on a public test set. A large gap signals overfitting or reward hacking.

    Long Contexts: Estimate Memory First, Then Choose a Strategy

    Supporting long contexts requires work on both training and inference.

    During training, positional encoding extrapolation is a common issue. RoPE variants such as Position Interpolation (PI), NTK-aware scaling, and YaRN can help the model handle inputs longer than those seen in training. These methods typically require continued training on a small amount of long text, and effectiveness must be validated on long-context benchmarks; changing the config alone is often insufficient.

    Attention memory and compute grow with sequence length. FlashAttention uses block-wise computation to reduce memory reads/writes, improving speed and peak memory usage of the attention operation, but it does not reduce KV cache occupancy.

    During inference, the KV cache is usually the dominant memory consumer. Its size can be estimated as follows:

    KV cache bytes = 2 × layers × KV heads × head dimension × sequence length × batch size × bytes per element

    The factor of 2 accounts for both Key and Value caches. Under FP16, each element takes 2 bytes. For example, a model with 40 layers, 8 KV heads, and head dimension 128, processing a single sequence of 32,768 tokens, yields approximately 2 × 40 × 8 × 128 × 32,768 × 1 × 2 bytes ≈ 5.4 GB. Actual usage will also include framework overhead.

    PagedAttention divides the KV cache into fixed-size blocks and allocates them on demand, similar to paged memory in operating systems. This reduces fragmentation and increases the number of concurrent requests. Inference frameworks like vLLM implement this idea.

    Sandbox Environment: Isolation and Resource Limits First

    Agent training and evaluation require executing code, making the sandbox a critical security boundary. Common practices include:

    • Use containers or lightweight virtual machines to isolate execution. For untrusted code, lightweight VMs typically provide stronger isolation than standard containers.
    • Disable external network access by default; open outbound connections only to whitelisted domains.
    • Run as a non-root user, mount dependency directories read-only, and expose only necessary writable paths.
    • Set limits on CPU, memory, disk, and per-execution wall-clock time to prevent infinite loops or memory leaks from saturating a node.
    • Sanitize secrets and personal information in training data and logs; real credentials should never be baked into the environment image.

    Monitor sandbox startup time, timeout rate, abnormal exit rate, and average resource usage. These metrics help determine whether a problem originates from the model, the environment, or the scheduler.

    Evaluating Long-Horizon Agents: End-to-End and Reproducible

    Reproducibility of agent evaluation depends on a fixed environment. A recommended workflow:

    1. Build a versioned environment image for each task, locking dependency versions.
    2. Document the initial state, allowed tools, and completion criteria for each task.
    3. Run predefined test commands and record pass/fail, number of steps, tool calls, and total time.
    4. Save complete trajectories for later review.
    5. Categorize failures by type rather than only looking at overall pass rate.

    Common failure types can be diagnosed with the following table:

    Failure Type Typical Symptom Common Cause Debugging Approach
    Environment failure Dependency installation error Image version drift, network restrictions Pin image and dependency versions
    Tool call failure Parsing error in return format Inconsistent tool output formats Unify return structures and add validation
    Context overflow Early information lost mid-trajectory Trajectory too long Use summarization or segmented memory
    Misjudgment Tests pass but functionality is wrong Insufficient test coverage Add edge-case tests
    Timeout No output for an extended period Infinite loop or waiting for input Set step and time limits

    Inference Acceleration: Estimate Gains with Formulas

    Speculative decoding uses a small draft model to generate several candidate tokens, then a larger target model verifies them in one forward pass. Let α be the acceptance probability per candidate token and k the number of drafted tokens per round. The expected number of tokens accepted per verification step is:

    E = (1 − α^(k+1)) / (1 − α)

    For example, with α = 0.8 and k = 4, E ≈ 3.36. The draft model itself adds compute overhead, so real speedup must be measured on actual workloads. Acceptance rates depend on how closely the draft model’s distribution matches the target model’s, and can vary significantly across domains.

    Low-precision inference also requires validation. INT8 or FP8 typically reduce memory usage and improve bandwidth utilization, but accuracy loss depends on the model and task. Before deploying, compare quantized and unquantized results on your own evaluation set.

    Technique Primary Benefit Primary Risk Suitable Conditions
    Speculative decoding Lower per-token latency Limited benefit if acceptance rate is low Draft model closely matches target model
    INT8 quantization Lower memory and cost Accuracy degradation on certain tasks Reliable evaluation set available
    FP8 quantization Speedup on supported hardware Depends on hardware and framework support Hardware natively supports FP8

    Deployment and Monitoring

    The model can be accessed via API, IDE plugin, or an internal workbench. Recommended metrics to monitor during deployment: time-to-first-token (TTFT), time-per-output-token (TPOT), P95 latency, error rate, and per-task cost. Logs must be sanitized, avoiding the storage of user code containing sensitive information.