1mod fixedpoint;
2pub mod math;
3
4use math::{
5 convert_scale_to_mult_shift, exp_on_negative_values, get_reciprocal, rescale,
6 rounding_divide_by_pot, saturating_rounding_doubling_high_mul,
7 saturating_rounding_multiply_by_pot,
8};
9use num_traits::Float;
10use std::fmt::Debug;
11use tract_num_traits::Zero;
12
13use crate::internal::*;
14use ndarray::prelude::*;
15use tract_linalg::routines::Func;
16
17#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Default)]
18pub enum SoftmaxKind {
19 #[default]
20 Softmax,
21 LogSoftmax,
22}
23
24#[derive(Debug, Clone, new, Hash, Default, PartialEq, Eq)]
25pub struct Softmax {
26 pub axes: TVec<usize>,
27 pub quant_output_dt: Option<DatumType>,
28 pub kind: SoftmaxKind,
29}
30
31impl Op for Softmax {
32 fn name(&self) -> StaticName {
33 match self.kind {
34 SoftmaxKind::Softmax => "Softmax".into(),
35 SoftmaxKind::LogSoftmax => "LogSoftmax".into(),
36 }
37 }
38
39 fn info(&self) -> TractResult<Vec<String>> {
40 Ok(vec![format!("Axis: {:?}", self.axes)])
41 }
42
43 op_as_typed_op!();
44}
45
46impl TypedOp for Softmax {
47 fn output_facts(&self, inputs: &[&TypedFact]) -> TractResult<TVec<TypedFact>> {
48 let dt = inputs[0].datum_type;
49 if dt.is_float() {
50 ensure!(
51 self.quant_output_dt.is_none(),
52 "Float softmax should not have quant_output_dt, have {:?}",
53 self.quant_output_dt
54 );
55 } else if dt.is_quantized() {
56 ensure!(
57 self.quant_output_dt.map(|q| q.is_quantized()).unwrap_or(false),
58 "Quantized softmax should have a quantized output type (got {:?})",
59 self.quant_output_dt
60 );
61 } else {
62 bail!(
63 "Unsupported datum type in softmax: input type {:?}, output type {:?}",
64 dt,
65 self.quant_output_dt
66 );
67 }
68
69 let fact = self.quant_output_dt.unwrap_or(dt).fact(inputs[0].shape.clone());
70 Ok(tvec!(fact))
71 }
72
73 fn input_roi(
74 &self,
75 model: &TypedModel,
76 node: &TypedNode,
77 ) -> TractResult<Option<TVec<Option<TDim>>>> {
78 crate::optim::propagate_roi::bubble_roi(model, node)
79 }
80
81 fn axes_mapping(
82 &self,
83 inputs: &[&TypedFact],
84 outputs: &[&TypedFact],
85 ) -> TractResult<AxesMapping> {
86 AxesMapping::natural(inputs, outputs)
87 }
88
89 fn change_axes(
90 &self,
91 model: &TypedModel,
92 node: &TypedNode,
93 _io: InOut,
94 change: &AxisOp,
95 ) -> TractResult<Option<AxisChangeConsequence>> {
96 let axes: Option<TVec<usize>> =
97 self.axes.iter().map(|it| change.transform_axis(*it)).collect();
98 if let Some(axes) = axes {
99 Ok(Some(AxisChangeConsequence::new(
100 model,
101 node,
102 Some(Box::new(Softmax { axes, ..self.clone() })),
103 change,
104 )))
105 } else {
106 Ok(None)
107 }
108 }
109
110 as_op!();
111}
112
113impl EvalOp for Softmax {
114 op_out_of_plan!();
115
116 fn eval(&self, _ctx: &EvalContext, inputs: TVec<TValue>) -> TractResult<TVec<TValue>> {
117 let input = args_1!(inputs);
118 let dt = input.datum_type();
119
120 let output = match dt {
121 DatumType::F64 => self.eval_t::<f64>(input)?,
122 DatumType::F32 => self.eval_t::<f32>(input)?,
123 DatumType::F16 => self.eval_t::<f16>(input)?,
124 DatumType::QI8(_) | DatumType::QU8(_) => self.eval_quant(input)?,
125 dt => bail!("Unsupported type {dt:?}"),
126 };
127 Ok(output)
128 }
129}
130
131impl Softmax {
132 fn eval_t<T>(&self, input: TValue) -> TractResult<TVec<TValue>>
133 where
134 T: Float + Datum + std::iter::Sum,
135 {
136 let mut output = input.into_tensor();
137
138 let rank = output.rank();
144 let mut sm_axes: TVec<usize> = self.axes.clone();
145 sm_axes.sort_unstable();
146 let trailing = !sm_axes.is_empty()
147 && sm_axes.len() <= rank
148 && sm_axes.iter().enumerate().all(|(i, &a)| a == rank - sm_axes.len() + i);
149 if trailing
150 && matches!(T::datum_type(), DatumType::F32 | DatumType::F16)
151 && output.strides() == &*Tensor::natural_strides(output.shape())
152 {
153 let row_len: usize = sm_axes.iter().map(|&a| output.shape()[a]).product();
154 if row_len > 0 {
155 let kind = self.kind;
156 let mut output_plain = output.try_as_plain_mut()?;
157 if T::datum_type() == f32::datum_type() {
160 let data = output_plain.as_slice_mut::<f32>()?;
161 let total = data.len();
162 tract_linalg::multithread::par_chunks_mut(data, row_len, total, |_, chunk| {
163 for row in chunk.chunks_mut(row_len) {
164 self.softmax_inner_slice_f32(row, kind)?;
165 }
166 Ok(())
167 })?;
168 } else {
169 let data = output_plain.as_slice_mut::<f16>()?;
170 let total = data.len();
171 tract_linalg::multithread::par_chunks_mut(data, row_len, total, |_, chunk| {
172 for row in chunk.chunks_mut(row_len) {
173 self.softmax_inner_slice_f16(row, kind)?;
174 }
175 Ok(())
176 })?;
177 }
178 return Ok(tvec!(output.into_tvalue()));
179 }
180 }
181
182 let mut iterating_shape: TVec<usize> = output.shape().into();
185
186 for i in 0..iterating_shape.len() {
187 if self.axes.contains(&i) {
188 iterating_shape[i] = 1
189 }
190 }
191
192 let mut output_plain = output.try_as_plain_mut()?;
193 let mut view = output_plain.to_array_view_mut::<T>()?;
194
195 for it_coords in tract_ndarray::indices(&*iterating_shape) {
196 let mut view = view.view_mut();
197 for ix in 0..iterating_shape.len() {
198 if !self.axes.contains(&ix) {
199 view.collapse_axis(Axis(ix), it_coords[ix]);
200 }
201 }
202 if let Some(slice) =
203 view.as_slice_mut().filter(|_| T::datum_type() == f32::datum_type())
204 {
205 let slice: &mut [f32] = unsafe { std::mem::transmute(slice) };
206 self.softmax_inner_slice_f32(slice, self.kind)?;
207 } else if let Some(slice) =
208 view.as_slice_mut().filter(|_| T::datum_type() == f16::datum_type())
209 {
210 let slice: &mut [f16] = unsafe { std::mem::transmute(slice) };
211 self.softmax_inner_slice_f16(slice, self.kind)?;
212 } else {
213 softmax_inner(view, self.kind);
214 }
215 }
216
217 Ok(tvec!(output.into_tvalue()))
218 }
219
220 fn eval_quant(&self, input: TValue) -> TractResult<TVec<TValue>> {
221 if self.kind == SoftmaxKind::LogSoftmax {
222 bail!("Quantized LogSoftmax is not supported")
223 }
224 let mut iterating_shape: TVec<usize> = input.shape().into();
225 let output_dt =
226 self.quant_output_dt.context("Quandized softmax eval with no output type")?;
227
228 for i in 0..iterating_shape.len() {
229 if self.axes.contains(&i) {
230 iterating_shape[i] = 1
231 }
232 }
233
234 let src_is_signed = input.datum_type().is_signed();
236 let out_is_signed = output_dt.is_signed();
237 let in_qp = input.datum_type().qparams().unwrap(); let out_qp = output_dt.qparams().unwrap(); let mut output = unsafe { input.into_tensor().into_array_unchecked::<u8>() };
240
241 for it_coords in tract_ndarray::indices(&*iterating_shape) {
242 let mut view = output.view_mut();
243 for ix in 0..iterating_shape.len() {
244 if !self.axes.contains(&ix) {
245 view.collapse_axis(Axis(ix), it_coords[ix]);
246 }
247 }
248 softmax_quant_inner(view, src_is_signed, in_qp, out_is_signed, out_qp);
249 }
250
251 let mut output_tensor = output.into_tensor();
252 unsafe { output_tensor.set_datum_type(output_dt) };
253 Ok(tvec!(output_tensor.into_tvalue()))
254 }
255
256 fn softmax_inner_slice_f16(&self, slice: &mut [f16], kind: SoftmaxKind) -> TractResult<()> {
257 let max = Func::ReduceMax.reduce_f16()?.run(slice)?;
258 match kind {
259 SoftmaxKind::Softmax => {
260 let mut sum = 0f32;
266 slice.iter_mut().for_each(|x| {
267 *x = (*x - max).exp();
268 sum += x.to_f32();
269 });
270 let rsum = f16::from_f32(sum.recip());
271 Func::MulByScalar.ew_f16_param()?.run_with_params(slice, rsum)?;
272 }
273 SoftmaxKind::LogSoftmax => {
274 let mut exp_sum = 0f32;
275 slice.iter_mut().for_each(|x| {
276 *x -= max;
277 exp_sum += x.exp().to_f32();
278 });
279 let log_sum = f16::from_f32(exp_sum.ln());
280 slice.iter_mut().for_each(|x| *x -= log_sum);
281 }
282 }
283 Ok(())
284 }
285
286 fn softmax_inner_slice_f32(&self, slice: &mut [f32], kind: SoftmaxKind) -> TractResult<()> {
287 let max = Func::ReduceMax.reduce_f32()?.run(slice)?;
288 match kind {
289 SoftmaxKind::Softmax => {
290 let sum = Func::Softmax2.map_reduce_f32()?.run_with_params(slice, max)?;
291 let rsum = sum.recip();
292 Func::MulByScalar.ew_f32_param()?.run_with_params(slice, rsum)?;
293 }
294 SoftmaxKind::LogSoftmax => {
295 let mut exp_sum = f32::zero();
296 slice.iter_mut().for_each(|x| {
297 *x -= max;
298 exp_sum += x.exp();
299 });
300 let log_sum = exp_sum.ln();
301 slice.iter_mut().for_each(|x| *x -= log_sum);
302 }
303 }
304 Ok(())
305 }
306}
307
308fn softmax_inner<T: Float + Datum + std::iter::Sum, D: Dimension>(
309 mut view: ArrayViewMut<T, D>,
310 kind: SoftmaxKind,
311) {
312 let max =
313 *view.iter().max_by(|i, j| i.partial_cmp(j).unwrap_or(std::cmp::Ordering::Less)).unwrap();
314 view.mapv_inplace(|x| x - max);
315 let exp_sum = view.iter().map(|&x| x.exp()).sum();
316 match kind {
317 SoftmaxKind::Softmax => {
318 view.mapv_inplace(|x| x.exp() / exp_sum);
319 }
320 SoftmaxKind::LogSoftmax => {
321 let log_sum = exp_sum.ln();
322 view.mapv_inplace(|x| x - log_sum);
323 }
324 }
325}
326
327fn softmax_quant_inner<D: Dimension>(
328 mut view: ArrayViewMut<u8, D>,
329 src_is_signed: bool,
330 in_qp: QParams,
331 out_is_signed: bool,
332 out_qp: QParams,
333) {
334 let (_, in_scale) = in_qp.zp_scale();
335 let (scale_in_multiplier, scale_in_shift) = convert_scale_to_mult_shift(in_scale).unwrap();
336 let (_, out_scale) = out_qp.zp_scale();
337 let (scale_out_multiplier, scale_out_shift) = convert_scale_to_mult_shift(out_scale).unwrap();
338 let shift = 26 - scale_in_shift;
339
340 let mut buffer = vec![0_i32; view.len()];
342
343 let safe_u8 = if src_is_signed { |x: &u8| x.wrapping_add(128) } else { |x: &u8| *x };
345
346 let max = view.iter().map(safe_u8).max().unwrap();
347 view.iter().zip(buffer.iter_mut()).for_each(|(x, exp)| {
348 let input_diff = safe_u8(x) as i32 - max as i32;
349
350 let scaled_input_diff = if scale_in_multiplier != 0 {
352 saturating_rounding_multiply_by_pot(
353 saturating_rounding_doubling_high_mul(input_diff, scale_in_multiplier),
354 shift as i32,
355 )
356 } else {
357 saturating_rounding_multiply_by_pot(input_diff, shift as i32)
358 };
359
360 *exp = exp_on_negative_values(scaled_input_diff);
362 });
363
364 let sum_of_exp = buffer.iter().map(|it| rescale(*it, 0, 12)).sum();
367
368 let (inv_sum_of_exp, num_bits_over_unit) = get_reciprocal(sum_of_exp, 12);
371
372 let exponent = num_bits_over_unit as isize + 31 - 8;
374
375 view.iter_mut().zip(buffer.iter()).for_each(|(it, exp)| {
376 let unsat_output = rounding_divide_by_pot(
378 saturating_rounding_doubling_high_mul(inv_sum_of_exp, *exp),
379 exponent as i32,
380 );
381
382 let unsat_scaled_output = {
384 if scale_out_multiplier != 0 {
385 let (inv_multiplier, num_bits) = get_reciprocal(scale_out_multiplier, 1);
386 rounding_divide_by_pot(
387 saturating_rounding_doubling_high_mul(unsat_output, inv_multiplier),
388 (8 - scale_out_shift - 1 - num_bits as isize) as i32,
389 )
390 } else {
391 rounding_divide_by_pot(unsat_output, (8 - scale_out_shift) as i32)
392 }
393 };
394
395 #[allow(unknown_lints, unnecessary_transmutes)]
398 if out_is_signed {
399 *it = unsafe {
400 std::mem::transmute::<i8, u8>(i32::max(
401 i32::min(unsat_scaled_output, i8::MAX as i32),
402 i8::MIN as i32,
403 ) as i8)
404 };
405 } else {
406 *it = i32::max(i32::min(unsat_scaled_output, u8::MAX as i32), u8::MIN as i32) as u8;
407 }
408 });
409}
410
411#[cfg(test)]
412mod test {
413 use super::*;
414 use crate::ops::nn::DataFormat::NCHW;
415 use anyhow::Result;
416 use num_traits::PrimInt;
417 use proptest::collection::vec;
418 use proptest::prelude::*;
419 use tract_data::internal::QParams::ZpScale;
420
421 fn assert_is_close(found: f32, expected: f32, in_dt: DatumType, out_dt: DatumType) {
422 let (_, in_epsilon) = in_dt.zp_scale();
423 let (_, out_epsilon) = out_dt.zp_scale();
424 let epsilon = in_epsilon + out_epsilon;
425 let error = (found - expected).abs();
426 assert!(
427 error <= epsilon,
428 "epsilon eq failed: |{found:?}-{expected:?}|={error} should be <= {epsilon}"
429 );
430 }
431
432 fn qtensor<T: PrimInt + Datum + Arbitrary>(shape: Vec<usize>) -> BoxedStrategy<Tensor> {
434 let len = shape.iter().product::<usize>();
435 let dt = q_datum::<T>((0.0001f32..0.1).boxed());
436 (vec(any::<T>(), len..=len), dt)
437 .prop_map(move |(vec, dt)| (ArrayD::from_shape_vec(shape.clone(), vec).unwrap(), dt))
438 .prop_map(move |(array, dt)| {
439 let mut tensor = array.into_tensor();
440 unsafe { tensor.set_datum_type(dt) };
441 tensor
442 })
443 .boxed()
444 }
445
446 fn q_datum<T: PrimInt + Datum>(range: BoxedStrategy<f32>) -> BoxedStrategy<DatumType> {
448 let max_integer_bits = std::mem::size_of::<T>() * 8 - T::datum_type().is_signed() as usize;
449 prop_oneof![
450 (1usize..max_integer_bits).prop_map(|fixed_point| { 2f32.powi(-(fixed_point as i32)) }),
451 range
452 ]
453 .prop_map(|scale| {
454 if T::datum_type().is_signed() {
455 DatumType::QI8(ZpScale { zero_point: 0, scale })
456 } else {
457 DatumType::QU8(ZpScale { zero_point: 0, scale })
458 }
459 })
460 .boxed()
461 }
462
463 #[derive(Debug)]
464 struct SoftmaxProblem {
465 data: Tensor,
466 axes: TVec<usize>,
467 output_dt: DatumType,
468 }
469
470 impl SoftmaxProblem {
471 fn check(&self) -> Result<()> {
472 let inputs = tvec!(self.data.clone().into_tvalue());
473 let quant_output_dt = Some(self.output_dt).filter(|dt| !dt.is_float());
474 let softmax =
475 Softmax { axes: self.axes.clone(), quant_output_dt, ..Softmax::default() };
476
477 let result = softmax.eval(&EvalContext::out_of_plan(), inputs)?;
479 let result = args_1!(result);
480 let result_float = result.cast_to::<f32>()?;
481
482 let input_float = self.data.cast_to::<f32>()?;
484 let inputs_float = tvec!(input_float.into_owned().into_tvalue());
485 let softmax_float = Softmax { axes: self.axes.clone(), ..Softmax::default() };
486 let reference_float = softmax_float.eval(&EvalContext::out_of_plan(), inputs_float)?;
487 let reference_array = args_1!(reference_float);
488 let reference = reference_array.to_plain_array_view::<f32>()?;
489
490 result_float
491 .to_plain_array_view::<f32>()?
492 .iter()
493 .zip(reference.iter())
494 .for_each(|(a, b)| assert_is_close(*a, *b, self.data.datum_type(), self.output_dt));
495 Ok(())
496 }
497 }
498
499 impl Arbitrary for SoftmaxProblem {
500 type Parameters = ();
501 type Strategy = BoxedStrategy<SoftmaxProblem>;
502 fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
503 (1usize..2, 1usize..2, 1usize..5, 1usize..5, 0usize..4)
504 .prop_flat_map(|(n, c, h, w, axis)| {
505 let shape_in: Vec<usize> =
506 NCHW.from_n_c_hw(n, c, [h, w]).unwrap().shape.to_vec();
507 (
508 prop_oneof![qtensor::<i8>(shape_in.clone()), qtensor::<u8>(shape_in)],
509 Just(tvec![axis]),
510 prop_oneof![
511 q_datum::<u8>((0.008f32..0.1).boxed()),
512 q_datum::<i8>((0.008f32..0.1).boxed())
513 ],
514 )
515 })
516 .prop_map(|(data, axes, output_dt)| SoftmaxProblem { data, axes, output_dt })
517 .boxed()
518 }
519 }
520
521 #[derive(Debug)]
522 pub struct InnerSoftmaxProblem {
523 in_qp: QParams,
524 out_qp: QParams,
525 data: Vec<i8>,
526 }
527
528 impl InnerSoftmaxProblem {
529 fn check(&self) -> Result<()> {
530 let quantized = self.quantized();
531 let reference = self.reference();
532 assert!(quantized.iter().zip(reference.iter()).all(|(quantized, expected)| {
533 let abs_diff = if *quantized > *expected {
534 quantized - *expected
535 } else {
536 expected - *quantized
537 };
538 abs_diff <= 1
539 }));
540 Ok(())
541 }
542
543 fn reference(&self) -> Vec<u8> {
544 let (in_zero_point, in_scale) = self.in_qp.zp_scale();
545 let (out_zero_point, out_scale) = self.out_qp.zp_scale();
546 let in_float =
547 self.data.iter().map(|it| (*it as f32 - in_zero_point as f32) * in_scale).collect();
548 let mut in_float_array = Array1::from_vec(in_float);
549 softmax_inner(in_float_array.view_mut(), SoftmaxKind::default());
550 in_float_array
551 .iter()
552 .map(|it| {
553 ((*it / out_scale).round() as i32 + out_zero_point)
554 .max(u8::MIN as i32)
555 .min(u8::MAX as i32) as u8
556 })
557 .collect()
558 }
559
560 fn quantized(&self) -> Vec<u8> {
561 let in_data: Vec<u8> = unsafe { std::mem::transmute(self.data.clone()) };
562 let mut in_array = Array1::from_vec(in_data);
563 softmax_quant_inner(in_array.view_mut(), true, self.in_qp, false, self.out_qp);
564 in_array.to_vec()
565 }
566 }
567
568 impl Arbitrary for InnerSoftmaxProblem {
569 type Parameters = ();
570 type Strategy = BoxedStrategy<InnerSoftmaxProblem>;
571 fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
572 (
573 prop_oneof![
574 q_datum::<i8>((0.0001f32..0.01).boxed()),
575 q_datum::<u8>((0.0001f32..0.01).boxed())
576 ],
577 prop_oneof![
578 q_datum::<u8>((0.008f32..0.1).boxed()),
579 q_datum::<i8>((0.008f32..0.1).boxed())
580 ],
581 vec(any::<i8>(), 1..10),
582 )
583 .prop_map(|(in_qp, out_qp, data)| InnerSoftmaxProblem {
584 in_qp: in_qp.qparams().unwrap(),
585 out_qp: out_qp.qparams().unwrap(),
586 data,
587 })
588 .boxed()
589 }
590 }
591
592 proptest::proptest! {
593 #![proptest_config(ProptestConfig::with_cases(1000))]
594 #[test]
595 fn test_softmax_inner_prop(pb in any::<InnerSoftmaxProblem>()) {
596 pb.check().unwrap()
597 }
598 }
599
600 proptest::proptest! {
601 #![proptest_config(ProptestConfig::with_cases(1000))]
602 #[test]
603 fn test_softmax_prop(pb in any::<SoftmaxProblem>()) {
604 pb.check().unwrap()
605 }
606 }
607
608 #[test]
609 fn test_softmax_trivial_0() -> Result<()> {
611 let input_dt = DatumType::QU8(ZpScale { zero_point: 0, scale: 0.03125 }); let output_dt = DatumType::QU8(ZpScale { zero_point: 0, scale: 0.00390625 }); let mut data = Tensor::from_shape(&[1, 1, 2, 2], &[0_u8, 0, 0, 4])?;
614 unsafe { data.set_datum_type(input_dt) };
615
616 let prob = SoftmaxProblem { data, axes: tvec![3], output_dt };
617 prob.check()?;
618 Ok(())
619 }
620
621 #[test]
622 fn test_softmax_trivial_1() -> Result<()> {
624 let input_dt = DatumType::QI8(ZpScale { zero_point: 0, scale: 0.0625 }); let output_dt = DatumType::QU8(ZpScale { zero_point: 0, scale: 0.00390625 }); let mut data = Tensor::from_shape(&[1, 1, 2, 2], &[0_i8, 0, 0, 4])?;
627 unsafe { data.set_datum_type(input_dt) };
628
629 let prob = SoftmaxProblem { data, axes: tvec![3], output_dt };
630 prob.check()?;
631 Ok(())
632 }
633
634 #[test]
635 fn test_softmax_trivial_2() -> Result<()> {
637 let input_dt = DatumType::QI8(ZpScale { zero_point: 0, scale: 0.0625 }); let output_dt = DatumType::QI8(ZpScale { zero_point: 0, scale: 0.0078125 }); let mut data = Tensor::from_shape(&[1, 1, 2, 2], &[0_i8, 0, 0, -4])?;
640 unsafe { data.set_datum_type(input_dt) };
641
642 let prob = SoftmaxProblem { data, axes: tvec![3], output_dt };
643 prob.check()?;
644 Ok(())
645 }
646
647 #[test]
648 fn test_softmax_trivial_3() -> Result<()> {
650 let input_dt = DatumType::QU8(ZpScale { zero_point: 0, scale: 0.03125 }); let output_dt = DatumType::QI8(ZpScale { zero_point: 0, scale: 0.0078125 }); let mut data = Tensor::from_shape(&[1, 1, 2, 2], &[0_u8, 0, 0, 4])?;
653 unsafe { data.set_datum_type(input_dt) };
654
655 let prob = SoftmaxProblem { data, axes: tvec![2], output_dt };
656 prob.check()?;
657 Ok(())
658 }
659
660 #[test]
661 fn test_softmax_1() -> Result<()> {
662 let input_dt = DatumType::QI8(ZpScale { zero_point: 0, scale: 0.5 }); let output_dt = DatumType::QU8(ZpScale { zero_point: 0, scale: 0.5 }); let mut data = Tensor::from_shape(&[1, 1, 1, 2], &[115_i8, 115])?;
665 unsafe { data.set_datum_type(input_dt) };
666
667 let prob = SoftmaxProblem { data, axes: tvec![3], output_dt };
668 prob.check()?;
669 Ok(())
670 }
671
672 #[test]
673 fn test_softmax_2() -> Result<()> {
674 let input_dt = DatumType::QI8(ZpScale { zero_point: 0, scale: 0.0001 });
675 let output_dt = DatumType::QU8(ZpScale { zero_point: 0, scale: 0.008 });
676 let mut data = Tensor::from_shape(&[1, 1, 1, 2], &[115_i8, 115])?;
677 unsafe { data.set_datum_type(input_dt) };
678
679 let prob = SoftmaxProblem { data, axes: tvec![3], output_dt };
680 prob.check()?;
681 Ok(())
682 }
683
684 #[test]
685 fn test_softmax_3() -> Result<()> {
686 let input_dt = DatumType::QU8(ZpScale { zero_point: 0, scale: 0.6220956 });
687 let output_dt = DatumType::QU8(ZpScale { zero_point: 0, scale: 0.5187921 });
688 let mut data = Tensor::from_shape(&[1, 1, 1, 2], &[13_u8, 218])?;
689 unsafe { data.set_datum_type(input_dt) };
690
691 let prob = SoftmaxProblem { data, axes: tvec![3], output_dt };
692 prob.check()?;
693 Ok(())
694 }
695
696 #[test]
697 fn test_inner_softmax_1() -> Result<()> {
698 let in_qp = ZpScale { zero_point: 0, scale: 0.03125 };
699 let out_qp = ZpScale { zero_point: 0, scale: 0.5 };
700 let data = vec![0_i8, 1];
701
702 let prob = InnerSoftmaxProblem { in_qp, out_qp, data };
703 prob.check()?;
704 Ok(())
705 }
706
707 #[test]
708 fn test_inner_softmax_2() -> Result<()> {
709 let in_qp = ZpScale { zero_point: 0, scale: 0.5 };
710 let out_qp = ZpScale { zero_point: 0, scale: 0.03125 };
711 let data = vec![100i8, -28];
712
713 let prob = InnerSoftmaxProblem { in_qp, out_qp, data };
714 prob.check()?;
715 Ok(())
716 }
717
718 #[test]
719 fn test_inner_softmax_not_pow_2_1() -> Result<()> {
720 let in_qp = ZpScale { zero_point: 0, scale: 0.7298456 };
721 let out_qp = ZpScale { zero_point: 0, scale: 0.03125 };
722 let data = vec![100i8, -28];
723
724 let prob = InnerSoftmaxProblem { in_qp, out_qp, data };
725 prob.check()?;
726 Ok(())
727 }
728
729 #[test]
730 #[ignore]
731 fn test_inner_softmax_not_pow_2_2() -> Result<()> {
735 let in_qp = ZpScale { zero_point: 0, scale: 0.2123116 };
736 let out_qp = ZpScale { zero_point: 0, scale: 0.008 };
737 let data = vec![118i8, 108];
738
739 let prob = InnerSoftmaxProblem { in_qp, out_qp, data };
740 prob.check()?;
741 Ok(())
742 }
743
744 #[test]
745 #[ignore]
746 fn test_inner_softmax_not_pow_2_3() -> Result<()> {
750 let in_qp = ZpScale { zero_point: 0, scale: 0.33034274 };
751 let out_qp = ZpScale { zero_point: 0, scale: 0.015625 };
752 let data = vec![45i8, 43];
753
754 let prob = InnerSoftmaxProblem { in_qp, out_qp, data };
755 prob.check()?;
756 Ok(())
757 }
758}
759
760#[cfg(test)]
761mod f16_accumulator {
762 use super::*;
763
764 #[test]
768 fn long_rows_keep_their_normalisation() -> TractResult<()> {
769 for len in [1024usize, 4096, 8192] {
770 let logits: Vec<f32> = (0..len).map(|i| ((i as f32) * 0.7).sin() * 0.5).collect();
771
772 let mut half: Vec<f16> = logits.iter().map(|v| f16::from_f32(*v)).collect();
773 Softmax::new(tvec![0], None, SoftmaxKind::Softmax)
774 .softmax_inner_slice_f16(&mut half, SoftmaxKind::Softmax)?;
775
776 let max = logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
777 let exps: Vec<f32> = logits.iter().map(|v| (v - max).exp()).collect();
778 let total: f32 = exps.iter().sum();
779
780 let got: f32 = half.iter().map(|v| v.to_f32()).sum();
781 assert!((got - 1.0).abs() < 0.02, "len {len}: row sums to {got}, expected 1.0");
782 for (i, (h, e)) in half.iter().zip(&exps).enumerate() {
783 let want = e / total;
784 let err = (h.to_f32() - want).abs() / want.max(f32::MIN_POSITIVE);
785 assert!(err < 0.05, "len {len} lane {i}: got {h}, want {want}, rel {err}");
786 }
787 }
788 Ok(())
789 }
790}