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
pub(crate) mod simple;
pub(crate) mod subword;
use std::borrow::Borrow;
use std::collections::HashMap;
use std::hash::Hash;
use crate::idx::WordIdx;
const BOW: char = '<';
const EOW: char = '>';
pub type Word = CountedType<String>;
#[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct CountedType<T> {
count: usize,
label: T,
}
impl<T> CountedType<T> {
pub fn new(label: T, count: usize) -> Self {
CountedType { label, count }
}
pub fn count(&self) -> usize {
self.count
}
pub fn label(&self) -> &T {
&self.label
}
}
impl CountedType<String> {
pub fn word(&self) -> &str {
&self.label
}
}
pub trait Vocab {
type VocabType: Hash + Eq;
type IdxType: WordIdx;
type Config;
fn config(&self) -> Self::Config;
fn is_empty(&self) -> bool {
self.len() == 0
}
fn len(&self) -> usize {
self.types().len()
}
fn idx<Q>(&self, key: &Q) -> Option<Self::IdxType>
where
Self::VocabType: Borrow<Q>,
Q: Hash + ?Sized + Eq;
fn discard(&self, idx: usize) -> f32;
fn n_input_types(&self) -> usize;
fn types(&self) -> &[CountedType<Self::VocabType>];
fn n_types(&self) -> usize;
}
pub struct VocabBuilder<C, T> {
config: C,
items: HashMap<T, usize>,
n_items: usize,
}
impl<C, T> VocabBuilder<C, T>
where
T: Hash + Eq,
{
pub fn new(config: C) -> Self {
VocabBuilder {
config,
items: HashMap::new(),
n_items: 0,
}
}
pub fn count<S>(&mut self, item: S)
where
S: Into<T>,
{
self.n_items += 1;
let cnt = self.items.entry(item.into()).or_insert(0);
*cnt += 1;
}
}
pub(crate) fn create_discards<S>(
discard_threshold: f32,
types: &[CountedType<S>],
n_tokens: usize,
) -> Vec<f32> {
let mut discards = Vec::with_capacity(types.len());
for item in types {
let p = item.count() as f32 / n_tokens as f32;
let p_discard = discard_threshold / p + (discard_threshold / p).sqrt();
discards.push(1f32.min(p_discard));
}
discards
}
pub(crate) fn create_indices<S>(types: &[CountedType<S>]) -> HashMap<S, usize>
where
S: Hash + Eq + Clone,
{
let mut token_indices = HashMap::new();
for (idx, item) in types.iter().enumerate() {
token_indices.insert(item.label.clone(), idx);
}
assert_eq!(types.len(), token_indices.len());
token_indices
}
pub(crate) fn bracket(word: &str) -> String {
let mut bracketed = String::new();
bracketed.push(BOW);
bracketed.push_str(word);
bracketed.push(EOW);
bracketed
}