gabrielchua commited on
Commit
3896954
·
1 Parent(s): 9750a17

Delete lionguard2.py

Browse files
Files changed (1) hide show
  1. lionguard2.py +0 -170
lionguard2.py DELETED
@@ -1,170 +0,0 @@
1
- """
2
- lionguard2.py
3
- """
4
-
5
- import torch
6
- import torch.nn as nn
7
-
8
- CATEGORIES = {
9
- "binary": ["binary"],
10
- "hateful": ["hateful_l1", "hateful_l2"],
11
- "insults": ["insults"],
12
- "sexual": [
13
- "sexual_l1",
14
- "sexual_l2",
15
- ],
16
- "physical_violence": ["physical_violence"],
17
- "self_harm": ["self_harm_l1", "self_harm_l2"],
18
- "all_other_misconduct": [
19
- "all_other_misconduct_l1",
20
- "all_other_misconduct_l2",
21
- ],
22
- }
23
-
24
- INPUT_DIMENSION = 3072 # length of OpenAI embeddings
25
-
26
-
27
- class LionGuard2(nn.Module):
28
- def __init__(
29
- self,
30
- input_dim=INPUT_DIMENSION,
31
- label_names=CATEGORIES.keys(),
32
- categories=CATEGORIES,
33
- ):
34
- """
35
- LionGuard2 is a localised content moderation model that flags whether text violates the following categories:
36
-
37
- 1. `hateful`: Text that discriminates, criticizes, insults, denounces, or dehumanizes a person or group on the basis of a protected identity.
38
-
39
- There are two sub-categories for the `hateful` category:
40
- a. `level_1_discriminatory`: Text that contains derogatory or generalized negative statements targeting a protected group.
41
- b. `level_2_hate_speech`: Text that explicitly calls for harm or violence against a protected group; or language praising or justifying violence against them.
42
-
43
- 2. `insults`: Text that insults demeans, humiliates, mocks, or belittles a person or group **without** referencing a legally protected trait.
44
- For example, this includes personal attacks on attributes such as someone’s appearance, intellect, behavior, or other non-protected characteristics.
45
-
46
- 3. `sexual`: Text that depicts or indicates sexual interest, activity, or arousal, using direct or indirect references to body parts, sexual acts, or physical traits.
47
- This includes sexual content that may be inappropriate for certain audiences.
48
-
49
- There are two sub-categories for the `sexual` category:
50
- a. `level_1_not_appropriate_for_minors`: Text that contains mild-to-moderate sexual content that is generally adult-oriented or potentially unsuitable for those under 16.
51
- May include matter-of-fact discussions about sex, sexuality, or sexual preferences.
52
- b. `level_2_not_appropriate_for_all_ages`: Text that contains content aimed at adults and considered explicit, graphic, or otherwise inappropriate for a broad audience.
53
- May include explicit descriptions of sexual acts, detailed sexual fantasies, or highly sexualized content.
54
-
55
- 4. `physical_violence`: Text that includes glorification of violence or threats to inflict physical harm or injury on a person, group, or entity.
56
-
57
- 5. `self_harm`: Text that promotes, suggests, or expresses intent to self-harm or commit suicide.
58
-
59
- There are two sub-categories for the `self_harm` category:
60
- a. `level_1_self_harm_intent`: Text that expresses suicidal thoughts or self-harm intention; or content encouraging someone to self-harm.
61
- b. `level_2_self_harm_action`: Text that describes or indicates ongoing or imminent self-harm behavior.
62
-
63
- 6. `all_other_misconduct`: This is a catch-all category for any other unsafe text that does not fit into the other categories.
64
- It includes text that seeks or provides information about engaging in misconduct, wrongdoing, or criminal activity, or that threatens to harm,
65
- defraud, or exploit others. This includes facilitating illegal acts (under Singapore law) or other forms of socially harmful activity.
66
-
67
- There are two sub-categories for the `all_other_misconduct` category:
68
- a. `level_1_not_socially_accepted`: Text that advocates or instructs on unethical/immoral activities that may not necessarily be illegal but are socially condemned.
69
- b. `level_2_illegal_activities`: Text that seeks or provides instructions to carry out clearly illegal activities or serious wrongdoing; includes credible threats of severe harm.
70
-
71
- Lastly, there is an additional `binary` category (#7) which flags whether the text is unsafe in general.
72
-
73
- The model takes in as input text, after it has been encoded with OpenAI's `text-embedding-3-small` model.
74
-
75
- The model outputs the probabilities of each category being true.
76
-
77
- ================================
78
-
79
- Args:
80
- input_dim: The dimension of the input embeddings. This defaults to 3072, which is the dimension of the embeddings from OpenAI's `text-embedding-3-small` model. This should not be changed.
81
- label_names: The names of the labels. This defaults to the keys of the CATEGORIES dictionary. This should not be changed.
82
- categories: The categories of the labels. This defaults to the CATEGORIES dictionary. This should not be changed.
83
-
84
- Returns:
85
- A LionGuard2 model.
86
- """
87
- super(LionGuard2, self).__init__()
88
- self.label_names = label_names
89
- self.n_outputs = len(label_names)
90
- self.categories = categories
91
-
92
- # Shared layers
93
- self.shared_layers = nn.Sequential(
94
- nn.Linear(input_dim, 256),
95
- nn.ReLU(),
96
- nn.Dropout(0.2),
97
- nn.Linear(256, 128),
98
- nn.ReLU(),
99
- nn.Dropout(0.2),
100
- )
101
-
102
- # Output heads for each label
103
- self.output_heads = nn.ModuleList(
104
- [
105
- nn.Sequential(
106
- nn.Linear(128, 32),
107
- nn.ReLU(),
108
- nn.Linear(32, 2), # 2 thresholds for ordinal classification
109
- nn.Sigmoid(),
110
- )
111
- for _ in range(self.n_outputs)
112
- ]
113
- )
114
-
115
- def forward(self, x):
116
- # Pass through shared layers
117
- h = self.shared_layers(x)
118
- # Pass through each output head
119
- return [head(h) for head in self.output_heads]
120
-
121
- def predict(self, embeddings):
122
- """
123
- Predict the probabilities of each label being true.
124
-
125
- Args:
126
- embeddings: A numpy array of embeddings (N * INPUT_DIMENSION)
127
-
128
- Returns:
129
- A dictionary of probabilities.
130
- """
131
- # Convert input to PyTorch tensor if not already
132
- if not isinstance(embeddings, torch.Tensor):
133
- x = torch.tensor(embeddings, dtype=torch.float32)
134
- else:
135
- x = embeddings
136
-
137
- # Pass through model
138
- with torch.no_grad():
139
- outputs = self.forward(x)
140
-
141
- # Stack outputs into a single tensor
142
- raw_predictions = torch.stack(outputs) # SIZE:
143
-
144
- # Extract and format probabilities from raw predictions
145
- output = {}
146
- for i, main_cat in enumerate(self.label_names):
147
- sub_categories = self.categories[main_cat]
148
- for j, sub_cat in enumerate(sub_categories):
149
- # j=0 uses P(y>0)
150
- # j=1 uses P(y>1) if L2 category exists
151
- output[sub_cat] = raw_predictions[i, :, j]
152
-
153
- # Post processing step:
154
- # If L2 category exists, and P(L2) > P(L1),
155
- # Set both P(L1) and P(L2) to their average to maintain ordinal consistency
156
- if len(sub_categories) > 1:
157
- l1 = output[sub_categories[0]]
158
- l2 = output[sub_categories[1]]
159
-
160
- # Update probabilities on samples where P(L2) > P(L1)
161
- mask = l2 > l1
162
- mean_prob = (l1 + l2) / 2
163
- l1[mask] = mean_prob[mask]
164
- l2[mask] = mean_prob[mask]
165
- output[sub_categories[0]] = l1
166
- output[sub_categories[1]] = l2
167
-
168
- for key, value in output.items():
169
- output[key] = value.numpy().tolist()
170
- return output