Auditing Hidden Drift in AI-Generated Training Code

    ML training that starts cleanly and shows a falling loss is not proof that the run matches the research plan. AI coding tools often emit complete training scripts that still deviate in sampling mix, conditioning updates, or embedding cache placement. This article explains why logs miss those silent mismatches and how to catch them with checkable specs, counters, asserts, and short controlled ablations before a long run.

    Machine learning training burns compute and time once it starts. A script that launches and a slowly falling loss do not mean the implementation matches the research plan. AI coding tools are good at producing structurally complete, well-commented training scripts, and equally good at drifting on details: the write-up describes one recipe while execution follows a more expensive or weaker learning signal. These mismatches raise no exception. They show up as slower convergence, weak high-resolution quality, or broken conditioning. The goal of review is not to reject generated code, but to align plan, documentation, implementation, and metrics, and to stop hidden drift before a full-length run.

    Why training logs miss the drift

    Training stacks trust the combination of data loaders, optimizers, and the forward pass. If tensor shapes match and the loss backpropagates, the job is treated as a success. The three issues below all satisfy that surface condition.

    First, sampling frequency is silently lowered. The plan may require multi-resolution joint training so high-resolution samples enter each stage at an agreed rate. Generated code may describe that rate correctly in comments while the sampler or dataset wrapper uses different weights, filters, or stage-switch logic. High-resolution batches become rare; low-resolution loss dominates updates. Total steps look large while effective high-resolution steps stay too small, so quality lags a correctly implemented control.

    Second, conditioning that should update layer by layer is frozen. Text or other side information may need to be injected across layers and participate in optimization, yet the implementation marks the condition branch as non-differentiable, wraps it in stop-gradient, or caches it after the first forward and disconnects it from parameters. The forward pass still “sees” the condition; backward barely updates the relevant layers. The model behaves like an unconditional or weakly conditioned model, while logged loss can still drop because unconditional reconstruction fits part of the data.

    Third, embeddings that should be cached are recomputed inside the training loop. If text embeddings can be computed offline or at startup, they should not be rebuilt on every micro-batch and every gradient-accumulation step. A faulty implementation leaves the encoder inside the step loop and multiplies forward cost with accumulation. The job still finishes, but throughput falls. If the encoder is not put in eval/inference mode, extra stochasticity or unnecessary gradients can appear.

    In all three cases, notes and comments agree; the execution path does not. Reading only docs or only the loss curve misses the bug.

    Freeze a checkable plan before reading generated code

    Before inspecting any generated script, write the plan as testable clauses, not adjectives. Each clause should name object, location, frequency, and a failure criterion. For example:

    • Multi-resolution: expected step share per resolution in each training stage, and a threshold below which the run fails.
    • Conditioning updates: which layers receive the condition, whether those parameters are in the optimizer, and whether stop-gradient is allowed.
    • Embedding cache: whether encoding happens outside or inside the loop; with gradient accumulation, the maximum encoder calls allowed per optimizer step.
    • Control experiment: how to interpret metric gaps between a correct implementation and the candidate, on the same data subset and step budget.

    Put clauses in experiment config, not only in chat history. Archive config with the code version. Object storage is appropriate for config, data manifests, and checkpoints; training logs should record actual batch counts per resolution, encoding time, and whether parameters actually update. If you use Baidu AI Cloud, rely only on generic object storage, logging, and monitoring for archive and alerts, and keep judgment in your own check scripts. “It runs in the cloud” is not “the implementation is correct.”

    Check sampling with counts and asserts

    The most useful multi-resolution check is not looking at images; it is counting what actually entered the batch. Add lightweight counters at the loader exit, bucket by resolution, and print or log every optimizer step. After a short run, verify:

    • Relative error between actual and planned shares against a preset tolerance.
    • After a stage switch, whether the high-resolution bucket is still near zero.
    • With gradient accumulation, whether counts are in micro-batches or optimizer steps, and whether mixing the two makes “enough steps” look true while effective steps are not.

    Illustrative check location (framework-agnostic):

    1. def assert_resolution_mix(counts, expected, tol=0.05):
    2. total = sum(counts.values()) or 1
    3. for res, exp in expected.items():
    4. got = counts.get(res, 0) / total
    5. if abs(got - exp) > tol:
    6. raise RuntimeError(f"res {res}: got {got:.3f}, expected {exp:.3f}")

    Also check that docstrings, config, and the sampler cite the same mix. A common generated-code failure is copying the requirement into comments while hard-coding uniform weights or keeping only the lowest resolution. Automated tests should use a tiny dataset so every resolution must appear within a few dozen steps; a zero high-resolution count should fail the test without a full training run.

    Verify that conditioning actually updates

    Inspect both the forward connection and parameter deltas.

    Forward: breakpoint or print at target layers to confirm condition tensor shape, layer index, and injection match the plan, and that the signal is not truncated before those layers. If the plan requires per-layer updates, the condition or the modulation it produces should change across layers, not a single vector computed and frozen at the entry.

    Backward: record the norm change of relevant parameters over a few optimizer steps. A zero delta means the optimizer never touched them, or gradients were cut. You can also temporarily give the condition branch a non-zero learning rate, freeze other branches, and see whether validation metrics respond to condition text. Complete insensitivity points first to stop-gradient, freeze flags, wrong eval/inference mode, or a cached condition that left the graph.

    Do not trust a comment that “the loss is differentiable w.r.t. condition embeddings.” Confirm on the graph that a path exists from embeddings to target-layer parameters, and that those layers are in the optimizer param groups. Freezing is often buried in an obscure branch of initialization while the main loop still calls backward.

    Separate caching from gradient accumulation

    The usual correct boundary for embedding cache is: encoder inputs do not change during training, or they may be reused by sample id. Encoding then belongs outside the loop; results are looked up by id. Gradient accumulation should repeat only the main model’s forward and backward, not non-trainable text encoding.

    Three small checks:

    • Count calls at the encoder entry. If accumulation is K and encoder calls per optimizer step scale like batch-related work times K, the cache is in the wrong place.
    • Profile encoder time vs. backbone time. If encoder share is abnormally high and grows linearly with accumulation, move encoding out of the step loop.
    • Confirm cached tensors are detached from unused graph before reuse, so a constant embedding does not become a rebuilt graph every step (slow and memory-heavy).

    Cache should sit outside the optimizer loop; the accumulation loop only consumes it:

    1. embeddings = encode_once(text_batch) # before training or when a new sample enters
    2. for accum in range(accum_steps):
    3. loss = model(images, embeddings).mean() / accum_steps
    4. loss.backward()
    5. optimizer.step()

    If text changes every step because of augmentation, you cannot pretend to cache; the plan should say “recompute allowed” and cost should be measured separately. Review must distinguish “the plan allows recompute” from “the implementation recomputes on its own.”

    Estimate impact with a minimal control

    After counters and asserts find drift, estimate harm with a short control instead of discarding the whole script on gut feel. Lock data subset, seed, step budget, and eval script; swap only the suspect piece: mix ratios, frozen vs. live conditioning, cached vs. in-loop embeddings. Compare validation loss, condition following, high-resolution sample quality, and throughput. That turns “docs are right, code drifted” into a reproducible engineering fact.

    For long jobs, add periodic checkpoints: re-run mix asserts and parameter-delta checks every fixed number of optimizer steps. Monitoring should alert when mix is out of band, encoding time spikes, or condition-parameter norms stay at zero. Alerts do not replace code review.

    Collaboration habits worth keeping

    Generated code can speed scaffolding, but execution of the research plan should live in testable config and asserts. Before merging a training change, at least complete: a clause list, a resolution-count test, a condition-parameter update test, an encoder-call budget test, and a short control. When docs and code conflict, executable asserts win, and the docs should be corrected so the next generation pass does not copy the wrong comments.

    Moving these checks to submit time costs far less than burning a full budget and then blaming data or architecture. Hidden drift is not a crashed training job; it is the implementation quietly swapping in a weaker problem. Review is asking that problem again, clearly.