Skip to content

Merge upstream b9501 + fix: context-checkpoint reuse for recurrent/hybrid (qwen35moe) - #1

Merged
ddvnguyen merged 149 commits into
hydra-state-streamingfrom
merge/upstream-b9501
Jun 4, 2026
Merged

ddvnguyen merged 149 commits into
hydra-state-streamingfrom
merge/upstream-b9501

Conversation

@ddvnguyen

Copy link
Copy Markdown
Owner

Summary

  1. Merge ggml-org/master b9501 (147 commits) into hydra-state-streaming. Sole conflict in tools/server/server-context.cpp resolved by keeping both our hydra_send_all forward-decl and upstream's new server_n_outputs_max. All Hydra state-streaming handlers preserved.
  2. Fix context-checkpoint reuse for recurrent/hybrid models (port of ik_llama.cpp#1762). For recurrent/hybrid arches (incl. LLM_ARCH_QWEN35MOE) a checkpoint's pos_min equals the full sequence length, so the search test cur.pos_min < pos_min_thold is perpetually false → every turn logged forcing full prompt re-processing (… SWA or hybrid/recurrent memory) and re-prefilled the entire prompt. Two model-gated changes (llama_model_is_recurrent || llama_model_is_hybrid, so non-recurrent models unaffected):
    • checkpoint search: match cur.pos_max <= pos_next
    • checkpoint creation: smaller min spacing (≤4) so short follow-ups still snapshot

Validation (live, RTX sm_120, Qwopus3.6-35B-A3B / qwen35moe)

2-turn conversation against :8080:

  • Turn 1: prompt_tokens=1233, cached_tokens=0, 5.9 s (cold).
  • Turn 2 (prefix + follow-up): cached_tokens=1229, 1.1 s — log shows
    restored context checkpoint (… n_past = 1229), no forcing full prompt re-processing.
  • 5.4× faster turn-2; ~98% of the prompt reused from cache.

Before the patch this was cached_tokens=0 + full re-prefill every turn (the ~7.6 min loop on a 115K prompt).

quyentonndbs and others added 30 commits May 27, 2026 09:34
…l-org#23763)

* ci : fix undefined sanitizer build to use Debug build type only

* ci : ccache the server builds

* cont : remove ui dependency + reuse ccache for both ubuntu jobs

* tmp : force ccache save

* Revert "tmp : force ccache save"

This reverts commit a857b03.

* cont : no need for node.js
* run tests in correct build folder

* remove wasm test
* ci : server windows set build type explicitly

* cont : try windows-2025

* ci : use llvm

* cont : use ninja

* cont : fix shell

* ci : set number of jobs correctly

* ci : fix windows with vulkan ccache by using llvm

* ci : server ccache only on master

* ocd : fix job names

[no release]
…3746)

* add conversion folder and update dependencies

* limit python version for triton

* update dev-dependencies section
…l-org#23780)

* ci : move ARM jobs to 3rd-party runners + disable kleidiai release

* cont : fix deps + fix names

* ocd : fix names

* cont : fix PR links
* feat: extend repeat op for vulkan

* feat: add repeat_f16 vulkan pipeline

* fix: ensure same dst and src types

* fix: use type_size instead of data types

* fix: use int16 and int32 for repeat shader op

* chore: rename repeat_f* to repeat_i*

* chore: rename repeat vulkan pipelines
…22887)

* vulkan: Switch MUL_MAT_VEC to 4 K per iteration for F16/32

Against mesa git, this shows a 4.8% performance improvement for
tg128 on Qwen3.5-9B:BF16 on Intel BMG.

Note that this breaks some tests until the last commit which fixes
OOB A reads.

* vulkan: Use aligned loads in mul_mat_vec when available

Against mesa git, this shows a 3.3% performance improvement for
tg128 on Qwen3.5-9B:BF16 on Intel BMG.

* Make explicit that `num_rows` is <= `NUM_ROWS` in mul_mat_vec

