abdoelsayed commited on
Commit
4f1113e
Β·
verified Β·
1 Parent(s): 7eebc09

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +348 -190
README.md CHANGED
@@ -1,202 +1,360 @@
1
  ---
2
- base_model: meta-llama/Llama-3.1-8B
 
 
3
  library_name: peft
 
 
 
 
 
 
 
 
 
 
 
 
4
  ---
5
 
6
- # Model Card for Model ID
7
-
8
- <!-- Provide a quick summary of what the model is/does. -->
9
 
 
10
 
 
11
 
12
  ## Model Details
13
 
14
- ### Model Description
15
-
16
- <!-- Provide a longer summary of what this model is. -->
17
-
18
-
19
-
20
- - **Developed by:** [More Information Needed]
21
- - **Funded by [optional]:** [More Information Needed]
22
- - **Shared by [optional]:** [More Information Needed]
23
- - **Model type:** [More Information Needed]
24
- - **Language(s) (NLP):** [More Information Needed]
25
- - **License:** [More Information Needed]
26
- - **Finetuned from model [optional]:** [More Information Needed]
27
-
28
- ### Model Sources [optional]
29
-
30
- <!-- Provide the basic links for the model. -->
31
-
32
- - **Repository:** [More Information Needed]
33
- - **Paper [optional]:** [More Information Needed]
34
- - **Demo [optional]:** [More Information Needed]
35
-
36
- ## Uses
37
-
38
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
-
40
- ### Direct Use
41
-
42
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
-
44
- [More Information Needed]
45
-
46
- ### Downstream Use [optional]
47
-
48
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
-
50
- [More Information Needed]
51
-
52
- ### Out-of-Scope Use
53
-
54
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
-
56
- [More Information Needed]
57
-
58
- ## Bias, Risks, and Limitations
59
-
60
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
-
62
- [More Information Needed]
63
-
64
- ### Recommendations
65
-
66
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
-
68
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
-
70
- ## How to Get Started with the Model
71
-
72
- Use the code below to get started with the model.
73
-
74
- [More Information Needed]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  ## Training Details
77
 
78
- ### Training Data
79
-
80
- <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
-
82
- [More Information Needed]
83
-
84
- ### Training Procedure
85
-
86
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
-
88
- #### Preprocessing [optional]
89
-
90
- [More Information Needed]
91
-
92
-
93
- #### Training Hyperparameters
94
-
95
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
-
97
- #### Speeds, Sizes, Times [optional]
98
-
99
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
-
101
- [More Information Needed]
102
-
103
- ## Evaluation
104
-
105
- <!-- This section describes the evaluation protocols and provides the results. -->
106
-
107
- ### Testing Data, Factors & Metrics
108
-
109
- #### Testing Data
110
-
111
- <!-- This should link to a Dataset Card if possible. -->
112
-
113
- [More Information Needed]
114
-
115
- #### Factors
116
-
117
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
-
119
- [More Information Needed]
120
-
121
- #### Metrics
122
-
123
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
-
125
- [More Information Needed]
126
-
127
- ### Results
128
-
129
- [More Information Needed]
130
-
131
- #### Summary
132
-
133
-
134
-
135
- ## Model Examination [optional]
136
-
137
- <!-- Relevant interpretability work for the model goes here -->
138
-
139
- [More Information Needed]
140
-
141
- ## Environmental Impact
142
-
143
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
-
145
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
-
147
- - **Hardware Type:** [More Information Needed]
148
- - **Hours used:** [More Information Needed]
149
- - **Cloud Provider:** [More Information Needed]
150
- - **Compute Region:** [More Information Needed]
151
- - **Carbon Emitted:** [More Information Needed]
152
-
153
- ## Technical Specifications [optional]
154
-
155
- ### Model Architecture and Objective
156
-
157
- [More Information Needed]
158
-
159
- ### Compute Infrastructure
160
-
161
- [More Information Needed]
162
-
163
- #### Hardware
164
-
165
- [More Information Needed]
166
-
167
- #### Software
168
-
169
- [More Information Needed]
170
-
171
- ## Citation [optional]
172
-
173
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
-
175
- **BibTeX:**
176
-
177
- [More Information Needed]
178
-
179
- **APA:**
180
-
181
- [More Information Needed]
182
-
183
- ## Glossary [optional]
184
-
185
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
-
187
- [More Information Needed]
188
-
189
- ## More Information [optional]
190
-
191
- [More Information Needed]
192
-
193
- ## Model Card Authors [optional]
194
-
195
- [More Information Needed]
196
-
197
- ## Model Card Contact
198
-
199
- [More Information Needed]
200
- ### Framework versions
201
-
202
- - PEFT 0.13.2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ language:
3
+ - en
4
+ license: mit
5
  library_name: peft
