Class DeepSeek

java.lang.Object
smile.llm.model.deepseek.DeepSeek
All Implemented Interfaces:
AutoCloseable, ModelExecutor, LanguageModel

public final class DeepSeek extends Object implements LanguageModel, ModelExecutor, AutoCloseable
DeepSeek-V4.1 behind the continuous-batching engine: a 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 Details

    • build

      public static DeepSeek build(String checkpointDir, int layers, int maxSeqLen, byte[] devices) throws IOException
      Loads a checkpoint.
      Parameters:
      checkpointDir - directory with config.json, tokenizer.json and 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), or null for CPU.
      Returns:
      the model.
      Throws:
      IOException - if the checkpoint is incomplete.
    • family

      public String family()
      Description copied from interface: LanguageModel
      Returns the architecture family label.

      Examples: meta/llama3, alibaba/qwen3.5. This is not necessarily the public API model id used by serve.

      Specified by:
      family in interface LanguageModel
      Returns:
      the family label string.
    • name

      public String name()
      Description copied from interface: LanguageModel
      Returns the model instance / checkpoint name.
      Specified by:
      name in interface LanguageModel
      Returns:
      the instance name (e.g. directory or HF repo leaf name).
    • maxSeqLen

      public int maxSeqLen()
      Description copied from interface: LanguageModel
      Returns the configured maximum sequence length (max-model-len / context length).
      Specified by:
      maxSeqLen in interface LanguageModel
      Specified by:
      maxSeqLen in interface ModelExecutor
      Returns:
      the maximum number of tokens allowed for prompt plus completion.
    • encodeChat

      public int[] encodeChat(Message... dialog)
      Description copied from interface: LanguageModel
      Encodes a dialog with the model chat template, leaving the assistant turn open for completion.
      Specified by:
      encodeChat in interface LanguageModel
      Parameters:
      dialog - ordered conversation turns (system / user / assistant).
      Returns:
      prompt token ids ready for LanguageModel.generate(int[], int, double, double, boolean, long, GenerationListener).
    • encodeChat

      public int[] encodeChat(Message[] dialog, ChatOptions options)
      Description copied from interface: LanguageModel
      Encodes a dialog with optional tool-calling options.

      Default ignores options and delegates to LanguageModel.encodeChat(Message...).

      Specified by:
      encodeChat in interface LanguageModel
      Parameters:
      dialog - ordered conversation turns.
      options - chat options; may be null.
      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: LanguageModel
      Generates a completion from an already-tokenized prompt.
      Specified by:
      generate in interface LanguageModel
      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 - true to include per-token log-probabilities in the result.
      seed - optional RNG seed for deterministic sampling; 0 means non-deterministic.
      listener - optional progress callback; may be null.
      cancelRequested - when non-null and returns true, generation stops between decode steps with CancellationException.
      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: LanguageModel
      Specified by:
      chat in interface LanguageModel
      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 - true to include per-token log-probabilities in the result.
      seed - optional RNG seed for deterministic sampling; 0 means non-deterministic.
      listener - optional progress callback; may be null.
      cancelRequested - cooperative cancel flag; may be null.
      Returns:
      the completion for dialog.
    • model

      public LanguageModel model()
      Description copied from interface: ModelExecutor
      Returns the underlying language-model façade.
      Specified by:
      model in interface ModelExecutor
      Returns:
      language model.
    • kvCachePool

      public KvCachePool kvCachePool()
      Description copied from interface: ModelExecutor
      Primary KV cache pool (rank 0 for TP). May be null only for models without full-attention layers.
      Specified by:
      kvCachePool in interface ModelExecutor
      Returns:
      KV cache pool, or null.
    • padToken

      public int padToken()
      Description copied from interface: ModelExecutor
      Returns the pad token id.
      Specified by:
      padToken in interface ModelExecutor
      Returns:
      pad token id.
    • stopTokens

      public int[] stopTokens()
      Description copied from interface: ModelExecutor
      Returns stop / EOS token ids.
      Specified by:
      stopTokens in interface ModelExecutor
      Returns:
      stop token ids.
    • decode

      public String decode(int[] tokens)
      Description copied from interface: ModelExecutor
      Decodes token ids to UTF-8 text.
      Specified by:
      decode in interface ModelExecutor
      Parameters:
      tokens - token ids.
      Returns:
      decoded text.
    • tryDecode

      public String tryDecode(int[] tokens, boolean skipSpecial) throws CharacterCodingException
      Description copied from interface: ModelExecutor
      Attempts a streaming decode; returns empty on incomplete UTF-8.
      Specified by:
      tryDecode in interface ModelExecutor
      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: ModelExecutor
      Binds one request into the KV pool (multi-request safe).
      Specified by:
      bind in interface ModelExecutor
      Parameters:
      prompt - prompt token ids.
      totalCapacity - desired slots (prompt + generation).
      Returns:
      request id (> 0).
    • prefixLen

      public int prefixLen(int requestId)
      Description copied from interface: ModelExecutor
      Page-aligned matched prefix length for a bound request.
      Specified by:
      prefixLen in interface ModelExecutor
      Parameters:
      requestId - id from ModelExecutor.bind(int[], int).
      Returns:
      prefix length (>= 0).
    • prefill

      public Tensor prefill(int requestId, int[] prompt, int prefixLen)
      Description copied from interface: ModelExecutor
      Prefills the unbound suffix of a prompt (activates this request alone).
      Specified by:
      prefill in interface ModelExecutor
      Parameters:
      requestId - request id.
      prompt - full prompt tokens.
      prefixLen - cached prefix to skip (from ModelExecutor.prefixLen(int)).
      Returns:
      last-position logits shaped [1, vocab] (caller owns).
    • prefillChunk

      public Tensor prefillChunk(int requestId, int[] prompt, int from, int to)
      Description copied from interface: ModelExecutor
      Prefills prompt[from, to) (chunked Continuous Batching). Returns last-token logits only when to == prompt.length.
      Specified by:
      prefillChunk in interface ModelExecutor
      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; otherwise null.
    • hasDraft

      public boolean hasDraft()
      Whether the model has a DSpark draft head (and it is not turned off with SMILE_DS_DRAFT=0).
      Returns:
      true if 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 in DeepSeekSampler). 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:
      speculateStep in interface ModelExecutor
      Parameters:
      requestIds - active KV request ids (order = batch).
      lastTokens - last committed token per request.
      positions - absolute position of lastTokens[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: ModelExecutor
      One speculative MTP round for a uniform draft depth.

      Default throws; Qwen overrides when MTP weights are loaded.

      Specified by:
      speculateStep in interface ModelExecutor
      Parameters:
      requestIds - active KV request ids (order = batch).
      lastTokens - last committed token per request.
      positions - absolute position of lastTokens[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: ModelExecutor
      Whether ModelExecutor.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:
      speculationMayOvershoot in interface ModelExecutor
      Returns:
      true if speculation may overshoot the remaining token budget.
    • supportsBatchedPrefill

      public boolean supportsBatchedPrefill()
      Description copied from interface: ModelExecutor
      Whether ModelExecutor.prefillBatch(int[], int[][]) processes several prompts in one pass (cheaper than one ModelExecutor.prefill(int, int[], int) each). The engine only batches whole prompts that start at position 0.
      Specified by:
      supportsBatchedPrefill in interface ModelExecutor
      Returns:
      true if batched prefill is supported.
    • prefillBatch

      public Tensor[] prefillBatch(int[] requestIds, int[][] prompts)
      Description copied from interface: ModelExecutor
      Prefills several complete prompts (each from position 0) together.
      Specified by:
      prefillBatch in interface ModelExecutor
      Parameters:
      requestIds - request ids.
      prompts - the prompts, one per request.
      Returns:
      last-position logits [1, vocab] per request (caller owns each).
    • decodeStep

      public Tensor decodeStep(int[] requestIds, int[] lastTokens, int[] positions)
      Description copied from interface: ModelExecutor
      One 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:
      decodeStep in interface ModelExecutor
      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: ModelExecutor
      Inserts into the radix tree (when enabled) and unbinds the request.
      Specified by:
      finish in interface ModelExecutor
      Parameters:
      requestId - request id.
      sequenceTokens - prompt + completion (no pad).
    • evict

      public void evict(int requestId)
      Description copied from interface: ModelExecutor
      Instant Eviction without radix insert.
      Specified by:
      evict in interface ModelExecutor
      Parameters:
      requestId - request id.
    • close

      public void close() throws IOException
      Specified by:
      close in interface AutoCloseable
      Throws:
      IOException