onnx-runtime-session 0.1.0-dev.6

Session and inference API for the ORT 2.0 runtime: intent-based SessionBuilder and sequential executor (skeleton)
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use onnx_runtime_ir::DataType;

use crate::Tensor;

use super::{
    SeqTensor, SequenceError, SequenceResult, SequenceValue, addressable, checked_add, checked_mul,
    checked_product, clone_shape, normalize_axis, overflow, validate_view_bounds, zeroed_bytes,
};

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct ConcatCopyStats {
    pub destination_writes: usize,
    pub source_materializations: usize,
}

/// Fully validated geometry for `ConcatFromSequence`.
pub(crate) struct ConcatPlan {
    pub dtype: DataType,
    pub shape: Vec<usize>,
    pub bytes: usize,
    axis: usize,
    new_axis: bool,
    outer: usize,
    inner: usize,
    total_axis: usize,
}

impl ConcatPlan {
    pub(crate) fn new(sequence: &SequenceValue, axis: i64, new_axis: bool) -> SequenceResult<Self> {
        const OP: &str = "ConcatFromSequence";
        let first = sequence.items.first().ok_or(SequenceError::InvalidSplit {
            op: OP,
            reason: "cannot concatenate an empty sequence".to_string(),
        })?;
        let dtype = sequence.elem_dtype;
        let esize = dtype.byte_size();
        if esize == 0 {
            return Err(SequenceError::UnsupportedDtype { op: OP, dtype });
        }
        let rank = first.shape.len();
        let output_rank = rank
            .checked_add(usize::from(new_axis))
            .ok_or_else(|| overflow(OP, "concat output rank", &first.shape))?;
        let axis = normalize_axis(OP, axis, output_rank, new_axis)?;

        for (index, item) in sequence.items.iter().enumerate() {
            if item.dtype != dtype {
                return Err(SequenceError::DtypeMismatch {
                    op: OP,
                    index: Some(index),
                    expected: dtype,
                    actual: item.dtype,
                });
            }
            let mismatch = if new_axis {
                item.shape != first.shape
            } else {
                item.shape.len() != rank
                    || item.shape.iter().enumerate().any(|(dimension, &extent)| {
                        dimension != axis && extent != first.shape[dimension]
                    })
            };
            if mismatch {
                return Err(SequenceError::ShapeMismatch {
                    op: OP,
                    index,
                    expected: clone_shape(OP, &first.shape)?,
                    actual: clone_shape(OP, &item.shape)?,
                    requirement: if new_axis {
                        "new_axis=1 requires identical shapes"
                    } else {
                        "all dimensions except the concat axis must match"
                    },
                });
            }
            validate_view_bounds(
                OP,
                &item.shape,
                &item.layout.resolved_strides(&item.shape),
                item.byte_offset,
                item.dtype,
                item.root_len(),
            )?;
        }

        if new_axis {
            let outer = checked_product(OP, "stack outer element count", &first.shape[..axis])?;
            let inner_elements =
                checked_product(OP, "stack inner element count", &first.shape[axis..])?;
            let inner = checked_mul(
                OP,
                "stack inner byte count",
                inner_elements,
                esize,
                &first.shape,
            )?;
            let mut shape = Vec::new();
            shape
                .try_reserve_exact(output_rank)
                .map_err(|_| SequenceError::Allocation {
                    op: OP,
                    context: "stack output shape",
                    bytes: output_rank.saturating_mul(std::mem::size_of::<usize>()),
                })?;
            shape.extend_from_slice(&first.shape[..axis]);
            shape.push(sequence.items.len());
            shape.extend_from_slice(&first.shape[axis..]);
            let bytes = checked_mul(
                OP,
                "stack output byte count",
                checked_mul(
                    OP,
                    "stack output row count",
                    outer,
                    sequence.items.len(),
                    &shape,
                )?,
                inner,
                &shape,
            )?;
            Ok(Self {
                dtype,
                shape,
                bytes,
                axis,
                new_axis,
                outer,
                inner,
                total_axis: sequence.items.len(),
            })
        } else {
            let outer = checked_product(OP, "concat outer element count", &first.shape[..axis])?;
            let inner_elements =
                checked_product(OP, "concat inner element count", &first.shape[axis + 1..])?;
            let inner = checked_mul(
                OP,
                "concat inner byte count",
                inner_elements,
                esize,
                &first.shape,
            )?;
            let mut total_axis = 0usize;
            for item in &sequence.items {
                total_axis = checked_add(
                    OP,
                    "concat axis extent",
                    total_axis,
                    item.shape[axis],
                    &first.shape,
                )?;
            }
            let mut shape = clone_shape(OP, &first.shape)?;
            shape[axis] = total_axis;
            let bytes = checked_mul(
                OP,
                "concat output byte count",
                checked_mul(OP, "concat output row count", outer, total_axis, &shape)?,
                inner,
                &shape,
            )?;
            Ok(Self {
                dtype,
                shape,
                bytes,
                axis,
                new_axis,
                outer,
                inner,
                total_axis,
            })
        }
    }

