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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
use crate::internal::*;
use crate::ops::source::Source;
use std::fmt;

use std::convert::TryFrom;

pub mod delay;

#[derive(Clone, PartialEq)]
pub struct PulsedTensorFact {
    pub dt: DatumType,
    pub shape: TVec<usize>,
    pub axis: usize,
    pub dim: TDim,
    pub delay: usize,
}

impl fmt::Debug for PulsedTensorFact {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        use itertools::Itertools;
        write!(
            fmt,
            "Pulse:{}x{:?}{{ax:{},d:{},dim:{:?}}}",
            self.shape.iter().join("x"),
            self.dt,
            self.axis,
            self.delay,
            self.dim
        )
    }
}

impl TensorInfo for PulsedTensorFact {
    fn to_tensor_fact(&self) -> TensorFact {
        TensorFact::dt_shape(self.dt, &self.shape)
    }
}

impl TryFrom<PulsedTensorFact> for TypedTensorInfo {
    type Error = TractError;
    fn try_from(fact: PulsedTensorFact) -> TractResult<TypedTensorInfo> {
        Ok(TypedTensorInfo { shape: (&fact.shape).into(), datum_type: fact.dt, konst: None })
    }
}

impl PulsedTensorFact {
    pub fn from_tensor_fact_pulse(
        tf: &NormalizedTensorInfo,
        pulse: usize,
    ) -> TractResult<PulsedTensorFact> {
        let dt = tf.datum_type;
        let stream = tf.shape.stream_info.ok_or("Can not pulse a tensor with no streaming dim")?;
        let shape =
            tf.shape.iter().map(|d| d.to_integer().map(|d| d as usize).unwrap_or(pulse)).collect();
        Ok(PulsedTensorFact { dt, shape, axis: stream.axis, dim: stream.len, delay: 0 })
    }

    pub fn pulse(&self) -> usize {
        self.shape[self.axis]
    }

    pub fn to_pulse_fact(&self) -> NormalizedTensorInfo {
        NormalizedTensorInfo { datum_type: self.dt, shape: ShapeInfo::from(&*self.shape) }
    }

    pub fn streaming_shape(&self) -> Vec<TDim> {
        self.shape
            .iter()
            .enumerate()
            .map(|(ix, &d)| if ix == self.axis { self.dim } else { d.to_dim() })
            .collect()
    }

    pub fn to_streaming_fact(&self) -> NormalizedTensorInfo {
        let mut info = self.to_pulse_fact();
        info.shape.stream_info = Some(StreamInfo { axis: self.axis, len: self.dim });
        info
    }
}

pub type PulsedModel = Model<PulsedTensorFact>;

impl PulsedModel {
    pub fn new(source: &NormalizedModel, pulse: usize) -> TractResult<PulsedModel> {
        Ok(PulsedModel::new_with_mapping(source, pulse)?.0)
    }

    pub fn new_with_mapping(
        source: &NormalizedModel,
        pulse: usize,
    ) -> TractResult<(PulsedModel, HashMap<OutletId, OutletId>)> {
        let mut target = PulsedModel::default();
        let mut mapping = HashMap::new();
        for old_id in source.eval_order()? {
            trace!(
                "Pulsify node {} {} ({})",
                old_id,
                source.node(old_id).name,
                source.node(old_id).op().name()
            );
            if source.node(old_id).op_as::<Source>().is_some() {
                let node = source.node(old_id);
                let pulsed_fact =
                    PulsedTensorFact::from_tensor_fact_pulse(&node.outputs[0].fact, pulse)?;
                let id = target.add_source(node.name.clone(), pulsed_fact)?;
                mapping.insert(OutletId::new(old_id, 0), OutletId::new(id, 0));
            } else {
                let node = &source.nodes()[old_id];
                let outlets = node.op().pulsify(&source, &node, &mut target, &mapping)?;
                for (ix, outlet) in outlets.into_iter().enumerate() {
                    mapping.insert(OutletId::new(node.id, ix), outlet);
                }
            }
            trace!("Target is now {}", target.nodes().len());
        }
        // maintaining order of i/o interface
        target.inputs = source.input_outlets()?.iter().map(|i| mapping[&i]).collect();
        target.outputs = source.output_outlets()?.iter().map(|o| mapping[&o]).collect();
        Ok((target, mapping))
    }