Mesa's UUB logic can't see through conditionals, limiting its
ability to understand the bounds on the `num_rows` field in the
cleanup run. Making it explicit that `num_rows` is, indeed, always
<= `NUM_ROWS` helps mesa make slightly better codegen.

Against mesa git, this currently shows a 1% performance improvement
in tg128 on Qwen3.5-9B:BF16 on Intel BMG.

* vulkan: Fix OOB A reads in MUL_MAT_VEC for odd sizes

There was a TODO to fix the OOB reads from the A matrix which we do
here.

It is within performance noise (+<0.1%) in tg128 for
Qwen3.5-9B:BF16 on Intel BMG.
* hex-mm: add support for Q4_1 matmul/matvec, hvx-only for now

* hmx-mm: add support for Q4_1

* hex-mm: use Q8_1 dynamic quantization to avoid having to compute sums in the vec_dot

* hexagon: fix repack scratch buffer overflow

* hex-mm: fix Q4_1 repack buffer sizing

* hexagon: flip the build order for mm and fa (seems to help LTO)

* hex-mm: add vec_dot 4x1s and minor HMX cleanup after adding Q4_1

* hex-mm: fix fp16 vec_dot fallback to 2x1 and another issue that could cause incorrect output

* hexagon: resurrect early-wake and add support for polling for op-batch completions

With Q4_1 ggml-hexagon now claims pretty much the entire graphs which gives the CPU more time to chilax.
This is a good thing! But it does add extra latency for the pure benchmark runs.
Early wakeup helps recover the latency a bit in the normals runs and op-batch polling is just for benchmarking.

---------

Co-authored-by: Todor Boinovski <[email protected]>
* OP_GATED_DELTA_NET impl

* add back lanes_per_column declaration

* removed has_subgroup_arithmetic and has_subgroup_clustered_reduce

* removed trailing spaces and fixes indentation. Hard coded subgroup size for Adreno and Intel. Return not supported when K>1 state snapshot

* support for K>1 state snapshot

* removed picky indent multiple of 4 fixes

* removed return that won\'t be executed
* K>1 state snapshot support

* removed picky indent multiple of 4 fixes
* ci : separate CUDA windows workflow + fix names

* ci : rename workflow

* ci : prefix cache names with workflow name

* ci : rename build.yml -> build-cpu.yml

* ci : cache keys

* ci : fix windows cuda/hip concurrency of release workflow

* ci : fix apple cache names

* ci : add TODOs

* cont : keep just the last cache

* ci : update release concurrency to queue

* ci : move the release trigger to ubuntu-slim

* ci : hip add TODO

* cont : improve words

Co-authored-by: Georgi Gerganov <[email protected]>
* Updated vec.h/vec.cpp code to accumulate to F32 rather than F16



Change-Id: I0cb789347f2bf60ffaf9047319f727e788c825f8

Signed-off-by: Martin Klacer <[email protected]>
Co-authored-by: Milos Puzovic <[email protected]>
* allow caching of ui elements in llama-server

* use fnv_hash

* Update tools/server/server-http.cpp

etag has to be set always

Co-authored-by: Xuan-Son Nguyen <[email protected]>

---------

Co-authored-by: Xuan-Son Nguyen <[email protected]>
* vulkan: fast path for walsh-hadamard transform

* disable for intel due to segfault
@ddvnguyen
ddvnguyen merged commit d01f107 into hydra-state-streaming Jun 4, 2026
31 of 71 checks passed
@ddvnguyen
ddvnguyen deleted the merge/upstream-b9501 branch June 19, 2026 09:52
ddvnguyen pushed a commit that referenced this pull request Jul 12, 2026
Addresses all findings from the ddvnguyen review (Jul 11, 2026) on
#42:

1. [P0] stale slot.ctx_tgt/ctx_dft after T2 rebuild: Updated all
   slots' ctx_tgt pointer and n_ctx after context recreation
   (both success and rollback paths) to prevent use-after-free.

