Skip to content

Studio: split core/inference/llama_cpp.py into a package - #13990

Open
csun365 wants to merge 1 commit into
unslothai:mainfrom
csun365:studio/llama-cpp-package
Open

csun365 wants to merge 1 commit into
unslothai:mainfrom
csun365:studio/llama-cpp-package

Conversation

@csun365

@csun365 csun365 commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Studio: split core/inference/llama_cpp.py into a package

studio/backend/core/inference/llama_cpp.py was 43,872 lines and 2.3 MB: ~300 module-level
helpers followed by one LlamaCppBackend class with 525 methods (load_model alone is 9,500
lines). This moves it, statement by statement, into core/inference/llama_cpp/: 22 helper
modules by topic, 21 mixin modules that follow the class's own section banners, backend.py
composing LlamaCppBackend from the mixins, and an __init__ that keeps the old module's
surface.

What moved where

  • Helpers: compaction, core_types, server_log, binary_runtime, answer_artifacts,
    tool_loop_text, gguf_cache, swa_cache, hf_offline, reasoning, drafters,
    load_markers, memory_policy, launch_flags, placement_args, draft_args, batch_args,
    moe_cache, spec_args, timings, launch_support, log.
  • The class, one mixin per section banner (# ── GPU allocation ── and friends), with the
    6,500-line GPU section split in three and the 16,000-line lifecycle section in seven:
    backend_properties, backend_binary, backend_capabilities, backend_gpu_devices,
    backend_gpu_memory, backend_gpu_fit, backend_kv_cache, backend_download,
    backend_process_io, backend_diffusion, backend_preflight, backend_start_failures,
    backend_launch_retries, backend_load, backend_shutdown, backend_spill,
    backend_slots, backend_health, backend_generation, backend_tool_loop,
    backend_tokens. backend.py holds the docstring, the two locks and __init__.
  • The largest module is backend_load.py at 10,600 lines because load_model is one method.

How the move was made

Mechanically. A script read the old file's AST, assigned every top-level and class-body
statement to a module by line range (comments and blank lines travel with the statement that
follows them), computed each module's imports from the compiler's own symbol table
(symtable), refused on any import cycle, and asserted that every source line of the old file
landed in exactly one module. Only four edits were made to the moved text, each asserted to
match once:

  • logger = get_logger(__name__) keeps the literal name "core.inference.llama_cpp", so log
    records and the tests that patch llama_cpp.logger see one logger;
  • two Path(__file__).resolve().parents[4] become parents[5]: the package is one directory
    deeper (_find_llama_server_binary, _kill_orphaned_servers);
  • Path(__file__).with_name("_vulkan_probe.py") resolves the sibling probe from the package's
    parent directory.

The committed files are that output passed through scripts/run_ruff_format.py, which only
wrapped a few long import lines in the generated headers; a diff of the regenerated package
against the committed one touches no moved code.

What the facade keeps true

The old module was also a seam: 33 production modules import 153 distinct names from it
(routes/inference.py alone imports from it at module level), and the test suite patches 163
distinct names on the module object, by attribute and by string. __init__ therefore:

  • re-exports every name the old module defined (550 definitions) and repeats its import block,
    so from core.inference.llama_cpp import X and llama_cpp.subprocess are unchanged;
  • is a ModuleType subclass whose __setattr__ rebinds the same object in every submodule
    that imported it. monkeypatch.setattr(llama_cpp, "cached_gguf_for_load", fake) reaches the
    three modules that call it, and the undo restores them; a name two modules bind to different
    objects is left alone;
  • reads the two globals a function rebinds with global (_SWA_CACHE,
    _CHAT_LOADS_IN_FLIGHT) live from their owning module instead of copying them, and writes
    them back there;
  • binds LlamaCppBackend into the 15 submodules whose static methods call
    LlamaCppBackend.<helper> by name, after the class exists, as the one module's global used
    to resolve.

What changes for callers: inspect.getsource(LlamaCppBackend) now returns the composing
class body, and LlamaCppBackend.__dict__["method"] no longer finds mixin methods
(inspect.getattr_static does). Both only affected tests, updated below.

Tests

  • 37 test files read llama_cpp.py off disk or through inspect.getsource, and three frontend
    parity tests read it with readFileSync. They now read the package through one helper,
    tests/_shared/llama_cpp_source.py (package_source(), package_tree(), class_source(),
    module_source()), and studio/frontend/tests/helpers/backend-llama-cpp-source.ts. The
    concatenation leaves __init__ out so a scan that looks a constant up by name finds its
    definition, not the re-export list. Checks that compared positions across the file were
    verified to compare positions inside one module (load_model for most of them).
  • tests/tools/refactor_guard.py accepts a package directory for core.inference.llama_cpp;
    its recorded baseline was NOT regenerated, and verify passes against it: no symbol
    dropped, every string patch target in the suite still resolves.
  • New studio/backend/tests/test_llama_cpp_package_layout.py (19 tests) pins the package's
    own contract: every definition exported once and identical to the owner's; the recorded
    refactor-guard inventory is a subset of what the package defines; patch propagation and undo;
    live globals; global targets owned and never copied; submodules import siblings relatively
    and never the package; the class is bound wherever named and no two mixins define one
    attribute; every from core.inference.llama_cpp import ... in production code (lazy ones and
    every routes/*.py included) names an attribute the package has; the parents[5] and
    _vulkan_probe.py lookups resolve.
  • test_orchestrator_unload_cancel.py treats the package as one spawner unit, as it treated
    the one file: the diffusion runner is adopted in backend_diffusion and the shutdown latch
    is consulted in backend_load.
  • test_gpu_memory_nvml_fallback.py patches __file__ on the module that owns the finder,
    one directory deeper.

Results

Measured on an M2 Pro Mac (CPU torch, no llama-server runs), the whole studio/backend
suite as the backend CI job runs it (same --ignore list, -n 5), on a pristine worktree at
the base commit and on this branch:

Suite Base commit This branch
studio/backend/tests 72,420 passed, 391 failed, 103 errors 72,494 passed, 392 failed, 103 errors
tests/studio 13,683 passed, 44 failed 13,686 passed, 44 failed

The failure sets are the same 44 names for tests/studio. For the backend suite, every
failure present on one side only passes when rerun on its own on both trees, and the set
shifts between two runs of the same tree: order- and timing-dependent tests
(test_llama_cpp_placement, test_slot_reduction_context_refit, test_decision_serving,
test_conversation_archive), not the split. The 391 shared failures are Mac-only: /proc,
nvidia-smi, readelf, non-UTF-8 paths on APFS, and the ltx2 pipeline import against
transformers 5.5.

Also checked:

  • python tests/tools/refactor_guard.py verify passes against the recorded baseline.
  • studio/backend/tests/test_llama_cpp_package_layout.py: 19 passed.
  • All 41 routes/*.py modules import; the FastAPI route table and the OpenAPI document
    digest are identical between the two trees; unsloth studio --api-only boots to a healthy
    /api/health serving 528 paths.
  • Steady-state import core.inference.llama_cpp: 0.13 s before, 0.14 s after.
  • Frontend: the three parity tests pass, npm run typecheck passes, biome reports nothing new.
  • scripts/run_ruff_format.py (ruff 0.6.9) and ruff check with the repo's rules are clean.

Not covered

  • Runtime behaviour on a GPU host: no CUDA, ROCm or Metal-with-llama-server runs here. The
    moved code is byte-identical and the import graph is verified, so the risk is in name
    resolution, which the suite exercises on CPU.
  • codespell reports unparseable and CANN in the moved text; both are pre-existing.

🤖 Generated with Claude Code

The module was 43,872 lines: ~300 helpers and one LlamaCppBackend class
with 525 methods. It is now core/inference/llama_cpp/, 22 helper modules
by topic, 21 mixin modules following the class's section banners,
backend.py composing the class, and an __init__ that keeps the module's
surface.

Every statement moved verbatim, by a script that assigned statements by
line range, derived imports from the compiler's symbol table, refused
import cycles and checked that every old line landed exactly once. Four
edits to moved text: the logger keeps its old name as a literal, two
parents[4] lookups become parents[5], and the _vulkan_probe.py sibling is
resolved from the package's parent.

__init__ re-exports every definition, repeats the old import block, and
is a ModuleType subclass whose __setattr__ rebinds the same object in
every submodule alias, so the 163 names the suite patches on the module
still reach the code that reads them. The two globals rebound with
`global` are read live from their owner. LlamaCppBackend is bound into
the 15 submodules whose static methods name it.

Tests that read the file by path or getsource read the package through
tests/_shared/llama_cpp_source.py; refactor_guard accepts a package and
verifies against its unchanged baseline; a new layout test pins the
facade, propagation, live globals, import graph, every production
import (routes included) and the file-depth lookups.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

This branch has not been deployed

No deployments
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.

2 participants