1use std::collections::HashMap;
14use std::ops::Range;
15
16use super::classifier::Classifier;
17use super::features::FeatureSet;
18use crate::bytes::{Reader, push_string, push_u32};
19use crate::error::{Error, Result};
20use crate::model::table::{self, Layout, Table};
21use crate::schema::Schema;
22
23pub(crate) fn feature_key(feature: &str) -> u32 {
34 table::hash(feature.as_bytes()) as u32
35}
36
37pub(crate) fn bucket(one: u32, other: u32, bits: u32) -> u32 {
51 let mut value = (u64::from(one.min(other)) << 32) | u64::from(one.max(other));
52 value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
53 value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
54 (value >> (64 - bits)) as u32
55}
56
57#[derive(Debug, Clone, PartialEq)]
59pub enum PairWeights {
60 Exact(Vec<((u32, u32), f32)>),
63 Hashed {
66 bits: u32,
68 weights: Vec<f32>,
70 },
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum Quantization {
76 F32,
78 I16,
81 I8,
84}
85
86impl Quantization {
87 const ALL: [(Quantization, &'static str, u8); 3] = [
89 (Quantization::F32, "f32", 0),
90 (Quantization::I16, "i16", 1),
91 (Quantization::I8, "i8", 2),
92 ];
93
94 pub fn name(self) -> &'static str {
100 Self::ALL
101 .iter()
102 .find(|(one, _, _)| *one == self)
103 .map_or("", |(_, name, _)| name)
104 }
105
106 pub fn from_name(name: &str) -> Option<Self> {
116 Self::ALL
117 .iter()
118 .find(|(_, other, _)| *other == name)
119 .map(|(one, _, _)| *one)
120 }
121
122 fn code(self) -> u8 {
124 Self::ALL
125 .iter()
126 .find(|(one, _, _)| *one == self)
127 .map_or(u8::MAX, |(_, _, code)| *code)
128 }
129
130 fn from_code(code: u8) -> Option<Self> {
132 Self::ALL
133 .iter()
134 .find(|(_, _, other)| *other == code)
135 .map(|(one, _, _)| *one)
136 }
137
138 fn width(self) -> usize {
140 match self {
141 Quantization::F32 => 4,
142 Quantization::I16 => 2,
143 Quantization::I8 => 1,
144 }
145 }
146
147 fn largest(self) -> Option<f64> {
150 match self {
151 Quantization::F32 => None,
152 Quantization::I16 => Some(f64::from(i16::MAX)),
153 Quantization::I8 => Some(f64::from(i8::MAX)),
154 }
155 }
156
157 fn push(self, bytes: &mut Vec<u8>, weight: f32, scale: f64) {
165 let whole = || (f64::from(weight) / scale).round();
166 match self {
167 Quantization::F32 => bytes.extend_from_slice(&weight.to_le_bytes()),
168 Quantization::I16 => bytes.extend_from_slice(&(whole() as i16).to_le_bytes()),
169 Quantization::I8 => bytes.extend_from_slice(&(whole() as i8).to_le_bytes()),
170 }
171 }
172
173 #[inline]
184 fn read(self, bytes: &[u8], index: usize) -> f64 {
185 match self {
186 Quantization::F32 => {
187 let start = index.saturating_mul(4);
188 bytes
189 .get(start..start.saturating_add(4))
190 .and_then(|bytes| bytes.try_into().ok())
191 .map_or(0.0, |bytes| f64::from(f32::from_le_bytes(bytes)))
192 }
193 Quantization::I16 => {
194 let start = index.saturating_mul(2);
195 bytes
196 .get(start..start.saturating_add(2))
197 .and_then(|bytes| bytes.try_into().ok())
198 .map_or(0.0, |bytes| f64::from(i16::from_le_bytes(bytes)))
199 }
200 Quantization::I8 => bytes.get(index).map_or(0.0, |byte| f64::from(*byte as i8)),
201 }
202 }
203}
204
205#[derive(Debug, Clone, PartialEq)]
215pub struct ParserModel {
216 schema: Schema,
218 feature_set: FeatureSet,
220 bias: f64,
222 unit: f64,
225 names: Vec<String>,
227 weights: Vec<f32>,
229 pairs: PairWeights,
231 numbers: HashMap<String, u32>,
233 keys: Vec<u32>,
235 exact: HashMap<(u32, u32), f32>,
237}
238
239impl ParserModel {
240 pub fn new(
259 schema: Schema,
260 feature_set: FeatureSet,
261 bias: f64,
262 features: Vec<(String, f32)>,
263 pairs: PairWeights,
264 ) -> Result<Self> {
265 let finite = bias.is_finite()
266 && features.iter().all(|(_, weight)| weight.is_finite())
267 && match &pairs {
268 PairWeights::Exact(pairs) => pairs.iter().all(|(_, weight)| weight.is_finite()),
269 PairWeights::Hashed { weights, .. } => {
270 weights.iter().all(|weight| weight.is_finite())
271 }
272 };
273 if !finite {
274 return Err(Error::Parser("a weight is not finite".to_string()));
275 }
276 if features
277 .windows(2)
278 .any(|pair| pair[0].0.as_bytes() >= pair[1].0.as_bytes())
279 {
280 return Err(Error::Parser(
281 "the features are not sorted, each once".to_string(),
282 ));
283 }
284 if u32::try_from(features.len()).is_err() {
285 return Err(Error::Parser("too many features".to_string()));
286 }
287 match &pairs {
288 PairWeights::Exact(pairs) => {
289 let count = features.len() as u32;
290 if pairs
291 .iter()
292 .any(|((one, other), _)| one >= other || *other >= count)
293 {
294 return Err(Error::Parser(
295 "a pair does not name two features, the smaller number first".to_string(),
296 ));
297 }
298 if pairs.windows(2).any(|pair| pair[0].0 >= pair[1].0) {
299 return Err(Error::Parser(
300 "the pairs are not sorted, each once".to_string(),
301 ));
302 }
303 }
304 PairWeights::Hashed { bits, weights } => {
305 if !(1..=30).contains(bits) || weights.len() != 1usize << bits {
306 return Err(Error::Parser(format!(
307 "a table of hashed pairs of {bits} bits has {} weights",
308 weights.len()
309 )));
310 }
311 }
312 }
313
314 let (names, weights): (Vec<String>, Vec<f32>) = features.into_iter().unzip();
315 let numbers = names
316 .iter()
317 .enumerate()
318 .map(|(index, name)| (name.clone(), index as u32))
319 .collect();
320 let keys = names.iter().map(|name| feature_key(name)).collect();
321 let exact = match &pairs {
322 PairWeights::Exact(pairs) => pairs.iter().copied().collect(),
323 PairWeights::Hashed { .. } => HashMap::new(),
324 };
325 Ok(Self {
326 schema,
327 feature_set,
328 bias,
329 unit: 1.0,
330 names,
331 weights,
332 pairs,
333 numbers,
334 keys,
335 exact,
336 })
337 }
338
339 pub fn with_unit(mut self, unit: f64) -> Result<Self> {
357 if !unit.is_finite() || unit <= 0.0 {
358 return Err(Error::Parser(format!(
359 "the unit of the weights is {unit}, and has to be greater than 0"
360 )));
361 }
362 self.unit = unit;
363 Ok(self)
364 }
365
366 pub fn compact(self) -> Self {
376 let pairs = match self.pairs {
377 PairWeights::Exact(pairs) => PairWeights::Exact(
378 pairs
379 .into_iter()
380 .filter(|(_, weight)| *weight != 0.0)
381 .collect(),
382 ),
383 hashed => hashed,
384 };
385 let mut kept: Vec<bool> = self.weights.iter().map(|weight| *weight != 0.0).collect();
386 if let PairWeights::Exact(pairs) = &pairs {
387 for ((one, other), _) in pairs {
388 kept[*one as usize] = true;
389 kept[*other as usize] = true;
390 }
391 }
392 let mut renumbered = vec![u32::MAX; kept.len()];
394 let mut next = 0;
395 for (index, kept) in kept.iter().enumerate() {
396 if *kept {
397 renumbered[index] = next;
398 next += 1;
399 }
400 }
401 let features = self
402 .names
403 .into_iter()
404 .zip(self.weights)
405 .zip(&kept)
406 .filter(|(_, kept)| **kept)
407 .map(|(feature, _)| feature)
408 .collect();
409 let pairs = match pairs {
410 PairWeights::Exact(pairs) => PairWeights::Exact(
411 pairs
412 .into_iter()
413 .map(|((one, other), weight)| {
414 (
415 (renumbered[one as usize], renumbered[other as usize]),
416 weight,
417 )
418 })
419 .collect(),
420 ),
421 hashed => hashed,
422 };
423 let unit = self.unit;
426 let mut model = Self::new(self.schema, self.feature_set, self.bias, features, pairs)
427 .expect("a model without what has no weight is a model");
428 model.unit = unit;
429 model
430 }
431
432 pub fn schema(&self) -> &Schema {
438 &self.schema
439 }
440
441 pub fn feature_set(&self) -> &FeatureSet {
447 &self.feature_set
448 }
449
450 pub fn bias(&self) -> f64 {
456 self.bias
457 }
458
459 pub fn unit(&self) -> f64 {
466 self.unit
467 }
468
469 pub fn feature_count(&self) -> usize {
475 self.names.len()
476 }
477
478 pub fn pairs(&self) -> &PairWeights {
484 &self.pairs
485 }
486
487 pub fn pair_count(&self) -> usize {
494 match &self.pairs {
495 PairWeights::Exact(pairs) => pairs.iter().filter(|(_, weight)| *weight != 0.0).count(),
496 PairWeights::Hashed { weights, .. } => {
497 weights.iter().filter(|weight| **weight != 0.0).count()
498 }
499 }
500 }
501
502 fn scale(&self, quantization: Quantization) -> f64 {
506 let Some(largest) = quantization.largest() else {
507 return 1.0;
508 };
509 let pairs: Box<dyn Iterator<Item = f32> + '_> = match &self.pairs {
510 PairWeights::Exact(pairs) => Box::new(pairs.iter().map(|(_, weight)| *weight)),
511 PairWeights::Hashed { weights, .. } => Box::new(weights.iter().copied()),
512 };
513 let highest = self
514 .weights
515 .iter()
516 .copied()
517 .chain(pairs)
518 .fold(0.0f32, |highest, weight| highest.max(weight.abs()));
519 if highest == 0.0 {
520 1.0
521 } else {
522 f64::from(highest) / largest
523 }
524 }
525
526 pub(crate) fn write_part(&self, bytes: &mut Vec<u8>, quantization: Quantization) {
538 let scale = self.scale(quantization);
539 let written_scale = scale * self.unit;
542 push_string(bytes, &self.feature_set.to_string());
543 bytes.push(quantization.code());
544 bytes.push(match self.pairs {
545 PairWeights::Exact(_) => PAIRS_EXACT,
546 PairWeights::Hashed { .. } => PAIRS_HASHED,
547 });
548 bytes.extend_from_slice(&self.bias.to_le_bytes());
549 bytes.extend_from_slice(&written_scale.to_le_bytes());
550
551 let hashed = matches!(self.pairs, PairWeights::Hashed { .. });
554 let width = quantization.width() + if hashed { 4 } else { 0 };
555 let values: Vec<Vec<u8>> = self
556 .weights
557 .iter()
558 .zip(&self.keys)
559 .map(|(weight, key)| {
560 let mut value = Vec::with_capacity(width);
561 quantization.push(&mut value, *weight, scale);
562 if hashed {
563 value.extend_from_slice(&key.to_le_bytes());
564 }
565 value
566 })
567 .collect();
568 let entries: Vec<(&str, &[u8])> = self
569 .names
570 .iter()
571 .zip(&values)
572 .map(|(name, value)| (name.as_str(), value.as_slice()))
573 .collect();
574 table::write(bytes, width, &entries);
575
576 match &self.pairs {
577 PairWeights::Exact(pairs) => {
578 bytes.extend_from_slice(&(pairs.len() as u64).to_le_bytes());
581 let mut offsets = vec![0u32; self.names.len() + 1];
582 for ((one, _), _) in pairs {
583 offsets[*one as usize + 1] += 1;
584 }
585 let mut total = 0;
586 for offset in &mut offsets {
587 total += *offset;
588 *offset = total;
589 }
590 for offset in offsets {
591 push_u32(bytes, offset);
592 }
593 for ((_, other), _) in pairs {
594 push_u32(bytes, *other);
595 }
596 for (_, weight) in pairs {
597 quantization.push(bytes, *weight, scale);
598 }
599 }
600 PairWeights::Hashed { bits, weights } => {
601 push_u32(bytes, *bits);
602 for weight in weights {
603 quantization.push(bytes, *weight, scale);
604 }
605 }
606 }
607 }
608}
609
610impl Classifier for ParserModel {
611 fn id(&self, feature: &str) -> Option<u32> {
612 self.numbers.get(feature).copied()
613 }
614
615 fn score(&self, features: &[u32]) -> f64 {
616 let mut sum = 0.0;
619 for &feature in features {
620 sum += self
621 .weights
622 .get(feature as usize)
623 .map_or(0.0, |weight| f64::from(*weight));
624 }
625 match &self.pairs {
626 PairWeights::Exact(_) => {
627 for (index, &one) in features.iter().enumerate() {
628 for &other in &features[index + 1..] {
629 if let Some(weight) = self.exact.get(&(one, other)) {
630 sum += f64::from(*weight);
631 }
632 }
633 }
634 }
635 PairWeights::Hashed { bits, weights } => {
636 for (index, &one) in features.iter().enumerate() {
637 let Some(&one) = self.keys.get(one as usize) else {
638 continue;
639 };
640 for &other in &features[index + 1..] {
641 if let Some(&other) = self.keys.get(other as usize) {
642 sum += f64::from(weights[bucket(one, other, *bits) as usize]);
643 }
644 }
645 }
646 }
647 }
648 self.bias + self.unit * sum
649 }
650}
651
652const PAIRS_EXACT: u8 = 0;
654const PAIRS_HASHED: u8 = 1;
656
657#[derive(Debug, Clone, PartialEq, Eq)]
659enum PairsLayout {
660 Exact {
662 offsets: Range<usize>,
664 columns: Range<usize>,
666 weights: Range<usize>,
668 },
669 Hashed {
671 bits: u32,
673 weights: Range<usize>,
675 },
676}
677
678#[derive(Debug, Clone, PartialEq)]
681pub(crate) struct ParserLayout {
682 feature_set: FeatureSet,
684 quantization: Quantization,
686 bias: f64,
688 scale: f64,
690 features: Layout,
692 pairs: PairsLayout,
694}
695
696#[inline]
698fn read_u32(bytes: &[u8], index: usize) -> u32 {
699 let start = index.saturating_mul(4);
700 bytes
701 .get(start..start.saturating_add(4))
702 .and_then(|bytes| bytes.try_into().ok())
703 .map_or(0, u32::from_le_bytes)
704}
705
706impl ParserLayout {
707 pub(crate) fn read(part: &[u8], base: usize) -> Result<Self> {
724 let mut reader = Reader::new(part, "model", Error::Model);
725 let feature_set = FeatureSet::parse(&reader.string()?).map_err(|error| {
726 reader.error(format_args!("has a feature set that is not one: {error}"))
727 })?;
728 let code = reader.u8()?;
729 let quantization = Quantization::from_code(code)
730 .ok_or_else(|| reader.error(format_args!("has the unknown quantization {code}")))?;
731 let kind = reader.u8()?;
732 let bias = reader.f64()?;
733 let scale = reader.f64()?;
734 if !(bias.is_finite() && scale.is_finite()) {
735 return Err(reader.error("has a weight that is not finite"));
736 }
737 if scale <= 0.0 {
738 return Err(reader.error(format_args!("has the scale {scale}, which is not above 0")));
739 }
740 let width = quantization.width();
741
742 let hashed = match kind {
743 PAIRS_EXACT => false,
744 PAIRS_HASHED => true,
745 _ => {
746 return Err(reader.error(format_args!("has the unknown table of pairs {kind}")));
747 }
748 };
749 let features = Layout::read(&mut reader, width + if hashed { 4 } else { 0 })?;
750 let count = features.table(part).len();
751
752 let (pairs, weights) = if hashed {
753 let bits = reader.u32()?;
754 if !(1..=30).contains(&bits) {
755 return Err(
756 reader.error(format_args!("has a table of hashed pairs of {bits} bits"))
757 );
758 }
759 let start = reader.position();
760 let weights = reader.take((1usize << bits).saturating_mul(width))?;
761 (
762 PairsLayout::Hashed {
763 bits,
764 weights: start..reader.position(),
765 },
766 weights,
767 )
768 } else {
769 let pair_count = usize::try_from(reader.u64()?)
770 .map_err(|_| reader.error("has more pairs than can be read"))?;
771 let start = reader.position();
772 let offsets = reader.take((count + 1).saturating_mul(4))?;
773 let offsets_range = start..reader.position();
774 let start = reader.position();
775 let columns = reader.take(pair_count.saturating_mul(4))?;
776 let columns_range = start..reader.position();
777 let start = reader.position();
778 let weights = reader.take(pair_count.saturating_mul(width))?;
779 let weights_range = start..reader.position();
780
781 let mut end = 0;
784 for feature in 0..count {
785 let from = read_u32(offsets, feature) as usize;
786 let to = read_u32(offsets, feature + 1) as usize;
787 if from != end || to < from || to > pair_count {
791 return Err(
792 reader.error("has pairs that are not in the order of their features")
793 );
794 }
795 end = to;
796 let mut before = feature as u32;
797 for index in from..to {
798 let other = read_u32(columns, index);
799 if other <= before || other as usize >= count {
800 return Err(
801 reader.error("has pairs that are not in the order of their features")
802 );
803 }
804 before = other;
805 }
806 }
807 if end != pair_count {
808 return Err(reader.error("has pairs that are not in the order of their features"));
809 }
810 (
811 PairsLayout::Exact {
812 offsets: offsets_range,
813 columns: columns_range,
814 weights: weights_range,
815 },
816 weights,
817 )
818 };
819 if reader.remaining() != 0 {
820 return Err(reader.error(format_args!(
821 "has {} bytes after its parser",
822 reader.remaining()
823 )));
824 }
825
826 if quantization == Quantization::F32 {
827 let table = features.table(part);
828 let finite = (0..count)
829 .all(|index| quantization.read(table.value(index), 0).is_finite())
830 && (0..weights.len() / 4)
831 .all(|index| quantization.read(weights, index).is_finite());
832 if !finite {
833 return Err(reader.error("has a weight that is not finite"));
834 }
835 }
836
837 let shift = |range: Range<usize>| base + range.start..base + range.end;
838 Ok(Self {
839 feature_set,
840 quantization,
841 bias,
842 scale,
843 features: features.shifted(base),
844 pairs: match pairs {
845 PairsLayout::Exact {
846 offsets,
847 columns,
848 weights,
849 } => PairsLayout::Exact {
850 offsets: shift(offsets),
851 columns: shift(columns),
852 weights: shift(weights),
853 },
854 PairsLayout::Hashed { bits, weights } => PairsLayout::Hashed {
855 bits,
856 weights: shift(weights),
857 },
858 },
859 })
860 }
861
862 pub(crate) fn feature_set(&self) -> &FeatureSet {
864 &self.feature_set
865 }
866
867 pub(crate) fn part<'a>(&'a self, bytes: &'a [u8]) -> ParserPart<'a> {
877 let piece = |range: &Range<usize>| bytes.get(range.clone()).unwrap_or_default();
878 ParserPart {
879 layout: self,
880 features: self.features.table(bytes),
881 pairs: match &self.pairs {
882 PairsLayout::Exact {
883 offsets,
884 columns,
885 weights,
886 } => PairsPart::Exact {
887 offsets: piece(offsets),
888 columns: piece(columns),
889 weights: piece(weights),
890 },
891 PairsLayout::Hashed { bits, weights } => PairsPart::Hashed {
892 bits: *bits,
893 weights: piece(weights),
894 },
895 },
896 }
897 }
898}
899
900#[derive(Debug, Clone, Copy)]
902enum PairsPart<'a> {
903 Exact {
905 offsets: &'a [u8],
907 columns: &'a [u8],
909 weights: &'a [u8],
911 },
912 Hashed {
914 bits: u32,
916 weights: &'a [u8],
918 },
919}
920
921#[derive(Debug, Clone, Copy)]
925pub struct ParserPart<'a> {
926 layout: &'a ParserLayout,
928 features: Table<'a>,
930 pairs: PairsPart<'a>,
932}
933
934impl ParserPart<'_> {
935 pub fn feature_count(&self) -> usize {
941 self.features.len()
942 }
943
944 pub fn pair_count(&self) -> usize {
951 match self.pairs {
952 PairsPart::Exact { columns, .. } => columns.len() / 4,
953 PairsPart::Hashed { bits, .. } => 1usize << bits,
954 }
955 }
956
957 pub fn quantization(&self) -> Quantization {
963 self.layout.quantization
964 }
965}
966
967impl Classifier for ParserPart<'_> {
968 fn id(&self, feature: &str) -> Option<u32> {
969 self.features.find(feature).map(|index| index as u32)
970 }
971
972 fn score(&self, features: &[u32]) -> f64 {
973 let quantization = self.layout.quantization;
974 let mut sum = 0.0;
975 for &feature in features {
976 sum += quantization.read(self.features.value(feature as usize), 0);
977 }
978 match self.pairs {
979 PairsPart::Exact {
980 offsets,
981 columns,
982 weights,
983 } => {
984 for (index, &one) in features.iter().enumerate() {
985 let mut from = read_u32(offsets, one as usize) as usize;
986 let to = read_u32(offsets, one as usize + 1) as usize;
987 for &other in &features[index + 1..] {
990 if from >= to {
991 break;
992 }
993 let (mut low, mut high) = (from, to);
994 while low < high {
995 let middle = low + (high - low) / 2;
996 if read_u32(columns, middle) < other {
997 low = middle + 1;
998 } else {
999 high = middle;
1000 }
1001 }
1002 from = low;
1003 if low < to && read_u32(columns, low) == other {
1004 sum += quantization.read(weights, low);
1005 from = low + 1;
1006 }
1007 }
1008 }
1009 }
1010 PairsPart::Hashed { bits, weights } => {
1011 let width = quantization.width();
1012 let key = |feature: u32| {
1013 self.features
1014 .value(feature as usize)
1015 .get(width..width + 4)
1016 .and_then(|bytes| bytes.try_into().ok())
1017 .map(u32::from_le_bytes)
1018 };
1019 for (index, &one) in features.iter().enumerate() {
1020 let Some(one) = key(one) else {
1021 continue;
1022 };
1023 for &other in &features[index + 1..] {
1024 if let Some(other) = key(other) {
1025 sum += quantization.read(weights, bucket(one, other, bits) as usize);
1026 }
1027 }
1028 }
1029 }
1030 }
1031 self.layout.bias + self.layout.scale * sum
1032 }
1033}
1034
1035#[cfg(test)]
1036pub(crate) mod tests {
1037 use super::*;
1038
1039 pub(crate) const NAMES: [&str; 4] = ["DIST:1", "SFS:は", "SFS:を", "a:が"];
1041
1042 fn features() -> Vec<(String, f32)> {
1044 NAMES
1045 .iter()
1046 .zip([0.5, -1.25, 2.0, 0.0])
1047 .map(|(name, weight)| (name.to_string(), weight))
1048 .collect()
1049 }
1050
1051 pub(crate) fn exact() -> ParserModel {
1053 ParserModel::new(
1054 Schema::ipadic(),
1055 FeatureSet::default(),
1056 -1.0,
1057 features(),
1058 PairWeights::Exact(vec![((0, 2), 1.5), ((1, 3), -0.75), ((2, 3), 0.25)]),
1059 )
1060 .unwrap()
1061 }
1062
1063 pub(crate) fn hashed() -> ParserModel {
1065 ParserModel::new(
1066 Schema::ipadic(),
1067 FeatureSet::cabocha(),
1068 0.25,
1069 features(),
1070 PairWeights::Hashed {
1071 bits: 4,
1072 weights: (0..16).map(|index| index as f32 * 0.125 - 1.0).collect(),
1073 },
1074 )
1075 .unwrap()
1076 }
1077
1078 fn part(model: &ParserModel, quantization: Quantization) -> Vec<u8> {
1080 let mut part = Vec::new();
1081 model.write_part(&mut part, quantization);
1082 part
1083 }
1084
1085 fn subsets() -> Vec<Vec<u32>> {
1087 (0..16u32)
1088 .map(|mask| (0..4).filter(|bit| mask & (1 << bit) != 0).collect())
1089 .collect()
1090 }
1091
1092 fn error(part: &[u8]) -> String {
1094 let error = ParserLayout::read(part, 0).unwrap_err();
1095 assert!(matches!(error, Error::Model(_)), "{error:?}");
1096 error.to_string()
1097 }
1098
1099 fn refused(bias: f64, features: Vec<(String, f32)>, pairs: PairWeights) -> String {
1101 let error = ParserModel::new(
1102 Schema::ipadic(),
1103 FeatureSet::default(),
1104 bias,
1105 features,
1106 pairs,
1107 )
1108 .unwrap_err();
1109 assert!(matches!(error, Error::Parser(_)), "{error:?}");
1110 error.to_string()
1111 }
1112
1113 #[test]
1114 fn a_model_scores_a_bias_its_features_and_their_pairs() {
1115 let model = exact();
1116 for (index, name) in NAMES.iter().enumerate() {
1117 assert_eq!(model.id(name), Some(index as u32));
1118 }
1119 assert_eq!(model.id("SFS:が"), None);
1120 assert_eq!(model.score(&[]), -1.0);
1121 assert_eq!(model.score(&[0]), -0.5);
1122 assert_eq!(model.score(&[0, 2]), 3.0);
1124 assert_eq!(model.score(&[1, 3]), -3.0);
1125 assert_eq!(model.score(&[0, 1, 2, 3]), 1.25);
1126 assert_eq!(model.score(&[0, 9]), -0.5);
1128 assert_eq!(model.bias(), -1.0);
1129 assert_eq!(model.feature_count(), 4);
1130 assert_eq!(model.pair_count(), 3);
1131 assert_eq!(model.feature_set(), &FeatureSet::default());
1132 assert_eq!(model.schema(), &Schema::ipadic());
1133 }
1134
1135 #[test]
1136 fn hashed_pairs_share_the_weight_of_their_place() {
1137 let model = hashed();
1138 let keys: Vec<u32> = NAMES.iter().map(|name| feature_key(name)).collect();
1139 let PairWeights::Hashed { bits, weights } = model.pairs() else {
1140 panic!("the pairs are hashed");
1141 };
1142 let weights = weights.clone();
1143 let place = |one: usize, other: usize| bucket(keys[one], keys[other], *bits) as usize;
1144 assert_eq!(
1145 model.score(&[0, 2]),
1146 0.25 + 0.5 + 2.0 + f64::from(weights[place(0, 2)])
1147 );
1148 let all: f64 = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
1149 .iter()
1150 .map(|(one, other)| f64::from(weights[place(*one, *other)]))
1151 .sum();
1152 assert_eq!(model.score(&[0, 1, 2, 3]), 0.25 + (1.25 + all));
1153 assert_eq!(model.pair_count(), 15);
1155 }
1156
1157 #[test]
1158 fn the_place_of_a_pair_is_the_same_for_its_two_orders() {
1159 assert_eq!(feature_key("a"), 0xaf63_dc4c ^ 0x8601_ec8c);
1162 let (one, other) = (feature_key("SFS:は"), feature_key("DIST:1"));
1163 for bits in [1, 4, 22, 30] {
1164 let place = bucket(one, other, bits);
1165 assert_eq!(place, bucket(other, one, bits));
1166 assert!(place < 1 << bits);
1167 }
1168 assert_eq!(bucket(one, other, 22) >> 2, bucket(one, other, 20));
1171 let mut value = (u64::from(one.min(other)) << 32) | u64::from(one.max(other));
1173 value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
1174 value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
1175 assert_eq!(bucket(one, other, 30), (value >> 34) as u32);
1176 assert_eq!(bucket(1, 2, 16), {
1178 let mut value = (1u64 << 32) | 2;
1179 value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
1180 value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
1181 (value >> 48) as u32
1182 });
1183 let keys: Vec<u32> = NAMES.iter().map(|name| feature_key(name)).collect();
1185 let mut places: Vec<u32> = vec![
1186 bucket(keys[0], keys[1], 4),
1187 bucket(keys[0], keys[2], 4),
1188 bucket(keys[1], keys[2], 4),
1189 bucket(keys[2], keys[3], 4),
1190 ];
1191 places.dedup();
1192 assert!(places.len() > 1);
1193 }
1194
1195 #[test]
1196 fn what_is_not_a_model_is_refused() {
1197 let pairs = || PairWeights::Exact(vec![((0, 2), 1.5)]);
1198 assert_eq!(
1199 refused(f64::NAN, features(), pairs()),
1200 "a weight is not finite"
1201 );
1202 let mut other = features();
1203 other[1].1 = f32::INFINITY;
1204 assert_eq!(refused(0.0, other, pairs()), "a weight is not finite");
1205 assert_eq!(
1206 refused(
1207 0.0,
1208 features(),
1209 PairWeights::Exact(vec![((0, 2), f32::NAN)])
1210 ),
1211 "a weight is not finite"
1212 );
1213 let table = |weight: f32| PairWeights::Hashed {
1214 bits: 1,
1215 weights: vec![0.0, weight],
1216 };
1217 assert_eq!(
1218 refused(0.0, features(), table(f32::NEG_INFINITY)),
1219 "a weight is not finite"
1220 );
1221 assert!(
1222 ParserModel::new(
1223 Schema::ipadic(),
1224 FeatureSet::default(),
1225 0.0,
1226 features(),
1227 table(1.0)
1228 )
1229 .is_ok()
1230 );
1231
1232 for (one, other) in [(0, 1), (1, 1)] {
1234 let mut unsorted = features();
1235 unsorted[one].0 = features()[other].0.clone();
1236 unsorted[other].0 = features()[one].0.clone();
1237 if one == other {
1238 unsorted[0].0 = unsorted[1].0.clone();
1239 }
1240 assert_eq!(
1241 refused(0.0, unsorted, pairs()),
1242 "the features are not sorted, each once"
1243 );
1244 }
1245
1246 for pair in [(1, 1), (2, 0), (0, 4)] {
1249 assert_eq!(
1250 refused(0.0, features(), PairWeights::Exact(vec![(pair, 1.0)])),
1251 "a pair does not name two features, the smaller number first"
1252 );
1253 }
1254 for pairs in [[(1, 3), (0, 2)], [(0, 2), (0, 2)]] {
1256 let pairs = pairs.iter().map(|pair| (*pair, 1.0)).collect();
1257 assert_eq!(
1258 refused(0.0, features(), PairWeights::Exact(pairs)),
1259 "the pairs are not sorted, each once"
1260 );
1261 }
1262
1263 for (bits, count) in [(2, 3), (2, 5), (0, 1), (31, 2)] {
1265 let table = PairWeights::Hashed {
1266 bits,
1267 weights: vec![0.0; count],
1268 };
1269 assert_eq!(
1270 refused(0.0, features(), table),
1271 format!("a table of hashed pairs of {bits} bits has {count} weights")
1272 );
1273 }
1274 }
1275
1276 #[test]
1277 fn a_compact_model_has_only_what_has_a_weight() {
1278 let features: Vec<(String, f32)> = ["a", "b", "c", "d", "e"]
1281 .iter()
1282 .zip([1.0, 0.0, -2.0, 0.0, 0.5])
1283 .map(|(name, weight)| (name.to_string(), weight))
1284 .collect();
1285 let model = ParserModel::new(
1286 Schema::ipadic(),
1287 FeatureSet::default(),
1288 0.5,
1289 features.clone(),
1290 PairWeights::Exact(vec![((0, 1), 0.0), ((0, 4), 3.0), ((2, 3), -1.0)]),
1291 )
1292 .unwrap();
1293 let before: Vec<f64> = [vec![0, 4], vec![2, 3], vec![0, 1, 2, 3, 4]]
1294 .iter()
1295 .map(|features| model.score(features))
1296 .collect();
1297 let compact = model.compact();
1298 assert_eq!(compact.feature_count(), 4);
1299 assert_eq!(compact.id("b"), None);
1300 assert_eq!(compact.id("c"), Some(1));
1302 assert_eq!(compact.id("d"), Some(2));
1303 assert_eq!(
1304 compact.pairs(),
1305 &PairWeights::Exact(vec![((0, 3), 3.0), ((1, 2), -1.0)])
1306 );
1307 let after: Vec<f64> = [vec![0, 3], vec![1, 2], vec![0, 1, 2, 3]]
1308 .iter()
1309 .map(|features| compact.score(features))
1310 .collect();
1311 assert_eq!(after, before);
1312 assert_eq!(compact.clone().compact(), compact);
1314
1315 let table = PairWeights::Hashed {
1318 bits: 2,
1319 weights: vec![0.0, 1.0, 0.0, -1.0],
1320 };
1321 let model = ParserModel::new(
1322 Schema::ipadic(),
1323 FeatureSet::default(),
1324 0.5,
1325 features,
1326 table.clone(),
1327 )
1328 .unwrap()
1329 .compact();
1330 assert_eq!(model.feature_count(), 3);
1331 assert_eq!(model.id("d"), None);
1332 assert_eq!(model.pairs(), &table);
1333 }
1334
1335 #[test]
1336 fn a_quantization_has_a_name_and_a_code() {
1337 for (quantization, name, code) in Quantization::ALL {
1338 assert_eq!(quantization.name(), name);
1339 assert_eq!(Quantization::from_name(name), Some(quantization));
1340 assert_eq!(quantization.code(), code);
1341 assert_eq!(Quantization::from_code(code), Some(quantization));
1342 }
1343 assert_eq!(Quantization::from_name("f32"), Some(Quantization::F32));
1346 assert_eq!(Quantization::from_name("i16"), Some(Quantization::I16));
1347 assert_eq!(Quantization::from_name("i8"), Some(Quantization::I8));
1348 assert_eq!(
1349 [
1350 Quantization::F32.code(),
1351 Quantization::I16.code(),
1352 Quantization::I8.code()
1353 ],
1354 [0, 1, 2]
1355 );
1356 assert_eq!(Quantization::from_name("f64"), None);
1357 assert_eq!(Quantization::from_code(3), None);
1358 assert_eq!(
1359 [
1360 Quantization::F32.width(),
1361 Quantization::I16.width(),
1362 Quantization::I8.width()
1363 ],
1364 [4, 2, 1]
1365 );
1366 }
1367
1368 #[test]
1369 fn the_part_of_a_file_scores_as_the_model_in_memory() {
1370 for model in [exact(), hashed()] {
1371 let bytes = part(&model, Quantization::F32);
1372 let layout = ParserLayout::read(&bytes, 0).unwrap();
1373 let read = layout.part(&bytes);
1374 assert_eq!(layout.feature_set(), model.feature_set());
1375 assert_eq!(read.feature_count(), 4);
1376 assert_eq!(read.quantization(), Quantization::F32);
1377 for (index, name) in NAMES.iter().enumerate() {
1378 assert_eq!(read.id(name), Some(index as u32));
1379 }
1380 assert_eq!(read.id("SFS:が"), None);
1381 for features in subsets() {
1383 assert_eq!(
1384 read.score(&features).to_bits(),
1385 model.score(&features).to_bits(),
1386 "{features:?}"
1387 );
1388 }
1389 assert_eq!(part(&model.clone(), Quantization::F32), bytes);
1391 }
1392 let bytes = part(&exact(), Quantization::F32);
1393 assert_eq!(
1394 ParserLayout::read(&bytes, 0)
1395 .unwrap()
1396 .part(&bytes)
1397 .pair_count(),
1398 3
1399 );
1400 let bytes = part(&hashed(), Quantization::F32);
1401 assert_eq!(
1402 ParserLayout::read(&bytes, 0)
1403 .unwrap()
1404 .part(&bytes)
1405 .pair_count(),
1406 16
1407 );
1408 }
1409
1410 #[test]
1411 fn the_weights_of_a_model_with_a_unit_are_multiplied_by_it() {
1412 let whole = ParserModel::new(
1414 Schema::ipadic(),
1415 FeatureSet::cabocha(),
1416 -3.0 * 0.3,
1417 NAMES
1418 .iter()
1419 .zip([2.0, -5.0, 8.0, 0.0])
1420 .map(|(name, weight)| (name.to_string(), weight))
1421 .collect(),
1422 PairWeights::Exact(vec![((0, 2), 6.0), ((1, 3), -3.0), ((2, 3), 1.0)]),
1423 )
1424 .unwrap();
1425 assert_eq!(whole.unit(), 1.0);
1426 let model = whole.clone().with_unit(0.3).unwrap();
1427 assert_eq!(model.unit(), 0.3);
1428 assert_ne!(model, whole);
1429 assert_eq!(model.score(&[0, 2]), -3.0 * 0.3 + 0.3 * 16.0);
1431 assert_eq!(model.score(&[]), -3.0 * 0.3);
1432 let three = ParserModel::new(
1435 Schema::ipadic(),
1436 FeatureSet::cabocha(),
1437 -3.0 * 0.3,
1438 vec![("a".to_string(), 3.0)],
1439 PairWeights::Exact(Vec::new()),
1440 )
1441 .unwrap()
1442 .with_unit(0.3)
1443 .unwrap();
1444 assert_eq!(three.score(&[0]), 0.0);
1445
1446 let bytes = part(&model, Quantization::F32);
1449 let layout = ParserLayout::read(&bytes, 0).unwrap();
1450 assert_eq!(layout.scale, 0.3);
1451 let read = layout.part(&bytes);
1452 for features in subsets() {
1453 assert_eq!(
1454 read.score(&features).to_bits(),
1455 model.score(&features).to_bits(),
1456 "{features:?}"
1457 );
1458 }
1459 let bytes = part(&model, Quantization::I8);
1462 let layout = ParserLayout::read(&bytes, 0).unwrap();
1463 assert_eq!(layout.scale, 8.0 / 127.0 * 0.3);
1464 let read = layout.part(&bytes);
1465 assert!((read.score(&[0, 2]) - model.score(&[0, 2])).abs() < 0.3 * 8.0 / 127.0 * 2.0);
1466
1467 let compact = model.clone().compact();
1469 assert_eq!(compact.unit(), 0.3);
1470 assert_eq!(compact.feature_count(), 4);
1471 let bytes = part(&whole, Quantization::F32);
1473 assert_eq!(ParserLayout::read(&bytes, 0).unwrap().scale, 1.0);
1474 }
1475
1476 #[test]
1477 fn refuses_a_unit_that_is_not_one() {
1478 for unit in [0.0, -1.0, f64::NAN, f64::INFINITY] {
1479 let error = exact().with_unit(unit).unwrap_err();
1480 assert!(matches!(error, Error::Parser(_)), "{error:?}");
1481 assert!(
1482 error.to_string().contains("has to be greater than 0"),
1483 "{error}"
1484 );
1485 }
1486 }
1487
1488 #[test]
1489 fn quantized_weights_are_whole_numbers_times_a_scale() {
1490 for model in [exact(), hashed()] {
1491 let sizes: Vec<usize> = Quantization::ALL
1492 .iter()
1493 .map(|(quantization, _, _)| part(&model, *quantization).len())
1494 .collect();
1495 assert!(sizes[0] > sizes[1] && sizes[1] > sizes[2], "{sizes:?}");
1496
1497 for (quantization, largest) in [(Quantization::I16, 32767.0), (Quantization::I8, 127.0)]
1498 {
1499 let bytes = part(&model, quantization);
1500 let layout = ParserLayout::read(&bytes, 0).unwrap();
1501 let read = layout.part(&bytes);
1502 assert_eq!(read.quantization(), quantization);
1503 let scale = 2.0 / largest;
1505 assert_eq!(layout.scale, scale);
1506 for features in subsets() {
1507 let weights =
1510 features.len() + features.len() * features.len().saturating_sub(1) / 2;
1511 let difference = (read.score(&features) - model.score(&features)).abs();
1512 assert!(
1513 difference <= scale / 2.0 * weights as f64 + 1e-12,
1514 "{quantization:?} {features:?}: {difference}"
1515 );
1516 }
1517 assert_eq!(read.score(&[]), model.bias());
1519 }
1520 }
1521 let bytes = part(&exact(), Quantization::I8);
1524 let read = ParserLayout::read(&bytes, 0).unwrap();
1525 let read = read.part(&bytes);
1526 assert_eq!(read.score(&[2]), -1.0 + 2.0 / 127.0 * 127.0);
1527 assert_eq!(read.score(&[1]), -1.0 + 2.0 / 127.0 * -79.0);
1528 assert_eq!(read.score(&[0]), -1.0 + 2.0 / 127.0 * 32.0);
1531 let heavy = ParserModel::new(
1534 Schema::ipadic(),
1535 FeatureSet::default(),
1536 0.0,
1537 features(),
1538 PairWeights::Exact(vec![((0, 1), -4.0)]),
1539 )
1540 .unwrap();
1541 let bytes = part(&heavy, Quantization::I8);
1542 assert_eq!(ParserLayout::read(&bytes, 0).unwrap().scale, 4.0 / 127.0);
1543 let table = PairWeights::Hashed {
1544 bits: 1,
1545 weights: vec![0.0, 8.0],
1546 };
1547 let heavy = ParserModel::new(
1548 Schema::ipadic(),
1549 FeatureSet::default(),
1550 0.0,
1551 features(),
1552 table,
1553 )
1554 .unwrap();
1555 let bytes = part(&heavy, Quantization::I16);
1556 assert_eq!(ParserLayout::read(&bytes, 0).unwrap().scale, 8.0 / 32767.0);
1557 let empty = ParserModel::new(
1559 Schema::ipadic(),
1560 FeatureSet::default(),
1561 0.5,
1562 Vec::new(),
1563 PairWeights::Exact(Vec::new()),
1564 )
1565 .unwrap();
1566 let bytes = part(&empty, Quantization::I8);
1567 let layout = ParserLayout::read(&bytes, 0).unwrap();
1568 assert_eq!(layout.scale, 1.0);
1569 assert_eq!(layout.part(&bytes).score(&[]), 0.5);
1570 assert_eq!(layout.part(&bytes).id("a"), None);
1571 }
1572
1573 fn larger(hashed: bool) -> ParserModel {
1576 let mut state = 0x2545_f491_4f6c_dd1du64;
1577 let mut next = move || {
1578 state ^= state << 13;
1580 state ^= state >> 7;
1581 state ^= state << 17;
1582 ((state % 2001) as f32 - 1000.0) / 250.0
1583 };
1584 let features: Vec<(String, f32)> = (0..40)
1585 .map(|index| (format!("F{index:02}:素性"), next()))
1586 .collect();
1587 let pairs = if hashed {
1588 PairWeights::Hashed {
1589 bits: 7,
1590 weights: (0..128).map(|_| next()).collect(),
1591 }
1592 } else {
1593 let mut pairs = Vec::new();
1594 for one in 0..40u32 {
1595 for other in one + 1..40 {
1596 if (one * 7 + other) % 3 == 0 {
1597 pairs.push(((one, other), next()));
1598 }
1599 }
1600 }
1601 PairWeights::Exact(pairs)
1602 };
1603 ParserModel::new(
1604 Schema::ipadic(),
1605 FeatureSet::default(),
1606 0.125,
1607 features,
1608 pairs,
1609 )
1610 .unwrap()
1611 }
1612
1613 #[test]
1614 fn a_larger_model_scores_the_same_from_a_file() {
1615 for hashed in [false, true] {
1616 let model = larger(hashed);
1617 let bytes = part(&model, Quantization::F32);
1618 let layout = ParserLayout::read(&bytes, 0).unwrap();
1619 let read = layout.part(&bytes);
1620 assert_eq!(read.feature_count(), 40);
1621 let mut different = 0;
1625 for mask in 1..400u64 {
1626 let features: Vec<u32> = (0..40u32)
1627 .filter(|index| (mask.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> index) & 1 == 1)
1628 .collect();
1629 let (from_file, in_memory) = (read.score(&features), model.score(&features));
1630 assert_eq!(from_file.to_bits(), in_memory.to_bits(), "{features:?}");
1631 different += usize::from(in_memory != model.bias());
1632 }
1633 assert!(different > 390);
1634 let all: Vec<u32> = (0..40).collect();
1636 assert_eq!(read.score(&all).to_bits(), model.score(&all).to_bits());
1637 for feature in 0..40 {
1638 assert_eq!(read.score(&[feature]), model.score(&[feature]));
1639 assert_eq!(read.id(&format!("F{feature:02}:素性")), Some(feature));
1640 }
1641 }
1642 }
1643
1644 #[test]
1645 fn the_layout_is_counted_from_the_base() {
1646 for model in [exact(), hashed()] {
1647 let part = part(&model, Quantization::I16);
1648 let mut bytes = vec![0xa5; 13];
1649 bytes.extend_from_slice(&part);
1650 let layout = ParserLayout::read(&part, 13).unwrap();
1651 let read = layout.part(&bytes);
1652 let alone = ParserLayout::read(&part, 0).unwrap();
1653 for features in subsets() {
1654 assert_eq!(read.score(&features), alone.part(&part).score(&features));
1655 }
1656 assert_eq!(read.id("SFS:を"), Some(2));
1657 let read = layout.part(&bytes[..20]);
1659 assert_eq!(read.id("SFS:を"), None);
1660 let _ = read.score(&[0, 1, 2, 3]);
1661 }
1662 }
1663
1664 fn after_the_set(model: &ParserModel) -> usize {
1667 4 + model.feature_set().to_string().len()
1668 }
1669
1670 #[test]
1671 fn refuses_a_parser_part_that_is_not_one() {
1672 for model in [exact(), hashed()] {
1673 let bytes = part(&model, Quantization::F32);
1674 assert!(ParserLayout::read(&bytes, 0).is_ok());
1675 let start = after_the_set(&model);
1676
1677 let mut other = bytes.clone();
1679 other[4] = b'x';
1680 assert!(
1681 error(&other).starts_with("the model has a feature set that is not one: "),
1682 "{}",
1683 error(&other)
1684 );
1685
1686 let mut other = bytes.clone();
1687 other[start] = 3;
1688 assert_eq!(error(&other), "the model has the unknown quantization 3");
1689 let mut other = bytes.clone();
1690 other[start + 1] = 2;
1691 assert_eq!(error(&other), "the model has the unknown table of pairs 2");
1692
1693 for offset in [start + 2, start + 10] {
1695 let mut other = bytes.clone();
1696 other[offset..offset + 8].copy_from_slice(&f64::NAN.to_le_bytes());
1697 assert_eq!(error(&other), "the model has a weight that is not finite");
1698 }
1699
1700 for scale in [0.0f64, -1.0] {
1702 let mut other = bytes.clone();
1703 other[start + 10..start + 18].copy_from_slice(&scale.to_le_bytes());
1704 assert_eq!(
1705 error(&other),
1706 format!("the model has the scale {scale}, which is not above 0")
1707 );
1708 }
1709
1710 let mut other = bytes.clone();
1712 let last = other.len() - 4;
1713 other[last..].copy_from_slice(&f32::INFINITY.to_le_bytes());
1714 assert_eq!(error(&other), "the model has a weight that is not finite");
1715
1716 let mut other = bytes.clone();
1717 other.push(0);
1718 assert_eq!(error(&other), "the model has 1 bytes after its parser");
1719 for length in 0..bytes.len() {
1720 let message = error(&bytes[..length]);
1721 assert!(
1722 message.starts_with("the model ends early"),
1723 "{length}: {message}"
1724 );
1725 }
1726 }
1727 }
1728
1729 #[test]
1730 fn refuses_weights_of_features_and_pairs_that_are_not_what_the_format_says() {
1731 let bytes = part(&exact(), Quantization::F32);
1735 let pairs = bytes.len() - (8 + 5 * 4 + 3 * 4 + 3 * 4);
1736 let values = pairs - 8 * 4 - 4 * 4;
1737 assert_eq!(bytes[values..values + 4], 0.5f32.to_le_bytes());
1738 let mut other = bytes.clone();
1739 other[values..values + 4].copy_from_slice(&f32::NAN.to_le_bytes());
1740 assert_eq!(error(&other), "the model has a weight that is not finite");
1741
1742 assert_eq!(bytes[pairs..pairs + 8], 3u64.to_le_bytes());
1745 let offsets = pairs + 8;
1746 let offset = |index: usize| bytes[offsets + 4 * index];
1747 assert_eq!(
1748 [offset(0), offset(1), offset(2), offset(3), offset(4)],
1749 [0, 1, 2, 3, 3]
1750 );
1751 let columns = offsets + 5 * 4;
1752 assert_eq!(
1753 [bytes[columns], bytes[columns + 4], bytes[columns + 8]],
1754 [2, 3, 3]
1755 );
1756 let order = "the model has pairs that are not in the order of their features";
1757 for (index, value) in [(0, 1), (2, 0), (4, 2), (4, 4)] {
1760 let mut other = bytes.clone();
1761 other[offsets + 4 * index] = value;
1762 assert_eq!(error(&other), order, "offset {index} = {value}");
1763 }
1764 for (index, value) in [(0, 0), (1, 4), (2, 2)] {
1767 let mut other = bytes.clone();
1768 other[columns + 4 * index] = value;
1769 assert_eq!(error(&other), order, "column {index} = {value}");
1770 }
1771 let model = ParserModel::new(
1773 Schema::ipadic(),
1774 FeatureSet::default(),
1775 0.0,
1776 features(),
1777 PairWeights::Exact(vec![((0, 1), 1.0), ((0, 2), 1.0)]),
1778 )
1779 .unwrap();
1780 let bytes = part(&model, Quantization::F32);
1781 let columns = bytes.len() - 2 * 4 - 2 * 4;
1782 assert_eq!([bytes[columns], bytes[columns + 4]], [1, 2]);
1783 let mut other = bytes.clone();
1784 other[columns] = 2;
1785 other[columns + 4] = 1;
1786 assert_eq!(error(&other), order);
1787 let mut other = bytes.clone();
1788 other[columns + 4] = 1;
1789 assert_eq!(error(&other), order);
1790 let five: Vec<(String, f32)> = ["a", "b", "c", "d", "e"]
1794 .iter()
1795 .map(|name| (name.to_string(), 1.0))
1796 .collect();
1797 let model = ParserModel::new(
1798 Schema::ipadic(),
1799 FeatureSet::default(),
1800 0.0,
1801 five,
1802 PairWeights::Exact(vec![((0, 1), 1.0), ((0, 3), 1.0), ((2, 4), 1.0)]),
1803 )
1804 .unwrap();
1805 let bytes = part(&model, Quantization::F32);
1806 let columns = bytes.len() - 3 * 4 - 3 * 4;
1807 let offsets = columns - 6 * 4;
1808 let offset = |index: usize| bytes[offsets + 4 * index];
1809 assert_eq!(
1810 [
1811 offset(0),
1812 offset(1),
1813 offset(2),
1814 offset(3),
1815 offset(4),
1816 offset(5)
1817 ],
1818 [0, 2, 2, 3, 3, 3]
1819 );
1820 assert_eq!(
1821 [bytes[columns], bytes[columns + 4], bytes[columns + 8]],
1822 [1, 3, 4]
1823 );
1824 let mut other = bytes.clone();
1825 other[offsets + 4 * 2] = 1;
1826 assert_eq!(error(&other), order);
1827 let mut other = bytes.clone();
1829 other[offsets + 4 * 3] = 2;
1830 other[offsets + 4 * 4] = 2;
1831 other[offsets + 4 * 5] = 2;
1832 assert_eq!(error(&other), order);
1833
1834 let pairs = columns - 5 * 4 - 8;
1836 let mut other = bytes.clone();
1837 other[pairs..pairs + 8].copy_from_slice(&u64::MAX.to_le_bytes());
1838 assert!(error(&other).starts_with("the model ends early"));
1839
1840 let bytes = part(&hashed(), Quantization::I8);
1842 let bits = bytes.len() - 16 - 4;
1843 assert_eq!(bytes[bits..bits + 4], 4u32.to_le_bytes());
1844 for value in [0, 31] {
1845 let mut other = bytes.clone();
1846 other[bits] = value;
1847 assert_eq!(
1848 error(&other),
1849 format!("the model has a table of hashed pairs of {value} bits")
1850 );
1851 }
1852 let mut other = bytes.clone();
1853 other[bits] = 5;
1854 assert!(error(&other).starts_with("the model ends early"));
1855 }
1856
1857 #[test]
1858 fn no_changed_byte_makes_reading_or_scoring_panic() {
1859 for (model, quantization) in [
1860 (exact(), Quantization::F32),
1861 (exact(), Quantization::I8),
1862 (hashed(), Quantization::I16),
1863 ] {
1864 let bytes = part(&model, quantization);
1865 let mut read = 0;
1866 for position in 0..bytes.len() {
1867 for value in [0, 1, 0x7f, 0x80, 0xff, bytes[position] ^ 1] {
1868 if value == bytes[position] {
1869 continue;
1870 }
1871 let mut other = bytes.clone();
1872 other[position] = value;
1873 if let Ok(layout) = ParserLayout::read(&other, 0) {
1874 read += 1;
1875 let part = layout.part(&other);
1876 for name in NAMES {
1877 let _ = part.id(name);
1878 }
1879 let _ = part.score(&[0, 1, 2, 3]);
1880 let _ = part.score(&[3, 2, 1, 0, 9, 9]);
1881 }
1882 }
1883 }
1884 assert!(read > 0);
1885 }
1886 }
1887}