6
+ tags:
7
+ - reranking
8
+ - information-retrieval
9
+ - pointwise
10
+ - lora
11
+ - peft
12
+ - ranknet
13
+ base_model: meta-llama/Llama-3.1-8B
14
+ datasets:
15
+ - Tevatron/msmarco-passage
16
+ - abdoelsayed/DeAR-COT
17
+ pipeline_tag: text-classification
18
  ---
19
 
20
+ # DeAR-8B-Reranker-RankNet-LoRA-v1
 
 
21
 
22
+ ## Model Description
23
 
24
+ **DeAR-8B-Reranker-RankNet-LoRA-v1** is a LoRA (Low-Rank Adaptation) adapter for neural reranking. This lightweight adapter can be applied to LLaMA-3.1-8B to create a reranker with minimal storage overhead. It achieves comparable performance to the full fine-tuned model while requiring only ~100MB of storage.
25
 
26
  ## Model Details
27
 
28
+ - **Model Type:** LoRA Adapter for Pointwise Reranking
29
+ - **Base Model:** meta-llama/Llama-3.1-8B
30
+ - **Adapter Size:** ~100MB (vs 16GB for full model)
31
+ - **Training Method:** LoRA with RankNet Loss + Knowledge Distillation
32
+ - **LoRA Rank:** 16
33
+ - **LoRA Alpha:** 32
34
+ - **Target Modules:** q_proj, v_proj, k_proj, o_proj, gate_proj, up_proj, down_proj
35
+
36
+ ## Key Features
37
+
38
+ βœ… **Lightweight:** Only 100MB vs 16GB full model
39
+ βœ… **Efficient Training:** Trains 3x faster than full fine-tuning
40
+ βœ… **Easy Deployment:** Just load adapter on top of base model
41
+ βœ… **Comparable Performance:** ~98% of full model performance
42
+ βœ… **Memory Efficient:** Lower GPU memory during training
43
+
44
+ ## Usage
45
+
46
+ ### Option 1: Load with PEFT (Recommended)
47
+
48
+ ```python
49
+ import torch
50
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
51
+ from peft import PeftModel, PeftConfig
52
+
53
+ # Load LoRA adapter
54
+ adapter_path = "abdoelsayed/dear-8b-reranker-ranknet-lora-v1"
55
+
56
+ # Get base model from adapter config
57
+ config = PeftConfig.from_pretrained(adapter_path)
58
+ base_model_name = config.base_model_name_or_path
59
+
60
+ # Load tokenizer
61
+ tokenizer = AutoTokenizer.from_pretrained(base_model_name)
62
+ if tokenizer.pad_token is None:
63
+ tokenizer.pad_token = tokenizer.eos_token
64
+ tokenizer.pad_token_id = tokenizer.eos_token_id
65
+
66
+ # Load base model
67
+ base_model = AutoModelForSequenceClassification.from_pretrained(
68
+ base_model_name,
69
+ num_labels=1,
70
+ torch_dtype=torch.bfloat16
71
+ )
72
+
73
+ # Load and merge LoRA adapter
74
+ model = PeftModel.from_pretrained(base_model, adapter_path)
75
+ model = model.merge_and_unload() # Merge adapter into base model
76
+
77
+ model.eval().cuda()
78
+
79
+ # Use the model
80
+ query = "What is machine learning?"
81
+ document = "Machine learning is a subset of artificial intelligence..."
82
+
83
+ inputs = tokenizer(
84
+ f"query: {query}",
85
+ f"document: {document}",
86
+ return_tensors="pt",
87
+ truncation=True,
88
+ max_length=228,
89
+ padding="max_length"
90
+ )
91
+ inputs = {k: v.cuda() for k, v in inputs.items()}
92
+
93
+ with torch.no_grad():
94
+ score = model(**inputs).logits.squeeze().item()
95
+
96
+ print(f"Relevance score: {score}")
97
+ ```
98
+
99
+ ### Option 2: Use Helper Function
100
+
101
+ ```python
102
+ import torch
103
+ from typing import List, Tuple
104
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
105
+ from peft import PeftModel, PeftConfig
106
+
107
+ def load_lora_ranker(adapter_path: str, device: str = "cuda"):
108
+ """Load LoRA adapter and merge with base model."""
109
+ # Get base model path from adapter config
110
+ peft_config = PeftConfig.from_pretrained(adapter_path)
111
+ base_model_name = peft_config.base_model_name_or_path
112
+
113
+ # Load tokenizer
114
+ tokenizer = AutoTokenizer.from_pretrained(base_model_name)
115
+ if tokenizer.pad_token is None:
116
+ tokenizer.pad_token = tokenizer.eos_token
117
+ tokenizer.pad_token_id = tokenizer.eos_token_id
118
+ tokenizer.padding_side = "right"
119
+
120
+ # Load base model
121
+ base_model = AutoModelForSequenceClassification.from_pretrained(
122
+ base_model_name,
123
+ num_labels=1,
124
+ torch_dtype=torch.bfloat16
125
+ )
126
+
127
+ # Load LoRA adapter and merge
128
+ model = PeftModel.from_pretrained(base_model, adapter_path)
129
+ model = model.merge_and_unload()
130
+
131
+ model.eval().to(device)
132
+ return tokenizer, model
133
+
134
+ # Load model
135
+ tokenizer, model = load_lora_ranker("abdoelsayed/dear-8b-reranker-ranknet-lora-v1")
136
+
137
+ # Rerank documents
138
+ @torch.inference_mode()
139
+ def rerank(tokenizer, model, query: str, docs: List[Tuple[str, str]], batch_size: int = 64):
140
+ """Rerank documents for a query."""
141
+ device = next(model.parameters()).device
142
+ scores = []
143
+
144
+ for i in range(0, len(docs), batch_size):
145
+ batch = docs[i:i + batch_size]
146
+ queries = [f"query: {query}"] * len(batch)
147
+ documents = [f"document: {title} {text}" for title, text in batch]
148
+
149
+ inputs = tokenizer(
150
+ queries,
151
+ documents,
152
+ return_tensors="pt",
153
+ truncation=True,
154
+ max_length=228,
155
+ padding=True
156
+ )
157
+ inputs = {k: v.to(device) for k, v in inputs.items()}
158
+
159
+ logits = model(**inputs).logits.squeeze(-1)
160
+ scores.extend(logits.cpu().tolist())
161
+
162
+ return sorted(enumerate(scores), key=lambda x: x[1], reverse=True)
163
+
164
+ # Example
165
+ query = "When did Thomas Edison invent the light bulb?"
166
+ docs = [
167
+ ("", "Thomas Edison invented the light bulb in 1879"),
168
+ ("", "Coffee is good for diet"),
169
+ ("", "Lightning strike at Seoul"),
170
+ ]
171
+
172
+ ranking = rerank(tokenizer, model, query, docs)
173
+ print(ranking) # [(0, 5.2), (2, -3.1), (1, -4.8)]
174
+ ```
175
+
176
+ ### Using Without Merging (Memory Efficient)
177
+
178
+ ```python
179
+ from peft import PeftModel, PeftConfig
180
+ from transformers import AutoModelForSequenceClassification
181
+
182
+ adapter_path = "abdoelsayed/dear-8b-reranker-ranknet-lora-v1"
183
+ config = PeftConfig.from_pretrained(adapter_path)
184
+
185
+ # Load base model
186
+ base_model = AutoModelForSequenceClassification.from_pretrained(
187
+ config.base_model_name_or_path,
188
+ num_labels=1,
189
+ torch_dtype=torch.bfloat16,
190
+ device_map="auto"
191
+ )
192
+
193
+ # Load adapter (without merging)
194
+ model = PeftModel.from_pretrained(base_model, adapter_path)
195
+ model.eval()
196
+
197
+ # Use model (adapter layers will be applied automatically)
198
+ # ... same inference code as above ...
199
+ ```
200
+
201
+ ## Performance
202
+
203
+ | Benchmark | LoRA | Full Model | Difference |
204
+ |-----------|------|------------|------------|
205
+ | TREC DL19 | 74.2 | 74.5 | -0.3 |
206
+ | TREC DL20 | 72.5 | 72.8 | -0.3 |
207
+ | BEIR (Avg) | 44.9 | 45.2 | -0.3 |
208
+ | MS MARCO | 68.6 | 68.9 | -0.3 |
209
+
210
+ βœ… **98% of full model performance with only 0.6% of the storage!**
211
 
