View the streaming example on GitHub
Why streaming?
LLMs generate tokens in sequence, so you can return useful output to users before the full response is ready. Truss supports streaming output to do this.Set up the imports
In this example, we use the HuggingFace transformers library to build a text generation model.model/model.py
Define the load function
In theload function of the Truss, we implement logic
involved in downloading the instruct version of the Qwen2.5 7B model and loading it into memory.
model/model.py
Define the preprocess function
In thepreprocess function of the Truss, we set up a generate_args dictionary with some generation arguments from the inference request to be used in the predict function.
model/model.py
Define the predict function
In thepredict function of the Truss, we implement the actual
inference logic.
The two main steps are:
- Tokenize the input
- Call the model’s
generatefunction if we’re not streaming the output, otherwise call thestreamhelper function
model/model.py
Define the stream helper function
In this helper function, we instantiate the TextIteratorStreamer object, which holds the tokens as the
model generates them. skip_prompt keeps the request out of the response, so the client only sees the
new text, and skip_special_tokens keeps the control tokens out of it.
model/model.py
GenerationConfig from the request’s generation arguments and pass
the streamer object alongside it. Every sampling parameter lives in the
generation config, so nothing is passed twice.
model/model.py
model/model.py
streamer,
which produces output and yields it until the generation is complete.
We define this inner function to create our generator.
model/model.py
Set up the config.yaml
Running Qwen2.5 7B Instruct requires torch, transformers, and accelerate,
which transformers needs to place the model with device_map="auto".
config.yaml
Configure resources for Qwen
We will use an L4 to run this model.config.yaml