Skip to content

Vector512 CopyTo<T>(this Vector512<T> vector, T[] destination, int startIndex) incorrect #94743

Closed

Description

@JamesVaughan

Description

The current implementation of Vector512.CopyTo uses a byte offset into the array instead of an offset for the size of the given type. This causes unexpected results for all types outside of byte.

Reproduction Steps

var a = new float[17];
var toSet = Vector512.Create(2.0f);
toSet.CopyTo(a, 1);
for (int i = 0; i < a.Length; i++)
{
    Console.WriteLine($"{i} = {a[i]}");
}

Expected behavior

0 = 0
1 = 2
2 = 2
3 = 2
4 = 2
5 = 2
6 = 2
7 = 2
8 = 2
9 = 2
10 = 2
11 = 2
12 = 2
13 = 2
14 = 2
15 = 2
16 = 2

Actual behavior

0 = 0
1 = 9E-44
2 = 9E-44
3 = 9E-44
4 = 9E-44
5 = 9E-44
6 = 9E-44
7 = 9E-44
8 = 9E-44
9 = 9E-44
10 = 9E-44
11 = 9E-44
12 = 9E-44
13 = 9E-44
14 = 9E-44
15 = 9E-44
16 = 9E-44

Regression?

No response

Known Workarounds

var a = new float[17];
var toSet = Vector512.Create(2.0f);
Vector512.StoreUnsafe(toSet, ref a[1]);
for (int i = 0; i < a.Length; i++)
{
    Console.WriteLine($"{i} = {a[i]}");
}

Configuration

.net 8.0.100
Windows 11
x64, AMD 7950X.

Other information

No response

Activity

  1. ghost added
    area-CodeGen-coreclr
    on Nov 15, 2023
  2. ghost added
    untriaged
    on Nov 15, 2023
  3. added and removed
    area-CodeGen-coreclr
    on Nov 15, 2023
  4. huoyaoyuan commented on Nov 15, 2023

    @huoyaoyuan
    Member

    The implementation for Vector256:

    Unsafe.WriteUnaligned(ref Unsafe.As<T, byte>(ref destination[startIndex]), vector);

    Which correctly adds offset in T.

    For Vector512:

    ref byte address = ref Unsafe.As<T, byte>(ref MemoryMarshal.GetArrayDataReference(destination));
    Unsafe.WriteUnaligned(ref Unsafe.Add(ref address, startIndex), vector);

    Which incorrectly adds offset in bytes.

    The correct and optimal implementation would be swapping Unsafe.Add and Unsafe.As:

    ref T address = ref MemoryMarshal.GetArrayDataReference(destination);
    Unsafe.WriteUnaligned(ref Unsafe.As<T, byte>(ref Unsafe.Add(ref address, startIndex)), vector);
  5. ghost added
    in-pr
    on Nov 15, 2023
  6. ghost removed
    in-pr
    on Nov 20, 2023
  7. ghost removed
    untriaged
    on Nov 20, 2023
  8. locked and limited conversation to collaborators on Dec 21, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions