1use serde::Deserialize;
20use std::sync::OnceLock;
21
22#[derive(Deserialize)]
23struct Weights {
24 #[serde(rename = "L")]
25 l: usize,
26 #[serde(rename = "C")]
27 c: usize,
28 k: usize,
29 nsym: usize,
30 aa_order: String,
31 classes: Vec<String>,
32 #[allow(dead_code)]
33 n_conv: usize,
34 conv1_w: Vec<Vec<Vec<f32>>>, conv1_b: Vec<f32>,
36 conv2_w: Vec<Vec<Vec<f32>>>, conv2_b: Vec<f32>,
38 conv3_w: Vec<Vec<Vec<f32>>>,
39 conv3_b: Vec<f32>,
40 conv4_w: Vec<Vec<Vec<f32>>>,
41 conv4_b: Vec<f32>,
42 type_w: Vec<Vec<f32>>, type_b: Vec<f32>,
44}
45
46#[derive(Debug, Clone)]
48pub struct Prediction {
49 pub label: String,
51 pub prob: f32,
53 pub class_index: usize,
55 pub probs: Vec<f32>,
57}
58
59pub struct Model {
61 w: Weights,
62 aa_to_idx: [usize; 256],
64 conv_wf: Vec<Vec<f32>>,
68}
69
70fn flatten3(w: &[Vec<Vec<f32>>]) -> Vec<f32> {
73 let mut v = Vec::new();
74 for a in w {
75 for b in a {
76 v.extend_from_slice(b);
77 }
78 }
79 v
80}
81
82const EMBEDDED_WEIGHTS_GZ: &[u8] = include_bytes!("../weights.json.gz");
85
86impl Model {
87 pub fn embedded() -> &'static Model {
89 static M: OnceLock<Model> = OnceLock::new();
90 M.get_or_init(|| {
91 use std::io::Read;
92 let mut s = String::new();
93 flate2::read::GzDecoder::new(EMBEDDED_WEIGHTS_GZ)
94 .read_to_string(&mut s)
95 .expect("decompress embedded weights");
96 Model::from_json(&s).expect("embedded weights parse")
97 })
98 }
99
100 pub fn from_json(s: &str) -> Result<Model, String> {
102 let w: Weights = serde_json::from_str(s).map_err(|e| e.to_string())?;
103 let mut aa_to_idx = [0usize; 256]; for (i, c) in w.aa_order.bytes().enumerate() {
105 aa_to_idx[c as usize] = i + 1;
106 aa_to_idx[c.to_ascii_lowercase() as usize] = i + 1;
107 }
108 let conv_wf = vec![
109 flatten3(&w.conv1_w),
110 flatten3(&w.conv2_w),
111 flatten3(&w.conv3_w),
112 flatten3(&w.conv4_w),
113 ];
114 Ok(Model { aa_to_idx, conv_wf, w })
115 }
116
117 pub fn classes(&self) -> &[String] {
119 &self.w.classes
120 }
121
122 pub fn predict_many(&self, seqs: &[&[u8]]) -> Vec<Prediction> {
126 use rayon::prelude::*;
127 seqs.par_iter().map(|s| self.predict(s)).collect()
128 }
129
130 pub fn predict(&self, aa: &[u8]) -> Prediction {
132 let l = self.w.l;
133 let c = self.w.c;
134 let chan = self.w.nsym - 1; let mut idx = vec![0usize; l];
138 for t in 0..l.min(aa.len()) {
139 idx[t] = self.aa_to_idx[aa[t] as usize];
140 }
141 let mut oh = vec![0.0f32; chan * l];
143 for t in 0..l {
144 let j = idx[t];
145 if j >= 1 && j <= chan {
146 oh[(j - 1) * l + t] = 1.0;
147 }
148 }
149 let h1 = conv1d_relu(&oh, chan, l, &self.conv_wf[0], &self.w.conv1_b, c, self.w.k);
151 let h2 = conv1d_relu(&h1, c, l, &self.conv_wf[1], &self.w.conv2_b, c, self.w.k);
152 let h3 = conv1d_relu(&h2, c, l, &self.conv_wf[2], &self.w.conv3_b, c, self.w.k);
153 let h = conv1d_relu(&h3, c, l, &self.conv_wf[3], &self.w.conv4_b, c, self.w.k);
154
155 let mut pooled = vec![0.0f32; 2 * c];
157 for ci in 0..c {
158 let base = ci * l;
159 let mut sum = 0.0f32;
160 let mut mx = f32::NEG_INFINITY;
161 for t in 0..l {
162 let v = h[base + t];
163 sum += v;
164 if v > mx {
165 mx = v;
166 }
167 }
168 pooled[ci] = sum / l as f32;
169 pooled[c + ci] = mx;
170 }
171 let nclass = self.w.classes.len();
173 let mut logits = vec![0.0f32; nclass];
174 for k in 0..nclass {
175 let mut s = self.w.type_b[k];
176 let row = &self.w.type_w[k];
177 for j in 0..2 * c {
178 s += row[j] * pooled[j];
179 }
180 logits[k] = s;
181 }
182 let probs = softmax(&logits);
183 let mut best = 0usize;
184 for k in 1..nclass {
185 if probs[k] > probs[best] {
186 best = k;
187 }
188 }
189 Prediction {
190 label: self.w.classes[best].clone(),
191 prob: probs[best],
192 class_index: best,
193 probs,
194 }
195 }
196}
197
198fn conv1d_relu(
207 inp: &[f32],
208 cin: usize,
209 l: usize,
210 w: &[f32],
211 b: &[f32],
212 cout: usize,
213 k: usize,
214) -> Vec<f32> {
215 let pad = k as isize / 2;
216 let mut out = vec![0.0f32; cout * l];
217 for co in 0..cout {
218 let orow = &mut out[co * l..co * l + l];
219 for o in orow.iter_mut() {
220 *o = b[co];
221 }
222 let wco = &w[co * cin * k..(co + 1) * cin * k];
223 for ci in 0..cin {
224 let irow = &inp[ci * l..ci * l + l];
225 let wci = &wco[ci * k..ci * k + k];
226 for dk in 0..k {
227 let wt = wci[dk];
228 let shift = dk as isize - pad;
229 let (t0, t1) = if shift >= 0 {
230 (0usize, l.saturating_sub(shift as usize))
231 } else {
232 (((-shift) as usize).min(l), l)
233 };
234 if t0 >= t1 {
235 continue;
236 }
237 let src = (t0 as isize + shift) as usize;
238 for (o, &x) in orow[t0..t1].iter_mut().zip(&irow[src..src + (t1 - t0)]) {
239 *o += wt * x;
240 }
241 }
242 }
243 for o in orow.iter_mut() {
244 if *o < 0.0 {
245 *o = 0.0;
246 }
247 }
248 }
249 out
250}
251
252fn softmax(x: &[f32]) -> Vec<f32> {
253 let m = x.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
254 let mut e: Vec<f32> = x.iter().map(|v| (v - m).exp()).collect();
255 let s: f32 = e.iter().sum();
256 for v in &mut e {
257 *v /= s;
258 }
259 e
260}
261
262#[cfg(test)]
263mod tests {
264 use super::*;
265
266 #[test]
267 fn embedded_predicts() {
268 let m = Model::embedded();
269 let p = m.predict(b"MSKIVKIIGREIIDSRGNPTVEAEVHLEGGFVGMAAAPSGASTGSREALELRDGDKSRFLGKG");
270 let s: f32 = p.probs.iter().sum();
271 assert!((s - 1.0).abs() < 1e-3, "probs sum {s}");
272 assert!(!p.label.is_empty());
273 }
274}