Skip to content

In-process LoRA training on llama.cpp; llama is the default trainer - #5

Merged
FMXExpress merged 2 commits into
mainfrom
claude/optimistic-allen-i3bd3d
Oct 30, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/optimistic-allen-i3bd3d

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

What this adds

Long-term memory now trains inside memagent too. With the defaults (engine=auto, trainer=llama), chat, retrieval, LoRA training and the hot swap all run in one Free Pascal process on llama.cpp, with no Python.

Mem.Train: the trainer, in Pascal

A step-for-step port of trainer/consolidate.py, running on a background thread with its own f32 copy of the base model:

  • Data: the active facts with their paraphrases; anchors (the base model's own answers) and held-out anchors.
  • Training: a fresh LoRA trained with llama.cpp's optimizer. AdamW with warmup and linear decay, gradient-norm clipping at 1.0, loss only on the answer tokens.
  • Packing: examples are packed into windows sized to one profile batch, each example its own sequence (own positions, attends only to itself).
  • Gate and output: the recall/drift gate, then adapter.gguf, manifest.json and ready.json. The agent and the hot swap are unchanged.

Which trainer runs

[consolidate] trainer=llama is the default. It falls back to the Python trainer, and says why at startup, for:

  • the python engine (it loads PEFT adapters);
  • a llama.cpp build without the patch;
  • medium/large, marked "trainer": "python" in models.json, because their f32 copies would be 16 GB / 96 GB.

The llama.cpp patch (packaging/llama-patches/0001-lora-training.patch)

Stock b11985 trains only a model's own weights. The patch adds:

  • A training API: llama_adapter_lora_init_new, llama_lora_train_init, llama_lora_train_epoch, llama_adapter_lora_save and llama_model_convert_f32.
  • Fixes for two training bugs, each found by checking against PyTorch + PEFT on the same model and data:
    • Masked positions flattened the model. The cross-entropy backward softmax − labels gives an all-zero (masked) row the full softmax as its gradient. It is now softmax·sum(labels) − labels, on CPU and CUDA.
    • Gradients accumulated across optimizer steps. With graphs rebuilt every step and opt_period = 1, ggml never reset the parameter gradient accumulators, so step n trained on the sum of all gradients so far. In-session step 1 = fresh step 1 + step 0, cosine 1.0000. Training looked fine for a few steps, then diverged even at near-zero learning rate. This also affects stock llama.cpp's finetune example.

After the fixes:

  • Gradients: LoRA gradients match PEFT on all 420 tensors (cosine 1.000000).
  • Losses: losses match PyTorch step by step to 1e-4 over 12 AdamW steps with clipping.

Results (bench/README.md)

30 facts, tiny profile, 4-core CPU:

Trainer Recall Held-out drift After-sleep accuracy Confabulation Training time
python 1.00 1.33× 0.80 0.20 132 s
llama, in-process 1.00 1.22× 0.75 0.20 340 s

make test-e2e-llama passes on the in-process trainer: two consolidations, a correction, /forget and /rollback, with hot swaps of 14–40 ms. make test passes.

Release workflow

  • The Windows build applies the patch.
  • Both smoke tests now also train: three facts, /sleep, and the run must show training: in-process on llama.cpp and a hot-swapped LoRA. That is the first run of the trainer on Windows.

Not tested

  • CUDA training: the CUDA masking change compiles nowhere here (no nvcc).
  • small on the in-process trainer.
  • The 340 s: about 2.8× PyTorch on this CPU. The graph is rebuilt every step and there's no grouping by length yet.

Generated by Claude Code

Stock llama.cpp b11985 trains only the base model's own weights. The patch:
- llama_adapter_lora_init_new: a fresh LoRA (A kaiming-uniform, B zero, like PEFT)
- llama_opt_init also marks the attached adapters' tensors trainable, so a
  param_filter that rejects every model tensor trains the adapter alone
- label -1 = masked position (prompt, padding), and the CPU cross-entropy
  backward uses softmax*sum(labels) - labels, so a masked row has no gradient
  (with softmax - labels the masked rows flattened the model into noise)
- llama_adapter_lora_save: write the trained adapter as a loadable LoRA GGUF
- the training graph budget counts the LoRA backward nodes

lora_train_spike.cpp trains two facts on the tiny model, saves, reloads and
hot-swaps: the adapter answers a held-out paraphrase; the base is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
Mem.Train ports trainer/consolidate.py to Pascal: the active facts and their
paraphrases, anchors and held-out anchors, a fresh LoRA trained on llama.cpp's
optimizer (AdamW, warmup/decay, grad clipping, loss on the answer tokens),
the recall/drift gate, adapter.gguf + manifest + ready.json for the hot swap.
It runs on a background thread with its own f32 copy of the base model.
[consolidate] trainer=llama is the default; it falls back to the Python
trainer (and says why) for the python engine, an unpatched llama.cpp and the
medium/large profiles.

The llama.cpp patch now carries the training API and fixes two training
bugs, both verified against PyTorch + PEFT:
- the cross-entropy backward gave masked (all-zero) label rows the softmax as
  gradient, flattening the model; now softmax * sum(labels) - labels (CPU, CUDA)
- with graphs rebuilt per step and opt_period 1, ggml never reset the
  parameter gradient accumulators: every step used the sum of all gradients
  so far, and training diverged even at near-zero learning rate
After the fixes, LoRA gradients match PEFT on all 420 tensors (cosine 1.0)
and step-by-step losses to 1e-4.

30-fact benchmark: recall 1.00 and held-out drift 1.22x (python 1.00, 1.33x);
make test-e2e-llama passes with the in-process trainer.

Also: Mem.LlamaChat (generation shared by engine and trainer), thread-safe
llama.cpp logging, per-thread FPU masking, release smoke tests now train
on Linux and Windows, Windows release builds apply the patch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
@FMXExpress
FMXExpress merged commit bd68bf3 into main Oct 30, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants