AhmedSSabir commited on
Commit
59c43da
1 Parent(s): 0c726aa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -43
app.py CHANGED
@@ -7,6 +7,17 @@ import re
7
  import os
8
  import gradio as gr
9
  import requests
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  from sentence_transformers import SentenceTransformer, util
12
  #url = "https://github.com/simonepri/lm-scorer/tree/master/lm_scorer/models"
@@ -47,16 +58,16 @@ import re
47
 
48
 
49
 
50
- def Sort_Tuple(tup):
51
 
52
- # (Sorts in descending order)
53
- tup.sort(key = lambda x: x[1])
54
- return tup[::-1]
55
 
56
 
57
- def softmax(x):
58
- exps = np.exp(x)
59
- return np.divide(exps, np.sum(exps))
60
 
61
 
62
  def get_sim(x):
@@ -68,7 +79,7 @@ def get_sim(x):
68
  # Load pre-trained model
69
 
70
  #model = GPT2LMHeadModel.from_pretrained('distilgpt2', output_hidden_states = True, output_attentions = True)
71
- model = GPT2LMHeadModel.from_pretrained('gpt2', output_hidden_states = True, output_attentions = True)
72
  #model = gr.Interface.load('huggingface/distilgpt2', output_hidden_states = True, output_attentions = True)
73
 
74
  #model.eval()
@@ -90,46 +101,77 @@ tokenizer = GPT2TokenizerFast.from_pretrained(model_name)
90
 
91
 
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
- def cloze_prob(text):
95
 
96
- whole_text_encoding = tokenizer.encode(text)
97
- # Parse out the stem of the whole sentence (i.e., the part leading up to but not including the critical word)
98
- text_list = text.split()
99
- stem = ' '.join(text_list[:-1])
100
- stem_encoding = tokenizer.encode(stem)
101
- # cw_encoding is just the difference between whole_text_encoding and stem_encoding
102
- # note: this might not correspond exactly to the word itself
103
- cw_encoding = whole_text_encoding[len(stem_encoding):]
104
- # Run the entire sentence through the model. Then go "back in time" to look at what the model predicted for each token, starting at the stem.
105
- # Put the whole text encoding into a tensor, and get the model's comprehensive output
106
- tokens_tensor = torch.tensor([whole_text_encoding])
107
 
108
- with torch.no_grad():
109
- outputs = model(tokens_tensor)
110
- predictions = outputs[0]
111
-
112
- logprobs = []
113
- # start at the stem and get downstream probabilities incrementally from the model(see above)
114
- start = -1-len(cw_encoding)
115
- for j in range(start,-1,1):
116
- raw_output = []
117
- for i in predictions[-1][j]:
118
- raw_output.append(i.item())
119
 
120
- logprobs.append(np.log(softmax(raw_output)))
121
 
122
- # if the critical word is three tokens long, the raw_probabilities should look something like this:
123
- # [ [0.412, 0.001, ... ] ,[0.213, 0.004, ...], [0.002,0.001, 0.93 ...]]
124
- # Then for the i'th token we want to find its associated probability
125
- # this is just: raw_probabilities[i][token_index]
126
- conditional_probs = []
127
- for cw,prob in zip(cw_encoding,logprobs):
128
- conditional_probs.append(prob[cw])
129
- # now that you have all the relevant probabilities, return their product.
130
- # This is the probability of the critical word given the context before it.
131
-
132
- return np.exp(np.sum(conditional_probs))
133
 
134
 
135
 
 
7
  import os
8
  import gradio as gr
9
  import requests
10
+ from doctest import OutputChecker
11
+ import sys
12
+ import torch
13
+ import re
14
+ import os
15
+ import gradio as gr
16
+ import requests
17
+ import torch
18
+ from transformers import GPT2Tokenizer, GPT2LMHeadModel
19
+ from torch.nn.functional import softmax
20
+ import numpy as np
21
 
22
  from sentence_transformers import SentenceTransformer, util
23
  #url = "https://github.com/simonepri/lm-scorer/tree/master/lm_scorer/models"
 
58
 
59
 
60
 
61
+ # def Sort_Tuple(tup):
62
 
