Technical Practices for Large-Scale Foundation Models in Agentic Programming

    This article explains how coding assistants are moving from code completion toward agentic engineering, in which a model plans tasks, acts in a sandbox, runs tests, and fixes failures in a verifiable loop. It covers architecture choices such as sparse attention, long context, multi-token prediction, and sparse activation. It also covers training with asynchronous reinforcement learning, data curation, evaluation methods, and cloud deployment for an agent sandbox platform.

    Technical Practices for Large-Scale Foundation Models in Agentic Programming

    1. Background: Coding Assistants Move Toward Agentic Engineering

    Until recently, the main value of coding models centered on code completion, function generation, error explanation, and single-turn question answering. These capabilities can noticeably improve a developer’s local productivity. However, developers still have to break down tasks, provide context, run commands, check results, and correct the direction. This can be called “intuitive coding”: a developer describes intent in natural language, the model returns a code snippet, and validation and integration remain manual work.

    When models gain long-context understanding, tool calling, terminal operation, multi-turn reflection, and result verification, programming shifts further toward “agentic engineering.” The core of agentic engineering is not having the model write more code at once. Instead, the model completes a verifiable engineering loop in a controlled environment. It understands the task, makes a plan, reads the codebase, modifies files, runs tests, analyzes failure causes, iterates on fixes, and produces a reviewable change summary.

    This shift raises the requirements for foundation models. They need strong code understanding and generation, along with stable long-context management, tool use, structured output, and self-correction. Training and evaluation must also move from single-problem code generation to multi-step task completion. This article covers architecture design, capability building, training frameworks, evaluation methods, and engineering deployment, and it offers a set of reusable technical practices.

    2. Architecture Design: Sparsity, Long Context, and Multi-Token Prediction

    1. Sparse attention: balancing scale and efficiency

    Large foundation models in coding and agent scenarios often process very long code files, logs, test reports, and results from many rounds of tool calls. With full attention, growing context length creates significant compute and memory pressure. Sparse attention lets each token attend to only a subset of key positions. This preserves long-range dependencies while reducing computational complexity.

    In engineering, sparse attention requires attention to three points. First, sparse patterns should fit code structure, such as function boundaries, bracket nesting, file modules, and call relationships. Second, key information must not be lost to sparsification, such as error stack traces, interface signatures, test assertions, and the most recent modifications. Third, the sparse strategy must work with cache management in the inference framework to prevent cache growth in long-context scenarios. For agent tasks, the model also needs to maintain stable links among tool outputs, historical actions, and the current plan. Therefore, a sparse strategy should not optimize for speed alone. It must also keep task state traceable.

    2. Long context windows: from being able to read to using well

    A 200K-class context window gives a coding agent the foundation to handle large codebases, long logs, and multi-turn tool calls. However, a long context is not the same as an effective context. In practice, teams need a layered context mechanism. System prompts and safety constraints get the highest priority. The task goal and acceptance criteria stay stable. Codebase summaries, interface indexes, and recent changes serve as the working set. Tool outputs are compressed as needed. For past failed attempts, the system keeps the key conclusions rather than the full original text.

    A common mistake is to load all files into the context at once. A better approach first builds a code index, then retrieves relevant files for the task, and finally injects key snippets and call relationships into the context. In each agent loop, the system should update a task state summary. This summary covers completed steps, the current failure point, hypotheses awaiting verification, and the next action. This approach controls token consumption and reduces the risk that the model loses its way in a long context.

    3. Multi-token prediction: improving generation efficiency and structural consistency

    Multi-token prediction lets a model predict several subsequent tokens in one forward pass. This increases generation throughput and helps keep code structure continuous. In code generation, adjacent tokens often have strong constraints, such as indentation, bracket matching, type declarations, and call arguments. Multi-token prediction can reduce local jitter during token-by-token generation and make the output better match syntax.

    Multi-token prediction must also work with the decoding strategy. For code completion, a higher share of parallel prediction can improve speed. For tool call arguments and structured output, stricter validation and fallback mechanisms should remain in place. For steps that require precise reasoning, the model still needs enough room for intermediate reasoning. In engineering, teams should treat multi-token prediction as an optimization for efficiency and stability, not as a replacement for verification. Every generated code change and command must pass sandbox execution, static checks, or tests.

    4. Total and active parameters: trading capacity against inference cost

    Foundation models for complex programming tasks typically have a large total parameter count. This capacity holds code knowledge, tool use patterns, and engineering reasoning. Meanwhile, sparse activation or routing lets each inference activate only part of those parameters. A common trade-off is a total of several hundred billion parameters with tens of billions of activated parameters. This keeps model capacity while controlling online inference cost.

    At deployment, teams should choose configurations based on task type. Code completion and simple Q&A can use a low-latency path. Repository-level changes, terminal tasks, and multi-turn tool calls need more capacity and a longer context. Task routing, batching, caching, and quantization can reduce the cost per task. These methods should not, however, bypass the verification process for critical tasks.

    3. Capability Building: From Code Generation to a Verifiable Task Loop

    1. Code understanding: building a repository-level view

    The first step in agentic engineering is understanding the codebase. The model needs to identify project structure, dependencies, build methods, test entry points, and coding conventions. Context limited to a single file often leads to changes that are locally correct but globally conflicting. Therefore, both training and inference should strengthen the repository-level view. The file tree, module dependencies, interface definitions, call chains, and test coverage information should all be part of the context.

    In practice, teams can first generate a lightweight index of the codebase. The index includes file summaries, exported symbols, key classes, and function signatures. When an agent receives a task, it first retrieves relevant modules and then reads only the necessary snippets. After a change, the agent verifies the scope of impact through static checks, unit tests, and diff review. This turns code generation into code change management.

    2. Tool calling: making model actions executable and observable

    Agents need to call tools for the file system, terminal, test frameworks, version control interfaces, and log queries. Tool design should follow the principles of least privilege, structured parameters, explicit return values, and rollback capability. Each tool should define a clear input schema, output schema, and error types, so the model does not depend on ambiguous natural-language returns.

    For example, a file modification tool should return a change summary and a diff. A terminal execution tool should return the exit code, standard output, standard error, and elapsed time. A test tool should return the pass rate, failed cases, and a stack trace summary. The model decides the next action based on these structured results rather than guessing what happened. As the number of tool calls grows, audit logs and permission boundaries become more important to prevent mistakes from spreading.

    3. Self-correction: extracting reusable signals from failures

    Much of the value of a coding agent comes from its ability to recover after a failure. The model needs to read test failure messages, locate the relevant code, propose a fix hypothesis, run a minimal verification, and adjust its strategy based on the result. To avoid repeating the same mistake, the agent should maintain a failure memory. This memory records attempted changes, failure causes, and hypotheses that have been ruled out.

    During training, asynchronous reinforcement learning or preference optimization can help the model learn effective repair paths. During evaluation, teams should not look only at whether the final result passes. They should also measure the average number of repair rounds, the proportion of invalid tool calls, the regression introduction rate, and how easy the changes are to review. A model that generates large blocks of code in one pass but frequently introduces regressions is not suitable for production engineering.

    4. Training Framework: Asynchronous Reinforcement Learning and Data Scaling

    1. Asynchronous reinforcement learning: improving training efficiency for multi-step tasks

    Agent tasks have long trajectories, slow environment interaction, and sparse rewards. If training waits synchronously for every environment to return, efficiency is very low. An asynchronous reinforcement learning framework decouples environment execution, model inference, and parameter updates. Multiple task environments run in parallel, the model side keeps sampling, and the training side updates in batches. This improves throughput, but it also introduces policy lag, sample bias, and stability issues.

    Engineering this framework requires attention to several points. Teams must control the degree of asynchrony to avoid too many samples from outdated policies. They should apply segment-level credit assignment to long trajectories. They should mask tool call failures, timeouts, and environment exceptions. Rewards should be normalized and clipped. Experiment configurations should remain reproducible. Asynchronous training is not just adding parallelism. Teams need to tune the balance among sample freshness, system throughput, and training stability.

    2. Pretraining data scaling: quality before quantity

    Pretraining data has grown from tens of trillions of tokens, and further expansion can improve coverage of code, documentation, logs, and tool use patterns. However, scaling data must come with quality governance. This includes removing duplicate code, low-quality Q&A, outdated interfaces, and non-executable examples. It also means adding real engineering changes, test fix trajectories, terminal operations, and multi-turn tool call traces. Data should be filtered for licensing and security compliance.

    For coding agents, the data mix is especially important. Code corpora provide syntax and patterns. Engineering documentation provides semantics. Tests and logs provide verification signals. Tool traces provide action strategies. Teams can use curriculum learning to increase task complexity step by step: from single-function fixes to multi-file changes, from static Q&A to terminal execution, and from single tool calls to coordinated multi-tool workflows.

    5. Evaluation: Look Beyond a Single Score

    1. Coding benchmarks: focus on real fixes and regression control

    Public coding benchmarks can measure a model’s ability to fix real issues, but a single pass rate does not fully represent engineering value. A more complete evaluation should include issue localization accuracy, the number of modified files, test pass rate, regression failure rate, average iteration rounds, patch readability, and the time needed for human review. For enterprise scenarios, teams should also add checks for private codebase style, internal framework constraints, and security rules.

    2. Terminal tasks and tool calling: verifying executability

    Terminal task benchmarks test a model’s ability to operate in a command-line environment. Tasks include finding files, installing dependencies, running builds, analyzing logs, and fixing errors. Tool calling evaluations focus on whether the model selects the right tool, fills in parameters correctly, handles returned results, and chains multi-step actions. Browsing and multi-turn interaction evaluations can complement these by measuring information retrieval, state tracking, and the ability to ask clarifying questions.

    Evaluation environments should be as close to production as possible. They should enforce permission boundaries, impose timeouts, include noisy logs, and allow failures and retries. Otherwise, a model may score well in an idealized environment but frequently get stuck in real engineering work.

    3. Business simulation and long-term tasks: observing strategy stability

    Business simulation tests can show how a model manages resources, adjusts plans, and controls risk over long tasks. For these tests, rewards depend not only on single-step correctness but also on long-term gains and stability. For coding agents, teams can design similar long-horizon tasks. Examples include completing a multi-module refactor within a fixed budget, gradually fixing a test suite, maintaining a change log, and controlling regressions. Evaluations should record account balance, resource consumption, the number of failure recoveries, and policy drift, not just the final outcome.

    6. Engineering Deployment: Cloud Sandboxes, Context Management, and a Monitoring Loop

    To build an agentic programming platform on the cloud, teams can combine categories of capabilities from Baidu AI Cloud, including a general container platform, object storage, log service, and monitoring and alerting. These components can support isolated sandboxes, task queues, artifact storage, and an observability system. The sandbox runs code and commands. Object storage holds code snapshots and test artifacts. The log service collects tool call records and failure information. Monitoring and alerting track task timeouts, resource anomalies, and regression risks.

    A workable minimum loop includes task intake, code retrieval, plan generation, sandbox execution, test verification, diff review, and result archiving. Each step should produce structured logs and replayable records. High-risk operations, such as bulk deletion, dependency upgrades, and production configuration changes, should require human approval or a second confirmation.

    The following pseudocode shows an abstract agent loop. It focuses on state updates and the verification loop rather than specific interfaces:

    1. def run_agent_task(task, model, tools, sandbox, max_steps=20):
    2. context = build_initial_context(task)
    3. history = []
    4. for step in range(max_steps):
    5. plan = model.plan(context)
    6. action = model.choose_action(plan, tools)
    7. if not is_safe(action):
    8. context = add_observation(context, "action rejected by policy")
    9. continue
    10. observation = sandbox.execute(action)
    11. history.append({
    12. "step": step,
    13. "action": action,
    14. "observation": summarize(observation)
    15. })
    16. context = update_context(context, action, observation)
    17. context = compress_history(context, keep=["failure", "decision", "diff"])
    18. if model.is_done(context):
    19. result = model.final_answer(context)
    20. if verify(result, sandbox):
    21. return result
    22. return fallback_with_history(history)

    This pseudocode highlights three points: safety checks on actions, structured observations, and mandatory verification before completion. A real system should also add timeout control, retry limits, cost budgets, and a way for humans to take over.

    7. Challenges and Best Practices

    First, long-context management is the central challenge. Teams should combine indexed retrieval, layered summaries, and state memory instead of stacking raw text without limit. Second, tool calls must be observable. Each tool return should be structured, and failures should distinguish environment errors, parameter errors, and task errors. Third, evaluation must cover regressions. Passing only the target tests is not enough. Teams should also check existing tests and static analysis. Fourth, training and inference should stay consistent. The tool protocol, context format, and reward design used in training should match the online agent loop as closely as possible. Fifth, safety boundaries must be built in up front. Sandbox isolation, least-privilege permissions, command allowlists, and audit logs should be implemented at the system level, not left to the model’s judgment.

    8. Summary

    Large-scale foundation models for programming and agent tasks are moving code generation from isolated assistance to verifiable engineering loops. Sparse attention, long context, multi-token prediction, and sparse activation provide the basis for capacity and efficiency. Asynchronous reinforcement learning and high-quality data scaling improve training for multi-step tasks. Evaluations based on coding benchmarks, terminal tasks, tool calling, and long-term tasks help judge real-world usability. In the end, architecture choices, training frameworks, evaluation systems, and the cloud engineering loop must be designed together. Only when a system can execute, verify, roll back, and audit what the model generates does agentic programming deliver real engineering value.