    pub(crate) fn write<F>(
        &self,
        sequence: &SequenceValue,
        mut write: F,
    ) -> crate::Result<ConcatCopyStats>
    where
        F: FnMut(usize, &[u8]) -> crate::Result<()>,
    {
        const OP: &str = "ConcatFromSequence";
        let max_root = sequence
            .items
            .iter()
            .filter(|item| !item.device().is_host_accessible())
            .map(SeqTensor::root_len)
            .max()
            .unwrap_or(0);
        let mut scratch = if max_root == 0 {
            Vec::new()
        } else {
            zeroed_bytes(OP, "device source materialization", max_root, &self.shape)?
        };
        let mut stats = ConcatCopyStats::default();
        if self.new_axis {
            for outer_index in 0..self.outer {
                for (item_index, item) in sequence.items.iter().enumerate() {
                    let source_offset = checked_mul(
                        OP,
                        "stack source offset",
                        outer_index,
                        self.inner,
                        &item.shape,
                    )?;
                    let destination_row = checked_add(
                        OP,
                        "stack destination row",
                        checked_mul(
                            OP,
                            "stack destination outer offset",
                            outer_index,
                            self.total_axis,
                            &self.shape,
                        )?,
                        item_index,
                        &self.shape,
                    )?;
                    let destination_offset = checked_mul(
                        OP,
                        "stack destination byte offset",
                        destination_row,
                        self.inner,
                        &self.shape,
                    )?;
                    item.write_contiguous_range(
                        source_offset,
                        self.inner,
                        destination_offset,
                        &mut scratch,
                        &mut write,
                        &mut stats,
                    )?;
                }
            }
        } else {
            for outer_index in 0..self.outer {
                let mut axis_cursor = 0usize;
                for item in &sequence.items {
                    let copy_bytes = checked_mul(
                        OP,
                        "concat copy width",
                        item.shape[self.axis],
                        self.inner,
                        &item.shape,
                    )?;
                    let source_offset = checked_mul(
                        OP,
                        "concat source byte offset",
                        outer_index,
                        copy_bytes,
                        &item.shape,
                    )?;
                    let destination_row = checked_add(
                        OP,
                        "concat destination row",
                        checked_mul(
                            OP,
                            "concat destination outer offset",
                            outer_index,
                            self.total_axis,
                            &self.shape,
                        )?,
                        axis_cursor,
                        &self.shape,
                    )?;
                    let destination_offset = checked_mul(
                        OP,
                        "concat destination byte offset",
                        destination_row,
                        self.inner,
                        &self.shape,
                    )?;
                    item.write_contiguous_range(
                        source_offset,
                        copy_bytes,
                        destination_offset,
                        &mut scratch,
                        &mut write,
                        &mut stats,
                    )?;
                    axis_cursor = checked_add(
                        OP,
                        "concat axis cursor",
                        axis_cursor,
                        item.shape[self.axis],
                        &self.shape,
                    )?;
                }
            }
        }
        Ok(stats)
    }
}

