generated from guardrails-ai/validator-template
-
Notifications
You must be signed in to change notification settings - Fork 0
do not allow remote inference #8
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
zsimjee
wants to merge
4
commits into
main
Choose a base branch
from
fix-local-inference
base: main
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.
+25
−20
Open
Changes from all commits
Commits
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 |
---|---|---|
|
@@ -16,4 +16,5 @@ jobs: | |
- name: Run qa | ||
run: | | ||
pip install ".[dev]" | ||
python validator/post-install.py | ||
make qa |
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 |
---|---|---|
@@ -1,4 +1,4 @@ | ||
from typing import Callable, Dict, List, Optional, Union | ||
from typing import Any, Dict, List, Optional, Union, TypedDict | ||
|
||
from guardrails.validator_base import ( | ||
FailResult, | ||
|
@@ -9,7 +9,7 @@ | |
) | ||
from guardrails.types import OnFailAction | ||
from sentence_splitter import split_text_into_sentences | ||
from transformers import pipeline | ||
from transformers.pipelines import pipeline | ||
|
||
|
||
@register_validator(name="guardrails/bias_check", data_type="string") | ||
|
@@ -32,14 +32,9 @@ class BiasCheck(Validator): | |
def __init__( | ||
self, | ||
threshold: float = 0.9, | ||
on_fail: Optional[Union[str, Callable]] = None, | ||
**kwargs, | ||
): | ||
super().__init__(on_fail=on_fail) # type: ignore | ||
valid_on_fail_operations = {"fix", "noop", "exception"} | ||
if isinstance(on_fail, str) and on_fail not in valid_on_fail_operations: | ||
raise Exception( | ||
f"on_fail value ({on_fail}) not in list of allowable operations: {valid_on_fail_operations}" | ||
) | ||
super().__init__(**kwargs) | ||
self.threshold = threshold | ||
|
||
# There are some spurious loading complaints with TFDistilBert models. | ||
|
@@ -50,7 +45,10 @@ def __init__( | |
tokenizer="d4data/bias-detection-model", | ||
) | ||
|
||
def validate( | ||
def validate(self, value: Any, metadata: Dict[str, Any] = {}) -> ValidationResult: | ||
return super().validate(value, metadata) | ||
|
||
def _validate( | ||
self, | ||
value: Union[str, List[str]], | ||
metadata: Optional[Dict] = None | ||
|
@@ -61,7 +59,7 @@ def validate( | |
single_sentence_passed = True | ||
value = [value,] # Ensure we're always passing lists of strings into the classifier. | ||
|
||
scores = self._inference(value) | ||
scores = self._inference_local(value) | ||
passing_outputs = list() | ||
passing_scores = list() | ||
failing_outputs = list() | ||
|
@@ -106,7 +104,7 @@ def fix_passage(self, text: str) -> str: | |
then recombine them and return a new paragraph. May not preserve whitespace | ||
between sentences.""" | ||
sentences = split_text_into_sentences(text, language='en') | ||
scores = self._inference(sentences) | ||
scores = self._inference_local(sentences) | ||
unbiased_sentences = list() | ||
for score, sentence in zip(scores, sentences): | ||
if score < self.threshold: | ||
|
@@ -117,10 +115,10 @@ def fix_passage(self, text: str) -> str: | |
# Remote inference is unsupported for this model on account of the NER. | ||
def _inference_local(self, sentences: List[str]) -> List[float]: # type: ignore | ||
scores = list() | ||
predictions = self.classification_model(sentences) | ||
predictions: List[PipelinePrediction] = self.classification_model(sentences) # type: ignore | ||
for pred in predictions: | ||
label = pred['label'] # type: ignore | ||
score = pred['score'] # type: ignore | ||
label = pred['label'] | ||
score = pred['score'] | ||
Comment on lines
+118
to
+121
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. 🙏 |
||
if label == 'Biased': | ||
scores.append(score) | ||
elif label == 'Non-biased': | ||
|
@@ -129,3 +127,8 @@ def _inference_local(self, sentences: List[str]) -> List[float]: # type: ignore | |
# This should never happen: | ||
raise Exception("Unexpected prediction label: {}".format(label)) | ||
return scores | ||
|
||
# Define the type for pipeline predictions | ||
class PipelinePrediction(TypedDict): | ||
label: str | ||
score: float |
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.
I think this would be a breaking change since
on_fail
is going fro a positional argument to a keyword only argument.