Skip to content

llama : adapter factors update in place, with no GGUF parse (engine #973) - #215

Merged
bong-water-water-bong merged 1 commit into
1bit/hrx-vulkan-patchedfrom
1bit/973-inplace-adapter
Nov 6, 2026
Merged

bong-water-water-bong merged 1 commit into
1bit/hrx-vulkan-patchedfrom
1bit/973-inplace-adapter

Conversation

@bong-water-water-bong

Copy link
Copy Markdown

llama : adapter factors update in place, with no GGUF parse (engine ggml-org#973)

Part of engine ggml-org#973. Today the engine changes an adapter's factors by writing a new adapter GGUF and calling
llama_adapter_lora_init() again: that re-parses the file, allocates new a/b tensors, and llama_set_adapters_lora()
changes the adapter set, which forces a graph rebuild. Measured cost on the reporting lane (Vulkan0, Qwen3-0.6B
Q4_K_M, rank 2, batch 16): 16-23 ms per write, 45 -> 195 ms per write as a multi-stage bank grows to rank 26.

What this adds

The adapter already holds its a/b tensors in backend buffers, allocated once by
llama_adapter_lora_init_impl() via ggml_backend_alloc_ctx_tensors_from_buft(). This PR writes new values into
those tensors through ggml_backend_tensor_set() and touches nothing else: no file read, no allocation, no change to
the context's adapter set. Graph construction reads the tensors' pointers and shapes, and llama.cpp keys graph reuse
on the adapter set and shapes, not on tensor contents, so the next decode just reads the new values.

// 0 on success; -1 invalid argument, -2 unknown name, -3 size mismatch. Nothing is written on failure.
// a_data or b_data may be NULL to keep that side. Same type and shape as the loaded factor:
// a [n_embd_in, rank], b [rank, n_embd_out].
LLAMA_API int32_t llama_adapter_lora_set_factors(
        struct llama_adapter_lora * adapter,
        const char * name,                     // base-model tensor name, e.g. "blk.3.attn_q.weight"
        const void * a_data, size_t a_size,
        const void * b_data, size_t b_size);

// Batch form: every entry is checked before anything is written, so a bad entry writes nothing.
struct llama_adapter_lora_factor { const char * name; const void * a_data; size_t a_size; const void * b_data; size_t b_size; };
LLAMA_API int32_t llama_adapter_lora_set_factors_multi(
        struct llama_adapter_lora * adapter,
        const struct llama_adapter_lora_factor * factors,
        size_t n_factors);

// Enumerate the weights (to rewrite all of them with the batch form).
LLAMA_API size_t  llama_adapter_lora_n_factors(const struct llama_adapter_lora * adapter);
LLAMA_API int32_t llama_adapter_lora_factor_name_by_index(const struct llama_adapter_lora * adapter, size_t i, char * buf, size_t buf_size);

Constraints, documented in the header: the type and shape of a factor cannot change in place. A different rank is a
new adapter (today's path), and alpha is a struct field the graph bakes into its scale node, so a caller that changes
alpha still goes through llama_set_adapters_lora(). A caller must not run an in-place write while a decode that
reads the same adapter is in flight.

Test

tests/test-lora-inplace.cpp runs in ctest (label main) with no model files: it builds a tiny llama model in memory
with the existing llama_model_init_from_user(), writes two rank-2 adapter GGUFs with the gguf writer, then deletes
both files before any in-place update
, so a re-parse would fail. No test adapter fixture existed in the repo, so the
test creates its model and adapter itself.

What it asserts:

  1. Applying the adapter moves the logits (nmse = 3.7e-05, dmax = 7.4e-03, logits |max| 1.02).
  2. One in-place update of blk.0.attn_q.weight on the same context moves them again (nmse = 5.7e-05), and the result
    is bit-identical to a second context that loaded the same factors from a file (nmse = 0).
  3. Structural no-parse evidence: the factor tensors keep the same ggml_tensor * addresses, the files are gone, and
    the context never sees a new adapter set (readback of device tensors is also checked at load).
  4. Refused updates (unknown name -2, wrong size -3, both sides NULL -1, NULL name -1, and a batch whose second entry is
    unknown -2) leave the logits bit-identical to before and the tensor pointers unchanged.
  5. The batch form rewrites every weight of the adapter (names from n_factors() / factor_name_by_index()), and
    writing the original values back restores the logits bit-identically to the first application.

Build and run, CPU only, on this box (gcc 15.2.0, 16 threads):

$ cmake -B build-clean -DLLAMA_CURL=OFF -DGGML_HIP=OFF -DCMAKE_BUILD_TYPE=Release
$ cmake --build build-clean -j16
[100%] Built target llama-app                      # full default build, green
$ cd build-clean && ctest -R test-lora-inplace --output-on-failure
1/1 Test #28: test-lora-inplace ................   Passed    0.01 sec
100% tests passed, 0 tests failed out of 1

Also run in a Debug build (assertions on): build green, test passes.

Engine side (not part of this PR)

  1. Pin bump: the engine's third_party/llama.cpp is at 4a375bf2d; this branch's merge commit becomes the new pin
    (6 commits ahead of 4a375bf2d, all HRX/kv-share changes, plus this one).
  2. Callsite: the grease point is the process that owns the factor bank. At engine origin/main there is currently
    no llama_adapter_lora_init callsite (grep of the whole repo outside third_party), so the change is not a
    one-line swap in the engine: the ZO/finetune driver that writes adapter GGUFs (the lane that filed Android build fails with ld: error: undefined symbol: aligned_alloc ggml-org/llama.cpp#973 measured it
    with ~/amd-oss/inferzo) must replace "write GGUF -> llama_adapter_lora_init -> llama_set_adapters_lora" with
    "write the host factors -> llama_adapter_lora_set_factors_multi". That also removes the intermediate GGUF write
    (24.5 ms of the 65 ms per ZO step on the issue).

Not verified here

  • The device write path on Vulkan/HRX. This build is CPU only (-DGGML_HIP=OFF, no GPU). The write is the same
    ggml_backend_tensor_set() call the loader already uses to fill these buffers (src/llama-adapter.cpp), so the
    backend behaviour is the existing one, but a device-side run is the missing evidence.
  • The end-to-end ZO-step latency win. It needs the driver change above; this PR only proves the primitive and that it
    applies without a parse.
  • No engine repo files are touched, no pin is changed, nothing is merged.

llama_adapter_lora_set_factors() copies new lora_a/lora_b values into the
tensors the adapter already owns in the backend buffer, through
ggml_backend_tensor_set(). The adapter file is not read, no tensor is
allocated, and the adapter set on the context does not change, so the next
decode reuses the graph.

The bulk variant checks the whole batch before writing anything, so a bad
entry leaves every weight as it was. n_factors() and factor_name_by_index()
let a caller enumerate the weights and rewrite all of them.

test-lora-inplace builds a tiny llama model in memory and a rank-2 adapter
GGUF, then deletes the adapter file. It checks that the in-place update
changes the logits, matches a fresh load of the same factors, restores
bit-identical logits when the old values are written back, and that a
refused update keeps the old values and the old logits. The factor tensors
keep their addresses throughout, so nothing was reloaded.

Refs engine#973.

Co-authored-by: agent <agent@local>
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.

1 participant