Post-Training and Agent Engineering for Very Large Models

    This article examines practical engineering considerations for post-training and agent systems built on very large models, covering compute efficiency, RL parallelism and communication, long-context KV cache scheduling, sandbox isolation, environment validation, long-horizon terminal task execution, and code-fix agent workflows.

    1. What Post-Training Must Solve

    Pretraining gives a model basic language capability. Post-training then uses reinforcement learning (RL) and instruction data to make the model more stable on code, tool calling, and multi-step tasks. As parameter scale grows, each training run consumes more compute, so teams typically care about two things: whether compute is being used efficiently, and whether the training process is stable.

    Compute utilization can be measured with the following metrics:

    • Tokens processed per second (throughput)
    • GPU utilization; a persistently low value usually indicates that data loading or inter-device communication is slowing training
    • Gradient communication time as a share of single-step training time
    • Headroom between peak memory usage and the memory limit

    These numbers must be recorded under fixed hardware, batch size, and sequence length. Otherwise, results from different configurations cannot be compared directly.

    2. Parallelism and Communication in RL Frameworks

    Large-model training commonly uses three forms of parallelism: data parallelism, tensor parallelism, and pipeline parallelism. Tensor parallelism splits the matrix operations of a single layer across multiple cards. It involves frequent communication and is usually placed between devices connected by high-speed interconnects within the same server. Pipeline parallelism places different layers on different devices. It has lower communication volume but creates idle waiting periods known as bubbles. In practice, first confirm how many parameters and activations fit into a single card’s memory, then decide how to split the workload.

    RL training adds another stage: the model first generates trajectories, then computes rewards and updates the policy. Generation and training have different resource requirements. If they share the same set of devices, switching between them incurs additional overhead. A common approach is to schedule generation and training separately and return generation results asynchronously in batches.

    When tuning parameters, use the following checklist:

    1. Validate whether the reward function truly reflects the target on a small-scale model before scaling up.
    2. Fix random seeds, record the reward curve for each version, and record KL divergence when using KL constraints.
    3. Tune the learning rate and gradient clipping threshold separately, changing only one variable at a time.
    4. If reward rises but evaluation scores fall, first suspect reward hacking rather than assuming training has succeeded.
    5. Save checkpoints and record the data version corresponding to each checkpoint.

    3. Memory and Scheduling for Long-Context Inference

    When supporting very long contexts, the main pressure comes from the KV cache. KV cache memory usage grows linearly with sequence length. The larger the batch and the longer the context, the higher the usage. Common methods for reducing pressure include:

    • Managing the KV cache with paging to reduce memory fragmentation
    • Reusing the KV cache for shared prefixes, such as when the same system prompt is requested multiple times
    • Scheduling by input length buckets so short requests are not slowed down by long requests
    • Applying queuing or rejection policies to requests that exceed the memory budget instead of letting the inference process crash

    The scheduling system needs to estimate memory requirements based on the number of input tokens. If the estimate is too low, a request may trigger out-of-memory during execution. If the estimate is too high, device utilization drops. Both cases should be calibrated through load testing on real traffic.

    When evaluating long-context capability, do not look only at the maximum window length. Measure time to first token, tokens generated per second, and accuracy at locating key information in long text across different length ranges.

    4. Sandbox Infrastructure and Environment Quality Checks

    Agents need to execute commands, modify files, and access networks in real environments, so the sandbox is the core of the security boundary. When choosing a sandbox approach, compare the following dimensions:

    • Isolation strength: containers, microVMs, and independent virtual machines provide increasing isolation, with increasing startup overhead.
    • Startup latency: long-horizon tasks create environments frequently, so slow startup reduces overall efficiency.
    • Snapshots and rollback: whether a snapshot can be saved before a critical step and quickly restored after a failure.
    • Network policy: deny external network access by default and allow only whitelisted domains.
    • Auditability: record every command, file change, and network request for later tracing.

    Basic security requirements include:

    • Run the sandbox as a non-root user and mount only the directories required by the task.
    • Do not write secrets into images or code. Inject them through short-lived tokens and limit their permission scope.
    • Operations such as deletion, overwriting, and permission changes require secondary confirmation or should be blocked directly at the policy layer.
    • Destroy the sandbox after the task ends to avoid data residue.

    An environment quality-check platform validates before and after agent actions. Before an action, it checks whether dependencies are complete, whether target files exist, and whether the workspace is clean. After an action, it runs tests, checks whether coverage has decreased, and checks for new warnings. These checks reduce invalid trial and error, but they also add latency, so they should be placed only at key checkpoints rather than executed at every step.

    Risk note: if the quality-check scripts themselves are defective, they can produce incorrect pass results. Quality-check rules need version control and should be validated regularly with known bad samples.

    5. Execution and Evaluation of Long-Horizon Terminal Tasks

    Terminal tasks require an agent to understand the goal, decompose steps, call tools, and correct operations based on error messages. A practical execution flow usually includes:

    1. Read the task description and list the conditions that must be satisfied.
    2. Inspect the current environment state, such as directory structure, dependency versions, and service status.
    3. Execute only one command at a time with a clear expected result.
    4. Check the output. If it does not match expectations, record the reason, then decide whether to retry or adjust the plan.
    5. After reaching the retry limit or timeout, stop execution and report failure.

    When evaluating this type of agent, record the following metrics:

    • Task success rate: the proportion of tasks completed successfully on an independent test task set.
    • Average steps: the number of tool calls required to complete a task.
    • Per-step retry count: the number of repeated attempts for the same step. Exceeding the limit should be judged as failure directly.
    • Timeout rate: the proportion of tasks that exceed the time budget.

    Common failure cases include:

    • Context forgetting: a path or configuration determined earlier is forgotten in later steps, leading to repeated operations.
    • Over-modification: unrelated files are changed in order to fix one error.
    • False success: a command returns code 0, but the result is incorrect because the output content was not checked.
    • Retry loops: the same error is retried repeatedly without changing strategy.

    To address these issues, require the agent to write the expected result at each step and compare it after execution; set a whitelist for tool calls; and keep key decision records in the state to avoid forgetting early information during long tasks.

    6. Code-Fix Agent Workflow

    Code repair is a typical long-horizon agent scenario. The pseudocode below shows the basic setup for a retry cap, timeout, and rollback:

    1. # Pseudocode: code-fix agent with a retry cap and rollback
    2. MAX_RETRIES = 3
    3. STEP_TIMEOUT_S = 300
    4. def code_fix