ds4 icon indicating copy to clipboard operation
ds4 copied to clipboard

ds4-agent: first generation after /switch can loop on BOS tokens

Open freemanconsulting opened this issue 6 months ago • 2 comments

Bug description

ds4-agent saved-session /switch can restore the saved KV/session successfully, but the first generated answer after the switch often degenerates into repeated BOS tokens (<|begin▁of▁sentence|>). Once that happens, subsequent turns in the same restored session also tend to continue the BOS loop.

This appears to be a generation/runtime boundary problem after /switch, not lost saved-session content. In cases that do not hit the BOS loop, the same saved sessions recall profile-local canaries correctly and preserve silo separation.

Environment

  • Repo: antirez/ds4
  • Commit tested: 8d576642c39b9a2d782a80159ba84ef5a81c0b81
  • Runtime: ds4-agent
  • Backend: CUDA on NVIDIA GB10 / DGX Spark-class machine
  • Model: DeepSeek-V4-Flash-IQ2XXS-w2Q2K-AProjQ8-SExpQ8-OutQ8-chat-v2-imatrix.gguf
  • Launch shape:
DS4_CUDA_DIRECT_MODEL=1 ./ds4-agent \
  --cuda \
  -m /path/to/DeepSeek-V4-Flash-IQ2XXS-w2Q2K-AProjQ8-SExpQ8-OutQ8-chat-v2-imatrix.gguf \
  -c 100000 \
  -n 128 \
  --nothink \
  --trace agent-trace.log \
  -sys "You are running a DS4 first-answer-after-switch regression test..." \
  --prompt-file blank-prompt.txt

Note: my local build carries a small --prompt-file FILE patch for reliable large prompt automation. The failure itself occurs after normal interactive /switch and generation; the prompt-file patch is only how the blank controller session is seeded.

Reproduction shape

  1. Create several saved ds4-agent sessions with profile-local synthetic canaries.
  2. Start a fresh ds4-agent process with a short blank prompt.
  3. /switch <saved-session-sha>.
  4. If prompted Save current session? (y/n), answer n.
  5. Ask a simple profile-local recall question.
  6. Observe first generated token(s).

The synthetic profile test used public sports champion-list filler plus private canaries such as profile slug, codename, curator, review phrase, and checksum. No private data is required to reproduce.

Expected behavior

After /switch, the next assistant generation should continue from a valid assistant boundary and answer the user question from the restored saved session.

Actual behavior

In many fresh-process switch cases, the first generated token is token id 0, text <|begin▁of▁sentence|>, and generation continues emitting token id 0 repeatedly until the generation cap.

Example trace excerpt from a failing first recall:

user="Active profile recall for nfl: answer ACTIVE_PROFILE_SLUG, ARCHIVE_CODENAME, ARCHIVE_CURATOR, INTERNAL_REVIEW_PHRASE, PRIMARY_SOURCE_CHECKSUM."
prefill tool_round=0 transcript=13125 prompt=13125 cached=13080 suffix=45 think=none
token index=1 id=0 bytes=29 text="<|begin▁of▁sentence|>" hex=3cefbd9c626567696ee296816f66e2968173656e74656e6365efbd9c3e
token index=2 id=0 bytes=29 text="<|begin▁of▁sentence|>" hex=3cefbd9c626567696ee296816f66e2968173656e74656e6365efbd9c3e
token index=3 id=0 bytes=29 text="<|begin▁of▁sentence|>" hex=3cefbd9c626567696ee296816f66e2968173656e74656e6365efbd9c3e
...

A passing case against the same type of saved profile looks like:

prefill tool_round=0 transcript=13179 prompt=13179 cached=13133 suffix=46 think=none
token index=1 id=13455 bytes=3 text="ACT" hex=414354
token index=2 id=17640 bytes=3 text="IVE" hex=495645
token index=3 id=71289 bytes=4 text="_PRO" hex=5f50524f

Focused matrix result

A 12-case fresh-process matrix produced 8 BOS-pathology failures:

case_count: 12
first_answer_failures: 8
first_answer_bos_pathologies: 8
second_answer_failures: 8

BOS failure labels:
- fresh-first-nfl-no-list-t128
- fresh-first-nba-no-list-t128
- fresh-first-mlb-no-list-t128
- fresh-first-mlb-with-list-t128
- fresh-first-nhl-no-list-t128
- fresh-first-nfl-no-list-t384
- fresh-first-mlb-warmup-t128
- fresh-first-mlb-no-list-t384

Some variants pass, which is why this looks like a state/boundary edge case rather than an always-broken /switch path.

