Skip to content

Commit ec435ed

Browse files
mkopcinsMateusz Kopciński
authored andcommitted
feature: llm output tokens batching (#628)
## Description Added batching feature to llms so that `onTokenCallback` is not triggered on each token, but after every batch to reduce number of rerenders. ### Introduces a breaking change? - [ ] Yes - [x] No ### Type of change - [ ] Bug fix (change which fixes an issue) - [x] New feature (change which adds functionality) - [x] Documentation update (improves or adds clarity to existing documentation) - [ ] Other (chores, tests, code style improvements etc.) ### Tested on - [x] iOS - [x] Android ### Testing instructions <!-- Provide step-by-step instructions on how to test your changes. Include setup details if necessary. --> ### Screenshots <!-- Add screenshots here, if applicable --> ### Related issues <!-- Link related issues here using #issue-number --> ### Checklist - [x] I have performed a self-review of my code - [x] I have commented my code, particularly in hard-to-understand areas - [x] I have updated the documentation accordingly - [x] My changes generate no new warnings ### Additional notes <!-- Include any additional information, assumptions, or context that reviewers might need to understand this PR. --> --------- Co-authored-by: Mateusz Kopciński <mateusz.kopcinski@swmansnion.com>
1 parent ffdb85d commit ec435ed

File tree

12 files changed

+207
-55
lines changed

12 files changed

+207
-55
lines changed

docs/docs/02-hooks/01-natural-language-processing/useLLM.md

Lines changed: 33 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -64,20 +64,21 @@ For more information on loading resources, take a look at [loading models](../..
6464

6565
### Returns
6666

67-
| Field | Type | Description |
68-
| ------------------ | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
69-
| `generate()` | `(messages: Message[], tools?: LLMTool[]) => Promise<void>` | Runs model to complete chat passed in `messages` argument. It doesn't manage conversation context. |
70-
| `interrupt()` | `() => void` | Function to interrupt the current inference. |
71-
| `response` | `string` | State of the generated response. This field is updated with each token generated by the model. |
72-
| `token` | `string` | The most recently generated token. |
73-
| `isReady` | `boolean` | Indicates whether the model is ready. |
74-
| `isGenerating` | `boolean` | Indicates whether the model is currently generating a response. |
75-
| `downloadProgress` | `number` | Represents the download progress as a value between 0 and 1, indicating the extent of the model file retrieval. |
76-
| `error` | <code>string &#124; null</code> | Contains the error message if the model failed to load. |
77-
| `configure` | `({ chatConfig?: Partial<ChatConfig>, toolsConfig?: ToolsConfig }) => void` | Configures chat and tool calling. See more details in [configuring the model](#configuring-the-model). |
78-
| `sendMessage` | `(message: string) => Promise<void>` | Function to add user message to conversation. After model responds, `messageHistory` will be updated with both user message and model response. |
79-
| `deleteMessage` | `(index: number) => void` | Deletes all messages starting with message on `index` position. After deletion `messageHistory` will be updated. |
80-
| `messageHistory` | `Message[]` | History containing all messages in conversation. This field is updated after model responds to `sendMessage`. |
67+
| Field | Type | Description |
68+
| ------------------------ | -------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
69+
| `generate()` | `(messages: Message[], tools?: LLMTool[]) => Promise<void>` | Runs model to complete chat passed in `messages` argument. It doesn't manage conversation context. |
70+
| `interrupt()` | `() => void` | Function to interrupt the current inference. |
71+
| `response` | `string` | State of the generated response. This field is updated with each token generated by the model. |
72+
| `token` | `string` | The most recently generated token. |
73+
| `isReady` | `boolean` | Indicates whether the model is ready. |
74+
| `isGenerating` | `boolean` | Indicates whether the model is currently generating a response. |
75+
| `downloadProgress` | `number` | Represents the download progress as a value between 0 and 1, indicating the extent of the model file retrieval. |
76+
| `error` | <code>string &#124; null</code> | Contains the error message if the model failed to load. |
77+
| `configure` | `({chatConfig?: Partial<ChatConfig>, toolsConfig?: ToolsConfig, generationConfig?: GenerationConfig}) => void` | Configures chat and tool calling. See more details in [configuring the model](#configuring-the-model). |
78+
| `sendMessage` | `(message: string) => Promise<void>` | Function to add user message to conversation. After model responds, `messageHistory` will be updated with both user message and model response. |
79+
| `deleteMessage` | `(index: number) => void` | Deletes all messages starting with message on `index` position. After deletion `messageHistory` will be updated. |
80+
| `messageHistory` | `Message[]` | History containing all messages in conversation. This field is updated after model responds to `sendMessage`. |
81+
| `getGeneratedTokenCount` | `() => number` | Returns the number of tokens generated in the last response. |
8182

8283
<details>
8384
<summary>Type definitions</summary>
@@ -106,9 +107,11 @@ interface LLMType {
106107
configure: ({
107108
chatConfig,
108109
toolsConfig,
110+
generationConfig,
109111
}: {
110112
chatConfig?: Partial<ChatConfig>;
111113
toolsConfig?: ToolsConfig;
114+
generationConfig?: GenerationConfig;
112115
}) => void;
113116
generate: (messages: Message[], tools?: LLMTool[]) => Promise<void>;
114117
sendMessage: (message: string) => Promise<void>;
@@ -142,6 +145,11 @@ interface ToolCall {
142145
arguments: Object;
143146
}
144147

148+
interface GenerationConfig {
149+
outputTokenBatchSize: number;
150+
batchTimeInterval: number;
151+
}
152+
145153
type LLMTool = Object;
146154
```
147155

@@ -151,7 +159,7 @@ type LLMTool = Object;
151159

152160
You can use functions returned from this hooks in two manners:
153161

154-
1. Functional/pure - we will not keep any state for you. You'll need to keep conversation history and handle function calling yourself. Use `generate` (and rarely `forward`) and `response`. Note that you don't need to run `configure` to use those. Furthermore, it will not have any effect on those functions.
162+
1. Functional/pure - we will not keep any state for you. You'll need to keep conversation history and handle function calling yourself. Use `generate` (and rarely `forward`) and `response`. Note that you don't need to run `configure` to use those. Furthermore, `chatConfig` and `toolsConfig` will not have any effect on those functions.
155163

156164
2. Managed/stateful - we will manage conversation state. Tool calls will be parsed and called automatically after passing appropriate callbacks. See more at [managed LLM chat](#managed-llm-chat).
157165

@@ -271,6 +279,12 @@ To configure model (i.e. change system prompt, load initial conversation history
271279

272280
- **`displayToolCalls`** - If set to true, JSON tool calls will be displayed in chat. If false, only answers will be displayed.
273281

282+
**`generationConfig`** - Object configuring generation settings, currently only output token batching.
283+
284+
- **`outputTokenBatchSize`** - Soft upper limit on the number of tokens in each token batch (in certain cases there can be more tokens in given batch, i.e. when the batch would end with special emoji join character).
285+
286+
- **`batchTimeInterval`** - Upper limit on the time interval between consecutive token batches.
287+
274288
### Sending a message
275289

276290
In order to send a message to the model, one can use the following code:
@@ -463,6 +477,10 @@ The response should include JSON:
463477
}
464478
```
465479

480+
## Token Batching
481+
482+
Depending on selected model and the user's device generation speed can be above 60 tokens per second. If the `tokenCallback` triggers rerenders and is invoked on every single token it can significantly decrease the app's performance. To alleviate this and help improve performance we've implemented token batching. To configure this you need to call `configure` method and pass `generationConfig`. Inside you can set two parameters `outputTokenBatchSize` and `batchTimeInterval`. They set the size of the batch before tokens are emitted and the maximum time interval between consecutive batches respectively. Each batch is emitted if either `timeInterval` elapses since last batch or `countInterval` number of tokens are generated. This allows for smooth generation even if model lags during generation. Default parameters are set to 10 tokens and 80ms for time interval (~12 batches per second).
483+
466484
## Available models
467485

468486
| Model Family | Sizes | Quantized |

0 commit comments

Comments
 (0)