Elffuss BraidHub

kikocis/llama-stack public

main · 5.0 KiBRawPermalink
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the terms described in the LICENSE file in
5# the root directory of this source tree.
6
7from enum import auto, Enum
8from typing import List
9
10import torch
11
12from llama_models.llama3.api.datatypes import Message
13from termcolor import cprint
14
15from .base import message_content_as_str, OnViolationAction, ShieldResponse, TextShield
16
17
18class PromptGuardShield(TextShield):
19 class Mode(Enum):
20 INJECTION = auto()
21 JAILBREAK = auto()
22
23 _instances = {}
24 _model_cache = None
25
26 @staticmethod
27 def instance(
28 model_dir: str,
29 threshold: float = 0.9,
30 temperature: float = 1.0,
31 mode: "PromptGuardShield.Mode" = Mode.JAILBREAK,
32 on_violation_action=OnViolationAction.RAISE,
33 ) -> "PromptGuardShield":
34 action_value = on_violation_action.value
35 key = (model_dir, threshold, temperature, mode, action_value)
36 if key not in PromptGuardShield._instances:
37 PromptGuardShield._instances[key] = PromptGuardShield(
38 model_dir=model_dir,
39 threshold=threshold,
40 temperature=temperature,
41 mode=mode,
42 on_violation_action=on_violation_action,
43 )
44 return PromptGuardShield._instances[key]
45
46 def __init__(
47 self,
48 model_dir: str,
49 threshold: float = 0.9,
50 temperature: float = 1.0,
51 mode: "PromptGuardShield.Mode" = Mode.JAILBREAK,
52 on_violation_action: OnViolationAction = OnViolationAction.RAISE,
53 ):
54 super().__init__(on_violation_action)
55 assert (
56 model_dir is not None
57 ), "Must provide a model directory for prompt injection shield"
58 if temperature <= 0:
59 raise ValueError("Temperature must be greater than 0")
60 self.device = "cuda"
61 if PromptGuardShield._model_cache is None:
62 from transformers import AutoModelForSequenceClassification, AutoTokenizer
63
64 # load model and tokenizer
65 tokenizer = AutoTokenizer.from_pretrained(model_dir)
66 model = AutoModelForSequenceClassification.from_pretrained(
67 model_dir, device_map=self.device
68 )
69 PromptGuardShield._model_cache = (tokenizer, model)
70
71 self.tokenizer, self.model = PromptGuardShield._model_cache
72 self.temperature = temperature
73 self.threshold = threshold
74 self.mode = mode
75
76 def convert_messages_to_text(self, messages: List[Message]) -> str:
77 return message_content_as_str(messages[-1])
78
79 async def run_impl(self, text: str) -> ShieldResponse:
80 # run model on messages and return response
81 inputs = self.tokenizer(text, return_tensors="pt")
82 inputs = {name: tensor.to(self.model.device) for name, tensor in inputs.items()}
83 with torch.no_grad():
84 outputs = self.model(**inputs)
85 logits = outputs[0]
86 probabilities = torch.softmax(logits / self.temperature, dim=-1)
87 score_embedded = probabilities[0, 1].item()
88 score_malicious = probabilities[0, 2].item()
89 cprint(
90 f"Ran PromptGuardShield and got Scores: Embedded: {score_embedded}, Malicious: {score_malicious}",
91 color="magenta",
92 )
93
94 if self.mode == self.Mode.INJECTION and (
95 score_embedded + score_malicious > self.threshold
96 ):
97 return ShieldResponse(
98 is_violation=True,
99 violation_type=f"prompt_injection:embedded={score_embedded},malicious={score_malicious}",
100 violation_return_message="Sorry, I cannot do this.",
101 )
102 elif self.mode == self.Mode.JAILBREAK and score_malicious > self.threshold:
103 return ShieldResponse(
104 is_violation=True,
105 violation_type=f"prompt_injection:malicious={score_malicious}",
106 violation_return_message="Sorry, I cannot do this.",
107 )
108
109 return ShieldResponse(
110 is_violation=False,
111 )
112
113
114class JailbreakShield(PromptGuardShield):
115 def __init__(
116 self,
117 model_dir: str,
118 threshold: float = 0.9,
119 temperature: float = 1.0,
120 on_violation_action: OnViolationAction = OnViolationAction.RAISE,
121 ):
122 super().__init__(
123 model_dir=model_dir,
124 threshold=threshold,
125 temperature=temperature,
126 mode=PromptGuardShield.Mode.JAILBREAK,
127 on_violation_action=on_violation_action,
128 )
129
130
131class InjectionShield(PromptGuardShield):
132 def __init__(
133 self,
134 model_dir: str,
135 threshold: float = 0.9,
136 temperature: float = 1.0,
137 on_violation_action: OnViolationAction = OnViolationAction.RAISE,
138 ):
139 super().__init__(
140 model_dir=model_dir,
141 threshold=threshold,
142 temperature=temperature,
143 mode=PromptGuardShield.Mode.INJECTION,
144 on_violation_action=on_violation_action,
145 )