-
Notifications
You must be signed in to change notification settings - Fork 552
feat: add XBG rails #1314
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
base: develop
Are you sure you want to change the base?
feat: add XBG rails #1314
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,43 @@ | ||||||
| # XGB Detectors Integration | ||||||
|
|
||||||
| XGB Detectors utilizes [XGBoost machine learning models](https://xgboost.readthedocs.io/en/stable/tutorials/model.html) to detect harmful content in data. Currently, only | ||||||
| the spam text detector, trained by the [Red Hat TrustyAI team](https://github.com/trustyai-explainability), is available for guardrailing use. | ||||||
|
Comment on lines
+3
to
+4
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. I would suggest a different name, such as |
||||||
|
|
||||||
| ## Setup | ||||||
|
|
||||||
| Update your `config.yaml` file to include XGB detectors: | ||||||
|
|
||||||
| **Spam detection config** | ||||||
| ``` | ||||||
| rails: | ||||||
| config: | ||||||
| xgb: | ||||||
| input: | ||||||
| detectors: | ||||||
| - SPAM | ||||||
| output: | ||||||
| detectors: | ||||||
| - SPAM | ||||||
| input: | ||||||
| flows: | ||||||
| - xgb detect on input | ||||||
| output: | ||||||
| flows: | ||||||
| - xgb detect on output | ||||||
| ``` | ||||||
| The detection flow will not let the input and output text pass if spam is detected. | ||||||
|
|
||||||
| ## Usage | ||||||
|
|
||||||
| Once configured, the XGB Guardrails integration will automatically: | ||||||
|
|
||||||
| 1. Detect spam in inputs to the LLM | ||||||
|
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. I'm not sure I understand the harm of spam being input to the LLM is? Assuming that we are using the common definition of spam as unsolicited bulk email/messaging, I don't know what harmful behavior we're looking to prevent here. I suppose I can accept that detecting spam in outputs from the LLM might be desirable from the perspective of not wanting to have your system used to generate spam emails? I would be concerned about the FPR on this model, specifically as it pertains to the use of LLMs to generate e.g. messages for marketing or others. It would be helpful to have a model card linked in this doc. |
||||||
| 3. Detect spam in outputs from the LLM | ||||||
|
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.
Suggested change
|
||||||
|
|
||||||
| ## Error Handling | ||||||
|
|
||||||
| If the inference request to the XGB spam model fails, the system will assume spam is present as a precautionary measure. | ||||||
|
|
||||||
| ## Notes | ||||||
|
|
||||||
| For more information on TrustyAI and its projects, please visit the TrustyAI [documentation](https://trustyai.org/docs/main/main). | ||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| models: | ||
| - type: main | ||
| engine: hf_pipeline_gpt2 | ||
| model: "openai-community/gpt2" | ||
| rails: | ||
| config: | ||
| xgb: | ||
| input: | ||
| detectors: | ||
| - SPAM | ||
| output: | ||
| detectors: | ||
| - SPAM | ||
| input: | ||
| flows: | ||
| - xgb detect on input | ||
| output: | ||
| flows: | ||
| - xgb detect on output |
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,14 @@ | ||||||
| # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||||||
|
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.
Suggested change
|
||||||
| # SPDX-License-Identifier: Apache-2.0 | ||||||
| # | ||||||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||||||
| # you may not use this file except in compliance with the License. | ||||||
| # You may obtain a copy of the License at | ||||||
| # | ||||||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||||||
| # | ||||||
| # Unless required by applicable law or agreed to in writing, software | ||||||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||||||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||||||
| # See the License for the specific language governing permissions and | ||||||
| # limitations under the License. | ||||||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,56 @@ | ||||||
| # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||||||
|
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.
Suggested change
|
||||||
| # SPDX-License-Identifier: Apache-2.0 | ||||||
| # | ||||||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||||||
| # you may not use this file except in compliance with the License. | ||||||
| # You may obtain a copy of the License at | ||||||
| # | ||||||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||||||
| # | ||||||
| # Unless required by applicable law or agreed to in writing, software | ||||||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||||||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||||||
| # See the License for the specific language governing permissions and | ||||||
| # limitations under the License. | ||||||
|
|
||||||
| from nemoguardrails.actions import action | ||||||
| from nemoguardrails.library.xgb.inference import xgb_inference | ||||||
| from nemoguardrails.rails.llm.config import RailsConfig | ||||||
|
|
||||||
|
|
||||||
| @action() | ||||||
| async def xgb_detect( | ||||||
| source: str, | ||||||
| text: str, | ||||||
| config: RailsConfig, | ||||||
| **kwargs, | ||||||
| ): | ||||||
| xgb_config = getattr(config.rails.config, "xgb") | ||||||
| source_config = getattr(xgb_config, source) | ||||||
|
|
||||||
| enabled_detectors = getattr(source_config, "detectors", None) | ||||||
| if enabled_detectors is None: | ||||||
| raise ValueError( | ||||||
| f"Could not find 'detectors' in source_config: {source_config}" | ||||||
| ) | ||||||
| valid_detectors = ["SPAM"] | ||||||
| for detector in enabled_detectors: | ||||||
| if detector not in valid_detectors: | ||||||
| raise ValueError( | ||||||
| f"XGB detectors can only be defined in the following detectors: {valid_detectors}. " | ||||||
| f"The current detector, '{detector}' is not allowed." | ||||||
| ) | ||||||
|
|
||||||
| valid_sources = ["input", "output"] | ||||||
| if source not in valid_sources: | ||||||
| raise ValueError( | ||||||
| f"XGB detectors can only be defined in the following flows: {valid_sources}. " | ||||||
| f"The current flow, '{source} is not allowed." | ||||||
| ) | ||||||
|
|
||||||
| xgb_response = xgb_inference( | ||||||
| text, | ||||||
| enabled_detectors, | ||||||
| ) | ||||||
|
|
||||||
| return xgb_response | ||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| #### XGB DETECTION RAILS #### | ||
|
|
||
| # INPUT RAILS | ||
|
|
||
| flow xgb detect on input | ||
| """Check if the user content has harmful content" | ||
| $detection = await XGBDetectAction(source="input", text=$user_message) | ||
|
|
||
| if $detection | ||
| bot inform answer unknown | ||
|
Comment on lines
+9
to
+10
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. I'm not sure that this is a particularly helpful response. In both cases, I'd think you would want to provide something more informative. 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. This comment also applies to the output rail. |
||
| abort | ||
|
|
||
| # OUTPUT RAILS | ||
|
|
||
| flow xgb detect on output | ||
| """Check if the bot output has harmful content" | ||
| $detection = await XGBDetectAction(source="output", text=$bot_message) | ||
|
|
||
| if $detection | ||
| bot inform answer unknown | ||
| abort | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| #### XGB DETECTION RAILS #### | ||
|
|
||
| # INPUT RAILS | ||
|
|
||
| define subflow xgb detect on input | ||
| $detection = execute xgb_detect(source="input", text=$user_message) | ||
|
|
||
| if $detection | ||
| bot inform answer unknown | ||
|
Comment on lines
+8
to
+9
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. As with the v2 flows, this response is not particularly helpful and I would suggest having a different message. The same notion applies to the output rail. |
||
| stop | ||
|
|
||
| # OUTPUT RAILS | ||
| define subflow xgb detect on output | ||
| $detection = execute xgb_detect(source="output", text=$user_message) | ||
|
|
||
| if $detection | ||
| bot inform answer unknown | ||
| stop | ||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,64 @@ | ||||||
| # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||||||
|
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.
Suggested change
|
||||||
| # SPDX-License-Identifier: Apache-2.0 | ||||||
| # | ||||||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||||||
| # you may not use this file except in compliance with the License. | ||||||
| # You may obtain a copy of the License at | ||||||
| # | ||||||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||||||
| # | ||||||
| # Unless required by applicable law or agreed to in writing, software | ||||||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||||||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||||||
| # See the License for the specific language governing permissions and | ||||||
| # limitations under the License. | ||||||
|
|
||||||
| import logging | ||||||
| import pickle | ||||||
| from typing import List | ||||||
|
|
||||||
| log = logging.getLogger(__name__) | ||||||
| MODEL_REGISTRY = { | ||||||
| "SPAM": { | ||||||
| "model_path": "nemoguardrails/library/xgb/model_artifacts/model.pkl", | ||||||
| "vectorizer_path": "nemoguardrails/library/xgb/model_artifacts/vectorizer.pkl", | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
|
|
||||||
| def xgb_inference(text: str, enabled_detectors: List[str]): | ||||||
| detections = [] | ||||||
| for detector in enabled_detectors: | ||||||
| model_info = MODEL_REGISTRY.get(detector) | ||||||
| if not model_info: | ||||||
| raise ValueError( | ||||||
| f"XGB detector '{detector}' is not configured in the MODEL_REGISTRY." | ||||||
| ) | ||||||
| model_path = model_info["model_path"] | ||||||
| vectorizer_path = model_info["vectorizer_path"] | ||||||
| with open(model_path, "rb") as f: | ||||||
| model = pickle.load(f) | ||||||
| with open(vectorizer_path, "rb") as f: | ||||||
| vectorizer = pickle.load(f) | ||||||
|
|
||||||
| try: | ||||||
| X_vec = vectorizer.transform([text]) | ||||||
| prediction = model.predict(X_vec)[0] | ||||||
| probability = model.predict_proba(X_vec)[0] | ||||||
|
|
||||||
| is_safe = prediction == 0 | ||||||
| confidence = max(probability) | ||||||
|
|
||||||
| detections.append( | ||||||
| { | ||||||
| "allowed": bool(is_safe), | ||||||
| "score": float(confidence), | ||||||
| "prediction": "safe" if is_safe else detector, | ||||||
| } | ||||||
| ) | ||||||
|
|
||||||
| except Exception as e: | ||||||
| raise ValueError( | ||||||
| f"Error during XGBoost inference for detector '{detector}': {e}" | ||||||
| ) | ||||||
| return detections | ||||||
|
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. Is this model currently on something like Huggingface? I'm very much against including the pickle files in the repo itself and it's important to have a model card and version control for the model itself that is independent of the guardrails git repository. Same comment applies to the vectorizer pickle file. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -46,7 +46,7 @@ repository = "https://github.com/NVIDIA/NeMo-Guardrails" | |
| nemoguardrails = "nemoguardrails.__main__:app" | ||
|
|
||
| [tool.poetry.dependencies] | ||
| python = ">=3.9,!=3.9.7,<3.14" | ||
| python = ">=3.10,!=3.9.7,<3.14" | ||
|
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. This is a really significant change. Although Python 3.9 is EOL, dropping support for an entire Python version is not something that should be done without significant regression testing. |
||
| aiohttp = ">=3.10.11" | ||
| annoy = ">=1.17.3" | ||
| fastapi = ">=0.103.0," | ||
|
|
@@ -101,6 +101,11 @@ google-cloud-language = { version = ">=2.14.0", optional = true } | |
| # jailbreak injection | ||
| yara-python = { version = "^4.5.1", optional = true } | ||
|
|
||
| # xgb | ||
| xgboost = "^3.0.2" | ||
| scikit-learn = "^1.7.1" | ||
| huggingface-hub = "^0.34.3" | ||
|
|
||
| [tool.poetry.extras] | ||
| sdd = ["presidio-analyzer", "presidio-anonymizer"] | ||
| eval = ["tqdm", "numpy", "streamlit", "tornado"] | ||
|
|
||
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.
Do you have a link to information about how this model was trained? What is the F1 score on various spam datasets?
I would like to see some information like what is presented about the jailbreak heuristics and ideally, the model should be hosted on something like HuggingFace alongside a model card.