Skip to content

feat(bailing_hybrid): Ling-3.0 KDA + MLA hybrid MoE backbone (P0, #672) - #759

Merged
goodmai merged 2 commits into
mainfrom
feat/672-bailing-hybrid-p0
Nov 24, 2026
Merged

goodmai merged 2 commits into
mainfrom
feat/672-bailing-hybrid-p0

Conversation

@goodmai

@goodmai goodmai commented Nov 24, 2026

Copy link
Copy Markdown
Owner

Part of #672 (Phase P0: runnable bailing_hybrid backbone in plain MLX ops + tiny parity & all-family integration).

Summary

  • Architecture (Sources/BasaltInference/Models/BailingHybrid/):
    • BailingHybridConfiguration.swift: Codable, Sendable, Equatable config supporting short_conv_kernel_size / conv_kernel_size, no_kda_lora / use_kda_lora, MLA LoRA / RoPE / head-wise or element-wise output gate granularity, noaux_tc MoE routing, isMLALayer(_:) group + trailing remainder schedule, and validated() typed throws.
    • BailingHybridKDA.swift: Kimi Delta Attention with causal depthwise short-conv (*_conv1d.conv.weight [C, K, 1], fp) + SiLU + rolling history in ArraysCache(size: 4) slots 0–2, L2-normalized q/k (x / (||x|| + 1e-6)) with q scaled by d^-0.5, fp32 per-channel safe gate lowerBound * sigmoid(exp(A_log) * (f + dt_bias)) (plus softplus fallback & full/LoRA gate projections), fp32 delta-rule recurrence in slot 3, gated o_norm -> o_proj.
    • BailingHybridMLA.swift: DeepSeek-V3-style MLA (q_a_proj/q_a_layernorm/q_b_proj or direct q_proj, kv_a_proj_with_mqa/kv_a_layernorm/kv_b_proj), interleaved RoPE (traditional: ropeInterleave) with cache?.ropeOffset, attentionWithCacheUpdate, head-wise / element-wise output gate sigmoid(g_proj(x)), and dense output projection.
    • BailingHybridMoE.swift: Sigmoid router with expert_bias + noaux_tc group selection (top-topk_group groups by sum of top-2 biased scores, top-k experts, unbiased normalized sigmoid weights × routed_scaling_factor), stacked SwitchGLU experts (experts), optional shared_experts, and dense SwiGLU for layer < first_k_dense_replace.
    • BailingHybridModel.swift: Decoder layer, inner model, BailingHybridModel (LLMModel, KVCacheDimensionProvider, LoRAModel, BasaltProbableModel, toolCallFormat: .glm4), hybrid newCache (ArraysCache(size: 4) on KDA, KVCacheSimple on MLA), sanitize(weights:) (drops MTP / out-of-range layers / tied lm_head / disabled expert_bias, atomically stacks unmerged experts, canonicalizes 2D & 3D conv weights, calls FlintModel.quantizeModulesMatchingPackedWeights).
  • Registration, Capabilities, Profile & Geometry:
    • Registered "bailing_hybrid" in LLMTypeRegistry and VLMTypeRegistry via MLXInferenceEngine.registerBailingHybridAliases().
    • Added ModelCapabilities row ([.batchedDecode, .promptCacheReuse, .grammarJumpForward]; lookup, KV quantization/zones/head-split, Quest, MTP, CacheBlend stay off for P0).
    • Added BailingHybridProfile (<think>/</think>, enable_thinking, detailed thinking on|off, 16_384 default max tokens) and table-driven exact lookup in ModelProfileRegistry.
    • Extended KVCacheGeometry (layer_group_size + kv_lora_rank schedule and KDA fixed state bytes), AnatomyScan (word_embeddings, .experts., reflected linear-attention heads), and MLXInferenceEngine.cacheIsHybrid (ArraysCache recurrent-state detection so multi-turn anchor snapshots activate).
  • Tests:
    • Added TinyModel.Family.bailingHybrid (6 layers [KDA, KDA, MLA] × 2, head_dim = 32, 8 experts top-2 in 4 groups keep 2, first_k_dense_replace = 1) and wired all-family suites (TinyModelFixtureTests, CausalityTests, FeatureMatrixTests, TokenTraceParityTests, BatchedDecoderTests, BatchedRoutingTests, GenerationPlanTests).
    • Added BailingHybridTests.swift and BailingHybridIntegrationTests.swift covering CPU reference parity (< 1e-5), full vs chunked (1, 3, 7) decode parity (< 1e-4, exact greedy IDs), optional architecture variants, packed-weight sanitize & ModelDeepCheck / ModelInspector round-trip, and PromptCacheTree + PromptCacheDiskStore snapshot parity.

7-Round Self-Review Summary

  1. Math & architecture parity: Fixed BailingHybridRouter.route expertMask probe under sigmoid + positive expert_bias (mask applied after bias); guarded empty steps == 0 in KDA recurrence and short-conv; matched Metal kernel masked-output zeroing in recurrentStep; eliminated all force unwraps (!); moved MLA ForwardProbe.headOutputs post-gate to match KDA; added even qk_rope_head_dim validation.
  2. Quantization & sanitize edge cases: Made stackExpertPart atomic (verify all experts present before mutating dict) and removed brittle gate_proj-only gate; tightened MTP key drop prefixes; dropped unused expert_bias when moe_router_enable_expert_bias == false; verified dual quantization + quantization_config checkpoints do not double-quantize.
  3. Cache & decode edge cases: Fixed MLXInferenceEngine.cacheIsHybrid checking MambaCache instead of ArraysCache (which disabled multi-turn anchor snapshots for bailing_hybrid); tightened bailingLinearStateBytes predicate to require kv_lora_rank; verified PromptCacheDiskStore save/load round-trip parity.
  4. Concurrency & race audit: Verified zero new concurrency hatches, zero mutable globals, all config/profile/router-config types pure Sendable values, all MLX objects isolated inside ModelContainer.
  5. Size, CCN & lean cleanup: Removed unused stored properties (projDim, convKernelSize, qLoraRank, BailingHybridDecoderLayer.layerIdx), added KDA kvHeads reflection for AnatomyScan, split ModelProfileRegistry exact lookup (CCN 16 → 14), split MLXInferenceEngine+Loading.swift extension (≤ 150 NLOC), split TinyModels / GenerationPlanTests / BailingHybrid*Tests so zero limits exceed or grow.
  6. Coverage & release build: Achieved 96.4% (815/845) changed-line coverage, 5× repetition determinism pass (65/65), and zero-warning release build (swift build -c release -Xswiftc -warnings-as-errors).
  7. Final verification: Rebased cleanly onto origin/main (e35d2a5), passed all static gates and 95 tests across 12 affected suites.

Verification Gates

  • swift scripts/check_no_new_comments.swift origin/main: PASS (No comments added.)
  • swift scripts/check_size_limits.swift origin/main --impact: PASS
    Impact: 13 Swift file(s) in Sources, 61 of 8258 functions in Sources touched (0.7%), CCN sum 351 → 521, largest CCN 15 → 14
    No size or complexity limit exceeded or grown.
  • swift scripts/check_concurrency_hatches.swift: PASS (No concurrency hatch outside scripts/concurrency-hatches.allow.)
  • swift build -Xswiftc -warnings-as-errors: PASS
  • swift build -c release -Xswiftc -warnings-as-errors: PASS (318.16s)
  • swift test --maximum-repetitions 5 --repeat-until fail --filter "BailingHybridTests|BailingHybridIntegrationTests": PASS (13 tests × 5 repetitions = 65 runs, 9.33s)
  • swift scripts/check_changed_coverage.swift <codecov> origin/main: PASS (Changed-line coverage: 96.4% (815/845), minimum 60%.)
  • SWT_EXPERIMENTAL_MAXIMUM_PARALLELIZATION_WIDTH=4 swift test --parallel --filter "BailingHybridTests|BailingHybridIntegrationTests|TinyModelFixtureTests|CausalityTests|GenerationPlanTests|TokenTraceParityTests|FeatureMatrixTests|BatchedDecoderTests|BatchedRoutingTests|KVCacheGeometryTests|PromptCacheDiskTests|ModelDeepCheckTests|ModelProfileTests": PASS (95 tests in 12 suites, 215.19s)

goodmai and others added 2 commits November 24, 2026 11:14
… recurrent state, so Inkling 2's conv ArraysCache does not turn on anchor search (#672 review)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012cicguZMN3jhNGmf5327oh
@goodmai

goodmai commented Nov 24, 2026

Copy link
Copy Markdown
Owner Author

Review at the owner's request. Rebased on main 4ca5435 (#733), plus one fix commit:

  • hasRecurrentState had moved from $0 is MambaCache to $0 is ArraysCache. That also matches Inkling 2's conv-only ArraysCache, so findsAnchors would switch on for Inkling and change its prompt-cache memory and time. The check is now MambaCache or context.model is BailingHybridModel, so Bailing keeps its anchors and Inkling is unchanged.

Run locally on the rebased branch: BailingHybrid, GenerationPlan, PromptCache, Inkling, BatchedDecodingIsolation, TokenTrace, FeatureMatrix, ModelProfile, KVCacheGeometry and Anatomy. 211 tests, all pass. The fixture move to extendedConfig keeps every config unchanged, since the goldens pass.

@goodmai
goodmai force-pushed the feat/672-bailing-hybrid-p0 branch from 0a11408 to b2a9b0e Compare November 24, 2026 10:22
@goodmai
goodmai merged commit 9403f42 into main Nov 24, 2026
8 of 9 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.

1 participant