Skip to content

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:

SurfaceBest forRequires Server?Entry Points
Inline Harness MCP + local-runtimeFast folder-local model acquisition, format conversion, graph optimization, quantization, and OCR/VLM pipelines directly inside kompile chat or MCP stdioNo (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 promotionYes (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 actionWhat it does
statusLists ready local artifacts and runtime readiness in <project>/data/models
bootstrapDownloads and provisions configured remote model artifacts from the pinned manifest
importProvisions a model from a remote source or binds an existing localPath in place
convertRuns standalone kompile-model convert on local ONNX, TensorFlow, Keras, GGUF/GGML, or SafeTensors files
optimizeRuns 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_runtime to convert ./weights/qwen3-4b-q4.gguf into data/models/qwen3-4b.sdz with weightDtype=int4 so it runs via runtime-quantized matmul."

Optimize a converted ONNX encoder with the Transformer profile:"Preview a TRANSFORMER graph optimization pass (dryRun=true) on data/models/bge-base.sdz using model_runtime, then write the optimized graph to data/models/bge-base-opt.sdz."

Bind and run a local VLM pipeline:"Register ./models/florence-2 via vlm_model_definition and test an OCR extraction step via pipeline."

Direct standalone CLI equivalents ​

The same request-scoped engine runs directly from the shell via kompile-model / kompile-model-staging:

bash
# 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 int8

2. 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 FormatExtensions / SourcesNotes
ONNX.onnxFull SameDiff graph import (OnnxFrameworkImporterService); ideal for encoders, rerankers, vision, and custom models
GGUF / GGML.gguf, .ggmlNative parser with configurable weightDtype (fp32, fp16, bf16, fp8, fp8_e5m2, int8, int4)
SafeTensors.safetensorsDirect HuggingFace weight import without pickle execution
TensorFlow.pb, checkpointsFrozen graph import (TensorFlowImporterService)
Keras.h5, .kerasSequential and functional model import (KerasImporterService)
HuggingFace & .karchRepo IDs / .karch bundlesResumable 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) ​

ProfileIntended use
NONENo passes (baseline / validation)
BASICCleanup, constant folding, and algebraic simplification
TRANSFORMERCleanup + simplification + attention, RMSNorm, SwiGLU/Swish, horizontal MatMul, and linear layer fusions
GPUTransformer/fusion stack plus GPU-targeted layout and hardware passes
FULLComplete default optimization stack across multiple convergence iterations (maxIterations)

All 23 GraphOptimizer Passes ​

CategoryPass IDsWhat they do
Cleanup & FoldingUNUSED_FUNCTION, CONSTANT_FUNCTION, IDENTITY_FUNCTION, REDUNDANCY_ELIMINATION, COMMON_SUBEXPRESSION_ELIMINATIONPrunes dead subgraphs, pre-evaluates constant ops, strips no-op identities/slices/gathers, and deduplicates identical ops
Algebraic & SimplificationBROADCAST_ELIMINATION, REORDERING, ALGEBRAIC, PEEPHOLE, ARITHMETIC_CHAIN, STRENGTH_REDUCTION, CONCAT_SPLIT, SELECT_WHERESimplifies 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 FusionSHAPE_FUNCTION, ATTENTION_FUSION, HORIZONTAL_FUSION, MATMUL_CHAIN, ACTIVATION_FUSION, NORMALIZATION_FUSION, LINEAR_FUSION, REMATERIALIZATIONFuses 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 & HardwareQUANTIZATION, CUDNN_FUNCTIONCompresses 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) ​

MethodIDHow it works
Full Fine-TuningfinetuneUpdates all trainable SameDiff graph parameters end-to-end on JSONL datasets
LoRALORAInjects trainable low-rank decomposition matrices (A, B) into attention/projection weights
QLoRAQLORATrains LoRA adapters over a frozen 4-bit quantized base (using ggml_qmatmul_lora over packed GGUF weights) for low-VRAM fine-tuning
AdaLoRAADALORADynamically reallocates rank/parameter budget across weight matrices by importance score during training
DyLoRADYLORATrains LoRA blocks across a range of ranks simultaneously so inference can pick rank dynamically
DoRADORAWeight-Decomposed Low-Rank Adaptation splitting updates into magnitude and direction components
IA³IA3Infused Adapter learning lightweight rescaling vectors over inner activations with minimal parameters
Prompt TuningPROMPT_TUNINGPrepends trainable soft-prompt tokens while keeping the entire base model frozen
Prefix TuningPREFIX_TUNINGPrepends 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):

AlgorithmFamilyTypical use
DPODirect Preference OptimizationAligning preference pairs (chosen vs. rejected) without a separate reward model
ORPOOdds Ratio Preference OptimizationSingle-stage supervised fine-tuning + preference alignment without a reference model
KTOKahneman-Tversky OptimizationTraining from binary thumbs-up / thumbs-down feedback without paired completions
GRPOGroup Relative Policy OptimizationReasoning and verifiable-reward RL using group-normalized rewards (no value network)
PPOProximal Policy OptimizationClassic policy-gradient RL optimization against a reward signal
RLHFReinforcement Learning from Human FeedbackReward-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 ​

  1. Resolve candidate directions (RefusalDirectionFinder): Supply either explicit per-layer direction vectors (directions) or contrastive activation sets (harmfulActivations vs. harmlessActivations) collected across target layers.
  2. Select & stabilize directions: Filter candidate layers via layerSelectionStrategy and topK, with optional outlier clamping (winsorize / winsorizePercentile) and configurable ablationStrength.
  3. Orthogonalize weights (WeightOrthogonalizer): Projects out the selected direction(s) from every weight tensor matching targetWeightPatterns directly inside the loaded SameDiff graph.
  4. Emit a deployable artifact + manifest: Saves <outputModelId>.fb alongside a structured ABLITERATION training 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_model or kompile-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, and vlm_model_definition tools directly in kompile chat — ideal for import, conversion, graph optimization, quantization, and local OCR/VLM execution.
  • Full staging + training + alignment + evaluation from chat: Register http://localhost:8090 as a custom SSE MCP server (see Custom MCP Servers) so your coding agent can search and invoke staging_* tools via mcp_tool_search and mcp_tool_call.

Released under the Apache-2.0 License.