Skip to content

Fork/hydra 368 bind on activation - #26

Merged
ddvnguyen merged 5 commits into
hydra-forkfrom
fork/hydra-368-bind-on-activation
Jul 1, 2026
Merged

ddvnguyen merged 5 commits into
hydra-forkfrom
fork/hydra-368-bind-on-activation

Conversation

@ddvnguyen

Copy link
Copy Markdown
Owner

Overview

Additional information

Requirements

Hydra Engineering and others added 5 commits June 28, 2026 19:27
…ra_vortex ggml-org#368)

Makes COMBINED zero-copy binding (llama.cpp#20) swap-safe and re-callable
in preparation for dynamic quant swap (ggml-org#263, SWAP_QUANT 0x45). Also fixes
the COMBINED startup race (hydra_vortex ggml-org#357) by binding on demand at
SET_EXPERT_MODE("combined") instead of one-shot at startup.

Forward-compatible slice per docs/dynamic-quant-swap-combined.md: this
lands the protocol + binding + fail-open + tests now, so ggml-org#263 can plug
in the actual model free/reload against a stable contract.

## What

### 1. Registry epoch (ggml-rpc.cpp)
- rpc_msg_resolve_tensor_rsp gets a new uint32_t registry_epoch; the
  server returns its g_hydra_registry_epoch with every resolve.
- g_hydra_registry_epoch (atomic<uint32_t>) is bumped on every
  ggml_backend_rpc_clear_local_tensors() call. A head re-checks
  ggml_backend_rpc_get_remote_registry_epoch() before each use of a
  binding; mismatch = stale = the head must rebind or stay solo.

### 2. ggml_backend_rpc_clear_local_tensors
New public proc. Clears the local-tensor registry and bumps the epoch.
Idempotent. Foreign-buffer clearing is a defense-in-depth follow-up
(the head's epoch check is the primary safety).

### 3. ggml_backend_rpc_get_remote_registry_epoch
New public proc. Probes the peer's current epoch over RPC (reuses
RPC_CMD_RESOLVE_TENSOR with a sentinel name and reads back the epoch
field of the response — single round trip). Returns 0 on any failure;
callers must treat 0 as "couldn't verify" not "epoch is 0".

### 4. Fail-open in ggml_backend_rpc_bind_remote_tensor
Replaced RPC_STATUS_ASSERT(status) (which calls GGML_ABORT) with
"if (!status) { log; return nullptr; }" — peer drop, malformed
response, or transient RPC error must NOT crash the engine. The
bind result is still observable: nullptr means "fall back to solo".

### 5. ne-guard
ggml_backend_rpc_bind_remote_tensor takes a new const uint32_t*
expected_ne parameter (may be NULL to skip). After resolve, the
response's ne[] is compared element-wise; mismatch = refuse the bind
(return nullptr) — only type/nb (the quant layout) may differ between
bindings; ne (the count along each axis) is structural. A head bound
to a different peer's resident model fails loud, not by running on
the wrong weights (which would corrupt the KV cache silently).

### 6. llama_hydra_rebind_combined_experts (new)
Extracted from llama_hydra_load_combined_experts. Reuses the per-peer
backend (which is registered once at startup), frees the previous
binding's meta_ctx, allocates a new one, and re-runs the bind loop
with the new epoch + ne-guard. Per-peer resource map
(s_hydra_combined_bindings) owns the meta_ctx — replacing an entry
drops the previous ctx (the per-rebind leak fix; old code pushed
ctxs into a static vector and never freed).

### 7. llama_hydra_register_local_tensors_for_rpc re-callable
Now calls ggml_backend_rpc_clear_local_tensors before the registration
loop. First call: clear is a no-op (epoch 0 → 1). Subsequent calls
(after a model swap / re-register on the peer) bump the epoch again,
so any outstanding binding becomes observably stale.

### 8. SET_EXPERT_MODE(combined) handler now binds on activation
server-context.cpp:3504. Replaces the implicit reliance on a
startup-only binding. On each SET_EXPERT_MODE("combined") the head
calls llama_hydra_rebind_combined_experts and degrades to solo if
the rebind fails (peer unreachable, ne-guard, RPC error). This is
the ggml-org#357 fix: the head binds on demand when the peer is reachable,
every time. No abort path.

## Tests (test-hydra-rpc-bind.cpp)
- original round-trip (zero-copy read of server's live tensor)
- registry_epoch in resolve response
- ne-guard: rejected bind with mismatched shape (returns null)
- ne-guard: NULL expected_ne skips the check (legacy callers)
- missing name: returns null
- clear → epoch bumps; re-register → epoch unchanged (only clear bumps)
- re-bind after clear+re-register succeeds and observes the new epoch
- fail-open: bind to unreachable endpoint returns null (no abort)
- re-callable register is monotonic (no spurious epoch bump)

Run: `./bin/test-hydra-rpc-bind` → "OK: zero-copy RESOLVE_TENSOR/
bind_remote_tensor round-trips correctly (incl. ggml-org#368 epoch, ne-guard,
fail-open, re-callable register)"

## Build verification
- sm_120 (CUDA 13.2): `cmake --build build_sm120 --target llama-engine
  test-hydra-rpc-bind` — clean. Test runs and passes.
- sm_60 build deferred to P100 host (the AGENTS.md note about the
  gcc-15 / cuda-12.9 toolchain incompatibility is unchanged).

## Out of scope (lands with ggml-org#263)
The actual SWAP_QUANT model free/reload + re-register on the engine
(0x45 handler body) — slots into this contract once built. The Core
side (WorkerSchedulerService SWAPPING state) is in the parent repo
(ddvnguyen/hydra_vortex#368 §3).

## Cross-repo
- ddvnguyen/hydra_vortex#368 (parent issue)
- ddvnguyen/hydra_vortex#366 (merged — the SOLO_BUSY/COMBINED_SERVING
  state machine foundation that ggml-org#368 §3 extends)
- ddvnguyen/hydra_vortex#357 (startup race — fixed here by bind-on-
  activation)
- #22 (fork-side tracker)

AI assistance note: this commit was produced with AI assistance
(Claude) under explicit owner direction. Per AGENTS.md the private
fork ddvnguyen/llama.cpp is exempt from the upstream llama.cpp AI-
submission policy.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…VERSION to 1

P1: rpc_server::resolve_tensor left response.registry_epoch uninitialised
on the not-found early return. ggml_backend_rpc_get_remote_registry_epoch
probes with a sentinel name that is never found, so it was reading
indeterminate stack bytes instead of the real epoch. Fix: populate
registry_epoch before the not-found return, inside the lock where
g_hydra_registry_epoch is already loaded for the found path.

P2: rpc_msg_resolve_tensor_rsp gained a uint32_t registry_epoch field but
RPC_PROTO_MINOR_VERSION was not bumped. A new RTX head talking to an old
P100 server (not yet rebuilt) would size-mismatch on RESOLVE_TENSOR and
silently fail-open to permanent solo with no diagnostic. Fix: bump minor
to 1 and tighten negotiate_hello to require an exact minor match (reject
both older AND newer peers) so the mismatch is diagnosed at hello, not
buried in a silent fail-open.

Fixes review findings P1 and P2 on #23.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… in capabilities (hydra_vortex ggml-org#375 ggml-org#376)

## ggml-org#375 — advertise combined/pipeline in engine_info

server-context.cpp: the engine_info (0x41) handler now lists 'combined' and
'pipeline' in the capabilities set. The build that ships this binary is
always the llama-engine fork, which carries the COMBINED code path; this
is the engine-side mirror of the static workers.json fields.

## ggml-org#376 — fail-open on RPC handshake

ggml-rpc.cpp: RPC_STATUS_ASSERT in negotiate_hello (line 363) replaced
with if(!status){log; return false;}. The TCP connection succeeds before
the RPC server's HELLO handler is ready, especially under compose where
two llama-engine instances start simultaneously. Aborting on a transient
HELLO failure crashes the head for no reason — returning false lets the
caller (get_socket -> get_device_count -> add_server) return 0 devs,
which keeps the head alive and degrades to solo instead.

Refs: ddvnguyen/hydra_vortex#375, ddvnguyen/hydra_vortex#376

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Two bugs prevented SET_EXPERT_MODE("combined") from ever activating when
the peer (RTX 3060) came up after the head (RTX 5060 Ti) had already started:

1. server-context.cpp: want_combined was gated on hydra_combined_head_attached,
   which is only set true when the startup llama_hydra_load_combined_experts
   call succeeds. If the peer was down at boot, the flag stayed false and the
   entire bind-on-activation code path (ggml-org#368) was unreachable. Fixed by gating
   on "is the engine configured as a combined head" (non-empty peer addr +
   OT pattern) instead, which correctly reflects what the engine is configured
   to do rather than an accident of startup ordering. Also latches
   hydra_combined_head_attached=true on first successful rebind so INFO RPC
   advertises combined capability.

2. llama-hydra.cpp: tensor_pattern from --combined-ot-pattern uses the
   override-tensor format "<name_regex>=<backend>" (e.g.
   "blk\.([0-9]+)\.ffn_.*_exps\.weight=CPU"), but the regex was matched
   against raw tensor names which never contain "=CPU". Fixed by stripping
   everything from the last '=' onward before compiling the regex.

With both fixes applied: 120/120 expert tensors across 40 layers are bound
to the peer on the first COMBINED request, and the engine reports
applied='combined' instead of falling back to solo.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…68-bind-on-activation

# Conflicts:
#	src/llama-hydra.cpp
#	tools/server/server-context.cpp
@hydra-z

hydra-z Bot commented Jul 1, 2026

Copy link
Copy Markdown

Conflicts Resolved ✅

Merged hydra-fork into fork/hydra-368-bind-on-activation and resolved conflicts in:

  • src/llama-hydra.cpp — OT-pattern stripping block (2 conflicts over name_pattern vs tensor_pattern in log calls)
  • tools/server/server-context.cpp — 2 conflicts over the want_combined gate (config-based vs hydra_combined_head_attached) and the hydra_combined_head_attached latch on success

HEAD's version was kept for all resolutions (these are the new fix commits on top of PR #23).

Review: APPROVE

What this does

Adds 2 fix commits on top of the already-merged PR #23:

  1. Enable Fused-Multiply-Add (FMA) and F16C/CVT16 vector extensions on MSVC ggml-org/llama.cpp#375/CI: CMake: Separate build and test steps ggml-org/llama.cpp#376 fixes — fail-open on RPC HELLO handshake (no abort), strict minor-version match, advertise combined/pipeline in capabilities
  2. OT-pattern stripping + bind-on-activation — strips =backend suffix from --combined-ot-pattern so regex matches tensor names; makes COMBINED rebind re-callable per-peer with meta_ctx leak fix

Strengths

Minor notes (non-blocking)

  • foreign_buffers clearing on clear (TODO fix typo in chatLLaMa ggml-org/llama.cpp#368-foreign) is acknowledged but not implemented — epoch check is the primary safety so this is acceptable
  • Per-rebind cost is N RPC resolves; the optional epoch-cache optimization can be a follow-up if it shows up on profiles

@ddvnguyen
ddvnguyen merged commit 8d18d1b into hydra-fork Jul 1, 2026
ddvnguyen added a commit that referenced this pull request Jul 6, 2026
…pp + Phase C/E

ggml-org#376: The original fix (PR #26, commit 8d18d1b) addressed the RPC HELLO
handshake assert only. Remaining RPC_STATUS_ASSERT calls throughout
ggml-rpc.cpp still called GGML_ABORT when the RPC connection dropped
during model loading or inference — hitting buffer_free, graph_compute,
set_tensor, get_tensor, etc. This made COMBINED mode crash on any
transient peer disconnect.

Changes:
- ggml/src/ggml-rpc/ggml-rpc.cpp: Changed RPC_STATUS_ASSERT macro from
  GGML_ABORT to GGML_LOG_ERROR. Added null/connection guards to
  buffer_free_buffer, buffer_get_base, init_tensor, set_tensor,
  get_tensor, buffer_clear, cpy_tensor, graph_compute, alloc_buffer,
  get_alignment, get_max_size. All these paths now return failure
  gracefully instead of aborting the process.
- include/llama-hydra.h: Added llama_hydra_validate_quant_parity API
  for SWAP_QUANT tensor validation.
- src/llama-hydra.cpp: Implemented validation — opens target GGUF,
  iterates tensors matching pattern, compares shapes/types against
  loaded model.
- tools/server/server-context.h/cpp: SWAP_QUANT handler now resolves
  quant_key, calls validate, returns validation JSON. Added startup
  stage tracking (1-4) for staged health endpoint.
- tools/llama-engine/llama-engine.cpp: Set startup stages during init,
  augmented /health with staged readiness info. Added silent
  consumption of removed --yarn-ext-ctx / --yarn-orig-ctx flags.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
ddvnguyen added a commit that referenced this pull request Jul 6, 2026
…ness

Replaces the fail-open approach (which masked the crash and introduced a
worse one) with the gate-then-degrade design. Fixes the ggml-org#376 startup race
at its source.

ggml-rpc.cpp (Step 1 — restore fail-stop transport):
- Revert RPC_STATUS_ASSERT from log-only back to GGML_ABORT. The log-only
  macro let 4 unconverted query helpers (get_max_size/get_alloc_size/
  get_device_memory/get_device_count) fall through and return an
  UNINITIALIZED response struct on peer failure — garbage sizes/counts,
  a non-deterministic downstream crash. Fail-stop is correct for the
  transport; recovery belongs one layer up.
- buffer_free_buffer: keep the null-socket guard but make the send itself
  fail-SOFT (log, don't abort) so degrade-to-solo / shutdown teardown can
  tolerate an already-gone peer.
- Zero-initialize the 4 query response structs as defense-in-depth.
- Keep the legitimate null-socket guards and graph_compute/init_tensor
  GGML_STATUS_FAILED returns added earlier.

llama-engine.cpp (Step 3+6 — readiness gate, the actual ggml-org#376 fix):
- New wait_for_peer_ready(): before registering the peer, poll the peer's
  staged /health (optional, via --peer-health-url) until rpc_active, then
  retry the RPC HELLO handshake (safe post-#26). Bounded (180s). On timeout
  the head loads SOLO — never aborts, never crash-loops.
- has_peer block now gates via wait_for_peer_ready instead of a cold
  ggml_backend_rpc_add_server that races the peer's startup.
- Add --peer-health-url flag.

Deferred to follow-up (documented in the ggml-org#376 plan on PR #31; require a
CUDA build env to verify safely — not attempted blind):
- Step 2: HTTP-before-load reorder (staged /health observable during load).
- Step 4: runtime degrade-to-solo on mid-inference peer loss.
- Step 5: combined/degraded fields on /health + INFO.
- Phase C (quant-parity) still bundled; split to its own PR.

NOT built here (no CUDA/2-GPU env in this session); changes reviewed by
inspection. Needs cmake --build build_sm86_sm120 --target llama-engine.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant