AhmedSSabir commited on
Commit
37b9ac3
1 Parent(s): 41816f7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -7
app.py CHANGED
@@ -8,23 +8,88 @@ import os
8
  import gradio as gr
9
  import requests
10
 
11
- url = "https://github.com/simonepri/lm-scorer/tree/master/lm_scorer/models"
12
- resp = requests.get(url)
13
 
14
 
15
  #from sentence_transformers import SentenceTransformer, util
16
  #from sklearn.metrics.pairwise import cosine_similarity
17
- from lm_scorer.models.auto import AutoLMScorer as LMScorer
18
  #from sentence_transformers import SentenceTransformer, util
19
- from sklearn.metrics.pairwise import cosine_similarity
20
 
21
  device = "cuda:0" if torch.cuda.is_available() else "cpu"
22
  model = gr.interface.huggingface.load('sentence-transformers/stsb-distilbert-base')
23
 
24
  #SentenceTransformer('stsb-distilbert-base', device=device)
25
 
26
- batch_size = 1
27
- scorer = LMScorer.from_pretrained('gpt2' , device=device, batch_size=batch_size)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
 
30
  def cos_sim(a, b):
@@ -45,7 +110,8 @@ def Visual_re_ranker(caption, visual_context_label, visual_context_prob):
45
  sim = str(sim)[1:-1]
46
  sim = str(sim)[1:-1]
47
 
48
- LM = scorer.sentence_score(caption, reduce="mean")
 
49
  score = pow(float(LM),pow((1-float(sim))/(1+ float(sim)),1-float(visual_context_prob)))
50
 
51
 
 
8
  import gradio as gr
9
  import requests
10
 
11
+ #url = "https://github.com/simonepri/lm-scorer/tree/master/lm_scorer/models"
12
+ #resp = requests.get(url)
13
 
14
 
15
  #from sentence_transformers import SentenceTransformer, util
16
  #from sklearn.metrics.pairwise import cosine_similarity
17
+ #from lm_scorer.models.auto import AutoLMScorer as LMScorer
18
  #from sentence_transformers import SentenceTransformer, util
19
+ #from sklearn.metrics.pairwise import cosine_similarity
20
 
21
  device = "cuda:0" if torch.cuda.is_available() else "cpu"
22
  model = gr.interface.huggingface.load('sentence-transformers/stsb-distilbert-base')
23
 
24
  #SentenceTransformer('stsb-distilbert-base', device=device)
25
 
26
+ #batch_size = 1
27
+ #scorer = LMScorer.from_pretrained('gpt2' , device=device, batch_size=batch_size)
28
+
29
+ import torch
30
+ from transformers import GPT2Tokenizer, GPT2LMHeadModel
31
+ import NumPy as np
32
+ import re
33
+
34
+ def Sort_Tuple(tup):
35
+
36
+ # (Sorts in descending order)
37
+ tup.sort(key = lambda x: x[1])
38
+ return tup[::-1]
39
+
40
+
41
+ def softmax(x):
42
+ exps = np.exp(x)
43
+ return np.divide(exps, np.sum(exps))
44
+
45
+ # Load pre-trained model
46
+ model = GPT2LMHeadModel.from_pretrained('distilgpt2', output_hidden_states = True, output_attentions = True)
47
+ model.eval()
48
+ tokenizer = GPT2Tokenizer.from_pretrained('distilgpt2')
49
+
50
+
51
+ def cloze_prob(text):
52
+
53
+ whole_text_encoding = tokenizer.encode(text)
54
+ # Parse out the stem of the whole sentence (i.e., the part leading up to but not including the critical word)
55
+ text_list = text.split()
56
+ stem = ' '.join(text_list[:-1])
57
+ stem_encoding = tokenizer.encode(stem)
58
+ # cw_encoding is just the difference between whole_text_encoding and stem_encoding
59
+ # note: this might not correspond exactly to the word itself
60
+ cw_encoding = whole_text_encoding[len(stem_encoding):]
61
+ # 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.
62
+ # Put the whole text encoding into a tensor, and get the model's comprehensive output
63
+ tokens_tensor = torch.tensor([whole_text_encoding])
64
+
65
+ with torch.no_grad():
66
+ outputs = model(tokens_tensor)
67
+ predictions = outputs[0]
68
+
69
+ logprobs = []
70
+ # start at the stem and get downstream probabilities incrementally from the model(see above)
71
+ start = -1-len(cw_encoding)
72
+ for j in range(start,-1,1):
73
+ raw_output = []
74
+ for i in predictions[-1][j]:
75
+ raw_output.append(i.item())
76
+
77
+ logprobs.append(np.log(softmax(raw_output)))
78
+
79
+ # if the critical word is three tokens long, the raw_probabilities should look something like this:
80
+ # [ [0.412, 0.001, ... ] ,[0.213, 0.004, ...], [0.002,0.001, 0.93 ...]]
81
+ # Then for the i'th token we want to find its associated probability
82
+ # this is just: raw_probabilities[i][token_index]
83
+ conditional_probs = []
84
+ for cw,prob in zip(cw_encoding,logprobs):
85
+ conditional_probs.append(prob[cw])
86
+ # now that you have all the relevant probabilities, return their product.
87
+ # This is the probability of the critical word given the context before it.
88
+
89
+ return np.exp(np.sum(conditional_probs))
90
+
91
+
92
+
93
 
94
 
95
  def cos_sim(a, b):
 
110
  sim = str(sim)[1:-1]
111
  sim = str(sim)[1:-1]
112
 
113
+ LM = cloze_prob(caption)
114
+ #LM = scorer.sentence_score(caption, reduce="mean")
115
  score = pow(float(LM),pow((1-float(sim))/(1+ float(sim)),1-float(visual_context_prob)))
116
 
117