espnet2.sds.llm.hugging_face_llm.HuggingFaceLLM
espnet2.sds.llm.hugging_face_llm.HuggingFaceLLM
class espnet2.sds.llm.hugging_face_llm.HuggingFaceLLM(access_token: str | None = None, tag: str = 'meta-llama/Llama-3.2-1B-Instruct', device: str = 'cuda', dtype: str = 'float16', max_new_tokens: int = 64, chat_template_kwargs: Dict[str, Any] | None = None)
Bases: AbsLLM
Hugging Face LLM
A class for initializing a text response generator
using the Transformers library.
- Parameters:
- access_token (str , optional) – The Hugging Face access token. Only gated models such as meta-llama/* need it. Defaults to None.
- tag (str , optional) – The model tag for the pre-trained language model. Defaults to “meta-llama/Llama-3.2-1B-Instruct”.
- device (str , optional) – The device to run the inference on. Defaults to “cuda”.
- dtype (str , optional) – The data type for model computation, a torch dtype name or “auto” for the checkpoint’s own. Defaults to “float16”.
- max_new_tokens (int , optional) – The maximum number of tokens in one reply. Defaults to 64.
- chat_template_kwargs (dict , optional) – Extra variables for the model’s chat template. Defaults to {“enable_thinking”: False}, which stops Qwen3 and SmolLM3 from writing their reasoning before the reply. A chat template that does not use a variable ignores it.
- Raises:ImportError – If the transformers library is not installed.
forward(chat_messages: List[dict]) → str
Generate a response from the language model based on
the provided chat messages.
- Parameters:chat_messages (List *[*dict ]) – A list of chat messages, where each message is a dictionary containing the conversation history. Each dictionary should have keys like “role” (e.g., “user”, “assistant”) and “content” (the message text).
- Returns: The generated response text from the language model.
- Return type: str
Notes
- The model generates at most max_new_tokens new tokens
with greedy decoding (do_sample set to False).
stream(chat_messages: List[dict]) → Iterator[str]
Yield the reply piece by piece while the model generates it.
A caller that times the first non-empty piece gets the time to the first text of the reply, which forward() cannot report. A piece is decoded text, not one token: TextIteratorStreamer holds the text back until it ends a word, so the first piece can come a few tokens after the first token.
- Parameters:chat_messages (List *[*dict ]) – The conversation history, as for forward().
- Yields:str – The next decoded piece of the reply.
warmup()
Perform a single forward pass with dummy input to
pre-load and warm up the model.