2. [P0] ctx_dft freed but never rebuilt in T2 path: Stop freeing
   ctx_dft in apply_t2_rebuild() — T2 rebuilds only the context,
   not the model, so ctx_dft (tied to model_tgt) cannot be
   recreated. Keeping it alive preserves MTP/speculative decode.

3. [P0] dangling pointer in override_tensor parsing: Store pattern
   strings in a vector that outlives the parsing loop, so
   entry.pattern C strings remain valid when load_model() reads
   them.

4. [P1] COMBINED reattach skipped on rollback: After rollback to
   old model, re-attach COMBINED mode if it was active before the
   CONFIGURE. Without this, the engine silently stays in SOLO.

5. [P1] hydra_parse_cache_type matches all ggml_types: Restrict to
   a whitelist of valid KV cache types (f16, q8_0, q4_0, q4_1,
   q5_0, q5_1, q8_1, f32) to prevent non-KV types from parsing
   successfully and hitting GGML_ABORT in the allocator.

6. [P2] slot.n_ctx never refreshed after T2 n_ctx change: Fixed as
   part of #1 — slot.n_ctx is now updated after both success and
   rollback.

7. [P2] apply_t3_rebuild blocks update_slots: Added design note
   documenting the synchronous blocking behavior and suggesting
   background-thread offload as a future improvement.

8. [P2] hand-rolled parsers duplicate existing helpers: Left as-is;
   the existing common/arg.cpp helpers (parse_tensor_buffer_overrides,
   kv_cache_type_from_str) are tightly coupled to CLI arg parsing
   and not directly usable here. Refactor tracked in #40.

Refs: #42

