ds4 icon indicating copy to clipboard operation
ds4 copied to clipboard

DSpark B2 rejection sampling + adaptive block sizing

Open machiabeli opened this issue 5 months ago • 9 comments

Summary

Adds lossless B2 rejection sampling (Chen/Leviathan 2023) to the DSpark speculative decode path, plus adaptive block sizing for workload-aware performance.

Builds on PR #480 (@audreyt) which provides the DSpark loader, Metal drafter, converter, and test infrastructure.

Verified speedups (M5 Max 128GB, Q2 base + Q4K drafter)

Prompt Baseline DSpark Speedup
Repetitive JSON (30x) 38.72 52.81 +36.4%
Diverse JSON (20 items) 38.85 42.29 +8.9%
Markdown tables 42.54 45.21 +6.3%
Thinking: prime checking 14.71 17.61 +19.7%

All outputs are token-identical to non-speculative greedy decode at temp=0. Lossless by construction at any temperature.

What's in this PR

  1. B2 rejection sampling (b2_rejection_sample, 170 lines) — log-space stable for 129K vocab. Accept with probability min(1, target/draft), sample correction from residual on reject. Activated via DS4_SPEC_TEMP=0.6 env var; greedy path unchanged when unset.

  2. Off-by-one fix — metal_graph_verify_suffix_tops row[i] predicts drafts[i+1], not drafts[i]. B2 target logits shifted by prepending s->logits as row 0.

  3. RNG state persistence — moved from stack-local (reseeded per call from time(NULL)) to ds4_session struct. Prevents correlated random sequences at >1 tok/s.

  4. Adaptive block sizing (DS4_DSPARK_ADAPTIVE=1) — starts conservative (block=2), escalates to full block after full commits, drops back on partial commits.

