Skip to content

[Question] How to get NDarray into .NET native types array effectivly? #139

Closed

Description

@ElinLiu0

Like this code:

for (int i = 0; i < hubertFeature.shape[0]; i++)
{
    for (int j = 0; j < hubertFeature.shape[1]; j++)
    {
        for (int k = 0; k < hubertFeature.shape[2]; k++)
        {
            hubertSharpNative[i * hubertFeature.shape[1] * hubertFeature.shape[2] + j * hubertFeature.shape[2] + k] = (Single)hubertFeature[i, j, k];
        }
    }
}

I promise i've tried using GetData<Single>() or flatten first then using GetData<Single>(),non of them are correct actually.So i'm just looking for a more effective and fast way to do this. : )

Activity

  1. henon commented on Oct 24, 2025

    @henon
    Contributor

    Manually looping over a 3-dimensional ndarray in C# is the most inefficient way of retrieving the data I can think of. You are crossing the Python-C# boundary for every single entry and thus have cubic overhead.

    I don't believe that GetData<float> is not working. I have here a testcase that proves otherwise:

            [TestMethod]
            public void IssueByElinLiu0()
            {
                var x = np.array(new float[,] { { 1.1f, 2.2f }, { 3.141596f, 4.4f } });
                var y = string.Join(',', x.GetData<float>().Select(z => z.ToString(CultureInfo.InvariantCulture)));
                Console.WriteLine("Proof: " + y);
                Assert.AreEqual("1.1,2.2,3.141596,4.4", y);
            }

    Output is Proof: 1.1,2.2,3.141596,4.4

  2. added a commit that references this issue on Oct 24, 2025
  3. ElinLiu0 commented on Oct 27, 2025

    @ElinLiu0
    Author

    Sorry lately for the reply,since i've played video games in this whole weekend😂
    Here is a little code to demostrate what i've met:

    using Numpy;
    const string numpyFilePath = @"D:\My Code\quantize_test\callibration_data\phone.npy";
    var npArray = np.load(numpyFilePath);
    Console.WriteLine($"Array Shape: {string.Join(", ", npArray.shape)}");
    Console.WriteLine($"Array Data Type: {npArray.dtype}");
    var nativeViaGetData = npArray.GetData<float>();
    Console.WriteLine("First 10 elements via ToCsharp<float>:");

    Well,the real problem is not reproduce on my laptop but anothere has appeared:

    Array Shape: (1, 150, 768)
    Array Data Type: float16
    Fatal error. Internal CLR error. (0x80131506)
       at System.Buffer._Memmove(Byte ByRef, Byte ByRef, UIntPtr)
       at System.Runtime.InteropServices.Marshal.CopyToManaged[[System.Single, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]](IntPtr, Single[], Int32, Int32)
       at Numpy.NDarray.GetData[[System.Single, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]()
       at Numpy.NDarray.GetData[[System.Single, System.Private.CoreLib, Version=8.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]()
       at Program.<Main>$(System.String[])

    Any idea on this?? : (

    phone.zip

  4. ElinLiu0 commented on Oct 27, 2025

    @ElinLiu0
    Author

    Well,i think i found the solution way out:

    using Numpy;
    using Microsoft.ML.OnnxRuntime.Tensors;
    
    const string numpyFilePath = @"D:\My Code\quantize_test\callibration_data\phone.npy";
    
    var npArray = np.load(numpyFilePath).astype(np.float32);
    
    Console.WriteLine($"Array Shape: {string.Join(", ", npArray.shape)}");
    
    Console.WriteLine($"Array Data Type: {npArray.dtype}");
    
    var nativeViaGetData = npArray.GetData<float>();
    
    var fp16Array = nativeViaGetData.Select(x => (Half)x).ToArray();
    
    var onnxTensor = new DenseTensor<Half>(fp16Array, new int[] { npArray.shape[0], npArray.shape[1], npArray.shape[2] });
    
    Console.WriteLine("First 10 elements via ToCsharp<float>:");

    And it's worked fine:

    Image
  5. ElinLiu0 commented on Oct 27, 2025

    @ElinLiu0
    Author

    The problem used is that:

    var fp16Array = nativeViaGetData.Select(x => (Float16)x).ToArray();

    See Microsoft.ML.OnnxRuntime also provide a dtype called Float16,but it actually looks in this way:

    Image

    I really don't know why?May be it's a predefined strcuture somehow i guess?When i turn Float16 into Half it as expected as upon post.

  6. henon commented on Oct 27, 2025

    @henon
    Contributor

    I just remembered, there was an issue with Float16: #115

  7. ElinLiu0 commented on Oct 27, 2025

    @ElinLiu0
    Author

    I just remembered, there was an issue with Float16: #115

    Yeah,but the FP16 you mentioned is different like mine.But,anyway the problem is solved in...
    Right? 🤣

  8. henon commented on Oct 27, 2025

    @henon
    Contributor

    Here is a specification of C#'s Half type: This is the IEEE floating point specification, a very common format: https://devblogs.microsoft.com/dotnet/introducing-the-half-type/

    I can't believe that numpy uses a different format internally but I don't have time to research it. Maybe it is an endianness problem?

  9. henon commented on Oct 27, 2025

    @henon
    Contributor

    But like I showed in #115 you have the option to copy the bytes and transform the data into floats in C#, provided that you know the binary format.

  10. ElinLiu0 commented on Oct 27, 2025

    @ElinLiu0
    Author

    Here is a specification of C#'s Half type: This is the IEEE floating point specification, a very common format: https://devblogs.microsoft.com/dotnet/introducing-the-half-type/

    I can't believe that numpy uses a different format internally but I don't have time to research it. Maybe it is an endianness problem?

    Opps..Not numpy's problem at all cause it working as expected on Python.Seems the Float16 structure in ONNX c# quite be Special...

  11. ElinLiu0 commented on Oct 27, 2025

    @ElinLiu0
    Author

    But like I showed in #115 you have the option to copy the bytes and transform the data into floats in C#, provided that you know the binary format.

    Yeah.I've seen this annda will that in mind.

  12. henon commented on Oct 27, 2025

    @henon
    Contributor

    c# quite be Special...

    Actually the The IEEE 754 specification is nothing special. It is the most common representation of floating point values of 16, 32, 64 and 128 bits.

  13. henon commented on Oct 27, 2025

    @henon
    Contributor

    I found information about Float16 here https://numpy.org/doc/stable/user/basics.types.html

    Half precision float: sign bit, 5 bits exponent, 10 bits mantissa.

    That looks like IEEE to me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions