Class Llama
- All Implemented Interfaces:
ModelExecutor, LanguageModel
-
Constructor Summary
ConstructorsConstructorDescriptionLlama(String name, LlamaModel model, Tokenizer tokenizer, LlamaModelArgs params) Constructor. -
Method Summary
Modifier and TypeMethodDescriptionintbind(int[] prompt, int totalCapacity) Binds one request into the KV pool (multi-request safe).static LlamaBuilds a Llama instance by initializing and loading a model checkpoint.static Llamabuild(String checkpointDir, String tokenizerPath, int maxBatchSize, int maxSeqLen, byte deviceId, double memFractionStatic) Builds a Llama instance by initializing and loading a model checkpoint.static Llamabuild(String checkpointDir, String tokenizerPath, int maxBatchSize, int maxSeqLen, byte deviceId, double memFractionStatic, String kvCacheDtype) Builds a Llama instance by initializing and loading a model checkpoint.static Llamabuild(String checkpointDir, String tokenizerPath, int maxBatchSize, int maxSeqLen, byte deviceId, double memFractionStatic, String kvCacheDtype, int pageSize) Builds a Llama instance by initializing and loading a model checkpoint.static Llamabuild(String checkpointDir, String tokenizerPath, int maxBatchSize, int maxSeqLen, byte deviceId, double memFractionStatic, String kvCacheDtype, int pageSize, int modelLoaderThreads) Builds a Llama instance by initializing and loading a model checkpoint.chat(Message[] dialog, int maxGenLen, double temperature, double topp, boolean logprobs, long seed, GenerationListener listener, BooleanSupplier cancelRequested) Generates an assistant response for a conversational dialog.complete(String prompt, int maxGenLen, double temperature, double topp, boolean logprobs, long seed, GenerationListener listener) Performs text completion for a prompt.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).int[]encodeChat(Message... dialog) Encodes a dialog with the model chat template, leaving the assistant turn open for completion.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 text completion from a tokenized prompt using nucleus sampling.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 name.intpadToken()Returns the pad token id.params()Returns the transformer hyperparameters loaded from the checkpoint.static ScalarTypeparseDtypeName(String name) Parses a human-readable floating-point dtype name.prefill(int requestId, int[] prompt, int prefixLen) Prefills the unbound suffix of a prompt (activates this request alone).prefillChunk(int requestId, int[] prompt, int from, int to) Prefillsprompt[from, to)into the KV cache (exclusive activate).intprefixLen(int requestId) Page-aligned matched prefix length for a bound request.voidsetPrefixReuseEnabled(boolean enabled) Enables or disables radix prefix reuse for all KV pools on this model.int[]Returns stop / EOS token ids.toString()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, wait, wait, waitMethods inherited from interface LanguageModel
chat, encodeChat, generateMethods inherited from interface ModelExecutor
idleDecodeGraphPrefetch, prefillMultimodal, speculateStep, speculateStep, supportsStepApi, warmPrefix
-
Constructor Details
-
Llama
Constructor.- Parameters:
name- the model name.model- the transformer model.tokenizer- the tokenizer.params- the model hyperparameters.
-
-
Method Details
-
toString
-
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.
-
setPrefixReuseEnabled
public void setPrefixReuseEnabled(boolean enabled) Enables or disables radix prefix reuse for all KV pools on this model.- Parameters:
enabled-trueto match/insert prefixes across requests.
-
params
Returns the transformer hyperparameters loaded from the checkpoint.- Returns:
- model args from
config.json/params.json.
-
name
Returns the model instance name.- Specified by:
namein interfaceLanguageModel- Returns:
- the model instance 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).
-
build
public static Llama build(String checkpointDir, String tokenizerPath, int maxBatchSize, int maxSeqLen, byte deviceId) throws IOException Builds a Llama instance by initializing and loading a model checkpoint.Supports two on-disk layouts:
- Meta —
params.jsonplusconsolidated.*.ptshards. - HuggingFace —
config.jsonplus*.safetensors(optionally indexed bymodel.safetensors.index.json).
- Parameters:
checkpointDir- the directory path of checkpoint files.tokenizerPath- the path of tokenizer model file.maxBatchSize- the maximum batch size for inference.maxSeqLen- the maximum sequence length for input text.deviceId- the optional CUDA device ID. If negative, don't use CUDA.- Returns:
- an instance of Llama model.
- Throws:
IOException- if fail to open model checkpoint.
- Meta —
-
build
public static Llama build(String checkpointDir, String tokenizerPath, int maxBatchSize, int maxSeqLen, byte deviceId, double memFractionStatic) throws IOException Builds a Llama instance by initializing and loading a model checkpoint.When
memFractionStatic > 0, aKvCachePoolis allocated after weight loading with SGLang--mem-fraction-staticsemantics:yis a fraction of total GPU memory for the static region (weights + KV); seesmile.chat.mem-fraction-staticin smile-serve.- Parameters:
checkpointDir- the directory path of checkpoint files.tokenizerPath- the path of tokenizer model file.maxBatchSize- the maximum batch size for inference.maxSeqLen- the maximum sequence length for input text.deviceId- the optional CUDA device ID. If negative, don't use CUDA.memFractionStatic- static-region fraction of total GPU memory for weights + KV;<= 0keeps the default test-sized pool.- Returns:
- an instance of Llama model.
- Throws:
IOException- if fail to open model checkpoint.
-
build
public static Llama build(String checkpointDir, String tokenizerPath, int maxBatchSize, int maxSeqLen, byte deviceId, double memFractionStatic, String kvCacheDtype) throws IOException Builds a Llama instance by initializing and loading a model checkpoint.When
memFractionStatic > 0, aKvCachePoolis allocated after weight loading with SGLang--mem-fraction-staticsemantics:yis a fraction of total GPU memory for the static region (weights + KV); seesmile.chat.mem-fraction-staticin smile-serve.- Parameters:
checkpointDir- the directory path of checkpoint files.tokenizerPath- the path of tokenizer model file.maxBatchSize- the maximum batch size for inference.maxSeqLen- the maximum sequence length for input text.deviceId- the optional CUDA device ID. If negative, don't use CUDA.memFractionStatic- static-region fraction of total GPU memory for weights + KV;<= 0keeps the default test-sized pool.kvCacheDtype- optional KV-cache element dtype name (e.g.bfloat16,float16);null/blank usestorch_dtypefromconfig.json, then the CUDA compute dtype.- Returns:
- an instance of Llama model.
- Throws:
IOException- if fail to open model checkpoint.
-
build
public static Llama build(String checkpointDir, String tokenizerPath, int maxBatchSize, int maxSeqLen, byte deviceId, double memFractionStatic, String kvCacheDtype, int pageSize) throws IOException Builds a Llama instance by initializing and loading a model checkpoint.When
memFractionStatic > 0, aKvCachePoolis allocated after weight loading with SGLang--mem-fraction-staticsemantics:yis a fraction of total GPU memory for the static region (weights + KV); seesmile.chat.mem-fraction-staticin smile-serve.- Parameters:
checkpointDir- the directory path of checkpoint files.tokenizerPath- the path of tokenizer model file.maxBatchSize- the maximum batch size for inference.maxSeqLen- the maximum sequence length for input text.deviceId- the optional CUDA device ID. If negative, don't use CUDA.memFractionStatic- static-region fraction of total GPU memory for weights + KV;<= 0keeps the default test-sized pool.kvCacheDtype- optional KV-cache element dtype name (e.g.bfloat16,float16);null/blank usestorch_dtypefromconfig.json, then the CUDA compute dtype.pageSize- tokens per radix / KV pool page (>= 1).- Returns:
- an instance of Llama model.
- Throws:
IOException- if fail to open model checkpoint.
-
build
public static Llama build(String checkpointDir, String tokenizerPath, int maxBatchSize, int maxSeqLen, byte deviceId, double memFractionStatic, String kvCacheDtype, int pageSize, int modelLoaderThreads) throws IOException Builds a Llama instance by initializing and loading a model checkpoint.When
memFractionStatic > 0, aKvCachePoolis allocated after weight loading with SGLang--mem-fraction-staticsemantics:yis a fraction of total GPU memory for the static region (weights + KV); seesmile.chat.mem-fraction-staticin smile-serve.- Parameters:
checkpointDir- the directory path of checkpoint files.tokenizerPath- the path of tokenizer model file.maxBatchSize- the maximum batch size for inference.maxSeqLen- the maximum sequence length for input text.deviceId- the optional CUDA device ID. If negative, don't use CUDA.memFractionStatic- static-region fraction of total GPU memory for weights + KV;<= 0keeps the default test-sized pool.kvCacheDtype- optional KV-cache element dtype name (e.g.bfloat16,float16);null/blank usestorch_dtypefromconfig.json, then the CUDA compute dtype.pageSize- tokens per radix / KV pool page (>= 1).modelLoaderThreads- safetensors loader threads;0= auto (SafeTensorsLoaderThreads.resolve(int, int)).- Returns:
- an instance of Llama model.
- Throws:
IOException- if fail to open model checkpoint.
-
parseDtypeName
Parses a human-readable floating-point dtype name.- Parameters:
name- dtype name (case-insensitive), e.g.bfloat16,float16.- Returns:
- the corresponding
ScalarType.
-
generate
public ChatCompletion generate(int[] prompt, int maxGenLen, double temperature, double topp, boolean logprobs, long seed, GenerationListener listener, BooleanSupplier cancelRequested) Generates a text completion from a tokenized prompt using nucleus sampling.- Specified by:
generatein interfaceLanguageModel- Parameters:
prompt- tokenized prompt.maxGenLen- maximum number of new tokens to generate.temperature- temperature value for controlling randomness in sampling.topp- top-p probability threshold for nucleus sampling.logprobs- flag indicating whether to compute token log probabilities.seed- optional RNG seed to sample deterministically;0is non-deterministic.listener- optional generation progress callback.cancelRequested- when non-null and returnstrue, generation stops between decode steps withCancellationException.- Returns:
- the generated text completion.
-
complete
public ChatCompletion complete(String prompt, int maxGenLen, double temperature, double topp, boolean logprobs, long seed, GenerationListener listener) Performs text completion for a prompt.- Parameters:
prompt- text prompt.maxGenLen- maximum number of new tokens to generate.temperature- temperature value for controlling randomness in sampling.topp- top-p probability threshold for nucleus sampling.logprobs- flag indicating whether to compute token log probabilities.seed- optional RNG seed to sample deterministically.listener- optional generation progress callback.- Returns:
- the generated text completion.
-
chat
public ChatCompletion chat(Message[] dialog, int maxGenLen, double temperature, double topp, boolean logprobs, long seed, GenerationListener listener, BooleanSupplier cancelRequested) Generates an assistant response for a conversational dialog.- Specified by:
chatin interfaceLanguageModel- Parameters:
dialog- ordered conversation turns.maxGenLen- maximum number of new tokens to generate.temperature- temperature value for controlling randomness in sampling.topp- top-p probability threshold for nucleus sampling.logprobs- flag indicating whether to compute token log probabilities.seed- optional RNG seed to sample deterministically.listener- optional generation progress callback.cancelRequested- cooperative cancel flag; may benull.- Returns:
- the generated chat response.
-
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
Prefillsprompt[from, to)into the KV cache (exclusive activate). Returns last-token logits only whento == prompt.length; otherwisenull(intermediate chunk).- Specified by:
prefillChunkin interfaceModelExecutor- Parameters:
requestId- KV request id.prompt- full prompt tokens.from- start position (usually matched prefix, possibly trimmed).to- exclusive end (<= prompt.length).- Returns:
- logits
[1, vocab]ornull.
-
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.
-