Observed details:

  • /switch reports success and the saved session token count.
  • prefill reports high cache reuse (cached=<saved session tokens>, small suffix).
  • When generation is normal, profile recall and silo separation are correct.
  • When BOS looping starts, repeating the recall question in the same session also fails.
  • A naive local guard that replaced first-token BOS with ds4_session_argmax_excluding(..., BOS) was not sufficient: the alternate was EOS in at least one case, resulting in empty output. So a proper fix likely needs to inspect the restored prompt/generation boundary or logits/special-token handling more carefully, not just suppress BOS at sample time.

Hypothesis

The restored /switch session appears valid, but the next assistant generation can start from a malformed/ambiguous special-token boundary or stale decode state where BOS is a high-probability next token. Possible fix areas:

  • Normalize/validate the transcript tail after loading a saved session and before appending the next user/assistant prefix.
  • Ensure /switch resets sampler/decode state that should not survive across loaded sessions.
  • Prevent BOS from being emitted as assistant content, but with a better special-token policy than simply falling back to EOS.
  • Add a post-switch internal sanity check around the prompt boundary before first generation.

Happy to provide compact synthetic repro artifacts if helpful.

freemanconsulting avatar May 23 '26 02:05 freemanconsulting

Follow-up from the focused repro/debug run.

I instrumented the first generated token after /switch to dump top logits before sampling. In failing cases the logits were invalid after ds4_session_sync():

first-token-top rank=0 id=-1 logit=-1e+30 logprob=-1e+30 text=
...
first-token-top rank=15 id=-1 logit=-1e+30 logprob=-1e+30 text=
first-token-sampled id=0 text=<|begin▁of▁sentence|>

Passing cases had sane logits, e.g.:

first-token-top rank=0 id=13455 logit=37.7091 logprob=-0.0057538 text=ACT
first-token-sampled id=13455 text=ACT

So the failure does not look like ordinary prompt confusion or random bad sampling. After restoring a saved session with /switch, the next sync can leave generation with unusable logits even though cache reuse/session state otherwise looks valid.

I tested a local patch with two guardrails:

  1. after ds4_session_sync(), call ds4_session_top_logprobs(..., 1);
  2. if the top candidate is invalid (nsanity <= 0, id < 0, or non-finite logit), call ds4_session_invalidate() and rebuild from the full prompt via ds4_session_sync() before sampling;
  3. as a secondary guard, suppress generated BOS token id 0 during assistant generation with ds4_session_argmax_excluding().

Results:

baseline corrected matrix: 12 cases, 8 first-answer BOS failures
instrumented/toplog matrix: 12 cases, 9 first-answer BOS failures; invalid top logits confirmed
invalid-logits rebuild only: 12 cases, 0 first-answer failures, 0 first-answer BOS pathologies, 1 second-answer failure
rebuild + generated-BOS guard: 12 cases, 0 first-answer failures, 0 BOS pathologies, 0 second-answer failures
clean final patch validation: 12 cases, 0 first-answer failures, 0 BOS pathologies, 0 second-answer failures

In the clean final validation, all 12 cases triggered the invalid-logits rebuild and the generated-BOS guard did not fire. The BOS guard is there because the rebuild-only run still had one mid-generation BOS loop after a valid answer prefix.

Minimal patch shape:

ds4_token_score sanity[1];
int nsanity = ds4_session_top_logprobs(w->session, sanity, 1);
if (nsanity <= 0 || sanity[0].id < 0 || !isfinite(sanity[0].logit)) {
    agent_trace(w, "post-sync logits invalid; rebuilding session from full prompt");
    ds4_session_invalidate(w->session);
    ds4_session_set_progress(w->session, worker_progress_cb, w);
    if (ds4_session_sync(w->session, prompt_for_sync, err, sizeof(err)) != 0) {
        ds4_session_set_progress(w->session, NULL, NULL);
        agent_set_error(w, err);
        return 1;
    }
    ds4_session_set_progress(w->session, NULL, NULL);
    nsanity = ds4_session_top_logprobs(w->session, sanity, 1);
    if (nsanity <= 0 || sanity[0].id < 0 || !isfinite(sanity[0].logit)) {
        agent_set_error(w, "post-sync logits remained invalid after full rebuild");
        return 1;
    }
}

And during generation:

int token = ds4_session_sample(w->session, cfg->gen.temperature, 0,
                               cfg->gen.top_p, cfg->gen.min_p, &rng);
if (token == 0) {
    int alt = ds4_session_argmax_excluding(w->session, token);
    agent_trace(w, "suppressed generated BOS token at index=%d alt=%d",
                generated + 1, alt);
    token = alt;
}
if (token == ds4_token_eos(w->engine)) break;

The more likely true root cause is still below this guard: restored-session sync can return success but leave logits invalid. The full-prompt rebuild is a pragmatic repair path and a useful diagnostic boundary.

freemanconsulting avatar May 23 '26 03:05 freemanconsulting

Fixed, thanks.

antirez avatar May 23 '26 06:05 antirez