File size: 8,022 Bytes
10d5c2f
 
 
 
 
 
390bfe1
10d5c2f
4d28d18
 
 
 
 
 
4cbf73f
4d28d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1828d76
 
 
 
 
 
 
4d28d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1828d76
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
---
license: apache-2.0
datasets:
- daily_dialog
language:
- en
pipeline_tag: text-retrieval
---

<p align="center">
  <img align="center" src="img/triple-encoder-logo_with_border.png" width="430px" />
</p>

<p align="center">
    πŸ—οΈ <a href="https://github.com/UKPLab/arxiv2024-triple-encoders" target="_blank">GitHub repo</a> | πŸ“ƒ <a href="https://aclanthology.org/2024.acl-long.290/" target="_blank">Paper</a>
</p>

`triple-encoders` are models for contextualizing distributed [Sentence Transformers](https://sbert.net/) representations. This model was trained on the [DailyDialog](https://huggingface.co/datasets/daily_dialog) dataset and can be used for conversational sequence modeling and short-term planning via sequential modular late-interaction:
<p align="center">
  <img align="center" src="img/triple-encoder.jpg" width="1000px" />
</p>

Representations are encoded **separately** and the contextualization is **weightless**:
1. *mean-pooling* to pairwise contextualize sentence representations (creates a distributed query)
2. *cosine similarity* to measure the similarity between all query vectors and the retrieval candidates.
3. *summation* to aggregate the similarity (similar to average-based late interaction of [ColBERT](https://github.com/stanford-futuredata/ColBERT)).

## Key Features
- 1️⃣ **One dense vector vs distributed dense vectors**: in our paper we demonstrate that our late interaction-based approach outperforms single-vector representations on long sequences, including zero-shot settings.
- πŸŽοΈπŸ’¨ **Relative compute**: as every representation is encoded separately, you only need to encode, compute mixtures and similarities for the latest added representation (in dialog: the latest utterance). 
- πŸ“š **No Limit on context-length**: our distributed sentence transformer architecture is not limited to any sequence length. You can use your entire sequence as query!
- 🌎 **Multilingual support**: `triple-encoders` can be used with any [Sentence Transformers](https://sbert.net/) model. This means that you can model multilingual sequences by simply training on a multilingual model checkpoint. 


## Installation
You can install `triple-encoders` via pip:
```bash
pip install triple-encoders
``` 
Note that `triple-encoders` requires Python 3.6 or higher.

# Getting Started

Our experiments for sequence modeling and short-term planning conducted in the paper can be found in the `notebooks` folder. The hyperparameter that we used for training are the default parameters in the `trainer.py` file.

## Retrieval-based Sequence Modeling
We provide an example of how to use triple-encoders for conversational sequence modeling (response selection) with 2 dialog speakers. If you want to use triple-encoders for other sequence modeling tasks, you can use the `TripleEncodersForSequenceModeling` class.

### Loading the model
```python
from triple_encoders.TripleEncodersForConversationalSequenceModeling import TripleEncodersForConversationalSequenceModeling

triple_path = 'UKPLab/triple-encoders-dailydialog'

# load model
model = TripleEncodersForConversationalSequenceModeling(triple_path)
```

### Inference

```python
# load candidates for response selection 
candidates = ['I am doing great too!','Where did you go?', 'ACL is an interesting conference']

# load candidates and store index
model.load_candidates_from_strings(candidates, output_directory_candidates_dump='output/path/to/save/candidates')

# create a sequence
sequence = model.contextualize_sequence(["Hi!",'Hey, how are you?'], k_last_rows=2)

# model sequence (compute scores for candidates)
sequence = model.sequence_modeling(sequence)

# retrieve utterance from dialog partner
new_utterance = "I'm fine, thanks. How are you?"

# pass it to the model with dialog_partner=True 
sequence = model.contextualize_utterance(new_utterance, sequence, dialog_partner=True)

# model sequence (compute scores for candidates)
sequence = model.sequence_modeling(sequence)

# retrieve candidates to provide a response
response = model.retrieve_candidates(sequence, 3)
response
#(['I am doing great too!','Where did you go?', 'ACL is an interesting conference'],
# tensor([0.4944, 0.2392, 0.0483]))
```
**Speed:** 
- Time to load candidates: 31.815 ms
- Time to contextualize sequence: 18.078 ms
- Time to model sequence: 0.256 ms
- Time to contextualize new utterance: 15.858 ms
- Time to model new utterance: 0.213 ms
- Time to retrieve candidates: 0.093 ms

### Evaluation
```python
from datasets import load_dataset

dataset = load_dataset("daily_dialog")
test = dataset['test']['dialog']

df = model.evaluate_seq_dataset(test, k_last_rows=2)
df
# pandas dataframe with the average rank for each history length
```

## Short-Term Planning (STP)
Short-term planning enables you to re-rank candidate replies from LLMs to reach a goal utterance over multiple turns.

### Inference

```python
from triple_encoders.TripleEncodersForSTP import TripleEncodersForSTP

model = TripleEncodersForSTP(triple_path)

context = ['Hey, how are you ?',
           'I am good, how about you ?',
           'I am good too.']

candidates = ['Want to eat something out ?',
              'Want to go for a walk ?']

goal = ' I am hungry.'

result = model.short_term_planning(candidates, goal, context)

result
# 'Want to eat something out ?'
```
### Evaluation

```python
from datasets import load_dataset
from triple_encoders.TripleEncodersForSTP import TripleEncodersForSTP

dataset = load_dataset("daily_dialog")
test = dataset['test']['dialog']

model = TripleEncodersForSTP(triple_path, llm_model_name_or_path='your favorite large language model')

df = model.evaluate_stp_dataset(test)
# pandas dataframe with the average rank and Hits@k for each history length, goal_distance
```


# Training Triple Encoders
You can train your own triple encoders with Contextualized Curved Contrastive Learning (C3L) using our trainer. 
The hyperparameters that we used for training are the default parameters in the `trainer.py` file. 
Note that we pre-trained our best model with Curved Contrastive Learning (CCL) (from [imaginaryNLP](https://github.com/Justus-Jonas/imaginaryNLP)) before training with C3L.

```python
from triple_encoders.trainer import TripleEncoderTrainer
from datasets import load_dataset

dataset = load_dataset("daily_dialog")

trainer = TripleEncoderTrainer(base_model_name_or_path=,
                               batch_size=48,
                               observation_window=5,
                               speaker_token=True, # used for conversational sequence modeling
                               num_epochs=3,
                               warmup_steps=10000)

trainer.generate_datasets(
    dataset["train"]["dialog"],
    dataset["validation"]["dialog"],
    dataset["test"]["dialog"],
)


trainer.train("output/path/to/save/model")
```
## Citation
If you use triple-encoders in your research, please cite the following paper:
```
@misc{erker2024tripleencoders,
      title={Triple-Encoders: Representations That Fire Together, Wire Together}, 
      author={Justus-Jonas Erker and Florian Mai and Nils Reimers and Gerasimos Spanakis and Iryna Gurevych},
      year={2024},
      eprint={2402.12332},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}
```
# Contact
Contact person: Justus-Jonas Erker, [email protected]

https://www.ukp.tu-darmstadt.de/

https://www.tu-darmstadt.de/

Don't hesitate to send us an e-mail or report an issue, if something is broken (and it shouldn't be) or if you have further questions.
This repository contains experimental software and is published for the sole purpose of giving additional background details on the respective publication. 

# License
triple-encoders is licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) for the full license text.


### Acknowledgement
our package is based upon the [imaginaryNLP](https://github.com/Justus-Jonas/imaginaryNLP) and [Sentence Transformers](https://sbert.net/).