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

[api] Implements NDArray.toType() for NDArrayAdapter #2746

Merged
merged 1 commit into from
Aug 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
43 changes: 41 additions & 2 deletions api/src/main/java/ai/djl/ndarray/NDArrayAdapter.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import ai.djl.ndarray.types.SparseFormat;

import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.function.Function;
Expand Down Expand Up @@ -157,8 +158,46 @@ public NDArray toType(DataType dataType, boolean copy) {
}
return this;
}
// TODO: each engine should override this method
throw new UnsupportedOperationException(UNSUPPORTED_MSG);
Number[] numbers = toArray();
ByteBuffer bb = toTypeInternal(numbers, dataType);
return manager.create(bb, getShape(), dataType);
}

private ByteBuffer toTypeInternal(Number[] numbers, DataType dataType) {
int size = dataType.getNumOfBytes() * numbers.length;
ByteBuffer bb = manager.allocateDirect(size);
for (Number number : numbers) {
switch (dataType) {
case FLOAT16:
case FLOAT32:
bb.putFloat(number.floatValue());
break;
case FLOAT64:
bb.putDouble(number.doubleValue());
break;
case INT16:
case UINT16:
bb.putShort(number.shortValue());
break;
case INT32:
case UINT32:
bb.putInt(number.intValue());
break;
case INT64:
case UINT64:
bb.putLong(number.longValue());
break;
case BOOLEAN:
case INT8:
case UINT8:
bb.put(number.byteValue());
break;
default:
throw new IllegalStateException("Unsupported DataType: " + getDataType());
}
}
bb.rewind();
return bb;
}

/** {@inheritDoc} */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1044,7 +1044,11 @@ public NDArray where(NDArray condition, NDArray other) {
array2 = other;
}
try {
return getManager().invoke("where", new NDArray[] {condition, array1, array2}, null);
MxNDManager manager = getManager();
return manager.invoke(
"where",
new NDArray[] {manager.from(condition), array1, manager.from(array2)},
null);
} finally {
if (array1 != array) {
array1.close();
Expand Down