    pub fn into_typed(self) -> TractResult<TypedModel> {
        crate::model::compact::compact(&self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ndarray::*;
    use proptest::proptest;
    use proptest::test_runner::TestCaseResult;
    use proptest::*;

    #[test]
    fn test_source_must_stream() {
        let mut model = Model::default();
        let _a =
            model.add_source("a", TensorFact::dt_shape(DatumType::F32, vec![1, 2, 3])).unwrap();
        assert!(
            PulsedModel::new(&model.into_typed().unwrap().into_normalized().unwrap(), 4).is_err()
        );

        let mut model = Model::default();
        let _a = model
            .add_source(
                "a",
                TensorFact::dt_shape(DatumType::F32, vec![1.to_dim(), TDim::s(), 3.to_dim()]),
            )
            .unwrap();
        let pulse =
            PulsedModel::new(&model.into_typed().unwrap().into_normalized().unwrap(), 4).unwrap();
        assert_eq!(
            pulse.outlet_fact(OutletId::new(0, 0)).unwrap().to_tensor_fact(),
            TensorFact::dt_shape(DatumType::F32, vec!(1, 4, 3))
        );
    }

    #[test]
    fn test_immediate() {
        let mut model = Model::default();
        let _a = model
            .add_source(
                "a",
                TensorFact::dt_shape(DatumType::F32, vec![TDim::s(), 2.to_dim(), 3.to_dim()]),
            )
            .unwrap();

        let pulse = PulsedModel::new(&model.into_normalized().unwrap(), 4).unwrap();

        assert_eq!(
            pulse.input_fact(0).unwrap().to_tensor_fact(),
            TensorFact::dt_shape(DatumType::F32, vec!(4, 2, 3))
        );
        assert_eq!(
            pulse.output_fact(0).unwrap().to_tensor_fact(),
            TensorFact::dt_shape(DatumType::F32, vec!(4, 2, 3))
        );
    }

    fn proptest_regular_against_pulse(
        model: InferenceModel,
        pulse: usize,
        input_array: ArrayD<f32>,
        axis: usize,
    ) -> TestCaseResult {
        let mut ref_model = model.clone();
        ref_model
            .set_input_fact(0, TensorFact::dt_shape(f32::datum_type(), input_array.shape()))?;
        let input = Tensor::from(input_array.clone());
        let plan = SimplePlan::new(&ref_model).unwrap();
        let outputs = plan.run(tvec!(input.clone())).unwrap();

        let model = model.into_normalized().unwrap();

        let pulsed = PulsedModel::new(&model, pulse).unwrap();
        let output_fact = pulsed.output_fact(0).unwrap().clone();

        let output_stream_axis = output_fact.axis;
        let delay = output_fact.delay;
        let mut initial_output_shape = output_fact.shape.clone();
        initial_output_shape[output_stream_axis] = 0;

        let pulsed_plan = SimplePlan::new(pulsed).unwrap();
        let mut state = SimpleState::new(&pulsed_plan).unwrap();

        let mut got: ArrayD<f32> = ArrayD::zeros(&*initial_output_shape);
        let mut output_len = None;

        let mut written = 0;
        loop {
            let to_write_in_chunk = pulse.min(input_array.shape()[axis].saturating_sub(written));
            let mut chunk: ArrayD<f32> = input_array
                .slice_axis(Axis(axis), (written..written + to_write_in_chunk).into())
                .to_owned();
            written += to_write_in_chunk;
            if to_write_in_chunk < pulse {
                let mut filler_shape = input_array.shape().to_vec();
                filler_shape[axis] = pulse - to_write_in_chunk;
                chunk = stack(
                    Axis(axis),
                    &[chunk.view(), ArrayD::from_elem(filler_shape, std::f32::NAN).view()],
                )
                .unwrap();
                output_len = output_fact.dim.eval(written as _);
                state.session_state.known_stream_len = Some(written)
            }
            let mut outputs = state.run(tvec!(Tensor::from(chunk.to_owned()).into())).unwrap();
            got = stack(
                Axis(output_stream_axis),
                &[got.view(), outputs.remove(0).to_array_view::<f32>().unwrap()],
            )
            .unwrap();
            if let Some(output_len) = output_len {
                if got.shape()[output_stream_axis] >= output_len as usize + delay {
                    break;
                }
            }
        }

        let pulsed_output = got.slice_axis(
            Axis(output_stream_axis),
            (output_fact.delay..output_fact.delay + output_len.unwrap() as usize).into(),
        );

        prop_assert_eq!(pulsed_output, outputs[0].to_array_view::<f32>().unwrap());
        Ok(())
    }

    proptest! {
        #[test]
        fn proptest_crop(pulse in 1i32..3, input_len in 0i32..10, begin in 0i32..3, end in 0i32..3) {
            use crate::ops::array::Slice;
            let input_len = input_len + begin + end;
            let mut model = Model::default();
            let _ = model
                .add_source("a", TensorFact::dt_shape(f32::datum_type(), shapefact!(S)))
                .unwrap();
            model.chain_default("slice", Slice::new(vec![(begin as usize, end as usize)])).unwrap();

            let input = Array1::range(1.0f32, input_len as f32 + 1.0, 1.0);
            proptest_regular_against_pulse(model, pulse as _, input.into_dyn(), 0)?;
        }

        #[test]
        fn proptest_pad(pulse in 1i32..3, input_len in 0i32..10, begin in 0i32..3, end in 0i32..3) {
            use crate::ops::array::{ Pad, PadMode };
            let mut model = Model::default();
            let _ = model
                .add_source("a", TensorFact::dt_shape(f32::datum_type(), shapefact!(S)))
                .unwrap();
            model.chain_default("pad", Pad::new(vec![(begin as _, end as _)], PadMode::Constant(-1.0))).unwrap();

            let input = Array1::range(1.0f32, input_len as f32 + 1.0, 1.0);
            proptest_regular_against_pulse(model, pulse as _, input.into_dyn(), 0)?;
        }

    }

    #[test]
    fn test_simple_conv() {
        use crate::ops::cnn::*;

        let mut model = Model::default();
        let ker = model.add_const("kernel", tensor3(&[[[0.5f32, 1.0, -0.1]]])).unwrap();
        let _ = model
            .add_source("a", TensorFact::dt_shape(f32::datum_type(), shapefact!(1, 1, S))) // NCT
            .unwrap();

        let conv = model.chain_default("conv", Conv::default()).unwrap();
        model.add_edge(OutletId::new(ker, 0), InletId::new(conv, 1)).unwrap();

        let input = arr3(&[[[1.0f32, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0]]]);
        proptest_regular_against_pulse(model, 4, input.into_dyn(), 2).unwrap();
    }

    #[test]
    fn test_pad_after_1() {
        use crate::ops::array::{Pad, PadMode};
        let mut model = Model::default();
        let _ =
            model.add_source("a", TensorFact::dt_shape(f32::datum_type(), shapefact!(S))).unwrap();
        model.chain_default("pad", Pad::new(vec![(0, 1)], PadMode::Constant(-1.0))).unwrap();

        let input = arr1(&[]);
        proptest_regular_against_pulse(model, 1, input.into_dyn(), 0).unwrap();
    }

    #[test]
    fn test_pad_before_1() {
        use crate::ops::array::{Pad, PadMode};
        let mut model = Model::default();
        let _ =
            model.add_source("a", TensorFact::dt_shape(f32::datum_type(), shapefact!(S))).unwrap();
        model.chain_default("pad", Pad::new(vec![(1, 0)], PadMode::Constant(-1.0))).unwrap();

        let input = arr1(&[1.0]);
        proptest_regular_against_pulse(model, 1, input.into_dyn(), 0).unwrap();
    }

    #[test]
    fn test_pad_before_2() {
        use crate::ops::array::{Pad, PadMode};
        let mut model = Model::default();
        let _ =
            model.add_source("a", TensorFact::dt_shape(f32::datum_type(), shapefact!(S))).unwrap();
        model.chain_default("pad", Pad::new(vec![(1, 0)], PadMode::Constant(-1.0))).unwrap();

        let input = arr1(&[1.0, 2.0]);
        proptest_regular_against_pulse(model, 2, input.into_dyn(), 0).unwrap();
    }

}