Shing Yee commited on
Commit
3c2639a
·
unverified ·
1 Parent(s): 2aec41c

Add application

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ models/*.safetensors filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
app.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ from utils import (
4
+ device,
5
+ jina_tokenizer,
6
+ jina_model,
7
+ embeddings_predict_relevance,
8
+ stsb_model,
9
+ stsb_tokenizer,
10
+ ms_model,
11
+ ms_tokenizer,
12
+ cross_encoder_predict_relevance
13
+ )
14
+
15
+ def predict(system_prompt, user_prompt, selected_model):
16
+ if selected_model == "jinaai/jina-embeddings-v2-small-en":
17
+ predicted_label, probabilities = embeddings_predict_relevance(system_prompt, user_prompt, jina_model, jina_tokenizer, device)
18
+ elif selected_model == "cross-encoder/stsb-roberta-base":
19
+ predicted_label, probabilities = cross_encoder_predict_relevance(system_prompt, user_prompt, stsb_model, stsb_tokenizer, device)
20
+ elif selected_model == "cross-encoder/ms-marco-MiniLM-L-6-v2":
21
+ predicted_label, probabilities = cross_encoder_predict_relevance(system_prompt, user_prompt, ms_model, ms_tokenizer, device)
22
+
23
+ probability_off_topic = probabilities[0][1] * 100
24
+ result = f'{probability_off_topic:.3f}% chance this is off-topic'
25
+
26
+ return result
27
+
28
+ with gr.Blocks(theme=gr.themes.Soft(), fill_height=True) as app:
29
+
30
+ gr.Markdown("# Off-Topic Classification using Fine-tuned Embeddings and Cross-Encoder Models")
31
+
32
+ with gr.Row():
33
+ system_prompt = gr.Textbox(label="System Prompt")
34
+ user_prompt = gr.Textbox(label="User Prompt")
35
+
36
+ with gr.Row():
37
+ selected_model = gr.Dropdown(
38
+ ["jinaai/jina-embeddings-v2-small-en",
39
+ "cross-encoder/stsb-roberta-base",
40
+ "cross-encoder/ms-marco-MiniLM-L-6-v2"],
41
+ label="Select a model")
42
+
43
+ # Button to run the prediction
44
+ get_classfication = gr.Button("Check Content")
45
+
46
+ output_result = gr.Textbox(label="Classification and Probabilities", lines=5)
47
+
48
+ get_classfication.click(
49
+ fn=predict,
50
+ inputs=[system_prompt, user_prompt, selected_model],
51
+ outputs=output_result
52
+ )
53
+
54
+ if __name__ == "__main__":
55
+ app.launch()
models/cross-encoder-ms-marco-MiniLM-L-6-v2-CrossEncoder-OffTopic-Classifier-20240918-090615.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:78a99fac3bc5b4729fee844d2154ea625aa9ceac2928cd648984ee1da5b8a203
3
+ size 91236352
models/cross-encoder-stsb-roberta-base-CrossEncoder-OffTopic-Classifier-20240920-174009.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1e90752828e92bc2f8ec567b85b3de5a0c8c5ddc331c1907d4dfa950624f71ce
3
+ size 500085976
models/jinaai-jina-embeddings-v2-small-en-TwinEncoder-OffTopic-Classifier-20240915-151858.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:223687abc28cf0fa198d326d2786374000396d841e66d684c022941da2ca9628
3
+ size 144076480
requirements.txt ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiofiles==23.2.1
2
+ annotated-types==0.7.0
3
+ anyio==4.6.0
4
+ certifi==2024.8.30
5
+ charset-normalizer==3.3.2
6
+ click==8.1.7
7
+ contourpy==1.3.0
8
+ cycler==0.12.1
9
+ fastapi==0.115.0
10
+ ffmpy==0.4.0
11
+ filelock==3.16.1
12
+ fonttools==4.54.0
13
+ fsspec==2024.9.0
14
+ gradio==4.44.0
15
+ gradio_client==1.3.0
16
+ h11==0.14.0
17
+ httpcore==1.0.5
18
+ httpx==0.27.2
19
+ huggingface-hub==0.25.1
20
+ idna==3.10
21
+ importlib_resources==6.4.5
22
+ Jinja2==3.1.4
23
+ kiwisolver==1.4.7
24
+ markdown-it-py==3.0.0
25
+ MarkupSafe==2.1.5
26
+ matplotlib==3.9.2
27
+ mdurl==0.1.2
28
+ mpmath==1.3.0
29
+ networkx==3.3
30
+ numpy==2.1.1
31
+ orjson==3.10.7
32
+ packaging==24.1
33
+ pandas==2.2.3
34
+ pillow==10.4.0
35
+ pydantic==2.9.2
36
+ pydantic_core==2.23.4
37
+ pydub==0.25.1
38
+ Pygments==2.18.0
39
+ pyparsing==3.1.4
40
+ python-dateutil==2.9.0.post0
41
+ python-multipart==0.0.10
42
+ pytz==2024.2
43
+ PyYAML==6.0.2
44
+ regex==2024.9.11
45
+ requests==2.32.3
46
+ rich==13.8.1
47
+ ruff==0.6.7
48
+ safetensors==0.4.5
49
+ semantic-version==2.10.0
50
+ setuptools==75.1.0
51
+ shellingham==1.5.4
52
+ six==1.16.0
53
+ sniffio==1.3.1
54
+ starlette==0.38.6
55
+ sympy==1.13.3
56
+ tokenizers==0.19.1
57
+ tomlkit==0.12.0
58
+ torch==2.4.1
59
+ tqdm==4.66.5
60
+ transformers==4.44.2
61
+ typer==0.12.5
62
+ typing_extensions==4.12.2
63
+ tzdata==2024.2
64
+ urllib3==2.2.3
65
+ uvicorn==0.30.6
66
+ websockets==12.0
utils.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ from safetensors.torch import load_file
4
+ from transformers import AutoModel, AutoTokenizer
5
+
6
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
7
+
8
+ # Load the model state_dict from safetensors
9
+ def load_model_safetensors(model, load_path="model.safetensors"):
10
+ # Load the safetensors file
11
+ state_dict = load_file(load_path)
12
+ # Load the state dict into the model
13
+ model.load_state_dict(state_dict)
14
+ return model
15
+
16
+ ##########################
17
+ # JINA EMBEDDINGS
18
+ ##########################
19
+
20
+ # Jina Configs
21
+ JINA_CONTEXT_LEN = 1024
22
+
23
+ # Adapter for embeddings
24
+ class Adapter(nn.Module):
25
+ def __init__(self, hidden_size):
26
+ super(Adapter, self).__init__()
27
+ self.down_project = nn.Linear(hidden_size, hidden_size // 2)
28
+ self.activation = nn.ReLU()
29
+ self.up_project = nn.Linear(hidden_size // 2, hidden_size)
30
+
31
+ def forward(self, x):
32
+ down = self.down_project(x)
33
+ activated = self.activation(down)
34
+ up = self.up_project(activated)
35
+ return up + x # Residual connection
36
+
37
+ # Pool by attention score
38
+ class AttentionPooling(nn.Module):
39
+ def __init__(self, hidden_size):
40
+ super(AttentionPooling, self).__init__()
41
+ self.attention_weights = nn.Parameter(torch.randn(hidden_size))
42
+
43
+ def forward(self, hidden_states):
44
+ # hidden_states: [seq_len, batch_size, hidden_size]
45
+ scores = torch.matmul(hidden_states, self.attention_weights)
46
+ attention_weights = torch.softmax(scores, dim=0)
47
+ weighted_sum = torch.sum(attention_weights.unsqueeze(-1) * hidden_states, dim=0)
48
+ return weighted_sum
49
+
50
+ # Custom bi-encoder model with MLP layers for interaction
51
+ class CrossEncoderWithSharedBase(nn.Module):
52
+ def __init__(self, base_model, num_labels=2, num_heads=8):
53
+ super(CrossEncoderWithSharedBase, self).__init__()
54
+ # Shared pre-trained model
55
+ self.shared_encoder = base_model
56
+ hidden_size = self.shared_encoder.config.hidden_size
57
+ # Sentence-specific adapters
58
+ self.adapter1 = Adapter(hidden_size)
59
+ self.adapter2 = Adapter(hidden_size)
60
+ # Cross-attention layers
61
+ self.cross_attention_1_to_2 = nn.MultiheadAttention(hidden_size, num_heads)
62
+ self.cross_attention_2_to_1 = nn.MultiheadAttention(hidden_size, num_heads)
63
+ # Attention pooling layers
64
+ self.attn_pooling_1_to_2 = AttentionPooling(hidden_size)
65
+ self.attn_pooling_2_to_1 = AttentionPooling(hidden_size)
66
+ # Projection layer with non-linearity
67
+ self.projection_layer = nn.Sequential(
68
+ nn.Linear(hidden_size * 2, hidden_size),
69
+ nn.ReLU()
70
+ )
71
+ # Classifier with three hidden layers
72
+ self.classifier = nn.Sequential(
73
+ nn.Linear(hidden_size, hidden_size // 2),
74
+ nn.ReLU(),
75
+ nn.Dropout(0.1),
76
+ nn.Linear(hidden_size // 2, hidden_size // 4),
77
+ nn.ReLU(),
78
+ nn.Dropout(0.1),
79
+ nn.Linear(hidden_size // 4, num_labels)
80
+ )
81
+ def forward(self, input_ids1, attention_mask1, input_ids2, attention_mask2):
82
+ # Encode sentences
83
+ outputs1 = self.shared_encoder(input_ids1, attention_mask=attention_mask1)
84
+ outputs2 = self.shared_encoder(input_ids2, attention_mask=attention_mask2)
85
+ # Apply sentence-specific adapters
86
+ embeds1 = self.adapter1(outputs1.last_hidden_state)
87
+ embeds2 = self.adapter2(outputs2.last_hidden_state)
88
+ # Transpose for attention layers
89
+ embeds1 = embeds1.transpose(0, 1)
90
+ embeds2 = embeds2.transpose(0, 1)
91
+ # Cross-attention
92
+ cross_attn_1_to_2, _ = self.cross_attention_1_to_2(embeds1, embeds2, embeds2)
93
+ cross_attn_2_to_1, _ = self.cross_attention_2_to_1(embeds2, embeds1, embeds1)
94
+ # Attention pooling
95
+ pooled_1_to_2 = self.attn_pooling_1_to_2(cross_attn_1_to_2)
96
+ pooled_2_to_1 = self.attn_pooling_2_to_1(cross_attn_2_to_1)
97
+ # Concatenate and project
98
+ combined = torch.cat((pooled_1_to_2, pooled_2_to_1), dim=1)
99
+ projected = self.projection_layer(combined)
100
+ # Classification
101
+ logits = self.classifier(projected)
102
+ return logits
103
+
104
+ # Prediction function
105
+ def embeddings_predict_relevance(sentence1, sentence2, model, tokenizer, device):
106
+ model.eval()
107
+ inputs1 = tokenizer(sentence1, return_tensors="pt", truncation=True, padding="max_length", max_length=1024)
108
+ inputs2 = tokenizer(sentence2, return_tensors="pt", truncation=True, padding="max_length", max_length=1024)
109
+ input_ids1 = inputs1['input_ids'].to(device)
110
+ attention_mask1 = inputs1['attention_mask'].to(device)
111
+ input_ids2 = inputs2['input_ids'].to(device)
112
+ attention_mask2 = inputs2['attention_mask'].to(device)
113
+ with torch.no_grad():
114
+ outputs = model(input_ids1=input_ids1, attention_mask1=attention_mask1,
115
+ input_ids2=input_ids2, attention_mask2=attention_mask2)
116
+ probabilities = torch.softmax(outputs, dim=1)
117
+ predicted_label = torch.argmax(probabilities, dim=1).item()
118
+ return predicted_label, probabilities.cpu().numpy()
119
+
120
+ # Jina model
121
+ JINA_MODEL_NAME = "jinaai/jina-embeddings-v2-small-en"
122
+ jina_tokenizer = AutoTokenizer.from_pretrained(JINA_MODEL_NAME)
123
+ jina_base_model = AutoModel.from_pretrained(JINA_MODEL_NAME)
124
+ jina_model = CrossEncoderWithSharedBase(jina_base_model, num_labels=2)
125
+ jina_model = load_model_safetensors(jina_model, load_path="models/jinaai-jina-embeddings-v2-small-en-TwinEncoder-OffTopic-Classifier-20240915-151858.safetensors")
126
+
127
+ ##########################
128
+ # CROSS-ENCODER
129
+ ##########################
130
+
131
+ # STSB Configs
132
+ STSB_CONTEXT_LEN = 512
133
+
134
+ # ms-macro Configs
135
+ MS_CONTEXT_LEN = 512
136
+
137
+ class CrossEncoderWithMLP(nn.Module):
138
+ def __init__(self, base_model, num_labels=2):
139
+ super(CrossEncoderWithMLP, self).__init__()
140
+
141
+ # Existing cross-encoder model
142
+ self.base_model = base_model
143
+ # Hidden size of the base model
144
+ hidden_size = base_model.config.hidden_size
145
+ # MLP layers after combining the cross-encoders
146
+ self.mlp = nn.Sequential(
147
+ nn.Linear(hidden_size, hidden_size // 2), # Input: a single sentence
148
+ nn.ReLU(),
149
+ nn.Linear(hidden_size // 2, hidden_size // 4), # Reduce the size of the layer
150
+ nn.ReLU()
151
+ )
152
+ # Classifier head
153
+ self.classifier = nn.Linear(hidden_size // 4, num_labels)
154
+
155
+ def forward(self, input_ids, attention_mask):
156
+ # Encode the pair of sentences in one pass
157
+ outputs = self.base_model(input_ids, attention_mask)
158
+ pooled_output = outputs.pooler_output
159
+ # Pass the pooled output through mlp layers
160
+ mlp_output = self.mlp(pooled_output)
161
+ # Pass the final MLP output through the classifier
162
+ logits = self.classifier(mlp_output)
163
+ return logits
164
+
165
+ def cross_encoder_predict_relevance(sentence1, sentence2, model, tokenizer, device):
166
+ model.eval()
167
+ # Tokenize the pair of sentences
168
+ encoding = tokenizer(
169
+ sentence1, sentence2, # Takes in a two sentences as a pair
170
+ return_tensors="pt",
171
+ truncation=True,
172
+ padding="max_length",
173
+ max_length=512,
174
+ return_token_type_ids=False
175
+ )
176
+ # Extract the input_ids and attention mask
177
+ input_ids = encoding["input_ids"].to(device)
178
+ attention_mask = encoding["attention_mask"].to(device)
179
+
180
+ with torch.no_grad():
181
+ outputs = model(
182
+ input_ids=input_ids,
183
+ attention_mask=attention_mask
184
+ ) # Returns logits
185
+ # Convert raw logits into probabilities for each class and get the predicted label
186
+ probabilities = torch.softmax(outputs, dim=1)
187
+ predicted_label = torch.argmax(probabilities, dim=1).item()
188
+ return predicted_label, probabilities.cpu().numpy()
189
+
190
+ # STSB model
191
+ STSB_MODEL_NAME = "cross-encoder/stsb-roberta-base"
192
+ stsb_tokenizer = AutoTokenizer.from_pretrained(STSB_MODEL_NAME)
193
+ stsb_base_model = AutoModel.from_pretrained(STSB_MODEL_NAME)
194
+ stsb_model = CrossEncoderWithMLP(stsb_base_model, num_labels=2)
195
+ stsb_model = load_model_safetensors(stsb_model, load_path="models/cross-encoder-stsb-roberta-base-CrossEncoder-OffTopic-Classifier-20240920-174009.safetensors")
196
+
197
+ # MS model
198
+ MS_MODEL_NAME = "cross-encoder/ms-marco-MiniLM-L-6-v2"
199
+ ms_tokenizer = AutoTokenizer.from_pretrained(MS_MODEL_NAME)
200
+ ms_base_model = AutoModel.from_pretrained(MS_MODEL_NAME)
201
+ ms_model = CrossEncoderWithMLP(ms_base_model, num_labels=2)
202
+ ms_model = load_model_safetensors(ms_model, load_path="models/cross-encoder-ms-marco-MiniLM-L-6-v2-CrossEncoder-OffTopic-Classifier-20240918-090615.safetensors")