Ryan Kim commited on
Commit
850858e
1 Parent(s): 4c8ff7b

updated readme with Milestone 4 breakdown

Browse files
Files changed (1) hide show
  1. README.md +370 -0
README.md CHANGED
@@ -11,6 +11,376 @@ pinned: false
11
 
12
  # cs-gy-6613-project-rk2546
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  ## Milestone 3
15
 
16
  Click the link to access the HuggingFace Streamlit application:
 
11
 
12
  # cs-gy-6613-project-rk2546
13
 
14
+ ## Milestone 4
15
+
16
+ ### **Code Breakdown**
17
+
18
+ The USPTO application is divided into several directories. Overall, the important files are present in the application as such:
19
+
20
+ ````
21
+ - data/
22
+ - train.json
23
+ - val.json
24
+ - src/
25
+ - main.py
26
+ - train.ipynb
27
+ ````
28
+
29
+ Both `train.json` and `val.json` contain the original USPTO data, sized down to contain only the relevant data from each recorded patent and split between training and validation data. The validation data `val.json` is used in the online USPTO application as a set of pre-set patents that a user can select when using the USPTO patent prediction function.
30
+
31
+ The primary code back-end is stored in `main.py`, which runs the application on the HuggingFace space UI. The application uses `Streamlit` to render UI elements on the screen. All models run off of Transformers and Tokenizers from HuggingFace.
32
+
33
+ The application has two features: Sentiment Analysis (for Milestone #2) and USPTO Patent Acceptance Prediction (Milestone #3). Both run on `main.py`. Sentiment Analysis relies on pre-trained [models](https://huggingface.co/models) from HuggingFace's public [datasets](https://huggingface.co/datasets) - particularly 4 models:
34
+
35
+ - [cardiffnlp/twitter-roberta-base-sentiment](https://huggingface.co/cardiffnlp/twitter-roberta-base-sentiment)
36
+ - [finiteautomata/beto-sentiment-analysis](https://huggingface.co/finiteautomata/beto-sentiment-analysis)
37
+ - [bhadresh-savani/distilbert-base-uncased-emotion](https://huggingface.co/bhadresh-savani/distilbert-base-uncased-emotion)
38
+ - [siebert/sentiment-roberta-large-english](https://huggingface.co/siebert/sentiment-roberta-large-english)
39
+
40
+ The Patent Acceptance Prediction uses two fine-tuned models, which are built off of a pre-existing model named [distilbert-base-uncased](https://huggingface.co/distilbert-base-uncased) and fine-tuned off of the USPTO dataset. The tokenizer used to parse text uses the same [distilbert-base-uncased](https://huggingface.co/distilbert-base-uncased) model but is left unmodified.
41
+
42
+ ### **Shared Code**
43
+
44
+ In this section, I describe some code back-end used universally across both the Sentiment Analysis and Patent Accceptance Prediction functions.
45
+
46
+ Starting from `main.py`, we load in the necessary tokenizers and pipelines needed to run the model.
47
+
48
+ ````python
49
+ import streamlit as st
50
+ from transformers import TextClassificationPipeline, pipeline
51
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, DistilBertTokenizerFast, DistilBertForSequenceClassification
52
+ ````
53
+
54
+ These transformers are crucial to the functionality of both Sentiment Analysis and Patent Acceptance Prediction. Particularly, Sentiment Analysis uses `AutoModelForSequenceClassification` as our model class, `AutoTokenizer` as our string pre-processor, and `pipeline` to combine the two. Patent Acceptance Prediction uses `DistilBertForSequenceClassification` as our model class, `DistilBertTokenizerFast` as our string pre-processor, and `TextClassificationPipeline` to combine the two.
55
+
56
+ Because everything runs on one `main.py` page and both the Sentiment Analysis and Patent Acceptance Prediction function similarly, I developed a custom python class called `ModelImplementation` that's used by both and allows for switching between different models:
57
+
58
+ ````python
59
+ class ModelImplementation(object):
60
+ def __init__(
61
+ self,
62
+ transformer_model_name,
63
+ model_transformer,
64
+ tokenizer_model_name,
65
+ tokenizer_func,
66
+ pipeline_func,
67
+ parser_func,
68
+ classifier_args={},
69
+ placeholders=[""]
70
+ ):
71
+ self.transformer_model_name = transformer_model_name
72
+ self.tokenizer_model_name = tokenizer_model_name
73
+ self.placeholders = placeholders
74
+
75
+ self.model = model_transformer.from_pretrained(self.transformer_model_name)
76
+ self.tokenizer = tokenizer_func.from_pretrained(self.tokenizer_model_name)
77
+ self.classifier = pipeline_func(model=self.model, tokenizer=self.tokenizer, padding=True, truncation=True, **classifier_args)
78
+ self.parser = parser_func
79
+
80
+ self.history = []
81
+
82
+ def predict(self, val):
83
+ result = self.classifier(val)
84
+ return self.parser(self, result)
85
+ ````
86
+
87
+ The main idea is that for every model that's needed, we create a new instance of this class. In each case, we can store a reference to the tokenizer, model, and pipeline; the model will then use that tokenizer, model, and pipeline in the `predict()` call. If the output of a model needs to be curated in some way (ex. we need to post-process the output of a model so that it's more human-readable), we can also pass a custom method alongside the other parameters too. This is useful when we are switching between models in the Sentiment Analysis page or between the Sentiment Analysis and Patent Acceptance Prediction page - we merely have to create or modify an instance of the `ModelImplementation` class with the proper tokenizer, model, pipeline, and post-process method (if needed). Placeholder text for any inputs can also be stored as well in an array.
88
+
89
+ The Sentiment Analysis and Patent Acceptance Prediction pages are both stored on one interface, with a sidebar menu allowing a user to switch between the two. The page has a simple title, subtitle, and sidebar implementation through `Streamlit`:
90
+
91
+ ````python
92
+ # Title
93
+ st.title("CSGY-6613 Project")
94
+ # Subtitle
95
+ st.markdown("_**Ryan Kim (rk2546)**_")
96
+ st.markdown("---")
97
+
98
+ def PageToHome():
99
+ st.session_state.page = "home"
100
+ def PageToEmotion():
101
+ st.session_state.page = "emotion"
102
+ def PageToPatent():
103
+ st.session_state.page = "patent"
104
+
105
+ with st.sidebar:
106
+ st.subheader("Toolbox")
107
+ home_selected = st.button("Home", on_click=PageToHome)
108
+ emotion_selected = st.button(
109
+ "Emotion Analysis [Milestone #2]",
110
+ on_click=PageToEmotion
111
+ )
112
+ patent_selected = st.button(
113
+ "Patent Prediction [Milestone #3]",
114
+ on_click=PageToPatent
115
+ )
116
+ ````
117
+
118
+ We store the current page of the user inside an `st.session_state` dictionary, which persists every time the page loads or changes. Because `Streamlit` will only re-render the page every time a change is made to the interface - this means that variables not stored in a session will be re-set. Alongside the current page, we also store models and user inputs inside of the session as well, which allows them to persist between `Streamlit` re-renderings.
119
+
120
+ Whenever we switch between pages via the sidebar, a simple `if-else` statement ensure that the proper page is loaded:
121
+
122
+ ````python
123
+ if st.session_state.page == "emotion":
124
+ st.subheader("Sentiment Analysis")
125
+ if "emotion_model" not in st.session_state:
126
+ st.write("Loading model...")
127
+ else:
128
+ // ...
129
+
130
+ elif st.session_state.page == "patent":
131
+ st.subheader("USPTO Patent Evaluation")
132
+ // ...
133
+ ````
134
+
135
+ #### **Sentiment Analysis**
136
+
137
+ Sentiment Analysis is relatively simple. It uses the `ModelImplementation` class detailed above to switch between four pre-existing HuggingFace models for the sentiment analysis:
138
+
139
+ - [cardiffnlp/twitter-roberta-base-sentiment](https://huggingface.co/cardiffnlp/twitter-roberta-base-sentiment)
140
+ - [finiteautomata/beto-sentiment-analysis](https://huggingface.co/finiteautomata/beto-sentiment-analysis)
141
+ - [bhadresh-savani/distilbert-base-uncased-emotion](https://huggingface.co/bhadresh-savani/distilbert-base-uncased-emotion)
142
+ - [siebert/sentiment-roberta-large-english](https://huggingface.co/siebert/sentiment-roberta-large-english)
143
+
144
+ A method called `ParseEmotionOutput()` is used to process labels outputted by the [cardiffnlp/twitter-roberta-base-sentiment](https://huggingface.co/cardiffnlp/twitter-roberta-base-sentiment) model in particular.
145
+
146
+ Upon loading, if a model hasn't been instantiated yet, the page will create a new model with a pre-set model name and cache it for later use:
147
+
148
+ ````python
149
+ def emotion_model_change():
150
+ st.session_state.emotion_model = ModelImplementation(
151
+ st.session_state.emotion_model_name,
152
+ AutoModelForSequenceClassification,
153
+ st.session_state.emotion_model_name,
154
+ AutoTokenizer,
155
+ pipeline,
156
+ ParseEmotionOutput,
157
+ classifier_args={ "task" : "sentiment-analysis" },
158
+ placeholders=["@AmericanAir just landed - 3hours Late Flight - and now we need to wait TWENTY MORE MINUTES for a gate! I have patience but none for incompetence."]
159
+ )
160
+
161
+ if "emotion_model_name" not in st.session_state:
162
+ st.session_state.emotion_model_name = "cardiffnlp/twitter-roberta-base-sentiment"
163
+ emotion_model_change()
164
+ ````
165
+
166
+ The method `emotion_model_change()` can be called to switch between different models, based on the session-saved `emotion_model_name` value. By default, the [cardiffnlp/twitter-roberta-base-sentiment](https://huggingface.co/cardiffnlp/twitter-roberta-base-sentiment) model is used. To switch between models, we use a `Streamlit` `selectbox` module:
167
+
168
+ ````python
169
+ model_option = st.selectbox(
170
+ "What sentiment analysis model do you want to use? NOTE: Lag may occur when loading a new model!",
171
+ emotion_model_names,
172
+ on_change=emotion_model_change,
173
+ key="emotion_model_name"
174
+ )
175
+
176
+ form = st.form(key='sentiment-analysis-form')
177
+ text_input = form.text_area(
178
+ "Enter some text for sentiment analysis! If you just want to test it out without entering anything, just press the \"Submit\" button and the model will look at the placeholder.",
179
+ placeholder=st.session_state.emotion_model.placeholders[0]
180
+ )
181
+ submit = form.form_submit_button('Submit')
182
+ ````
183
+
184
+ When the page loads, a placeholder from the current model is printed inside a `Streamlit` `text_area` module. When the user clicks on the `form_submit_button` button, the app will use whatever model is currently cached to generate output predictions. If no user input was provided, the placeholder value is passed as the input instead.
185
+
186
+ ````python
187
+ if submit:
188
+ if text_input is None or len(text_input.strip()) == 0:
189
+ to_eval = st.session_state.emotion_model.placeholders[0]
190
+ else:
191
+ to_eval = text_input.strip()
192
+ st.write("You entered:")
193
+ st.markdown("> {}".format(to_eval))
194
+ st.write("Using the NLP model:")
195
+ st.markdown("> {}".format(st.session_state.emotion_model_name))
196
+ label, score = st.session_state.emotion_model.predict(to_eval)
197
+ st.markdown("#### Result:")
198
+ st.markdown("**{}**: {}".format(label,score))
199
+ ````
200
+
201
+ #### **USPTO Patent Acceptance Prediction**
202
+
203
+ The back-end for the USPTO Patent Acceptance Prediction is similar to that of **Sentiment Analysis**, but with some major differences.
204
+
205
+ Instead of switching between for pre-trained HuggingFace models, we use two fine-tuned models. These models are available online:
206
+
207
+ - [rk2546/uspto-patents-abstracts](https://huggingface.co/rk2546/uspto-patents-abstracts)
208
+ - [rk2546/uspto-patents-claims](https://huggingface.co/rk2546/uspto-patents-claims)
209
+
210
+ and are built off of a pre-existing model named [distilbert-base-uncased](https://huggingface.co/distilbert-base-uncased). They are fine-tuned off of the USPTO dataset. The tokenizer used to parse text uses the same [distilbert-base-uncased](https://huggingface.co/distilbert-base-uncased) model but is left unmodified.
211
+
212
+ ````python
213
+ if "patent_data" not in st.session_state:
214
+ f = open('./data/val.json')
215
+ valData = json.load(f)
216
+ f.close()
217
+
218
+ patent_data = {}
219
+ for num, label, abstract, claim in zip(valData["patent_numbers"],valData["labels"], valData["abstracts"], valData["claims"]):
220
+ patent_data[num] = {"patent_number":num,"label":label,"abstract":abstract,"claim":claim}
221
+
222
+ st.session_state.patent_data = patent_data
223
+ st.session_state.patent_num = list(patent_data.keys())[0]
224
+ st.session_state.weight = 0.5
225
+ st.session_state.patent_abstract_model = ModelImplementation(
226
+ 'rk2546/uspto-patents-abstracts',
227
+ DistilBertForSequenceClassification,
228
+ 'distilbert-base-uncased',
229
+ DistilBertTokenizerFast,
230
+ TextClassificationPipeline,
231
+ ParsePatentOutput,
232
+ classifier_args={"return_all_scores":True},
233
+ )
234
+ print("Patent abstracts model initialized")
235
+ st.session_state.patent_claim_model = ModelImplementation(
236
+ 'rk2546/uspto-patents-claims',
237
+ DistilBertForSequenceClassification,
238
+ 'distilbert-base-uncased',
239
+ DistilBertTokenizerFast,
240
+ TextClassificationPipeline,
241
+ ParsePatentOutput,
242
+ classifier_args={"return_all_scores":True},
243
+ )
244
+ print("Patent claims model initialized")
245
+ ````
246
+
247
+ In addition, instead of the user selecting a particular model to use, instead the interface allows for two separate inputs - one for an Abstract draft and another for a Claims draft. These fields can be pre-populated using an `st.selectbox` that, when selected, pre-fills the two inputs with examples from `val.json`:
248
+
249
+ ````python
250
+ patent_select_list = list(st.session_state.patent_data.keys())
251
+ patent_index_option = st.selectbox(
252
+ "Want to pre-populate with an existing patent? Select the index number of below.",
253
+ patent_select_list,
254
+ key="patent_num",
255
+ )
256
+
257
+ //...
258
+
259
+ with st.form(key='patent-form'):
260
+ col1, col2 = st.columns(2)
261
+ with col1:
262
+ abstract_input = st.text_area(
263
+ "Enter the abstract of the patent below",
264
+ placeholder=st.session_state.patent_data[st.session_state.patent_num]["abstract"],
265
+ height=400
266
+ )
267
+ with col2:
268
+ claim_input = st.text_area(
269
+ "Enter the claims of the patent below",
270
+ placeholder=st.session_state.patent_data[st.session_state.patent_num]["claim"],
271
+ height=400
272
+ )
273
+ weight_val = st.slider(
274
+ "How much do the abstract and claims weight when aggregating a total softmax score?",
275
+ min_value=-1.0,
276
+ max_value=1.0,
277
+ value=0.5,
278
+ )
279
+ submit = st.form_submit_button('Submit')
280
+ ````
281
+
282
+ One unique addition is a slider `st.slider` that lets the user tune how much the two models' softmax outputs are combined. This way, some customizability is allowed - if the user wants only an Abstract to be used, then the weight can be adjusted to bias the Abstract model's output completely.
283
+
284
+ ### **Training the USPTO Patent Acceptance Predictor**
285
+
286
+ While the Sentiment Analysis function does not need to be trained, the model for the patent prediction needs to be fine-tuned from an existing model. The scripts that do so are available in both `src/train.py` and `src/patent_train.ipynb`, with the latter being a more user-readable option. **NOTE:** the `src/train.py` implementation is a tad outdated. Please rely on `src/patent_train.ipynb` if you want to try for yourself.
287
+
288
+ The general idea was to divide the training into steps:
289
+
290
+ 1. Parse only the necessary data out from the raw USPTO data,
291
+ 2. Separate the data into training and validation data
292
+ 3. Fine-tune an existing HuggingFace model into two separate models, each of which separately perform predictions onto abstracts and claims respectively.
293
+ 4. Publish the two models onto HuggingFace to make the models easily accessible.
294
+
295
+ The only data columns parsed from the original USPTO data were:
296
+ - "patent_number" <- Unique identifier
297
+ - "abstract" <- Input #1
298
+ - "claims" <- Input #2
299
+ - "decision" <- Output Labels
300
+
301
+ We also filter rows such that the values in the "decision" column only consist of "ACCEPTED" or "REJECTED"; these values are then coded into `1` and `0` respectively for easier data processing. Beyond splitting the data into training and validation data, we also split each into two sub-datasets - one consisting of Abstracts, and another for Claims. No pre-processing was performed further.
302
+
303
+ During fine-tuning, we use a custom class that will be used by HuggingFace's various transformers:
304
+
305
+ ````python
306
+ class USPTODataset(Dataset):
307
+ def __init__(self, encodings, labels):
308
+ self.encodings = encodings
309
+ self.labels = labels
310
+ def __getitem__(self, idx):
311
+ item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
312
+ item['labels'] = torch.tensor(self.labels[idx])
313
+ return item
314
+ def __len__(self):
315
+ return len(self.labels)
316
+ ````
317
+
318
+ The training data is fitted into an instance of this class, and that instance is fed into the training algorithm. First, all input strings are tokenized. The tokenized data is then fed into instances of `USPTODataset`.
319
+
320
+ ````python
321
+ train_abstracts_encodings = tokenizer(trainData["abstracts"], truncation=True, padding=True)
322
+ train_claims_encodings = tokenizer(trainData["claims"], truncation=True, padding=True)
323
+
324
+ train_abstracts_dataset = USPTODataset(train_abstracts_encodings, trainData["labels"])
325
+ train_claims_dataset = USPTODataset(train_claims_encodings, trainData["labels"])
326
+ ````
327
+
328
+ When initializing the model that we'll fine-tune, we also add an additional step to run the training on the GPU rather than the CPU. This is a time optimization measure.
329
+
330
+ ````python
331
+ device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
332
+ model = DistilBertForSequenceClassification.from_pretrained(model_name)
333
+ model.to(device)
334
+ model.train()
335
+ ````
336
+
337
+ Finally, we load the datasets into wrapper classes that are used during the training. We then train for `10` epochs.
338
+
339
+ ````python
340
+ train_abstracts_loader = DataLoader(train_abstracts_dataset, batch_size=32, shuffle=True)
341
+ train_claims_loader = DataLoader(train_claims_dataset, batch_size=32, shuffle=True)
342
+ optim = AdamW(model.parameters(), lr=5e-5)
343
+
344
+ def Train(loader, save_path, num_train_epochs=2):
345
+ batch_num = len(loader)
346
+ for epoch in range(num_train_epochs):
347
+ print(f'\t- Training epoch {epoch+1}/{num_train_epochs}')
348
+ batch_count = 0
349
+ for batch in loader:
350
+ print(f'{batch_count}|{batch_num} - {round((batch_count/batch_num)*100)}%', end="")
351
+ #print('\t\t- optim zero grad')
352
+ optim.zero_grad()
353
+ #print('\t\t- input_ids')
354
+ input_ids = batch['input_ids'].to(device)
355
+ #print('\t\t- attention_mask')
356
+ attention_mask = batch['attention_mask'].to(device)
357
+ #print('\t\t- labels0')
358
+ labels = batch['labels'].to(device)
359
+ #print('\t\t- outputs')
360
+ outputs = model(input_ids, attention_mask=attention_mask, labels=labels)
361
+
362
+ #print('\t\t- loss')
363
+ loss = outputs[0]
364
+ #print('\t\t- backwards')
365
+ loss.backward()
366
+ #print('\t\t- step')
367
+ optim.step()
368
+
369
+ batch_count += 1
370
+ print("\r", end="")
371
+
372
+ model.save_pretrained(save_path, from_pt=True)
373
+ print(f'Saved model in {save_path}!\n')
374
+
375
+ print("=== TRAINING ABSTRACTS ===")
376
+ Train(train_abstracts_loader,upsto_abstracts_model_path, num_train_epochs=10)
377
+ print("----")
378
+ print("=== TRAINING CLAIMS ===")
379
+ Train(train_claims_loader,upsto_claims_model_path, num_train_epochs=10)
380
+ ````
381
+
382
+ ---
383
+
384
  ## Milestone 3
385
 
386
  Click the link to access the HuggingFace Streamlit application: