Views
No views yet
answerdotai/ModernBERT-base. The model is designed to perform target identification by finding the most relevant theses along with their associated data for a given claimtop_k, num_args & top_level_only variables to adjust the output of the model.transformers library. The following code demonstrates how to make a prediction:1import torch
2import torch.nn as nn
3
4from transformers import AutoModel, AutoTokenizer
5from huggingface_hub import hf_hub_download, PyTorchModelHubMixin
6
7import pickle
8from sklearn.metrics.pairwise import cosine_similarity
9import numpy as np
10
11class DualEncoderThesisModel(nn.Module, PyTorchModelHubMixin):
12 def __init__(self) -> None:
13 super(DualEncoderThesisModel, self).__init__()
14 self.encoder = AutoModel.from_pretrained("answerdotai/ModernBERT-base")
15
16 def forward(self, input_ids_a, attention_mask_a, input_ids_b, attention_mask_b):
17 # Encode arguments
18 output_a = self.encoder(input_ids=input_ids_a, attention_mask=attention_mask_a).last_hidden_state
19 emb_a = output_a[:, 0]
20
21 # Encode theses
22 output_b = self.encoder(input_ids=input_ids_b, attention_mask=attention_mask_b).last_hidden_state
23 emb_b = output_b[:, 0]
24
25 return emb_a, emb_b
26
27model_name = "ag-charalampous/target-identification"
28tokenizer = AutoTokenizer.from_pretrained(model_name)
29
30model = DualEncoderThesisModel.from_pretrained(model_name)
31model.eval()
32
33device = "cpu"
34
35embeddings_path = hf_hub_download(
36 repo_id="ag-charalampous/target-identification",
37 filename="retrieval_data_random_negatives_10_train_data.pkl"
38)
39
40with open(embeddings_path, "rb") as f:
41 embeddings_metadata = pickle.load(f)
42
43@torch.no_grad()
44def retrieve_theses(claim, top_k=3, num_args=5, top_level_only=True, device="cpu"):
45 stored_embeddings = embeddings_metadata["embeddings"]
46 metadata = embeddings_metadata["metadata"]
47
48 enc = tokenizer(claim, return_tensors='pt', truncation=True, padding='max_length', max_length=1024).to(device)
49 query_embedding = model.encoder(**enc).last_hidden_state[:, 0].cpu().numpy()
50
51 sims = cosine_similarity(query_embedding, stored_embeddings)[0]
52 top_indices = np.argsort(sims)[::-1][:top_k]
53
54 results = []
55 for idx in top_indices:
56 arguments = metadata[idx]['arguments']
57 if top_level_only:
58 arguments = [arg for arg in arguments if arg['target_type'] == 'thesis']
59
60 results.append({
61 "thesis": metadata[idx]["thesis"],
62 "debate_title": metadata[idx]["debate_title"],
63 "arguments": arguments[:num_args]
64 })
65
66 return results
67
68claim = "A fetus or embryo is not a person; therefore, abortion should not be considered murder."
69
70theses = retrieve_theses(claim)
71
72for thesis in theses:
73 print(f"{thesis['thesis']} | {thesis['debate_title']}")