LLM & VLM Stack
Complete guide to the samediff-llm generation pipeline, KV cache management, speculative decoding, continuous batching, tokenizers, evaluation framework, and model editing
Deeplearning4j 1.0.0-rewrite ships a full large language model (LLM) and vision-language model (VLM) application stack built on top of SameDiff. The stack is organized into six new Maven modules that together cover every layer of inference: tokenization, generation, KV cache management, speculative decoding, continuous batching, evaluation, benchmarking, model editing, audio transcription, and a web frontend for ND4J graphs.
This page gives a complete reference for all six modules, with API details and working Java code examples for the most important classes.
1. Overview and Module Map
The LLM stack sits above the existing SameDiff execution engine. SameDiff handles op dispatch and graph execution; the new modules provide the inference-specific infrastructure that production LLM serving requires.
Your Application
│
▼
samediff-llm ← generation pipeline, KV cache, speculative decoding,
continuous batching, tokenizers, evaluation, benchmarking,
model editing
samediff-vlm ← vision-language model support (image+text)
samediff-audio ← Whisper ASR support
nd4j-tokenizers ← Rust-backed HuggingFace / SentencePiece / CLIP tokenizers
nd4j-torchscript ← TorchScript / PyTorch model import
nd4j-web ← TypeScript / FlatBuffers frontend for ND4J graphs
│
▼
SameDiff (ND4J) ← op execution, graph optimization, DSP plan lifecycle
│
▼
libnd4j (C++) ← CPU/CUDA kernels, BLAS, cuDNNThe six modules are independent of each other except that samediff-vlm and samediff-audio depend on samediff-llm, and all of them depend on nd4j-tokenizers.
2. Maven Dependencies
Add only the modules you need. All modules share the same version string.
3. Generation Pipeline
The generation pipeline is the unified entry point for all text generation tasks. It handles model I/O auto-discovery, embedding extraction, tokenization, decode loop construction, and configuration-driven optimization.
Core Classes
GenerationPipeline
Top-level entry point; owns the decode loop and lifecycle
GenerationPipelineConfig
Builder-style configuration for the pipeline
DecodeOptions
Per-call generation parameters (temperature, top-k, etc.)
GenerationResult
Output: token IDs, decoded text, timing data
TextGenerator
Higher-level API with streaming callback support
Sampler / GreedySampler / CompositeSampler
Sampling strategy hierarchy
SamplingConfig / SamplerUtils
Temperature / top-k / top-p config and utilities
DecoderInputBuilder / DecoderUtils
Tensor construction for each decode step
DecodeStepDiagnostics
Per-step diagnostics: token IDs, logit stats, timing
Building a Pipeline
GenerationPipelineConfig uses a fluent builder. All fields are optional; the pipeline performs auto-discovery for any field not set.
Running Generation
Pass per-call options via DecodeOptions. Settings in DecodeOptions override the pipeline-level SamplingConfig for that call only.
Streaming with TextGenerator
TextGenerator wraps GenerationPipeline and adds token-by-token streaming via a callback.
Sampling Strategies
GreedySampler always picks the highest-probability token. CompositeSampler chains a sequence of sampling transforms — temperature scaling, then top-k filtering, then top-p nucleus filtering — before the final argmax or categorical sample.
Per-Step Diagnostics
Enable DecodeStepDiagnostics to capture detailed information about each decode step. This is useful for debugging generation quality issues.
4. KV Cache Management
The key-value (KV) cache stores the attention keys and values computed during the prefill and previous decode steps. Good cache management is the single largest lever for improving LLM serving throughput. The LLM stack provides a comprehensive hierarchy of cache implementations.
Cache Strategy Overview
Paged
PagedKVCache
Default; best memory utilization
Paged + eviction
EvictablePagedKVCache
Long conversations; evict old pages
Per-layer policy
PerLayerPagedKVCache
Different eviction per transformer layer
Quantized
QuantizedPagedKVCache
Memory-constrained GPUs; INT8/FP16 pages
MLA
MLAKVCache
DeepSeek Multi-head Latent Attention
Beam search
BeamKVCacheManager
Beam decoding with K beams
Speculative
SpeculativeKVCacheManager
Speculative decoding draft/verify
Tiered
TieredKVCacheManager
GPU → host DRAM → disk tiering
Unified
UnifiedKvCacheManager
Single manager across all strategies
PagedKVCache
PagedKVCache partitions the cache into fixed-size pages. Sequences are allocated pages on demand; eviction is O(1) — just reclaim a page. This is the vLLM-style approach and is the default strategy.
Eviction Policies
EvictablePagedKVCache adds eviction support. Three built-in eviction policies are provided:
LRU
default
Evict least recently used page
H2O
H2OEvictionPolicy
Heavy Hitter Oracle: evict low-importance tokens based on accumulated attention scores
StreamingLLM
StreamingLLMEvictionPolicy
Preserve attention sink tokens + recent sliding window
Per-Layer Eviction
PerLayerPagedKVCache assigns a different PerLayerKVPolicy to each transformer layer. This is useful because attention patterns differ significantly between early and late layers.
Quantized KV Cache
QuantizedPagedKVCache stores pages in INT8 or FP16 and dequantizes on read. This roughly halves or quarters the memory footprint of the cache with minimal accuracy impact on most models.
KV Cache Offloading
For very long contexts, the cache can be offloaded from GPU VRAM to host DRAM or disk.
Use TieredKVCacheManager to combine GPU, host, and disk tiers automatically:
Prefix Sharing
KVCachePrefixTree and RadixPrefixCache enable sharing KV cache pages across requests that share a common prompt prefix (e.g., a system prompt). Matching prefixes are detected and their cached pages are reused rather than recomputed.
KV Cache Checkpointing
Save and restore cache state to disk, enabling pause-and-resume of long generation sessions.
5. Speculative Decoding
Speculative decoding uses a fast draft model (or an n-gram heuristic) to propose multiple tokens ahead, then verifies them in a single forward pass of the full target model. Accepted tokens come for free; only rejected tokens require additional passes. On hardware where the target model is memory-bandwidth-bound, speculative decoding commonly delivers 2-3x throughput improvement.
Speculator Implementations
NgramSpeculator
N-gram from generated context
No secondary model required
DraftModelSpeculator
Smaller SameDiff model
Highest acceptance rate
NgramSpeculator
Uses an n-gram index built from the tokens already generated in the current sequence. No additional model weights are required.
DraftModelSpeculator
Uses a smaller, faster model to generate draft tokens. The draft model should share the same vocabulary as the target model.
Tree Attention Verification
TreeAttentionVerifier organizes draft tokens into a tree structure and verifies all candidates in parallel with a single batched forward pass of the target model. This maximizes GPU utilization during the verification step.
The tree verifier is selected automatically when draftLength > 1 and is the recommended choice for DraftModelSpeculator. It requires no additional configuration beyond being set on the SpeculativeDecodeLoop.
6. Continuous Batching
Continuous batching (sometimes called in-flight batching) keeps the GPU fully saturated by interleaving prefill and decode steps across multiple requests. Unlike static batching, where a batch waits until all sequences in it complete, continuous batching allows new requests to be admitted and completed sequences to exit at any decode step.
Architecture
ContinuousBatchScheduler
BatchGenerationState
BatchGenerationState tracks per-sequence state within the batch: current token position, KV cache page assignments, sampling state, and completion status. It is managed automatically by ContinuousBatchScheduler and is not normally accessed directly.
BatchCompactor
BatchCompactor runs at the end of each decode step to remove completed sequences and compact the batch tensor so that the GPU kernel always operates on a dense, full-occupancy batch. It is attached to the scheduler automatically.
7. Tokenizers
The nd4j-tokenizers module provides tokenizers backed by Rust-native implementations for correctness and performance. All tokenizers implement the Tokenizer interface.
Tokenizer Interface
Encoding holds the token IDs, attention mask, and (optionally) token type IDs.
HuggingFaceTokenizer
Loads any tokenizer in the standard tokenizer.json format as exported by Hugging Face transformers. Supports BPE, WordPiece, and Unigram models.
SentencePieceTokenizer
Loads SentencePiece BPE models (.model files), used by LLaMA, Gemma, Mistral, and other models that do not use the HuggingFace format.
CLIPTokenizer
A specialized tokenizer for CLIP-family vision-language models, following the byte-pair encoding used by the original OpenAI CLIP implementation.
Chat Templates
ChatTemplate renders structured chat conversations into the prompt format expected by an instruction-tuned model. It implements a Jinja2-subset template engine compatible with the chat_template field in HuggingFace tokenizer_config.json.
TokenizerFactory
TokenizerFactory auto-detects the tokenizer type from the files present in a directory and instantiates the correct implementation.
8. Evaluation Framework
The evaluation framework provides automated benchmarking of LLM capabilities across standard academic benchmarks and custom datasets.
Core Evaluation Classes
EvalRunner
Orchestrates evaluation runs; parallelizes across dataset examples
EvalConfig
Dataset, benchmark, metric, and generation options
EvalResult
Aggregated result: per-benchmark scores, timing, sample results
SampleResult
Per-example output, prediction, and score
PerplexityEvaluator
Computes log-perplexity over a reference corpus
GenerationQualityValidator
Validates generation coherence (length, repetition, entropy)
AnswerExtractor
Extracts structured answers from free-form generated text
Running a Standard Benchmark
Available Benchmarks
MMLU
MMLUBenchmark
Massive Multitask Language Understanding (57 subjects)
ARC
ArcBenchmark
AI2 Reasoning Challenge (grade-school science)
GSM8K
Gsm8kBenchmark
Grade school math word problems
HellaSwag
HellaSwagBenchmark
Commonsense reasoning / sentence completion
TruthfulQA
TruthfulQABenchmark
Truthfulness and calibration
WinoGrande
WinograndeBenchmark
Pronoun coreference resolution
Metrics
Exact Match
ExactMatch
Binary: prediction equals gold label
F1
F1
Token-level F1 between prediction and gold
BLEU
BLEU
N-gram precision (translation quality)
ROUGE
ROUGE
Recall-oriented n-gram overlap (summarization)
ANLS
ANLS
Average Normalized Levenshtein Similarity (document QA)
VQA Accuracy
VqaAccuracy
Soft accuracy for visual question answering
Relaxed Accuracy
RelaxedAccuracy
Case/punctuation-insensitive exact match
Multiple Choice
MultipleChoiceAccuracy
Accuracy over A/B/C/D choices
Dataset Sources
HuggingFaceDataset
HuggingFace Hub (requires network)
JsonlDataset
Local JSONL file
CsvDataset
Local CSV file
CustomDataset
In-memory list of (input, label) pairs
DatasetCache
Wraps any dataset; caches to disk to avoid re-download
Perplexity
9. Model Editing / Abliteration
The model editing module provides tools for modifying model behavior by directly editing weight matrices. The primary use case implemented is abliteration: removing a model's refusal directions to understand or modify how refusal behavior is encoded in the model's weights. This is useful for research into model internals and for running ablations on safety-trained models in controlled research environments.
Important: These tools modify model weights irreversibly. Always work on a copy. Abliterated models should be used only within the bounds of your organization's AI safety policies.
Abliteration Workflow
Abliteration works by:
Collecting activations for harmful and harmless prompt pairs (contrastive pairs).
Computing the mean activation difference between the two sets — the "refusal direction".
Orthogonalizing all weight matrices in the model against the refusal direction using Gram-Schmidt.
This removes the direction from the model's weight space so the model cannot activate along it, effectively removing the refusal behavior.
RefusalDirectionFinder
Used internally by AbliterationWorkflow, but can also be used standalone to analyze where refusal behavior is most strongly encoded across layers.
WeightOrthogonalizer
Applies the Gram-Schmidt orthogonalization to remove a direction from a weight matrix. Used by AbliterationWorkflow but also available directly.
10. Benchmarking
The benchmark framework measures LLM inference throughput under controlled conditions. It distinguishes between three throughput regimes that capture different aspects of serving performance.
Throughput Metrics
lateSteady tok/s
Tokens per second after full JIT warmup and cache warmup
steady tok/s
Tokens per second during the steady decode phase (most representative)
decode tok/s
Tokens per second for the decode phase only (excludes prefill)
BenchmarkConfig Presets
BenchmarkConfig ships four presets that control how the SameDiff graph is executed during the benchmark run.
Optimal
BenchmarkConfig.OPTIMAL
Lets the system select the best execution mode automatically
Slot-by-slot
BenchmarkConfig.SLOT_BY_SLOT
Executes one op at a time; useful for per-op profiling
Triton
BenchmarkConfig.TRITON
Routes eligible ops through Triton kernels (requires tritonEnabled=true)
CUDA Graphs
BenchmarkConfig.CUDA_GRAPHS
Captures and replays CUDA graphs; lowest decode latency on GPU
Running a Benchmark
BenchmarkConfigApplier
BenchmarkConfigApplier is the only legitimate caller of setGraphExecutionMode on a SameDiff instance. If you need to apply a BenchmarkConfig to an existing pipeline outside of BenchmarkRunner, use it rather than calling SameDiff execution mode methods directly.
Decode Step Validation
The benchmark framework ships a suite of validation utilities for verifying that optimization changes do not alter numerical outputs.
11. VLM, Audio, and Other Modules
samediff-vlm: Vision-Language Models
samediff-vlm extends the generation pipeline with image conditioning. The module handles image preprocessing (resize, normalize, patch extraction), image encoding via a vision encoder SameDiff graph, cross-attention injection into the language model, and the combined text-image generation loop.
The CLIPTokenizer in nd4j-tokenizers is used by samediff-vlm to tokenize text for CLIP-family vision encoders. Text embeddings and image patch embeddings are concatenated in the language model's embedding space before the decode loop begins.
samediff-audio: Whisper ASR
samediff-audio provides a complete Whisper automatic speech recognition pipeline, including mel spectrogram extraction, audio chunking for long audio, beam search decoding, and optional language detection.
nd4j-torchscript: PyTorch Model Import
nd4j-torchscript imports TorchScript (.pt) files exported from PyTorch into native SameDiff graphs. This allows any PyTorch model that can be torch.jit.traced or torch.jit.scripted to be run without any Python dependency at inference time.
Supported op coverage includes all ops commonly used in transformer architectures: matrix multiply, layer norm, softmax, attention, RoPE, SiLU/GELU activations, and element-wise operations. Unsupported ops will raise TorchScriptImportException with the op name.
nd4j-web: Browser Frontend for ND4J Graphs
nd4j-web provides a TypeScript/FlatBuffers-based web frontend for visualizing and executing ND4J computation graphs in a browser. Graphs are serialized to FlatBuffers format and served over a lightweight HTTP endpoint. This is primarily useful for debugging graph structure and for building web-based tooling around ND4J models.
Navigate to http://localhost:8080 to see the graph structure, inspect variable shapes, and trigger execution from the browser.
Next Steps
Getting Started: See the Quickstart for setting up the Maven project and running your first model.
SameDiff Graph Execution: Review the SameDiff Execution documentation to understand how
GenerationPipelineintegrates with the DSP plan lifecycle.OmniHub Model Zoo: Use OmniHub to download pre-converted LLM weights in the SameDiff FlatBuffers format without manual conversion.
Performance Tuning: See GPU/CPU Configuration and Memory and Workspaces for hardware-specific tuning guidance that applies to LLM inference.
CUDA Graphs: The
BenchmarkConfig.CUDA_GRAPHSpreset delivers the lowest decode latency on NVIDIA GPUs; see the CUDA backend documentation for prerequisites.
Last updated
Was this helpful?