This repository was archived by the owner on Sep 10, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 248
Chat tokenization fixes in generate.py & API #1035
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,6 +10,8 @@ | |
| from dataclasses import dataclass | ||
| from typing import Any, Dict, List, Optional, Union | ||
|
|
||
| import torch | ||
|
|
||
| from build.utils import device_sync | ||
|
|
||
| from generate import Generator, GeneratorArgs | ||
|
|
@@ -222,7 +224,6 @@ def __init__(self, *args, **kwargs): | |
| """ | ||
|
|
||
| super().__init__(*args, **kwargs) | ||
| self.start_pos = 0 | ||
| self.max_seq_length = ( | ||
| self.model.config.max_seq_length | ||
| + self.speculative_builder_args.speculate_k | ||
|
|
@@ -257,20 +258,25 @@ def chunked_completion(self, completion_request: CompletionRequest): | |
| CompletionResponseChunk objects in response to completion_request as tokens are generated. | ||
|
|
||
| """ | ||
| device_sync(device=self.builder_args.device) | ||
|
|
||
| # Initialize counters for chunk responses and encode the prompt. | ||
| id = str(uuid.uuid4()) | ||
|
|
||
| idx = 0 | ||
| buffer = [] | ||
| encoded = self.encode_tokens( | ||
| completion_request.messages[-1].get("content"), | ||
| bos=True, | ||
| device=self.builder_args.device, | ||
| tokens = self.chat_formatter.encode_dialog_prompt( | ||
| dialog=[ | ||
| {"role": message["role"], "content": message["content"]} | ||
| for message in completion_request.messages | ||
| ] | ||
| ) | ||
|
|
||
| encoded = torch.tensor(tokens, dtype=torch.int, device=self.builder_args.device) | ||
| print(self.tokenizer.decode(tokens)) | ||
|
|
||
| start_pos = 0 | ||
|
|
||
| generator_args = GeneratorArgs( | ||
| completion_request.messages[-1].get("content"), | ||
| None, | ||
| max_new_tokens=( | ||
| int(completion_request.max_tokens) | ||
| if completion_request.max_tokens | ||
|
|
@@ -279,33 +285,39 @@ def chunked_completion(self, completion_request: CompletionRequest): | |
| encoded_prompt=encoded, | ||
| temperature=float(completion_request.temperature), | ||
| chat_mode=False, | ||
| sequential_prefill=True, | ||
| ) | ||
|
|
||
| def callback(x, *, done_generating=False): | ||
| return self._callback( | ||
| x, | ||
| buffer=buffer, | ||
| buffer=None, | ||
| done_generating=done_generating, | ||
| ) | ||
|
|
||
| device_sync(device=self.builder_args.device) | ||
|
|
||
| # Process each token, metrics tuple yielded by Generator.generate. | ||
| for y, _ in self.generate( | ||
| self.model, | ||
| encoded, | ||
| generator_args.max_new_tokens, | ||
| model=self.model, | ||
| prompt=encoded, | ||
| max_new_tokens=generator_args.max_new_tokens, | ||
| draft_model=self.draft_model, | ||
| speculate_k=generator_args.speculate_k, | ||
| chat_mode=generator_args.chat_mode, | ||
| callback=callback, | ||
| temperature=generator_args.temperature, | ||
| top_k=generator_args.top_k, | ||
| sequential_prefill=generator_args.sequential_prefill, | ||
| start_pos=self.start_pos, | ||
| start_pos=start_pos, | ||
| max_seq_length=self.max_seq_length, | ||
| seed=int(completion_request.seed), | ||
| ): | ||
| if y is None: | ||
| continue | ||
| elif y.item() == self.tokenizer.eos_id: | ||
| # Stop generation if the EOS token is generated. | ||
| break | ||
|
|
||
| # Decode the torch.Tensor token to a string and append to the buffer. Separate the sequences with a period token. | ||
| content = "".join( | ||
|
|
@@ -330,7 +342,7 @@ def callback(x, *, done_generating=False): | |
| system_fingerprint=self.system_fingerprint, | ||
| ) | ||
| yield chunk_response | ||
| self.start_pos += y.size(0) | ||
| start_pos += y.size(0) | ||
| idx += 1 | ||
|
|
||
| # Yield an ending chunk indicating the generation has completed. | ||
|
|
@@ -369,10 +381,4 @@ def sync_completion(self, request: CompletionRequest): | |
| ) | ||
|
|
||
| def _callback(self, x, *, buffer, done_generating): | ||
| period_id = self.tokenizer.encode(".")[0] | ||
| buffer.append(self.tokenizer.decode([period_id] + x.tolist())[1:]) | ||
| if ( | ||
| self.is_llama3_model | ||
| and x.item() == self.tokenizer.special_tokens["<|eot_id|>"] | ||
| ): | ||
| buffer = buffer[:-1] # drop the eot_id from the output buffer | ||
| pass | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why is this is a pass again? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The callback function is only used in generate() for the CLI interactive chat to print results to stdout. I initially copied this code naively when refactoring the original generate.py and copied it over to openaiapi where it isn't used. |
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just checking that this is an intentional print
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes - this prints out the prompt on the server side so that it's easy to track the full prompt solely from the server side.
However, this raises a larger issue in the generate/API stack - we need to replace print statements with a logger so that users can choose not to print these debug messages.