Views
No views yet
1from transformers import AutoModel, AutoTokenizer
2
3model = AutoModel.from_pretrained("BMRetriever/BMRetriever-410M")
4tokenizer = AutoTokenizer.from_pretrained("BMRetriever/BMRetriever-410M") 1import torch
2import torch.nn.functional as F
3
4from torch import Tensor
5from transformers import AutoTokenizer, AutoModel
6
7
8def last_token_pool(last_hidden_states: Tensor,
9 attention_mask: Tensor) -> Tensor:
10 last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0)
11 left_padding = (attention_mask[:, -1].sum() == attention_mask.shape[0])
12 if left_padding:
13 embedding = last_hidden[:, -1]
14 else:
15 sequence_lengths = attention_mask.sum(dim=1) - 1
16 batch_size = last_hidden.shape[0]
17 embedding = last_hidden[torch.arange(batch_size, device=last_hidden.device), sequence_lengths]
18 return embedding
19
20def get_detailed_instruct_query(task_description: str, query: str) -> str:
21 return f'{task_description}\nQuery: {query}'
22
23def get_detailed_instruct_passage(passage: str) -> str:
24 return f'Represent this passage\npassage: {passage}'
25
26# Each query must come with a one-sentence instruction that describes the task
27task = 'Given a scientific claim, retrieve documents that support or refute the claim'
28queries = [
29 get_detailed_instruct_query(task, 'Cis-acting lncRNAs control the expression of genes that are positioned in the vicinity of their transcription sites.'),
30 get_detailed_instruct_query(task, 'Forkhead 0 (fox0) transcription factors are involved in apoptosis.')
31]
32
33# No need to add instruction for retrieval documents
34documents = [
35 get_detailed_instruct_passage("Gene regulation by the act of long non-coding RNA transcription Long non-protein-coding RNAs (lncRNAs) are proposed to be the largest transcript class in the mouse and human transcriptomes. Two important questions are whether all lncRNAs are functional and how they could exert a function. Several lncRNAs have been shown to function through their product, but this is not the only possible mode of action. In this review we focus on a role for the process of lncRNA transcription, independent of the lncRNA product, in regulating protein-coding-gene activity in cis. We discuss examples where lncRNA transcription leads to gene silencing or activation, and describe strategies to determine if the lncRNA product or its transcription causes the regulatory effect."),
36 get_detailed_instruct_passage("Noncoding transcription at enhancers: general principles and functional models. Mammalian genomes are extensively transcribed outside the borders of protein-coding genes. Genome-wide studies recently demonstrated that cis-regulatory genomic elements implicated in transcriptional control, such as enhancers and locus-control regions, represent major sites of extragenic noncoding transcription. Enhancer-templated transcripts provide a quantitatively small contribution to the total amount of cellular nonribosomal RNA; nevertheless, the possibility that enhancer transcription and the resulting enhancer RNAs may, in some cases, have functional roles, rather than represent mere transcriptional noise at accessible genomic regions, is supported by an increasing amount of experimental data. In this article we review the current knowledge on enhancer transcription and its functional implications.")
37]
38input_texts = queries + documents
39
40max_length = 512
41
42# Tokenize the input texts
43batch_dict = tokenizer(input_texts, max_length=max_length-1, padding=True, truncation=True, return_tensors='pt')
44
45# Important! Adding EOS token at the end
46batch_dict['input_ids'] = [input_ids + [tokenizer.eos_token_id] for input_ids in batch_dict['input_ids']]
47batch_dict = tokenizer.pad(batch_dict, padding=True, return_attention_mask=True, return_tensors='pt').to("cuda")
48
49model.eval()
50with torch.no_grad():
51 outputs = model(**batch_dict)
52 embeddings = last_token_pool(outputs.last_hidden_state, batch_dict['attention_mask'])1scores = (embeddings[:2] @ embeddings[2:].T)
2print(scores.tolist())@inproceedings{xu2024bmretriever,
title={BMRetriever: Tuning Large Language Models as Better Biomedical Text Retrievers},
author={Ran Xu and Wenqi Shi and Yue Yu and Yuchen Zhuang and Yanqiao Zhu and May D. Wang and Joyce C. Ho and Chao Zhang and Carl Yang},
year={2024},
booktitle={Proceedings of the 2024 Conference on Empirical Methods in Natural Language Processing},
}