1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
use tract_core::internal::*;

use std::collections::BTreeMap;

#[derive(Clone, Debug)]
pub struct KaldiProtoModel {
    pub config_lines: ConfigLines,
    pub components: HashMap<String, Component>,
    pub adjust_final_offset: isize,
}

#[derive(Clone, Debug)]
pub struct ConfigLines {
    pub input_name: String,
    pub input_dim: usize,
    pub nodes: Vec<(String, NodeLine)>,
    pub outputs: Vec<OutputLine>,
}

#[derive(Clone, Debug)]
pub enum NodeLine {
    Component(ComponentNode),
    DimRange(DimRangeNode),
}

#[derive(Clone, Debug)]
pub struct OutputLine {
    pub output_alias: String,
    pub descriptor: GeneralDescriptor,
}

#[derive(Clone, Debug, PartialEq)]
pub enum GeneralDescriptor {
    Append(Vec<GeneralDescriptor>),
    IfDefined(Box<GeneralDescriptor>),
    Name(String),
    Offset(Box<GeneralDescriptor>, isize),
}

impl GeneralDescriptor {
    pub fn inputs(&self) -> TVec<&str> {
        match self {
            GeneralDescriptor::Append(ref gds) => gds.iter().fold(tvec!(), |mut acc, gd| {
                gd.inputs().iter().for_each(|i| {
                    if !acc.contains(i) {
                        acc.push(i)
                    }
                });
                acc
            }),
            GeneralDescriptor::IfDefined(ref gd) => gd.inputs(),
            GeneralDescriptor::Name(ref s) => tvec!(&**s),
            GeneralDescriptor::Offset(ref gd, _) => gd.inputs(),
        }
    }

    pub fn as_conv_shape_dilation(&self) -> Option<(usize, usize)> {
        if let GeneralDescriptor::Name(_) = self {
            return Some((1, 1));
        }
        if let GeneralDescriptor::Append(ref appendees) = self {
            let mut offsets = vec![];
            for app in appendees {
                match app {
                    GeneralDescriptor::Name(_) => offsets.push(0),
                    GeneralDescriptor::Offset(_, offset) => offsets.push(*offset),
                    _ => return None,
                }
            }
            let dilation = offsets[1] - offsets[0];
            if offsets.windows(2).all(|pair| pair[1] - pair[0] == dilation) {
                return Some((offsets.len(), dilation as usize));
            }
        }
        return None;
    }

    fn wire<'a>(
        &'a self,
        inlet: InletId,
        name: &str,
        model: &mut InferenceModel,
        deferred: &mut BTreeMap<InletId, String>,
        adjust_final_offset: Option<isize>,
    ) -> TractResult<()> {
        use GeneralDescriptor::*;
        match &self {
            &Name(n) => {
                deferred.insert(inlet, n.to_string());
                return Ok(());
            }
            &Append(appendees) => {
                let name = format!("{}-Append", name);
                let id = model.add_node(
                    &*name,
                    tract_core::ops::array::Concat::new(1),
                    tvec!(InferenceFact::default()),
                )?;
                model.add_edge(OutletId::new(id, 0), inlet)?;
                for (ix, appendee) in appendees.iter().enumerate() {
                    let name = format!("{}-{}", name, ix);
                    appendee.wire(
                        InletId::new(id, ix),
                        &*name,
                        model,
                        deferred,
                        adjust_final_offset,
                    )?;
                }
                return Ok(());
            }
            &IfDefined(ref o) => {
                if let &Offset(ref n, ref o) = &**o {
                    if let Name(n) = &**n {
                        let name = format!("{}-Memory", name);
                        model.add_node(
                            &*name,
                            crate::ops::memory::Memory::new(n.to_string(), *o),
                            tvec!(InferenceFact::default()),
                        )?;
                        deferred.insert(inlet, name);
                        return Ok(());
                    }
                }
            }
            &Offset(ref n, o) if *o > 0 => {
                let name = format!("{}-Delay", name);
                let crop = *o as isize + adjust_final_offset.unwrap_or(0);
                if crop < 0 {
                    bail!("Invalid offset adjustment (network as {}, adjustment is {}", o, crop)
                }
                let id = model.add_node(
                    &*name,
                    tract_core::ops::array::Crop::new(0, crop as usize, 0),
                    tvec!(InferenceFact::default()),
                )?;
                model.add_edge(OutletId::new(id, 0), inlet)?;
                n.wire(InletId::new(id, 0), &*name, model, deferred, adjust_final_offset)?;
                return Ok(());
            }
            _ => (),
        }
        bail!("Unhandled input descriptor: {:?}", self)
    }
}

