Model Import, Optimization, Fine-Tuning & Abliteration
Kompile's local model engine is a complete model engineering stack built on Eclipse DL4J / SameDiff — not just an inference wrapper. Underneath local chat and embeddings, Kompile supports multi-format model import, a 23-pass graph optimizer & Triton compiler, full fine-tuning & 8 PEFT methods, knowledge distillation, 6 post-training alignment algorithms, and training-free abliteration (weight orthogonalization).
You can drive these capabilities through two complementary surfaces:
| Surface | Best for | Requires Server? | Entry Points |
|---|---|---|---|
Inline Harness MCP + local-runtime | Fast folder-local model acquisition, format conversion, graph optimization, quantization, and OCR/VLM pipelines directly inside kompile chat or MCP stdio | No (request-scoped subprocesses with guaranteed teardown) | model_runtime (status, bootstrap, import, convert, optimize), pipeline, vlm_model_definition, kompile-model CLI |
Model Staging Service (:8090) | Full training jobs, PEFT adapter creation/merging, distillation, alignment, abliteration, evaluation suites, Triton compilation jobs, .karch archives, and zero-downtime hot-swap promotion | Yes (kompile-model-staging on :8090) | Angular UI, REST API (/api/...), and 90+ staging_* MCP tools over SSE |
1. Inline Model Engineering in the CLI Harness (model_runtime)
When the local-runtime companion overlay is installed, agents in kompile chat or external MCP clients can inspect, acquire, convert, and optimize models inside the active project folder (<project>/data/models) with zero server setup using model_runtime:
model_runtime action | What it does |
|---|---|
status | Lists ready local artifacts and runtime readiness in <project>/data/models |
bootstrap | Downloads and provisions configured remote model artifacts from the pinned manifest |
import | Provisions a model from a remote source or binds an existing localPath in place |
convert | Runs standalone kompile-model convert on local ONNX, TensorFlow, Keras, GGUF/GGML, or SafeTensors files |
optimize | Runs SameDiff's provider-neutral GraphOptimizer with selectable profiles, explicit passes, quantization, .backup safety, and dryRun preview |
Example conversational workflows in kompile chat
Convert a GGUF model keeping packed INT4 weights:"Use
model_runtimeto convert./weights/qwen3-4b-q4.ggufintodata/models/qwen3-4b.sdzwithweightDtype=int4so it runs via runtime-quantized matmul."
Optimize a converted ONNX encoder with the Transformer profile:"Preview a
TRANSFORMERgraph optimization pass (dryRun=true) ondata/models/bge-base.sdzusingmodel_runtime, then write the optimized graph todata/models/bge-base-opt.sdz."
Bind and run a local VLM pipeline:"Register
./models/florence-2viavlm_model_definitionand test an OCR extraction step viapipeline."
Direct standalone CLI equivalents
The same request-scoped engine runs directly from the shell via kompile-model / kompile-model-staging:
# Convert ONNX / TensorFlow / Keras / GGUF / SafeTensors -> SameDiff (.sdz)
kompile-model convert -i ./model.onnx -o ./model.sdz
kompile-model convert -i ./qwen.gguf -o ./qwen.sdz --weight-dtype int4
# Optimize a local SameDiff artifact in place (creates .backup by default) or to a new file
kompile-model optimize -i ./model.sdz -o ./model-opt.sdz --profile TRANSFORMER --max-iterations 3
# Dry-run pass resolution or select exact passes + quantization
kompile-model optimize -i ./model.sdz --passes ATTENTION_FUSION,NORMALIZATION_FUSION,ACTIVATION_FUSION --dry-run
kompile-model optimize -i ./model.sdz -o ./model-int8.sdz --profile FULL --quantization-type int82. Multi-Format Model Import & Storage Precision
Kompile imports models from all major training and distribution ecosystems into its unified SameDiff graph representation (.sdz / sharded .sdnb / .fb), auto-detecting formats from file extensions or explicit --format:
| Input Format | Extensions / Sources | Notes |
|---|---|---|
| ONNX | .onnx | Full SameDiff graph import (OnnxFrameworkImporterService); ideal for encoders, rerankers, vision, and custom models |
| GGUF / GGML | .gguf, .ggml | Native parser with configurable weightDtype (fp32, fp16, bf16, fp8, fp8_e5m2, int8, int4) |
| SafeTensors | .safetensors | Direct HuggingFace weight import without pickle execution |
| TensorFlow | .pb, checkpoints | Frozen graph import (TensorFlowImporterService) |
| Keras | .h5, .keras | Sequential and functional model import (KerasImporterService) |
HuggingFace & .karch | Repo IDs / .karch bundles | Resumable HF downloads (kompile local-models download) and checksum-verified air-gapped .karch archives |
GGUF weightDtype choices
fp16(default) /bf16/fp32/fp8/fp8_e5m2— dense dequantized weights at conversion time.int4/int8— keeps GGUF-packed quantized blocks intact for runtime-quantized matrix multiplication (ggml_qmatmul), drastically cutting VRAM footprint and enabling QLoRA adapter training directly over frozen packed blocks (ggml_qmatmul_lora).
3. Graph & Model Optimization (23 Passes + Triton Compiler)
Both inline model_runtime action=optimize and Model Staging (staging_optimize_model / staging_compiler_optimize) execute ND4J's provider-neutral GraphOptimizer.
Built-in Optimization Profiles (--profile)
| Profile | Intended use |
|---|---|
NONE | No passes (baseline / validation) |
BASIC | Cleanup, constant folding, and algebraic simplification |
TRANSFORMER | Cleanup + simplification + attention, RMSNorm, SwiGLU/Swish, horizontal MatMul, and linear layer fusions |
GPU | Transformer/fusion stack plus GPU-targeted layout and hardware passes |
FULL | Complete default optimization stack across multiple convergence iterations (maxIterations) |
All 23 GraphOptimizer Passes
| Category | Pass IDs | What they do |
|---|---|---|
| Cleanup & Folding | UNUSED_FUNCTION, CONSTANT_FUNCTION, IDENTITY_FUNCTION, REDUNDANCY_ELIMINATION, COMMON_SUBEXPRESSION_ELIMINATION | Prunes dead subgraphs, pre-evaluates constant ops, strips no-op identities/slices/gathers, and deduplicates identical ops |
| Algebraic & Simplification | BROADCAST_ELIMINATION, REORDERING, ALGEBRAIC, PEEPHOLE, ARITHMETIC_CHAIN, STRENGTH_REDUCTION, CONCAT_SPLIT, SELECT_WHERE | Simplifies identities (x+0, x*1, pow(x,2) -> square(x), div(x,c) -> mul(x,1/c)), folds arithmetic chains, flattens nested concats, and eliminates inverse pairs |
| Transformer & Operator Fusion | SHAPE_FUNCTION, ATTENTION_FUSION, HORIZONTAL_FUSION, MATMUL_CHAIN, ACTIVATION_FUSION, NORMALIZATION_FUSION, LINEAR_FUSION, REMATERIALIZATION | Fuses multi-head attention patterns, merges parallel matmuls sharing an input, absorbs transposes into matmul flags, fuses Swish / SwiGLU activations, fuses RMSNorm subgraphs, fuses matmul+add into xw_plus_b, and shortens live variable ranges to cut peak memory |
| Quantization & Hardware | QUANTIZATION, CUDNN_FUNCTION | Compresses weights to INT8, UINT8, FLOAT16, or BFLOAT16; lowers eligible CUDA ops to cuDNN |
Triton GPU Compilation & Graph Benchmarking
In Model Staging (:8090), CompilerService layers Triton GPU kernel compilation, compiled-graph caching, async compilation jobs, and before/after benchmarks on top of GraphOptimizer:
- Inspect graph op counts and memory footprint (
staging_get_graph_info) - Compare optimized vs. unoptimized graphs (
staging_compare_graphs) or precision variants (staging_compare_models) - Compile and cache Triton kernels asynchronously (
staging_compile_triton,staging_start_compilation_job,staging_save_compiled_graph)
4. Fine-Tuning & Parameter-Efficient Fine-Tuning (8 PEFT Methods)
All fine-tuning runs inside an isolated training subprocess (TrainingSubprocessMain) so heavy backward passes never contend with CLI or server stability, with built-in JSONL dataset management (DatasetService), configurable updaters/LR schedules, and live SSE logs and metrics.
Full Fine-Tuning & 8 PEFT Methods (PeftService)
| Method | ID | How it works |
|---|---|---|
| Full Fine-Tuning | finetune | Updates all trainable SameDiff graph parameters end-to-end on JSONL datasets |
| LoRA | LORA | Injects trainable low-rank decomposition matrices (A, B) into attention/projection weights |
| QLoRA | QLORA | Trains LoRA adapters over a frozen 4-bit quantized base (using ggml_qmatmul_lora over packed GGUF weights) for low-VRAM fine-tuning |
| AdaLoRA | ADALORA | Dynamically reallocates rank/parameter budget across weight matrices by importance score during training |
| DyLoRA | DYLORA | Trains LoRA blocks across a range of ranks simultaneously so inference can pick rank dynamically |
| DoRA | DORA | Weight-Decomposed Low-Rank Adaptation splitting updates into magnitude and direction components |
| IA³ | IA3 | Infused Adapter learning lightweight rescaling vectors over inner activations with minimal parameters |
| Prompt Tuning | PROMPT_TUNING | Prepends trainable soft-prompt tokens while keeping the entire base model frozen |
| Prefix Tuning | PREFIX_TUNING | Prepends trainable key/value prefix vectors to each transformer layer |
After training a PEFT adapter, merge adapters cleanly back into a standalone deployable artifact with staging_merge_peft_weights, inspect trainable vs. total parameter ratios with staging_get_peft_info, and promote with zero downtime (staging_promote_model).
5. Knowledge Distillation & Post-Training Alignment
Logit Knowledge Distillation (DistillationService)
Runs in the same isolated TrainingSubprocessMain lifecycle as fine-tuning and PEFT:
- Objective (
LOGIT_KD): Transfers capability from a larger teacher model to a compact student model by matching raw teacher and student logits with temperature-scaled KL divergence. - Controlled via REST or MCP (
staging_start_distillation,staging_get_distillation_job,staging_cancel_distillation) with live SSE log streaming.
Post-Training Alignment (AlignmentService)
Supports 6 alignment algorithms with PEFT integration and live SSE progress tracking (staging_start_alignment, staging_list_alignment_algorithms):
| Algorithm | Family | Typical use |
|---|---|---|
| DPO | Direct Preference Optimization | Aligning preference pairs (chosen vs. rejected) without a separate reward model |
| ORPO | Odds Ratio Preference Optimization | Single-stage supervised fine-tuning + preference alignment without a reference model |
| KTO | Kahneman-Tversky Optimization | Training from binary thumbs-up / thumbs-down feedback without paired completions |
| GRPO | Group Relative Policy Optimization | Reasoning and verifiable-reward RL using group-normalized rewards (no value network) |
| PPO | Proximal Policy Optimization | Classic policy-gradient RL optimization against a reward signal |
| RLHF | Reinforcement Learning from Human Feedback | Reward-model-guided alignment loop |
6. Training-Free Model Editing & Abliteration (AbliterationService)
Kompile includes first-class training-free abliteration / weight orthogonalization (org.eclipse.deeplearning4j.llm.editing, exposed via POST /api/abliteration/apply in kompile-model-staging) for modifying specific behavioral or refusal directions in a SameDiff model without running a training loop or updating gradients.
How it works
- Resolve candidate directions (
RefusalDirectionFinder): Supply either explicit per-layer direction vectors (directions) or contrastive activation sets (harmfulActivationsvs.harmlessActivations) collected across target layers. - Select & stabilize directions: Filter candidate layers via
layerSelectionStrategyandtopK, with optional outlier clamping (winsorize/winsorizePercentile) and configurableablationStrength. - Orthogonalize weights (
WeightOrthogonalizer): Projects out the selected direction(s) from every weight tensor matchingtargetWeightPatternsdirectly inside the loaded SameDiff graph. - Emit a deployable artifact + manifest: Saves
<outputModelId>.fbalongside a structuredABLITERATIONtraining manifest recording applied directions, candidate count, and modified weight tensors so the edited model can be evaluated and promoted through the exact same staging pipeline.
7. Evaluation, Hot-Swap Promotion & Wiring Staging MCP Tools
Evaluation & Zero-Downtime Promotion
- Evaluation suites (
EvaluationService): Run built-in evaluation presets and custom metric checks (staging_evaluate_model,staging_list_evaluation_metrics) before promoting any converted, optimized, fine-tuned, aligned, or abliterated model. - Hot-swap promotion (
StagingService): Promoting a model (staging_promote_modelorkompile-model-staging promote <modelId>) notifies the running Kompile server to swap the active model in memory with no server restart.
Connecting Model Staging's 90+ MCP Tools to Your Chat Agent
When kompile-model-staging is running on :8090, it exposes an MCP SSE server covering the entire staging_* tool catalog (registry, catalog, download, convert, optimize, Triton compile, fine-tuning, 8 PEFT types, distillation, alignment, evaluation, datasets, LLM chat/speculative decoding/pipelines, and VLM OCR):
- Folder-local only (no server): Use Kompile's built-in
model_runtime,pipeline, andvlm_model_definitiontools directly inkompile chat— ideal for import, conversion, graph optimization, quantization, and local OCR/VLM execution. - Full staging + training + alignment + evaluation from chat: Register
http://localhost:8090as a custom SSE MCP server (see Custom MCP Servers) so your coding agent can search and invokestaging_*tools viamcp_tool_searchandmcp_tool_call.
Related Pages
- Local Models &
local-runtime— Installinglocal-runtime,kompile local-models, and lease-pooled local chat. - How the Local Runtime Works — Platform spins, DynamicShapePlan (DSP), compiler backends (Triton, Vulkan, CPU-MLIR, MLX, OpenVINO, ZLUDA), and disk caches.
- Embeddings, Serving & Pipelines — Subprocess isolation, dense embeddings, local LLM serving, and OCR/VLM pipelines.
- Model Staging —
:8090staging lifecycle, OpenAI-compatible serving, and.karcharchives. - MCP Tool Reference — Clickable catalog of all Kompile harness MCP tools (including
model_runtime,pipeline, andvlm_model_definition).