Co-Authored-By: Claude Opus 4.8 <[email protected]>
ddvnguyen added a commit that referenced this pull request Jul 12, 2026
…lot-free moment (#42)

* fork: implement T2/T3 apply path — actually reload model+context at slot-free moment

Phase 2b of #36 — follow-up to #41.

The previous PR (#41) added the wire schema (tier classification,
params_applied echo, deferred_keys list) but the actual T2/T3
apply step in the slot-free moment was a no-op (just cleared
the staged state and invalidated the graph cache). This PR
completes the work: the apply step now actually rebuilds
llama_context (T2) or fully reloads llama_model (T3) when
the slot-free moment fires.

## T2 apply (apply_t2_rebuild)
- Reads the staged T2 keys (n_ctx, cache_type_k, cache_type_v,
  rope_*, yarn_*) from the pending_config JSON on the context
- Updates params_base in-place
- Frees the live llama_context (and ctx_dft if present)
- Rebuilds llama_context_params from params_base
- Recreates the context via llama_new_context_with_model
- Re-inits per-slot samplers (the old samplers were bound to
  the freed context)
- On failure: rollback to the old params_base and recreate.
  If the rollback itself fails, GGML_ABORT (the engine is in
  a bad state and must exit).

## T3 apply (apply_t3_rebuild)
- Reads the staged T3 statics (n_gpu_layers, n_cpu_moe,
  model.path, split_mode, tensor_split, override_tensor)
  populated by the CONFIGURE handler
- Builds swapped_params from params_base + staged statics
- Parses the override_tensor wire string into
  llama_model_tensor_buft_override entries (via
  ggml_backend_dev_buffer_type() lookup; 'CPU' mapped to
  ggml_backend_cpu_buffer_type())
- COMBINED-mode teardown BEFORE the model reload:
  llama_hydra_set_expert_mode(0),
  hydra_remove_combined_rpc_backend(peer),
  llama_hydra_clear_combined_bindings(peer). The dual-loaded
  expert bindings must be cleared so the new ctx_tgt doesn't
  inherit stale peer device references.
- Full model reload via the existing load_model() (same call
  site as the per-PREFILL model swap at server-context.cpp:3392).
  load_model() handles the unload of the current model, the
  load of the new model, the new context creation, MTP/draft
  paths, and slot rebuild.
- COMBINED-mode reattach AFTER the reload: for layer-split,
  re-enable the mode flag (the new load_model already
  preloaded the peer device with the new tensor_split); for
  expert-split, re-resolve the peer's RPC device, rebind the
  expert tensors via llama_hydra_rebind_combined_experts().
  Same fail-open pattern as SET_EXPERT_MODE — if the peer is
  unreachable, the engine stays solo.
- On failure: rollback by reloading the old params_base.
  If the rollback itself fails, GGML_ABORT.

## Drain timeout
- The apply step checks HYDRA_COORD_PROFILE_SWITCH_DRAIN_TIMEOUT
  (default 300s). On timeout, the staged config is discarded
  and the next INFO call surfaces the cleared state.

## Files

- tools/server/server-context.cpp (+410/-8): adds
  apply_pending_hydra_config() (the high-level orchestrator),
  apply_t2_rebuild() (context-only rebuild), apply_t3_rebuild()
  (full model reload), and hydra_parse_cache_type() (helper
  for parsing wire-shape cache_type strings). The existing
  llama_hydra_apply_pending_config() low-level helper in
  llama-hydra.cpp remains in place (it now serves as the
  graph cache invalidator + state clearer; the slot-free
  check in update_slots now calls the new high-level method
  first, which does the actual rebuild before the low-level
  helper would clear the staged state).

## Build status

- sm_120 (RTX 5060 Ti): builds clean
- sm_60 (Tesla P100): builds clean (with CMAKE_CUDA_HOST_COMPILER=g++-14)
- Tests: test-hydra-state-chunk-size, test-hydra-configure-tier,
  test-hydra-checkpoint-policy, test-hydra-rpc-bind — all pass

## Cross-references

- #36 (v4 design handoff, Phase 2)
- #40 (fork-side Phase 2b issue)
- #41 (predecessor PR — wire schema + best-effort stub)
- ddvnguyen/hydra_vortex#397 (parent tracker)
- ddvnguyen/hydra_vortex#406 (parent-side docs PR — the wire schema)
- ddvnguyen/hydra_vortex#407 (parent-side code PR — applier + overrides)
- docs/system-test-phase-2b.md (live E2E test procedure)

Refs: #41, ddvnguyen/hydra_vortex#406,
ddvnguyen/hydra_vortex#407

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix: address review findings on fork PR #41 and #42

Addresses all review findings from the ddv-hydra review bot on
#41 and #42.

## PR #42 P1: params_base stale after load_model()
- Added comment in apply_t3_rebuild() confirming load_model()
  does params_base = params internally (line 844), so no explicit
  reassignment is needed after a successful load.

## PR #42 P1: T2 rollback log before GGML_ABORT
- Added SRV_ERR log before the GGML_ABORT on rollback failure
  so the operator sees the unrecoverable-state warning in the log.
- Added SRV_INF log on successful rollback so the operator can
  confirm the engine recovered to the old model.

## PR #42 P2: override_tensor pointer lifetime
- Updated comment in apply_t3_rebuild() clarifying that the
  pattern C string in tensor_buft_overrides points into the
  staged static s_hydra_pending_override_tensor, which is valid
  for the entire load_model() call (load_model parses overrides
  synchronously before T3 statics are cleared).

## PR #41 P1: T3 statics thread model invariant
- Added a hard-constraint comment block on the s_hydra_pending_*
  file-scope statics in llama-hydra.cpp explaining why they are
  safe without locking today (same-thread dispatch) and what
  must change if the thread model changes (move to llama_context
  or add mutex).

## PR #42 P2: hydra_peer vs hydra_current_peer verification
- hydra_current_peer is the currently connected peer (may change
  on SET_EXPERT_MODE peer switch). hydra_peer is the configured
  peer (from startup YAML). The teardown removes the RPC backend
  for the CURRENT peer and clears bindings for the CONFIGURED peer.
  These can differ only during a peer-switch mid-reload, which is
  blocked by the same-thread dispatch invariant. The existing code
  is correct; the comment above the teardown block now explains
  this.

## PR #42 P3: dead drain timeout in llama-hydra.cpp stub
- Not changed in this commit — the llama_hydra_apply_pending_config()
  stub is still called as a fallback for non-server callers.
  Left as-is for now; can be removed in a follow-up.

Refs: #41 (review), #42 (review)

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix: dangling hydra_rpc_ctx stack pointer breaks RPC response delivery (#44)

server_context::start_rpc_server() declared hydra_rpc_ctx as an
automatic-storage local, then handed hydra_rpc::start() its address to
retain in a process-lifetime singleton (hydra_rpc::state().hydra_ctx),
read by every future RPC connection from a bounded-thread-pool worker
thread. The local went out of scope the moment start_rpc_server()
returned, so the singleton retained a dangling pointer into a freed
stack frame — a stack-use-after-return. Whether a given request's
queue_tasks/queue_results dereference through it "worked" depended
entirely on whether the freed stack slot had been reused yet, which
explains the intermittent nature of #43 (task processed, result
queued, but the response body never reaching the client socket).

Fix: give ctx static storage duration. start_rpc_server() only ever
runs meaningfully once per process (hydra_rpc::start() itself guards
double-start), so `static` gives it exactly the lifetime the singleton
already assumes.

Also make hydra_send_all/hydra_recv_all log on failure (fd, bytes
transferred, errno) instead of silently returning false — every caller
already treats a false return as "give up" but had no way to tell a
real socket error from `-lv` output, which the issue itself flagged as
a diagnostic gap.

Verified live on hardware (RTX 5060 Ti, Qwen3.5-2B-Q8_0): INFO (0x41)
and CONFIGURE (0x40) previously timed out after 10s against a raw
socat client, a raw Python client, and C# RpcClient. All three now
round-trip correctly, including a second request on the same
persistent connection. test-hydra-rpc-bind, test-hydra-configure-tier,
and dotnet Tests.Shared EngineOpcodeTests all still pass.

Closes #43

Co-authored-by: Hydra Engineering <hydra-engineering@local>
Co-authored-by: Claude Sonnet 5 <[email protected]>

* fix: address 8 review findings on PR #42 T2/T3 apply path

Addresses all findings from the ddvnguyen review (Jul 11, 2026) on
#42:

1. [P0] stale slot.ctx_tgt/ctx_dft after T2 rebuild: Updated all
   slots' ctx_tgt pointer and n_ctx after context recreation
   (both success and rollback paths) to prevent use-after-free.

2. [P0] ctx_dft freed but never rebuilt in T2 path: Stop freeing
   ctx_dft in apply_t2_rebuild() — T2 rebuilds only the context,
   not the model, so ctx_dft (tied to model_tgt) cannot be
   recreated. Keeping it alive preserves MTP/speculative decode.

3. [P0] dangling pointer in override_tensor parsing: Store pattern
   strings in a vector that outlives the parsing loop, so
   entry.pattern C strings remain valid when load_model() reads
   them.

4. [P1] COMBINED reattach skipped on rollback: After rollback to
   old model, re-attach COMBINED mode if it was active before the
   CONFIGURE. Without this, the engine silently stays in SOLO.

5. [P1] hydra_parse_cache_type matches all ggml_types: Restrict to
   a whitelist of valid KV cache types (f16, q8_0, q4_0, q4_1,
   q5_0, q5_1, q8_1, f32) to prevent non-KV types from parsing
   successfully and hitting GGML_ABORT in the allocator.

6. [P2] slot.n_ctx never refreshed after T2 n_ctx change: Fixed as
   part of #1 — slot.n_ctx is now updated after both success and
   rollback.

7. [P2] apply_t3_rebuild blocks update_slots: Added design note
   documenting the synchronous blocking behavior and suggesting
   background-thread offload as a future improvement.

8. [P2] hand-rolled parsers duplicate existing helpers: Left as-is;
   the existing common/arg.cpp helpers (parse_tensor_buffer_overrides,
   kv_cache_type_from_str) are tightly coupled to CLI arg parsing
   and not directly usable here. Refactor tracked in #40.

Refs: #42

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix: address 4 residual findings from follow-up review on PRs #41 and #42

Addresses the residual issues identified in the Jul 11 follow-up
review comments:

1. attention_type classified as T2 but not applied in T2 rebuild:
   Add handler block in apply_t2_rebuild() that maps 'causal' and
   'non-causal' strings to LLAMA_ATTENTION_TYPE_CAUSAL /
   LLAMA_ATTENTION_TYPE_NON_CAUSAL on params_base.attention_type.
   The field flows through common_context_params_to_llama() ->
   llama_context constructor -> cparams.causal_attn.

2. Spec-decode holds stale ctx_tgt after T2 rebuild (use-after-free):
   common_speculative_impl_draft_mtp stores a COPIED ctx_tgt pointer
   from params_base.speculative.draft.ctx_tgt at init time. After
   T2 rebuilds the context, this pointer is dangling. Fix: update
   params_base.speculative.draft.ctx_tgt to the new ctx_tgt, then
   re-create spec via common_speculative_init() and re-assign to
   every slot. Also clear spec_ckpt/spec_draft/spec_i_batch since
   the KV cache was rebuilt from scratch.

3. override_tensor pattern lifetime — scope + SSO + null terminator:
   a) pattern_strings was declared inside the override parsing
   if-block but load_model() runs after the block closes, so all
   entry.pattern C strings were dangling. Move declaration to
   function scope alongside swapped_params.
   b) std::vector::push_back can reallocation-invalidate c_str()
   pointers for SSO strings (patterns < 15 chars). Add reserve(16)
   to prevent reallocation.
   c) tensor_buft_overrides must be null-terminated — the model
   loader asserts on this. Add {nullptr, nullptr} sentinel.

