Class DeepSeek
- All Implemented Interfaces:
AutoCloseable, ModelExecutor, LanguageModel
LanguageModel and ModelExecutor over
DeepSeekModel.
With several devices every device holds a replica of the dense layers and 1/n of each layer's routed
experts (expert parallelism, partial outputs summed with NCCL); each device is driven by its own thread because the
collectives need all ranks to be inside the same layer at once. One request's state is a DeepSeekModel.Session
per rank.
Current limits (the model code was written for validation first): a decode step over B requests is one batched
pass (the sequence-independent math runs once, attention state per row); a prompt is prefilled in one pass (the engine's chunks are
collected and the work happens with the last one); no prefix reuse, CUDA graphs, speculation or images.
-
Method Summary
Modifier and TypeMethodDescriptionintbind(int[] prompt, int totalCapacity) Binds one request into the KV pool (multi-request safe).static DeepSeekLoads a checkpoint.chat(Message[] dialog, int maxGenLen, double temperature, double topp, boolean logprobs, long seed, GenerationListener listener, BooleanSupplier cancelRequested) Generates an assistant reply for a dialog.voidclose()decode(int[] tokens) Decodes token ids to UTF-8 text.decodeStep(int[] requestIds, int[] lastTokens, int[] positions) One decode step for an active set (same or mixed positions; engine may cohort by position).intTokens the DSpark head drafts per round (0 without a draft head).int[]encodeChat(Message... dialog) Encodes a dialog with the model chat template, leaving the assistant turn open for completion.int[]encodeChat(Message[] dialog, ChatOptions options) Encodes a dialog with optional tool-calling options.voidevict(int requestId) Instant Eviction without radix insert.family()Returns the architecture family label.voidfinish(int requestId, int[] sequenceTokens) Inserts into the radix tree (when enabled) and unbinds the request.generate(int[] prompt, int maxGenLen, double temperature, double topp, boolean logprobs, long seed, GenerationListener listener, BooleanSupplier cancelRequested) Generates a completion from an already-tokenized prompt.booleanhasDraft()Whether the model has a DSpark draft head (and it is not turned off withSMILE_DS_DRAFT=0).Primary KV cache pool (rank 0 for TP).intReturns the configured maximum sequence length (max-model-len/ context length).model()Returns the underlying language-model façade.name()Returns the model instance / checkpoint name.intpadToken()Returns the pad token id.prefill(int requestId, int[] prompt, int prefixLen) Prefills the unbound suffix of a prompt (activates this request alone).Tensor[]prefillBatch(int[] requestIds, int[][] prompts) Prefills several complete prompts (each from position 0) together.prefillChunk(int requestId, int[] prompt, int from, int to) Prefillsprompt[from, to)(chunked Continuous Batching).intprefixLen(int requestId) Page-aligned matched prefix length for a bound request.int[][]speculateStep(int[] requestIds, int[] lastTokens, int[] positions, int numDrafts, double[] temperatures, double[] topps) One DSpark round for several sequences: drafts a block per sequence and verifies the blocks of all of them in one CUDA-graph pass of the main model, then keeps each sequence's accepted prefix plus one token of the model's own (greedy argmax, or sampled as inDeepSeekSampler).int[][]speculateStep(int[] requestIds, int[] lastTokens, int[] positions, int numDrafts, double temperature, double topp) One speculative MTP round for a uniform draft depth.booleanWhetherModelExecutor.speculateStep(int[], int[], int[], int, double, double)may be asked for more drafts than a request has tokens left (the extra tokens are dropped by the engine).int[]Returns stop / EOS token ids.booleanWhetherModelExecutor.prefillBatch(int[], int[][])processes several prompts in one pass (cheaper than oneModelExecutor.prefill(int, int[], int)each).tryDecode(int[] tokens, boolean skipSpecial) Attempts a streaming decode; returns empty on incomplete UTF-8.Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface LanguageModel
chat, generateMethods inherited from interface ModelExecutor
idleDecodeGraphPrefetch, prefillMultimodal, speculationSwitchable, supportsMultimodalPrefixReuse, supportsStepApi, warmPrefix
-
Method Details
-
build
public static DeepSeek build(String checkpointDir, int layers, int maxSeqLen, byte[] devices) throws IOException Loads a checkpoint.- Parameters:
checkpointDir- directory withconfig.json,tokenizer.jsonand the safetensors shards.layers- number of layers to load (<= 0: all); a truncated model is for testing only.maxSeqLen- maximum context length (<= 0: the checkpoint's).devices- CUDA device ids, one rank each (routed experts are split over them), ornullfor CPU.- Returns:
- the model.
- Throws:
IOException- if the checkpoint is incomplete.
-
family
Description copied from interface:LanguageModelReturns the architecture family label.Examples:
meta/llama3,alibaba/qwen3.5. This is not necessarily the public API model id used by serve.- Specified by:
familyin interfaceLanguageModel- Returns:
- the family label string.
-
name
Description copied from interface:LanguageModelReturns the model instance / checkpoint name.- Specified by:
namein interfaceLanguageModel- Returns:
- the instance name (e.g. directory or HF repo leaf name).
-
maxSeqLen
public int maxSeqLen()Description copied from interface:LanguageModelReturns the configured maximum sequence length (max-model-len/ context length).- Specified by:
maxSeqLenin interfaceLanguageModel- Specified by:
maxSeqLenin interfaceModelExecutor- Returns:
- the maximum number of tokens allowed for prompt plus completion.
-
encodeChat
Description copied from interface:LanguageModelEncodes a dialog with the model chat template, leaving the assistant turn open for completion.- Specified by:
encodeChatin interfaceLanguageModel- Parameters:
dialog- ordered conversation turns (system/user/assistant).- Returns:
- prompt token ids ready for
LanguageModel.generate(int[], int, double, double, boolean, long, GenerationListener).
-
encodeChat
Description copied from interface:LanguageModelEncodes a dialog with optional tool-calling options.Default ignores
optionsand delegates toLanguageModel.encodeChat(Message...).- Specified by:
encodeChatin interfaceLanguageModel- Parameters:
dialog- ordered conversation turns.options- chat options; may benull.- Returns:
- prompt token ids.
-
generate
public ChatCompletion generate(int[] prompt, int maxGenLen, double temperature, double topp, boolean logprobs, long seed, GenerationListener listener, BooleanSupplier cancelRequested) Description copied from interface:LanguageModelGenerates a completion from an already-tokenized prompt.- Specified by:
generatein interfaceLanguageModel- Parameters:
prompt- prompt token id sequence.maxGenLen- maximum number of new tokens to generate (not including the prompt itself).temperature- sampling temperature; higher values increase randomness.topp- nucleus-sampling top-p threshold in(0, 1].logprobs-trueto include per-token log-probabilities in the result.seed- optional RNG seed for deterministic sampling;0means non-deterministic.listener- optional progress callback; may benull.cancelRequested- when non-null and returnstrue, generation stops between decode steps withCancellationException.- Returns:
- the completion for
prompt.
-
chat
public ChatCompletion chat(Message[] dialog, int maxGenLen, double temperature, double topp, boolean logprobs, long seed, GenerationListener listener, BooleanSupplier cancelRequested) Description copied from interface:LanguageModelGenerates an assistant reply for a dialog.Equivalent to
LanguageModel.encodeChat(Message...)followed byLanguageModel.generate(int[], int, double, double, boolean, long, GenerationListener).- Specified by:
chatin interfaceLanguageModel- Parameters:
dialog- ordered conversation turns.maxGenLen- maximum number of new tokens to generate.temperature- sampling temperature; higher values increase randomness.topp- nucleus-sampling top-p threshold in(0, 1].logprobs-trueto include per-token log-probabilities in the result.seed- optional RNG seed for deterministic sampling;0means non-deterministic.listener- optional progress callback; may benull.cancelRequested- cooperative cancel flag; may benull.- Returns:
- the completion for
dialog.
-
model
Description copied from interface:ModelExecutorReturns the underlying language-model façade.- Specified by:
modelin interfaceModelExecutor- Returns:
- language model.
-
kvCachePool
Description copied from interface:ModelExecutorPrimary KV cache pool (rank 0 for TP). May benullonly for models without full-attention layers.- Specified by:
kvCachePoolin interfaceModelExecutor- Returns:
- KV cache pool, or
null.
-
padToken
public int padToken()Description copied from interface:ModelExecutorReturns the pad token id.- Specified by:
padTokenin interfaceModelExecutor- Returns:
- pad token id.
-
stopTokens
public int[] stopTokens()Description copied from interface:ModelExecutorReturns stop / EOS token ids.- Specified by:
stopTokensin interfaceModelExecutor- Returns:
- stop token ids.
-
decode
Description copied from interface:ModelExecutorDecodes token ids to UTF-8 text.- Specified by:
decodein interfaceModelExecutor- Parameters:
tokens- token ids.- Returns:
- decoded text.
-
tryDecode
Description copied from interface:ModelExecutorAttempts a streaming decode; returns empty on incomplete UTF-8.- Specified by:
tryDecodein interfaceModelExecutor- Parameters:
tokens- token ids.skipSpecial- whether to skip special tokens.- Returns:
- decoded text, or empty on incomplete UTF-8.
- Throws:
CharacterCodingException- when the sequence is incomplete.
-
bind
public int bind(int[] prompt, int totalCapacity) Description copied from interface:ModelExecutorBinds one request into the KV pool (multi-request safe).- Specified by:
bindin interfaceModelExecutor- Parameters:
prompt- prompt token ids.totalCapacity- desired slots (prompt + generation).- Returns:
- request id (
> 0).
-
prefixLen
public int prefixLen(int requestId) Description copied from interface:ModelExecutorPage-aligned matched prefix length for a bound request.- Specified by:
prefixLenin interfaceModelExecutor- Parameters:
requestId- id fromModelExecutor.bind(int[], int).- Returns:
- prefix length (
>= 0).
-
prefill
Description copied from interface:ModelExecutorPrefills the unbound suffix of a prompt (activates this request alone).- Specified by:
prefillin interfaceModelExecutor- Parameters:
requestId- request id.prompt- full prompt tokens.prefixLen- cached prefix to skip (fromModelExecutor.prefixLen(int)).- Returns:
- last-position logits shaped
[1, vocab](caller owns).
-
prefillChunk
Description copied from interface:ModelExecutorPrefillsprompt[from, to)(chunked Continuous Batching). Returns last-token logits only whento == prompt.length.- Specified by:
prefillChunkin interfaceModelExecutor- Parameters:
requestId- request id.prompt- full prompt tokens.from- inclusive start position in the prompt.to- exclusive end position.- Returns:
- logits
[1, vocab]when the prompt is fully prefilled; otherwisenull.
-
hasDraft
public boolean hasDraft()Whether the model has a DSpark draft head (and it is not turned off withSMILE_DS_DRAFT=0).- Returns:
trueif the model has an active draft head.
-
draftBlock
public int draftBlock()Tokens the DSpark head drafts per round (0 without a draft head).- Returns:
- the number of tokens drafted per round.
-
speculateStep
public int[][] speculateStep(int[] requestIds, int[] lastTokens, int[] positions, int numDrafts, double[] temperatures, double[] topps) One DSpark round for several sequences: drafts a block per sequence and verifies the blocks of all of them in one CUDA-graph pass of the main model, then keeps each sequence's accepted prefix plus one token of the model's own (greedy argmax, or sampled as inDeepSeekSampler). Sequences whose draft state is out of step (they took a plain decode step) and rounds that cannot use a graph fall back to plain steps.- Specified by:
speculateStepin interfaceModelExecutor- Parameters:
requestIds- active KV request ids (order = batch).lastTokens- last committed token per request.positions- absolute position oflastTokens[i](write of next is+1).numDrafts- draft depth (same for every request in this call).temperatures- per-request sampling temperature (verify).topps- per-request nucleus top-p (verify).- Returns:
- accepted token ids per request (each length
>= 1; caller owns arrays).
-
speculateStep
public int[][] speculateStep(int[] requestIds, int[] lastTokens, int[] positions, int numDrafts, double temperature, double topp) Description copied from interface:ModelExecutorOne speculative MTP round for a uniform draft depth.Default throws; Qwen overrides when MTP weights are loaded.
- Specified by:
speculateStepin interfaceModelExecutor- Parameters:
requestIds- active KV request ids (order = batch).lastTokens- last committed token per request.positions- absolute position oflastTokens[i](write of next is+1).numDrafts- draft depth (same for every request in this call).temperature- sampling temperature (verify).topp- nucleus top-p (verify).- Returns:
- accepted token ids per request (each length
>= 1; caller owns arrays).
-
speculationMayOvershoot
public boolean speculationMayOvershoot()Description copied from interface:ModelExecutorWhetherModelExecutor.speculateStep(int[], int[], int[], int, double, double)may be asked for more drafts than a request has tokens left (the extra tokens are dropped by the engine). Lets a request near its end stay in the batched round instead of speculating alone.- Specified by:
speculationMayOvershootin interfaceModelExecutor- Returns:
trueif speculation may overshoot the remaining token budget.
-
supportsBatchedPrefill
public boolean supportsBatchedPrefill()Description copied from interface:ModelExecutorWhetherModelExecutor.prefillBatch(int[], int[][])processes several prompts in one pass (cheaper than oneModelExecutor.prefill(int, int[], int)each). The engine only batches whole prompts that start at position 0.- Specified by:
supportsBatchedPrefillin interfaceModelExecutor- Returns:
trueif batched prefill is supported.
-
prefillBatch
Description copied from interface:ModelExecutorPrefills several complete prompts (each from position 0) together.- Specified by:
prefillBatchin interfaceModelExecutor- Parameters:
requestIds- request ids.prompts- the prompts, one per request.- Returns:
- last-position logits
[1, vocab]per request (caller owns each).
-
decodeStep
Description copied from interface:ModelExecutorOne decode step for an active set (same or mixed positions; engine may cohort by position). Tokens are[B]last tokens; positions are the write index for each row.- Specified by:
decodeStepin interfaceModelExecutor- Parameters:
requestIds- active KV request ids (order = batch).lastTokens- token id per request.positions- absolute position per request.- Returns:
- logits
[B, vocab](caller owns).
-
finish
public void finish(int requestId, int[] sequenceTokens) Description copied from interface:ModelExecutorInserts into the radix tree (when enabled) and unbinds the request.- Specified by:
finishin interfaceModelExecutor- Parameters:
requestId- request id.sequenceTokens- prompt + completion (no pad).
-
evict
public void evict(int requestId) Description copied from interface:ModelExecutorInstant Eviction without radix insert.- Specified by:
evictin interfaceModelExecutor- Parameters:
requestId- request id.
-
close
- Specified by:
closein interfaceAutoCloseable- Throws:
IOException
-