Skip to main content

narrative_graph/heuristic/
model.rs

1//! Optional, local DeBERTa relation extraction using a fine-tuned checkpoint.
2
3mod input;
4
5use super::{aggregate, collect_candidates, dedup_candidates, normalize_relation, pack::ENGLISH};
6use super::{segment, Context, Emitted};
7use crate::{
8    AggregateTriple, Language, NarrativeGraphError, Options, Polarity, RelationshipState,
9    TripleCandidate,
10};
11use anyhow::{ensure, Context as _, Result};
12use input::{MAX_NAMES, MAX_TOKENS};
13use serde::Deserialize;
14use std::collections::BTreeSet;
15use std::fs::File;
16use std::io::Read;
17use std::path::Path;
18use std::sync::Arc;
19use tract_onnx::prelude::{
20    tvec, DatumType, Framework, InferenceModelExt, IntoRunnable, Tensor, TypedRunnableModel,
21};
22
23#[doc(hidden)]
24pub use input::{Input, InputTokenizer};
25
26const BATCH: usize = 2;
27
28#[derive(Deserialize)]
29struct Manifest {
30    version: u32,
31    labels: Vec<String>,
32    threshold: f32,
33}
34
35struct Label {
36    relation: String,
37    polarity: Polarity,
38}
39
40/// A local student checkpoint for English prose. Load once and reuse across documents.
41pub struct StudentModel {
42    tokenizer: InputTokenizer,
43    network: Arc<TypedRunnableModel>,
44    labels: Vec<Label>,
45    threshold: f32,
46}
47
48impl StudentModel {
49    /// Load `student.json`, `spm.model` and the ONNX graph exported by the training script.
50    pub fn load(directory: impl AsRef<Path>) -> Result<Self> {
51        let directory = directory.as_ref();
52        let manifest = read_artifact(&directory.join("student.json"), 64 << 10)?;
53        let manifest: Manifest =
54            serde_json::from_slice(&manifest).context("invalid student.json")?;
55        let labels = manifest.labels()?;
56        let tokenizer = InputTokenizer::load(&directory.join("spm.model"))?;
57        let mut artifact = open_artifact(&directory.join("model.onnx"), 640 << 20)?;
58        let network = tract_onnx::onnx()
59            .model_for_read(&mut artifact)?
60            .into_optimized()?;
61        let shapes: [&[usize]; 4] = [
62            &[BATCH, MAX_TOKENS],
63            &[BATCH, MAX_TOKENS],
64            &[BATCH, MAX_NAMES],
65            &[BATCH],
66        ];
67        ensure!(
68            network.input_outlets()?.len() == shapes.len() && network.output_outlets()?.len() == 1,
69            "invalid student inputs or output"
70        );
71        for (index, shape) in shapes.into_iter().enumerate() {
72            let fact = network.input_fact(index)?;
73            ensure!(
74                fact.datum_type == DatumType::I64 && fact.shape.as_concrete() == Some(shape),
75                "invalid student input {index}"
76            );
77        }
78        let output = network.output_fact(0)?;
79        ensure!(
80            output.datum_type == DatumType::F32
81                && output.shape.as_concrete()
82                    == Some(&[BATCH, MAX_NAMES, MAX_NAMES, labels.len() + 1]),
83            "invalid student scores shape"
84        );
85        Ok(Self {
86            tokenizer,
87            network: network.into_runnable()?,
88            labels,
89            threshold: manifest.threshold,
90        })
91    }
92
93    /// Extract asserted candidates from the rules and the student.
94    pub fn extract_candidate_triples(
95        &self,
96        text: &str,
97        opts: &Options,
98    ) -> Result<Vec<TripleCandidate>> {
99        let mut candidates = self
100            .extract(text, opts)?
101            .into_iter()
102            .filter(|e| e.polarity == Polarity::Asserted)
103            .map(|e| e.candidate)
104            .collect();
105        dedup_candidates(&mut candidates);
106        Ok(candidates)
107    }
108
109    /// Extract asserted and denied aggregates from the rules and the student.
110    pub fn extract_aggregates(&self, text: &str, opts: &Options) -> Result<Vec<AggregateTriple>> {
111        let (mut facts, _) = aggregate::aggregate(self.extract(text, opts)?);
112        for fact in &mut facts {
113            fact.spans.dedup();
114        }
115        Ok(facts)
116    }
117
118    fn extract(&self, text: &str, opts: &Options) -> Result<Vec<Emitted>> {
119        let spans: Vec<_> = segment::split_sentences(text, &ENGLISH)
120            .into_iter()
121            .map(|(sentence, start)| [start, start + sentence.len()])
122            .collect();
123        let predicted = self.predict(text, &spans, opts)?;
124        let mut emitted = collect_candidates(text, opts, &Context::default(), None)?;
125        emitted.extend(predicted);
126        emitted.sort_by_key(|e| e.candidate.span);
127        Ok(emitted)
128    }
129
130    /// Score only the requested sentence byte ranges, with document context.
131    pub fn predict_spans(
132        &self,
133        text: &str,
134        spans: &[[usize; 2]],
135        opts: &Options,
136    ) -> Result<Vec<AggregateTriple>> {
137        let mut emitted = self.predict(text, spans, opts)?;
138        emitted.sort_by_key(|e| e.candidate.span);
139        let (facts, _) = aggregate::aggregate(emitted);
140        Ok(facts)
141    }
142
143    fn predict(&self, text: &str, spans: &[[usize; 2]], opts: &Options) -> Result<Vec<Emitted>> {
144        ensure!(
145            opts.language == Language::English,
146            "the local student requires English text"
147        );
148        let threshold = opts.min_confidence.unwrap_or(0.0);
149        if !(0.0..=1.0).contains(&threshold) {
150            return Err(NarrativeGraphError::InvalidConfidenceThreshold(threshold).into());
151        }
152        let threshold = threshold.max(self.threshold);
153        let rejected: BTreeSet<_> = opts
154            .rejections
155            .iter()
156            .map(|r| (r.subject.as_str(), r.relation.as_str(), r.object.as_str()))
157            .collect();
158        let mut emitted = Vec::new();
159        self.tokenizer
160            .for_batches(text, spans, opts, BATCH, |inputs| {
161                let inputs: Vec<_> = inputs
162                    .iter()
163                    .filter(|input| input.names.len() >= 2)
164                    .collect();
165                if inputs.is_empty() {
166                    return Ok(());
167                }
168                let scores = self.score(&inputs)?;
169                let stride = self.labels.len() + 1;
170                let windows = scores.chunks_exact(MAX_NAMES * MAX_NAMES * stride);
171                for (input, scores) in inputs.into_iter().zip(windows) {
172                    let mut pairs = Vec::new();
173                    for (subject_index, subject) in input.names.iter().enumerate() {
174                        for (object_index, object) in input.names.iter().enumerate() {
175                            if subject_index != object_index {
176                                let offset = (subject_index * MAX_NAMES + object_index) * stride;
177                                let row = &scores[offset..offset + stride];
178                                pairs.push((subject, object, row));
179                            }
180                        }
181                    }
182                    // The student compares each pair to a no-relation choice with logit zero.
183                    let links = pairs
184                        .iter()
185                        .map(|(_, _, row)| row[0])
186                        .chain(std::iter::once(0.0));
187                    let (link_max, link_sum) = softmax_scale(links)?;
188                    for (subject, object, row) in pairs {
189                        let link = (row[0] - link_max).exp() / link_sum;
190                        if link < threshold {
191                            continue;
192                        }
193                        let (relation_max, relation_sum) = softmax_scale(row[1..].iter().copied())?;
194                        for (label, &score) in self.labels.iter().zip(&row[1..]) {
195                            let confidence = link * (score - relation_max).exp() / relation_sum;
196                            if confidence < threshold {
197                                continue;
198                            }
199                            let relation = normalize_relation(&label.relation, &opts.ontology);
200                            if rejected.contains(&(
201                                subject.as_str(),
202                                relation.as_str(),
203                                object.as_str(),
204                            )) {
205                                continue;
206                            }
207                            emitted.push(Emitted {
208                                candidate: TripleCandidate {
209                                    subject: subject.clone(),
210                                    relation,
211                                    object: object.clone(),
212                                    confidence,
213                                    span: input.span,
214                                    rule: "student-model".into(),
215                                },
216                                polarity: label.polarity,
217                                single_filler: ENGLISH
218                                    .single_filler_relations
219                                    .contains(&label.relation.as_str()),
220                                state: RelationshipState::from_relation(&label.relation),
221                                ends_state: false,
222                            });
223                        }
224                    }
225                }
226                Ok(())
227            })?;
228        Ok(emitted)
229    }
230
231    fn score(&self, inputs: &[&Input]) -> Result<Vec<f32>> {
232        let mut ids = vec![i64::from(self.tokenizer.pad); BATCH * MAX_TOKENS];
233        let mut mask = vec![0_i64; BATCH * MAX_TOKENS];
234        let mut positions = vec![0_i64; BATCH * MAX_NAMES];
235        let mut targets = vec![0_i64; BATCH];
236        for (row, input) in inputs.iter().enumerate() {
237            let base = row * MAX_TOKENS;
238            for (slot, &id) in ids[base..].iter_mut().zip(&input.ids) {
239                *slot = i64::from(id);
240            }
241            mask[base..base + input.ids.len()].fill(1);
242            for (k, &position) in input.positions.iter().enumerate() {
243                positions[row * MAX_NAMES + k] = i64::from(position);
244            }
245            targets[row] = i64::from(input.target);
246        }
247        let scores = self.network.run(tvec!(
248            Tensor::from_shape(&[BATCH, MAX_TOKENS], &ids)?.into(),
249            Tensor::from_shape(&[BATCH, MAX_TOKENS], &mask)?.into(),
250            Tensor::from_shape(&[BATCH, MAX_NAMES], &positions)?.into(),
251            Tensor::from_shape(&[BATCH], &targets)?.into(),
252        ))?;
253        Ok(scores[0]
254            .to_plain_array_view::<f32>()?
255            .iter()
256            .copied()
257            .collect())
258    }
259}
260
261impl Manifest {
262    fn labels(&self) -> Result<Vec<Label>> {
263        ensure!(self.version == 2, "unsupported student checkpoint version");
264        ensure!(
265            self.threshold > 0.0 && self.threshold <= 1.0,
266            "invalid student threshold"
267        );
268        ensure!(
269            (1..=256).contains(&self.labels.len()),
270            "invalid student label count"
271        );
272        let mut seen = BTreeSet::new();
273        self.labels
274            .iter()
275            .map(|value| {
276                let (relation, polarity) = value
277                    .strip_prefix("not ")
278                    .map_or((value.as_str(), Polarity::Asserted), |name| {
279                        (name, Polarity::Denied)
280                    });
281                ensure!(
282                    !relation.is_empty()
283                        && relation.len() <= 64
284                        && relation
285                            .bytes()
286                            .all(|c| c.is_ascii_lowercase() || c == b'_')
287                        && seen.insert(value),
288                    "invalid or duplicate student label"
289                );
290                Ok(Label {
291                    relation: relation.into(),
292                    polarity,
293                })
294            })
295            .collect()
296    }
297}
298
299fn softmax_scale(logits: impl Iterator<Item = f32> + Clone) -> Result<(f32, f32)> {
300    let max = logits.clone().fold(f32::NEG_INFINITY, f32::max);
301    let sum = logits.map(|logit| (logit - max).exp()).sum::<f32>();
302    ensure!(sum.is_finite() && sum > 0.0, "non-finite student scores");
303    Ok((max, sum))
304}
305
306fn read_artifact(path: &Path, limit: u64) -> Result<Vec<u8>> {
307    let mut bytes = Vec::new();
308    open_artifact(path, limit)?.read_to_end(&mut bytes)?;
309    ensure!(
310        bytes.len() as u64 <= limit,
311        "{} exceeds the size limit",
312        path.display()
313    );
314    Ok(bytes)
315}
316
317fn open_artifact(path: &Path, limit: u64) -> Result<impl Read> {
318    let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
319    let info = file.metadata()?;
320    ensure!(
321        info.is_file() && info.len() <= limit,
322        "invalid size or type for {}",
323        path.display()
324    );
325    Ok(file.take(limit + 1))
326}
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331    use std::fs;
332    use std::path::PathBuf;
333    use std::time::{SystemTime, UNIX_EPOCH};
334
335    struct TestBundle(PathBuf);
336
337    impl Drop for TestBundle {
338        fn drop(&mut self) {
339            let _ = fs::remove_dir_all(&self.0);
340        }
341    }
342
343    fn bundle() -> Result<TestBundle> {
344        let nonce = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos();
345        let path =
346            std::env::temp_dir().join(format!("narrative-student-{}-{nonce}", std::process::id()));
347        fs::create_dir(&path)?;
348        let bundle = TestBundle(path);
349
350        fs::write(
351            bundle.0.join("spm.model"),
352            include_bytes!("../../tests/fixtures/student/spm.model"),
353        )?;
354        fs::write(
355            bundle.0.join("model.onnx"),
356            include_bytes!("../../tests/fixtures/student/model.onnx"),
357        )?;
358        let manifest = r#"{"version":2,"labels":["admires","not helps"],"threshold":0.10}"#;
359        fs::write(bundle.0.join("student.json"), manifest)?;
360        Ok(bundle)
361    }
362
363    #[test]
364    fn student_bundle_preserves_spans_polarity_and_options() -> Result<()> {
365        let bundle = bundle()?;
366        let model = StudentModel::load(&bundle.0)?;
367        let chinese = Options {
368            language: Language::Chinese,
369            ..Options::default()
370        };
371        let error = model
372            .extract_candidate_triples("賈寶玉", &chinese)
373            .unwrap_err();
374        assert_eq!(error.to_string(), "the local student requires English text");
375        let text = "Elena is Marco’s sister. Marco thanks Elena.";
376        let start = text.find("Marco thanks").unwrap();
377        let span = [start, text.len()];
378        let inside_apostrophe = text.find('’').unwrap() + 1;
379        assert!(model
380            .predict_spans(
381                text,
382                &[[inside_apostrophe, text.len()]],
383                &Options::default()
384            )
385            .is_err());
386
387        let confidence = 1.0 / 6.0;
388        for (threshold, claims) in [
389            (confidence - 0.001, 4),
390            (confidence, 4),
391            (confidence + 0.001, 0),
392        ] {
393            let opts = Options {
394                min_confidence: Some(threshold),
395                ..Options::default()
396            };
397            let facts = model.predict_spans(text, &[span], &opts)?;
398            assert_eq!(facts.len(), claims);
399            assert!(facts
400                .iter()
401                .all(|fact| fact.spans == [span] && fact.confidence == confidence));
402        }
403
404        let mut opts = Options::default();
405        opts.ontology.insert("admires".into(), "respects".into());
406        opts.rejections.push(crate::Rejection {
407            subject: "elena".into(),
408            relation: "respects".into(),
409            object: "marco".into(),
410        });
411        let facts = model.extract_aggregates(text, &opts)?;
412        assert!(facts.iter().any(|fact| fact.relation == "sister_of"));
413        assert!(facts
414            .iter()
415            .any(|fact| fact.relation == "helps" && fact.polarity == Polarity::Denied));
416        assert!(facts
417            .iter()
418            .any(|fact| fact.subject == "marco" && fact.relation == "respects"));
419        assert!(!facts
420            .iter()
421            .any(|fact| fact.subject == "elena" && fact.relation == "respects"));
422        assert!(!model
423            .extract_candidate_triples(text, &opts)?
424            .iter()
425            .any(|fact| fact.relation == "helps"));
426        Ok(())
427    }
428}