4. Cache-type whitelist mismatch with upstream:
   Replace the hydra_parse_cache_type() whitelist to match upstream's
   authoritative kv_cache_types array (common/arg.cpp:390): add
   GGML_TYPE_BF16 and GGML_TYPE_IQ4_NL, remove GGML_TYPE_Q8_1.

Refs: #41 (follow-up review), #42 (follow-up review)

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix: re-init spec on T2 rollback path (missing spec-decode ctx_tgt refresh)

The previous commit added spec re-init on apply_t2_rebuild's success
path, but the rollback path (first context-recreate fails, falls back
to old params) also creates a fresh ctx_tgt without re-initing spec.
This leaves common_speculative_impl_draft_mtp holding a dangling
ctx_tgt pointer — reachable via a T2 CONFIGURE that fails its first
attempt while MTP/speculative decode is active.

Mirror the same if (spec) { ... } re-init block into the rollback
branch.

Refs: #42 (follow-up review)

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix: retry hydra RPC recv on EINTR/EAGAIN instead of dropping connection

Signals (SIGCHLD from subprocess exit, etc.) can cause recv() to
return EAGAIN/EWOULDBLOCK even on blocking sockets with SO_RCVTIMEO.
The old code treated every recv failure as fatal, closing the RPC
connection and surfacing as engine_rpc_error prefill fallbacks.