#[derive(Clone, Debug)]
pub struct DimRangeNode {
    pub input: GeneralDescriptor,
    pub offset: usize,
    pub dim: usize,
}

#[derive(Clone, Debug)]
pub struct ComponentNode {
    pub input: GeneralDescriptor,
    pub component: String,
}

#[derive(Clone, Debug, Default)]
pub struct Component {
    pub klass: String,
    pub attributes: HashMap<String, Arc<Tensor>>,
}

pub struct ParsingContext<'a> {
    pub proto_model: &'a KaldiProtoModel,
}

#[derive(Clone, Default)]
pub struct KaldiOpRegister(
    pub HashMap<String, fn(&ParsingContext, node: &str) -> TractResult<Box<dyn InferenceOp>>>,
);

impl KaldiOpRegister {
    pub fn insert(
        &mut self,
        s: &'static str,
        builder: fn(&ParsingContext, node: &str) -> TractResult<Box<dyn InferenceOp>>,
    ) {
        self.0.insert(s.into(), builder);
    }
}

#[derive(Clone, Default)]
pub struct Kaldi {
    pub op_register: KaldiOpRegister,
}

impl Framework<KaldiProtoModel> for Kaldi {
    fn proto_model_for_read(&self, r: &mut dyn std::io::Read) -> TractResult<KaldiProtoModel> {
        use crate::parser;
        let mut v = vec![];
        r.read_to_end(&mut v)?;
        parser::nnet3(&*v)
    }

    fn model_for_proto_model(&self, proto_model: &KaldiProtoModel) -> TractResult<InferenceModel> {
        let ctx = ParsingContext { proto_model };
        let mut model = InferenceModel::default();
        model.add_source(
            proto_model.config_lines.input_name.clone(),
            InferenceFact::dt_shape(
                f32::datum_type(),
                shapefact!(S, (proto_model.config_lines.input_dim)),
            ),
        )?;
        let mut inputs_to_wire: BTreeMap<InletId, String> = Default::default();
        for (name, node) in &proto_model.config_lines.nodes {
            match node {
                NodeLine::Component(line) => {
                    let component = &proto_model.components[&line.component];
                    if crate::ops::AFFINE.contains(&&*component.klass)
                        && line.input.as_conv_shape_dilation().is_some()
                    {
                        let op = crate::ops::affine::affine_component(&ctx, name)?;
                        let id = model.add_node(
                            name.to_string(),
                            op,
                            tvec!(InferenceFact::default()),
                        )?;
                        inputs_to_wire
                            .insert(InletId::new(id, 0), line.input.inputs()[0].to_owned());
                    } else {
                        let op = match self.op_register.0.get(&*component.klass) {
                            Some(builder) => (builder)(&ctx, name)?,
                            None => {
                                (Box::new(tract_core::ops::unimpl::UnimplementedOp::new(
                                    1,
                                    component.klass.to_string(),
                                    format!("{:?}", line),
                                )))
                            }
                        };
                        let id = model.add_node(
                            name.to_string(),
                            op,
                            tvec!(InferenceFact::default()),
                        )?;
                        line.input.wire(
                            InletId::new(id, 0),
                            name,
                            &mut model,
                            &mut inputs_to_wire,
                            None,
                        )?
                    }
                }
                NodeLine::DimRange(line) => {
                    let op = tract_core::ops::array::Slice::new(
                        1,
                        line.offset as usize,
                        (line.offset + line.dim) as usize,
                    );
                    let id =
                        model.add_node(name.to_string(), op, tvec!(InferenceFact::default()))?;
                    line.input.wire(
                        InletId::new(id, 0),
                        name,
                        &mut model,
                        &mut inputs_to_wire,
                        None,
                    )?
                }
            }
        }
        let mut outputs = vec![];
        for o in &proto_model.config_lines.outputs {
            let output = model.add_node(
                &*o.output_alias,
                tract_core::ops::identity::Identity::default(),
                tvec!(InferenceFact::default()),
            )?;
            o.descriptor.wire(
                InletId::new(output, 0),
                "output",
                &mut model,
                &mut inputs_to_wire,
                Some(proto_model.adjust_final_offset),
            )?;
            outputs.push(OutletId::new(output, 0));
        }
        for (inlet, name) in inputs_to_wire {
            let src = OutletId::new(model.node_by_name(&*name)?.id, 0);
            model.add_edge(src, inlet)?;
        }
        model.set_output_outlets(&*outputs)?;
        Ok(model)
    }
}