divergent-beamsearch 0.1.0__tar.gz → 0.1.2__tar.gz
Sign up to get free protection for your applications and to get access to all the features.
- {divergent_beamsearch-0.1.0 → divergent_beamsearch-0.1.2}/.gitignore +5 -4
- {divergent_beamsearch-0.1.0 → divergent_beamsearch-0.1.2}/LICENCE +20 -20
- {divergent_beamsearch-0.1.0 → divergent_beamsearch-0.1.2}/PKG-INFO +2 -2
- {divergent_beamsearch-0.1.0 → divergent_beamsearch-0.1.2}/README.md +67 -67
- {divergent_beamsearch-0.1.0 → divergent_beamsearch-0.1.2}/pyproject.toml +2 -2
- {divergent_beamsearch-0.1.0 → divergent_beamsearch-0.1.2}/src/divergent_beamsearch/algorithm.py +146 -112
- divergent_beamsearch-0.1.2/tests/test_beamsearch.py +125 -0
- {divergent_beamsearch-0.1.0 → divergent_beamsearch-0.1.2}/uv.lock +2 -2
- divergent_beamsearch-0.1.0/tests/test_beamsearch.py +0 -41
- {divergent_beamsearch-0.1.0 → divergent_beamsearch-0.1.2}/.python-version +0 -0
- {divergent_beamsearch-0.1.0 → divergent_beamsearch-0.1.2}/src/divergent_beamsearch/__init__.py +0 -0
@@ -1,4 +1,5 @@
|
|
1
|
-
**/__pycache__
|
2
|
-
.pytest_cache
|
3
|
-
.vscode
|
4
|
-
.venv
|
1
|
+
**/__pycache__
|
2
|
+
.pytest_cache
|
3
|
+
.vscode
|
4
|
+
.venv
|
5
|
+
dist
|
@@ -1,21 +1,21 @@
|
|
1
|
-
MIT License
|
2
|
-
|
3
|
-
Copyright (c) 2025 Hichem Ammar Khodja
|
4
|
-
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
7
|
-
in the Software without restriction, including without limitation the rights
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
10
|
-
furnished to do so, subject to the following conditions:
|
11
|
-
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
13
|
-
copies or substantial portions of the Software.
|
14
|
-
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
1
|
+
MIT License
|
2
|
+
|
3
|
+
Copyright (c) 2025 Hichem Ammar Khodja
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
13
|
+
copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21
21
|
SOFTWARE.
|
@@ -1,11 +1,11 @@
|
|
1
1
|
Metadata-Version: 2.4
|
2
2
|
Name: divergent-beamsearch
|
3
|
-
Version: 0.1.
|
3
|
+
Version: 0.1.2
|
4
4
|
Summary: A variant of the beam search algorithm that focuses on finding answers that maximize the probability of generating an answer before diverging into another subject.
|
5
5
|
License-File: LICENCE
|
6
6
|
Requires-Python: >=3.11
|
7
7
|
Requires-Dist: multi-choices-parser>=0.9.57
|
8
|
-
Requires-Dist: torch>=2.
|
8
|
+
Requires-Dist: torch>=2.0.0
|
9
9
|
Requires-Dist: transformers>=4.47.1
|
10
10
|
Description-Content-Type: text/markdown
|
11
11
|
|
@@ -1,67 +1,67 @@
|
|
1
|
-
# Divergent Beam Search
|
2
|
-
## Overview
|
3
|
-
|
4
|
-
Divergent Beam Search is a variant of the beam search algorithm. Unlike the beam search where answers are constrained, which aims to find the answers with the highest probability of appearing, Divergent Beam Search focuses on finding answers that are not likely to be continued with another answer. Essentially, it finds the answers that maximize the probability of generating an answer before diverging into another subject given the prompt.
|
5
|
-
|
6
|
-
The core idea of this algorithm can be roughly summarized in the following optimization problem:
|
7
|
-
|
8
|
-
$$\max_{ans \in A} P(ans + diverging\ into\ another\ subject \mid prompt)$$
|
9
|
-
|
10
|
-
It is important that the set of answers $A$ is sufficiently exhaustive for this method to work. Otherwise, the algorithm could unjustifiably conclude that an answer is not being followed by the answer while this longer answer exists but is not included in the set $A$.
|
11
|
-
|
12
|
-
## Installation
|
13
|
-
|
14
|
-
To install the package, use the following command:
|
15
|
-
|
16
|
-
```bash
|
17
|
-
pip install divergent-beamsearch
|
18
|
-
```
|
19
|
-
|
20
|
-
## Usage
|
21
|
-
|
22
|
-
Here's a brief example of how to use `divergent-beamsearch`:
|
23
|
-
|
24
|
-
```python
|
25
|
-
import torch
|
26
|
-
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
27
|
-
from multi_choices_parser import MultiChoicesParser
|
28
|
-
from divergent_beamsearch import divergent_beamsearch
|
29
|
-
|
30
|
-
# Load model and tokenizer
|
31
|
-
model = GPT2LMHeadModel.from_pretrained("gpt2")
|
32
|
-
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
|
33
|
-
|
34
|
-
# Define input prompt
|
35
|
-
prompt = "The capital of France is"
|
36
|
-
input_ids = tokenizer.encode(prompt, return_tensors="pt")
|
37
|
-
|
38
|
-
# Define beam search parameters
|
39
|
-
beam_size = 5
|
40
|
-
max_length = 10
|
41
|
-
pad_token_id = tokenizer.eos_token_id
|
42
|
-
|
43
|
-
# Define possible answers
|
44
|
-
possible_answers = [' Paris', ' Paris Hilton']
|
45
|
-
tokenized_answers = tokenizer(possible_answers).input_ids
|
46
|
-
multi_choices_parser = MultiChoicesParser([tokenized_answers])
|
47
|
-
|
48
|
-
# Perform beam search
|
49
|
-
scores, solutions = divergent_beamsearch(
|
50
|
-
input_ids=input_ids,
|
51
|
-
model=model,
|
52
|
-
beam_size=beam_size,
|
53
|
-
max_length=max_length,
|
54
|
-
multi_choices_parser=multi_choices_parser,
|
55
|
-
pad_token_id=pad_token_id,
|
56
|
-
num_solutions=2
|
57
|
-
)
|
58
|
-
|
59
|
-
# Decode solutions
|
60
|
-
decoded_solutions = [tokenizer.decode(solution, skip_special_tokens=True) for solution in solutions]
|
61
|
-
print("Scores:", scores)
|
62
|
-
print("Solutions:", decoded_solutions)
|
63
|
-
```
|
64
|
-
|
65
|
-
## License
|
66
|
-
|
67
|
-
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
|
1
|
+
# Divergent Beam Search
|
2
|
+
## Overview
|
3
|
+
|
4
|
+
Divergent Beam Search is a variant of the beam search algorithm. Unlike the beam search where answers are constrained, which aims to find the answers with the highest probability of appearing, Divergent Beam Search focuses on finding answers that are not likely to be continued with another answer. Essentially, it finds the answers that maximize the probability of generating an answer before diverging into another subject given the prompt.
|
5
|
+
|
6
|
+
The core idea of this algorithm can be roughly summarized in the following optimization problem:
|
7
|
+
|
8
|
+
$$\max_{ans \in A} P(ans + diverging\ into\ another\ subject \mid prompt)$$
|
9
|
+
|
10
|
+
It is important that the set of answers $A$ is sufficiently exhaustive for this method to work. Otherwise, the algorithm could unjustifiably conclude that an answer is not being followed by the answer while this longer answer exists but is not included in the set $A$.
|
11
|
+
|
12
|
+
## Installation
|
13
|
+
|
14
|
+
To install the package, use the following command:
|
15
|
+
|
16
|
+
```bash
|
17
|
+
pip install divergent-beamsearch
|
18
|
+
```
|
19
|
+
|
20
|
+
## Usage
|
21
|
+
|
22
|
+
Here's a brief example of how to use `divergent-beamsearch`:
|
23
|
+
|
24
|
+
```python
|
25
|
+
import torch
|
26
|
+
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
27
|
+
from multi_choices_parser import MultiChoicesParser
|
28
|
+
from divergent_beamsearch import divergent_beamsearch
|
29
|
+
|
30
|
+
# Load model and tokenizer
|
31
|
+
model = GPT2LMHeadModel.from_pretrained("gpt2")
|
32
|
+
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
|
33
|
+
|
34
|
+
# Define input prompt
|
35
|
+
prompt = "The capital of France is"
|
36
|
+
input_ids = tokenizer.encode(prompt, return_tensors="pt")
|
37
|
+
|
38
|
+
# Define beam search parameters
|
39
|
+
beam_size = 5
|
40
|
+
max_length = 10
|
41
|
+
pad_token_id = tokenizer.eos_token_id
|
42
|
+
|
43
|
+
# Define possible answers
|
44
|
+
possible_answers = [' Paris', ' Paris Hilton']
|
45
|
+
tokenized_answers = tokenizer(possible_answers).input_ids
|
46
|
+
multi_choices_parser = MultiChoicesParser([tokenized_answers])
|
47
|
+
|
48
|
+
# Perform beam search
|
49
|
+
scores, solutions = divergent_beamsearch(
|
50
|
+
input_ids=input_ids,
|
51
|
+
model=model,
|
52
|
+
beam_size=beam_size,
|
53
|
+
max_length=max_length,
|
54
|
+
multi_choices_parser=multi_choices_parser,
|
55
|
+
pad_token_id=pad_token_id,
|
56
|
+
num_solutions=2
|
57
|
+
)
|
58
|
+
|
59
|
+
# Decode solutions
|
60
|
+
decoded_solutions = [tokenizer.decode(solution, skip_special_tokens=True) for solution in solutions]
|
61
|
+
print("Scores:", scores)
|
62
|
+
print("Solutions:", decoded_solutions)
|
63
|
+
```
|
64
|
+
|
65
|
+
## License
|
66
|
+
|
67
|
+
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
|
@@ -1,12 +1,12 @@
|
|
1
1
|
[project]
|
2
2
|
name = "divergent-beamsearch"
|
3
|
-
version = "0.1.
|
3
|
+
version = "0.1.2"
|
4
4
|
description = "A variant of the beam search algorithm that focuses on finding answers that maximize the probability of generating an answer before diverging into another subject."
|
5
5
|
readme = "README.md"
|
6
6
|
requires-python = ">=3.11"
|
7
7
|
dependencies = [
|
8
8
|
"multi-choices-parser>=0.9.57",
|
9
|
-
"torch>=2.
|
9
|
+
"torch>=2.0.0",
|
10
10
|
"transformers>=4.47.1",
|
11
11
|
]
|
12
12
|
|
{divergent_beamsearch-0.1.0 → divergent_beamsearch-0.1.2}/src/divergent_beamsearch/algorithm.py
RENAMED
@@ -1,112 +1,146 @@
|
|
1
|
-
import math
|
2
|
-
import torch
|
3
|
-
from transformers import GPT2LMHeadModel
|
4
|
-
from multi_choices_parser import MultiChoicesParser, end_symb
|
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
|
-
|
1
|
+
import math
|
2
|
+
import torch
|
3
|
+
from transformers import GPT2LMHeadModel
|
4
|
+
from multi_choices_parser import MultiChoicesParser, end_symb
|
5
|
+
|
6
|
+
|
7
|
+
class Parser:
|
8
|
+
def step(self, token):
|
9
|
+
raise NotImplementedError
|
10
|
+
|
11
|
+
def next(self):
|
12
|
+
raise NotImplementedError
|
13
|
+
|
14
|
+
def copy(self):
|
15
|
+
raise NotImplementedError
|
16
|
+
|
17
|
+
def get_parsers_tokens(parsers : list[Parser]) -> tuple[list, list[int]]:
|
18
|
+
parsers_tokens = []
|
19
|
+
can_end = []
|
20
|
+
for parser in parsers:
|
21
|
+
tokens = list(parser.next())
|
22
|
+
if end_symb in tokens:
|
23
|
+
can_end.append(True)
|
24
|
+
tokens.remove(end_symb)
|
25
|
+
else:
|
26
|
+
can_end.append(False)
|
27
|
+
parsers_tokens.append(tokens)
|
28
|
+
return parsers_tokens, can_end
|
29
|
+
|
30
|
+
def apply_mask_tokens(pred : torch.Tensor, parsers_tokens):
|
31
|
+
mask = torch.ones_like(pred, dtype=torch.bool)
|
32
|
+
for tokens in parsers_tokens:
|
33
|
+
mask[:, tokens] = False
|
34
|
+
pred[mask] = -float('inf')
|
35
|
+
return pred[~pred.isinf().all(dim=-1)]
|
36
|
+
|
37
|
+
|
38
|
+
def batched_inference_logits(model : GPT2LMHeadModel, input_ids : torch.Tensor, batch_size : int = 32) -> torch.Tensor:
|
39
|
+
logits = []
|
40
|
+
for i in range(0, input_ids.shape[0], batch_size):
|
41
|
+
logits.append(model(input_ids[i:i+batch_size]).logits)
|
42
|
+
return torch.cat(logits, dim=0)
|
43
|
+
|
44
|
+
def select_mask(source : list, mask : list[bool]) -> list:
|
45
|
+
assert len(source) == len(mask)
|
46
|
+
return [x for x, m in zip(source, mask) if m]
|
47
|
+
|
48
|
+
|
49
|
+
def log1mexp(x: torch.Tensor) -> torch.Tensor:
|
50
|
+
"""Numerically accurate evaluation of log(1 - exp(x)) for x < 0.
|
51
|
+
See [Maechler2012accurate]_ for details.
|
52
|
+
"""
|
53
|
+
mask = -math.log(2) < x # x < 0
|
54
|
+
return torch.where(
|
55
|
+
mask,
|
56
|
+
(-x.expm1()).log(),
|
57
|
+
(-x.exp()).log1p(),
|
58
|
+
)
|
59
|
+
|
60
|
+
|
61
|
+
|
62
|
+
|
63
|
+
class AcceptEverythingParser(Parser):
|
64
|
+
def __init__(self, vocab_size : int):
|
65
|
+
self.vocab_size = vocab_size
|
66
|
+
self.tokens = tuple(range(vocab_size))
|
67
|
+
|
68
|
+
def step(self, token):
|
69
|
+
pass
|
70
|
+
|
71
|
+
def next(self):
|
72
|
+
return self.tokens
|
73
|
+
|
74
|
+
def copy(self):
|
75
|
+
return self
|
76
|
+
|
77
|
+
@torch.no_grad()
|
78
|
+
def divergent_beamsearch(input_ids : torch.Tensor, model : GPT2LMHeadModel, beam_size : int, max_length : int, parser : Parser, pad_token_id : int, batch_size=32, num_solutions = None) -> tuple[torch.Tensor, torch.Tensor]:
|
79
|
+
assert input_ids.shape[0] == 1, "Batch size must be 1"
|
80
|
+
device = input_ids.device
|
81
|
+
input_ids = input_ids.cpu()
|
82
|
+
|
83
|
+
if num_solutions is None:
|
84
|
+
num_solutions = beam_size
|
85
|
+
vanilla = parser is None
|
86
|
+
if vanilla:
|
87
|
+
parser = AcceptEverythingParser(model.config.vocab_size)
|
88
|
+
|
89
|
+
parsers_unfinished = [parser]
|
90
|
+
scores_finished = torch.tensor([], dtype=torch.float)
|
91
|
+
solutions_finished = torch.tensor([], dtype=torch.long).view(0,0)
|
92
|
+
|
93
|
+
input_ids_unfinished = input_ids
|
94
|
+
scores_unfinished = torch.tensor([0.0], dtype=torch.float)
|
95
|
+
solutions_unfinished = torch.tensor([], dtype=torch.long).view(1,0)
|
96
|
+
|
97
|
+
|
98
|
+
for _ in range(max_length):
|
99
|
+
if len(input_ids_unfinished) == 0:
|
100
|
+
break
|
101
|
+
pred = batched_inference_logits(model, input_ids_unfinished.to(device), batch_size)[:, -1].cpu()
|
102
|
+
parsers_tokens, can_end = get_parsers_tokens(parsers_unfinished)
|
103
|
+
logprobs = torch.log_softmax(pred, dim=-1)
|
104
|
+
logprobs_filtered = apply_mask_tokens(logprobs, parsers_tokens)
|
105
|
+
if len(logprobs_filtered):
|
106
|
+
topk = torch.topk(logprobs_filtered, beam_size, dim=-1) # shape (batch_size, beam_size)
|
107
|
+
values = topk.values + scores_unfinished.unsqueeze(-1)
|
108
|
+
topk_global = values.flatten().topk(beam_size)
|
109
|
+
best_tokens_row = topk_global.indices // beam_size
|
110
|
+
best_tokens, best_tokens_logprobs = topk.indices[best_tokens_row, topk_global.indices % beam_size], topk.values[best_tokens_row, topk_global.indices % beam_size]
|
111
|
+
notinf = ~best_tokens_logprobs.isinf()
|
112
|
+
best_tokens, best_tokens_row, best_tokens_logprobs = best_tokens[notinf], best_tokens_row[notinf], best_tokens_logprobs[notinf]
|
113
|
+
else:
|
114
|
+
best_tokens = torch.tensor([], dtype=torch.long)
|
115
|
+
best_tokens_row = torch.tensor([], dtype=torch.long)
|
116
|
+
best_tokens_logprobs = torch.tensor([], dtype=torch.float)
|
117
|
+
|
118
|
+
|
119
|
+
scores_finished_current = scores_unfinished[can_end]
|
120
|
+
solutions_finished_current = solutions_unfinished[can_end]
|
121
|
+
scores_finished_current = scores_finished_current + log1mexp(logprobs[can_end, select_mask(parsers_tokens, can_end)].logsumexp(dim=-1)).squeeze(-1)
|
122
|
+
scores_finished = torch.cat([scores_finished, scores_finished_current])
|
123
|
+
if len(solutions_finished_current):
|
124
|
+
pad = torch.full((len(scores_finished_current), solutions_finished_current.shape[1] - solutions_finished.shape[1]), pad_token_id, dtype=torch.long)
|
125
|
+
solutions_finished = torch.cat([solutions_finished.view(-1, solutions_finished_current.shape[1]+pad.shape[1]), torch.cat([solutions_finished_current, pad], dim=1)], dim=0)
|
126
|
+
if solutions_finished.numel():
|
127
|
+
# Keep num_solutions best solutions in finished
|
128
|
+
order = scores_finished.argsort(descending=True)
|
129
|
+
solutions_finished = solutions_finished[order][:num_solutions]
|
130
|
+
scores_finished = scores_finished[order][:num_solutions]
|
131
|
+
|
132
|
+
|
133
|
+
input_ids_unfinished = torch.cat([input_ids_unfinished[best_tokens_row], best_tokens.unsqueeze(-1)], dim=-1)
|
134
|
+
scores_unfinished = scores_unfinished[best_tokens_row] + best_tokens_logprobs
|
135
|
+
solutions_unfinished = torch.cat([solutions_unfinished[best_tokens_row], best_tokens.unsqueeze(-1)], dim=-1)
|
136
|
+
parsers_unfinished = [parsers_unfinished[row].copy() for row in best_tokens_row]
|
137
|
+
for parser, token in zip(parsers_unfinished, best_tokens.tolist()):
|
138
|
+
parser.step(token)
|
139
|
+
|
140
|
+
# Special case of vanilla beam search where all answers are valid
|
141
|
+
if vanilla:
|
142
|
+
order = scores_unfinished.argsort(descending=True)
|
143
|
+
scores_finished = scores_unfinished[order][:num_solutions]
|
144
|
+
solutions_finished = solutions_unfinished[order][:num_solutions]
|
145
|
+
|
146
|
+
return scores_finished, solutions_finished
|
@@ -0,0 +1,125 @@
|
|
1
|
+
import numpy as np
|
2
|
+
import pytest
|
3
|
+
import torch
|
4
|
+
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
5
|
+
from multi_choices_parser import MultiChoicesParser
|
6
|
+
from divergent_beamsearch.algorithm import divergent_beamsearch, log1mexp
|
7
|
+
from multi_choices_parser import MultiChoicesParser
|
8
|
+
|
9
|
+
@pytest.fixture
|
10
|
+
def model_and_tokenizer():
|
11
|
+
model = GPT2LMHeadModel.from_pretrained("gpt2")
|
12
|
+
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
|
13
|
+
return model, tokenizer
|
14
|
+
|
15
|
+
@pytest.mark.parametrize("device", ['cpu', 'cuda'])
|
16
|
+
def test_divergent_beamsearch(model_and_tokenizer, device):
|
17
|
+
if device == 'cuda' and not torch.cuda.is_available():
|
18
|
+
pytest.skip("CUDA is not available on this machine.")
|
19
|
+
model, tokenizer = model_and_tokenizer
|
20
|
+
model.to(device)
|
21
|
+
prompt = "The capital of France is"
|
22
|
+
input_ids = tokenizer.encode(prompt, return_tensors="pt").to(device)
|
23
|
+
beam_size = 5
|
24
|
+
max_length = 10
|
25
|
+
pad_token_id = tokenizer.eos_token_id
|
26
|
+
|
27
|
+
possible_answers = [' Paris', ' Paris Hilton']
|
28
|
+
tokenized_answers = tokenizer(possible_answers).input_ids
|
29
|
+
multi_choices_parser = MultiChoicesParser([tokenized_answers])
|
30
|
+
|
31
|
+
logprob_paris = model(input_ids).logits.cpu().log_softmax(dim=-1)[0, -1, tokenized_answers[0][0]]
|
32
|
+
logprob_hilton = model(torch.cat([input_ids, torch.tensor(tokenized_answers[1][0], device=device).view(1,1)], dim=-1)).logits.cpu().log_softmax(dim=-1)[0, -1, tokenized_answers[1][1]]
|
33
|
+
logprob_paris_hilton = logprob_paris + logprob_hilton
|
34
|
+
|
35
|
+
scores, solutions = divergent_beamsearch(
|
36
|
+
input_ids=input_ids,
|
37
|
+
model=model,
|
38
|
+
beam_size=beam_size,
|
39
|
+
max_length=max_length,
|
40
|
+
parser=multi_choices_parser,
|
41
|
+
pad_token_id=pad_token_id,
|
42
|
+
num_solutions=10
|
43
|
+
)
|
44
|
+
true_solutions = torch.nn.utils.rnn.pad_sequence([torch.tensor(ans) for ans in tokenized_answers], batch_first=True, padding_value=pad_token_id)
|
45
|
+
assert (solutions == true_solutions).all(), "Beam search did not return the expected solutions"
|
46
|
+
assert scores[0] == logprob_paris + log1mexp(logprob_hilton), "Beam search did not return the expected score"
|
47
|
+
assert scores[1] == logprob_paris_hilton, "Beam search did not return the expected score"
|
48
|
+
|
49
|
+
@pytest.mark.parametrize("device", ['cpu', 'cuda'])
|
50
|
+
def test_vanilla_beamsearch(model_and_tokenizer, device):
|
51
|
+
if device == 'cuda' and not torch.cuda.is_available():
|
52
|
+
pytest.skip("CUDA is not available on this machine.")
|
53
|
+
# Verify that divergent beam search where all answers are valid is equivalent to vanilla beam search
|
54
|
+
# Results of beam search were compared with huggingface implementation (https://huggingface.co/spaces/m-ric/beam_search_visualizer)
|
55
|
+
model, tok = model_and_tokenizer
|
56
|
+
model.to(device)
|
57
|
+
model.eval()
|
58
|
+
prompt = "The capital of France is"
|
59
|
+
input_ids = tok(prompt, return_tensors="pt").input_ids.to(device)
|
60
|
+
scores, sequences = divergent_beamsearch(
|
61
|
+
input_ids, model, beam_size=3, max_length=1, pad_token_id=tok.eos_token_id, num_solutions=3, parser=None
|
62
|
+
)
|
63
|
+
sequences = [tok.decode(s) for s in sequences]
|
64
|
+
assert sequences == [" the", " now", " a"]
|
65
|
+
assert np.isclose(
|
66
|
+
scores.cpu().numpy(), np.array([-2.4699, -3.0377, -3.0756]), atol=0.0001
|
67
|
+
).all()
|
68
|
+
|
69
|
+
scores, sequences = divergent_beamsearch(
|
70
|
+
input_ids, model, beam_size=3, max_length=2, pad_token_id=tok.eos_token_id, num_solutions=3, parser=None
|
71
|
+
)
|
72
|
+
sequences = [tok.decode(s) for s in sequences]
|
73
|
+
assert sequences == [" the capital", " now home", " now the"]
|
74
|
+
assert np.isclose(
|
75
|
+
scores.cpu().numpy(), np.array([-4.2437, -5.3013, -5.3408]), atol=0.0001
|
76
|
+
).all()
|
77
|
+
|
78
|
+
scores, sequences = divergent_beamsearch(
|
79
|
+
input_ids, model, beam_size=3, max_length=3, pad_token_id=tok.eos_token_id, num_solutions=3, parser=None
|
80
|
+
)
|
81
|
+
sequences = [tok.decode(s) for s in sequences]
|
82
|
+
assert sequences == [" the capital of", " now home to", " now the capital"]
|
83
|
+
assert np.isclose(
|
84
|
+
scores.cpu().numpy(), np.array([-4.3194, -5.3057, -7.7173]), atol=0.0001
|
85
|
+
).all()
|
86
|
+
|
87
|
+
scores, sequences = divergent_beamsearch(
|
88
|
+
input_ids, model, beam_size=3, max_length=4, pad_token_id=tok.eos_token_id, num_solutions=3, parser=None
|
89
|
+
)
|
90
|
+
sequences = [tok.decode(s) for s in sequences]
|
91
|
+
assert sequences == [
|
92
|
+
" the capital of the",
|
93
|
+
" the capital of France",
|
94
|
+
" the capital of a",
|
95
|
+
]
|
96
|
+
assert np.isclose(
|
97
|
+
scores.cpu().numpy(), np.array([-5.5825, -5.9150, -7.1716]), atol=0.0001
|
98
|
+
).all()
|
99
|
+
|
100
|
+
scores, sequences = divergent_beamsearch(
|
101
|
+
input_ids, model, beam_size=3, max_length=5, pad_token_id=tok.eos_token_id, num_solutions=3, parser=None
|
102
|
+
)
|
103
|
+
sequences = [tok.decode(s) for s in sequences]
|
104
|
+
assert sequences == [
|
105
|
+
" the capital of France,",
|
106
|
+
" the capital of France.",
|
107
|
+
" the capital of the French",
|
108
|
+
]
|
109
|
+
assert np.isclose(
|
110
|
+
scores.cpu().numpy(), np.array([-6.9453, -7.1549, -7.5727]), atol=0.0001
|
111
|
+
).all()
|
112
|
+
|
113
|
+
|
114
|
+
scores, sequences = divergent_beamsearch(
|
115
|
+
input_ids, model, beam_size=3, max_length=6, pad_token_id=tok.eos_token_id, num_solutions=3, parser=None
|
116
|
+
)
|
117
|
+
sequences = [tok.decode(s) for s in sequences]
|
118
|
+
assert sequences == [
|
119
|
+
" the capital of France, and",
|
120
|
+
" the capital of the French Republic",
|
121
|
+
" the capital of France. It",
|
122
|
+
]
|
123
|
+
assert np.isclose(
|
124
|
+
scores.cpu().numpy(), np.array([-8.1361, -8.7745, -9.1053]), atol=0.0001
|
125
|
+
).all()
|
@@ -73,7 +73,7 @@ wheels = [
|
|
73
73
|
|
74
74
|
[[package]]
|
75
75
|
name = "divergent-beamsearch"
|
76
|
-
version = "0.1.
|
76
|
+
version = "0.1.1"
|
77
77
|
source = { editable = "." }
|
78
78
|
dependencies = [
|
79
79
|
{ name = "multi-choices-parser" },
|
@@ -89,7 +89,7 @@ dev = [
|
|
89
89
|
[package.metadata]
|
90
90
|
requires-dist = [
|
91
91
|
{ name = "multi-choices-parser", specifier = ">=0.9.57" },
|
92
|
-
{ name = "torch", specifier = ">=2.
|
92
|
+
{ name = "torch", specifier = ">=2.0.0" },
|
93
93
|
{ name = "transformers", specifier = ">=4.47.1" },
|
94
94
|
]
|
95
95
|
|
@@ -1,41 +0,0 @@
|
|
1
|
-
import pytest
|
2
|
-
import torch
|
3
|
-
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
4
|
-
from multi_choices_parser import MultiChoicesParser
|
5
|
-
from divergent_beamsearch.algorithm import divergent_beamsearch, log1mexp
|
6
|
-
|
7
|
-
@pytest.fixture
|
8
|
-
def model_and_tokenizer():
|
9
|
-
model = GPT2LMHeadModel.from_pretrained("gpt2")
|
10
|
-
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
|
11
|
-
return model, tokenizer
|
12
|
-
|
13
|
-
def test_divergent_beamsearch(model_and_tokenizer):
|
14
|
-
model, tokenizer = model_and_tokenizer
|
15
|
-
prompt = "The capital of France is"
|
16
|
-
input_ids = tokenizer.encode(prompt, return_tensors="pt")
|
17
|
-
beam_size = 5
|
18
|
-
max_length = 10
|
19
|
-
pad_token_id = tokenizer.eos_token_id
|
20
|
-
|
21
|
-
possible_answers = [' Paris', ' Paris Hilton']
|
22
|
-
tokenized_answers = tokenizer(possible_answers).input_ids
|
23
|
-
multi_choices_parser = MultiChoicesParser([tokenized_answers])
|
24
|
-
|
25
|
-
logprob_paris = model(input_ids).logits.log_softmax(dim=-1)[0, -1, tokenized_answers[0][0]]
|
26
|
-
logprob_hilton = model(torch.cat([input_ids, torch.tensor(tokenized_answers[1][0]).view(1,1)], dim=-1)).logits.log_softmax(dim=-1)[0, -1, tokenized_answers[1][1]]
|
27
|
-
logprob_paris_hilton = logprob_paris + logprob_hilton
|
28
|
-
|
29
|
-
scores, solutions = divergent_beamsearch(
|
30
|
-
input_ids=input_ids,
|
31
|
-
model=model,
|
32
|
-
beam_size=beam_size,
|
33
|
-
max_length=max_length,
|
34
|
-
multi_choices_parser=multi_choices_parser,
|
35
|
-
pad_token_id=pad_token_id,
|
36
|
-
num_solutions=10
|
37
|
-
)
|
38
|
-
true_solutions = torch.nn.utils.rnn.pad_sequence([torch.tensor(ans) for ans in tokenized_answers], batch_first=True, padding_value=pad_token_id)
|
39
|
-
assert (solutions == true_solutions).all(), "Beam search did not return the expected solutions"
|
40
|
-
assert scores[0] == logprob_paris + log1mexp(logprob_hilton), "Beam search did not return the expected score"
|
41
|
-
assert scores[1] == logprob_paris_hilton, "Beam search did not return the expected score"
|
File without changes
|
{divergent_beamsearch-0.1.0 → divergent_beamsearch-0.1.2}/src/divergent_beamsearch/__init__.py
RENAMED
File without changes
|