hydra_recv_all now retries on EINTR (transient signal) and retries
once on EAGAIN/EWOULDBLOCK to distinguish signal-induced transients
from a genuine SO_RCVTIMEO idle timeout (120s). A second consecutive
EAGAIN is a real timeout — connection dropped as intended.

Fixes the intermittent 21% COMBINED prefill fallback rate on DENSE 27B.

ddvnguyen/hydra_vortex#382

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix: enable combined-static flag for DENSE tensor-split engines

set_hydra_capabilities was hardcoded to split_mode='solo' and
set_hydra_combined_static was never called, so tensor-split engines
(DENSE profile) always reported mode='solo' to the Hydra control
plane. This caused SetExpertMode('combined') to fall through to
the expert-split path which requires --combined-ot-pattern (absent
for DENSE), resulting in 'staying solo' fallback.

Fix: detect tensor_split at init, pass split_mode='layer' and call
set_hydra_combined_static(true). The layer-split SetExpertMode
path (line 3906) then correctly handles 'combined' as a no-op success.

ddvnguyen/hydra_vortex#382

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat: engine-side config diff — skip drain when T2/T3 keys match current state

The engine owns the drain decision, not Hydra Core. Hydra Core sends
the desired config via 0x40 CONFIGURE, and the engine diffs it against
its current running state (params_base + pending T3 statics). If all
T2/T3 values already match, the drain + rebuild is skipped entirely —
the CONFIGURE response reports success with empty deferred_keys.