63
+ # # (Sorts in descending order)
64
+ # tup.sort(key = lambda x: x[1])
65
+ # return tup[::-1]
66
 
67
 
68
+ # def softmax(x):
69
+ # exps = np.exp(x)
70
+ # return np.divide(exps, np.sum(exps))
71
 
72
 
73
  def get_sim(x):
 
79
  # Load pre-trained model
80
 
81
  #model = GPT2LMHeadModel.from_pretrained('distilgpt2', output_hidden_states = True, output_attentions = True)
82
+ #model = GPT2LMHeadModel.from_pretrained('gpt2', output_hidden_states = True, output_attentions = True)
83
  #model = gr.Interface.load('huggingface/distilgpt2', output_hidden_states = True, output_attentions = True)
84
 
85
  #model.eval()
 
101
 
102
 
103
 
104
+ # tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
105
+ # model = GPT2LMHeadModel.from_pretrained('gpt2')
106
+
107
+
108
+
109
+ def sentence_prob_mean(text):
110
+ # Tokenize the input text and add special tokens
111
+ input_ids = tokenizer.encode(text, return_tensors='pt')
112
+
113
+ # Obtain model outputs
114
+ with torch.no_grad():
115
+ outputs = model(input_ids, labels=input_ids)
116
+ logits = outputs.logits # logits are the model outputs before applying softmax
117
+
118
+ # Shift logits and labels so that tokens are aligned:
119
+ shift_logits = logits[..., :-1, :].contiguous()
120
+ shift_labels = input_ids[..., 1:].contiguous()
121
+
122
+ # Calculate the softmax probabilities
123
+ probs = softmax(shift_logits, dim=-1)
124
+
125
+ # Gather the probabilities of the actual token IDs
126
+ gathered_probs = torch.gather(probs, 2, shift_labels.unsqueeze(-1)).squeeze(-1)
127
+
128
+ # Compute the mean probability across the tokens
129
+ mean_prob = torch.mean(gathered_probs).item()
130
+
131
+ return mean_prob
132
+
133
+
134
+
135
 
136
+ # def cloze_prob(text):
137
 
138
+ # whole_text_encoding = tokenizer.encode(text)
139
+ # # Parse out the stem of the whole sentence (i.e., the part leading up to but not including the critical word)
140
+ # text_list = text.split()
141
+ # stem = ' '.join(text_list[:-1])
142
+ # stem_encoding = tokenizer.encode(stem)
143
+ # # cw_encoding is just the difference between whole_text_encoding and stem_encoding
144
+ # # note: this might not correspond exactly to the word itself
145
+ # cw_encoding = whole_text_encoding[len(stem_encoding):]
146
+ # # Run the entire sentence through the model. Then go "back in time" to look at what the model predicted for each token, starting at the stem.
147
+ # # Put the whole text encoding into a tensor, and get the model's comprehensive output
148
+ # tokens_tensor = torch.tensor([whole_text_encoding])
149
 
150
+ # with torch.no_grad():
151
+ # outputs = model(tokens_tensor)
152
+ # predictions = outputs[0]
153
+
154
+ # logprobs = []
155
+ # # start at the stem and get downstream probabilities incrementally from the model(see above)
156
+ # start = -1-len(cw_encoding)
157
+ # for j in range(start,-1,1):
158
+ # raw_output = []
159
+ # for i in predictions[-1][j]:
160
+ # raw_output.append(i.item())
161
 
162
+ # logprobs.append(np.log(softmax(raw_output)))
163
 
164
+ # # if the critical word is three tokens long, the raw_probabilities should look something like this:
165
+ # # [ [0.412, 0.001, ... ] ,[0.213, 0.004, ...], [0.002,0.001, 0.93 ...]]
166
+ # # Then for the i'th token we want to find its associated probability
167
+ # # this is just: raw_probabilities[i][token_index]
168
+ # conditional_probs = []
169
+ # for cw,prob in zip(cw_encoding,logprobs):
170
+ # conditional_probs.append(prob[cw])
171
+ # # now that you have all the relevant probabilities, return their product.
172
+ # # This is the probability of the critical word given the context before it.
173
+
174
+ # return np.exp(np.sum(conditional_probs))
175
 
176
 
177