shoukaku commited on
Commit
f2abd03
·
1 Parent(s): ee7d166

initial commit

Browse files
.gitignore ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/
161
+
162
+ # Checkpoints
163
+ src/ckpt/*.pt
app.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable
2
+ import gradio as gr
3
+
4
+ if gr.NO_RELOAD:
5
+ import numpy as np
6
+ from src.distilbert_tf import DistilBertTransferLearningModel
7
+
8
+
9
+ DEVICE = 'cpu'
10
+ MODELS = [
11
+ (
12
+ 'distilbert-1linear-1650',
13
+ lambda: DistilBertTransferLearningModel(
14
+ 'distilbert-base-uncased',
15
+ [
16
+ ('linear', ['in', 'out']),
17
+ ('softmax'),
18
+ ],
19
+ 2,
20
+ device=DEVICE,
21
+ state_dict='src/ckpt/distilbert-1linear-dataset-all-augmented-all-1650.pt',
22
+ ),
23
+ ),
24
+ ]
25
+
26
+
27
+ class WebUI:
28
+
29
+ def __init__(self, models: list[(str, Callable)] = [], device: str = 'cpu') -> None:
30
+ self.models = models
31
+ self.device = device
32
+ self.model = self.models[0][1]()
33
+
34
+ def _change_model(self, idx: int) -> None:
35
+ if gr.NO_RELOAD:
36
+ try:
37
+ print(self.models[idx])
38
+ del self.model
39
+ self.model = self.models[idx][1]()
40
+ print('done loading')
41
+ except Exception as e:
42
+ print(e)
43
+ gr.Error(e)
44
+
45
+ def _predict(self, text: str) -> str:
46
+ print(text)
47
+ output = self.model.predict(text, self.device).detach().cpu().numpy()[0]
48
+ return f'Fake: {output[0]}, Real: {output[1]}'
49
+
50
+ def get_ui(self) -> None:
51
+ with gr.Blocks() as ui:
52
+ with gr.Row():
53
+ with gr.Column():
54
+ t_inp = gr.Textbox(label='Input')
55
+ with gr.Row():
56
+ btn_reset = gr.ClearButton(
57
+ value='Reset',
58
+ components=[
59
+ t_inp,
60
+ ],
61
+ )
62
+ btn_submit = gr.Button(value='Submit', variant='primary')
63
+ with gr.Column():
64
+ ddl_model = gr.Dropdown(
65
+ label='Model',
66
+ choices=[model[0] for model in self.models],
67
+ value=self.models[0][0],
68
+ type='index',
69
+ interactive=True,
70
+ filterable=True,
71
+ )
72
+ t_out = gr.Textbox(label='Output')
73
+ ddl_model.change(fn=self._change_model, inputs=ddl_model)
74
+ btn_submit.click(fn=self._predict, inputs=t_inp, outputs=t_out)
75
+ return ui
76
+
77
+
78
+ webui = WebUI(models=MODELS, device=DEVICE).get_ui()
79
+
80
+ if __name__ == '__main__':
81
+ webui.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ numpy==1.26.4
2
+ torch==2.2.1
3
+ transformers==4.39.3
src/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .distilbert_tf import DistilBertTransferLearningModel
src/ckpt/checkpoint_here.txt ADDED
File without changes
src/distilbert_tf.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Optional, Tuple, Union
2
+ import torch
3
+ import transformers
4
+
5
+
6
+ class DistilBertTransferLearningModel(torch.nn.Module):
7
+
8
+ def __init__(
9
+ self,
10
+ pretrained_model: str = "distilbert-base-uncased",
11
+ layers: list[Tuple[str, Optional[list[Any]]]] = [
12
+ ('linear', ['in', 'out']),
13
+ ('softmax'),
14
+ ],
15
+ dim_out: int = 2,
16
+ use_local_file: bool = False,
17
+ device: str = 'cpu',
18
+ state_dict: Optional[Union[str, dict]] = None,
19
+ ):
20
+ super(DistilBertTransferLearningModel, self).__init__()
21
+ self.tokenizer = transformers.AutoTokenizer.from_pretrained(
22
+ pretrained_model, local_files_only=use_local_file
23
+ )
24
+ self.base_model = transformers.AutoModel.from_pretrained(
25
+ pretrained_model, local_files_only=use_local_file
26
+ )
27
+ clf_layers = []
28
+ for layer in layers:
29
+ layer_type = layer[0] if isinstance(layer, tuple) else layer
30
+ if layer_type == 'linear':
31
+ layer_in, layer_out = [
32
+ (
33
+ self.base_model.config.hidden_size
34
+ if x == 'in'
35
+ else dim_out if x == 'out' else x
36
+ )
37
+ for x in layer[1]
38
+ ]
39
+ clf_layers.append(torch.nn.Linear(layer_in, layer_out))
40
+ elif layer_type == 'softmax':
41
+ clf_layers.append(torch.nn.Softmax(dim=-1))
42
+ self.clf = torch.nn.Sequential(*clf_layers)
43
+
44
+ if state_dict is not None:
45
+ if isinstance(state_dict, str) and state_dict.endswith('.pt'):
46
+ if device == 'cpu':
47
+ state_dict = torch.load(state_dict, map_location='cpu')
48
+ else:
49
+ state_dict = torch.load(state_dict)
50
+ self.load_state_dict(state_dict)
51
+
52
+ def forward(self, ids: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
53
+ y = self.base_model(ids, attention_mask=mask, return_dict=False)[0][:, 0]
54
+ y = self.clf(y)
55
+ return y
56
+
57
+ def predict(self, text: str, device: str) -> torch.Tensor:
58
+ encoded = self.tokenizer.encode_plus(
59
+ text,
60
+ add_special_tokens=True,
61
+ return_token_type_ids=False,
62
+ return_attention_mask=True,
63
+ max_length=512,
64
+ padding='max_length',
65
+ truncation=True,
66
+ return_tensors='pt',
67
+ )
68
+ with torch.no_grad():
69
+ ids = encoded['input_ids'].to(device)
70
+ mask = encoded['attention_mask'].to(device)
71
+ output = self.forward(ids, mask)
72
+ return output.to(device)