Add hydra_t2t3_key_changed() that compares each T2/T3 key's requested
value against the current params_base (for T2: n_ctx, cache_type_*,
rope_*, yarn_*, attention_type) and pending T3 statics (for T3:
n_gpu_layers, n_cpu_moe, model.path, override_tensor). Keys that
match are filtered out before staging. split_mode and tensor_split
always treat as changed (no reliable current-state comparison).

Refs: #42

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix: move pattern_strings to member to fix use-after-scope in tensor_buft_overrides

load_model(swapped_params) copies params into params_base (line 844),
which includes tensor_buft_overrides entries whose entry.pattern is a
raw const char* into pattern_strings. If pattern_strings is a local
variable in apply_t3_rebuild(), it is destroyed at function exit,
leaving dangling pointers in params_base.tensor_buft_overrides.

Move pattern_strings to server_context_impl::hydra_pattern_strings
(member scope) so it outlives apply_t3_rebuild(). Cleared explicitly
on each T3 apply.

Refs: #42 (follow-up review P0)

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix: P1 gate layer-split teardown + P2 consolidate peer + P2 DRY reinit helpers

P1: T3 teardown breaks layer-split COMBINED reloads. For
hydra_combined_static (layer-split, DENSE profile), the teardown
removes the peer from the ggml backend registry. Then load_model()
builds the new model without the peer, placing the entire model on
the local GPU — OOM on next prefill. The reattach only sets a flag
without re-registering the peer.

Fix: gate the teardown on hydra_combined_static. For layer-split,
only zero the mode flag — leave the peer registered so load_model()
can see it during tensor_split placement. For expert-split, the full
teardown is required.

P2: Consolidate hydra_current_peer vs hydra_peer in teardown. Use
hydra_current_peer consistently for both remove and clear — it's the
endpoint actually registered in the ggml backend registry (SET_EXPERT_MODE
registers via hydra_current_peer). The reattach paths correctly use
hydra_peer for re-registration.

P2: Extract refresh_slots_after_ctx_rebuild() helper. Both the success
and rollback paths of apply_t2_rebuild had byte-for-byte identical
15-line blocks (slot pointers + smpl + spec reinit). This was the
exact bug class where the rollback path originally missed the spec
reinit. Single helper eliminates the possibility of recurrence.

Refs: #42 (follow-up review)

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* refactor: move T3 pending state from file-scope statics to llama_context

P3 thread-model migration. The six s_hydra_pending_* statics
(override_tensor, split_mode, tensor_split, n_gpu_layers,
n_cpu_moe, model_path) in llama-hydra.cpp are moved to
llama_context fields (hydra_pending_*). All getters/setters
now take a llama_context* parameter and read/write the
context's own fields instead of file-scope statics.

This eliminates the hard threading invariant documented in
the old code: 'CONFIGURE handler and update_slots must run on
the same thread.' Each context now owns its own pending T3
state, so concurrent contexts (future multi-model or
multi-worker) won't collide.

P3b (async T3 reload) is deferred to a follow-up — load_model()
replaces nearly every member variable, making background-thread
reload require double-buffering, which is a larger architectural
change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix: T2/T3 diff check false positives after drain clears pending statics

n_cpu_moe: always return true (no params equivalent; informational
only — apply path just logs it).

model.path: fall back to params.model.path when pending static is
empty, so re-sending the current path doesn't trigger a spurious
T3 reload (same pattern as n_gpu_layers).

override_tensor: always return true (no params equivalent; apply
path parses and applies on model reload).

Refs: #42

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Hydra Engineering <hydra-engineering@local>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.