-
Notifications
You must be signed in to change notification settings - Fork 658
refactor(jailbreak): Use onnx instead of pickle to load model #1715
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
Open
erickgalinkin
wants to merge
6
commits into
develop
Choose a base branch
from
jailbreak-onnx
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
82633e2
Update code to use onnx instead of pickle
erickgalinkin fbece23
Update nemoguardrails/library/jailbreak_detection/model_based/models.py
erickgalinkin 63a9a54
Apply black, adjust comments. Add trailing newline to `requirements.txt`
erickgalinkin 759e8ef
Adjust tests to expect onnx instead of pickle
erickgalinkin 947e011
Fix broken test.
erickgalinkin be31f73
Fix file download for checks. Update Dockerfiles with new location. F…
erickgalinkin 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
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
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 |
|---|---|---|
|
|
@@ -15,16 +15,17 @@ | |
|
|
||
| from typing import Tuple | ||
|
|
||
| import numpy as np | ||
|
|
||
|
|
||
| class SnowflakeEmbed: | ||
| def __init__(self): | ||
| import torch | ||
| from transformers import AutoModel, AutoTokenizer | ||
|
|
||
| self.device = "cuda:0" if torch.cuda.is_available() else "cpu" | ||
| self.tokenizer = AutoTokenizer.from_pretrained("Snowflake/snowflake-arctic-embed-m-long") | ||
| self.device = "cuda" if torch.cuda.is_available() else "cpu" | ||
|
Member
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. Shouldn't we also use |
||
| self.tokenizer = AutoTokenizer.from_pretrained( | ||
| "Snowflake/snowflake-arctic-embed-m-long", | ||
| trust_remote_code=True, | ||
| ) | ||
|
erickgalinkin marked this conversation as resolved.
|
||
| self.model = AutoModel.from_pretrained( | ||
| "Snowflake/snowflake-arctic-embed-m-long", | ||
| trust_remote_code=True, | ||
|
|
@@ -35,24 +36,31 @@ def __init__(self): | |
| self.model.eval() | ||
|
|
||
| def __call__(self, text: str): | ||
| tokens = self.tokenizer([text], padding=True, truncation=True, return_tensors="pt", max_length=2048) | ||
| tokens = self.tokenizer( | ||
| [text], padding=True, truncation=True, return_tensors="pt", max_length=2048 | ||
| ) | ||
| tokens = tokens.to(self.device) | ||
| embeddings = self.model(**tokens)[0][:, 0] | ||
| return embeddings.detach().cpu().squeeze(0).numpy() | ||
|
|
||
|
|
||
| class JailbreakClassifier: | ||
| def __init__(self, random_forest_path: str): | ||
| import pickle | ||
| from onnxruntime import InferenceSession | ||
|
|
||
| self.embed = SnowflakeEmbed() | ||
| with open(random_forest_path, "rb") as fd: | ||
| self.classifier = pickle.load(fd) | ||
| # See https://onnx.ai/sklearn-onnx/auto_examples/plot_convert_decision_function.html | ||
| self.classifier = InferenceSession( | ||
| random_forest_path, providers=["CPUExecutionProvider"] | ||
| ) | ||
|
|
||
| def __call__(self, text: str) -> Tuple[bool, float]: | ||
| e = self.embed(text) | ||
| probs = self.classifier.predict_proba([e]) | ||
| classification = np.argmax(probs) | ||
| prob = np.max(probs) | ||
| res = self.classifier.run(None, {"X": [e]}) | ||
| # InferenceSession returns a result where the first item is equivalent to argmax over probabilities | ||
| classification = res[0].item() | ||
| # The second is a list of dicts of probabilities -- the slice res[1][:2] should have only one element. | ||
| # We access the dict entry for the class. | ||
| prob = res[1][:2][0][classification] | ||
|
erickgalinkin marked this conversation as resolved.
|
||
| score = -prob if classification == 0 else prob | ||
| return bool(classification), float(score) | ||
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
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.
Don't we want to use
local_dirinstead ofcache_dir?Here also the test fails if the
classifier_pathcannot be created for some reason.