-
Notifications
You must be signed in to change notification settings - Fork 27
⚡ cache hf results in tests #373
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 5 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
eaf62d1
:zap: cache hf results in tests
joerunde af9b454
:bug: fix token prompts
joerunde a7ec8d8
:sparkles: swap to persistent file-based caching
joerunde 798f157
:memo: docstring for hf cache
joerunde 403bac7
:bug: fix caching
joerunde 36bf204
:art: fixup type hint
joerunde 05be1a6
Merge branch 'main' into cache-hf-results
joerunde 5916fb2
:bug: fix merge error, add cache
joerunde 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
Large diffs are not rendered by default.
Oops, something went wrong.
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 |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| import json | ||
| import os | ||
| from pathlib import Path | ||
|
|
||
|
|
||
| class HFResultCache: | ||
| """ | ||
| A simple cache for storing and retrieving results from Hugging Face models. | ||
| The cache is stored in a JSON file named 'hf_cache.json' in the same | ||
| directory as this script. | ||
|
|
||
| This cache can be (re)populated by running all tests and committing the | ||
| changes to the .json file. | ||
| """ | ||
|
|
||
| def __init__(self): | ||
| """ | ||
| Initialize the HFResultCache. Load existing cached results from | ||
| 'hf_cache.json'. If the file does not exist, an empty cache dictionary | ||
| is created. | ||
| """ | ||
| current_dir = Path(os.path.abspath(os.path.dirname(__file__))) | ||
| self.cached_results_file_path = current_dir / "hf_cache.json" | ||
|
|
||
| if not self.cached_results_file_path.exists(): | ||
| self.cached_results = {} | ||
| # Start with empty file | ||
| with open(self.cached_results_file_path, 'w') as f: | ||
| json.dump(self.cached_results, f) | ||
| else: | ||
| with open(self.cached_results_file_path) as f: | ||
| self.cached_results = json.load(f) | ||
|
|
||
| self.dirty = False | ||
|
|
||
| def write_cache(self): | ||
| """ | ||
| Write the current cache to 'hf_cache.json' if it has been modified. | ||
| """ | ||
| if self.dirty: | ||
| with open(self.cached_results_file_path, 'w') as f: | ||
| json.dump(self.cached_results, f) | ||
| self.dirty = False | ||
|
|
||
| def get_cached_result(self, model: str, prompt: str, | ||
| max_tokens: int) -> dict: | ||
| """ | ||
| Retrieve a cached result for the given model, prompt, and max_tokens. | ||
| Returns an empty dictionary if no cache entry is found. | ||
| """ | ||
| if isinstance(prompt, list): | ||
| prompt = self._token_ids_to_string(prompt) | ||
| max_tokens = str(max_tokens) | ||
|
|
||
| return self.cached_results.get(model, {}).get(prompt, | ||
| {}).get(max_tokens, {}) | ||
|
|
||
| def add_to_cache(self, model: str, prompt: str, max_tokens: int, | ||
|
||
| result: dict): | ||
| """ | ||
| Add a new result to the cache for the given model, prompt, and | ||
| max_tokens. Marks the cache as 'dirty' to indicate that it needs to be | ||
| written to disk. | ||
| """ | ||
| if isinstance(prompt, list): | ||
| prompt = self._token_ids_to_string(prompt) | ||
| max_tokens = str(max_tokens) | ||
|
|
||
| self.cached_results.setdefault(model, | ||
| {}).setdefault(prompt, {}).setdefault( | ||
| max_tokens, result) | ||
| self.dirty = True | ||
|
|
||
| def _token_ids_to_string(self, token_ids: list[int]) -> str: | ||
| """Use a string to represent a list of token ids, so that it can be | ||
| hashed and used as a json key.""" | ||
|
|
||
| return "__tokens__" + "_".join(str(token_id) for token_id in token_ids) | ||
|
Collaborator
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. nice, no tokenizer required. |
||
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
Oops, something went wrong.
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.
Shouldn't the type annotation for prompt be
Union[str, list[int]]?