System.Numerics.Vectors可以保证大小和位顺序吗?

时间:2019-06-18 04:33:11

标签: c# floating-point endianness simd unsafe

我已经实现了Log的基于矢量的c#近似。它包含不安全的代码。它在许多环境中都运行良好,但是最近的部署已经失败了。该实现通过System.Numerics.Vectors库使用SIMD。

很遗憾,我无法在软件无法正常运行的系统上进行测试。但是,我想知道我对库所做的假设是无效的:

  • Vector .Count是否总是返回2的幂?
  • Vector .Count == Vector.Count * 2吗?
  • 我可以使用Unsafe.AsPointer获取向量的指针,然后执行标准操作,就好像它是内存中的N个压缩数字吗?
  • 是否有运行dotNet 4的处理器具有不同的字节序或不以IEEE754格式存储浮点数?

代码如下:

const float invLn2 = 1.44269504089f; // 1 / ln(2)
        const float pow2_126 = 8.5070592e+37f; //2^126

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static Vector<float> QuickLog2(Vector<float> vecOrig)
        {
            //32 bit Float specification:
            //Leftmost bit is sign bit.
            //Next 8 bits are exponent
            //Next 23 bits are mantissa
            unsafe
            {
                var ints = Vector.AsVectorUInt32(vecOrig);

                var exponents = Vector.BitwiseAnd(ints, new Vector<uint>(0x7F800000));
                BitshiftVector23(Unsafe.AsPointer(ref exponents));

                var unsignedExponents = exponents - new Vector<uint>(127);
                var signedExponents = Vector.AsVectorInt32(unsignedExponents);
                var localMantissBitmask = Vector.AsVectorSingle(new Vector<UInt32>(0x807FFFFF));
                var maskedMantissas = Vector.BitwiseAnd(vecOrig, localMantissBitmask);
                var mantissas = maskedMantissas * new Vector<float>(pow2_126);

                var mantissasLogged = LogPolynomialFunction2(mantissas) * new Vector<float>(invLn2);

                Vector<float> floatExponents;
#if false
                floatExponents = Vector.ConvertToSingle(signedExponents);               
#else
                ConvertIntToFloatInPace(Unsafe.AsPointer(ref signedExponents));
                floatExponents = Vector.AsVectorSingle(signedExponents);
#endif

                return mantissasLogged + floatExponents;
            }
        }

        const float log10_2 = 0.30102999566398119521373889472449f;
        /// <summary>
        /// A vectorized implementation of Log10(N). Uses bitshift, bitmasks, and unsafe code.
        /// Does not have the same safety as Math.Log10: Behaviour for infities, zero, negative numbers are undefined.
        /// </summary>
        /// <param name="vec">The vector to take the log of</param>
        /// <returns>The log, to the base 10, of the vector</returns>
        /// <remarks>
        /// Accurate to about 10^-7, which is the limit of a 32 bit float anyway.
        /// In my (BS) tests, takes about twice as long to run on as Math.Log10(...), but operates on 8 numbers,
        /// so 4x faster.
        /// Reverts to Math.Log10(...) if vectors are not hardware accelerated. 
        /// Given the extra memory copies required, that will be much slower than using scalar code.
        /// It'll be nice once intrinsics make it into dotNet and we can replace this with a single instruction...
        /// </remarks>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static Vector<float> QuickLog10(Vector<float> vec)
        {
            if (Vector.IsHardwareAccelerated)
                return QuickLog2(vec) * new Vector<float>(log10_2);
            else
            {
                float[] tmp = new float[Vector<float>.Count];
                vec.CopyTo(tmp);
                for (int i = 0; i < Vector<float>.Count; i++)
                    tmp[i] = (float)Math.Log10(tmp[i]);
                return new Vector<float>(tmp);
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static unsafe void BitshiftVector23(void* vector)
        {
            UInt64* asUlong = (UInt64*)vector;
            if (Vector<UInt64>.Count == 4)
            {
                *asUlong = *asUlong >> 23;
                asUlong++;
                *asUlong = *asUlong >> 23;
                asUlong++;
                *asUlong = *asUlong >> 23;
                asUlong++;
                *asUlong = *asUlong >> 23;
            }
            else if (Vector<UInt64>.Count == 8)
            {
                *asUlong = *asUlong >> 23;
                asUlong++;
                *asUlong = *asUlong >> 23;
                asUlong++;
                *asUlong = *asUlong >> 23;
                asUlong++;
                *asUlong = *asUlong >> 23;
                asUlong++;
                *asUlong = *asUlong >> 23;
                asUlong++;
                *asUlong = *asUlong >> 23;
                asUlong++;
                *asUlong = *asUlong >> 23;
                asUlong++;
                *asUlong = *asUlong >> 23;
            }
            else
                for (int i = 0; i < Vector<UInt64>.Count; i++)
                    asUlong[i] = asUlong[i] >> 23;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static unsafe void ConvertIntToFloatInPace(void* vector)
        {
            int* asInt = (int*)vector;
            if (Vector<int>.Count == 8)
            {
                *(float*)asInt = *asInt;
                asInt++;
                *(float*)asInt = *asInt;
                asInt++;
                *(float*)asInt = *asInt;
                asInt++;
                *(float*)asInt = *asInt;
                asInt++;
                *(float*)asInt = *asInt;
                asInt++;
                *(float*)asInt = *asInt;
                asInt++;
                *(float*)asInt = *asInt;
                asInt++;
                *(float*)asInt = *asInt;
                asInt++;
            }
            else if (Vector<UInt64>.Count == 16)
            {
                for (int i = 0; i < 2; i++)
                {
                    *(float*)asInt = *asInt;
                    asInt++;
                    *(float*)asInt = *asInt;
                    asInt++;
                    *(float*)asInt = *asInt;
                    asInt++;
                    *(float*)asInt = *asInt;
                    asInt++;
                    *(float*)asInt = *asInt;
                    asInt++;
                    *(float*)asInt = *asInt;
                    asInt++;
                    *(float*)asInt = *asInt;
                    asInt++;
                    *(float*)asInt = *asInt;
                    asInt++;
                }
            }
            else
                for (int i = 0; i < Vector<UInt64>.Count; i++)
                {
                    *(float*)asInt = *asInt;
                    asInt++;
                }
        }


        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static Vector<float> LogPolynomialFunction2(Vector<float> mantissas)
        {
            var zm1 = mantissas;
            var zp1 = mantissas + new Vector<float>(2f);
            var zm1Divzp1 = Vector.Divide(zm1, zp1);
            var squared = zm1Divzp1 * zm1Divzp1;
            var cur = zm1Divzp1;

            //Manual loop unwinding:
#if false
                var mantissasLogged = Vector<float>.Zero;
                for (float i = 0; i < 4; i++)
                {
                    var fac = 2f / (2f * i + 1f);
                    mantissasLogged += cur * new Vector<float>(fac);
                    cur *= squared;
                }
#else
            //i = 0;
            const float fac0 = 2f / (2 * 0 + 1);
            var mantissasLogged = cur * new Vector<float>(fac0);
            cur *= squared;

            //i = 1;
            const float fac1 = 2f / (2 * 1 + 1);
            mantissasLogged += cur * new Vector<float>(fac1);
            cur *= squared;

            //i = 2;
            const float fac2 = 2f / (2 * 2 + 1);
            mantissasLogged += cur * new Vector<float>(fac2);
            cur *= squared;

            //i = 3;
            const float fac3 = 2f / (2 * 3 + 1);
            mantissasLogged += cur * new Vector<float>(fac3);
            cur *= squared;

            //i = 4;
            const float fac4 = 2f / (2 * 4 + 1);
            mantissasLogged += cur * new Vector<float>(fac4);
#endif
            return mantissasLogged;
        }

编辑:启动时,我对程序进行了一些简单的测试。 Vector.IsHardwareAccelerated == true; Vector.Count == 4;此矢量化Log给出了前两个输入的正确答案,但后两个输入却不正确。也许假设Unsafe.AsPointer(Vector)给我一个指向矢量元素的指针是连续的四个浮点的假设是错误的。

日志输出:

DEBUG Vector.IsHardwareAccelerated: True 
DEBUG Vector<float>.Count: 4 
DEBUG Vector<Uint64>.Count: 2 
DEBUG MathUtils test input data: 5.967E+009,1.072E+006,9.521E+017,4.726E+000 
DEBUG MathUtils required output: 9.776,6.030,17.979,0.674 
DEBUG MathUtils actual output: 9.776,6.030,0.218,0.072 

(还有机会检查位模式...)

1 个答案:

答案 0 :(得分:0)

IEEE 754 浮点标准未指定字节序,这肯定是一个问题(取决于您运行的程序)

您可以使用BitConverter.IsLittleEndian并相应地进行更改

  

表示存储数据的字节顺序(“字节序”)   这种计算机体系结构。