KaiYinTAMU commited on
Commit
a0fe500
·
verified ·
1 Parent(s): 6d02df8

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +108 -3
README.md CHANGED
@@ -1,3 +1,108 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ tags:
6
+ - Retrieval
7
+ - LLM
8
+ - Embedding
9
+ ---
10
+
11
+ This model is trained through the approach described in [DMRetriever: A Family of Models for Improved Text Retrieval in Disaster Management](https://www.arxiv.org/abs/2510.15087).
12
+ The associated GitHub repository is available [here](https://github.com/KaiYin97/DMRETRIEVER).
13
+ This model has 33M parameters.
14
+
15
+ ## Usage
16
+
17
+ Using HuggingFace Transformers:
18
+ ```python
19
+ import numpy as np
20
+ import torch
21
+ import torch.nn.functional as F
22
+ from transformers import AutoTokenizer, AutoModel
23
+
24
+ MODEL_NAME = "DMIR01/DMRetriever-33M"
25
+
26
+ # Load model/tokenizer
27
+ device = "cuda" if torch.cuda.is_available() else "cpu"
28
+ dtype = torch.float16 if device == "cuda" else torch.float32
29
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, use_fast=True)
30
+ # Some decoder-only models have no pad token; fall back to EOS if needed
31
+ if tokenizer.pad_token is None and tokenizer.eos_token is not None:
32
+ tokenizer.pad_token = tokenizer.eos_token
33
+ model = AutoModel.from_pretrained(MODEL_NAME, torch_dtype=dtype).to(device)
34
+ model.eval()
35
+
36
+ # Mean pooling over valid tokens (mask==1)
37
+ def mean_pool(last_hidden_state: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
38
+ mask = attention_mask.unsqueeze(-1).type_as(last_hidden_state) # [B, T, 1]
39
+ summed = (last_hidden_state * mask).sum(dim=1) # [B, H]
40
+ counts = mask.sum(dim=1).clamp(min=1e-9) # [B, 1]
41
+ return summed / counts # [B, H]
42
+
43
+ # Optional task prefixes (use for queries; keep corpus plain)
44
+ TASK2PREFIX = {
45
+ "FactCheck": "Given the claim, retrieve most relevant document that supports or refutes the claim",
46
+ "NLI": "Given the premise, retrieve most relevant hypothesis that is entailed by the premise",
47
+ "QA": "Given the question, retrieve most relevant passage that best answers the question",
48
+ "QAdoc": "Given the question, retrieve the most relevant document that answers the question",
49
+ "STS": "Given the sentence, retrieve the sentence with the same meaning",
50
+ "Twitter": "Given the user query, retrieve the most relevant Twitter text that meets the request",
51
+ }
52
+ def with_prefix(task: str, text: str) -> str:
53
+ p = TASK2PREFIX.get(task, "")
54
+ return f"{p}: {text}" if p else text
55
+
56
+ # Batch encode with L2 normalization (recommended for cosine/inner-product search)
57
+ @torch.inference_mode()
58
+ def encode_texts(texts, batch_size: int = 32, max_length: int = 512, normalize: bool = True):
59
+ all_embs = []
60
+ for i in range(0, len(texts), batch_size):
61
+ batch = texts[i:i + batch_size]
62
+ toks = tokenizer(
63
+ batch,
64
+ padding=True,
65
+ truncation=True,
66
+ max_length=max_length,
67
+ return_tensors="pt",
68
+ )
69
+ toks = {k: v.to(device) for k, v in toks.items()}
70
+ out = model(**toks, return_dict=True)
71
+ emb = mean_pool(out.last_hidden_state, toks["attention_mask"])
72
+ if normalize:
73
+ emb = F.normalize(emb, p=2, dim=1)
74
+ all_embs.append(emb.cpu().numpy())
75
+ return np.vstack(all_embs) if all_embs else np.empty((0, model.config.hidden_size), dtype=np.float32)
76
+
77
+ # ---- Example: plain sentences ----
78
+ sentences = [
79
+ "A cat sits on the mat.",
80
+ "The feline is resting on the rug.",
81
+ "Quantum mechanics studies matter and light.",
82
+ ]
83
+ embs = encode_texts(sentences) # shape: [N, hidden_size]
84
+ print("Embeddings shape:", embs.shape)
85
+
86
+ # Cosine similarity (embeddings are L2-normalized)
87
+ sims = embs @ embs.T
88
+ print("Cosine similarity matrix:\n", np.round(sims, 3))
89
+
90
+ # ---- Example: query with task prefix (QA) ----
91
+ qa_queries = [
92
+ with_prefix("QA", "Who wrote 'Pride and Prejudice'?"),
93
+ with_prefix("QA", "What is the capital of Japan?"),
94
+ ]
95
+ qa_embs = encode_texts(qa_queries)
96
+ print("QA Embeddings shape:", qa_embs.shape)
97
+
98
+ ```
99
+ ## Citation
100
+ If you find this repository helpful, please kindly consider citing the corresponding paper. Thanks!
101
+ ```
102
+ @article{yin2025dmretriever,
103
+ title={DMRetriever: A Family of Models for Improved Text Retrieval in Disaster Management},
104
+ author={Yin, Kai and Dong, Xiangjue and Liu, Chengkai and Lin, Allen and Shi, Lingfeng and Mostafavi, Ali and Caverlee, James},
105
+ journal={arXiv preprint arXiv:2510.15087},
106
+ year={2025}
107
+ }
108
+ ```