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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
//! # Special Words Vocabulary
use crate::{
WCResult,
alloc::vec::Vec,
support::{
regex::{
RegexPattern,
alternate_choice_regex_pattern,
},
strings::string_from_utf8_lossy,
},
types::{
TokenType,
WCHashSet,
},
vocab::{
SpanTokenMap,
VocabIndex,
utility::validators::try_vocab_size,
},
};
/// Token vocabulary for special words.
///
/// This contains no byte:token mappings, or pair mergers.
#[derive(Default, Debug, Clone, PartialEq)]
pub struct SpecialVocab<T: TokenType> {
/// The map of special words to tokens.
span_map: SpanTokenMap<T>,
}
impl<T: TokenType> From<SpanTokenMap<T>> for SpecialVocab<T> {
fn from(span_map: SpanTokenMap<T>) -> Self {
Self::from_map(span_map)
}
}
impl<T: TokenType> SpecialVocab<T> {
/// Create a new special words vocab.
///
/// ## Arguments
/// * `span_map` - A mapping of byte spans to tokens.
///
/// ## Returns
/// A new `SpecialVocab` instance.
pub fn from_map(span_map: SpanTokenMap<T>) -> Self {
Self { span_map }
}
/// Get the span map.
pub fn span_map(&self) -> &SpanTokenMap<T> {
&self.span_map
}
/// Get the number of special words in the vocab.
pub fn len(&self) -> usize {
self.span_map.len()
}
/// Check if the vocab is empty.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Convert to a different token type.
pub fn to_token_type<G: TokenType>(&self) -> WCResult<SpecialVocab<G>> {
if let Some(max) = self.max_token() {
try_vocab_size::<G>(max.to_usize().unwrap() + 1)?;
}
Ok(SpecialVocab::<G>::from_map(
self.span_map
.iter()
.map(|(chunk, &token)| (chunk.clone(), G::from(token).unwrap()))
.collect(),
))
}
/// Add a word to the vocab.
///
/// ## Arguments
/// * `word` - The word string to add.
/// * `token` - The token value to assign to the word.
pub fn add_str_word(
&mut self,
word: &str,
token: T,
) {
self.span_map.insert(word.as_bytes().to_vec(), token);
}
/// Extend the vocabulary with the given special words.
///
/// ## Arguments
/// * `special_words` - An iterator of word strings and tokens.
///
/// ## Returns
/// The updated `SpecialVocab` instance.
pub fn with_special_words<W, S>(
self,
special_words: W,
) -> Self
where
W: IntoIterator<Item = (S, T)>,
S: AsRef<str>,
{
let mut vocab = self;
for (word, token) in special_words {
vocab.add_str_word(word.as_ref(), token);
}
vocab
}
/// Return the associated token for the word, if any.
///
/// ## Arguments
/// * `chunk` - The byte slice to look up.
///
/// ## Returns
/// An `Option` containing the token if the span exists in the special
/// vocabulary.
pub fn lookup_token(
&self,
chunk: &[u8],
) -> Option<T> {
self.span_map.get(chunk).copied()
}
/// Get the associated span for a token, if any.
pub fn lookup_span(
&self,
token: &T,
) -> Option<&[u8]> {
self.span_map.iter().find_map(|(chunk, &t)| {
if t == *token {
Some(chunk.as_ref())
} else {
None
}
})
}
/// Get the regex pattern for special words.
///
/// ## Returns
/// `None` if no special words are present;
/// and `Some(RegexPattern)` otherwise.
pub fn special_pattern(&self) -> Option<RegexPattern> {
if self.is_empty() {
return None;
}
let alts = self
.span_map
.keys()
.map(|k| string_from_utf8_lossy(k.clone()))
.collect::<Vec<_>>();
Some(alternate_choice_regex_pattern(&alts))
}
}
impl<T: TokenType> VocabIndex<T> for SpecialVocab<T> {
type Token = T;
fn len(&self) -> usize {
self.span_map.len()
}
fn tokens(&self) -> WCHashSet<T> {
self.span_map.values().copied().collect()
}
fn max_token(&self) -> Option<T> {
self.span_map.values().max().copied()
}
fn span_pairs(&self) -> impl Iterator<Item = (Vec<u8>, T)> {
self.span_map
.iter()
.map(|(chunk, &token)| (chunk.clone(), token))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_special_vocab() {
type T = u32;
let mut vocab: SpecialVocab<T> = SpecialVocab::default();
assert!(vocab.is_empty());
assert_eq!(vocab.len(), 0);
vocab.add_str_word("hello", 1);
assert_eq!(vocab.len(), 1);
assert!(!vocab.is_empty());
assert_eq!(
&vocab.span_map,
&[("hello".as_bytes().to_vec(), 1)].into_iter().collect()
);
let rebuild: SpecialVocab<T> = vocab.span_map.clone().into();
assert_eq!(rebuild, vocab);
}
#[test]
fn test_to_token_type_accepts_minimum_vocab_size() {
let vocab = SpecialVocab::<u32>::from_map(
[("special".as_bytes().to_vec(), 255_u32)]
.into_iter()
.collect(),
);
let converted = vocab.to_token_type::<u8>().unwrap();
assert_eq!(converted.max_token(), Some(255));
assert_eq!(converted.lookup_token(b"special"), Some(255));
}
}