Debian Codegraph @

debian/rust-vendor/icu_segmenter/src/complex/lstm/mod.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 use crate::grapheme::GraphemeClusterSegmenterBorrowed;
6 use crate::indices::Utf16Indices;
7 use crate::provider::*;
8 #[cfg(feature = "unstable")]
9 use crate::scaffold::PotentiallyIllFormedUtf8;
10 use crate::scaffold::{RuleBreakType, Utf8, Utf16};
11 use alloc::vec::Vec;
12 use potential_utf::PotentialUtf8;
13 #[cfg(feature = "unstable")]
14 use utf8_iter::{Utf8CharIndices, Utf8Chars};
15 use zerovec::maps::ZeroMapBorrowed;
16
17 mod matrix;
18 use matrix::*;
19
20 // A word break iterator using LSTM model. Input string have to be same complex script.
21 #[derive(Debug)]
22 pub(super) struct LstmSegmenterIterator<'data, 's, R: RuleBreakType> {
23 chars: R::IterAttr<'s>,
24 bies: BiesIterator<'data>,
25 }
26
27 impl<R: RuleBreakType> Iterator for LstmSegmenterIterator<'_, '_, R> {
28 type Item = usize;
29
30 fn next(&mut self) -> Option<Self::Item> {
31 loop {
32 let is_e = self.bies.next()?;
33 let (idx, ch) = self.chars.next()?;
34 if is_e || self.bies.input_seq.len() == 0 {
35 return Some(idx + R::char_len(ch));
36 }
37 }
38 }
39 }
40
41 #[derive(Clone, Copy)]
42 pub(super) struct LstmSegmenter<'data> {
43 dic: ZeroMapBorrowed<'data, PotentialUtf8, u16>,
44 embedding: MatrixZero<'data, 2>,
45 fw_w: MatrixZero<'data, 3>,
46 fw_u: MatrixZero<'data, 3>,
47 fw_b: MatrixZero<'data, 2>,
48 bw_w: MatrixZero<'data, 3>,
49 bw_u: MatrixZero<'data, 3>,
50 bw_b: MatrixZero<'data, 2>,
51 timew_fw: MatrixZero<'data, 2>,
52 timew_bw: MatrixZero<'data, 2>,
53 time_b: MatrixZero<'data, 1>,
54 grapheme: Option<GraphemeClusterSegmenterBorrowed<'data>>,
55 }
56
57 impl<'data> LstmSegmenter<'data> {
58 /// Returns `Err` if grapheme data is required but not present
59 pub(super) fn new(
60 lstm: &'data LstmData<'data>,
61 grapheme: GraphemeClusterSegmenterBorrowed<'data>,
62 ) -> Self {
63 let LstmData::Float32(lstm) = lstm;
64 let time_w = MatrixZero::from(&lstm.time_w);
65 #[expect(clippy::unwrap_used)] // shape (2, 4, hunits)
66 let timew_fw = time_w.submatrix(0).unwrap();
67 #[expect(clippy::unwrap_used)] // shape (2, 4, hunits)
68 let timew_bw = time_w.submatrix(1).unwrap();
69 Self {
70 dic: lstm.dic.as_borrowed(),
71 embedding: MatrixZero::from(&lstm.embedding),
72 fw_w: MatrixZero::from(&lstm.fw_w),
73 fw_u: MatrixZero::from(&lstm.fw_u),
74 fw_b: MatrixZero::from(&lstm.fw_b),
75 bw_w: MatrixZero::from(&lstm.bw_w),
76 bw_u: MatrixZero::from(&lstm.bw_u),
77 bw_b: MatrixZero::from(&lstm.bw_b),
78 timew_fw,
79 timew_bw,
80 time_b: MatrixZero::from(&lstm.time_b),
81 grapheme: (lstm.model == ModelType::GraphemeClusters).then_some(grapheme),
82 }
83 }
84
85 /// Create an LSTM based break iterator for an `str` (a UTF-8 string).
86 pub(super) fn segment_str<'s>(self, input: &'s str) -> LstmSegmenterIterator<'data, 's, Utf8> {
87 let input_seq = if let Some(grapheme) = self.grapheme {
88 grapheme
89 .segment_str(input)
90 .collect::<Vec<usize>>()
91 .windows(2)
92 .map(|chunk| {
93 let range = if let [first, second, ..] = chunk {
94 *first..*second
95 } else {
96 unreachable!()
97 };
98 let grapheme_cluster = if let Some(grapheme_cluster) = input.get(range) {
99 grapheme_cluster
100 } else {
101 return self.dic.len() as u16;
102 };
103
104 self.dic
105 .get_copied(PotentialUtf8::from_str(grapheme_cluster))
106 .unwrap_or_else(|| self.dic.len() as u16)
107 })
108 .collect()
109 } else {
110 input
111 .chars()
112 .map(|c| {
113 self.dic
114 .get_copied(PotentialUtf8::from_str(c.encode_utf8(&mut [0; 4])))
115 .unwrap_or_else(|| self.dic.len() as u16)
116 })
117 .collect()
118 };
119 LstmSegmenterIterator {
120 chars: input.char_indices(),
121 bies: BiesIterator::new(self, input_seq),
122 }
123 }
124
125 /// Create an LSTM based break iterator for a UTF-8 string.
126 #[cfg(feature = "unstable")]
127 pub(super) fn segment_utf8<'s>(
128 self,
129 input: &'s [u8],
130 ) -> LstmSegmenterIterator<'data, 's, PotentiallyIllFormedUtf8> {
131 let input_seq = if let Some(grapheme) = self.grapheme {
132 grapheme
133 .segment_utf8(input)
134 .collect::<Vec<usize>>()
135 .windows(2)
136 .map(|chunk| {
137 let range = if let [first, second, ..] = chunk {
138 *first..*second
139 } else {
140 unreachable!()
141 };
142 let grapheme_cluster = if let Some(grapheme_cluster) = input.get(range) {
143 grapheme_cluster
144 } else {
145 return self.dic.len() as u16;
146 };
147
148 self.dic
149 .get_copied(PotentialUtf8::from_bytes(grapheme_cluster))
150 .unwrap_or_else(|| self.dic.len() as u16)
151 })
152 .collect()
153 } else {
154 Utf8Chars::new(input)
155 .map(|c| {
156 self.dic
157 .get_copied(PotentialUtf8::from_str(c.encode_utf8(&mut [0; 4])))
158 .unwrap_or_else(|| self.dic.len() as u16)
159 })
160 .collect()
161 };
162 LstmSegmenterIterator {
163 chars: Utf8CharIndices::new(input),
164 bies: BiesIterator::new(self, input_seq),
165 }
166 }
167
168 /// Create an LSTM based break iterator for a UTF-16 string.
169 pub(super) fn segment_utf16<'s>(
170 self,
171 input: &'s [u16],
172 ) -> LstmSegmenterIterator<'data, 's, Utf16> {
173 let input_seq = if let Some(grapheme) = self.grapheme {
174 grapheme
175 .segment_utf16(input)
176 .collect::<Vec<usize>>()
177 .windows(2)
178 .map(|chunk| {
179 let range = if let [first, second, ..] = chunk {
180 *first..*second
181 } else {
182 unreachable!()
183 };
184 let grapheme_cluster = if let Some(grapheme_cluster) = input.get(range) {
185 grapheme_cluster
186 } else {
187 return self.dic.len() as u16;
188 };
189
190 self.dic
191 .get_copied_by(|key| {
192 key.as_bytes().iter().copied().cmp(
193 char::decode_utf16(grapheme_cluster.iter().copied()).flat_map(
194 |c| {
195 let mut buf = [0; 4];
196 let len = c
197 .unwrap_or(char::REPLACEMENT_CHARACTER)
198 .encode_utf8(&mut buf)
199 .len();
200 buf.into_iter().take(len)
201 },
202 ),
203 )
204 })
205 .unwrap_or_else(|| self.dic.len() as u16)
206 })
207 .collect()
208 } else {
209 char::decode_utf16(input.iter().copied())
210 .map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER))
211 .map(|c| {
212 self.dic
213 .get_copied(PotentialUtf8::from_str(c.encode_utf8(&mut [0; 4])))
214 .unwrap_or_else(|| self.dic.len() as u16)
215 })
216 .collect()
217 };
218 LstmSegmenterIterator {
219 chars: Utf16Indices::new(input),
220 bies: BiesIterator::new(self, input_seq),
221 }
222 }
223 }
224
225 #[derive(Debug)]
226 struct BiesIterator<'data> {
227 embedding: MatrixZero<'data, 2>,
228 fw_w: MatrixZero<'data, 3>,
229 fw_u: MatrixZero<'data, 3>,
230 fw_b: MatrixZero<'data, 2>,
231 timew_fw: MatrixZero<'data, 2>,
232 timew_bw: MatrixZero<'data, 2>,
233 time_b: MatrixZero<'data, 1>,
234 input_seq: core::iter::Enumerate<alloc::vec::IntoIter<u16>>,
235 h_bw: MatrixOwned<2>,
236 curr_fw: MatrixOwned<1>,
237 c_fw: MatrixOwned<1>,
238 }
239
240 impl<'data> BiesIterator<'data> {
241 // input_seq is a sequence of id numbers that represents grapheme clusters or code points in the input line. These ids are used later
242 // in the embedding layer of the model.
243 fn new(
244 LstmSegmenter {
245 embedding,
246 fw_w,
247 fw_u,
248 fw_b,
249 bw_w,
250 bw_u,
251 bw_b,
252 timew_fw,
253 timew_bw,
254 time_b,
255 ..
256 }: LstmSegmenter<'data>,
257 input_seq: Vec<u16>,
258 ) -> Self {
259 let hunits = fw_u.dim().1;
260
261 // Backward LSTM
262 let mut c_bw = MatrixOwned::<1>::new_zero([hunits]);
263 let mut h_bw = MatrixOwned::<2>::new_zero([input_seq.len(), hunits]);
264 for (i, &g_id) in input_seq.iter().enumerate().rev() {
265 if i + 1 < input_seq.len() {
266 h_bw.as_mut().copy_submatrix::<1>(i + 1, i);
267 }
268 #[expect(clippy::unwrap_used)]
269 compute_hc(
270 embedding.submatrix::<1>(g_id as usize).unwrap(), /* shape (dict.len() + 1, hunit), g_id is at most dict.len() */
271 h_bw.submatrix_mut(i).unwrap(), // shape (input_seq.len(), hunits)
272 c_bw.as_mut(),
273 bw_w,
274 bw_u,
275 bw_b,
276 );
277 }
278
279 Self {
280 input_seq: input_seq.into_iter().enumerate(),
281 h_bw,
282 c_fw: MatrixOwned::<1>::new_zero([hunits]),
283 curr_fw: MatrixOwned::<1>::new_zero([hunits]),
284 embedding,
285 fw_w,
286 fw_u,
287 fw_b,
288 timew_fw,
289 timew_bw,
290 time_b,
291 }
292 }
293 }
294
295 impl Iterator for BiesIterator<'_> {
296 type Item = bool;
297
298 fn next(&mut self) -> Option<Self::Item> {
299 let (i, g_id) = self.input_seq.next()?;
300
301 #[expect(clippy::unwrap_used)]
302 compute_hc(
303 self.embedding.submatrix::<1>(g_id as usize).unwrap(), // shape (dict.len() + 1, hunit), g_id is at most dict.len()
304 self.curr_fw.as_mut(),
305 self.c_fw.as_mut(),
306 self.fw_w,
307 self.fw_u,
308 self.fw_b,
309 );
310
311 #[expect(clippy::unwrap_used)] // shape (input_seq.len(), hunits)
312 let curr_bw = self.h_bw.submatrix::<1>(i).unwrap();
313 let mut weights = [0.0; 4];
314 let mut curr_est = MatrixBorrowedMut {
315 data: &mut weights,
316 dims: [4],
317 };
318 curr_est.add_dot_2d(self.curr_fw.as_borrowed(), self.timew_fw);
319 curr_est.add_dot_2d(curr_bw, self.timew_bw);
320 #[expect(clippy::unwrap_used)] // both shape (4)
321 curr_est.add(self.time_b).unwrap();
322 // For correct BIES weight calculation we'd now have to apply softmax, however
323 // we're only doing a naive argmax, so a monotonic function doesn't make a difference.
324
325 Some(weights[2] > weights[0] && weights[2] > weights[1] && weights[2] > weights[3])
326 }
327 }
328
329 /// `compute_hc1` implemens the evaluation of one LSTM layer.
330 fn compute_hc<'a>(
331 x_t: MatrixZero<'a, 1>,
332 mut h_tm1: MatrixBorrowedMut<'a, 1>,
333 mut c_tm1: MatrixBorrowedMut<'a, 1>,
334 w: MatrixZero<'a, 3>,
335 u: MatrixZero<'a, 3>,
336 b: MatrixZero<'a, 2>,
337 ) {
338 #[cfg(debug_assertions)]
339 {
340 let hunits = h_tm1.dim();
341 let embedd_dim = x_t.dim();
342 c_tm1.as_borrowed().debug_assert_dims([hunits]);
343 w.debug_assert_dims([4, hunits, embedd_dim]);
344 u.debug_assert_dims([4, hunits, hunits]);
345 b.debug_assert_dims([4, hunits]);
346 }
347
348 let mut s_t = b.to_owned();
349
350 s_t.as_mut().add_dot_3d_2(x_t, w);
351 s_t.as_mut().add_dot_3d_1(h_tm1.as_borrowed(), u);
352
353 #[expect(clippy::unwrap_used)] // first dimension is 4
354 s_t.submatrix_mut::<1>(0).unwrap().sigmoid_transform();
355 #[expect(clippy::unwrap_used)] // first dimension is 4
356 s_t.submatrix_mut::<1>(1).unwrap().sigmoid_transform();
357 #[expect(clippy::unwrap_used)] // first dimension is 4
358 s_t.submatrix_mut::<1>(2).unwrap().tanh_transform();
359 #[expect(clippy::unwrap_used)] // first dimension is 4
360 s_t.submatrix_mut::<1>(3).unwrap().sigmoid_transform();
361
362 #[expect(clippy::unwrap_used)] // first dimension is 4
363 c_tm1.convolve(
364 s_t.as_borrowed().submatrix(0).unwrap(),
365 s_t.as_borrowed().submatrix(2).unwrap(),
366 s_t.as_borrowed().submatrix(1).unwrap(),
367 );
368
369 #[expect(clippy::unwrap_used)] // first dimension is 4
370 h_tm1.mul_tanh(s_t.as_borrowed().submatrix(3).unwrap(), c_tm1.as_borrowed());
371 }
372
373 #[cfg(test)]
374 mod tests {
375 use super::*;
376 use crate::GraphemeClusterSegmenter;
377 use icu_provider::prelude::*;
378 use serde::Deserialize;
379
380 /// `TestCase` is a struct used to store a single test case.
381 /// Each test case has two attributes: `unseg` which denotes the unsegmented line, and `true_bies` which indicates the Bies
382 /// sequence representing the true segmentation.
383 #[derive(PartialEq, Debug, Deserialize)]
384 struct TestCase {
385 unseg: String,
386 expected_bies: String,
387 true_bies: String,
388 }
389
390 /// `TestTextData` is a struct to store a vector of `TestCase` that represents a test text.
391 #[derive(PartialEq, Debug, Deserialize)]
392 struct TestTextData {
393 testcases: Vec<TestCase>,
394 }
395
396 #[derive(Debug)]
397 struct TestText {
398 data: TestTextData,
399 }
400
401 #[test]
402 fn segment_file_by_lstm() {
403 let lstm: DataResponse<SegmenterLstmAutoV1> = Baked
404 .load(DataRequest {
405 id: DataIdentifierBorrowed::for_marker_attributes(
406 DataMarkerAttributes::from_str_or_panic(
407 "Thai_codepoints_exclusive_model4_heavy",
408 ),
409 ),
410 ..Default::default()
411 })
412 .unwrap();
413 let lstm = LstmSegmenter::new(lstm.payload.get(), GraphemeClusterSegmenter::new());
414
415 // Importing the test data
416 let test_text_data = serde_json::from_str(if lstm.grapheme.is_some() {
417 include_str!("../../../tests/testdata/test_text_graphclust.json")
418 } else {
419 include_str!("../../../tests/testdata/test_text_codepoints.json")
420 })
421 .expect("JSON syntax error");
422 let test_text = TestText {
423 data: test_text_data,
424 };
425
426 // Testing
427 for test_case in &test_text.data.testcases {
428 let lstm_output = lstm
429 .segment_str(&test_case.unseg)
430 .bies
431 .map(|is_e| if is_e { 'e' } else { '?' })
432 .collect::<String>();
433 println!("Test case : {}", test_case.unseg);
434 println!("Expected bies : {}", test_case.expected_bies);
435 println!("Estimated bies : {lstm_output}");
436 println!("True bies : {}", test_case.true_bies);
437 println!("****************************************************");
438 assert_eq!(
439 test_case.expected_bies.replace(['b', 'i', 's'], "?"),
440 lstm_output
441 );
442 }
443 }
444 }