AI Coding Model Training and N-Back Experiment: Code Practice

    This article explains what each training stage of mainstream AI coding models addresses. It then uses an N-Back task to test a model's ability to generate front-end code, and provides corrected core code and an acceptance checklist.

    Mainstream AI coding models are usually trained in several stages. This article first explains the problem each stage addresses. It then uses an N-Back cognitive experiment to test a model’s ability to generate front-end code, and provides corrected core code and an acceptance checklist.

    1. Three Training Stages of AI Coding Models

    1. Mid-Training

    Mid-training sits between general pretraining and later fine-tuning. It has three main goals:

    • Add coding knowledge, so the model becomes familiar with more languages, frameworks, and engineering conventions.
    • Strengthen instruction following and multi-turn interaction, so the model keeps context consistent over longer conversations.
    • Train tool use, such as calling external APIs, running terminal commands, or querying databases.

    This stage also introduces version control data, such as commit history and code review workflows, to help the model understand the full software development process. It does not guarantee that the model will write correct code. The final result still depends on data quality and evaluation methods.

    2. Supervised Fine-Tuning and Reinforcement Fine-Tuning

    Supervised fine-tuning (SFT) trains the model on instruction and response pairs that people write or select. This makes the answer format, problem-solving steps, and code style closer to what developers expect. SFT mainly addresses how answers are presented. It does not directly guarantee that the answers are correct.

    Reinforcement fine-tuning (RFT) samples multiple responses to the same problem and provides several acceptable reference answers. The goal is to increase the diversity of sampled trajectories. If samples always cluster around one way of writing a solution, later reinforcement learning can get stuck in a local optimum. With higher diversity, exploration efficiency usually improves, but the size of the gain depends on the experimental setup.

    3. Agentic Reinforcement Learning

    In this stage, the model completes tasks in an executable environment. The environment gives rewards based on the results, and the model adjusts its behavior accordingly. Two techniques are common in practice:

    • Entropy-guided tree pruning: Merge a large number of generated trajectories into a prefix tree. Then decide which branches to expand first, based on the information entropy and visit frequency of each node. When the compute budget is limited, this directs resources to high-information branches and reduces computation spent on repeated trajectories.
    • Decoupling training from the runtime environment: Separate modules schedule the training logic and the agent’s runtime environment, which reduces the time each waits for the other. This scheduling can reduce GPU idle time, but the benefit depends on cluster size, framework, and network conditions. A fixed utilization figure cannot be given without those conditions.

    2. Testing Code Generation with an N-Back Experiment

    1. Experiment Rules

    The N-Back experiment is commonly used to study working memory. The screen shows one character every second. The participant judges whether the current character matches the one N positions earlier. N is usually 2, 3, or 4. This article uses the task only as a front-end exercise with clearly defined state transitions. It is not used to measure cognitive ability.

    2. Prompt

    We gave the model the following requirement:

    Build an N-Back experiment page. Every second, flash an image, and let the user judge whether the current image matches the image N positions earlier. The image library consists of 10 common Chinese characters: [‘国’, ‘火’, ‘道’, ‘市’, ‘天’, ‘家’, ‘理’, ‘态’, ‘至’, ‘心’]. At the start of each session, the interface must let the user choose N, with three options: 2, 3, and 4.

    Several easily overlooked points apply. Judgment can only begin after the (N+1)th character appears. The labels ‘是’ (yes) and ‘否’ (no) are the text of the interface buttons, so the code must convert them to a boolean before comparing. The same character can only be answered once.

    3. Problems in the First Version

    The first version of the core logic built the basic flow but had three problems:

    • It compared the user’s “是” or “否” string directly with a boolean value, so the judgment result was always wrong.
    • After the timer started, there was no stop or reset logic. Restarting the experiment stacked multiple timers.
    • The same character could be submitted repeatedly, so the score was counted more than once.

    4. Corrected Core Code

    1. const CHARS = ["国", "火", "道", "市", "天", "家", "理", "态", "至", "心"];
    2. const INTERVAL_MS = 1000;
    3. let nValue = 2;
    4. let sequence = [];
    5. let timer = null;
    6. let awaitingAnswer = false; // Whether the current character can be answered
    7. let stats = { correct: 0, total: 0 };
    8. function getRandomChar() {
    9. return CHARS[Math.floor(Math.random() * CHARS.length)];
    10. }
    11. function startExperiment(n) {
    12. if (![2, 3, 4].includes(n)) {
    13. throw new Error("N 只能取 2、3 或 4");
    14. }
    15. stopExperiment(); // Clear the old timer first to prevent stacking
    16. nValue = n;
    17. sequence = [];
    18. stats = { correct: 0, total: 0 };
    19. timer = setInterval(nextTrial, INTERVAL_MS);
    20. }
    21. function stopExperiment() {
    22. clearInterval(timer);
    23. timer = null;
    24. awaitingAnswer = false;
    25. enableAnswerButtons(false);
    26. }
    27. function nextTrial() {
    28. const ch = getRandomChar();
    29. sequence.push(ch);
    30. displayToUI(ch);
    31. // The first N characters have nothing to compare against, so they are not judged
    32. awaitingAnswer = sequence.length > nValue;
    33. enableAnswerButtons(awaitingAnswer);
    34. }
    35. // answer comes from the interface buttons and can only be "是" or "否"
    36. function submitAnswer(answer) {
    37. if (answer !== "是" && answer !== "否") return null;
    38. if (!awaitingAnswer) return null; // Judgment stage not reached, or already answered
    39. awaitingAnswer = false;
    40. enableAnswerButtons(false);
    41. const userSaysMatch = answer === "是"; // Convert the string to a boolean
    42. const current = sequence[sequence.length - 1];
    43. const target = sequence[sequence.length - 1 - nValue];
    44. const isMatch = current === target;
    45. stats.total += 1;
    46. const correct = userSaysMatch === isMatch;
    47. if (correct) stats.correct += 1;
    48. return correct;
    49. }

    The code depends on two functions in the page, displayToUI and enableAnswerButtons, which you need to implement yourself. It works in modern browsers that support ES2015 and later.

    5. Acceptance Checklist

    • Before starting, N can be set to 2, 3, or 4. Any other value raises an error.
    • One character appears every second, randomly chosen from the ten Chinese characters.
    • The first N characters are not judged, and the answer buttons stay disabled.
    • When “yes” is answered, the result is correct if the current character matches the one N positions earlier. When “no” is answered, the result is reversed.
    • Each character can be answered only once. Unanswered characters are not counted in the accuracy rate.
    • On restart, the old timer stops, and the sequence and accuracy reset.

    The sample code covers all six items above. Pause, end conditions, and results display are not implemented, so you need to add them.

    With random generation, the current character matches the Nth character about 1 time in 10. To test model behavior in scenarios with more matches, you need to deliberately raise the match rate during generation.

    6. Research and Privacy Notes

    N-Back experiments involve cognitive assessment. If a page records or uploads response data, inform users first about how the data will be used and obtain their consent. State the retention period as well. The example in this article does not collect or upload any data, and it cannot serve as a diagnostic tool for cognitive ability.

    3. Tool Selection and Usage Advice

    AI coding models can quickly produce a runnable skeleton for small requests with clear boundaries. For an N-Back page like the one in this article, the model can generate most of the main flow. Styling details, abnormal input handling, accessibility, and integration testing in real environments still need to be completed by developers.

    When selecting a model, enterprises can compare three aspects:

    • Data compliance: Open-source models can be deployed locally, keeping code and data inside the internal network. Cloud services require checking their data storage and usage terms.
    • Cost and elasticity: Local deployment requires investment in hardware and operations. Cloud services are billed by usage, which suits teams with fluctuating demand. Verify prices and terms against the official documentation of each cloud provider.
    • Maintenance cost: Model-generated code needs testing and review. The team needs someone responsible for acceptance.

    When writing prompts, include four types of information: business rules, boundary conditions, input and output formats, and acceptance criteria. The more specific the rules, the less likely the model is to miss boundary conditions. However, the first version of the code in this article still had three problems, so testing steps cannot be skipped.