Key findings

  • Speedup scales with draft acceptance: repetitive structure = near-100% full commits = big wins
  • Partial-commit replay (~26ms/token) is the bottleneck on creative prompts (see #468 analysis)
  • Thinking mode with systematic reasoning (+19.7%) benefits because the checking pattern repeats
  • Fix for creative prompts: multi-point checkpointing in metal_graph_verify_suffix_tops (#468)

Credits

  • @audreyt — PR #480 loader/converter/Metal drafter plumbing
  • @lobanov — root-cause analysis (ffn_gate_inp F32/F16), numpy oracle, Q4_K GGUF

Co-Authored-By: Tang Feng (Audrey) [email protected] Co-Authored-By: lobanov [email protected]

machiabeli avatar Jun 30 '26 14:06 machiabeli

Review Change Stack

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review

Walkthrough

Graphiti warm context loads on initial turns and refreshes on substantive follow-up user turns. Refreshes use gated RRF retrieval and support forced execution after compaction. Baseline and SDK flows append refreshed context and remove injected blocks before CLI transcript upload.

Changes

Graphiti warm-context refresh

Layer / File(s) Summary
Warm-context refresh and retrieval recipes
autogpt_platform/backend/backend/copilot/graphiti/context.py, autogpt_platform/backend/backend/copilot/graphiti/config.py, autogpt_platform/backend/backend/copilot/graphiti/context_test.py
Adds message gating, forced refreshes, a dedicated timeout, configurable RRF retrieval, ratification rules, and tests.
Baseline and SDK follow-up integration
autogpt_platform/backend/backend/copilot/baseline/service.py, autogpt_platform/backend/backend/copilot/sdk/service.py, autogpt_platform/backend/backend/copilot/sdk/service_test.py
Refreshes context after pending-message folding, during query construction and retries, and after compaction.
CLI session context cleanup
autogpt_platform/backend/backend/copilot/sdk/service.py, autogpt_platform/backend/backend/copilot/sdk/service_test.py
Removes sentinel-marked injected temporal-context blocks from uploaded JSONL while preserving ordinary and structured content.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ChatCompletion
  participant refresh_warm_context
  participant fetch_warm_context
  participant _fetch
  ChatCompletion->>refresh_warm_context: submit substantive follow-up message
  refresh_warm_context->>fetch_warm_context: request RRF warm context
  fetch_warm_context->>_fetch: execute configured search
  _fetch-->>fetch_warm_context: return search results or None
  fetch_warm_context-->>refresh_warm_context: return temporal context
  refresh_warm_context-->>ChatCompletion: append stamped context

Suggested reviewers: ntindle, swiftyos

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 41.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely identifies the primary change: refreshing warm context on follow-up turns in the backend copilot.
Description check ✅ Passed The description is directly related to the changeset. It explains the memory-recall issue, the SDK and baseline changes, refresh gating, cost model, tests, and known limitations.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • [ ] Create stacked PR
  • [ ] Commit on current branch
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests
  • [ ] Commit unit tests in branch kpczerwinski/secrt-2378-autopilot-automatic-memory-recall-failures-memories-present

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

coderabbitai[bot] avatar Jul 25 '26 16:07 coderabbitai[bot]

Codecov Report

:x: Patch coverage is 99.06687% with 6 lines in your changes missing coverage. Please review. :white_check_mark: Project coverage is 81.66%. Comparing base (629e9a9) to head (03514bc). :warning: Report is 61 commits behind head on dev.

Additional details and impacted files
@@            Coverage Diff             @@
##              dev   #13673      +/-   ##
==========================================
+ Coverage   81.59%   81.66%   +0.06%     
==========================================
  Files        3615     3615              
  Lines      268774   269399     +625     
  Branches    24877    24913      +36     
==========================================
+ Hits       219311   220005     +694     
+ Misses      43951    43887      -64     
+ Partials     5512     5507       -5     
Flag Coverage Δ
platform-backend 86.59% <99.06%> (+0.05%) :arrow_up:
platform-frontend-e2e 28.14% <ø> (+0.13%) :arrow_up:

Flags with carried forward coverage won't be shown. Click here to find out more.

Components Coverage Δ
Platform Backend 86.60% <99.06%> (+0.05%) :arrow_up:
Platform Frontend 63.27% <ø> (+0.05%) :arrow_up:
AutoGPT Libs ∅ <ø> (∅)
Classic AutoGPT 28.43% <ø> (ø)
:rocket: New features to boost your workflow:
  • :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

codecov[bot] avatar Jul 25 '26 16:07 codecov[bot]

[!NOTE] GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

coderabbitai[bot] avatar Aug 05 '26 03:08 coderabbitai[bot]

🔍 PR Overlap Detection

This check compares your PR against all other open PRs targeting the same branch to detect potential merge conflicts early.

🔴 Merge Conflicts Detected

The following PRs have been tested and will have merge conflicts if merged after this PR. Consider coordinating with the authors.

  • #13651 (autogpt-batch-bot · updated 11h ago)

    • autogpt_platform/backend/backend/copilot/baseline/service.py (1 conflict, ~14 lines)
    • autogpt_platform/backend/backend/copilot/graphiti/context.py (6 conflicts, ~252 lines)
    • autogpt_platform/backend/backend/copilot/graphiti/context_test.py (1 conflict, ~331 lines)
    • autogpt_platform/backend/backend/data/graph.py (1 conflict, ~6 lines)
    • autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewSaveControl/NewSaveControl.tsx (1 conflict, ~6 lines)
    • autogpt_platform/frontend/src/app/(platform)/build/components/ReadOnlyBanner/ReadOnlyBanner.tsx (2 conflicts, ~42 lines)
    • autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/AgentActionsDropdown.tsx (1 conflict, ~5 lines)
    • autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/sidebar/SidebarRunsList/components/TaskListItem.tsx (1 conflict, ~14 lines)
    • autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/components/AgentCardMenu.tsx (2 conflicts, ~11 lines)
    • autogpt_platform/frontend/src/app/(platform)/library/components/LibraryFolderCreationDialog/LibraryFolderCreationDialog.tsx (1 conflict, ~8 lines)
    • autogpt_platform/frontend/src/app/(platform)/library/components/LibraryUploadAgentDialog/LibraryUploadAgentDialog.tsx (1 conflict, ~7 lines)
    • autogpt_platform/frontend/src/app/(platform)/marketplace/components/AddToLibraryButton/AddToLibraryButton.tsx (2 conflicts, ~33 lines)
    • autogpt_platform/frontend/src/app/(platform)/settings/api-keys/components/APIKeyRow/APIKeyRow.tsx (1 conflict, ~11 lines)
    • autogpt_platform/frontend/src/app/(platform)/settings/components/SettingsSidebar/helpers.ts (1 conflict, ~7 lines)
    • autogpt_platform/frontend/src/components/layout/Navbar/components/AccountMenu/components/AccountMenuOrgList.tsx (2 conflicts, ~111 lines)
    • autogpt_platform/frontend/src/components/layout/Navbar/components/OrgTeamSwitcher/OrgTeamSwitcher.tsx (2 conflicts, ~166 lines)
    • docs/platform/SUMMARY.md (1 conflict, ~20 lines)
  • #13642 (ntindle · updated 19h ago)

    • 📁 autogpt_platform/backend/backend/copilot/
      • baseline/service.py (1 conflict, ~14 lines)
      • graphiti/context.py (6 conflicts, ~252 lines)
      • graphiti/context_test.py (1 conflict, ~331 lines)
  • #13761 (ntindle · updated 11h ago)

    • 📁 autogpt_platform/backend/backend/
      • api/features/chat/routes.py (1 conflict, ~10 lines)
      • copilot/executor/utils.py (5 conflicts, ~29 lines)
      • copilot/model_router.py (3 conflicts, ~124 lines)
      • copilot/model_router_test.py (2 conflicts, ~11 lines)
      • copilot/sdk/service.py (5 conflicts, ~66 lines)
      • data/llm_registry/catalog.py (1 conflict, ~25 lines)
  • #13338 (ntindle · updated 14m ago)

    • 📁 autogpt_platform/backend/backend/copilot/graphiti/
      • context_test.py (1 conflict, ~227 lines)
  • #13432 (C1-BA-B1-F3 · updated 2d ago)

🟢 Low Risk — File Overlap Only

These PRs touch the same files but different sections (click to expand)
  • #13595 (Otto-AGPT · updated 11h ago)
    • Shared files: autogpt_platform/backend/backend/copilot/baseline/service.py

Summary: 5 conflict(s), 0 medium risk, 1 low risk (out of 6 PRs with file overlap)


Auto-generated on push. Ignores: openapi.json, lock files.

github-actions[bot] avatar Aug 05 '26 04:08 github-actions[bot]

/review

kcze avatar Aug 05 '26 09:08 kcze

Queued a review for PR #13673 at 8e8386a.

This pull request has conflicts with the base branch, please resolve those so we can evaluate the pull request.

github-actions[bot] avatar Aug 05 '26 10:08 github-actions[bot]

Conflicts have been resolved! 🎉 A maintainer will review the pull request shortly.

github-actions[bot] avatar Aug 06 '26 09:08 github-actions[bot]

/review

kcze avatar Aug 09 '26 00:08 kcze

Queued a review for PR #13673 at d7de14d.

/review

kcze avatar Aug 12 '26 00:08 kcze

Queued a review for PR #13673 at 67f3039.

This pull request has conflicts with the base branch, please resolve those so we can evaluate the pull request.

github-actions[bot] avatar Aug 12 '26 06:08 github-actions[bot]

Conflicts have been resolved! 🎉 A maintainer will review the pull request shortly.

github-actions[bot] avatar Aug 12 '26 13:08 github-actions[bot]

🤖 All four 🟠 Should Fix items from the automated review are addressed in 2dde368ab1.

1 & 2 — tag-neutralisation (graphiti/context.py). Both fixed together, and the security finding was the sharper one: str.replace("</temporal_context>", …) neutralised the tidy spelling — the only one an attacker would never use. Now a whitespace/case-tolerant regex (<\s*/\s*temporal_context\s*>, IGNORECASE), so </temporal_context >, </ temporal_context>, < /temporal_context> and case variants are all defanged.

New TestContextCloseTagNeutralisation covers it, parametrized over all six spellings, plus the episode renderer (a second path a fact-only guard would miss) and a no-mangling case for legitimate text. One detail worth flagging: the tests count anything the model would read as a closing tag rather than the literal string — a literal-substring count still passes against the old exact-match guard, so it would have pinned nothing.

3 — silent scrub-failure branch (sdk/service.py). Fixed, with one deliberate deviation: warning per line risked log spam on a long transcript, so misses are counted and reported once per scrub, naming the consequence ("will replay as stale context on --resume").

4 — _mark_injected_memory_block computed twice. Hoisted into one local. This was self-inflicted by the block-cache change; the comment now records why the cached and returned copies must be the same string — a second marking would still work, but any future non-determinism there would produce a block the scrub can't match.

🟡 / 🔵 items: the transcript-scrub short-circuit (NTH 3) already ships as the per-line nonce probe. Deliberately not taking: de-serializing the refresh off the TTFT path (NTH 1 — agreed, deferred to p95 measurement during SECRT-2484 rollout as you note), and the 4-word substance gate (NTH 2), which stays an open human decision — it is flagged in the handover doc rather than silently settled by me. Nits 1–2 are cosmetic and left to avoid churn on an approved diff; nit 3 (nonce visible as a tag attribute) is worth a follow-up but changes the wire format, so not on this PR.

Verified: 45 passed in context_test.py, 20 in the scrub/injection suites, lint + format clean.

kcze avatar Aug 13 '26 12:08 kcze

/review

kcze avatar Aug 13 '26 13:08 kcze

Queued a review for PR #13673 at 2dde368.

/review

kcze avatar Aug 14 '26 01:08 kcze

Queued a review for PR #13673 at 135dcd7.

This pull request has conflicts with the base branch, please resolve those so we can evaluate the pull request.

github-actions[bot] avatar Aug 17 '26 03:08 github-actions[bot]