Update app.py
Browse files
app.py
CHANGED
@@ -8,10 +8,7 @@ tokenizer = AutoTokenizer.from_pretrained(model_name)
|
|
8 |
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
9 |
model.eval() # Set the model to evaluation mode
|
10 |
|
11 |
-
#
|
12 |
-
THRESHOLD = 0.02 # Adjust as needed based on observations
|
13 |
-
|
14 |
-
# Function to get relevance score and relevant excerpt with bolded tokens
|
15 |
def get_relevance_score_and_excerpt(query, paragraph):
|
16 |
if not query.strip() or not paragraph.strip():
|
17 |
return "Please provide both a query and a document paragraph.", ""
|
@@ -22,36 +19,44 @@ def get_relevance_score_and_excerpt(query, paragraph):
|
|
22 |
with torch.no_grad():
|
23 |
output = model(**inputs, output_attentions=True) # Get attention scores
|
24 |
|
25 |
-
# Extract logits and calculate relevance score
|
26 |
logit = output.logits.squeeze().item()
|
27 |
-
|
|
|
|
|
|
|
28 |
|
29 |
# Extract attention scores (last layer)
|
30 |
attention = output.attentions[-1] # Shape: (batch_size, num_heads, seq_len, seq_len)
|
31 |
-
|
32 |
-
# Average across heads and batch dimension
|
33 |
-
attention_scores = attention.mean(dim=1).mean(dim=0) # Shape: (seq_len, seq_len)
|
34 |
|
35 |
# Tokenize query and paragraph separately
|
36 |
query_tokens = tokenizer.tokenize(query)
|
37 |
paragraph_tokens = tokenizer.tokenize(paragraph)
|
38 |
|
39 |
-
query_len = len(query_tokens) + 2 # +2 for [CLS] and first [SEP]
|
40 |
para_start_idx = query_len
|
41 |
para_end_idx = len(inputs["input_ids"][0]) - 1 # Ignore final [SEP] token
|
42 |
|
43 |
# Handle potential indexing issues
|
44 |
if para_end_idx <= para_start_idx:
|
45 |
-
return round(
|
46 |
|
47 |
-
# Extract paragraph attention scores
|
48 |
para_attention_scores = attention_scores[para_start_idx:para_end_idx, para_start_idx:para_end_idx].mean(dim=0)
|
49 |
|
50 |
if para_attention_scores.numel() == 0:
|
51 |
-
return round(
|
|
|
|
|
|
|
52 |
|
53 |
-
#
|
54 |
-
relevant_indices
|
|
|
|
|
|
|
|
|
55 |
|
56 |
# Reconstruct paragraph with bolded relevant tokens
|
57 |
highlighted_text = ""
|
@@ -61,10 +66,10 @@ def get_relevance_score_and_excerpt(query, paragraph):
|
|
61 |
else:
|
62 |
highlighted_text += f"{token} "
|
63 |
|
64 |
-
# Convert tokens to readable format
|
65 |
highlighted_text = tokenizer.convert_tokens_to_string(highlighted_text.split())
|
66 |
|
67 |
-
return round(
|
68 |
|
69 |
# Define Gradio interface
|
70 |
interface = gr.Interface(
|
@@ -74,11 +79,11 @@ interface = gr.Interface(
|
|
74 |
gr.Textbox(label="Document Paragraph", placeholder="Enter a paragraph to match...")
|
75 |
],
|
76 |
outputs=[
|
77 |
-
gr.Textbox(label="Relevance Score"),
|
78 |
gr.HTML(label="Highlighted Document Paragraph")
|
79 |
],
|
80 |
-
title="Cross-Encoder
|
81 |
-
description="Enter a query and
|
82 |
allow_flagging="never",
|
83 |
live=True
|
84 |
)
|
|
|
8 |
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
9 |
model.eval() # Set the model to evaluation mode
|
10 |
|
11 |
+
# Function to compute relevance score and dynamically adjust threshold
|
|
|
|
|
|
|
12 |
def get_relevance_score_and_excerpt(query, paragraph):
|
13 |
if not query.strip() or not paragraph.strip():
|
14 |
return "Please provide both a query and a document paragraph.", ""
|
|
|
19 |
with torch.no_grad():
|
20 |
output = model(**inputs, output_attentions=True) # Get attention scores
|
21 |
|
22 |
+
# Extract logits and calculate base relevance score
|
23 |
logit = output.logits.squeeze().item()
|
24 |
+
base_relevance_score = torch.sigmoid(torch.tensor(logit)).item()
|
25 |
+
|
26 |
+
# Dynamically adjust the attention threshold based on relevance score
|
27 |
+
dynamic_threshold = max(0.02, base_relevance_score * 0.1) # Example formula
|
28 |
|
29 |
# Extract attention scores (last layer)
|
30 |
attention = output.attentions[-1] # Shape: (batch_size, num_heads, seq_len, seq_len)
|
31 |
+
attention_scores = attention.mean(dim=1).mean(dim=0) # Average over heads and batch
|
|
|
|
|
32 |
|
33 |
# Tokenize query and paragraph separately
|
34 |
query_tokens = tokenizer.tokenize(query)
|
35 |
paragraph_tokens = tokenizer.tokenize(paragraph)
|
36 |
|
37 |
+
query_len = len(query_tokens) + 2 # +2 for special tokens [CLS] and first [SEP]
|
38 |
para_start_idx = query_len
|
39 |
para_end_idx = len(inputs["input_ids"][0]) - 1 # Ignore final [SEP] token
|
40 |
|
41 |
# Handle potential indexing issues
|
42 |
if para_end_idx <= para_start_idx:
|
43 |
+
return round(base_relevance_score, 4), "No relevant tokens extracted."
|
44 |
|
45 |
+
# Extract paragraph attention scores and apply dynamic threshold
|
46 |
para_attention_scores = attention_scores[para_start_idx:para_end_idx, para_start_idx:para_end_idx].mean(dim=0)
|
47 |
|
48 |
if para_attention_scores.numel() == 0:
|
49 |
+
return round(base_relevance_score, 4), "No relevant tokens extracted."
|
50 |
+
|
51 |
+
# Get indices of relevant tokens above dynamic threshold
|
52 |
+
relevant_indices = (para_attention_scores > dynamic_threshold).nonzero(as_tuple=True)[0].tolist()
|
53 |
|
54 |
+
# Compute attention-weighted relevance score
|
55 |
+
if relevant_indices:
|
56 |
+
relevant_attention_values = para_attention_scores[relevant_indices]
|
57 |
+
attention_weighted_score = relevant_attention_values.mean().item() * base_relevance_score
|
58 |
+
else:
|
59 |
+
attention_weighted_score = base_relevance_score # No relevant tokens found
|
60 |
|
61 |
# Reconstruct paragraph with bolded relevant tokens
|
62 |
highlighted_text = ""
|
|
|
66 |
else:
|
67 |
highlighted_text += f"{token} "
|
68 |
|
69 |
+
# Convert tokens back to readable format
|
70 |
highlighted_text = tokenizer.convert_tokens_to_string(highlighted_text.split())
|
71 |
|
72 |
+
return round(attention_weighted_score, 4), highlighted_text
|
73 |
|
74 |
# Define Gradio interface
|
75 |
interface = gr.Interface(
|
|
|
79 |
gr.Textbox(label="Document Paragraph", placeholder="Enter a paragraph to match...")
|
80 |
],
|
81 |
outputs=[
|
82 |
+
gr.Textbox(label="Attention-Weighted Relevance Score"),
|
83 |
gr.HTML(label="Highlighted Document Paragraph")
|
84 |
],
|
85 |
+
title="Cross-Encoder with Dynamic Attention Threshold",
|
86 |
+
description="Enter a query and document paragraph to get a relevance score with relevant tokens in bold.",
|
87 |
allow_flagging="never",
|
88 |
live=True
|
89 |
)
|