Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fast TensorAccessor #1396

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Numel
  • Loading branch information
haytham2597 committed Oct 25, 2024
commit 0b20f13779ace6460fe6391d1b81eecd05e98e01
22 changes: 8 additions & 14 deletions src/TorchSharp/Utils/TensorAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,15 @@ public T[] ToArray()
{
if (_tensor.ndim < 2)
return (T[])ToNDArray();

long Cnt = Count;
if (_tensor.is_contiguous()) {
haytham2597 marked this conversation as resolved.
Show resolved Hide resolved
//This is very fast. And work VERY WELL
var shps = _tensor.shape;
long TempCount = 1;
for (int i = 0; i < shps.Length; i++)
TempCount *= shps[i]; //Theorically the numel is simple as product of each element shape
if (Cnt == 0)
throw new Exception("Invalid");
unsafe {
return new Span<T>(_tensor_data_ptr.ToPointer(), Convert.ToInt32(TempCount)).ToArray();
return new Span<T>(_tensor_data_ptr.ToPointer(), Convert.ToInt32(Cnt)).ToArray();
}
}
var result = new T[Count];
var result = new T[Cnt];
CopyTo(result);
return result;
}
Expand Down Expand Up @@ -246,12 +243,9 @@ private void CopyContiguous(T[] array, int index=0, int count=0)
{
if (!_tensor.is_contiguous())
throw new Exception("The tensor is not contiguous");
var shps = _tensor.shape;
long TempCount = 1;
for (int i = 0; i < shps.Length; i++)
TempCount *= shps[i]; //Theorically the numel is simple as product of each element shape
if (count > TempCount || count == 0)
count = (int)TempCount;
var Cnt = Count;
if (count > Cnt || count == 0)
count = (int)Cnt;
if (array is byte[] ba)
Marshal.Copy(_tensor_data_ptr, ba, index, count);
if (array is short[] sa)
Expand Down