1use std::collections::{HashMap, HashSet};
2use std::io::{self, Cursor, Read, Seek, SeekFrom};
3
4#[derive(Debug)]
5pub struct Model {
6 tk_output: HashMap<u16, Vec<i32>>, nb_numfeats: usize,
8 tk_nextmove: Vec<u16>,
9 norm_probs: bool,
10 data: ModelData,
11 used_data: Option<ModelData>,
12}
13
14#[derive(Debug)]
15pub struct ModelData {
16 pub nb_classes: Vec<String>, pub nb_ptc: Vec<Vec<f32>>, pub nb_pc: Vec<f32>, }
20
21pub enum Error {
22 UnknownLanguageCode(String),
23 NoLanguage,
24}
25
26impl Model {
27 fn data(&self) -> &ModelData {
28 if let Some(data) = &self.used_data {
29 data
30 } else {
31 &self.data
32 }
33 }
34}
35
36impl Model {
37 pub fn set_langs(&mut self, langs: Option<HashSet<String>>) -> Result<(), Error> {
38 if let Some(langs) = langs {
39 if langs.len() < 2 {
40 return Err(Error::NoLanguage);
41 }
42 let unknown = langs
43 .iter()
44 .find(|lang| !self.data.nb_classes.contains(&lang));
45 if let Some(lang) = unknown {
46 return Err(Error::UnknownLanguageCode(lang.to_owned()));
47 }
48 let subset_mask = self
49 .data
50 .nb_classes
51 .iter()
52 .map(|s| langs.contains(s))
53 .collect::<Vec<_>>();
54 let nb_classes = self
55 .data
56 .nb_classes
57 .iter()
58 .filter(|s| langs.contains(*s))
59 .cloned()
60 .collect::<Vec<_>>();
61 let nb_pc = self
62 .data
63 .nb_pc
64 .iter()
65 .zip(&subset_mask)
66 .filter(|(_, m)| **m)
67 .map(|v| *v.0)
68 .collect::<Vec<_>>();
69
70 let nb_ptc = self
71 .data
72 .nb_ptc
73 .iter()
74 .map(|v| {
75 v.iter()
76 .zip(&subset_mask)
77 .filter(|(_, m)| **m)
78 .map(|v| *v.0)
79 .collect::<Vec<_>>()
80 })
81 .collect::<Vec<_>>();
82 self.used_data = Some(ModelData {
83 nb_classes,
84 nb_ptc,
85 nb_pc,
86 });
87 } else {
88 self.used_data = None;
89 }
90 Ok(())
91 }
92
93 fn compute_softmax(&self, pd: &[f32]) -> Vec<f32> {
94 pd.iter()
95 .map(|vi| 1.0 / pd.iter().map(|vj| (vj - vi).exp()).sum::<f32>())
96 .collect()
97 }
98
99 fn apply_norm_probs(&self, pd: Vec<f32>) -> Vec<f32> {
100 if self.norm_probs {
101 self.compute_softmax(&pd)
102 } else {
103 pd
104 }
105 }
106
107 pub fn rank(&self, text: &str) -> Vec<(&str, f32)> {
109 let fv: Vec<u16> = self.instance2fv(text);
110 let probs: Vec<f32> = self.apply_norm_probs(self.nb_classprobs(fv));
111 let mut class_probs: Vec<(&str, f32)> = self
112 .data()
113 .nb_classes
114 .iter()
115 .map(|class| class.as_str())
116 .zip(probs.into_iter())
117 .collect();
118
119 class_probs.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
120 class_probs
121 }
122
123 pub fn classify(&self, text: &str) -> Option<(&str, f32)> {
126 let fv = self.instance2fv(text);
127 let probs = self.apply_norm_probs(self.nb_classprobs(fv));
128 let (max_index, max_prob) = probs
129 .iter()
130 .enumerate()
131 .fold(None, |max, (idx, &prob)| match max {
132 None => Some((idx, prob)),
133 Some((max_idx, max_val)) => {
134 if prob > max_val {
135 Some((idx, prob))
136 } else {
137 Some((max_idx, max_val))
138 }
139 }
140 })
141 .unzip();
142 let (max_index, max_prob) = (max_index?, max_prob?);
143
144 self.data()
145 .nb_classes
146 .get(max_index)
147 .map(|class| (class.as_str(), max_prob))
148 }
149
150 fn nb_classprobs(&self, fv: Vec<u16>) -> Vec<f32> {
151 let n = self.data().nb_pc.len();
156 let mut pdc = vec![0f32; n];
157
158 for (i, fv_val) in fv.into_iter().enumerate() {
159 let fv_val = fv_val as f32;
160 for j in 0..n {
161 pdc[j] += fv_val * self.data().nb_ptc[i][j];
162 }
163 }
164
165 for j in 0..n {
167 pdc[j] += self.data().nb_pc[j];
168 }
169
170 pdc
171 }
172
173 fn instance2fv(&self, text: &str) -> Vec<u16> {
174 let indexes = text
175 .chars()
176 .fold((0usize, Vec::new()), |(state, mut acc), letter| {
177 let new_state = self.tk_nextmove[(state << 8) + letter as usize];
178 let new_state_u = new_state as usize;
179 let output = self.tk_output.get(&new_state).cloned().unwrap_or_default();
180 acc.extend(output);
181 (new_state_u, acc)
182 })
183 .1;
184 let mut arr = vec![0; self.nb_numfeats];
185
186 let counts = counter(&indexes);
187
188 for (index, value) in counts {
189 arr[index as usize] = value;
190 }
191 arr
192 }
193}
194
195fn counter(indexes: &Vec<i32>) -> HashMap<i32, u16> {
196 let mut counts = HashMap::new();
197
198 for inner_vec in indexes {
199 *counts.entry(*inner_vec).or_insert(0) += 1;
200 }
201
202 counts
203}
204fn read_u32(reader: &mut impl Read) -> io::Result<u32> {
205 let mut buf = [0u8; 4];
206 reader.read_exact(&mut buf)?;
207 Ok(u32::from_le_bytes(buf))
208}
209
210fn read_f32_vec(reader: &mut impl Read, len: usize) -> io::Result<Vec<f32>> {
211 let mut buf = vec![0u8; len * 4];
212 reader.read_exact(&mut buf)?;
213 let floats = buf
214 .chunks_exact(4)
215 .map(|b| f32::from_le_bytes(b.try_into().unwrap()))
216 .collect();
217 Ok(floats)
218}
219
220fn read_u16_vec(reader: &mut impl Read, len: usize) -> io::Result<Vec<u16>> {
221 let mut buf = vec![0u8; len * 2];
222 reader.read_exact(&mut buf)?;
223 let floats = buf
224 .chunks_exact(2)
225 .map(|b| u16::from_le_bytes(b.try_into().unwrap()))
226 .collect();
227 Ok(floats)
228}
229
230fn read_string(reader: &mut impl Read) -> io::Result<String> {
231 let len = read_u32(reader)? as usize;
232 let mut buf = vec![0u8; len];
233 reader.read_exact(&mut buf)?;
234 Ok(String::from_utf8(buf).expect("Invalid UTF-8"))
235}
236
237fn read_i32_vec(reader: &mut impl Read, len: usize) -> io::Result<Vec<i32>> {
238 let mut buf = vec![0u8; len * 4];
239 reader.read_exact(&mut buf)?;
240 let vals = buf
241 .chunks_exact(4)
242 .map(|b| i32::from_le_bytes(b.try_into().unwrap()))
243 .collect();
244 Ok(vals)
245}
246
247impl Model {
248 pub fn load(norm_probs: bool) -> io::Result<Self> {
249 let mut reader = Cursor::new(include_bytes!("model.bin"));
250
251 let rows = read_u32(&mut reader)? as usize;
252 let cols = read_u32(&mut reader)? as usize;
253 let nb_ptc_flat = read_f32_vec(&mut reader, rows * cols)?;
254 let nb_ptc: Vec<Vec<f32>> = nb_ptc_flat
255 .chunks_exact(cols)
256 .map(|row| row.to_vec())
257 .collect();
258
259 let nb_pc_len = read_u32(&mut reader)? as usize;
260 let nb_pc = read_f32_vec(&mut reader, nb_pc_len)?;
261
262 let tk_nextmove_len = read_u32(&mut reader)? as usize;
263 let tk_nextmove = read_u16_vec(&mut reader, tk_nextmove_len)?;
264
265 let nb_class_count = read_u32(&mut reader)? as usize;
266 let mut nb_classes = Vec::with_capacity(nb_class_count);
267 for _ in 0..nb_class_count {
268 nb_classes.push(read_string(&mut reader)?);
269 }
270
271 let tk_output_count = read_u32(&mut reader)? as usize;
272 let mut tk_output = HashMap::with_capacity(tk_output_count);
273 for _ in 0..tk_output_count {
274 let key = read_u32(&mut reader)?;
275 let key = match u16::try_from(key) {
276 Ok(v) => v,
277 Err(_) => unreachable!("Key does not fit in u16"),
278 };
279 let val_len = read_u32(&mut reader)? as usize;
280 let val = read_i32_vec(&mut reader, val_len)?;
281 tk_output.insert(key, val);
282 }
283
284 let nb_numfeats = nb_ptc.iter().map(|v| v.len()).sum::<usize>() / nb_pc.len();
285 assert_eq!(bytes_remaining(&mut reader)?, 0);
286 Ok(Self {
287 norm_probs,
288 used_data: None,
289 nb_numfeats,
290 data: ModelData {
291 nb_classes,
292 nb_ptc,
293 nb_pc,
294 },
295 tk_nextmove,
296 tk_output,
297 })
298 }
299}
300
301fn bytes_remaining<R: Read + Seek>(reader: &mut R) -> std::io::Result<u64> {
302 let current = reader.seek(SeekFrom::Current(0))?;
303 let end = reader.seek(SeekFrom::End(0))?;
304 reader.seek(SeekFrom::Start(current))?; Ok(end - current)
306}