/// Concatenate a sequence along an existing axis or stack it on a new axis.
pub fn concat(sequence: &SequenceValue, axis: i64, new_axis: bool) -> SequenceResult<SeqTensor> {
    const OP: &str = "ConcatFromSequence";
    let plan = ConcatPlan::new(sequence, axis, new_axis)?;
    let mut tensor = Tensor::allocate_cpu(plan.dtype, plan.shape.clone())
        .map_err(|source| SequenceError::TensorCreation { op: OP, source })?;
    plan.write(sequence, |offset, bytes| {
        tensor.copy_from_host_at(offset, bytes)
    })
    .map_err(|source| SequenceError::TensorCreation { op: OP, source })?;
    Ok(SeqTensor::new(tensor))
}

/// Stack already-validated contiguous element bytes along a new axis.
pub(crate) fn stack_new_axis(
    elements: &[&[u8]],
    elem_shape: &[usize],
    axis: usize,
    esize: usize,
) -> SequenceResult<(Vec<usize>, Vec<u8>)> {
    const OP: &str = "ConcatFromSequence";
    if axis > elem_shape.len() || esize == 0 {
        return Err(SequenceError::InvalidSplit {
            op: OP,
            reason: "invalid new axis or element byte size".to_string(),
        });
    }
    let outer = checked_product(OP, "stack outer element count", &elem_shape[..axis])?;
    let inner_elements = checked_product(OP, "stack inner element count", &elem_shape[axis..])?;
    let inner = checked_mul(
        OP,
        "stack inner byte count",
        inner_elements,
        esize,
        elem_shape,
    )?;
    let source_bytes = checked_mul(OP, "stack source byte count", outer, inner, elem_shape)?;
    addressable(OP, "stack source byte count", source_bytes, elem_shape)?;
    for element in elements {
        if element.len() != source_bytes {
            return Err(SequenceError::ByteLengthMismatch {
                op: OP,
                dtype: DataType::Uint8,
                shape: clone_shape(OP, elem_shape)?,
                expected: source_bytes,
                actual: element.len(),
            });
        }
    }
    let output_rows = checked_mul(
        OP,
        "stacked tensor output row count",
        elements.len(),
        outer,
        elem_shape,
    )?;
    let output_bytes = checked_mul(
        OP,
        "stack output byte count",
        output_rows,
        inner,
        elem_shape,
    )?;
    let mut bytes = zeroed_bytes(OP, "stack output", output_bytes, elem_shape)?;
    if inner != 0 {
        for (element_index, element) in elements.iter().enumerate() {
            for outer_index in 0..outer {
                let source_offset = checked_mul(
                    OP,
                    "stack source byte offset",
                    outer_index,
                    inner,
                    elem_shape,
                )?;
                let source_end = checked_add(
                    OP,
                    "stack source byte range",
                    source_offset,
                    inner,
                    elem_shape,
                )?;
                let destination_row = checked_add(
                    OP,
                    "stack destination row",
                    checked_mul(
                        OP,
                        "stack destination outer offset",
                        outer_index,
                        elements.len(),
                        elem_shape,
                    )?,
                    element_index,
                    elem_shape,
                )?;
                let destination_offset = checked_mul(
                    OP,
                    "stack destination byte offset",
                    destination_row,
                    inner,
                    elem_shape,
                )?;
                let destination_end = checked_add(
                    OP,
                    "stack destination byte range",
                    destination_offset,
                    inner,
                    elem_shape,
                )?;
                bytes[destination_offset..destination_end]
                    .copy_from_slice(&element[source_offset..source_end]);
            }
        }
    }
    let shape_capacity = elem_shape
        .len()
        .checked_add(1)
        .ok_or_else(|| overflow(OP, "stack output rank", elem_shape))?;
    let mut output_shape = Vec::new();
    output_shape
        .try_reserve_exact(shape_capacity)
        .map_err(|_| SequenceError::Allocation {
            op: OP,
            context: "stack output shape",
            bytes: shape_capacity.saturating_mul(std::mem::size_of::<usize>()),
        })?;
    output_shape.extend_from_slice(&elem_shape[..axis]);
    output_shape.push(elements.len());
    output_shape.extend_from_slice(&elem_shape[axis..]);
    Ok((output_shape, bytes))
}