212
  ## Training Details
213
 
214
+ ### LoRA Configuration
215
+ ```python
216
+ lora_config = {
217
+ "r": 16, # LoRA rank
218
+ "lora_alpha": 32, # Scaling factor
219
+ "target_modules": [
220
+ "q_proj", "v_proj", "k_proj", "o_proj",
221
+ "gate_proj", "up_proj", "down_proj"
222
+ ],
223
+ "lora_dropout": 0.05,
224
+ "bias": "none",
225
+ "task_type": "SEQ_CLS"
226
+ }
227
+ ```
228
+
229
+ ### Training Hyperparameters
230
+ ```python
231
+ training_args = {
232
+ "learning_rate": 1e-4, # Higher than full fine-tuning
233
+ "batch_size": 4, # Larger batch possible due to lower memory
234
+ "gradient_accumulation": 2,
235
+ "epochs": 2,
236
+ "warmup_ratio": 0.1,
237
+ "weight_decay": 0.01,
238
+ "max_length": 228,
239
+ "bf16": True
240
+ }
241
+ ```
242
+
243
+ ### Hardware
244
+ - **GPUs:** 4x NVIDIA A100 (40GB)
245
+ - **Training Time:** ~12 hours (3x faster than full model)
246
+ - **Memory Usage:** ~28GB per GPU (vs ~38GB for full)
247
+ - **Trainable Parameters:** 67M (0.8% of total)
248
+
249
+ ## Advantages of LoRA Version
250
+
251
+ | Aspect | LoRA | Full Model |
252
+ |--------|------|------------|
253
+ | Storage | 100MB | 16GB |
254
+ | Training Time | 12h | 36h |
255
+ | Training Memory | 28GB | 38GB |
256
+ | Performance | 98% | 100% |
257
+ | Loading Time | Fast | Slow |
258
+ | Easy Updates | βœ… Yes | ❌ No |
259
+
260
+ ## When to Use LoRA vs Full Model
261
+
262
+ **Use LoRA when:**
263
+ - βœ… Storage is limited
264
+ - βœ… Training multiple domain-specific versions
265
+ - βœ… Need fast iteration/experimentation
266
+ - βœ… 0.3 NDCG@10 difference is acceptable
267
+
268
+ **Use Full Model when:**
269
+ - ❌ Maximum performance required
270
+ - ❌ Storage not a concern
271
+ - ❌ Single production deployment
272
+
273
+ ## Fine-tuning on Your Data
274
+
275
+ ```python
276
+ from peft import LoraConfig, get_peft_model, TaskType
277
+ from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer
278
+
279
+ # Load base model
280
+ base_model = AutoModelForSequenceClassification.from_pretrained(
281
+ "meta-llama/Llama-3.1-8B",
282
+ num_labels=1
283
+ )
284
+
285
+ # Configure LoRA
286
+ lora_config = LoraConfig(
287
+ task_type=TaskType.SEQ_CLS,
288
+ r=16,
289
+ lora_alpha=32,
290
+ target_modules=["q_proj", "v_proj", "k_proj", "o_proj"],
291
+ lora_dropout=0.05,
292
+ bias="none",
293
+ )
294
+
295
+ # Apply LoRA
296
+ model = get_peft_model(base_model, lora_config)
297
+ model.print_trainable_parameters()
298
+ # Output: trainable params: 67M || all params: 8B || trainable%: 0.8%
299
+
300
+ # Train
301
+ training_args = TrainingArguments(
302
+ output_dir="./lora-finetuned",
303
+ learning_rate=1e-4,
304
+ per_device_train_batch_size=8,
305
+ num_train_epochs=3,
306
+ bf16=True,
307
+ )
308
+
309
+ trainer = Trainer(
310
+ model=model,
311
+ args=training_args,
312
+ train_dataset=your_dataset,
313
+ )
314
+
315
+ trainer.train()
316
+
317
+ # Save only the LoRA adapter
318
+ model.save_pretrained("./lora-adapter")
319
+ ```
320
+
321
+ ## Model Files
322
+
323
+ This adapter contains:
324
+ - `adapter_config.json` - LoRA configuration
325
+ - `adapter_model.safetensors` or `adapter_model.bin` - Adapter weights (~100MB)
326
+ - `README.md` - This documentation
327
+
328
+ ## Related Models
329
+
330
+ **Full Model:**
331
+ - [DeAR-8B-RankNet](https://huggingface.co/abdoelsayed/dear-8b-reranker-ranknet-v1) - Full fine-tuned version
332
+
333
+ **Other LoRA Adapters:**
334
+ - [DeAR-8B-CE-LoRA](https://huggingface.co/abdoelsayed/dear-8b-reranker-ce-lora-v1) - Binary Cross-Entropy
335
+ - [DeAR-8B-Listwise-LoRA](https://huggingface.co/abdoelsayed/dear-8b-reranker-listwise-lora-v1) - Listwise ranking
336
+
337
+ **Resources:**
338
+ - [DeAR-COT Dataset](https://huggingface.co/datasets/abdoelsayed/DeAR-COT)
339
+ - [Teacher Model](https://huggingface.co/abdoelsayed/llama2-13b-rankllama-teacher)
340
+
341
+ ## Citation
342
+
343
+ ```bibtex
344
+ @article{abdallah2025dear,
345
+ title={DeAR: Dual-Stage Document Reranking with Reasoning Agents via LLM Distillation},
346
+ author={Abdallah, Abdelrahman and Mozafari, Jamshid and Piryani, Bhawna and Jatowt, Adam},
347
+ journal={arXiv preprint arXiv:2508.16998},
348
+ year={2025}
349
+ }
350
+ ```
351
+
352
+ ## License
353
+
354
+ MIT License
355
+
356
+ ## More Information
357
+
358
+ - **GitHub:** [DataScienceUIBK/DeAR-Reranking](https://github.com/DataScienceUIBK/DeAR-Reranking)
359
+ - **Paper:** [arXiv:2508.16998](https://arxiv.org/abs/2508.16998)
360
+ - **Collection:** [DeAR Models](https://huggingface.co/collections/abdoelsayed/dear-reranking)