zyznull jinjiajie commited on
Commit
d22e8d3
Β·
1 Parent(s): b701458

Create README.md (#1)

Browse files

- Create README.md (0100ba1ac9af75c5b472c0c6d2a6862257dba325)


Co-authored-by: Jiajie Jin <jinjiajie@users.noreply.huggingface.co>

Files changed (1) hide show
  1. README.md +194 -0
README.md ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ language:
4
+ - en
5
+ library_name: transformers
6
+ tags:
7
+ - dense-retrieval
8
+ - latent-reasoning
9
+ - embeddings
10
+ - information-retrieval
11
+ - feature-extraction
12
+ base_model: Qwen/Qwen3-4B
13
+ pipeline_tag: feature-extraction
14
+ datasets:
15
+ - jinjiajie/LaSER-Training
16
+ ---
17
+
18
+ # LaSER-Qwen3-4B
19
+
20
+ **LaSER** (**La**tent **S**pace **E**xplicit **R**easoning) is a self-distillation framework that internalizes explicit Chain-of-Thought reasoning into the latent space of dense retrievers, enabling the model to "think silently" through continuous latent tokens.
21
+
22
+ **LaSER-Qwen3-4B** is a 4B-parameter dense retriever built on [Qwen/Qwen3-4B](https://huggingface.co/Qwen/Qwen3-4B).
23
+
24
+ > πŸ“„ **Paper:** [LaSER: Internalizing Explicit Reasoning into Latent Space for Dense Retrieval](https://arxiv.org/abs/2603.01425)
25
+ >
26
+ > πŸ’» **Code:** [https://github.com/ignorejjj/LaSER](https://github.com/ignorejjj/LaSER)
27
+
28
+ ## Model Summary
29
+
30
+ | Attribute | Detail |
31
+ |:---|:---|
32
+ | **Model Type** | Dense Retriever with Latent Thinking |
33
+ | **Base Model** | [Qwen/Qwen3-4B](https://huggingface.co/Qwen/Qwen3-4B) |
34
+ | **Parameters** | 4B |
35
+ | **Embedding Dimension** | 2560 |
36
+ | **Max Sequence Length** | 8192 (training: 512) |
37
+ | **Similarity Function** | Cosine Similarity |
38
+ | **Latent Thinking Steps (K)** | 3 (default) |
39
+ | **Training Data** | 81K examples from [ReasonEmb](https://huggingface.co/datasets/reasonir/ReasonEmb) |
40
+ | **License** | MIT |
41
+
42
+ ## How It Works
43
+
44
+ Unlike standard dense retrievers that encode queries in a single forward pass, LaSER generates **K continuous latent thinking tokens** autoregressively in the embedding space:
45
+
46
+ 1. Encode the input text into embeddings
47
+ 2. At each thinking step, project the last hidden state through the LM head β†’ softmax β†’ compute a probability-weighted soft token from the embedding table
48
+ 3. Append the soft token and repeat for K steps (using KV caching for efficiency)
49
+ 4. Mean-pool the hidden states from all K thinking steps β†’ L2 normalize
50
+
51
+ This enables complex reasoning while maintaining the inference efficiency of standard dense retrievers (~1.7Γ— latency overhead, only ~0.3% of rewrite-then-retrieve pipelines).
52
+
53
+ ## Usage
54
+
55
+ ### Direct Usage with Transformers
56
+
57
+ ```python
58
+ import torch
59
+ import torch.nn.functional as F
60
+ from transformers import AutoModelForCausalLM, AutoTokenizer
61
+
62
+
63
+ def laser_encode(model, tokenizer, texts, max_length=512, num_thinking_steps=3):
64
+ """Encode texts using LaSER's latent thinking mechanism."""
65
+ device = next(model.parameters()).device
66
+ batch = tokenizer(texts, padding=True, truncation=True, max_length=max_length, return_tensors="pt").to(device)
67
+ input_ids, attention_mask = batch["input_ids"], batch["attention_mask"]
68
+
69
+ batch_size = input_ids.size(0)
70
+ thinking_slots = num_thinking_steps - 1
71
+ eos_id = tokenizer.eos_token_id
72
+
73
+ if thinking_slots > 0:
74
+ eos_padding = torch.full((batch_size, thinking_slots), eos_id, dtype=input_ids.dtype, device=device)
75
+ mask_padding = torch.ones((batch_size, thinking_slots), dtype=attention_mask.dtype, device=device)
76
+ input_ids = torch.cat([input_ids, eos_padding], dim=1)
77
+ attention_mask = torch.cat([attention_mask, mask_padding], dim=1)
78
+
79
+ input_embeds = model.get_input_embeddings()(input_ids)
80
+ embedding_table = model.get_input_embeddings().weight
81
+ base_seq_len = input_embeds.size(1) - thinking_slots
82
+
83
+ past_key_values = None
84
+ hidden_steps = []
85
+
86
+ for step_idx in range(thinking_slots):
87
+ pos = base_seq_len + step_idx
88
+ step_embeds = input_embeds[:, :pos, :] if past_key_values is None else input_embeds[:, pos-1:pos, :]
89
+ step_mask = attention_mask[:, :pos]
90
+
91
+ outputs = model(inputs_embeds=step_embeds, attention_mask=step_mask,
92
+ output_hidden_states=True, past_key_values=past_key_values,
93
+ use_cache=True, return_dict=True)
94
+ hidden_steps.append(outputs.hidden_states[-1][:, -1, :])
95
+ token_probs = torch.softmax(outputs.logits[:, -1, :], dim=-1)
96
+ new_embed = token_probs @ embedding_table
97
+ past_key_values = outputs.past_key_values
98
+ pre = input_embeds[:, :pos, :]
99
+ post = input_embeds[:, pos+1:, :]
100
+ input_embeds = torch.cat([pre, new_embed.unsqueeze(1), post], dim=1)
101
+
102
+ final_embeds = input_embeds[:, -1:, :] if past_key_values else input_embeds
103
+ outputs = model(inputs_embeds=final_embeds, attention_mask=attention_mask,
104
+ output_hidden_states=True, past_key_values=past_key_values,
105
+ use_cache=True, return_dict=True)
106
+ hidden_steps.append(outputs.hidden_states[-1][:, -1, :])
107
+
108
+ embeddings = torch.stack(hidden_steps, dim=1).mean(dim=1)
109
+ return F.normalize(embeddings, p=2, dim=-1)
110
+
111
+
112
+ # Load model
113
+ model_name = "Alibaba-NLP/LaSER-Qwen3-4B"
114
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
115
+ tokenizer.padding_side = "left"
116
+ if tokenizer.pad_token_id is None:
117
+ tokenizer.pad_token = tokenizer.eos_token
118
+
119
+ model = AutoModelForCausalLM.from_pretrained(
120
+ model_name, torch_dtype=torch.float16, trust_remote_code=True
121
+ ).cuda().eval()
122
+
123
+ # Encode queries and documents
124
+ with torch.inference_mode():
125
+ query_emb = laser_encode(model, tokenizer, ["why is the sky blue"], num_thinking_steps=3)
126
+ doc_emb = laser_encode(model, tokenizer, ["Rayleigh scattering makes short wavelengths scatter more strongly"], num_thinking_steps=3)
127
+
128
+ # Compute similarity
129
+ similarity = (query_emb @ doc_emb.T).item()
130
+ print(f"Cosine similarity: {similarity:.4f}")
131
+ ```
132
+
133
+ ### Batch Encoding
134
+
135
+ ```python
136
+ queries = [
137
+ "What causes tides in the ocean?",
138
+ "How does photosynthesis convert light to energy?",
139
+ "Why do metals conduct electricity?",
140
+ ]
141
+
142
+ with torch.inference_mode():
143
+ query_embeddings = laser_encode(model, tokenizer, queries, num_thinking_steps=3)
144
+ print(f"Batch embeddings shape: {query_embeddings.shape}") # (3, 2560)
145
+ ```
146
+
147
+ ## Evaluation Results
148
+
149
+ ### BRIGHT Benchmark (nDCG@10) β€” In-Domain
150
+
151
+ | Model | Size | Avg. |
152
+ |:---|:---:|:---:|
153
+ | Qwen3-Embedding-4B | 4B | 17.9 |
154
+ | Fair Baseline (Qwen3-4B) | 4B | β€” |
155
+ | GIRCSE (Qwen3-4B) | 4B | β€” |
156
+ | **LaSER-Qwen3-4B (Ours)** | **4B** | **28.0** |
157
+
158
+ ### Cross-Scale Comparison on BRIGHT
159
+
160
+ | Model | Size | Avg. (nDCG@10) |
161
+ |:---|:---:|:---:|
162
+ | LaSER-Qwen3-0.6B | 0.6B | 23.1 |
163
+ | **LaSER-Qwen3-4B** | **4B** | **28.0** |
164
+ | LaSER-Qwen3-8B | 8B | 29.3 |
165
+
166
+ > LaSER-Qwen3-4B achieves a strong balance between performance and computational cost, outperforming 8B-scale standard dense retrievers while requiring significantly less compute.
167
+
168
+ ## Training Details
169
+
170
+ - **Training Data:** 81K query-document pairs from [ReasonEmb](https://huggingface.co/datasets/reasonir/ReasonEmb), each with a CoT reasoning path generated by GPT-4o-mini
171
+ - **Method:** LoRA fine-tuning (r=64, Ξ±=32) for 1 epoch on 4Γ—A100 GPUs
172
+ - **Loss:** Contrastive learning + Output-level KL distillation (Ξ»β‚‚=10) + Process-level trajectory alignment (λ₃=0.1)
173
+ - **Temperature:** Ο„=0.02
174
+ - **Thinking Steps:** K=3
175
+
176
+ ## Model Family
177
+
178
+ | Model | Parameters | BRIGHT Avg. | Link |
179
+ |:---|:---:|:---:|:---:|
180
+ | LaSER-Qwen3-0.6B | 0.6B | 23.1 | [πŸ€— Link](https://huggingface.co/Alibaba-NLP/LaSER-Qwen3-0.6B) |
181
+ | **LaSER-Qwen3-4B** | 4B | 28.0 | [πŸ€— This model](https://huggingface.co/Alibaba-NLP/LaSER-Qwen3-4B) |
182
+ | LaSER-Qwen3-8B | 8B | 29.3 | [πŸ€— Link](https://huggingface.co/Alibaba-NLP/LaSER-Qwen3-8B) |
183
+
184
+ ## Citation
185
+
186
+ ```bibtex
187
+ @article{jin2026laser,
188
+ title={LaSER: Internalizing Explicit Reasoning into Latent Space for Dense Retrieval},
189
+ author={Jin, Jiajie and Zhang, Yanzhao and Li, Mingxin and Long, Dingkun and Xie, Pengjun and Zhu, Yutao and Dou, Zhicheng},
190
+ year={2026},
191
+ journal={arXiv preprint},
192
+ url={https://arxiv.org/abs/2603.01425},
193
+ }
194
+ ```