Repository navigation
Description
Vision
The encoding model should improve from operational experience. Every encoding it produces, every recall that succeeds or fails, every feedback signal — all of this is training data that currently gets discarded. The model that encodes memory #10,000 should be measurably better than the one that encoded memory #1.
Full design document: docs/DESIGN_continuous_learning.md
Architecture
Four tiers that build on each other:
Tier 1 — Experience Collection (always running, zero cost)
- Verification gate scores every encoding (EPR, FR, TE) at write time
- Feedback from recall sessions links back to the encodings
- Experience buffer accumulates gold + bad encoding pairs
Tier 2 — Curriculum Generation (nightly, during dreaming)
- Bad encodings get re-encoded by Gemini to produce corrected versions
- Creates (input, bad_local, good_gemini) tuples — DPO training data
- Hard example mining focuses on the model's weakest areas
Tier 3 — Model Update (triggered when ≥50 new training pairs)
- Short spoke fine-tuning (SFT, later DPO) on new experience
- 30% replay from base dataset prevents catastrophic forgetting
- Quality gate: must pass EXP-25 probes before deployment
- Atomic spoke deployment with rollback
Tier 4 — Self-Assessment (metacognition-driven)
- Rolling quality window detects encoding drift
- Domain shift detection flags new patterns
- Autonomous training trigger when quality degrades
What Makes This Special
The feedback signal is downstream and delayed — an encoding is "good" not because it looks right at write time, but because it leads to useful recalls days or weeks later. The model learns what makes memories findable and useful, not just structurally correct.
Key Dependencies
- Verification gate (designed in EXP-29, not yet implemented)
- EXP-25 probe evaluation framework (exists)
- Spoke training pipeline (exists)
- Dreaming agent as training orchestrator (exists, needs extension)
- Gemini API for corrective re-encoding (available)
Implementation Roadmap
| Phase | Work | Estimate |
|---|---|---|
| 1. Experience Collection | DB migration, verification gate, experience buffer | 2-3 days |
| 2. Recall-Encoding Linkage | recall_feedback table, feedback processing | 1-2 days |
| 3. Curriculum Generation | Dreaming phase extension, Gemini re-encoding | 2-3 days |
| 4. Automated Training | Spoke training integration, quality gate, deployment | 3-5 days |
| 5. Metacognition Integration | Quality tracking, domain shift, training triggers | 2-3 days |
| 6. DPO (stretch) | Preference optimization from corrective pairs | 2-3 days |
Total: ~2-3 weeks
Success Criteria
- 1 month: ≥500 experience buffer entries, ≥2 training cycles, EPR +5pp
- 3 months: ≥10 training cycles, handles new domains without quality drop
- 6 months: model adapted to user's patterns, exceeds Gemini on user's actual inputs
Activity
CalebisGross commentedon Apr 10, 2026
Design Review Progress — 2026-04-10
Approach Selected: Phased Automation (Approach C)
Three independently valuable, independently reviewable phases. Each ships as its own PR.
Key Design Decisions
Model-agnostic architecture — The continuous learning pipeline works regardless of which base model wins EXP-29 (Qwen 3.5 2B, 4B, Gemma E2B, or Bespoke-pruned model from EXP-28). Verification gate is pure string matching, experience buffer stores quality metrics about encodings regardless of producer, training trigger is a config value pointing at a checkpoint.
Hybrid orchestration (Option C) — Go metacognition agent decides whether to train. If yes, daemon writes a training request file and exits gracefully. A systemd path unit watches for the file, runs the Python training script, validates quality gate, restarts daemon with new or old spokes. Daemon never restarts itself. Respects Unix philosophy, gives systemd proper supervision, keeps PyTorch in Python where it belongs.
Classification metrics: EPR + recall_score + TED — Fabrication Rate (FR) is monitoring-only, NOT used for gold/needs_improvement classification. EXP-25 showed 25.8% FR on perfect outputs due to legitimate semantic expansion ("WAL mode on." → "database"). FR has >25% false positive rate on correct outputs. Classification thresholds:
recall_count >= 3guard prevents a single irrelevant rating from condemning an encoding (design doc risk mitigation for feedback noise).Phase 1 signals: write-time verification + recall linkage — Gemini comparative baseline deferred to Phase B (curriculum generation). Write-time verification (EPR, TED, MIG) gives immediate signal. Recall feedback starts accumulating from day one; takes weeks to become dense but is the real downstream quality signal. Observe before intervening.
Phase A: Runtime Verification & Experience Collection (~1 week)
Pure observation. No model changes, no training, no Gemini calls.
A.1 Runtime Verification Gate
New file:
internal/agent/encoding/verification.goPipeline insertion point: After
compressAndExtractConcepts()returns (agent.go ~line 1046), before embedding generation:Checks computed (Go port of eval_faithfulness.py patterns):
Behavior: Soft mode only (no rejections). Log warning, store metrics, persist regardless. Reduce salience by 0.1 if TED=true. No hard mode until we have baseline data to calibrate thresholds — observe, then intervene.
A.2 Schema Migration
A.3 Experience Buffer Population
A.4 Metacognition: Quality Drift Detection
New observation type:
encoding_quality_drift. ExtendsauditMemoryQuality():A.5 Store Interface Additions
Phases B and C design in progress — will be added as subsequent comments.
CalebisGross commentedon Apr 10, 2026
Phase B: Curriculum Generation (~1 week)
Runs during dreaming hours. Builds the training data that Phase C consumes. Still no model changes.
B.1 Dreaming Agent Extension
New phase: Phase 4.5 in
internal/agent/dreaming/agent.go(after noise prune, before cross-project linking).Trigger conditions:
needs_improvementAlgorithm per entry (up to 50/run):
raw_memoriesbuild_production_prompt()— identical prompt the local model sawcorrected_outputon experience_buffer entry (training pair created)B.2 Schema Addition
B.3 Hard Example Mining
After curriculum generation, analyze the experience buffer for systematic failure patterns:
Detection heuristics:
needs_improvementby concept overlap — if 5+ share concepts not in training data, flag as new domainOutput:
curriculum_reportstored as metacognition observation. Tells Phase C what kind of training data to prioritize — targeted improvement, not random sampling.B.4 Gemini API Integration
Uses existing
llm.Providerinterface — daemon already has Gemini configured. SameChatCompletion()method, production encoding prompt, temperature 0.3.Rate limiting: Max 50 corrections per dreaming cycle. ~$0.01/night at Gemini 2.5 Flash pricing.
B.5 Training Data Assembly
Assembled data written to
training/data/continuous_learning/with timestamped filenames. This is the Go→Python handoff point.SFT pairs (gold examples):
{"input": "<raw input>", "output": "<local encoding rated gold>"}Corrective SFT pairs (Gemini re-encodings):
{"input": "<raw input>", "output": "<gemini corrected encoding>"}Future DPO triples (stretch goal):
{"input": "<raw input>", "chosen": "<gemini encoding>", "rejected": "<local bad encoding>"}Phase C: Automated Training & Deployment (~1-2 weeks)
Closes the loop. Metacognition decides when to train, systemd orchestrates it, Python runs PyTorch, quality gate validates.
C.1 Training Request Protocol
When metacognition detects
degradingquality trend (or manual MCP trigger), the daemon:~/.local/share/mnemonic/training_requests/pending.jsonC.2 Systemd Integration
Three new systemd units:
mnemonic-train.path— watches for training requests:mnemonic-train.service— runs training pipeline:continuous_train.sh— orchestrator:C.3 Training Script (
continuous_train.py)Training data mix per batch:
Key parameters:
train_qwen_spokes.pyinfrastructure (proven in EXP-18/20/25)C.4 Quality Gate
Reuses existing eval infrastructure. Runs after training completes:
export_qwen35_spokes.pyeval_faithfulness.pyon 25 gold-standard probesstress_test_hallucination.py(7 tests)Pass criteria:
FR is NOT a gate criterion — monitoring only, consistent with classification decision.
On pass: Export final GGUF, quantize to RQ4, update config.yaml, daemon restarts with new spokes.
On fail: Discard, log failure, daemon restarts with old spokes unchanged.
C.5 Spoke Deployment
qwen35-2b-spokes-cl001-f16.ggufrotorq_quantize_gguf.py(BetaQ RQ4)C.6 Manual Training Trigger
New MCP tool:
trigger_training(reason: string) -> {request_id, status}Allows manual trigger without waiting for quality drift. Same flow as automated trigger. Useful during development and pipeline testing.
C.7 Full Config Block
Summary: What Each Phase Delivers
Each phase is independently valuable and ships as its own PR.
CalebisGross commentedon Apr 10, 2026
Implementation Spec Complete
Spec committed:
docs/SPEC_continuous_learning.mdat7df03b3onfeat/exp29-candidate-evalKey additions beyond the original design doc:
VerificationResult,ExperienceEntry,ExperienceStats,RecallFeedback,EncodingQualityWindow)Next: Writing detailed implementation plan (step-by-step, file-by-file).
CalebisGross commentedon Apr 10, 2026
Phase A Implementation Plan Complete
Plan committed:
docs/PLAN_continuous_learning_phase_a.mdat5aa702d12 Tasks, TDD throughout:
migrations/007_continuous_learning.sql,schema.gostore.go(types + interface)sqlite/continuous_learning.goencoding/verification.goencoding/verification_test.goencoding/agent.gomcp/server.godreaming/agent.gometacognition/agent.goconfig/config.go,config.yamlEach task has exact file paths, complete code blocks, test commands, and commit messages. Designed for subagent execution.
Phase B and C plans will be written after Phase A ships and we have baseline quality data.
docs: implementation spec for continuous learning pipeline (#391)
docs: Phase A implementation plan for continuous learning (#391)
CalebisGross commentedon Apr 10, 2026
Phase A Progress — Tasks 1-10 Complete
Runtime verification and experience collection infrastructure is implemented and passing all tests.
What shipped:
encoding_epr/encoding_fr/encoding_flagscolumns on memories, plusrecall_feedbackandexperience_buffertablesContinuousLearningStorewith 9 methods (verification results, experience CRUD, recall linkage, quality window)eval_faithfulness.pyentity extraction (numbers, paths, versions, proper nouns, CamelCase, @mentions) + EPR/FR/TED/MIG checks. Wired into encoding pipeline — every encoding now runs throughverifyFaithfulness()after compressionfeedbacktool now propagates to experience buffer (running weighted average) and records recall-encoding linkageencoding_quality_driftobservation type — warnings at EPR < 0.85 or TED > 5%, critical at EPR < 0.70 or TED > 15%ContinuousLearningConfigwith training/trigger settings, disabled by defaultTest status:
golangci-lint run: 0 issuesRemaining:
feat: continuous learning Phase A — runtime verification & experience…
test: Go/Python verification parity test (#391)
CalebisGross commentedon Apr 10, 2026
Phase A Complete — All 12 Tasks Done
Update to previous comment: Tasks 11-12 are now also complete.
chat_templateconfig field to embedded provider ("chatml" for Qwen, "gemma" for Gemma 4 E2B). Full inference chain ready for Gemma spoke deploymentVerification gate is live in production — every encoding through the daemon now gets EPR/FR/TED/MIG scoring with results persisted to the experience buffer.
Phase A observation period begins now. Phases B and C depend on data collected during this period.
CalebisGross commentedon Apr 11, 2026
EXP-30 Inference Pipeline — Status Update
Training: Confirmed working. Python HF generate() with EXP-30 spokes produces valid faithful JSON (100% in testing) on both NF4 and bf16 base. Best eval loss 1.2002 (PPL 3.3).
llama.cpp deployment: Failed. Two issues found:
export_gemma4_spokes.pyconvertedgemma4.attention.sliding_window_patternfromarr[BOOL]toarr[INT32], corrupting SWA/global attention layer assignments. Fix committed onfeat/gemma-e2b-spokes./completionendpoint with Gemma token IDs — prompt echoing, not generation. The/v1/chat/completionsendpoint with ChatML fallback produces partial JSON but with hallucinations and wrong template format. GBNF grammar enforces structure but can't fix degenerate content. This is a Gemma 4 + llama.cpp compatibility issue, not spoke-specific.Decision: Stop fighting llama.cpp for Gemma 4 spoke inference. Explore bespoke inference path — either a minimal Python serve script (proven working) or a custom Go/C engine using ggml primitives directly. The spokes are good; the inference runtime is the bottleneck.
Next: Test Python serve as option 1, then evaluate building a bespoke inference engine for production deployment with hot-swappable spokes.
CalebisGross commentedon Apr 11, 2026
EXP-30 Systematic Characterization — Verdict Corrected to PARTIAL
Previous assessment was overstated
Session 4 concluded spokes "work" based on a few manual tests with Python HF generate() producing parseable JSON. Session 5 ran a systematic characterization (10/25 gold probes via
serve_gemma_spokes.py, plus manual diagnostic probes) and the picture is different.Characterization results (session 5)
Schema compliance: 0% of probes pass all checks. Every response has structural issues:
conceptswrong typedict(object with sub-keys) instead oflist[str]summarymissingstructured_conceptsmixed typesContent faithfulness: Confirmed. Entity preservation, file paths verbatim, correct factual content. The model knows what to say but can't maintain how to say it.
Root cause analysis
"summary":,[), this uncertainty allows the base model's JSON priors to override spoke training.Corrected verdict
PARTIAL — content faithfulness CONFIRMED, structural compliance REFUTED. EXP-30's useful training only occurred in phase 2 (steps 1800-4800, LR ~3e-5). The peak LR phase was counterproductive.
gemma.cpp: not viable
Investigated as alternative inference engine. Three hard blockers: no Gemma 4 support (ISWA/GDN/PLE unimplemented), no GPU (CPU-only), custom weight format (no GGUF).
Next: EXP-31 registered
Constant LR 3e-5 (no cosine, no warmup) with extended training. Karpathy overfit test first (10 examples, 500 steps) to verify spoke capacity before full run. Evaluation via
characterize_serve_output.pyon all 25 gold probes.CalebisGross commentedon Apr 12, 2026
Root Cause Found: All Gemma 4 Spoke Training Was Broken
Spent 2 days chasing Gemma 4 spoke training failures (0/10 schema compliance, PPL stuck at 3.3). Found the root cause: HF's
gradient_checkpointing_enable()forcesuse_cache=False, which breaks Gemma 4's ISWA attention.The Bug
Gemma 4 has KV sharing layers that reuse key/value states from earlier layers via
past_key_values.shared_layers. Whenpast_key_values=None(forced byuse_cache=False), these layers fall back tovalue_states = key_states, producing garbage attention output (2% accuracy, PPL 2.7M vs 68.6% accuracy with cache present).Every training run since gradient checkpointing was "fixed" was training on corrupted forward pass output. The LR analysis, cosine regression, and schema compliance failures in EXP-30 were all artifacts of training on garbage.
The Fix
TrainingCache— wrapsDynamicCachewith idempotentupdate()so checkpoint recomputation doesn't double KV entriesSpokeWrappedLayerowns gradient checkpointing — bypasses HF'sgradient_checkpointing_enable()entirely, preservesuse_cache=TrueValidation
What This Means for #391
The spoke training pipeline works. EXP-31 (full training run on 5,238 examples) is ready to go. Once we have a working Gemma spoke model, the continuous learning pipeline from this issue can build on top of it.
Branch:
feat/gemma-e2b-spokesCalebisGross commentedon Apr 13, 2026
EXP-31 Complete: 25/25 Gold Probes Pass
Full training run finished. Results:
This matches Qwen 3.5 2B spoke quality (100% schema, 7/7 stress test). The only gap is inference speed — 17 tok/s via HF generate vs Qwen's 95 tok/s via llama.cpp. Inference engine work is the next blocker for Gemma production deployment.
Checkpoint:
checkpoints/exp31_gemma4_fixed/best_spokes.ptBranch:
feat/gemma-e2b-spokesWandB:
exp31_gemma4_fixedCalebisGross commentedon Apr 13, 2026
EXP-31 Fully Validated
All tests complete:
PR: #400
Next blocker for this issue: inference speed. Currently 17 tok/s via HF generate (bf16, ~11GB VRAM). Need ~100 tok/s at <3GB VRAM for production deployment. Exploring quantization + optimized inference paths.
CalebisGross commentedon Apr 13, 2026
Inference Speed Benchmarks (2026-04-13)
Exported EXP-31 spokes to GGUF and tested through llama.cpp on RX 7800 XT:
Q4_K_M at 79.5 tok/s / 3.5GB VRAM is ready to deploy as the embedded provider. BetaQ hybrid quantization (RQ4 weights + Q8_0 embeddings) would hit 100+ tok/s at ~3GB but needs a fix for the get_rows kernel.
CalebisGross commentedon Apr 13, 2026
Model Prerequisite Satisfied (2026-04-13)
The continuous learning pipeline's key dependency — a production-quality local encoding model — is now in place:
Phase A (experience collection) is already collecting data against this model. The verification gate, experience buffer, and recall-feedback linkage are all operational.
Next: Phase B (curriculum generation) can proceed — the local model produces encodings that the verification gate scores, and Gemini API provides corrective re-encodings for the DPO training pairs. Phase C (automated training) can use the existing spoke training pipeline (
training/scripts/train_spokes.py --model-type gemma) with the accumulated experience data.The
continuous_learning.enabled: falseconfig flag gates activation. All infrastructure is in place to flip it on once Phase B is implemented.feat: continuous learning Phase B — curriculum generation (#391)
feat: training data assembly for continuous learning (#391)
feat: continuous learning Phase C — training trigger & orchestration (#…
refactor: adapt training data format for Gemma prep pipeline (#391)
docs: systemd training orchestration design (#391)
refactor: systemd-orchestrated training to prevent GPU crashes (#391)
feat: enable continuous learning by default (#391)
Merge pull request #406 from AppSprout-dev/feat/continuous-learning-p…
fix: training crash loop safety + episode synthesis quality (#391)