Spaces:
Runtime error
Runtime error
File size: 5,482 Bytes
10b912d |
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 |
import random
import numpy as np
from nltk import word_tokenize
from collections import defaultdict
from copy import deepcopy
import tqdm
class PunktTokenizer:
def __call__(self, texts):
return [word_tokenize(t) for t in texts]
class WhiteSpaceTokenizer:
def __call__(self, texts):
return [t.split() for t in texts]
class SearchState:
def __init__(self, tokens):
self.tokens = tokens
self.masks = []
self.mask_set = set()
self.summaries = []
self.scores = []
self.best_step = None
self.terminated = False
self.step = 0
def update(self, mask, summary, score):
if self.best_step is None or score > self.best_score():
self.best_step = self.step
self.masks.append(mask)
self.mask_set.add(tuple(mask))
self.summaries.append(summary)
self.scores.append(score)
self.step += 1
def best_mask(self):
return self.masks[self.best_step]
def best_score(self):
return self.scores[self.best_step]
def best_summary(self):
return self.summaries[self.best_step]
def to_dict(self):
return {
"scores": self.scores,
"masks": self.masks,
"summaries": self.summaries,
"best_summary": self.best_summary(),
"best_score": self.best_score(),
}
class DynamicRestartHCSC:
def __init__(self, tokenizer, objective):
self.tokenizer = tokenizer
self.objective = objective
self.n_trials = 100
def _mask_to_summary(self, mask, tokens):
summary = [tokens[i] for i in range(len(mask)) if mask[i] == 1]
return " ".join(summary)
def _sample(self, state, sent_len, target_len, from_scratch=False):
"""
Swaps one selected word for another, discarding previous solutions.
"""
if target_len >= sent_len:
mask = [1 for _ in range(sent_len)]
state.terminated = True
return mask, True
if state.step == 0 or from_scratch:
indices = list(range(sent_len))
sampled = set(random.sample(indices, min(target_len, sent_len)))
mask = [int(i in sampled) for i in indices]
return mask, False
else:
mask = state.masks[state.best_step]
indices = list(range(len(mask)))
one_indices = [i for i in range(len(mask)) if mask[i] == 1]
zero_indices = [i for i in range(len(mask)) if mask[i] == 0]
if len(zero_indices) == 0:
return mask
terminated = True
# trying to find unknown state, heuristically with fixed no. trials
for _ in range(self.n_trials):
i = random.choice(one_indices)
j = random.choice(zero_indices)
new_mask = mask.copy()
new_mask[i] = 0
new_mask[j] = 1
if tuple(new_mask) not in state.mask_set:
terminated = False
mask = new_mask
break
# terminate if no unknown neighbor state is found
return mask, terminated
def aggregate_states(self, states):
masks = [m for s in states for m in s.masks]
summaries = [x for s in states for x in s.summaries]
scores = [x for s in states for x in s.scores]
best_step = np.argmax(scores)
return {
"masks": masks,
"summaries": summaries,
"scores": scores,
"best_score": scores[best_step],
"best_summary": summaries[best_step],
}
def __call__(
self,
sentences,
target_lens,
n_steps=100,
verbose=False,
return_states=False,
):
tok_sentences = self.tokenizer(sentences)
batch_size = len(sentences)
terminated_states = [[] for _ in range(batch_size)]
states = [SearchState(s) for s in tok_sentences]
for t in tqdm.tqdm(list(range(1, n_steps + 1))):
masks = []
for i in range(batch_size):
if states[i].terminated:
if verbose:
print(f"step {t}, restarting state {i} with score {states[i].best_score()}")
terminated_states[i].append(states[i])
states[i] = SearchState(tok_sentences[i])
mask, terminated = self._sample(
states[i],
sent_len=len(tok_sentences[i]),
target_len=target_lens[i],
)
states[i].terminated = terminated
masks.append(mask)
summaries = [
self._mask_to_summary(m, tokens)
for m, tokens in zip(masks, tok_sentences)
]
scores, _ = self.objective(sentences, summaries)
if verbose:
print(f"t={t}")
for i in range(batch_size):
print(f"[{scores[i]:.3f}][{summaries[i]}]")
print()
for i in range(batch_size):
states[i].update(masks[i], summaries[i], scores[i])
for i in range(batch_size):
terminated_states[i].append(states[i])
output_states = [
self.aggregate_states(i_states) for i_states in terminated_states
]
return output_states
|