index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/ConfigSpace.java
package ai.djl.mxnet.jna; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.ptr.PointerByReference; import java.util.Arrays; import java.util.List; public class ConfigSpace extends Structure { public int entity_map_size; public PointerByReference entity_map_key; public OtherOptionEntity.ByReference entity_map_val; public int space_map_size; public PointerByReference space_map_key; public OtherOptionSpace.ByReference space_map_val; public ConfigSpace() { } public ConfigSpace(Pointer peer) { super(peer); } @Override protected List<String> getFieldOrder() { return Arrays.asList("entity_map_size", "entity_map_key", "entity_map_val", "space_map_size", "space_map_key", "space_map_val"); } public void setEntityMapSize(int entity_map_size) { this.entity_map_size = entity_map_size; } public int getEntityMapSize() { return entity_map_size; } public void setEntityMapKey(PointerByReference entity_map_key) { this.entity_map_key = entity_map_key; } public PointerByReference getEntityMapKey() { return entity_map_key; } public void setEntityMapVal(OtherOptionEntity.ByReference entity_map_val) { this.entity_map_val = entity_map_val; } public OtherOptionEntity.ByReference getEntityMapVal() { return entity_map_val; } public void setSpaceMapSize(int space_map_size) { this.space_map_size = space_map_size; } public int getSpaceMapSize() { return space_map_size; } public void setSpaceMapKey(PointerByReference space_map_key) { this.space_map_key = space_map_key; } public PointerByReference getSpaceMapKey() { return space_map_key; } public void setSpaceMapVal(OtherOptionSpace.ByReference space_map_val) { this.space_map_val = space_map_val; } public OtherOptionSpace.ByReference getSpaceMapVal() { return space_map_val; } public static final class ByReference extends ConfigSpace implements Structure.ByReference {} public static final class ByValue extends ConfigSpace implements Structure.ByValue {} }
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/FunctionInfo.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.mxnet.jna; import ai.djl.Device; import ai.djl.mxnet.engine.MxNDArray; import ai.djl.mxnet.engine.MxNDManager; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.SparseFormat; import ai.djl.training.Trainer; import ai.djl.util.PairList; import com.sun.jna.Pointer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** A FunctionInfo represents an operator (ie function) within the MXNet Engine. */ public class FunctionInfo { private Pointer handle; private String name; private PairList<String, String> arguments; private static final Logger logger = LoggerFactory.getLogger(Trainer.class); FunctionInfo(Pointer pointer, String functionName, PairList<String, String> arguments) { this.handle = pointer; this.name = functionName; this.arguments = arguments; } /** * Calls an operator with the given arguments. * * @param manager the manager to attach the result to * @param src the input NDArray(s) to the operator * @param dest the destination NDArray(s) to be overwritten with the result of the operator * @param params the non-NDArray arguments to the operator. Should be a {@code PairList<String, * String>} * @return the error code or zero for no errors */ public int invoke( NDManager manager, NDArray[] src, NDArray[] dest, PairList<String, ?> params) { checkDevices(src); checkDevices(dest); return JnaUtils.imperativeInvoke(handle, src, dest, params).size(); } /** * Calls an operator with the given arguments. * * @param manager the manager to attach the result to * @param src the input NDArray(s) to the operator * @param params the non-NDArray arguments to the operator. Should be a {@code PairList<String, * String>} * @return the error code or zero for no errors */ public NDArray[] invoke(NDManager manager, NDArray[] src, PairList<String, ?> params) { checkDevices(src); PairList<Pointer, SparseFormat> pairList = JnaUtils.imperativeInvoke(handle, src, null, params); final MxNDManager mxManager = (MxNDManager) manager; return pairList.stream() .map( pair -> { if (pair.getValue() != SparseFormat.DENSE) { return mxManager.create(pair.getKey(), pair.getValue()); } return mxManager.create(pair.getKey()); }) .toArray(MxNDArray[]::new); } /** * Returns the name of the operator. * * @return the name of the operator */ public String getFunctionName() { return name; } /** * Returns the names of the params to the operator. * * @return the names of the params to the operator */ public List<String> getArgumentNames() { return arguments.keys(); } /** * Returns the types of the operator arguments. * * @return the types of the operator arguments */ public List<String> getArgumentTypes() { return arguments.values(); } private void checkDevices(NDArray[] src) { // check if all the NDArrays are in the same device if (logger.isDebugEnabled() && src.length > 1) { Device device = src[0].getDevice(); for (int i = 1; i < src.length; ++i) { if (!device.equals(src[i].getDevice())) { logger.warn( "Please make sure all the NDArrays are in the same device. You can call" + " toDevice() to move the NDArray to the desired Device."); } } } } }
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/JnaUtils.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.mxnet.jna; import ai.djl.Device; import ai.djl.engine.EngineException; import ai.djl.mxnet.engine.CachedOp; import ai.djl.mxnet.engine.MxDeviceType; import ai.djl.mxnet.engine.MxNDArray; import ai.djl.mxnet.engine.MxNDManager; import ai.djl.mxnet.engine.MxSymbolBlock; import ai.djl.mxnet.engine.Symbol; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.ndarray.types.SparseFormat; import ai.djl.nn.Parameter; import ai.djl.util.PairList; import ai.djl.util.Utils; import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.ptr.PointerByReference; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * A class containing utilities to interact with the MXNet Engine's Java Native Access (JNA) layer. */ @SuppressWarnings({"MissingJavadocMethod", "dangling-doc-comments"}) public final class JnaUtils { public static final ObjectPool<PointerByReference> REFS = new ObjectPool<>(PointerByReference::new, r -> r.setValue(null)); /** An enum that enumerates the statuses of numpy mode. */ public enum NumpyMode { OFF, THREAD_LOCAL_ON, GLOBAL_ON } private static final String[] OP_NAME_PREFIX = { "_contrib_", "_linalg_", "_sparse_", "_image_", "_random_" }; private static final MxnetLibrary LIB = LibUtils.loadLibrary(); private static final Map<String, FunctionInfo> OPS = getNdArrayFunctions(); private static final Set<String> FEATURES = getFeaturesInternal(); private JnaUtils() {} ///////////////////////////////// // MXNet information ///////////////////////////////// public static int getVersion() { IntBuffer version = IntBuffer.allocate(1); checkCall(LIB.MXGetVersion(version)); return version.get(); } public static Set<String> getAllOpNames() { IntBuffer outSize = IntBuffer.allocate(1); PointerByReference outArray = REFS.acquire(); checkCall(LIB.MXListAllOpNames(outSize, outArray)); int size = outSize.get(); Pointer[] pointers = outArray.getValue().getPointerArray(0, size); Set<String> set = new HashSet<>(); for (Pointer p : pointers) { set.add(p.getString(0, StandardCharsets.UTF_8.name())); } REFS.recycle(outArray); return set; } public static Map<String, FunctionInfo> getNdArrayFunctions() { Set<String> opNames = JnaUtils.getAllOpNames(); Map<String, FunctionInfo> map = new ConcurrentHashMap<>(); PointerByReference ref = REFS.acquire(); for (String opName : opNames) { checkCall(LIB.NNGetOpHandle(opName, ref)); String functionName = getOpNamePrefix(opName); // System.out.println("Name: " + opName + "/" + functionName); map.put(functionName, getFunctionByName(opName, functionName, ref.getValue())); ref.setValue(null); } REFS.recycle(ref); return map; } public static FunctionInfo op(String opName) { if (!OPS.containsKey(opName)) { throw new IllegalArgumentException("Unknown operator: " + opName); } return OPS.get(opName); } private static FunctionInfo getFunctionByName( String name, String functionName, Pointer handle) { String[] nameRef = {name}; String[] description = new String[1]; IntBuffer numArgs = IntBuffer.allocate(1); PointerByReference argNameRef = REFS.acquire(); PointerByReference argTypeRef = REFS.acquire(); PointerByReference argDescRef = REFS.acquire(); String[] keyVarArgs = new String[1]; String[] returnType = new String[1]; checkCall( LIB.MXSymbolGetAtomicSymbolInfo( handle, nameRef, description, numArgs, argNameRef, argTypeRef, argDescRef, keyVarArgs, returnType)); int count = numArgs.get(); PairList<String, String> arguments = new PairList<>(); if (count != 0) { String[] argNames = argNameRef.getValue().getStringArray(0, count, StandardCharsets.UTF_8.name()); String[] argTypes = argTypeRef.getValue().getStringArray(0, count, StandardCharsets.UTF_8.name()); for (int i = 0; i < argNames.length; i++) { arguments.add(argNames[i], argTypes[i]); } } REFS.recycle(argNameRef); REFS.recycle(argTypeRef); REFS.recycle(argDescRef); return new FunctionInfo(handle, functionName, arguments); } /* int MXFuncGetInfo(Pointer fun, String name[], String description[], IntBuffer num_args, PointerByReference arg_names, PointerByReference arg_type_infos, PointerByReference arg_descriptions, String return_type[]); int MXFuncDescribe(Pointer fun, IntBuffer num_use_vars, IntBuffer num_scalars, IntBuffer num_mutate_vars, IntBuffer type_mask); int MXFuncInvoke(Pointer fun, PointerByReference use_vars, FloatBuffer scalar_args, PointerByReference mutate_vars); int MXFuncInvokeEx(Pointer fun, PointerByReference use_vars, FloatBuffer scalar_args, PointerByReference mutate_vars, int num_params, PointerByReference param_keys, PointerByReference param_vals); */ ///////////////////////////////// // System information ///////////////////////////////// public static int getGpuCount() { IntBuffer count = IntBuffer.allocate(1); checkCall(LIB.MXGetGPUCount(count)); return count.get(); } public static long[] getGpuMemory(Device device) { if (!device.isGpu()) { throw new IllegalArgumentException("Only GPU device is allowed."); } int deviceId = device.getDeviceId(); long[] ret = new long[2]; LongBuffer freeMem = LongBuffer.wrap(ret, 0, 1); LongBuffer totalMem = LongBuffer.wrap(ret, 1, 1); checkCall(LIB.MXGetGPUMemoryInformation64(deviceId, freeMem, totalMem)); return ret; } /* Need tests public static void setOmpThreads(int threads) { checkCall(LIB.MXSetNumOMPThreads(threads)); } public static int setBulkSize(int bulkSize) { IntBuffer prevBulkSize = IntBuffer.allocate(1); checkCall(LIB.MXEngineSetBulkSize(bulkSize, prevBulkSize)); return prevBulkSize.get(); } */ ///////////////////////////////// // Utilities ///////////////////////////////// public static Set<String> getFeatures() { return FEATURES; } private static Set<String> getFeaturesInternal() { PointerByReference ref = REFS.acquire(); NativeSizeByReference outSize = new NativeSizeByReference(); checkCall(LIB.MXLibInfoFeatures(ref, outSize)); int size = outSize.getValue().intValue(); if (size == 0) { REFS.recycle(ref); return Collections.emptySet(); } LibFeature pointer = new LibFeature(ref.getValue()); pointer.read(); LibFeature[] features = (LibFeature[]) pointer.toArray(size); Set<String> set = new HashSet<>(); for (LibFeature feature : features) { if (feature.getEnabled() == 1) { set.add(feature.getName()); } } REFS.recycle(ref); return set; } public static int randomSeed(int seed) { return LIB.MXRandomSeed(seed); } /* Need tests public static int randomSeed(int seed, Device device) { int deviceType = DeviceType.toDeviceType(device); return LIB.MXRandomSeedContext(seed, deviceType, device.getDeviceId()); } public static void notifyShutdown() { checkCall(LIB.MXNotifyShutdown()); } */ ///////////////////////////////// // Profiler information ///////////////////////////////// /* public static int setProcessProfilerConfig(int numParams, String keys[], String vals[], Pointer kvstoreHandle) { } int MXSetProfilerConfig(int num_params, String keys[], String vals[]); int MXSetProcessProfilerState(int state, int profile_process, Pointer kvStoreHandle); int MXSetProfilerState(int state); int MXDumpProcessProfile(int finished, int profile_process, Pointer kvStoreHandle); int MXDumpProfile(int finished); int MXAggregateProfileStatsPrint(String out_str[], int reset); int MXProcessProfilePause(int paused, int profile_process, Pointer kvStoreHandle); int MXProfilePause(int paused); int MXProfileCreateDomain(String domain, PointerByReference out); int MXProfileCreateTask(Pointer domain, Pointer task_name, PointerByReference out); int MXProfileCreateTask(Pointer domain, String task_name, PointerByReference out); int MXProfileCreateFrame(Pointer domain, String frame_name, PointerByReference out); int MXProfileCreateEvent(String event_name, PointerByReference out); int MXProfileCreateCounter(Pointer domain, String counter_name, PointerByReference out); int MXProfileDestroyHandle(Pointer frame_handle); int MXProfileDurationStart(Pointer duration_handle); int MXProfileDurationStop(Pointer duration_handle); int MXProfileSetCounter(Pointer counter_handle, long value); int MXProfileAdjustCounter(Pointer counter_handle, long value); int MXProfileSetMarker(Pointer domain, String instant_marker_name, String scope); */ ///////////////////////////////// // NDArray ///////////////////////////////// /* Need tests public static Pointer createNdArray() { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXNDArrayCreateNone(ref)); return ref.getValue(); } */ public static Pointer createNdArray( Device device, Shape shape, DataType dtype, int size, boolean delayedAlloc) { int deviceType = MxDeviceType.toDeviceType(device); int deviceId = device.getDeviceId(); int delay = delayedAlloc ? 1 : 0; PointerByReference ref = REFS.acquire(); long[] shapeArray = shape.getShape(); checkCall( LIB.MXNDArrayCreateEx64( shapeArray, size, deviceType, deviceId, delay, dtype.ordinal(), ref)); Pointer pointer = ref.getValue(); REFS.recycle(ref); return pointer; } public static Pointer createSparseNdArray( SparseFormat fmt, Device device, Shape shape, DataType dtype, DataType[] auxDTypes, Shape[] auxShapes, boolean delayedAlloc) { long[] shapeArray = shape.getShape(); int deviceType = MxDeviceType.toDeviceType(device); int deviceId = device.getDeviceId(); int delay = delayedAlloc ? 1 : 0; PointerByReference ref = REFS.acquire(); IntBuffer auxDTypesInt = IntBuffer.wrap(Arrays.stream(auxDTypes).mapToInt(DataType::ordinal).toArray()); IntBuffer auxNDims = IntBuffer.wrap(Arrays.stream(auxShapes).mapToInt(Shape::dimension).toArray()); long[] auxShapesInt = Arrays.stream(auxShapes).mapToLong(Shape::head).toArray(); checkCall( LIB.MXNDArrayCreateSparseEx64( fmt.getValue(), shapeArray, shapeArray.length, deviceType, deviceId, delay, dtype.ordinal(), auxDTypes.length, auxDTypesInt, auxNDims, auxShapesInt, ref)); Pointer pointer = ref.getValue(); REFS.recycle(ref); return pointer; } public static void ndArraySyncCopyFromNdArray(MxNDArray dest, MxNDArray src, int location) { checkCall(LIB.MXNDArraySyncCopyFromNDArray(dest.getHandle(), src.getHandle(), location)); } /* Need tests public static Pointer loadFromBytes(byte[] buf, int offset, int size) { Memory memory = new Memory(size); memory.write(0, buf, offset, size); PointerByReference ref = new PointerByReference(); checkCall(LIB.MXNDArrayLoadFromRawBytes(memory, new NativeSize(size), ref)); return ref.getValue(); } public static void saveNdArray(String file, Pointer[] ndArrays, String[] keys) { PointerArray array = new PointerArray(ndArrays); checkCall(LIB.MXNDArraySave(file, ndArrays.length, array, keys)); } */ public static NDList loadNdArray(MxNDManager manager, Path path, Device device) { IntBuffer handlesSize = IntBuffer.allocate(1); PointerByReference handlesRef = REFS.acquire(); PointerByReference namesRef = REFS.acquire(); IntBuffer namesSize = IntBuffer.allocate(1); checkCall(LIB.MXNDArrayLoad(path.toString(), handlesSize, handlesRef, namesSize, namesRef)); int ndArrayCount = handlesSize.get(); int nameCount = namesSize.get(); if (nameCount > 0 && ndArrayCount != nameCount) { throw new IllegalStateException( "Mismatch between names and arrays in checkpoint file: " + path.toString()); } Pointer[] handles = handlesRef.getValue().getPointerArray(0, ndArrayCount); NDList ndList = new NDList(); if (nameCount == 0) { for (Pointer handle : handles) { ndList.add(manager.create(handle)); } } else { String[] names = namesRef.getValue().getStringArray(0, nameCount); for (int i = 0; i < ndArrayCount; i++) { NDArray array = manager.create(handles[i]); array.setName(names[i]); ndList.add(array); } } REFS.recycle(namesRef); REFS.recycle(handlesRef); // MXNet always load NDArray on CPU if (Device.cpu().equals(device)) { return ndList; } NDList ret = ndList.toDevice(device, true); ndList.close(); return ret; } /* Need tests public static ByteBuffer readBytes(Pointer ndArray) { NativeSizeByReference size = new NativeSizeByReference(); PointerByReference ref = new PointerByReference(); checkCall(LIB.MXNDArraySaveRawBytes(ndArray, size, ref)); return ref.getValue().getByteBuffer(0, size.getValue().longValue()); } */ public static void freeNdArray(Pointer ndArray) { checkNDArray(ndArray, "free"); checkCall(LIB.MXNDArrayFree(ndArray)); } public static void waitToRead(Pointer ndArray) { checkNDArray(ndArray, "wait to read"); checkCall(LIB.MXNDArrayWaitToRead(ndArray)); } public static void waitToWrite(Pointer ndArray) { checkNDArray(ndArray, "wait to write"); checkCall(LIB.MXNDArrayWaitToWrite(ndArray)); } public static void waitAll() { checkCall(LIB.MXNDArrayWaitAll()); } public static void syncCopyToCPU(Pointer ndArray, Pointer data, int len) { NativeSize size = new NativeSize(len); checkNDArray(ndArray, "copy from"); checkNDArray(data, "copy to"); checkCall(LIB.MXNDArraySyncCopyToCPU(ndArray, data, size)); } public static void syncCopyFromCPU(Pointer ndArray, Buffer data, int len) { NativeSize size = new NativeSize(len); Pointer pointer = Native.getDirectBufferPointer(data); checkCall(LIB.MXNDArraySyncCopyFromCPU(ndArray, pointer, size)); } public static PairList<Pointer, SparseFormat> imperativeInvoke( Pointer function, NDArray[] src, NDArray[] dest, PairList<String, ?> params) { String[] keys; String[] values; if (params == null) { keys = Utils.EMPTY_ARRAY; values = Utils.EMPTY_ARRAY; } else { keys = params.keyArray(Utils.EMPTY_ARRAY); values = params.values().stream().map(Object::toString).toArray(String[]::new); } StringArray keyArray = StringArray.of(keys); StringArray valueArray = StringArray.of(values); PointerArray srcArray = toPointerArray(src); PointerArray destArray = toPointerArray(dest); PointerByReference destRef = REFS.acquire(); destRef.setValue(destArray); PointerByReference destSType = REFS.acquire(); IntBuffer numOutputs = IntBuffer.allocate(1); numOutputs.put(0, 1); checkCall( LIB.MXImperativeInvokeEx( function, src.length, srcArray, numOutputs, destRef, keys.length, keyArray, valueArray, destSType)); int numOfOutputs = numOutputs.get(0); Pointer[] ptrArray = destRef.getValue().getPointerArray(0, numOfOutputs); int[] sTypes = destSType.getValue().getIntArray(0, numOfOutputs); PairList<Pointer, SparseFormat> pairList = new PairList<>(); for (int i = 0; i < numOfOutputs; i++) { pairList.add(ptrArray[i], SparseFormat.fromValue(sTypes[i])); } REFS.recycle(destRef); REFS.recycle(destSType); srcArray.recycle(); keyArray.recycle(); valueArray.recycle(); if (destArray != null) { destArray.recycle(); } return pairList; } public static SparseFormat getStorageType(Pointer ndArray) { IntBuffer type = IntBuffer.allocate(1); checkNDArray(ndArray, "get the storage type of"); checkCall(LIB.MXNDArrayGetStorageType(ndArray, type)); return SparseFormat.fromValue(type.get()); } public static Device getDevice(Pointer ndArray) { IntBuffer deviceType = IntBuffer.allocate(1); IntBuffer deviceId = IntBuffer.allocate(1); checkNDArray(ndArray, "get the device of"); checkCall(LIB.MXNDArrayGetContext(ndArray, deviceType, deviceId)); String deviceTypeStr = MxDeviceType.fromDeviceType(deviceType.get(0)); // CPU is special case which don't have device id return Device.of(deviceTypeStr, deviceId.get(0)); } public static Shape getShape(Pointer ndArray) { IntBuffer dim = IntBuffer.allocate(1); PointerByReference ref = REFS.acquire(); checkNDArray(ndArray, "get the shape of"); checkCall(LIB.MXNDArrayGetShapeEx64(ndArray, dim, ref)); int nDim = dim.get(); if (nDim == 0) { REFS.recycle(ref); return new Shape(); } long[] shape = ref.getValue().getLongArray(0, nDim); REFS.recycle(ref); return new Shape(shape); } public static DataType getDataType(Pointer ndArray) { IntBuffer dataType = IntBuffer.allocate(1); checkNDArray(ndArray, "get the data type of"); checkCall(LIB.MXNDArrayGetDType(ndArray, dataType)); return DataType.values()[dataType.get()]; } /* Need tests public static DataType getAuxType(Pointer ndArray, int index) { IntBuffer dataType = IntBuffer.allocate(1); checkCall(LIB.MXNDArrayGetAuxType(ndArray, index, dataType)); return DataType.values()[dataType.get()]; } public static Pointer getAuxNdArray(Pointer ndArray, int index) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXNDArrayGetAuxNDArray(ndArray, index, ref)); return ref.getValue(); } public static Pointer getDataNdArray(Pointer ndArray) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXNDArrayGetDataNDArray(ndArray, ref)); return ref.getValue(); } public static Pointer getGrad(Pointer ndArray) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXNDArrayGetGrad(ndArray, ref)); return ref.getValue(); } public static Pointer reshape(Pointer ndArray, long[] dims, boolean reverse) { PointerByReference ref = new PointerByReference(); byte reverseByte = reverse ? (byte) 1 : 0; checkCall( LIB.MXNDArrayReshape64( ndArray, dims.length, LongBuffer.wrap(dims), reverseByte, ref)); return ref.getValue(); } */ ///////////////////////////////// // MxGradientCollector ///////////////////////////////// public static boolean autogradSetIsRecording(boolean isRecording) { IntBuffer prev = IntBuffer.allocate(1); checkCall(LIB.MXAutogradSetIsRecording(isRecording ? 1 : 0, prev)); return prev.get(0) == 1; } public static boolean autogradSetTraining(boolean isTraining) { IntBuffer prev = IntBuffer.allocate(1); checkCall(LIB.MXAutogradSetIsTraining(isTraining ? 1 : 0, prev)); return prev.get(0) == 1; } public static boolean autogradIsRecording() { ByteBuffer isRecording = ByteBuffer.allocate(1); checkCall(LIB.MXAutogradIsRecording(isRecording)); return isRecording.get(0) == 1; } public static boolean autogradIsTraining() { ByteBuffer isTraining = ByteBuffer.allocate(1); checkCall(LIB.MXAutogradIsTraining(isTraining)); return isTraining.get(0) == 1; } public static void autogradMarkVariables( int numVar, Pointer varHandles, IntBuffer reqsArray, Pointer gradHandles) { PointerByReference varRef = REFS.acquire(); PointerByReference gradRef = REFS.acquire(); varRef.setValue(varHandles); gradRef.setValue(gradHandles); checkCall(LIB.MXAutogradMarkVariables(numVar, varRef, reqsArray, gradRef)); REFS.recycle(varRef); REFS.recycle(gradRef); } public static void autogradBackward(NDList array, int retainGraph) { PointerByReference ref = REFS.acquire(); PointerArray pa = toPointerArray(array); checkCall(LIB.MXAutogradBackward(array.size(), pa, ref, retainGraph)); REFS.recycle(ref); pa.recycle(); } public static void autogradBackwardExecute( int numOutput, NDList array, NDArray outgrad, int numVariables, Pointer varHandles, int retainGraph, int createGraph, int isTrain, Pointer gradHandles, Pointer gradSparseFormat) { PointerByReference varRef = REFS.acquire(); PointerByReference gradRef = REFS.acquire(); PointerByReference gradSparseFormatRef = REFS.acquire(); varRef.setValue(varHandles); gradRef.setValue(gradHandles); gradSparseFormatRef.setValue(gradSparseFormat); PointerArray inputHandles = toPointerArray(array); PointerArray ogradHandles = PointerArray.of(); checkCall( LIB.MXAutogradBackwardEx( numOutput, inputHandles, ogradHandles, numVariables, varRef, retainGraph, createGraph, isTrain, gradRef, gradSparseFormatRef)); REFS.recycle(varRef); REFS.recycle(gradRef); REFS.recycle(gradSparseFormatRef); inputHandles.recycle(); ogradHandles.recycle(); } public static Pointer autogradGetSymbol(NDArray array) { Pointer handle = ((MxNDArray) array).getHandle(); PointerByReference out = REFS.acquire(); checkCall(LIB.MXAutogradGetSymbol(handle, out)); Pointer pointer = out.getValue(); REFS.recycle(out); return pointer; } public static int isNumpyMode() { IntBuffer ret = IntBuffer.allocate(1); checkCall(LIB.MXIsNumpyShape(ret)); return ret.get(); } public static void setNumpyMode(NumpyMode mode) { IntBuffer ret = IntBuffer.allocate(1); checkCall(LIB.MXSetIsNumpyShape(mode.ordinal(), ret)); } public static Pointer getGradient(Pointer handle) { PointerByReference ref = REFS.acquire(); checkNDArray(handle, "get the gradient for"); checkCall(LIB.MXNDArrayGetGrad(handle, ref)); Pointer pointer = ref.getValue(); REFS.recycle(ref); return pointer; } public static Pointer parameterStoreCreate(String type) { PointerByReference ref = REFS.acquire(); checkCall(LIB.MXKVStoreCreate(type, ref)); Pointer pointer = ref.getValue(); REFS.recycle(ref); return pointer; } public static void parameterStoreClose(Pointer handle) { checkCall(LIB.MXKVStoreFree(handle)); } public static void parameterStoreInit(Pointer handle, int num, String[] keys, NDList vals) { checkNDArray(handle, "initialize the parameter store with"); PointerArray pa = toPointerArray(vals); checkCall(LIB.MXKVStoreInitEx(handle, num, keys, pa)); pa.recycle(); } public static void parameterStorePush( Pointer handle, int num, String[] keys, NDList vals, int priority) { checkNDArray(handle, "push to the parameter store with"); PointerArray pa = toPointerArray(vals); checkCall(LIB.MXKVStorePushEx(handle, num, keys, pa, priority)); pa.recycle(); } public static void parameterStorePull( Pointer handle, int num, int[] keys, NDList vals, int priority) { checkNDArray(handle, "pull from the parameter store with"); PointerArray pa = toPointerArray(vals); checkCall(LIB.MXKVStorePull(handle, num, keys, pa, priority)); pa.recycle(); } public static void parameterStorePull( Pointer handle, int num, String[] keys, NDList vals, int priority) { checkNDArray(handle, "pull from the parameter store with"); PointerArray pa = toPointerArray(vals); checkCall(LIB.MXKVStorePullEx(handle, num, keys, pa, priority)); pa.recycle(); } public static void parameterStorePushPull( Pointer handle, int inputNum, String[] inputKeys, int outputNum, String[] outputKey, NDList inputs, NDList outputs, int priority) { checkNDArray(handle, "push from the parameter store with"); PointerArray inputHandles = toPointerArray(inputs); PointerArray outputHandles = toPointerArray(outputs); checkCall( LIB.MXKVStorePushPullEx( handle, inputNum, inputKeys, outputNum, outputKey, inputHandles, outputHandles, priority)); inputHandles.recycle(); outputHandles.recycle(); } public static void parameterStoreSetUpdater( Pointer handle, MxnetLibrary.MXKVStoreUpdater updater, MxnetLibrary.MXKVStoreStrUpdater stringUpdater, Pointer updaterHandle) { checkCall(LIB.MXKVStoreSetUpdaterEx(handle, updater, stringUpdater, updaterHandle)); } public static void parameterStoreSetUpdater( Pointer handle, MxnetLibrary.MXKVStoreUpdater updater, Pointer updaterHandle) { checkCall(LIB.MXKVStoreSetUpdater(handle, updater, updaterHandle)); } /* int MXInitPSEnv(int num_vars, String keys[], String vals[]); int MXKVStoreSetGradientCompression(Pointer handle, int num_params, String keys[], String vals[]); int MXKVStorePullWithSparse(Pointer handle, int num, int keys[], PointerByReference vals, int priority, byte ignore_sparse); int MXKVStorePullWithSparseEx(Pointer handle, int num, String keys[], PointerByReference vals, int priority, byte ignore_sparse); int MXKVStorePullRowSparse(Pointer handle, int num, int keys[], PointerByReference vals, PointerByReference row_ids, int priority); int MXKVStorePullRowSparseEx(Pointer handle, int num, String keys[], PointerByReference vals, PointerByReference row_ids, int priority); int MXKVStoreGetType(Pointer handle, String type[]); int MXKVStoreGetRank(Pointer handle, IntBuffer ret); int MXKVStoreGetGroupSize(Pointer handle, IntBuffer ret); int MXKVStoreIsWorkerNode(IntBuffer ret); int MXKVStoreIsServerNode(IntBuffer ret); int MXKVStoreIsSchedulerNode(IntBuffer ret); int MXKVStoreBarrier(Pointer handle); int MXKVStoreSetBarrierBeforeExit(Pointer handle, int barrier_before_exit); int MXKVStoreRunServer(Pointer handle, MxnetLibrary.MXKVStoreServerController controller, Pointer controller_handle); int MXKVStoreSendCommmandToServers(Pointer handle, int cmd_id, String cmd_body); int MXKVStoreGetNumDeadNode(Pointer handle, int node_id, IntBuffer number, int timeout_sec); */ /* int MXImperativeInvokeEx(Pointer creator, int num_inputs, PointerByReference inputs, IntBuffer num_outputs, PointerByReference outputs, int num_params, String param_keys[], String param_vals[], PointerByReference out_stypes); int MXNDArraySyncCopyFromCPU(Pointer handle, Pointer data, NativeSize size); int MXNDArraySyncCopyFromNDArray(Pointer handle_dst, Pointer handle_src, int i); int MXNDArraySyncCheckFormat(Pointer handle, byte full_check); int MXNDArrayReshape(Pointer handle, int ndim, IntBuffer dims, PointerByReference out); int MXNDArrayReshape64(Pointer handle, int ndim, LongBuffer dims, byte reverse, PointerByReference out); int MXNDArrayGetData(Pointer handle, PointerByReference out_pdata); int MXNDArrayToDLPack(Pointer handle, PointerByReference out_dlpack); int MXNDArrayFromDLPack(Pointer dlpack, PointerByReference out_handle); int MXNDArrayCallDLPackDeleter(Pointer dlpack); int MXNDArrayGetDType(Pointer handle, IntBuffer out_dtype); int MXNDArrayGetAuxType(Pointer handle, int i, IntBuffer out_type); int MXNDArrayGetAuxNDArray(Pointer handle, int i, PointerByReference out); int MXNDArrayGetDataNDArray(Pointer handle, PointerByReference out); int MXNDArrayGetContext(Pointer handle, IntBuffer out_dev_type, IntBuffer out_dev_id); */ public static Pointer detachGradient(Pointer handle) { PointerByReference ref = REFS.acquire(); checkCall(LIB.MXNDArrayDetach(handle, ref)); Pointer pointer = ref.getValue(); REFS.recycle(ref); return pointer; } /* int MXNDArraySetGradState(Pointer handle, int state); int MXNDArrayGetGradState(Pointer handle, IntBuffer out); int MXListFunctions(IntBuffer out_size, PointerByReference out_array); int MXAutogradComputeGradient(int num_output, PointerByReference output_handles); int MXAutogradGetSymbol(Pointer handle, PointerByReference out); int MXCreateCachedOp(Pointer handle, PointerByReference out); int MXCreateCachedOpEx(Pointer handle, int num_flags, String keys[], String vals[], PointerByReference out); int MXFreeCachedOp(Pointer handle); int MXInvokeCachedOp(Pointer handle, int num_inputs, PointerByReference inputs, IntBuffer num_outputs, PointerByReference outputs); int MXInvokeCachedOpEx(Pointer handle, int num_inputs, PointerByReference inputs, IntBuffer num_outputs, PointerByReference outputs, PointerByReference out_stypes); int MXListAllOpNames(IntBuffer out_size, PointerByReference out_array); */ ///////////////////////////////// // MXNet Symbols ///////////////////////////////// public static Pointer getSymbolOutput(Pointer symbol, int index) { PointerByReference ref = REFS.acquire(); checkCall(LIB.MXSymbolGetOutput(symbol, index, ref)); Pointer pointer = ref.getValue(); REFS.recycle(ref); return pointer; } public static String[] listSymbolOutputs(Pointer symbol) { IntBuffer size = IntBuffer.allocate(1); PointerByReference ref = REFS.acquire(); checkCall(LIB.MXSymbolListOutputs(symbol, size, ref)); String[] ret = toStringArray(ref, size.get()); REFS.recycle(ref); return ret; } /* Need tests public static String symbolToJson(Pointer symbol) { String[] out = new String[1]; checkCall(LIB.MXSymbolSaveToJSON(symbol, out)); return out[0]; } */ public static void freeSymbol(Pointer symbol) { checkCall(LIB.MXSymbolFree(symbol)); } /* Need tests public static void saveSymbol(Pointer symbol, String path) { checkCall(LIB.MXSymbolSaveToFile(symbol, path)); } public static Pointer copySymbol(Pointer symbol) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXSymbolCopy(symbol, ref)); return ref.getValue(); } public static String getSymbolDebugString(Pointer symbol) { String[] out = new String[1]; checkCall(LIB.MXSymbolPrint(symbol, out)); return out[0]; } public static String getSymbolName(Pointer symbol) { String[] out = new String[1]; IntBuffer success = IntBuffer.allocate(1); checkCall(LIB.MXSymbolGetName(symbol, out, success)); if (success.get() == 1) { return out[0]; } return null; } public static String getSymbolAttr(Pointer symbol, String key) { String[] out = new String[1]; IntBuffer success = IntBuffer.allocate(1); checkCall(LIB.MXSymbolGetAttr(symbol, key, out, success)); if (success.get() == 1) { return out[0]; } return null; } public static void setSymbolAttr(Pointer symbol, String key, String value) { checkCall(LIB.MXSymbolSetAttr(symbol, key, value)); } public static PairList<String, String> listSymbolAttr(Pointer symbol) { IntBuffer size = IntBuffer.allocate(1); PointerByReference ref = new PointerByReference(); checkCall(LIB.MXSymbolListAttr(symbol, size, ref)); return toPairList(ref, size.get()); } public static PairList<String, String> listSymbolAttrShallow(Pointer symbol) { IntBuffer size = IntBuffer.allocate(1); PointerByReference ref = new PointerByReference(); checkCall(LIB.MXSymbolListAttrShallow(symbol, size, ref)); return toPairList(ref, size.get()); } */ public static String[] listSymbolNames(Pointer symbol) { IntBuffer size = IntBuffer.allocate(1); PointerByReference ref = REFS.acquire(); checkCall(LIB.NNSymbolListInputNames(symbol, 0, size, ref)); String[] ret = toStringArray(ref, size.get()); REFS.recycle(ref); return ret; } public static String[] listSymbolArguments(Pointer symbol) { IntBuffer size = IntBuffer.allocate(1); PointerByReference ref = REFS.acquire(); checkCall(LIB.MXSymbolListArguments(symbol, size, ref)); String[] ret = toStringArray(ref, size.get()); REFS.recycle(ref); return ret; } public static String[] listSymbolAuxiliaryStates(Pointer symbol) { IntBuffer size = IntBuffer.allocate(1); PointerByReference ref = REFS.acquire(); checkCall(LIB.MXSymbolListAuxiliaryStates(symbol, size, ref)); String[] ret = toStringArray(ref, size.get()); REFS.recycle(ref); return ret; } public static Pointer getSymbolInternals(Pointer symbol) { PointerByReference ref = REFS.acquire(); checkCall(LIB.MXSymbolGetInternals(symbol, ref)); Pointer pointer = ref.getValue(); REFS.recycle(ref); return pointer; } /* Need tests public static String[] listSymbolArguments(Pointer symbol) { IntBuffer size = IntBuffer.allocate(1); PointerByReference ref = new PointerByReference(); checkCall(LIB.MXSymbolListArguments(symbol, size, ref)); return toStringArray(ref, size.get()); } public static int getSymbolNumOutputs(Pointer symbol) { IntBuffer size = IntBuffer.allocate(1); checkCall(LIB.MXSymbolGetNumOutputs(symbol, size)); return size.get(); } public static Pointer getSymbolInternals(Pointer symbol) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXSymbolGetInternals(symbol, ref)); return ref.getValue(); } public static String getSymbolChildren(Pointer symbol) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXSymbolGetChildren(symbol, ref)); return ref.getValue().getString(0, StandardCharsets.UTF_8.name()); } public static String[] listSymbolAuxiliaryStates(Pointer symbol) { IntBuffer size = IntBuffer.allocate(1); PointerByReference ref = new PointerByReference(); checkCall(LIB.MXSymbolListAuxiliaryStates(symbol, size, ref)); return toStringArray(ref, size.get()); } public static Pointer[] listAtomicSymbolCreators() { IntBuffer outSize = IntBuffer.allocate(1); PointerByReference ref = new PointerByReference(); checkCall(LIB.MXSymbolListAtomicSymbolCreators(outSize, ref)); int size = outSize.get(); return ref.getValue().getPointerArray(0, size); } public static String getAtomicSymbolName(Pointer symbol) { String[] ret = new String[1]; checkCall(LIB.MXSymbolGetAtomicSymbolName(symbol, ret)); return ret[0]; } public static String getInputSymbols(Pointer symbol) { IntBuffer size = IntBuffer.allocate(1); PointerByReference ref = new PointerByReference(); checkCall(LIB.MXSymbolGetInputSymbols(symbol, ref, size)); return ref.getValue().getString(0, StandardCharsets.UTF_8.name()); } public static String cutSubgraph(Pointer symbol) { IntBuffer inputSize = IntBuffer.allocate(1); PointerByReference ref = new PointerByReference(); checkCall(LIB.MXSymbolCutSubgraph(symbol, ref, inputSize)); return ref.getValue().getString(0, StandardCharsets.UTF_8.name()); } public static Pointer createAtomicSymbol(Pointer symbol, String[] keys, String[] values) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXSymbolCreateAtomicSymbol(symbol, keys.length, keys, values, ref)); return ref.getValue(); } public static Pointer createVariable(String name) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXSymbolCreateVariable(name, ref)); return ref.getValue(); } public static Pointer createGroup(int numOfSymbols, Pointer symbols) { PointerByReference symbolsRef = new PointerByReference(symbols); PointerByReference ref = new PointerByReference(); checkCall(LIB.MXSymbolCreateGroup(numOfSymbols, symbolsRef, ref)); return ref.getValue(); } */ public static Pointer createSymbolFromFile(String path) { PointerByReference ref = REFS.acquire(); checkCall(LIB.MXSymbolCreateFromFile(path, ref)); Pointer pointer = ref.getValue(); REFS.recycle(ref); return pointer; } public static Pointer createSymbolFromString(String json) { PointerByReference ref = REFS.acquire(); checkCall(LIB.MXSymbolCreateFromJSON(json, ref)); Pointer pointer = ref.getValue(); REFS.recycle(ref); return pointer; } public static String getSymbolString(Pointer symbol) { String[] holder = new String[1]; checkCall(LIB.MXSymbolSaveToJSON(symbol, holder)); return holder[0]; } private static List<Shape> recoverShape( NativeSizeByReference size, PointerByReference nDim, PointerByReference data) { int shapeLength = (int) size.getValue().longValue(); if (shapeLength == 0) { return new ArrayList<>(); } int[] dims = nDim.getValue().getIntArray(0, shapeLength); int flattenedLength = 0; for (int dim : dims) { flattenedLength += dim; } long[] flattenedShapes = data.getValue().getPointer(0).getLongArray(0, flattenedLength); int idx = 0; List<Shape> result = new ArrayList<>(); for (int dim : dims) { long[] shape = new long[dim]; System.arraycopy(flattenedShapes, idx, shape, 0, dim); idx += dim; result.add(new Shape(shape)); } return result; } public static List<List<Shape>> inferShape(Symbol symbol, PairList<String, Shape> args) { Pointer handler = symbol.getHandle(); int numArgs = args.size(); String[] keys = args.keys().toArray(Utils.EMPTY_ARRAY); // the following two is also the representation of // CSR NDArray long[] indPtr = new long[numArgs + 1]; Shape flattened = new Shape(); indPtr[0] = 0; for (int i = 0; i < args.size(); i++) { Shape shape = args.valueAt(i); indPtr[i + 1] = shape.dimension(); flattened = flattened.addAll(shape); } long[] flattenedShapeArray = flattened.getShape(); NativeSizeByReference inShapeSize = new NativeSizeByReference(); PointerByReference inShapeNDim = REFS.acquire(); PointerByReference inShapeData = REFS.acquire(); NativeSizeByReference outShapeSize = new NativeSizeByReference(); PointerByReference outShapeNDim = REFS.acquire(); PointerByReference outShapeData = REFS.acquire(); NativeSizeByReference auxShapeSize = new NativeSizeByReference(); PointerByReference auxShapeNDim = REFS.acquire(); PointerByReference auxShapeData = REFS.acquire(); IntBuffer complete = IntBuffer.allocate(1); checkCall( LIB.MXSymbolInferShapeEx64( handler, numArgs, keys, indPtr, flattenedShapeArray, inShapeSize, inShapeNDim, inShapeData, outShapeSize, outShapeNDim, outShapeData, auxShapeSize, auxShapeNDim, auxShapeData, complete)); if (complete.get() != 0) { return Arrays.asList( recoverShape(inShapeSize, inShapeNDim, inShapeData), recoverShape(outShapeSize, outShapeNDim, outShapeData), recoverShape(auxShapeSize, auxShapeNDim, auxShapeData)); } throw new IllegalArgumentException("Cannot infer shape based on the data provided!"); } public static void loadLib(String path, boolean verbose) { int intVerbose = verbose ? 1 : 0; checkCall(LIB.MXLoadLib(path, intVerbose)); } public static Pointer optimizeFor(Symbol current, String backend, Device device) { // TODO: Support partition on parameters PointerByReference returnedSymbolHandle = REFS.acquire(); // placeHolders PointerByReference[] placeHolders = { REFS.acquire(), REFS.acquire(), REFS.acquire(), REFS.acquire(), REFS.acquire(), REFS.acquire() }; // there is no need to update parameters checkCall( LIB.MXOptimizeForBackend( current.getHandle(), backend, MxDeviceType.toDeviceType(device), returnedSymbolHandle, 0, placeHolders[0], 0, placeHolders[1], 0, Utils.EMPTY_ARRAY, Utils.EMPTY_ARRAY, IntBuffer.allocate(1), placeHolders[2], placeHolders[3], IntBuffer.allocate(1), placeHolders[4], placeHolders[5])); Pointer ptr = returnedSymbolHandle.getValue(); REFS.recycle(returnedSymbolHandle); Arrays.stream(placeHolders).forEach(REFS::recycle); return ptr; } /* Need tests public static Pointer createSymbolFromJson(String json) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXSymbolCreateFromJSON(json, ref)); return ref.getValue(); } public static Pointer compose(Pointer symbol, String name, String[] keys) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXSymbolCompose(symbol, name, keys.length, keys, ref)); return ref.getValue(); } public static Pointer grad(Pointer symbol, String name, int numWrt, String[] wrt) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXSymbolCompose(symbol, name, numWrt, wrt, ref)); return ref.getValue(); } public static Shape[] inferShape(Pointer symbol, String[] keys) { IntBuffer argIndex = IntBuffer.allocate(1); IntBuffer argShapeData = IntBuffer.allocate(1); IntBuffer inShapeSize = IntBuffer.allocate(1); PointerByReference inShapeNDim = new PointerByReference(); PointerByReference inShapeData = new PointerByReference(); IntBuffer outShapeSize = IntBuffer.allocate(1); PointerByReference outShapeNDim = new PointerByReference(); PointerByReference outShapeData = new PointerByReference(); IntBuffer auxShapeSize = IntBuffer.allocate(1); PointerByReference auxShapeNDim = new PointerByReference(); PointerByReference auxShapeData = new PointerByReference(); IntBuffer complete = IntBuffer.allocate(1); checkCall( LIB.MXSymbolInferShape( symbol, keys.length, keys, argIndex.array(), argShapeData.array(), inShapeSize, inShapeNDim, inShapeData, outShapeSize, outShapeNDim, outShapeData, auxShapeSize, auxShapeNDim, auxShapeData, complete)); if (complete.get() == 1) { Shape[] ret = new Shape[keys.length]; // TODO: add implementation return ret; // NOPMD } return null; } public static Pointer inferType(Pointer symbol, String[] keys) { int[] argTypeData = new int[1]; IntBuffer inTypeSize = IntBuffer.allocate(1); PointerByReference inTypeData = new PointerByReference(); IntBuffer outTypeSize = IntBuffer.allocate(1); PointerByReference outTypeData = new PointerByReference(); IntBuffer auxTypeSize = IntBuffer.allocate(1); PointerByReference auxTypeData = new PointerByReference(); IntBuffer complete = IntBuffer.allocate(1); checkCall( LIB.MXSymbolInferType( symbol, keys.length, keys, argTypeData, inTypeSize, inTypeData, outTypeSize, outTypeData, auxTypeSize, auxTypeData, complete)); if (complete.get() == 1) { return outTypeData.getValue(); } return null; } public static Pointer quantizeSymbol( Pointer symbol, String[] excludedSymbols, String[] offlineParams, String quantizedDType, byte calibQuantize) { PointerByReference ref = new PointerByReference(); checkCall( LIB.MXQuantizeSymbol( symbol, ref, excludedSymbols.length, excludedSymbols, offlineParams.length, offlineParams, quantizedDType, calibQuantize)); return ref.getValue(); } public static Pointer setCalibTableToQuantizedSymbol( Pointer symbol, String[] layerNames, FloatBuffer lowQuantiles, FloatBuffer highQuantiles) { PointerByReference ref = new PointerByReference(); checkCall( LIB.MXSetCalibTableToQuantizedSymbol( symbol, layerNames.length, layerNames, lowQuantiles, highQuantiles, ref)); return ref.getValue(); } public static Pointer genBackendSubgraph(Pointer symbol, String backend) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXGenBackendSubgraph(symbol, backend, ref)); return ref.getValue(); } */ ///////////////////////////////// // MXNet Executors ///////////////////////////////// /* Need tests public static void freeExecutor(Pointer executor) { checkCall(LIB.MXExecutorFree(executor)); } public static String getExecutorDebugString(Pointer executor) { String[] ret = new String[1]; checkCall(LIB.MXExecutorPrint(executor, ret)); return ret[0]; } public static void forward(Pointer executor, boolean isTrain) { checkCall(LIB.MXExecutorForward(executor, isTrain ? 1 : 0)); } public static Pointer backward(Pointer executor, int length) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXExecutorBackward(executor, length, ref)); return ref.getValue(); } public static Pointer backwardEx(Pointer executor, int length, boolean isTrain) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXExecutorBackwardEx(executor, length, ref, isTrain ? 1 : 0)); return ref.getValue(); } public static NDArray[] getExecutorOutputs(MxNDManager manager, Pointer executor) { IntBuffer outSize = IntBuffer.allocate(1); PointerByReference ref = new PointerByReference(); checkCall(LIB.MXExecutorOutputs(executor, outSize, ref)); int size = outSize.get(); Pointer[] pointers = ref.getValue().getPointerArray(0, size); NDArray[] ndArrays = new NDArray[size]; for (int i = 0; i < size; ++i) { ndArrays[i] = manager.create(pointers[i]); } return ndArrays; } public static Pointer bindExecutorSimple( Symbol symbol, Device device, String[] g2cKeys, int[] g2cDeviceTypes, int[] g2cDeviceIds, String[] argParams, String[] argParamGradReqs, String[] inputArgNames, IntBuffer inputShapeData, IntBuffer inputShapeIdx, String[] inputDataTypeNames, int[] inputDataTypes, String[] inputStorageTypeNames, int[] inputStorageTypes, String[] sharedArgParams, IntBuffer sharedBufferLen, String[] sharedBufferNames, PointerByReference sharedBufferHandles, PointerByReference updatedSharedBufferNames, PointerByReference updatedSharedBufferHandles, IntBuffer numInArgs, PointerByReference inArgs, PointerByReference argGrads, IntBuffer numAuxStates, PointerByReference auxStates) { int deviceId = device.getDeviceId(); int deviceType = DeviceType.toDeviceType(device); PointerByReference ref = new PointerByReference(); checkCall( LIB.MXExecutorSimpleBind( symbol.getHandle(), deviceType, deviceId, g2cKeys == null ? 0 : g2cKeys.length, g2cKeys, g2cDeviceTypes, g2cDeviceIds, argParams.length, argParams, argParamGradReqs, inputArgNames.length, inputArgNames, inputShapeData.array(), inputShapeIdx.array(), inputDataTypeNames.length, inputDataTypeNames, inputDataTypes, inputStorageTypeNames == null ? 0 : inputStorageTypeNames.length, inputStorageTypeNames, inputStorageTypes, sharedArgParams.length, sharedArgParams, sharedBufferLen, sharedBufferNames, sharedBufferHandles, updatedSharedBufferNames, updatedSharedBufferHandles, numInArgs, inArgs, argGrads, numAuxStates, auxStates, null, ref)); return ref.getValue(); } public static Pointer bindExecutor( Pointer executor, Device device, int len, int auxStatesLen) { int deviceId = device.getDeviceId(); int deviceType = DeviceType.toDeviceType(device); PointerByReference inArgs = new PointerByReference(); PointerByReference argGradStore = new PointerByReference(); IntBuffer gradReqType = IntBuffer.allocate(1); PointerByReference auxStates = new PointerByReference(); PointerByReference ref = new PointerByReference(); checkCall( LIB.MXExecutorBind( executor, deviceType, deviceId, len, inArgs, argGradStore, gradReqType, auxStatesLen, auxStates, ref)); return ref.getValue(); } public static Pointer bindExecutorX( Pointer executor, Device device, int len, int auxStatesLen, String[] keys, int[] deviceTypes, int[] deviceIds) { int deviceId = device.getDeviceId(); int deviceType = DeviceType.toDeviceType(device); PointerByReference inArgs = new PointerByReference(); PointerByReference argGradStore = new PointerByReference(); IntBuffer gradReqType = IntBuffer.allocate(1); PointerByReference auxStates = new PointerByReference(); PointerByReference ref = new PointerByReference(); checkCall( LIB.MXExecutorBindX( executor, deviceType, deviceId, keys.length, keys, deviceTypes, deviceIds, len, inArgs, argGradStore, gradReqType, auxStatesLen, auxStates, ref)); return ref.getValue(); } public static Pointer bindExecutorEX( Pointer executor, Device device, int len, int auxStatesLen, String[] keys, int[] deviceTypes, int[] deviceIds, Pointer sharedExecutor) { int deviceId = device.getDeviceId(); int deviceType = DeviceType.toDeviceType(device); PointerByReference inArgs = new PointerByReference(); PointerByReference argGradStore = new PointerByReference(); IntBuffer gradReqType = IntBuffer.allocate(1); PointerByReference auxStates = new PointerByReference(); PointerByReference ref = new PointerByReference(); checkCall( LIB.MXExecutorBindEX( executor, deviceType, deviceId, keys.length, keys, deviceTypes, deviceIds, len, inArgs, argGradStore, gradReqType, auxStatesLen, auxStates, sharedExecutor, ref)); return ref.getValue(); } public static Pointer reshapeExecutor( boolean partialShaping, boolean allowUpSizing, Device device, String[] keys, int[] deviceTypes, int[] deviceIds, String[] providedArgShapeNames, IntBuffer providedArgShapeData, IntBuffer providedArgShapeIdx, IntBuffer numInArgs, PointerByReference inArgs, PointerByReference argGrads, IntBuffer numAuxStates, PointerByReference auxStates, Pointer sharedExecutor) { int deviceId = device.getDeviceId(); int deviceType = DeviceType.toDeviceType(device); PointerByReference ref = new PointerByReference(); checkCall( LIB.MXExecutorReshape( partialShaping ? 1 : 0, allowUpSizing ? 1 : 0, deviceType, deviceId, keys.length, keys, deviceTypes, deviceIds, providedArgShapeNames.length, providedArgShapeNames, providedArgShapeData.array(), providedArgShapeIdx.array(), numInArgs, inArgs, argGrads, numAuxStates, auxStates, sharedExecutor, ref)); return ref.getValue(); } public static Pointer getOptimizedSymbol(Pointer executor) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXExecutorGetOptimizedSymbol(executor, ref)); return ref.getValue(); } public static void setMonitorCallback( Pointer executor, MxnetLibrary.ExecutorMonitorCallback callback, Pointer callbackHandle) { checkCall(LIB.MXExecutorSetMonitorCallback(executor, callback, callbackHandle)); } */ ///////////////////////////////// // MXNet Executors ///////////////////////////////// /* public static Pointer[] listDataIters() { IntBuffer outSize = IntBuffer.allocate(1); PointerByReference ref = new PointerByReference(); checkCall(LIB.MXListDataIters(outSize, ref)); return ref.getValue().getPointerArray(0, outSize.get()); } public static Pointer createIter(Pointer iter, String[] keys, String[] values) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXDataIterCreateIter(iter, keys.length, keys, values, ref)); return ref.getValue(); } public static String getIterInfo(Pointer iter) { String[] name = new String[1]; String[] description = new String[1]; IntBuffer numArgs = IntBuffer.allocate(1); PointerByReference argNames = new PointerByReference(); PointerByReference argTypes = new PointerByReference(); PointerByReference argDesc = new PointerByReference(); checkCall( LIB.MXDataIterGetIterInfo( iter, name, description, numArgs, argNames, argTypes, argDesc)); return name[0]; } public static void freeDataIter(Pointer iter) { checkCall(LIB.MXDataIterFree(iter)); } public static int next(Pointer iter) { IntBuffer ret = IntBuffer.allocate(1); checkCall(LIB.MXDataIterNext(iter, ret)); return ret.get(); } public static void beforeFirst(Pointer iter) { checkCall(LIB.MXDataIterBeforeFirst(iter)); } public static Pointer getData(Pointer iter) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXDataIterGetData(iter, ref)); return ref.getValue(); } public static Pointer getIndex(Pointer iter) { LongBuffer outSize = LongBuffer.wrap(new long[1]); PointerByReference ref = new PointerByReference(); checkCall(LIB.MXDataIterGetIndex(iter, ref, outSize)); return ref.getValue(); } public static int getPadNum(Pointer iter) { IntBuffer outSize = IntBuffer.allocate(1); checkCall(LIB.MXDataIterGetPadNum(iter, outSize)); return outSize.get(); } public static String getDataIterLabel(Pointer iter) { PointerByReference ref = new PointerByReference(); checkCall(LIB.MXDataIterGetLabel(iter, ref)); return ref.getValue().getString(0, StandardCharsets.UTF_8.name()); } */ /* int MXRecordIOWriterCreate(String uri, PointerByReference out); int MXRecordIOWriterFree(Pointer handle); int MXRecordIOWriterWriteRecord(Pointer handle, String buf, NativeSize size); int MXRecordIOWriterTell(Pointer handle, NativeSizeByReference pos); int MXRecordIOReaderCreate(String uri, PointerByReference out); int MXRecordIOReaderFree(Pointer handle); int MXRecordIOReaderReadRecord(Pointer handle, String buf[], NativeSizeByReference size); int MXRecordIOReaderSeek(Pointer handle, NativeSize pos); int MXRecordIOReaderTell(Pointer handle, NativeSizeByReference pos); int MXRtcCreate(ByteBuffer name, int num_input, int num_output, PointerByReference input_names, PointerByReference output_names, PointerByReference inputs, PointerByReference outputs, ByteBuffer kernel, PointerByReference out); int MXRtcPush(Pointer handle, int num_input, int num_output, PointerByReference inputs, PointerByReference outputs, int gridDimX, int gridDimY, int gridDimZ, int blockDimX, int blockDimY, int blockDimZ); int MXRtcFree(Pointer handle); int MXCustomOpRegister(String op_type, MxnetLibrary.CustomOpPropCreator creator); int MXCustomFunctionRecord(int num_inputs, PointerByReference inputs, int num_outputs, PointerByReference outputs, MXCallbackList callbacks); int MXRtcCudaModuleCreate(String source, int num_options, String options[], int num_exports, String exports[], PointerByReference out); int MXRtcCudaModuleFree(Pointer handle); int MXRtcCudaKernelCreate(Pointer handle, String name, int num_args, IntBuffer is_ndarray, IntBuffer is_const, IntBuffer arg_types, PointerByReference out); int MXRtcCudaKernelFree(Pointer handle); int MXRtcCudaKernelCall(Pointer handle, int dev_id, PointerByReference args, int grid_dim_x, int grid_dim_y, int grid_dim_z, int block_dim_x, int block_dim_y, int block_dim_z, int shared_mem); int MXNDArrayGetSharedMemHandle(Pointer handle, IntBuffer shared_pid, IntBuffer shared_id); int MXNDArrayCreateFromSharedMem(int shared_pid, int shared_id, IntBuffer shape, int ndim, int dtype, PointerByReference out); */ ////////////////////////////////// // cached Op ////////////////////////////////// /** * Creates cached op flags. * * <p>data_indices : [0, 2, 4] Used to label input location, param_indices : [1, 3] Used to * label param location * * @param block the {@link MxSymbolBlock} that loaded in the backend * @param manager the NDManager used to create NDArray * @param training true if CachedOp is created to forward in traning otherwise, false * @return a CachedOp for inference */ public static CachedOp createCachedOp( MxSymbolBlock block, MxNDManager manager, boolean training) { Symbol symbol = block.getSymbol(); List<Parameter> parameters = block.getAllParameters(); // record data index in all inputs PairList<String, Integer> dataIndices = new PairList<>(); // record parameter index in all inputs List<Integer> paramIndices = new ArrayList<>(); int index = 0; for (Parameter parameter : parameters) { // We assume uninitialized parameters are data inputs if (parameter.isInitialized()) { paramIndices.add(index); } else { dataIndices.add(parameter.getName(), index); } ++index; } // Creating CachedOp Pointer symbolHandle = symbol.getHandle(); PointerByReference ref = REFS.acquire(); // static_alloc and static_shape are enabled by default String staticAlloc = "1"; String staticShape = "1"; if (!Boolean.parseBoolean(System.getProperty("ai.djl.mxnet.static_alloc", "true"))) { staticAlloc = "0"; } if (!Boolean.parseBoolean(System.getProperty("ai.djl.mxnet.static_shape", "true"))) { staticShape = "0"; } String[] keys = {"data_indices", "param_indices", "static_alloc", "static_shape"}; String[] values = { dataIndices.values().toString(), paramIndices.toString(), staticAlloc, staticShape }; checkCall(LIB.MXCreateCachedOpEx(symbolHandle, keys.length, keys, values, ref)); Pointer pointer = ref.getValue(); REFS.recycle(ref); return new CachedOp(pointer, manager, parameters, paramIndices, dataIndices); } public static void freeCachedOp(Pointer handle) { checkCall(LIB.MXFreeCachedOp(handle)); } public static MxNDArray[] cachedOpInvoke( MxNDManager manager, Pointer cachedOpHandle, MxNDArray[] inputs) { IntBuffer buf = IntBuffer.allocate(1); PointerArray array = toPointerArray(inputs); PointerByReference ref = REFS.acquire(); PointerByReference outSTypeRef = REFS.acquire(); checkCall( LIB.MXInvokeCachedOpEx( cachedOpHandle, inputs.length, array, buf, ref, outSTypeRef)); int numOutputs = buf.get(); Pointer[] ptrArray = ref.getValue().getPointerArray(0, numOutputs); int[] sTypes = outSTypeRef.getValue().getIntArray(0, numOutputs); MxNDArray[] output = new MxNDArray[numOutputs]; for (int i = 0; i < numOutputs; i++) { if (sTypes[i] != 0) { output[i] = manager.create(ptrArray[i], SparseFormat.fromValue(sTypes[i])); } else { output[i] = manager.create(ptrArray[i]); } } REFS.recycle(ref); REFS.recycle(outSTypeRef); array.recycle(); return output; } public static void checkCall(int ret) { if (ret != 0) { throw new EngineException("MXNet engine call failed: " + getLastError()); } } private static PointerArray toPointerArray(NDList vals) { Pointer[] valPointers = new Pointer[vals.size()]; for (int i = 0; i < vals.size(); i++) { valPointers[i] = ((MxNDArray) vals.get(i)).getHandle(); } return PointerArray.of(valPointers); } private static PointerArray toPointerArray(NDArray[] vals) { if (vals == null) { return null; } Pointer[] valPointers = new Pointer[vals.length]; for (int i = 0; i < vals.length; i++) { valPointers[i] = ((MxNDArray) vals[i]).getHandle(); } return PointerArray.of(valPointers); } private static void checkNDArray(Pointer pointer, String msg) { if (pointer == null) { throw new IllegalArgumentException( "Tried to " + msg + " an MXNet NDArray that was already closed"); } } private static String getLastError() { return LIB.MXGetLastError(); } private static String[] toStringArray(PointerByReference ref, int size) { if (size == 0) { return Utils.EMPTY_ARRAY; } Pointer[] pointers = ref.getValue().getPointerArray(0, size); String[] arr = new String[size]; for (int i = 0; i < size; ++i) { arr[i] = pointers[i].getString(0, StandardCharsets.UTF_8.name()); } return arr; } /* private static PairList<String, String> toPairList(PointerByReference ref, int size) { Pointer[] pointers = ref.getValue().getPointerArray(0, size); List<String> names = new ArrayList<>(size); List<String> values = new ArrayList<>(size); for (Pointer pointer : pointers) { String[] pair = pointer.getStringArray(0, 2, StandardCharsets.UTF_8.name()); names.add(pair[0]); values.add(pair[1]); } return new PairList<>(names, values); } */ private static String getOpNamePrefix(String name) { for (String prefix : OP_NAME_PREFIX) { if (name.startsWith(prefix)) { return name.substring(prefix.length()); } } return name; } }
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/LibFeature.java
package ai.djl.mxnet.jna; import com.sun.jna.Pointer; import com.sun.jna.Structure; import java.util.Arrays; import java.util.List; public class LibFeature extends Structure { public String name; public byte enabled; public LibFeature() { } public LibFeature(Pointer peer) { super(peer); } @Override protected List<String> getFieldOrder() { return Arrays.asList("name", "enabled"); } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setEnabled(byte enabled) { this.enabled = enabled; } public byte getEnabled() { return enabled; } public static final class ByReference extends LibFeature implements Structure.ByReference {} public static final class ByValue extends LibFeature implements Structure.ByValue {} }
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/LibUtils.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.mxnet.jna; import ai.djl.util.ClassLoaderUtils; import ai.djl.util.Platform; import ai.djl.util.Utils; import com.sun.jna.Library; import com.sun.jna.Native; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; /** * Utilities for finding the MXNet Engine binary on the System. * * <p>The Engine will be searched for in a variety of locations in the following order: * * <ol> * <li>In the path specified by the MXNET_LIBRARY_PATH environment variable * <li>In a jar file location in the classpath. These jars can be created with the mxnet-native * module. * <li>In the python3 path. These can be installed using pip. * <li>In the python path. These can be installed using pip. * </ol> */ @SuppressWarnings("MissingJavadocMethod") public final class LibUtils { private static final Logger logger = LoggerFactory.getLogger(LibUtils.class); private static final String LIB_NAME = "mxnet"; private static final Pattern VERSION_PATTERN = Pattern.compile("(\\d+\\.\\d+\\.\\d+(-[a-z]+)?)(-SNAPSHOT)?(-\\d+)?"); private LibUtils() {} public static MxnetLibrary loadLibrary() { String libName = getLibName(); logger.debug("Loading mxnet library from: {}", libName); if (System.getProperty("os.name").startsWith("Linux")) { Map<String, Integer> options = new ConcurrentHashMap<>(); int rtld = 1; // Linux RTLD lazy + local options.put(Library.OPTION_OPEN_FLAGS, rtld); return Native.load(libName, MxnetLibrary.class, options); } return Native.load(libName, MxnetLibrary.class); } public static String getLibName() { String libName = LibUtils.findOverrideLibrary(); if (libName == null) { libName = LibUtils.findLibraryInClasspath(); } return libName; } private static String findOverrideLibrary() { String libPath = Utils.getEnvOrSystemProperty("MXNET_LIBRARY_PATH"); if (libPath != null) { String libName = findLibraryInPath(libPath); if (libName != null) { return libName; } } libPath = System.getProperty("java.library.path"); if (libPath != null) { return findLibraryInPath(libPath); } return null; } private static synchronized String findLibraryInClasspath() { String overrideVersion = Utils.getEnvOrSystemProperty("MXNET_VERSION"); if (overrideVersion != null) { Platform platform = Platform.detectPlatform("mxnet", overrideVersion); return downloadMxnet(platform); } Platform platform = Platform.detectPlatform("mxnet"); if (platform.isPlaceholder()) { return downloadMxnet(platform); } return loadLibraryFromClasspath(platform); } private static String loadLibraryFromClasspath(Platform platform) { Path tmp = null; try { String libName = System.mapLibraryName(LIB_NAME); Path cacheFolder = Utils.getEngineCacheDir("mxnet"); String version = platform.getVersion(); String flavor = platform.getFlavor(); if ("cpu".equals(flavor)) { flavor = "mkl"; } else if (!flavor.endsWith("mkl")) { flavor += "mkl"; // NOPMD } String classifier = platform.getClassifier(); Path dir = cacheFolder.resolve(version + '-' + flavor + '-' + classifier); logger.debug("Using cache dir: {}", dir); Path path = dir.resolve(libName); if (Files.exists(path)) { return path.toAbsolutePath().toString(); } Files.createDirectories(cacheFolder); tmp = Files.createTempDirectory(cacheFolder, "tmp"); for (String file : platform.getLibraries()) { String libPath = "native/lib/" + file; logger.info("Extracting {} to cache ...", libPath); try (InputStream is = ClassLoaderUtils.getResourceAsStream(libPath)) { Files.copy(is, tmp.resolve(file), StandardCopyOption.REPLACE_EXISTING); } } Utils.moveQuietly(tmp, dir); return path.toAbsolutePath().toString(); } catch (IOException e) { throw new IllegalStateException("Failed to extract MXNet native library", e); } finally { if (tmp != null) { Utils.deleteQuietly(tmp); } } } private static String findLibraryInPath(String libPath) { String[] paths = libPath.split(File.pathSeparator); List<String> mappedLibNames; if (com.sun.jna.Platform.isMac()) { mappedLibNames = Arrays.asList("libmxnet.dylib", "libmxnet.jnilib", "libmxnet.so"); } else { mappedLibNames = Collections.singletonList(System.mapLibraryName(LIB_NAME)); } for (String path : paths) { File p = new File(path); if (!p.exists()) { continue; } for (String name : mappedLibNames) { if (p.isFile() && p.getName().endsWith(name)) { return p.getAbsolutePath(); } File file = new File(path, name); if (file.exists() && file.isFile()) { return file.getAbsolutePath(); } } } return null; } private static String downloadMxnet(Platform platform) { String version = platform.getVersion(); String flavor = platform.getFlavor(); if ("cpu".equals(flavor)) { flavor = "mkl"; } else if (!flavor.endsWith("mkl")) { flavor += "mkl"; // NOPMD } String classifier = platform.getClassifier(); String cudaArch = platform.getCudaArch(); String os = platform.getOsPrefix(); String libName = System.mapLibraryName(LIB_NAME); Path cacheFolder = Utils.getEngineCacheDir("mxnet"); Path dir = cacheFolder.resolve(version + '-' + flavor + '-' + classifier); Path path = dir.resolve(libName); if (Files.exists(path)) { logger.debug("Using cache dir: {}", dir); return path.toAbsolutePath().toString(); } Matcher matcher = VERSION_PATTERN.matcher(version); if (!matcher.matches()) { throw new IllegalArgumentException("Unexpected version: " + version); } Path tmp = null; String link = "https://publish.djl.ai/mxnet-" + matcher.group(1); try (InputStream is = Utils.openUrl(link + "/files.txt")) { Files.createDirectories(cacheFolder); tmp = Files.createTempDirectory(cacheFolder, "tmp"); List<String> lines = Utils.readLines(is); if (cudaArch != null) { // has CUDA if ("win".equals(os)) { if (!lines.contains(os + '/' + flavor + "/mxnet_" + cudaArch + ".dll.gz")) { logger.warn( "No matching cuda flavor for {} found: {}/sm_{}.", os, flavor, cudaArch); // fallback to CPU flavor = "mkl"; } } else if ("linux".equals(os)) { // MXNet must use exactly matched cuda minor version if (!lines.contains(os + '/' + flavor + "/libmxnet.so.gz") || !supported(platform)) { logger.warn( "No matching cuda flavor for {} found: {}/sm_{}.", os, flavor, cudaArch); // fallback to CPU flavor = "mkl"; } } else { throw new AssertionError("Unsupported GPU operating system: " + os); } // check again in case fallback to cpu or different cuda minor version dir = cacheFolder.resolve(version + '-' + flavor + '-' + classifier); path = dir.resolve(libName); if (Files.exists(path)) { return path.toAbsolutePath().toString(); } } logger.debug("Using cache dir: {}", dir); boolean found = false; for (String line : lines) { if (line.startsWith(os + "/common/") || line.startsWith(os + '/' + flavor + '/')) { found = true; URL url = new URL(link + '/' + line); String fileName = line.substring(line.lastIndexOf('/') + 1, line.length() - 3); if ("win".equals(os)) { if ("libmxnet.dll".equals(fileName)) { fileName = "mxnet.dll"; } else if (fileName.startsWith("mxnet_")) { if (!("mxnet_" + cudaArch + ".dll").equals(fileName)) { continue; } fileName = "mxnet.dll"; // split CUDA build } } logger.info("Downloading {} ...", fileName); try (InputStream fis = new GZIPInputStream(Utils.openUrl(url))) { Files.copy(fis, tmp.resolve(fileName), StandardCopyOption.REPLACE_EXISTING); } } } if (!found) { throw new IllegalStateException( "No MXNet native library matches your operating system: " + platform); } Utils.moveQuietly(tmp, dir); return path.toAbsolutePath().toString(); } catch (IOException e) { throw new IllegalStateException("Failed to download MXNet native library", e); } finally { if (tmp != null) { Utils.deleteQuietly(tmp); } } } private static boolean supported(Platform platform) { // mxnet-native-cu102mkl:1.8.0: 3.0, 5.0, 6.0, 7.0, 7.5 // mxnet-native-cu110mkl:1.8.0: 5.0, 6.0, 7.0, 8.0 // mxnet-native-cu112mkl:1.9.1: 5.0, 6.0, 7.0, 7.5, 8.0, 8.6 String version = platform.getVersion(); if (version.startsWith("1.8.") || version.startsWith("1.9.")) { String flavor = platform.getFlavor(); String cudaArch = platform.getCudaArch(); if (flavor.startsWith("cu11")) { if (version.startsWith("1.8.")) { return Arrays.asList("50", "60", "70", "80").contains(cudaArch); } return Arrays.asList("50", "60", "70", "75", "80", "86").contains(cudaArch); } else if (flavor.startsWith("cu10")) { return Arrays.asList("30", "50", "60", "70", "75").contains(cudaArch); } } return true; } }
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/MXCallbackList.java
package ai.djl.mxnet.jna; import com.sun.jna.Callback; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.ptr.PointerByReference; import java.util.Arrays; import java.util.List; public class MXCallbackList extends Structure { public int num_callbacks; public CallbacksCallback callbacks; public PointerByReference contexts; public MXCallbackList() { } public MXCallbackList(Pointer peer) { super(peer); } @Override protected List<String> getFieldOrder() { return Arrays.asList("num_callbacks", "callbacks", "contexts"); } public void setNumCallbacks(int num_callbacks) { this.num_callbacks = num_callbacks; } public int getNumCallbacks() { return num_callbacks; } public void setCallbacksCallback(CallbacksCallback callbacks) { this.callbacks = callbacks; } public CallbacksCallback getCallbacksCallback() { return callbacks; } public void setContexts(PointerByReference contexts) { this.contexts = contexts; } public PointerByReference getContexts() { return contexts; } public static final class ByReference extends MXCallbackList implements Structure.ByReference {} public static final class ByValue extends MXCallbackList implements Structure.ByValue {} public interface CallbacksCallback extends Callback { int apply(); } }
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/MxnetLibrary.java
package ai.djl.mxnet.jna; import com.sun.jna.Callback; import com.sun.jna.Library; import com.sun.jna.Pointer; import com.sun.jna.ptr.PointerByReference; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; public interface MxnetLibrary extends Library { enum CustomOpCallbacks { kCustomOpDelete, kCustomOpForward, kCustomOpBackward } enum CustomOpPropCallbacks { kCustomOpPropDelete, kCustomOpPropListArguments, kCustomOpPropListOutputs, kCustomOpPropListAuxiliaryStates, kCustomOpPropInferShape, kCustomOpPropDeclareBackwardDependency, kCustomOpPropCreateOperator, kCustomOpPropInferType, kCustomOpPropInferStorageType, kCustomOpPropBackwardInferStorageType } enum CustomFunctionCallbacks { kCustomFunctionBackward, kCustomFunctionDelete } interface EngineAsyncFunc extends Callback { void apply(Pointer arg1, Pointer arg2, Pointer arg3); } interface EngineSyncFunc extends Callback { void apply(Pointer arg1, Pointer arg2); } interface EngineFuncParamDeleter extends Callback { void apply(Pointer arg1); } interface ExecutorMonitorCallback extends Callback { void apply(String arg1, Pointer arg2, Pointer arg3); } interface CachedOpMonitorCallback extends Callback { void apply(String arg1, String arg2, Pointer arg3); } interface MXGenericCallback extends Callback { int apply(); } interface CustomOpFBFunc extends Callback { int apply(int arg1, PointerByReference arg2, IntBuffer arg3, int[] arg4, int arg5, Pointer arg6); } interface CustomOpDelFunc extends Callback { int apply(Pointer arg1); } interface CustomOpListFunc extends Callback { int apply(PointerByReference arg1, Pointer arg2); } interface CustomOpInferShapeFunc extends Callback { int apply(int arg1, IntBuffer arg2, PointerByReference arg3, Pointer arg4); } interface CustomOpInferStorageTypeFunc extends Callback { int apply(int arg1, IntBuffer arg2, Pointer arg3); } interface CustomOpBackwardInferStorageTypeFunc extends Callback { int apply(int arg1, IntBuffer arg2, IntBuffer arg3, Pointer arg4); } interface CustomOpInferTypeFunc extends Callback { int apply(int arg1, IntBuffer arg2, Pointer arg3); } interface CustomOpBwdDepFunc extends Callback { int apply(int[] arg1, int[] arg2, int[] arg3, IntBuffer arg4, PointerByReference arg5, Pointer arg6); } interface CustomOpCreateFunc extends Callback { int apply(String arg1, int arg2, PointerByReference arg3, int[] arg4, int[] arg5, MXCallbackList.ByReference arg6, Pointer arg7); } interface CustomOpPropCreator extends Callback { int apply(String arg1, int arg2, String[] arg3, String[] arg4, MXCallbackList.ByReference arg5); } interface CustomFunctionBwdFunc extends Callback { int apply(int arg1, int arg2, PointerByReference arg3, int[] arg4, int arg5, Pointer arg6); } interface CustomFunctionDelFunc extends Callback { int apply(Pointer arg1); } interface MXKVStoreUpdater extends Callback { void apply(int key, Pointer recv, Pointer local, Pointer handle); } interface MXKVStoreStrUpdater extends Callback { void apply(String key, Pointer recv, Pointer local, Pointer handle); } interface MXKVStoreServerController extends Callback { void apply(int head, String body, Pointer controller_handle); } String MXGetLastError(); int MXLoadLib(String path, int verbose); int MXLibInfoFeatures(PointerByReference libFeature, NativeSizeByReference size); int MXRandomSeed(int seed); int MXRandomSeedContext(int seed, int dev_type, int dev_id); int MXNotifyShutdown(); int MXSetProcessProfilerConfig(int num_params, String[] keys, String[] vals, Pointer kvstoreHandle); int MXSetProfilerConfig(int num_params, String[] keys, String[] vals); int MXSetProcessProfilerState(int state, int profile_process, Pointer kvStoreHandle); int MXSetProfilerState(int state); int MXDumpProcessProfile(int finished, int profile_process, Pointer kvStoreHandle); int MXDumpProfile(int finished); int MXAggregateProfileStatsPrint(String[] out_str, int reset); int MXAggregateProfileStatsPrintEx(String[] out_str, int reset, int format, int sort_by, int ascending); int MXProcessProfilePause(int paused, int profile_process, Pointer kvStoreHandle); int MXProfilePause(int paused); int MXProfileCreateDomain(String domain, PointerByReference out); int MXProfileCreateTask(Pointer domain, String task_name, PointerByReference out); int MXProfileCreateFrame(Pointer domain, String frame_name, PointerByReference out); int MXProfileCreateEvent(String event_name, PointerByReference out); int MXProfileCreateCounter(Pointer domain, String counter_name, PointerByReference out); int MXProfileDestroyHandle(Pointer frame_handle); int MXProfileDurationStart(Pointer duration_handle); int MXProfileDurationStop(Pointer duration_handle); int MXProfileSetCounter(Pointer counter_handle, long value); int MXProfileAdjustCounter(Pointer counter_handle, long value); int MXProfileSetMarker(Pointer domain, String instant_marker_name, String scope); int MXSetNumOMPThreads(int thread_num); int MXEngineSetBulkSize(int bulk_size, IntBuffer prev_bulk_size); int MXGetGPUCount(IntBuffer out); int MXGetGPUMemoryInformation(int dev, IntBuffer free_mem, IntBuffer total_mem); int MXGetGPUMemoryInformation64(int dev, LongBuffer free_mem, LongBuffer total_mem); int MXGetVersion(IntBuffer out); int MXLoadTVMOp(String libpath); int MXLoadTVMConfig(PointerByReference config); int MXNDArrayCreateNone(PointerByReference out); int MXNDArrayCreate(int[] shape, int ndim, int dev_type, int dev_id, int delay_alloc, PointerByReference out); int MXNDArrayCreateEx(int[] shape, int ndim, int dev_type, int dev_id, int delay_alloc, int dtype, PointerByReference out); int MXNDArrayCreateEx64(long[] shape, int ndim, int dev_type, int dev_id, int delay_alloc, int dtype, PointerByReference out); int MXNDArrayCreateSparseEx(int storage_type, int[] shape, int ndim, int dev_type, int dev_id, int delay_alloc, int dtype, int num_aux, IntBuffer aux_type, IntBuffer aux_ndims, int[] aux_shape, PointerByReference out); int MXNDArrayCreateSparseEx64(int storage_type, long[] shape, int ndim, int dev_type, int dev_id, int delay_alloc, int dtype, int num_aux, IntBuffer aux_type, IntBuffer aux_ndims, long[] aux_shape, PointerByReference out); int MXNDArrayLoadFromRawBytes(Pointer buf, NativeSize size, PointerByReference out); int MXNDArraySaveRawBytes(Pointer handle, NativeSizeByReference out_size, PointerByReference out_buf); int MXNDArraySave(String fname, int num_args, PointerArray args, String[] keys); int MXNDArrayLoad(String fname, IntBuffer out_size, PointerByReference out_arr, IntBuffer out_name_size, PointerByReference out_names); int MXNDArrayLoadFromBuffer(Pointer ndarray_buffer, NativeSize size, IntBuffer out_size, PointerByReference out_arr, IntBuffer out_name_size, PointerByReference out_names); int MXNDArraySyncCopyFromCPU(Pointer handle, Pointer data, NativeSize size); int MXNDArraySyncCopyToCPU(Pointer handle, Pointer data, NativeSize size); int MXNDArraySyncCopyFromNDArray(Pointer handle_dst, Pointer handle_src, int i); int MXNDArraySyncCheckFormat(Pointer handle, byte full_check); int MXNDArrayWaitToRead(Pointer handle); int MXNDArrayWaitToWrite(Pointer handle); int MXNDArrayWaitAll(); int MXNDArrayFree(Pointer handle); int MXNDArraySlice(Pointer handle, int slice_begin, int slice_end, PointerByReference out); int MXNDArraySlice64(Pointer handle, long slice_begin, long slice_end, PointerByReference out); int MXNDArrayAt(Pointer handle, int idx, PointerByReference out); int MXNDArrayAt64(Pointer handle, long idx, PointerByReference out); int MXNDArrayGetStorageType(Pointer handle, IntBuffer out_storage_type); int MXNDArrayReshape(Pointer handle, int ndim, IntBuffer dims, PointerByReference out); int MXNDArrayReshape64(Pointer handle, int ndim, LongBuffer dims, byte reverse, PointerByReference out); int MXNDArrayGetShape(Pointer handle, IntBuffer out_dim, PointerByReference out_pdata); int MXNDArrayGetShapeEx(Pointer handle, IntBuffer out_dim, PointerByReference out_pdata); int MXNDArrayGetShapeEx64(Pointer handle, IntBuffer out_dim, PointerByReference out_pdata); int MXNDArrayGetData(Pointer handle, PointerByReference out_pdata); int MXNDArrayToDLPack(Pointer handle, PointerByReference out_dlpack); int MXNDArrayFromDLPack(Pointer dlpack, PointerByReference out_handle); int MXNDArrayFromDLPackEx(Pointer dlpack, byte transient_handle, PointerByReference out_handle); int MXNDArrayCallDLPackDeleter(Pointer dlpack); int MXNDArrayGetDType(Pointer handle, IntBuffer out_dtype); int MXNDArrayGetAuxType(Pointer handle, int i, IntBuffer out_type); int MXNDArrayGetAuxType64(Pointer handle, long i, IntBuffer out_type); int MXNDArrayGetAuxNDArray(Pointer handle, int i, PointerByReference out); int MXNDArrayGetAuxNDArray64(Pointer handle, long i, PointerByReference out); int MXNDArrayGetDataNDArray(Pointer handle, PointerByReference out); int MXNDArrayGetContext(Pointer handle, IntBuffer out_dev_type, IntBuffer out_dev_id); int MXNDArrayGetGrad(Pointer handle, PointerByReference out); int MXNDArrayDetach(Pointer handle, PointerByReference out); int MXNDArraySetGradState(Pointer handle, int state); int MXNDArrayGetGradState(Pointer handle, IntBuffer out); int MXListFunctions(IntBuffer out_size, PointerByReference out_array); int MXGetFunction(String name, PointerByReference out); int MXFuncGetInfo(Pointer fun, String[] name, String[] description, IntBuffer num_args, PointerByReference arg_names, PointerByReference arg_type_infos, PointerByReference arg_descriptions, String[] return_type); int MXFuncDescribe(Pointer fun, IntBuffer num_use_vars, IntBuffer num_scalars, IntBuffer num_mutate_vars, IntBuffer type_mask); int MXFuncInvoke(Pointer fun, PointerByReference use_vars, FloatBuffer scalar_args, PointerByReference mutate_vars); int MXFuncInvokeEx(Pointer fun, PointerByReference use_vars, FloatBuffer scalar_args, PointerByReference mutate_vars, int num_params, PointerByReference param_keys, PointerByReference param_vals); int MXImperativeInvoke(Pointer creator, int num_inputs, PointerArray inputs, IntBuffer num_outputs, PointerByReference outputs, int num_params, String[] param_keys, String[] param_vals); int MXImperativeInvokeEx(Pointer creator, int num_inputs, PointerArray inputs, IntBuffer num_outputs, PointerByReference outputs, int num_params, StringArray param_keys, StringArray param_vals, PointerByReference out_stypes); int MXAutogradSetIsRecording(int is_recording, IntBuffer prev); int MXAutogradSetIsTraining(int is_training, IntBuffer prev); int MXAutogradIsRecording(ByteBuffer curr); int MXAutogradIsTraining(ByteBuffer curr); int MXIsNumpyShape(IntBuffer curr); int MXSetIsNumpyShape(int is_np_shape, IntBuffer prev); int MXAutogradMarkVariables(int num_var, PointerByReference var_handles, IntBuffer reqs_array, PointerByReference grad_handles); int MXAutogradComputeGradient(int num_output, PointerByReference output_handles); int MXAutogradBackward(int num_output, PointerArray output_handles, PointerByReference ograd_handles, int retain_graph); int MXAutogradBackwardEx(int num_output, PointerArray output_handles, PointerArray ograd_handles, int num_variables, PointerByReference var_handles, int retain_graph, int create_graph, int is_train, PointerByReference grad_handles, PointerByReference grad_stypes); int MXAutogradGetSymbol(Pointer handle, PointerByReference out); int MXCreateCachedOp(Pointer handle, PointerByReference out); int MXCreateCachedOpEx(Pointer handle, int num_flags, String[] keys, String[] vals, PointerByReference out); int MXCreateCachedOpEX(Pointer handle, int num_flags, String[] keys, String[] vals, PointerByReference out, byte thread_safe); int MXFreeCachedOp(Pointer handle); int MXInvokeCachedOp(Pointer handle, int num_inputs, Pointer inputs, IntBuffer num_outputs, PointerByReference outputs); int MXInvokeCachedOpEx(Pointer handle, int num_inputs, Pointer inputs, IntBuffer num_outputs, PointerByReference outputs, PointerByReference out_stypes); int MXCachedOpRegisterOpHook(Pointer handle, CachedOpMonitorCallback callback, byte monitor_all); int MXListAllOpNames(IntBuffer out_size, PointerByReference out_array); int MXSymbolListAtomicSymbolCreators(IntBuffer out_size, PointerByReference out_array); int MXSymbolGetAtomicSymbolName(Pointer creator, String[] name); int MXSymbolGetInputSymbols(Pointer sym, PointerByReference inputs, IntBuffer input_size); int MXSymbolCutSubgraph(Pointer sym, PointerByReference inputs, IntBuffer input_size); int MXSymbolGetAtomicSymbolInfo(Pointer creator, String[] name, String[] description, IntBuffer num_args, PointerByReference arg_names, PointerByReference arg_type_infos, PointerByReference arg_descriptions, String[] key_var_num_args, String[] return_type); int MXSymbolCreateAtomicSymbol(Pointer creator, int num_param, String[] keys, String[] vals, PointerByReference out); int MXSymbolCreateVariable(String name, PointerByReference out); int MXSymbolCreateGroup(int num_symbols, PointerByReference symbols, PointerByReference out); int MXSymbolCreateFromFile(String fname, PointerByReference out); int MXSymbolCreateFromJSON(String json, PointerByReference out); int MXSymbolRemoveAmpCast(Pointer sym_handle, PointerByReference ret_sym_handle); int MXSymbolSaveToFile(Pointer symbol, String fname); int MXSymbolSaveToJSON(Pointer symbol, String[] out_json); int MXSymbolFree(Pointer symbol); int MXSymbolCopy(Pointer symbol, PointerByReference out); int MXSymbolPrint(Pointer symbol, String[] out_str); int MXSymbolGetName(Pointer symbol, String[] out, IntBuffer success); int MXSymbolGetAttr(Pointer symbol, String key, String[] out, IntBuffer success); int MXSymbolSetAttr(Pointer symbol, String key, String value); int MXSymbolListAttr(Pointer symbol, IntBuffer out_size, PointerByReference out); int MXSymbolListAttrShallow(Pointer symbol, IntBuffer out_size, PointerByReference out); int MXSymbolListArguments(Pointer symbol, IntBuffer out_size, PointerByReference out_str_array); int MXSymbolListOutputs(Pointer symbol, IntBuffer out_size, PointerByReference out_str_array); int MXSymbolGetNumOutputs(Pointer symbol, IntBuffer output_count); int MXSymbolGetInternals(Pointer symbol, PointerByReference out); int MXSymbolGetChildren(Pointer symbol, PointerByReference out); int MXSymbolGetOutput(Pointer symbol, int index, PointerByReference out); int MXSymbolListAuxiliaryStates(Pointer symbol, IntBuffer out_size, PointerByReference out_str_array); int MXSymbolCompose(Pointer sym, String name, int num_args, String[] keys, PointerByReference args); int MXSymbolGrad(Pointer sym, int num_wrt, String[] wrt, PointerByReference out); int MXSymbolInferShape(Pointer sym, int num_args, String[] keys, int[] arg_ind_ptr, int[] arg_shape_data, IntBuffer in_shape_size, PointerByReference in_shape_ndim, PointerByReference in_shape_data, IntBuffer out_shape_size, PointerByReference out_shape_ndim, PointerByReference out_shape_data, IntBuffer aux_shape_size, PointerByReference aux_shape_ndim, PointerByReference aux_shape_data, IntBuffer complete); int MXSymbolInferShapeEx(Pointer sym, int num_args, String[] keys, int[] arg_ind_ptr, int[] arg_shape_data, IntBuffer in_shape_size, PointerByReference in_shape_ndim, PointerByReference in_shape_data, IntBuffer out_shape_size, PointerByReference out_shape_ndim, PointerByReference out_shape_data, IntBuffer aux_shape_size, PointerByReference aux_shape_ndim, PointerByReference aux_shape_data, IntBuffer complete); int MXSymbolInferShapeEx64(Pointer sym, int num_args, String[] keys, long[] arg_ind_ptr, long[] arg_shape_data, NativeSizeByReference in_shape_size, PointerByReference in_shape_ndim, PointerByReference in_shape_data, NativeSizeByReference out_shape_size, PointerByReference out_shape_ndim, PointerByReference out_shape_data, NativeSizeByReference aux_shape_size, PointerByReference aux_shape_ndim, PointerByReference aux_shape_data, IntBuffer complete); int MXSymbolInferShapePartial(Pointer sym, int num_args, String[] keys, int[] arg_ind_ptr, int[] arg_shape_data, IntBuffer in_shape_size, PointerByReference in_shape_ndim, PointerByReference in_shape_data, IntBuffer out_shape_size, PointerByReference out_shape_ndim, PointerByReference out_shape_data, IntBuffer aux_shape_size, PointerByReference aux_shape_ndim, PointerByReference aux_shape_data, IntBuffer complete); int MXSymbolInferShapePartialEx(Pointer sym, int num_args, String[] keys, int[] arg_ind_ptr, int[] arg_shape_data, IntBuffer in_shape_size, PointerByReference in_shape_ndim, PointerByReference in_shape_data, IntBuffer out_shape_size, PointerByReference out_shape_ndim, PointerByReference out_shape_data, IntBuffer aux_shape_size, PointerByReference aux_shape_ndim, PointerByReference aux_shape_data, IntBuffer complete); int MXSymbolInferShapePartialEx64(Pointer sym, int num_args, String[] keys, long[] arg_ind_ptr, long[] arg_shape_data, NativeSizeByReference in_shape_size, PointerByReference in_shape_ndim, PointerByReference in_shape_data, NativeSizeByReference out_shape_size, PointerByReference out_shape_ndim, PointerByReference out_shape_data, NativeSizeByReference aux_shape_size, PointerByReference aux_shape_ndim, PointerByReference aux_shape_data, IntBuffer complete); int MXSymbolInferType(Pointer sym, int num_args, String[] keys, int[] arg_type_data, IntBuffer in_type_size, PointerByReference in_type_data, IntBuffer out_type_size, PointerByReference out_type_data, IntBuffer aux_type_size, PointerByReference aux_type_data, IntBuffer complete); int MXSymbolInferTypePartial(Pointer sym, int num_args, String[] keys, int[] arg_type_data, IntBuffer in_type_size, PointerByReference in_type_data, IntBuffer out_type_size, PointerByReference out_type_data, IntBuffer aux_type_size, PointerByReference aux_type_data, IntBuffer complete); int MXQuantizeSymbol(Pointer sym_handle, PointerByReference ret_sym_handle, int[] dev_type, int num_excluded_sym_names, String[] excluded_sym_names, int num_excluded_op_names, String[] excluded_op_names, int num_offline, String[] offline_params, String quantized_dtype, byte calib_quantize, String quantize_mode, String quantize_granularity, IntBuffer out_num_calib_names, PointerByReference out_calib_names); int MXReducePrecisionSymbol(Pointer sym_handle, PointerByReference ret_sym_handle, int num_args, int[] arg_type_data, int num_ind_ptr, int[] ind_ptr, int[] target_dtype, int cast_optional_params, int num_target_dtype_op_names, int num_fp32_op_names, int num_widest_dtype_op_names, int num_conditional_fp32_op_names, int num_excluded_symbols, int num_model_params, String[] target_dtype_op_names, String[] fp32_op_names, String[] widest_dtype_op_names, String[] conditional_fp32_op_names, String[] excluded_symbols, String[] conditional_param_names, String[] conditional_param_vals, String[] model_param_names, String[] arg_names); int MXSetCalibTableToQuantizedSymbol(Pointer qsym_handle, int num_layers, String[] layer_names, FloatBuffer low_quantiles, FloatBuffer high_quantiles, PointerByReference ret_sym_handle); int MXGenBackendSubgraph(Pointer sym_handle, String backend, PointerByReference ret_sym_handle); int MXGenAtomicSymbolFromSymbol(Pointer sym_handle, PointerByReference ret_sym_handle); int MXOptimizeForBackend(Pointer sym_handle, String backend_name, int dev_type, PointerByReference ret_sym_handle, int args_len, PointerByReference in_args_handle, int aux_len, PointerByReference in_aux_handle, int num_options, String[] keys, String[] vals, IntBuffer new_args_cnt, PointerByReference new_args_handle, PointerByReference new_arg_names_handle, IntBuffer new_aux_cnt, PointerByReference new_aux_handle, PointerByReference new_aux_names_handle); int MXExecutorFree(Pointer handle); int MXExecutorPrint(Pointer handle, String[] out_str); int MXExecutorForward(Pointer handle, int is_train); int MXExecutorBackward(Pointer handle, int len, PointerByReference head_grads); int MXExecutorBackwardEx(Pointer handle, int len, PointerByReference head_grads, int is_train); int MXExecutorOutputs(Pointer handle, IntBuffer out_size, PointerByReference out); int MXExecutorBind(Pointer symbol_handle, int dev_type, int dev_id, int len, PointerByReference in_args, PointerByReference arg_grad_store, IntBuffer grad_req_type, int aux_states_len, PointerByReference aux_states, PointerByReference out); int MXExecutorBindX(Pointer symbol_handle, int dev_type, int dev_id, int num_map_keys, String[] map_keys, int[] map_dev_types, int[] map_dev_ids, int len, PointerByReference in_args, PointerByReference arg_grad_store, IntBuffer grad_req_type, int aux_states_len, PointerByReference aux_states, PointerByReference out); int MXExecutorBindEX(Pointer symbol_handle, int dev_type, int dev_id, int num_map_keys, String[] map_keys, int[] map_dev_types, int[] map_dev_ids, int len, PointerByReference in_args, PointerByReference arg_grad_store, IntBuffer grad_req_type, int aux_states_len, PointerByReference aux_states, Pointer shared_exec, PointerByReference out); int MXExecutorSimpleBind(Pointer symbol_handle, int dev_type, int dev_id, int num_g2c_keys, String[] g2c_keys, int[] g2c_dev_types, int[] g2c_dev_ids, int provided_grad_req_list_len, String[] provided_grad_req_names, String[] provided_grad_req_types, int num_provided_arg_shapes, String[] provided_arg_shape_names, int[] provided_arg_shape_data, int[] provided_arg_shape_idx, int num_provided_arg_dtypes, String[] provided_arg_dtype_names, int[] provided_arg_dtypes, int num_provided_arg_stypes, String[] provided_arg_stype_names, int[] provided_arg_stypes, int num_shared_arg_names, String[] shared_arg_name_list, IntBuffer shared_buffer_len, String[] shared_buffer_name_list, PointerByReference shared_buffer_handle_list, PointerByReference updated_shared_buffer_name_list, PointerByReference updated_shared_buffer_handle_list, IntBuffer num_in_args, PointerByReference in_args, PointerByReference arg_grads, IntBuffer num_aux_states, PointerByReference aux_states, Pointer shared_exec_handle, PointerByReference out); int MXExecutorSimpleBindEx(Pointer symbol_handle, int dev_type, int dev_id, int num_g2c_keys, String[] g2c_keys, int[] g2c_dev_types, int[] g2c_dev_ids, int provided_grad_req_list_len, String[] provided_grad_req_names, String[] provided_grad_req_types, int num_provided_arg_shapes, String[] provided_arg_shape_names, int[] provided_arg_shape_data, int[] provided_arg_shape_idx, int num_provided_arg_dtypes, String[] provided_arg_dtype_names, int[] provided_arg_dtypes, int num_provided_arg_stypes, String[] provided_arg_stype_names, int[] provided_arg_stypes, int num_shared_arg_names, String[] shared_arg_name_list, IntBuffer shared_buffer_len, String[] shared_buffer_name_list, PointerByReference shared_buffer_handle_list, PointerByReference updated_shared_buffer_name_list, PointerByReference updated_shared_buffer_handle_list, IntBuffer num_in_args, PointerByReference in_args, PointerByReference arg_grads, IntBuffer num_aux_states, PointerByReference aux_states, Pointer shared_exec_handle, PointerByReference out); int MXExecutorSimpleBindEx64(Pointer symbol_handle, int dev_type, int dev_id, int num_g2c_keys, String[] g2c_keys, int[] g2c_dev_types, int[] g2c_dev_ids, int provided_grad_req_list_len, String[] provided_grad_req_names, String[] provided_grad_req_types, int num_provided_arg_shapes, String[] provided_arg_shape_names, long[] provided_arg_shape_data, int[] provided_arg_shape_idx, int num_provided_arg_dtypes, String[] provided_arg_dtype_names, int[] provided_arg_dtypes, int num_provided_arg_stypes, String[] provided_arg_stype_names, int[] provided_arg_stypes, int num_shared_arg_names, String[] shared_arg_name_list, IntBuffer shared_buffer_len, String[] shared_buffer_name_list, PointerByReference shared_buffer_handle_list, PointerByReference updated_shared_buffer_name_list, PointerByReference updated_shared_buffer_handle_list, IntBuffer num_in_args, PointerByReference in_args, PointerByReference arg_grads, IntBuffer num_aux_states, PointerByReference aux_states, Pointer shared_exec_handle, PointerByReference out); int MXExecutorReshape(int partial_shaping, int allow_up_sizing, int dev_type, int dev_id, int num_map_keys, String[] map_keys, int[] map_dev_types, int[] map_dev_ids, int num_provided_arg_shapes, String[] provided_arg_shape_names, int[] provided_arg_shape_data, int[] provided_arg_shape_idx, IntBuffer num_in_args, PointerByReference in_args, PointerByReference arg_grads, IntBuffer num_aux_states, PointerByReference aux_states, Pointer shared_exec, PointerByReference out); int MXExecutorReshapeEx(int partial_shaping, int allow_up_sizing, int dev_type, int dev_id, int num_map_keys, String[] map_keys, int[] map_dev_types, int[] map_dev_ids, int num_provided_arg_shapes, String[] provided_arg_shape_names, int[] provided_arg_shape_data, int[] provided_arg_shape_idx, IntBuffer num_in_args, PointerByReference in_args, PointerByReference arg_grads, IntBuffer num_aux_states, PointerByReference aux_states, Pointer shared_exec, PointerByReference out); int MXExecutorGetOptimizedSymbol(Pointer handle, PointerByReference out); int MXExecutorSetMonitorCallback(Pointer handle, ExecutorMonitorCallback callback, Pointer callback_handle); int MXExecutorSetMonitorCallbackEX(Pointer handle, ExecutorMonitorCallback callback, Pointer callback_handle, byte monitor_all); int MXListDataIters(IntBuffer out_size, PointerByReference out_array); int MXDataIterCreateIter(Pointer handle, int num_param, String[] keys, String[] vals, PointerByReference out); int MXDataIterGetIterInfo(Pointer creator, String[] name, String[] description, IntBuffer num_args, PointerByReference arg_names, PointerByReference arg_type_infos, PointerByReference arg_descriptions); int MXDataIterFree(Pointer handle); int MXDataIterNext(Pointer handle, IntBuffer out); int MXDataIterBeforeFirst(Pointer handle); int MXDataIterGetData(Pointer handle, PointerByReference out); int MXDataIterGetIndex(Pointer handle, PointerByReference out_index, LongBuffer out_size); int MXDataIterGetPadNum(Pointer handle, IntBuffer pad); int MXDataIterGetLabel(Pointer handle, PointerByReference out); int MXInitPSEnv(int num_vars, String[] keys, String[] vals); int MXKVStoreCreate(String type, PointerByReference out); int MXKVStoreSetGradientCompression(Pointer handle, int num_params, String[] keys, String[] vals); int MXKVStoreFree(Pointer handle); int MXKVStoreInit(Pointer handle, int num, int[] keys, PointerArray vals); int MXKVStoreInitEx(Pointer handle, int num, String[] keys, PointerArray vals); int MXKVStorePush(Pointer handle, int num, int[] keys, PointerArray vals, int priority); int MXKVStorePushEx(Pointer handle, int num, String[] keys, PointerArray vals, int priority); int MXKVStorePullWithSparse(Pointer handle, int num, int[] keys, PointerByReference vals, int priority, byte ignore_sparse); int MXKVStorePullWithSparseEx(Pointer handle, int num, String[] keys, PointerByReference vals, int priority, byte ignore_sparse); int MXKVStorePull(Pointer handle, int num, int[] keys, PointerArray vals, int priority); int MXKVStorePullEx(Pointer handle, int num, String[] keys, PointerArray vals, int priority); int MXKVStorePullRowSparse(Pointer handle, int num, int[] keys, PointerByReference vals, PointerByReference row_ids, int priority); int MXKVStorePullRowSparseEx(Pointer handle, int num, String[] keys, PointerByReference vals, PointerByReference row_ids, int priority); int MXKVStoreBroadcast(Pointer handle, int vnum, int[] vkeys, int onum, int[] okeys, PointerByReference vals, PointerByReference outs, int priority); int MXKVStoreBroadcastEx(Pointer handle, int vnum, String[] vkeys, int onum, String[] okeys, PointerByReference vals, PointerByReference outs, int priority); int MXKVStorePushPull(Pointer handle, int vnum, int[] vkeys, int onum, int[] okeys, PointerByReference vals, PointerByReference outs, int priority); int MXKVStorePushPullEx(Pointer handle, int vnum, String[] vkeys, int onum, String[] okeys, PointerArray vals, PointerArray outs, int priority); int MXKVStoreSetUpdater(Pointer handle, MXKVStoreUpdater updater, Pointer updater_handle); int MXKVStoreSetUpdaterEx(Pointer handle, MXKVStoreUpdater updater, MXKVStoreStrUpdater str_updater, Pointer updater_handle); int MXKVStoreGetType(Pointer handle, String[] type); int MXKVStoreGetRank(Pointer handle, IntBuffer ret); int MXKVStoreGetGroupSize(Pointer handle, IntBuffer ret); int MXKVStoreIsWorkerNode(IntBuffer ret); int MXKVStoreIsServerNode(IntBuffer ret); int MXKVStoreIsSchedulerNode(IntBuffer ret); int MXKVStoreBarrier(Pointer handle); int MXKVStoreSetBarrierBeforeExit(Pointer handle, int barrier_before_exit); int MXKVStoreRunServer(Pointer handle, MXKVStoreServerController controller, Pointer controller_handle); int MXKVStoreSendCommmandToServers(Pointer handle, int cmd_id, String cmd_body); int MXKVStoreGetNumDeadNode(Pointer handle, int node_id, IntBuffer number, int timeout_sec); int MXRecordIOWriterCreate(String uri, PointerByReference out); int MXRecordIOWriterFree(Pointer handle); int MXRecordIOWriterWriteRecord(Pointer handle, String buf, NativeSize size); int MXRecordIOWriterTell(Pointer handle, NativeSizeByReference pos); int MXRecordIOReaderCreate(String uri, PointerByReference out); int MXRecordIOReaderFree(Pointer handle); int MXRecordIOReaderReadRecord(Pointer handle, String buf, NativeSizeByReference size); int MXRecordIOReaderSeek(Pointer handle, NativeSize pos); int MXRecordIOReaderTell(Pointer handle, NativeSizeByReference pos); int MXRtcCreate(ByteBuffer name, int num_input, int num_output, PointerByReference input_names, PointerByReference output_names, PointerByReference inputs, PointerByReference outputs, ByteBuffer kernel, PointerByReference out); int MXRtcPush(Pointer handle, int num_input, int num_output, PointerByReference inputs, PointerByReference outputs, int gridDimX, int gridDimY, int gridDimZ, int blockDimX, int blockDimY, int blockDimZ); int MXRtcFree(Pointer handle); int MXCustomOpRegister(String op_type, CustomOpPropCreator creator); int MXCustomFunctionRecord(int num_inputs, PointerByReference inputs, int num_outputs, PointerByReference outputs, MXCallbackList.ByReference callbacks); int MXRtcCudaModuleCreate(String source, int num_options, String[] options, int num_exports, String[] exports, PointerByReference out); int MXRtcCudaModuleFree(Pointer handle); int MXRtcCudaKernelCreate(Pointer handle, String name, int num_args, IntBuffer is_ndarray, IntBuffer is_const, IntBuffer arg_types, PointerByReference out); int MXRtcCudaKernelFree(Pointer handle); int MXRtcCudaKernelCall(Pointer handle, int dev_id, PointerByReference args, int grid_dim_x, int grid_dim_y, int grid_dim_z, int block_dim_x, int block_dim_y, int block_dim_z, int shared_mem); int MXNDArrayGetSharedMemHandle(Pointer handle, IntBuffer shared_pid, IntBuffer shared_id); int MXNDArrayCreateFromSharedMem(int shared_pid, int shared_id, int[] shape, int ndim, int dtype, PointerByReference out); int MXStorageEmptyCache(int dev_type, int dev_id); int MXNDArrayCreateFromSharedMemEx(int shared_pid, int shared_id, int[] shape, int ndim, int dtype, PointerByReference out); int MXEnginePushAsync(EngineAsyncFunc async_func, Pointer func_param, EngineFuncParamDeleter deleter, Pointer ctx_handle, Pointer const_vars_handle, int num_const_vars, Pointer mutable_vars_handle, int num_mutable_vars, Pointer prop_handle, int priority, String opr_name, byte wait); int MXEnginePushSync(EngineSyncFunc sync_func, Pointer func_param, EngineFuncParamDeleter deleter, Pointer ctx_handle, Pointer const_vars_handle, int num_const_vars, Pointer mutable_vars_handle, int num_mutable_vars, Pointer prop_handle, int priority, String opr_name); int MXShallowCopyNDArray(Pointer src, PointerByReference out); int MXShallowCopySymbol(Pointer src, PointerByReference out); int MXEnginePushAsyncND(EngineAsyncFunc async_func, Pointer func_param, EngineFuncParamDeleter deleter, Pointer ctx_handle, PointerByReference const_nds_handle, int num_const_nds, PointerByReference mutable_nds_handle, int num_mutable_nds, Pointer prop_handle, int priority, String opr_name, byte wait); int MXEnginePushSyncND(EngineSyncFunc sync_func, Pointer func_param, EngineFuncParamDeleter deleter, Pointer ctx_handle, PointerByReference const_nds_handle, int num_const_nds, PointerByReference mutable_nds_handle, int num_mutable_nds, Pointer prop_handle, int priority, String opr_name); void NNAPISetLastError(String msg); String NNGetLastError(); int NNListAllOpNames(IntBuffer out_size, PointerByReference out_array); int NNGetOpHandle(String op_name, PointerByReference op_out); int NNListUniqueOps(IntBuffer out_size, PointerByReference out_array); int NNGetOpInfo(Pointer op, String[] real_name, String[] description, IntBuffer num_doc_args, PointerByReference arg_names, PointerByReference arg_type_infos, PointerByReference arg_descriptions, String[] return_type); int NNSymbolCreateAtomicSymbol(Pointer op, int num_param, String[] keys, String[] vals, PointerByReference out); int NNSymbolCreateVariable(String name, PointerByReference out); int NNSymbolCreateGroup(int num_symbols, PointerByReference symbols, PointerByReference out); int NNAddControlDeps(Pointer handle, Pointer src_dep); int NNSymbolFree(Pointer symbol); int NNSymbolCopy(Pointer symbol, PointerByReference out); int NNSymbolPrint(Pointer symbol, String[] out_str); int NNSymbolGetAttr(Pointer symbol, String key, String[] out, IntBuffer success); int NNSymbolSetAttrs(Pointer symbol, int num_param, String[] keys, String[] values); int NNSymbolListAttrs(Pointer symbol, int recursive_option, IntBuffer out_size, PointerByReference out); int NNSymbolListInputVariables(Pointer symbol, int option, IntBuffer out_size, PointerByReference out_sym_array); int NNSymbolListInputNames(Pointer symbol, int option, IntBuffer out_size, PointerByReference out_str_array); int NNSymbolListOutputNames(Pointer symbol, IntBuffer out_size, PointerByReference out_str_array); int NNSymbolGetNumOutputs(Pointer symbol, IntBuffer output_count); int NNSymbolGetInternals(Pointer symbol, PointerByReference out); int NNSymbolGetChildren(Pointer symbol, PointerByReference out); int NNSymbolGetOutput(Pointer symbol, int index, PointerByReference out); int NNSymbolCompose(Pointer sym, String name, int num_args, String[] keys, PointerByReference args); int NNGraphCreate(Pointer symbol, PointerByReference graph); int NNGraphFree(Pointer handle); int NNGraphGetSymbol(Pointer graph, PointerByReference symbol); int NNGraphSetJSONAttr(Pointer handle, String key, String json_value); int NNGraphGetJSONAttr(Pointer handle, String key, String[] json_out, IntBuffer success); int NNGraphSetNodeEntryListAttr_(Pointer handle, String key, Pointer list); int NNGraphApplyPasses(Pointer src, int num_pass, String[] pass_names, PointerByReference dst); }
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/NDArrayOpInfo.java
package ai.djl.mxnet.jna; import com.sun.jna.Callback; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.ptr.PointerByReference; import java.nio.IntBuffer; import java.util.Arrays; import java.util.List; public class NDArrayOpInfo extends Structure { public ForwardCallback forward; public BackwardCallback backward; public InferShapeCallback infer_shape; public ListOutputsCallback list_outputs; public ListArgumentsCallback list_arguments; public DeclareBackwardDependencyCallback declare_backward_dependency; public Pointer p_forward; public Pointer p_backward; public Pointer p_infer_shape; public Pointer p_list_outputs; public Pointer p_list_arguments; public Pointer p_declare_backward_dependency; public NDArrayOpInfo() { } public NDArrayOpInfo(Pointer peer) { super(peer); } @Override protected List<String> getFieldOrder() { return Arrays.asList("forward", "backward", "infer_shape", "list_outputs", "list_arguments", "declare_backward_dependency", "p_forward", "p_backward", "p_infer_shape", "p_list_outputs", "p_list_arguments", "p_declare_backward_dependency"); } public void setForwardCallback(ForwardCallback forward) { this.forward = forward; } public ForwardCallback getForwardCallback() { return forward; } public void setBackwardCallback(BackwardCallback backward) { this.backward = backward; } public BackwardCallback getBackwardCallback() { return backward; } public void setInferShapeCallback(InferShapeCallback infer_shape) { this.infer_shape = infer_shape; } public InferShapeCallback getInferShapeCallback() { return infer_shape; } public void setListOutputsCallback(ListOutputsCallback list_outputs) { this.list_outputs = list_outputs; } public ListOutputsCallback getListOutputsCallback() { return list_outputs; } public void setListArgumentsCallback(ListArgumentsCallback list_arguments) { this.list_arguments = list_arguments; } public ListArgumentsCallback getListArgumentsCallback() { return list_arguments; } public void setDeclareBackwardDependencyCallback(DeclareBackwardDependencyCallback declare_backward_dependency) { this.declare_backward_dependency = declare_backward_dependency; } public DeclareBackwardDependencyCallback getDeclareBackwardDependencyCallback() { return declare_backward_dependency; } public void setPForward(Pointer p_forward) { this.p_forward = p_forward; } public Pointer getPForward() { return p_forward; } public void setPBackward(Pointer p_backward) { this.p_backward = p_backward; } public Pointer getPBackward() { return p_backward; } public void setPInferShape(Pointer p_infer_shape) { this.p_infer_shape = p_infer_shape; } public Pointer getPInferShape() { return p_infer_shape; } public void setPListOutputs(Pointer p_list_outputs) { this.p_list_outputs = p_list_outputs; } public Pointer getPListOutputs() { return p_list_outputs; } public void setPListArguments(Pointer p_list_arguments) { this.p_list_arguments = p_list_arguments; } public Pointer getPListArguments() { return p_list_arguments; } public void setPDeclareBackwardDependency(Pointer p_declare_backward_dependency) { this.p_declare_backward_dependency = p_declare_backward_dependency; } public Pointer getPDeclareBackwardDependency() { return p_declare_backward_dependency; } public static final class ByReference extends NDArrayOpInfo implements Structure.ByReference {} public static final class ByValue extends NDArrayOpInfo implements Structure.ByValue {} public interface ForwardCallback extends Callback { byte apply(int arg1, PointerByReference arg2, IntBuffer arg3, Pointer arg4); } public interface BackwardCallback extends Callback { byte apply(int arg1, PointerByReference arg2, IntBuffer arg3, Pointer arg4); } public interface InferShapeCallback extends Callback { byte apply(int arg1, IntBuffer arg2, PointerByReference arg3, Pointer arg4); } public interface ListOutputsCallback extends Callback { byte apply(PointerByReference arg1, Pointer arg2); } public interface ListArgumentsCallback extends Callback { byte apply(PointerByReference arg1, Pointer arg2); } public interface DeclareBackwardDependencyCallback extends Callback { byte apply(int[] arg1, int[] arg2, int[] arg3, IntBuffer arg4, PointerByReference arg5, Pointer arg6); } }
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/NativeOpInfo.java
package ai.djl.mxnet.jna; import com.sun.jna.Callback; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.ptr.PointerByReference; import java.nio.IntBuffer; import java.util.Arrays; import java.util.List; public class NativeOpInfo extends Structure { public ForwardCallback forward; public BackwardCallback backward; public InferShapeCallback infer_shape; public ListOutputsCallback list_outputs; public ListArgumentsCallback list_arguments; public Pointer p_forward; public Pointer p_backward; public Pointer p_infer_shape; public Pointer p_list_outputs; public Pointer p_list_arguments; public NativeOpInfo() { } public NativeOpInfo(Pointer peer) { super(peer); } @Override protected List<String> getFieldOrder() { return Arrays.asList("forward", "backward", "infer_shape", "list_outputs", "list_arguments", "p_forward", "p_backward", "p_infer_shape", "p_list_outputs", "p_list_arguments"); } public void setForwardCallback(ForwardCallback forward) { this.forward = forward; } public ForwardCallback getForwardCallback() { return forward; } public void setBackwardCallback(BackwardCallback backward) { this.backward = backward; } public BackwardCallback getBackwardCallback() { return backward; } public void setInferShapeCallback(InferShapeCallback infer_shape) { this.infer_shape = infer_shape; } public InferShapeCallback getInferShapeCallback() { return infer_shape; } public void setListOutputsCallback(ListOutputsCallback list_outputs) { this.list_outputs = list_outputs; } public ListOutputsCallback getListOutputsCallback() { return list_outputs; } public void setListArgumentsCallback(ListArgumentsCallback list_arguments) { this.list_arguments = list_arguments; } public ListArgumentsCallback getListArgumentsCallback() { return list_arguments; } public void setPForward(Pointer p_forward) { this.p_forward = p_forward; } public Pointer getPForward() { return p_forward; } public void setPBackward(Pointer p_backward) { this.p_backward = p_backward; } public Pointer getPBackward() { return p_backward; } public void setPInferShape(Pointer p_infer_shape) { this.p_infer_shape = p_infer_shape; } public Pointer getPInferShape() { return p_infer_shape; } public void setPListOutputs(Pointer p_list_outputs) { this.p_list_outputs = p_list_outputs; } public Pointer getPListOutputs() { return p_list_outputs; } public void setPListArguments(Pointer p_list_arguments) { this.p_list_arguments = p_list_arguments; } public Pointer getPListArguments() { return p_list_arguments; } public static final class ByReference extends NativeOpInfo implements Structure.ByReference {} public static final class ByValue extends NativeOpInfo implements Structure.ByValue {} public interface ForwardCallback extends Callback { void apply(int arg1, PointerByReference arg2, IntBuffer arg3, PointerByReference arg4, IntBuffer arg5, Pointer arg6); } public interface BackwardCallback extends Callback { void apply(int arg1, PointerByReference arg2, IntBuffer arg3, PointerByReference arg4, IntBuffer arg5, Pointer arg6); } public interface InferShapeCallback extends Callback { void apply(int arg1, IntBuffer arg2, PointerByReference arg3, Pointer arg4); } public interface ListOutputsCallback extends Callback { void apply(PointerByReference arg1, Pointer arg2); } public interface ListArgumentsCallback extends Callback { void apply(PointerByReference arg1, Pointer arg2); } }
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/NativeSize.java
package ai.djl.mxnet.jna; import com.sun.jna.IntegerType; import com.sun.jna.Native; public class NativeSize extends IntegerType { private static final long serialVersionUID = 1L; public static final int SIZE = Native.SIZE_T_SIZE; public NativeSize() { this(0); } public NativeSize(long value) { super(SIZE, value); } }
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/NativeSizeByReference.java
package ai.djl.mxnet.jna; import com.sun.jna.ptr.ByReference; public class NativeSizeByReference extends ByReference { public NativeSizeByReference() { this(new NativeSize(0)); } @SuppressWarnings("this-escape") public NativeSizeByReference(NativeSize value) { super(NativeSize.SIZE); setValue(value); } public void setValue(NativeSize value) { if (NativeSize.SIZE == 4) { getPointer().setInt(0, value.intValue()); } else if (NativeSize.SIZE == 8) { getPointer().setLong(0, value.longValue()); } else { throw new IllegalArgumentException("size_t has to be either 4 or 8 bytes."); } } public NativeSize getValue() { if (NativeSize.SIZE == 4) { return new NativeSize(getPointer().getInt(0)); } else if (NativeSize.SIZE == 8) { return new NativeSize(getPointer().getLong(0)); } else { throw new IllegalArgumentException("size_t has to be either 4 or 8 bytes."); } } }
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/NativeString.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.mxnet.jna; import com.sun.jna.Memory; import com.sun.jna.Pointer; import java.nio.charset.Charset; /** * Provides a temporary allocation of an immutable C string (<code>const char*</code> or <code> * const wchar_t*</code>) for use when converting a Java String into a native memory function * argument. */ final class NativeString { private static final ObjectPool<NativeString> POOL = new ObjectPool<>(null, null); private Memory pointer; /** * Create a native string (NUL-terminated array of <code>char</code>), using the requested * encoding. * * @param data the bytes of the string */ private NativeString(byte[] data) { pointer = new Memory(data.length + 1); setData(data); } private void setData(byte[] data) { pointer.write(0, data, 0, data.length); pointer.setByte(data.length, (byte) 0); } /** * Acquires a pooled {@code NativeString} object if available, otherwise a new instance is * created. * * @param string the string value * @param encoding the charset encoding * @return a {@code NativeString} object */ public static NativeString of(String string, Charset encoding) { byte[] data = string.getBytes(encoding); NativeString array = POOL.acquire(); if (array != null && array.pointer.size() > data.length) { array.setData(data); return array; } return new NativeString(data); } /** Recycles this instance and return it back to the pool. */ public void recycle() { POOL.recycle(this); } /** * Returns the peer pointer. * * @return the peer pointer */ public Pointer getPointer() { return pointer; } }
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/ObjectPool.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.mxnet.jna; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.function.Consumer; import java.util.function.Supplier; /** * A generic object pool implementation. * * @param <T> the type of object to put in the pool */ @SuppressWarnings("MissingJavadocMethod") public class ObjectPool<T> { private Queue<T> queue; private Supplier<T> supplier; private Consumer<T> consumer; public ObjectPool(Supplier<T> supplier, Consumer<T> consumer) { queue = new ConcurrentLinkedQueue<>(); this.supplier = supplier; this.consumer = consumer; } public T acquire() { T item = queue.poll(); if (item == null) { if (supplier != null) { return supplier.get(); } } return item; } public void recycle(T item) { if (consumer != null) { consumer.accept(item); } queue.add(item); } }
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/OtherOptionEntity.java
package ai.djl.mxnet.jna; import com.sun.jna.Pointer; import com.sun.jna.Structure; import java.util.Collections; import java.util.List; public class OtherOptionEntity extends Structure { public int val; public OtherOptionEntity() { } public OtherOptionEntity(Pointer peer) { super(peer); } @Override protected List<String> getFieldOrder() { return Collections.singletonList("val"); } public void setVal(int val) { this.val = val; } public int getVal() { return val; } public static final class ByReference extends OtherOptionEntity implements Structure.ByReference {} public static final class ByValue extends OtherOptionEntity implements Structure.ByValue {} }
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/OtherOptionSpace.java
package ai.djl.mxnet.jna; import com.sun.jna.Pointer; import com.sun.jna.Structure; import java.util.Arrays; import java.util.List; public class OtherOptionSpace extends Structure { public OtherOptionEntity.ByReference entities; public int entities_size; public OtherOptionSpace() { } public OtherOptionSpace(Pointer peer) { super(peer); } @Override protected List<String> getFieldOrder() { return Arrays.asList("entities", "entities_size"); } public void setEntities(OtherOptionEntity.ByReference entities) { this.entities = entities; } public OtherOptionEntity.ByReference getEntities() { return entities; } public void setEntitiesSize(int entities_size) { this.entities_size = entities_size; } public int getEntitiesSize() { return entities_size; } public static final class ByReference extends OtherOptionSpace implements Structure.ByReference {} public static final class ByValue extends OtherOptionSpace implements Structure.ByValue {} }
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/PointerArray.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.mxnet.jna; import com.sun.jna.Function; import com.sun.jna.Memory; import com.sun.jna.Native; import com.sun.jna.Pointer; /** * An abstraction for a native pointer array data type ({@code void**}). * * @see Pointer * @see com.sun.jna.ptr.PointerByReference * @see Function */ @SuppressWarnings("checkstyle:EqualsHashCode") final class PointerArray extends Memory { private static final ObjectPool<PointerArray> POOL = new ObjectPool<>(null, null); private int length; /** * Constructs a {@link Memory} buffer PointerArray given the Pointers to include in it. * * @param arg the pointers to include in the array */ private PointerArray(Pointer... arg) { super(Native.POINTER_SIZE * (arg.length + 1)); length = arg.length; setPointers(arg); } /** * Acquires a pooled {@code PointerArray} object if available, otherwise a new instance is * created. * * @param arg the pointers to include in the array * @return a {@code PointerArray} object */ public static PointerArray of(Pointer... arg) { PointerArray array = POOL.acquire(); if (array != null && array.length >= arg.length) { array.setPointers(arg); return array; } return new PointerArray(arg); } /** Recycles this instance and return it back to the pool. */ public void recycle() { POOL.recycle(this); } private void setPointers(Pointer[] pointers) { for (int i = 0; i < pointers.length; i++) { setPointer(i * Native.POINTER_SIZE, pointers[i]); } setPointer(Native.POINTER_SIZE * length, null); } /** {@inheritDoc} */ @Override public boolean equals(Object o) { return o == this; } }
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/StringArray.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.mxnet.jna; import com.sun.jna.Memory; import com.sun.jna.Native; import com.sun.jna.Pointer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; /** An abstraction for a native string array data type ({@code char**}). */ @SuppressWarnings("checkstyle:EqualsHashCode") final class StringArray extends Memory { private static final Charset ENCODING = Native.DEFAULT_CHARSET; private static final ObjectPool<StringArray> POOL = new ObjectPool<>(null, null); /** Hold all {@code NativeString}, avoid be GCed. */ private List<NativeString> natives; // NOPMD private int length; /** * Create a native array of strings. * * @param strings the strings */ private StringArray(String[] strings) { super((strings.length + 1) * Native.POINTER_SIZE); natives = new ArrayList<>(); length = strings.length; setPointers(strings); } private void setPointers(String[] strings) { for (NativeString ns : natives) { ns.recycle(); } natives.clear(); for (int i = 0; i < strings.length; i++) { Pointer p = null; if (strings[i] != null) { NativeString ns = NativeString.of(strings[i], ENCODING); natives.add(ns); p = ns.getPointer(); } setPointer(Native.POINTER_SIZE * i, p); } setPointer(Native.POINTER_SIZE * strings.length, null); } /** * Acquires a pooled {@code StringArray} object if available, otherwise a new instance is * created. * * @param strings the pointers to include in the array * @return a {@code StringArray} object */ public static StringArray of(String[] strings) { StringArray array = POOL.acquire(); if (array != null && array.length >= strings.length) { array.setPointers(strings); return array; } return new StringArray(strings); } /** Recycles this instance and return it back to the pool. */ public void recycle() { POOL.recycle(this); } /** {@inheritDoc} */ @Override public boolean equals(Object o) { return this == o; } }
0
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-engine/0.34.0/ai/djl/mxnet/jna/package-info.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** * Contains classes to interface with the underlying MXNet Engine. * * <p>Information about locating and loading the MXNet binary can be found in {@link * ai.djl.mxnet.jna.LibUtils}. */ package ai.djl.mxnet.jna;
0
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/MxModelZoo.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.mxnet.zoo; import ai.djl.Application.CV; import ai.djl.Application.NLP; import ai.djl.Application.TimeSeries; import ai.djl.mxnet.engine.MxEngine; import ai.djl.repository.RemoteRepository; import ai.djl.repository.Repository; import ai.djl.repository.zoo.ModelZoo; import java.util.Collections; import java.util.Set; /** * MxModelZoo is a repository that contains all MXNet models in {@link * ai.djl.mxnet.engine.MxSymbolBlock} for DJL. */ public class MxModelZoo extends ModelZoo { private static final Repository REPOSITORY = new RemoteRepository("MXNet", DJL_REPO_URL); public static final String GROUP_ID = "ai.djl.mxnet"; MxModelZoo() { addModel(REPOSITORY.model(CV.OBJECT_DETECTION, GROUP_ID, "ssd", "0.0.1")); addModel(REPOSITORY.model(CV.OBJECT_DETECTION, GROUP_ID, "yolo", "0.0.1")); addModel(REPOSITORY.model(CV.IMAGE_CLASSIFICATION, GROUP_ID, "alexnet", "0.0.1")); addModel(REPOSITORY.model(CV.IMAGE_CLASSIFICATION, GROUP_ID, "darknet", "0.0.1")); addModel(REPOSITORY.model(CV.IMAGE_CLASSIFICATION, GROUP_ID, "densenet", "0.0.1")); addModel(REPOSITORY.model(CV.IMAGE_CLASSIFICATION, GROUP_ID, "googlenet", "0.0.1")); addModel(REPOSITORY.model(CV.IMAGE_CLASSIFICATION, GROUP_ID, "inceptionv3", "0.0.1")); addModel(REPOSITORY.model(CV.IMAGE_CLASSIFICATION, GROUP_ID, "mlp", "0.0.1")); addModel(REPOSITORY.model(CV.IMAGE_CLASSIFICATION, GROUP_ID, "mobilenet", "0.0.1")); addModel(REPOSITORY.model(CV.IMAGE_CLASSIFICATION, GROUP_ID, "resnest", "0.0.1")); addModel(REPOSITORY.model(CV.IMAGE_CLASSIFICATION, GROUP_ID, "resnet", "0.0.1")); addModel(REPOSITORY.model(CV.IMAGE_CLASSIFICATION, GROUP_ID, "senet", "0.0.1")); addModel(REPOSITORY.model(CV.IMAGE_CLASSIFICATION, GROUP_ID, "se_resnext", "0.0.1")); addModel(REPOSITORY.model(CV.IMAGE_CLASSIFICATION, GROUP_ID, "squeezenet", "0.0.1")); addModel(REPOSITORY.model(CV.IMAGE_CLASSIFICATION, GROUP_ID, "vgg", "0.0.1")); addModel(REPOSITORY.model(CV.IMAGE_CLASSIFICATION, GROUP_ID, "xception", "0.0.1")); addModel(REPOSITORY.model(CV.POSE_ESTIMATION, GROUP_ID, "simple_pose", "0.0.1")); addModel(REPOSITORY.model(CV.INSTANCE_SEGMENTATION, GROUP_ID, "mask_rcnn", "0.0.1")); addModel(REPOSITORY.model(CV.ACTION_RECOGNITION, GROUP_ID, "action_recognition", "0.0.1")); addModel(REPOSITORY.model(NLP.QUESTION_ANSWER, GROUP_ID, "bertqa", "0.0.1")); addModel(REPOSITORY.model(NLP.WORD_EMBEDDING, GROUP_ID, "glove", "0.0.2")); addModel(REPOSITORY.model(TimeSeries.FORECASTING, GROUP_ID, "deepar", "0.0.1")); } /** {@inheritDoc} */ @Override public String getGroupId() { return GROUP_ID; } /** {@inheritDoc} */ @Override public Set<String> getSupportedEngines() { return Collections.singleton(MxEngine.ENGINE_NAME); } }
0
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/MxZooProvider.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.mxnet.zoo; import ai.djl.repository.zoo.ModelZoo; import ai.djl.repository.zoo.ZooProvider; /** * An MXNet model zoo provider implements the {@link ai.djl.repository.zoo.ZooProvider} interface. */ public class MxZooProvider implements ZooProvider { /** {@inheritDoc} */ @Override public ModelZoo getModelZoo() { return new MxModelZoo(); } }
0
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/package-info.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** Contains the built-in {@link ai.djl.mxnet.zoo.MxModelZoo}. */ package ai.djl.mxnet.zoo;
0
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/nlp
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/nlp/embedding/GloveWordEmbeddingBlockFactory.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.mxnet.zoo.nlp.embedding; import ai.djl.Model; import ai.djl.modality.nlp.DefaultVocabulary; import ai.djl.modality.nlp.embedding.TrainableWordEmbedding; import ai.djl.nn.Block; import ai.djl.nn.BlockFactory; import ai.djl.translate.ArgumentsUtil; import ai.djl.util.Utils; import java.io.IOException; import java.nio.file.Path; import java.util.List; import java.util.Map; /** A {@link BlockFactory} class that creates Glove word embedding block. */ public class GloveWordEmbeddingBlockFactory implements BlockFactory { private static final long serialVersionUID = 1L; /** {@inheritDoc} */ @Override public Block newBlock(Model model, Path modelPath, Map<String, ?> arguments) throws IOException { List<String> idxToToken = Utils.readLines(modelPath.resolve("idx_to_token.txt")); String dimension = ArgumentsUtil.stringValue(arguments, "dimensions"); String unknownToken = ArgumentsUtil.stringValue(arguments, "unknownToken"); TrainableWordEmbedding wordEmbedding = TrainableWordEmbedding.builder() .setEmbeddingSize(Integer.parseInt(dimension)) .setVocabulary( DefaultVocabulary.builder() .add(idxToToken) .optUnknownToken(unknownToken) .build()) .optUnknownToken(unknownToken) .optUseDefault(true) .build(); model.setProperty("unknownToken", unknownToken); return wordEmbedding; } }
0
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/nlp
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/nlp/embedding/GloveWordEmbeddingTranslatorFactory.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.mxnet.zoo.nlp.embedding; import ai.djl.Model; import ai.djl.ndarray.NDList; import ai.djl.nn.core.Embedding; import ai.djl.translate.ArgumentsUtil; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; import ai.djl.translate.TranslatorFactory; import ai.djl.util.Pair; import java.lang.reflect.Type; import java.util.Collections; import java.util.Map; import java.util.Set; /** A {@link TranslatorFactory} that creates a {@link GloveWordEmbeddingTranslator} instance. */ public class GloveWordEmbeddingTranslatorFactory implements TranslatorFactory { /** {@inheritDoc} */ @Override public Set<Pair<Type, Type>> getSupportedTypes() { return Collections.singleton(new Pair<>(String.class, NDList.class)); } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public <I, O> Translator<I, O> newInstance( Class<I> input, Class<O> output, Model model, Map<String, ?> arguments) { if (!isSupported(input, output)) { throw new IllegalArgumentException("Unsupported input/output types."); } String unknownToken = ArgumentsUtil.stringValue(arguments, "unknownToken"); return (Translator<I, O>) new GloveWordEmbeddingTranslator(unknownToken); } private static final class GloveWordEmbeddingTranslator implements Translator<String, NDList> { private String unknownToken; private Embedding<String> embedding; public GloveWordEmbeddingTranslator(String unknownToken) { this.unknownToken = unknownToken; } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public void prepare(TranslatorContext ctx) { try { embedding = (Embedding<String>) ctx.getBlock(); } catch (ClassCastException e) { throw new IllegalArgumentException("The model was not an embedding", e); } } /** {@inheritDoc} */ @Override public NDList processOutput(TranslatorContext ctx, NDList list) { list.detach(); return list; } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, String input) { if (embedding.hasItem(input)) { return new NDList(ctx.getNDManager().create(embedding.embed(input))); } return new NDList(ctx.getNDManager().create(embedding.embed(unknownToken))); } } }
0
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/nlp
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/nlp/embedding/package-info.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** * Contains classes for the natural language processing section ({@link ai.djl.Application.NLP}) of * the {@link ai.djl.mxnet.zoo.MxModelZoo}. */ package ai.djl.mxnet.zoo.nlp.embedding;
0
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/nlp/embedding
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/nlp/embedding/utils/BuildModelZooWordEmbedding.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.mxnet.zoo.nlp.embedding.utils; import ai.djl.Model; import ai.djl.modality.nlp.embedding.TrainableWordEmbedding; import ai.djl.ndarray.NDArray; import ai.djl.util.Utils; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; /** * A utility to build embeddings into DJL format from Gluon-NLP format. * * <p>This utility should be called after running convertEmbeddings.py */ public final class BuildModelZooWordEmbedding { private BuildModelZooWordEmbedding() {} /** * Runs main build embeddings after editing. * * @param args the arguments * @throws IOException thrown if unable to read files in directory */ public static void main(String[] args) throws IOException { // EDIT THESE STRINGS TO THE EMBEDDING DIR AND NAME buildEmbedding("", ""); } private static void buildEmbedding(String dir, String name) throws IOException { Path path = Paths.get(dir); Model model = Model.newInstance(name); NDArray idxToVec = model.getNDManager().load(path.resolve("idx_to_vec.mx")).singletonOrThrow(); List<String> idxToToken = Utils.readLines(path.resolve("idx_to_token.txt")); TrainableWordEmbedding embedding = TrainableWordEmbedding.fromPretrained(idxToVec, idxToToken); model.setBlock(embedding); model.save(path, name); } }
0
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/nlp/embedding
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/nlp/embedding/utils/package-info.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** * Contains utilities for the natural language processing section ({@link ai.djl.Application.NLP}) * of the {@link ai.djl.mxnet.zoo.MxModelZoo}. */ package ai.djl.mxnet.zoo.nlp.embedding.utils;
0
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/nlp
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/nlp/qa/MxBertQATranslator.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.mxnet.zoo.nlp.qa; import ai.djl.Model; import ai.djl.modality.nlp.DefaultVocabulary; import ai.djl.modality.nlp.Vocabulary; import ai.djl.modality.nlp.bert.BertToken; import ai.djl.modality.nlp.bert.BertTokenizer; import ai.djl.modality.nlp.qa.QAInput; import ai.djl.modality.nlp.translator.QATranslator; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.Shape; import ai.djl.translate.ArgumentsUtil; import ai.djl.translate.Batchifier; import ai.djl.translate.TranslatorContext; import ai.djl.util.JsonUtils; import ai.djl.util.Utils; import com.google.gson.annotations.SerializedName; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** The translator for MXNet BERT QA model. */ public class MxBertQATranslator extends QATranslator { private List<String> tokens; private Vocabulary vocabulary; private BertTokenizer tokenizer; private int seqLength; MxBertQATranslator(Builder builder) { super(builder); seqLength = builder.seqLength; } /** {@inheritDoc} */ @Override public void prepare(TranslatorContext ctx) throws IOException { Model model = ctx.getModel(); vocabulary = DefaultVocabulary.builder() .addFromCustomizedFile( model.getArtifact("vocab.json"), VocabParser::parseToken) .optUnknownToken("[UNK]") .build(); tokenizer = new BertTokenizer(); } /** {@inheritDoc} */ @Override public Batchifier getBatchifier() { // MXNet BertQA model doesn't support batch. See NoBatchifyTranslator. return null; } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, QAInput input) { BertToken token = tokenizer.encode( input.getQuestion().toLowerCase(), input.getParagraph().toLowerCase(), seqLength); tokens = token.getTokens(); List<Long> indices = token.getTokens().stream().map(vocabulary::getIndex).collect(Collectors.toList()); float[] indexesFloat = Utils.toFloatArray(indices); float[] types = Utils.toFloatArray(token.getTokenTypes()); int validLength = token.getValidLength(); NDManager manager = ctx.getNDManager(); NDArray data0 = manager.create(indexesFloat); data0.setName("data0"); NDArray data1 = manager.create(types); data1.setName("data1"); // avoid to use scalar as MXNet Bert model was trained with 1.5.0 // which is not compatible with MXNet NumPy NDArray data2 = manager.create(new float[] {validLength}); data2.setName("data2"); return new NDList(data0, data1, data2); } /** {@inheritDoc} */ @Override public String processOutput(TranslatorContext ctx, NDList list) { NDArray array = list.singletonOrThrow(); NDList output = array.split(2, 2); // Get the formatted logits result NDArray startLogits = output.get(0).reshape(new Shape(1, -1)); NDArray endLogits = output.get(1).reshape(new Shape(1, -1)); int startIdx = (int) startLogits.argMax(1).getLong(); int endIdx = (int) endLogits.argMax(1).getLong(); return tokenizer.buildSentence(tokens.subList(startIdx, endIdx + 1)); } /** * Creates a builder to build a {@code MxBertQATranslator}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** * Creates a builder to build a {@code MxBertQATranslator}. * * @param arguments the models' arguments * @return a new builder */ public static Builder builder(Map<String, ?> arguments) { Builder builder = new Builder(); builder.configure(arguments); builder.setSeqLength(ArgumentsUtil.intValue(arguments, "seqLength", 384)); return builder; } /** The builder for Bert QA translator. */ public static class Builder extends BaseBuilder<Builder> { private int seqLength; /** * Set the max length of the sequence to do the padding. * * @param seqLength the length of the sequence * @return builder */ public Builder setSeqLength(int seqLength) { this.seqLength = seqLength; return self(); } /** * Returns the builder. * * @return the builder */ @Override protected Builder self() { return this; } /** * Builds the translator. * * @return the new translator */ protected MxBertQATranslator build() { if (seqLength == 0) { throw new IllegalArgumentException("You must specify a seqLength with value > 0"); } return new MxBertQATranslator(this); } } private static final class VocabParser { @SerializedName("idx_to_token") List<String> idx2token; public static List<String> parseToken(URL url) { try (InputStream is = new BufferedInputStream(url.openStream()); Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) { return JsonUtils.GSON.fromJson(reader, VocabParser.class).idx2token; } catch (IOException e) { throw new IllegalArgumentException("Invalid url: " + url, e); } } } }
0
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/nlp
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/nlp/qa/MxBertQATranslatorFactory.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.mxnet.zoo.nlp.qa; import ai.djl.Model; import ai.djl.modality.Input; import ai.djl.modality.Output; import ai.djl.modality.nlp.qa.QAInput; import ai.djl.modality.nlp.translator.QATranslator; import ai.djl.modality.nlp.translator.QaServingTranslator; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorFactory; import ai.djl.util.Pair; import java.lang.reflect.Type; import java.util.HashSet; import java.util.Map; import java.util.Set; /** A {@link TranslatorFactory} that creates a {@link MxBertQATranslator} instance. */ public class MxBertQATranslatorFactory implements TranslatorFactory { private static final Set<Pair<Type, Type>> SUPPORTED_TYPES = new HashSet<>(); static { SUPPORTED_TYPES.add(new Pair<>(QAInput.class, String.class)); SUPPORTED_TYPES.add(new Pair<>(Input.class, Output.class)); } /** {@inheritDoc} */ @Override public Set<Pair<Type, Type>> getSupportedTypes() { return SUPPORTED_TYPES; } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public <I, O> Translator<I, O> newInstance( Class<I> input, Class<O> output, Model model, Map<String, ?> arguments) { if (!isSupported(input, output)) { throw new IllegalArgumentException("Unsupported input/output types."); } QATranslator translator = MxBertQATranslator.builder(arguments).build(); if (input == Input.class && output == Output.class) { return (Translator<I, O>) new QaServingTranslator(translator); } return (Translator<I, O>) translator; } }
0
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/nlp
java-sources/ai/djl/mxnet/mxnet-model-zoo/0.34.0/ai/djl/mxnet/zoo/nlp/qa/package-info.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** * Contains classes for the {@link ai.djl.Application.NLP#QUESTION_ANSWER} models in the {@link * ai.djl.mxnet.zoo.MxModelZoo}. */ package ai.djl.mxnet.zoo.nlp.qa;
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/engine/OrtEngine.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.onnxruntime.engine; import ai.djl.Device; import ai.djl.Model; import ai.djl.engine.Engine; import ai.djl.engine.StandardCapabilities; import ai.djl.ndarray.NDManager; import ai.onnxruntime.OrtEnvironment; import ai.onnxruntime.OrtException; import ai.onnxruntime.OrtLoggingLevel; import ai.onnxruntime.OrtSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@code OrtEngine} is an implementation of the {@link Engine} based on the <a * href="https://microsoft.github.io/onnxruntime/">ONNX Runtime Deep Learning Library</a>. * * <p>To get an instance of the {@code OrtEngine} when it is not the default Engine, call {@link * Engine#getEngine(String)} with the Engine name "OnnxRuntime". */ public final class OrtEngine extends Engine { private static final Logger logger = LoggerFactory.getLogger(OrtEngine.class); public static final String ENGINE_NAME = "OnnxRuntime"; static final int RANK = 10; private OrtEnvironment env; private Engine alternativeEngine; private boolean initialized; private OrtEngine() { // init OrtRuntime OrtEnvironment.ThreadingOptions options = new OrtEnvironment.ThreadingOptions(); try { Integer interOpThreads = Integer.getInteger("ai.djl.onnxruntime.num_interop_threads"); Integer intraOpsThreads = Integer.getInteger("ai.djl.onnxruntime.num_threads"); if (interOpThreads != null) { options.setGlobalInterOpNumThreads(interOpThreads); } if (intraOpsThreads != null) { options.setGlobalIntraOpNumThreads(intraOpsThreads); } OrtLoggingLevel logging = OrtLoggingLevel.ORT_LOGGING_LEVEL_WARNING; String name = OrtEnvironment.DEFAULT_NAME; this.env = OrtEnvironment.getEnvironment(logging, name, options); } catch (OrtException e) { options.close(); throw new AssertionError("Failed to config OrtEnvironment", e); } } static Engine newInstance() { return new OrtEngine(); } OrtEnvironment getEnv() { return env; } /** {@inheritDoc} */ @Override public Engine getAlternativeEngine() { if (!initialized && !Boolean.getBoolean("ai.djl.onnx.disable_alternative")) { Engine engine; if (Engine.hasEngine("PyTorch")) { // workaround MXNet engine issue on CI engine = Engine.getEngine("PyTorch"); } else { engine = Engine.getInstance(); } if (engine.getRank() < getRank()) { // alternativeEngine should not have the same rank as OnnxRuntime alternativeEngine = engine; } initialized = true; } return alternativeEngine; } /** {@inheritDoc} */ @Override public String getEngineName() { return ENGINE_NAME; } /** {@inheritDoc} */ @Override public int getRank() { return RANK; } /** {@inheritDoc} */ @Override public String getVersion() { return "1.21.1"; } /** {@inheritDoc} */ @Override public boolean hasCapability(String capability) { if (StandardCapabilities.MKL.equals(capability)) { return true; } else if (StandardCapabilities.CUDA.equals(capability)) { try (OrtSession.SessionOptions sessionOptions = new OrtSession.SessionOptions()) { sessionOptions.addCUDA(); return true; } catch (OrtException e) { logger.warn("CUDA is not supported OnnxRuntime engine: {}", e.getMessage()); return false; } } return false; } /** {@inheritDoc} */ @Override public Model newModel(String name, Device device) { return new OrtModel(name, newBaseManager(device), env); } /** {@inheritDoc} */ @Override public NDManager newBaseManager() { return newBaseManager(null); } /** {@inheritDoc} */ @Override public NDManager newBaseManager(Device device) { return OrtNDManager.getSystemManager().newSubManager(device); } /** {@inheritDoc} */ @Override public String toString() { StringBuilder sb = new StringBuilder(200); sb.append(getEngineName()).append(':').append(getVersion()).append(", "); sb.append(getEngineName()) .append(':') .append(getVersion()) .append(", capabilities: [\n\t" + StandardCapabilities.MKL); if (hasCapability(StandardCapabilities.CUDA)) { sb.append(",\n\t").append(StandardCapabilities.CUDA); // NOPMD } sb.append(']'); return sb.toString(); } }
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/engine/OrtEngineProvider.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.onnxruntime.engine; import ai.djl.engine.Engine; import ai.djl.engine.EngineProvider; /** {@code OrtEngineProvider} is the ONNX Runtime implementation of {@link EngineProvider}. */ public class OrtEngineProvider implements EngineProvider { /** {@inheritDoc} */ @Override public String getEngineName() { return OrtEngine.ENGINE_NAME; } /** {@inheritDoc} */ @Override public int getEngineRank() { return OrtEngine.RANK; } /** {@inheritDoc} */ @Override public Engine getEngine() { return InstanceHolder.INSTANCE; } private static class InstanceHolder { static final Engine INSTANCE = OrtEngine.newInstance(); } }
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/engine/OrtModel.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.onnxruntime.engine; import ai.djl.BaseModel; import ai.djl.Device; import ai.djl.MalformedModelException; import ai.djl.Model; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.DataType; import ai.djl.util.ClassLoaderUtils; import ai.djl.util.Utils; import ai.onnxruntime.OrtEnvironment; import ai.onnxruntime.OrtException; import ai.onnxruntime.OrtSession; import ai.onnxruntime.OrtSession.SessionOptions; import ai.onnxruntime.OrtSession.SessionOptions.ExecutionMode; import ai.onnxruntime.OrtSession.SessionOptions.OptLevel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.nio.file.Files; import java.nio.file.Path; import java.util.Map; /** * {@code OrtModel} is the ONNX Runtime implementation of {@link Model}. * * <p>OrtModel contains all the methods in Model to load and process a model. In addition, it * provides ONNX Runtime Specific functionality */ public class OrtModel extends BaseModel { private static final Logger logger = LoggerFactory.getLogger(OrtModel.class); private OrtEnvironment env; private SessionOptions sessionOptions; /** * Constructs a new Model on a given device. * * @param name the model name * @param manager the {@link NDManager} to holds the NDArray * @param env the {@link OrtEnvironment} ONNX Environment to create session */ OrtModel(String name, NDManager manager, OrtEnvironment env) { super(name); this.manager = manager; this.manager.setName("ortModel"); this.env = env; dataType = DataType.FLOAT32; sessionOptions = new SessionOptions(); } /** {@inheritDoc} */ @Override public void load(Path modelPath, String prefix, Map<String, ?> options) throws IOException, MalformedModelException { setModelDir(modelPath); wasLoaded = true; if (block != null) { throw new UnsupportedOperationException("ONNX Runtime does not support dynamic blocks"); } Path modelFile; if (prefix != null) { modelFile = findModelFile(prefix); } else { // search for .onnx file with folder name or "model.onnx" modelFile = findModelFile(modelName, modelDir.toFile().getName(), "model.onnx"); } if (modelFile == null) { throw new FileNotFoundException(".onnx file not found in: " + modelPath); } try { SessionOptions ortOptions = getSessionOptions(options); OrtSession session = env.createSession(modelFile.toString(), ortOptions); block = new OrtSymbolBlock(session, (OrtNDManager) manager); } catch (OrtException e) { throw new MalformedModelException("ONNX Model cannot be loaded", e); } } /** {@inheritDoc} */ @Override public void load(InputStream is, Map<String, ?> options) throws IOException, MalformedModelException { if (block != null) { throw new UnsupportedOperationException("ONNX Runtime does not support dynamic blocks"); } modelDir = Files.createTempDirectory("ort-model"); modelDir.toFile().deleteOnExit(); try { byte[] buf = Utils.toByteArray(is); SessionOptions ortOptions = getSessionOptions(options); OrtSession session = env.createSession(buf, ortOptions); block = new OrtSymbolBlock(session, (OrtNDManager) manager); } catch (OrtException e) { throw new MalformedModelException("ONNX Model cannot be loaded", e); } } private Path findModelFile(String... prefixes) { if (Files.isRegularFile(modelDir)) { Path file = modelDir; modelDir = modelDir.getParent(); String fileName = file.toFile().getName(); if (fileName.endsWith(".onnx")) { modelName = fileName.substring(0, fileName.length() - 5); } else { modelName = fileName; } return file; } for (String prefix : prefixes) { Path modelFile = modelDir.resolve(prefix); if (Files.isRegularFile(modelFile)) { return modelFile; } if (!prefix.endsWith(".onnx")) { modelFile = modelDir.resolve(prefix + ".onnx"); if (Files.isRegularFile(modelFile)) { return modelFile; } } } return null; } /** {@inheritDoc} */ @Override public void close() { super.close(); try { sessionOptions.close(); } catch (IllegalArgumentException ignore) { // ignore } } private SessionOptions getSessionOptions(Map<String, ?> options) throws OrtException { if (options == null) { return sessionOptions; } SessionOptions ortSession = sessionOptions; if (options.containsKey("sessionOptions")) { ortSession = (SessionOptions) options.get("sessionOptions"); } String interOpNumThreads = (String) options.get("interOpNumThreads"); if (interOpNumThreads != null) { ortSession.setInterOpNumThreads(Integer.parseInt(interOpNumThreads)); } String intraOpNumThreads = (String) options.get("intraOpNumThreads"); if (intraOpNumThreads != null) { ortSession.setIntraOpNumThreads(Integer.parseInt(intraOpNumThreads)); } String executionMode = (String) options.get("executionMode"); if (executionMode != null) { ortSession.setExecutionMode(ExecutionMode.valueOf(executionMode)); } String optLevel = (String) options.get("optLevel"); if (optLevel != null) { ortSession.setOptimizationLevel(OptLevel.valueOf(optLevel)); } String memoryOptimization = (String) options.get("memoryPatternOptimization"); if (Boolean.parseBoolean(memoryOptimization)) { ortSession.setMemoryPatternOptimization(true); } String cpuArena = (String) options.get("cpuArenaAllocator"); if (Boolean.parseBoolean(cpuArena)) { ortSession.setCPUArenaAllocator(true); } String disablePerSessionThreads = (String) options.get("disablePerSessionThreads"); if (Boolean.parseBoolean(disablePerSessionThreads)) { ortSession.disablePerSessionThreads(); } String customOpLibrary = (String) options.get("customOpLibrary"); if (customOpLibrary == null) { customOpLibrary = getOrtxLibraryPath(); } if (customOpLibrary != null) { ortSession.registerCustomOpLibrary(customOpLibrary); } String profilerOutput = (String) options.get("profilerOutput"); if (profilerOutput != null) { ortSession.enableProfiling(profilerOutput); } Device device = manager.getDevice(); if (options.containsKey("ortDevice")) { String ortDevice = (String) options.get("ortDevice"); switch (ortDevice) { case "TensorRT": if (!device.isGpu()) { throw new IllegalArgumentException("TensorRT required GPU device."); } ortSession.addTensorrt(device.getDeviceId()); break; case "ROCM": ortSession.addROCM(); break; case "CoreML": ortSession.addCoreML(); break; default: throw new IllegalArgumentException("Invalid ortDevice: " + ortDevice); } } else if (device.isGpu()) { ortSession.addCUDA(device.getDeviceId()); } return ortSession; } private String getOrtxLibraryPath() { ClassLoader cl = ClassLoaderUtils.getContextClassLoader(); try { Class<?> clazz = Class.forName("ai.onnxruntime.extensions.OrtxPackage", true, cl); Method method = clazz.getDeclaredMethod("getLibraryPath"); return (String) method.invoke(null); } catch (Throwable e) { logger.info("Onnx extension not found in classpath."); logger.trace("Failed to load onnx extension", e); } return null; } }
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/engine/OrtNDArray.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.onnxruntime.engine; import ai.djl.engine.EngineException; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDArrayAdapter; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.onnxruntime.OnnxTensor; import ai.onnxruntime.OrtException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.util.concurrent.atomic.AtomicReference; /** {@code OrtNDArray} is the ONNX Runtime implementation of {@link NDArray}. */ public class OrtNDArray extends NDArrayAdapter { private AtomicReference<OnnxTensor> tensor; /** * Constructs an ONNX Runtime NDArray from a {@link OnnxTensor} (internal. Use {@link NDManager} * instead). * * @param manager the manager to attach the new array to * @param alternativeManager the alternative manager to execute unsupported operation * @param tensor the {@link OnnxTensor} to the ONNX Runtime */ OrtNDArray(OrtNDManager manager, NDManager alternativeManager, OnnxTensor tensor) { super(manager, alternativeManager, null, null, NDManager.nextUid()); this.tensor = new AtomicReference<>(tensor); manager.attachInternal(uid, this); } /** * Returns the {@code OnnxTensor} representation of this OrtNDArray. * * @return the {@code OnnxTensor} representation of this OrtNDArray */ public OnnxTensor getTensor() { return tensor.get(); } /** {@inheritDoc} */ @Override public DataType getDataType() { if (isClosed) { throw new IllegalStateException("Native resource has been release already."); } if (dataType == null) { dataType = OrtUtils.toDataType(tensor.get().getInfo().type); } return dataType; } /** {@inheritDoc} */ @Override public Shape getShape() { if (isClosed) { throw new IllegalStateException("Native resource has been release already."); } if (shape == null) { shape = new Shape(tensor.get().getInfo().getShape()); } return shape; } /** {@inheritDoc} */ @Override public void intern(NDArray replaced) { OrtNDArray arr = (OrtNDArray) replaced; OnnxTensor oldHandle = tensor.getAndSet(arr.tensor.getAndSet(null)); if (oldHandle != null) { oldHandle.close(); } replaced.close(); } /** {@inheritDoc} */ @Override public void detach() { manager.detachInternal(getUid()); manager = OrtNDManager.getSystemManager(); } /** {@inheritDoc} */ @Override public String[] toStringArray(Charset charset) { if (isClosed) { throw new IllegalStateException("Native resource has been release already."); } try { Object obj = tensor.get().getValue(); if (obj instanceof String) { // Scalar type; return new String[] {(String) obj}; } else if (obj instanceof String[]) { return (String[]) obj; } else if (obj instanceof String[][]) { String[][] data = (String[][]) obj; if (data.length == 0) { return new String[0]; } String[] ret = new String[data.length * data[0].length]; for (int i = 0; i < data.length; ++i) { System.arraycopy(data[i], 0, ret, i * data.length, data[i].length); } return ret; } else { throw new UnsupportedOperationException("Unsupported Data type: " + obj.getClass()); } } catch (OrtException e) { throw new EngineException(e); } } /** {@inheritDoc} */ @Override public ByteBuffer toByteBuffer(boolean tryDirect) { if (getDataType() == DataType.STRING) { throw new IllegalArgumentException("Please use toStringArray() for String NDArray."); } return tensor.get().getByteBuffer().order(ByteOrder.nativeOrder()); } /** {@inheritDoc} */ @Override public void close() { OnnxTensor ortTensor = tensor.getAndSet(null); if (ortTensor != null) { ortTensor.close(); } super.close(); } }
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/engine/OrtNDManager.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.onnxruntime.engine; import ai.djl.Device; import ai.djl.engine.Engine; import ai.djl.engine.EngineException; import ai.djl.ndarray.BaseNDManager; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.onnxruntime.OnnxTensor; import ai.onnxruntime.OrtEnvironment; import ai.onnxruntime.OrtException; import ai.onnxruntime.OrtUtil; import ai.onnxruntime.TensorInfo; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; /** {@code OrtNDManager} is the ONNX Runtime implementation of {@link NDManager}. */ public class OrtNDManager extends BaseNDManager { private static final OrtNDManager SYSTEM_MANAGER = new SystemManager(); private OrtEnvironment env; private OrtNDManager(NDManager parent, Device device, OrtEnvironment env) { super(parent, device); this.env = env; } static OrtNDManager getSystemManager() { return SYSTEM_MANAGER; } /** {@inheritDoc} */ @Override public ByteBuffer allocateDirect(int capacity) { return ByteBuffer.allocateDirect(capacity).order(ByteOrder.nativeOrder()); } /** {@inheritDoc} */ @Override public OrtNDArray from(NDArray array) { if (array == null || array instanceof OrtNDArray) { return (OrtNDArray) array; } OrtNDArray result; if (array.getDataType() == DataType.BOOLEAN) { result = create(array.toBooleanArray()); } else { result = create(array.toByteBuffer(), array.getShape(), array.getDataType()); } result.setName(array.getName()); return result; } OrtNDArray createInternal(OnnxTensor tensor) { return new OrtNDArray(this, alternativeManager, tensor); } /** {@inheritDoc} */ @Override public OrtNDArray create(Buffer data, Shape shape, DataType dataType) { if (dataType == DataType.STRING) { throw new IllegalArgumentException( "Use NDManager.create(String[], Shape) to create String NDArray."); } int size = Math.toIntExact(shape.size()); BaseNDManager.validateBuffer(data, dataType, size); OnnxTensor tensor = OrtUtils.toTensor(env, data, shape, dataType); return new OrtNDArray(this, alternativeManager, tensor); } /** {@inheritDoc} */ @Override public OrtNDArray create(boolean[] data) { try { return new OrtNDArray(this, alternativeManager, OrtUtils.toTensor(env, data)); } catch (OrtException e) { throw new EngineException(e); } } /** {@inheritDoc} */ @Override public OrtNDArray create(boolean[] data, Shape shape) { long[] sh = shape.getShape(); if (sh.length == 0 || sh.length > TensorInfo.MAX_DIMENSIONS) { throw new UnsupportedOperationException( "Arrays with less than 1 and greater than " + TensorInfo.MAX_DIMENSIONS + " dimensions are not supported."); } Object tensorIn; if (sh.length != 1) { tensorIn = OrtUtil.reshape(data, sh); } else { // Work around the bug in OrtUtil.reshape() when sh.length == 1. long[] shExpanded = {1, sh[0]}; boolean[][] arrayIn = (boolean[][]) OrtUtil.reshape(data, shExpanded); tensorIn = arrayIn[0]; } try { return new OrtNDArray(this, alternativeManager, OrtUtils.toTensor(env, tensorIn)); } catch (OrtException e) { throw new EngineException(e); } } /** {@inheritDoc} */ @Override public NDArray create(String data) { return create(new String[] {data}); } /** {@inheritDoc} */ @Override public NDArray create(String[] data) { return create(data, new Shape(data.length)); } /** {@inheritDoc} */ @Override public NDArray create(String[] data, Charset charset, Shape shape) { try { return new OrtNDArray(this, alternativeManager, OrtUtils.toTensor(env, data, shape)); } catch (OrtException e) { throw new EngineException(e); } } /** {@inheritDoc} */ @Override public OrtNDManager newSubManager(Device device) { OrtNDManager manager = new OrtNDManager(this, device, env); attachInternal(manager.uid, manager); return manager; } /** {@inheritDoc} */ @Override public final Engine getEngine() { return Engine.getEngine(OrtEngine.ENGINE_NAME); } /** {@inheritDoc} */ @Override public void close() { super.close(); if (alternativeManager != null) { alternativeManager.close(); alternativeManager = null; } } /** The SystemManager is the root {@link OrtNDManager} of which all others are children. */ private static final class SystemManager extends OrtNDManager implements SystemNDManager { SystemManager() { super(null, null, ((OrtEngine) Engine.getEngine(OrtEngine.ENGINE_NAME)).getEnv()); } /** {@inheritDoc} */ @Override public void close() {} } }
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/engine/OrtSymbolBlock.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.onnxruntime.engine; import ai.djl.engine.EngineException; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.nn.AbstractSymbolBlock; import ai.djl.nn.ParameterList; import ai.djl.nn.SymbolBlock; import ai.djl.training.ParameterStore; import ai.djl.util.PairList; import ai.onnxruntime.OnnxJavaType; import ai.onnxruntime.OnnxMap; import ai.onnxruntime.OnnxModelMetadata; import ai.onnxruntime.OnnxSequence; import ai.onnxruntime.OnnxTensor; import ai.onnxruntime.OnnxValue; import ai.onnxruntime.OrtException; import ai.onnxruntime.OrtSession; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * {@code OrtSymbolBlock} is the ONNX Runtime implementation of {@link SymbolBlock}. * * <p>You can create a {@code OrtSymbolBlock} using {@link ai.djl.Model#load(java.nio.file.Path, * String)}. */ public class OrtSymbolBlock extends AbstractSymbolBlock implements AutoCloseable { private OrtSession session; private OrtNDManager manager; /** * Constructs a {@code OrtSymbolBlock}. * * <p>You can create a {@code PtSymbolBlock} using {@link ai.djl.Model#load(java.nio.file.Path, * String)}. * * @param session the {@link OrtSession} contains the model information * @param manager the {@link NDManager} to holds the NDArray */ @SuppressWarnings("this-escape") public OrtSymbolBlock(OrtSession session, OrtNDManager manager) { this.session = session; this.manager = manager; manager.attachInternal(NDManager.nextUid(), this); } /** {@inheritDoc} */ @Override public void removeLastBlock() { throw new UnsupportedOperationException("ONNX Runtime not supported"); } /** {@inheritDoc} */ @Override protected NDList forwardInternal( ParameterStore parameterStore, NDList inputs, boolean training, PairList<String, Object> params) { List<String> inputNames = new ArrayList<>(session.getInputNames()); if (inputs.size() != inputNames.size()) { throw new IllegalArgumentException("Input mismatch, looking for: " + inputNames); } Map<String, OnnxTensor> container = new ConcurrentHashMap<>(); // forward try (OrtNDManager sub = (OrtNDManager) manager.newSubManager()) { // If input data has name if (inputs.get(0).getName() != null) { for (NDArray input : inputs) { String name = input.getName(); if (name == null) { throw new IllegalArgumentException( "All or none of input tensors must have a name."); } if (!inputNames.contains(name)) { throw new IllegalArgumentException("Invalid input tensor name: " + name); } OrtNDArray ortNDArray = sub.from(input); container.put(name, ortNDArray.getTensor()); } } else { // feed data in to match names for (int i = 0; i < inputNames.size(); ++i) { OrtNDArray ortNDArray = sub.from(inputs.get(i)); container.put(inputNames.get(i), ortNDArray.getTensor()); } } OrtSession.Result results = session.run(container); NDList ret = evaluateOutput(results); ret.attach(inputs.head().getManager()); return ret; } catch (OrtException e) { throw new EngineException(e); } } /** {@inheritDoc} */ @Override public PairList<String, Shape> describeInput() { PairList<String, Shape> result = new PairList<>(); for (String name : session.getInputNames()) { result.add(name, null); } return result; } /** {@inheritDoc} */ @Override public Map<String, String> getCustomMetadata() { try { OnnxModelMetadata modelMetadata = session.getMetadata(); return modelMetadata.getCustomMetadata(); } catch (OrtException e) { throw new EngineException(e); } } private NDList evaluateOutput(OrtSession.Result results) { NDList output = new NDList(); for (Map.Entry<String, OnnxValue> r : results) { OnnxValue value = r.getValue(); if ((value instanceof OnnxTensor)) { NDArray array = manager.createInternal((OnnxTensor) value); array.setName(r.getKey()); output.add(array); } else if (value instanceof OnnxSequence) { // TODO: avoid memory copying to heap OnnxSequence seq = (OnnxSequence) value; if (seq.getInfo().isSequenceOfMaps()) { NDArray array = seq2Nd(seq); array.setName(r.getKey()); output.add(array); } else { output.addAll(seq2NdList(seq)); } } else { throw new UnsupportedOperationException("Unsupported output type! " + r.getKey()); } } return output; } @SuppressWarnings("unchecked") private NDArray seq2Nd(OnnxSequence seq) { try { List<OnnxMap> values = (List<OnnxMap>) seq.getValue(); DataType dp; List<Object> finalData = new ArrayList<>(); OnnxJavaType type = seq.getInfo().mapInfo.valueType; for (OnnxMap map : values) { finalData.addAll(((Map<Object, Object>) map.getValue()).values()); } Shape shape = new Shape(values.size(), finalData.size() / values.size()); ByteBuffer buffer = ByteBuffer.allocate(finalData.size() * type.size); switch (type) { case FLOAT: finalData.forEach(ele -> buffer.putFloat((Float) ele)); buffer.rewind(); return manager.create(buffer.asFloatBuffer(), shape, DataType.FLOAT32); case DOUBLE: finalData.forEach(ele -> buffer.putDouble((Double) ele)); buffer.rewind(); return manager.create(buffer.asDoubleBuffer(), shape, DataType.FLOAT64); case BOOL: case INT8: dp = (type == OnnxJavaType.BOOL) ? DataType.BOOLEAN : DataType.INT8; finalData.forEach(ele -> buffer.put((Byte) ele)); buffer.rewind(); return manager.create(buffer, shape, dp); case INT32: finalData.forEach(ele -> buffer.putInt((Integer) ele)); buffer.rewind(); return manager.create(buffer.asIntBuffer(), shape, DataType.INT32); case INT64: finalData.forEach(ele -> buffer.putLong((Long) ele)); buffer.rewind(); return manager.create(buffer.asLongBuffer(), shape, DataType.INT64); default: throw new UnsupportedOperationException("type is not supported: " + type); } } catch (OrtException e) { throw new EngineException(e); } } private NDList seq2NdList(OnnxSequence sequence) { try { NDList list = new NDList(); for (OnnxValue value : sequence.getValue()) { list.add(manager.createInternal((OnnxTensor) value)); } return list; } catch (OrtException e) { throw new EngineException(e); } } /** {@inheritDoc} */ @Override public void close() { if (session != null) { try { session.close(); session = null; } catch (OrtException e) { throw new EngineException(e); } } } /** {@inheritDoc} */ @Override public ParameterList getDirectParameters() { throw new UnsupportedOperationException("Not yet supported"); } }
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/engine/OrtUtils.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.onnxruntime.engine; import ai.djl.engine.EngineException; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.onnxruntime.OnnxJavaType; import ai.onnxruntime.OnnxTensor; import ai.onnxruntime.OrtEnvironment; import ai.onnxruntime.OrtException; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; final class OrtUtils { private OrtUtils() {} public static OnnxTensor toTensor( OrtEnvironment env, Buffer data, Shape shape, DataType dataType) { long[] sh = shape.getShape(); try { switch (dataType) { case FLOAT32: return OnnxTensor.createTensor(env, asFloatBuffer(data), sh); case FLOAT64: return OnnxTensor.createTensor(env, asDoubleBuffer(data), sh); case FLOAT16: return OnnxTensor.createTensor( env, (ByteBuffer) data, sh, OnnxJavaType.FLOAT16); case BFLOAT16: return OnnxTensor.createTensor( env, (ByteBuffer) data, sh, OnnxJavaType.BFLOAT16); case INT32: return OnnxTensor.createTensor(env, asIntBuffer(data), sh); case INT64: return OnnxTensor.createTensor(env, asLongBuffer(data), sh); case INT8: return OnnxTensor.createTensor(env, (ByteBuffer) data, sh, OnnxJavaType.INT8); case UINT8: return OnnxTensor.createTensor(env, (ByteBuffer) data, sh, OnnxJavaType.UINT8); case BOOLEAN: return OnnxTensor.createTensor(env, (ByteBuffer) data, sh, OnnxJavaType.BOOL); case STRING: throw new UnsupportedOperationException( "Use toTensor(OrtEnvironment env, String[] inputs, Shape shape)" + " instead."); default: throw new UnsupportedOperationException("Data type not supported: " + dataType); } } catch (OrtException e) { throw new EngineException(e); } } public static OnnxTensor toTensor(OrtEnvironment env, String[] inputs, Shape shape) throws OrtException { return OnnxTensor.createTensor(env, inputs, shape.getShape()); } public static OnnxTensor toTensor(OrtEnvironment env, Object inputs) throws OrtException { return OnnxTensor.createTensor(env, inputs); } public static DataType toDataType(OnnxJavaType javaType) { switch (javaType) { case FLOAT: return DataType.FLOAT32; case FLOAT16: return DataType.FLOAT16; case BFLOAT16: return DataType.BFLOAT16; case DOUBLE: return DataType.FLOAT64; case INT8: return DataType.INT8; case UINT8: return DataType.UINT8; case INT32: return DataType.INT32; case INT64: return DataType.INT64; case BOOL: return DataType.BOOLEAN; case UNKNOWN: return DataType.UNKNOWN; case STRING: return DataType.STRING; default: throw new UnsupportedOperationException("type is not supported: " + javaType); } } private static FloatBuffer asFloatBuffer(Buffer data) { if (data instanceof ByteBuffer) { return ((ByteBuffer) data).asFloatBuffer(); } return (FloatBuffer) data; } private static DoubleBuffer asDoubleBuffer(Buffer data) { if (data instanceof ByteBuffer) { return ((ByteBuffer) data).asDoubleBuffer(); } return (DoubleBuffer) data; } private static IntBuffer asIntBuffer(Buffer data) { if (data instanceof ByteBuffer) { return ((ByteBuffer) data).asIntBuffer(); } return (IntBuffer) data; } private static LongBuffer asLongBuffer(Buffer data) { if (data instanceof ByteBuffer) { return ((ByteBuffer) data).asLongBuffer(); } return (LongBuffer) data; } }
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/engine/package-info.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** Contains classes to interface with the underlying ONNXRuntime Engine. */ package ai.djl.onnxruntime.engine;
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/zoo/OrtHfModelZoo.java
/* * Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.onnxruntime.zoo; import ai.djl.Application; import ai.djl.engine.Engine; import ai.djl.repository.RemoteRepository; import ai.djl.repository.Repository; import ai.djl.repository.Version; import ai.djl.repository.VersionRange; import ai.djl.repository.zoo.ModelLoader; import ai.djl.repository.zoo.ModelZoo; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Set; /** OrtHfModelZoo is a repository that contains HuggingFace models for OnnxRuntime. */ public class OrtHfModelZoo extends ModelZoo { private static final Repository REPOSITORY = new RemoteRepository("Huggingface", DJL_REPO_URL); private static final String GROUP_ID = "ai.djl.huggingface.onnxruntime"; private volatile boolean initialized; // NOPMD OrtHfModelZoo() {} /** {@inheritDoc} */ @Override public String getGroupId() { return GROUP_ID; } /** {@inheritDoc} */ @Override public Set<String> getSupportedEngines() { return Collections.singleton("OnnxRuntime"); } /** {@inheritDoc} */ @Override public Collection<ModelLoader> getModelLoaders() { init(); return super.getModelLoaders(); } /** {@inheritDoc} */ @Override public ModelLoader getModelLoader(String name) { init(); return super.getModelLoader(name); } private void init() { if (!initialized) { synchronized (OrtHfModelZoo.class) { if (!initialized) { Version version = new Version(Engine.getDjlVersion()); addModels(Application.NLP.FILL_MASK, version); addModels(Application.NLP.QUESTION_ANSWER, version); addModels(Application.NLP.TEXT_CLASSIFICATION, version); addModels(Application.NLP.TEXT_EMBEDDING, version); addModels(Application.NLP.TOKEN_CLASSIFICATION, version); addModels(Application.NLP.ZERO_SHOT_CLASSIFICATION, version); initialized = true; } } } } private void addModels(Application app, Version version) { Map<String, Map<String, Object>> map = listModels(REPOSITORY, app); for (Map.Entry<String, Map<String, Object>> entry : map.entrySet()) { Map<String, Object> model = entry.getValue(); if ("failed".equals(model.get("result"))) { continue; } String requires = (String) model.get("requires"); if (requires != null) { // the model requires specific DJL version VersionRange range = VersionRange.parse(requires); if (!range.contains(version)) { continue; } } String artifactId = entry.getKey(); addModel(REPOSITORY.model(app, GROUP_ID, artifactId, "0.0.1")); } } }
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/zoo/OrtHfZooProvider.java
/* * Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.onnxruntime.zoo; import ai.djl.repository.zoo.ModelZoo; import ai.djl.repository.zoo.ZooProvider; /** * An Huggingface model zoo provider for OnnxRuntime implements the {@link * ai.djl.repository.zoo.ZooProvider} interface. */ public class OrtHfZooProvider implements ZooProvider { /** {@inheritDoc} */ @Override public ModelZoo getModelZoo() { return new OrtHfModelZoo(); } }
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/zoo/OrtModelZoo.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.onnxruntime.zoo; import ai.djl.Application.CV; import ai.djl.Application.Tabular; import ai.djl.onnxruntime.engine.OrtEngine; import ai.djl.repository.RemoteRepository; import ai.djl.repository.Repository; import ai.djl.repository.zoo.ModelZoo; import java.util.Collections; import java.util.Set; /** OrtModelZoo is a repository that contains all Onnx models for DJL. */ public class OrtModelZoo extends ModelZoo { private static final Repository REPOSITORY = new RemoteRepository("Ort", DJL_REPO_URL); public static final String GROUP_ID = "ai.djl.onnxruntime"; OrtModelZoo() { addModel(REPOSITORY.model(CV.IMAGE_CLASSIFICATION, GROUP_ID, "resnet", "0.0.1")); addModel(REPOSITORY.model(CV.INSTANCE_SEGMENTATION, GROUP_ID, "yolo11n-seg", "0.0.1")); addModel(REPOSITORY.model(CV.INSTANCE_SEGMENTATION, GROUP_ID, "yolov8n-seg", "0.0.1")); addModel(REPOSITORY.model(CV.MASK_GENERATION, GROUP_ID, "sam2-hiera-base-plus", "0.0.1")); addModel(REPOSITORY.model(CV.MASK_GENERATION, GROUP_ID, "sam2-hiera-large", "0.0.1")); addModel(REPOSITORY.model(CV.MASK_GENERATION, GROUP_ID, "sam2-hiera-small", "0.0.1")); addModel(REPOSITORY.model(CV.MASK_GENERATION, GROUP_ID, "sam2-hiera-tiny", "0.0.1")); addModel(REPOSITORY.model(CV.OBJECT_DETECTION, GROUP_ID, "yolo11n", "0.0.1")); addModel(REPOSITORY.model(CV.OBJECT_DETECTION, GROUP_ID, "yolo5s", "0.0.1")); addModel(REPOSITORY.model(CV.OBJECT_DETECTION, GROUP_ID, "yolov8n", "0.0.1")); addModel(REPOSITORY.model(CV.POSE_ESTIMATION, GROUP_ID, "yolo11n-pose", "0.0.1")); addModel(REPOSITORY.model(CV.POSE_ESTIMATION, GROUP_ID, "yolov8n-pose", "0.0.1")); addModel(REPOSITORY.model(Tabular.SOFTMAX_REGRESSION, GROUP_ID, "iris_flowers", "0.0.1")); } /** {@inheritDoc} */ @Override public String getGroupId() { return GROUP_ID; } /** {@inheritDoc} */ @Override public Set<String> getSupportedEngines() { return Collections.singleton(OrtEngine.ENGINE_NAME); } }
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/zoo/OrtZooProvider.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.onnxruntime.zoo; import ai.djl.repository.zoo.ModelZoo; import ai.djl.repository.zoo.ZooProvider; /** * An Onnx Runtime model zoo provider implements the {@link ai.djl.repository.zoo.ZooProvider} * interface. */ public class OrtZooProvider implements ZooProvider { /** {@inheritDoc} */ @Override public ModelZoo getModelZoo() { return new OrtModelZoo(); } }
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/zoo/package-info.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** Contains the built-in {@link ai.djl.onnxruntime.zoo.OrtModelZoo}. */ package ai.djl.onnxruntime.zoo;
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/zoo/nlp
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/zoo/nlp/textgeneration/OrtGptTranslator.java
/* * Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.onnxruntime.zoo.nlp.textgeneration; import ai.djl.modality.nlp.generate.CausalLMOutput; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.Shape; import ai.djl.translate.NoBatchifyTranslator; import ai.djl.translate.TranslatorContext; /** The {@link ai.djl.translate.Translator} for PyTorch GPT2 model. */ public class OrtGptTranslator implements NoBatchifyTranslator<NDList, CausalLMOutput> { private long kvDim; private int numAttentionHeads; private int numLayers; /** * Constructs a new instance of {@code PtGptTranslator}. * * @param kvDim the kv dimension * @param numAttentionHeads the number of attention heads * @param numLayers the number of layers */ public OrtGptTranslator(long kvDim, int numAttentionHeads, int numLayers) { this.kvDim = kvDim; this.numAttentionHeads = numAttentionHeads; this.numLayers = numLayers; } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, NDList input) throws Exception { // input = [inputIds, posIds, attnMask] NDManager manager = ctx.getNDManager(); NDArray inputIds = input.get(0); inputIds.setName("input_ids"); NDArray attentionMask = input.get(2); attentionMask.setName("attention_mask"); NDList inputNew; if (input.size() == 3) { // pastKeyValue == null NDArray useCacheBranch = manager.create(new boolean[] {false}, new Shape(1)); useCacheBranch.setName("use_cache_branch"); inputNew = new NDList(inputIds, attentionMask, useCacheBranch); initialDummyPastKeyValues(inputIds, manager, inputNew); } else { NDArray useCacheBranch = manager.create(new boolean[] {true}, new Shape(1)); useCacheBranch.setName("use_cache_branch"); inputNew = new NDList(inputIds, attentionMask, useCacheBranch); inputNew.addAll(input.subNDList(3)); } int offset = 3; for (int i = offset; i < numLayers * 2 + offset; i += 2) { int order = (i - offset) / 2; inputNew.get(i).setName(String.format("past_key_values.%s.key", order)); inputNew.get(i + 1).setName(String.format("past_key_values.%s.value", order)); } return inputNew; } /** {@inheritDoc} */ @Override public CausalLMOutput processOutput(TranslatorContext ctx, NDList output) throws Exception { return new CausalLMOutput(output.get(0), output.subNDList(1)); } private void initialDummyPastKeyValues(NDArray inputIds, NDManager manager, NDList list) { long numBatch = inputIds.getShape().get(0); for (int i = 0; i < numLayers * 2; ++i) { NDArray array = manager.zeros(new Shape(numBatch, numAttentionHeads, 1, kvDim)); list.add(array); } } }
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/zoo/nlp
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/zoo/nlp/textgeneration/OrtGptTranslatorFactory.java
/* * Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.onnxruntime.zoo.nlp.textgeneration; import ai.djl.Model; import ai.djl.modality.nlp.generate.CausalLMOutput; import ai.djl.ndarray.NDList; import ai.djl.translate.ArgumentsUtil; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorFactory; import ai.djl.util.Pair; import java.lang.reflect.Type; import java.util.HashSet; import java.util.Map; import java.util.Set; /** An {@link TranslatorFactory} that creates a {@link OrtGptTranslator} instance. */ public class OrtGptTranslatorFactory implements TranslatorFactory { private static final Set<Pair<Type, Type>> SUPPORTED_TYPES = new HashSet<>(); static { SUPPORTED_TYPES.add(new Pair<>(NDList.class, CausalLMOutput.class)); } /** {@inheritDoc} */ @Override public Set<Pair<Type, Type>> getSupportedTypes() { return SUPPORTED_TYPES; } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public <I, O> Translator<I, O> newInstance( Class<I> input, Class<O> output, Model model, Map<String, ?> arguments) { if (!isSupported(input, output)) { throw new IllegalArgumentException("Unsupported input/output types."); } long kvDim = ArgumentsUtil.longValue(arguments, "kvDim", 64); int numAttentionHeads = ArgumentsUtil.intValue(arguments, "numAttentionHeads", 12); int numLayers = ArgumentsUtil.intValue(arguments, "numLayers", 12); return (Translator<I, O>) (new OrtGptTranslator(kvDim, numAttentionHeads, numLayers)); } }
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/zoo/nlp
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/zoo/nlp/textgeneration/package-info.java
/* * Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** Contains classes for the {@link ai.djl.Application.NLP#TEXT_GENERATION} models. */ package ai.djl.onnxruntime.zoo.nlp.textgeneration;
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/zoo/tabular
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/zoo/tabular/softmax_regression/IrisClassificationTranslatorFactory.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.onnxruntime.zoo.tabular.softmax_regression; import ai.djl.Model; import ai.djl.modality.Classifications; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.types.Shape; import ai.djl.translate.NoBatchifyTranslator; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; import ai.djl.translate.TranslatorFactory; import ai.djl.util.Pair; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; /** A {@link TranslatorFactory} that creates a {@link IrisTranslator} instance. */ public class IrisClassificationTranslatorFactory implements TranslatorFactory { /** {@inheritDoc} */ @Override public Set<Pair<Type, Type>> getSupportedTypes() { return Collections.singleton(new Pair<>(IrisFlower.class, Classifications.class)); } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public <I, O> Translator<I, O> newInstance( Class<I> input, Class<O> output, Model model, Map<String, ?> arguments) { if (!isSupported(input, output)) { throw new IllegalArgumentException("Unsupported input/output types."); } return (Translator<I, O>) new IrisTranslator(); } private static final class IrisTranslator implements NoBatchifyTranslator<IrisFlower, Classifications> { private List<String> synset; public IrisTranslator() { // species name synset = Arrays.asList("setosa", "versicolor", "virginica"); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, IrisFlower input) { float[] data = { input.getSepalLength(), input.getSepalWidth(), input.getPetalLength(), input.getPetalWidth() }; NDArray array = ctx.getNDManager().create(data, new Shape(1, 4)); return new NDList(array); } /** {@inheritDoc} */ @Override public Classifications processOutput(TranslatorContext ctx, NDList list) { float[] data = list.get(1).toFloatArray(); List<Double> probabilities = new ArrayList<>(data.length); for (float f : data) { probabilities.add((double) f); } return new Classifications(synset, probabilities); } } }
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/zoo/tabular
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/zoo/tabular/softmax_regression/IrisFlower.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.onnxruntime.zoo.tabular.softmax_regression; /** A class holds the iris flower features. */ public class IrisFlower { private float sepalLength; private float sepalWidth; private float petalLength; private float petalWidth; /** * Constructs a new {@code IrisFlower} instance. * * @param sepalLength the sepal length * @param sepalWidth the sepal width * @param petalLength the petal length * @param petalWidth the petal width */ public IrisFlower(float sepalLength, float sepalWidth, float petalLength, float petalWidth) { this.sepalLength = sepalLength; this.sepalWidth = sepalWidth; this.petalLength = petalLength; this.petalWidth = petalWidth; } /** * Returns the sepal length. * * @return the sepal length */ public float getSepalLength() { return sepalLength; } /** * Returns the sepal width. * * @return the sepal width */ public float getSepalWidth() { return sepalWidth; } /** * Returns the petal length. * * @return the petal length */ public float getPetalLength() { return petalLength; } /** * Returns the petal width. * * @return the petal width */ public float getPetalWidth() { return petalWidth; } }
0
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/zoo/tabular
java-sources/ai/djl/onnxruntime/onnxruntime-engine/0.34.0/ai/djl/onnxruntime/zoo/tabular/softmax_regression/package-info.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** * Contains classes for the classification models in the {@link ai.djl.onnxruntime.zoo.OrtModelZoo}. */ package ai.djl.onnxruntime.zoo.tabular.softmax_regression;
0
java-sources/ai/djl/opencv/opencv/0.34.0/ai/djl
java-sources/ai/djl/opencv/opencv/0.34.0/ai/djl/opencv/OpenCVImage.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.opencv; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.output.BoundingBox; import ai.djl.modality.cv.output.DetectedObjects; import ai.djl.modality.cv.output.Joints; import ai.djl.modality.cv.output.Landmark; import ai.djl.modality.cv.output.Mask; import ai.djl.modality.cv.output.Rectangle; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.util.RandomUtils; import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.MatOfByte; import org.opencv.core.MatOfPoint; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.core.Size; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.awt.image.DataBuffer; import java.awt.image.DataBufferByte; import java.awt.image.DataBufferInt; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; /** {@code OpenCVImage} is a high performance implementation of {@link Image}. */ class OpenCVImage implements Image { private Mat image; /** * Constructs a new {@code OpenCVImage} instance. * * @param image the wrapped image */ public OpenCVImage(Mat image) { this.image = image; } /** {@inheritDoc} */ @Override public int getWidth() { return image.width(); } /** {@inheritDoc} */ @Override public int getHeight() { return image.height(); } /** {@inheritDoc} */ @Override public Mat getWrappedImage() { return image; } /** {@inheritDoc} */ @Override public OpenCVImage resize(int width, int height, boolean copy) { if (!copy && image.width() == width && image.height() == height) { return this; } Mat resized = new Mat(); Imgproc.resize(image, resized, new Size(width, height)); return new OpenCVImage(resized); } /** {@inheritDoc} */ @Override public Image getMask(int[][] mask) { int w = mask[0].length; int h = mask.length; OpenCVImage resized = resize(w, h, false); Mat img = resized.getWrappedImage(); Mat ret = new Mat(h, w, CvType.CV_8UC4); for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { if (mask[y][x] != 0) { double[] data = img.get(y, x); ret.put(y, x, data[0], data[1], data[2], 255); } } } return new OpenCVImage(ret); } /** {@inheritDoc} */ @Override public Image getSubImage(int x, int y, int w, int h) { Mat mat = image.submat(new Rect(x, y, w, h)); return new OpenCVImage(mat); } /** {@inheritDoc} */ @Override public Image duplicate() { Mat mat = new Mat(); image.copyTo(mat); return new OpenCVImage(mat); } /** {@inheritDoc} */ @Override public NDArray toNDArray(NDManager manager, Flag flag) { Mat mat = new Mat(); if (flag == Flag.GRAYSCALE) { Imgproc.cvtColor(image, mat, Imgproc.COLOR_BGR2GRAY); } else { Imgproc.cvtColor(image, mat, Imgproc.COLOR_BGR2RGB); } byte[] buf = new byte[mat.height() * mat.width() * mat.channels()]; mat.get(0, 0, buf); Shape shape = new Shape(mat.height(), mat.width(), mat.channels()); return manager.create(ByteBuffer.wrap(buf), shape, DataType.UINT8); } /** {@inheritDoc} */ @Override public void save(OutputStream os, String type) throws IOException { MatOfByte buf = new MatOfByte(); if (!Imgcodecs.imencode('.' + type, image, buf)) { throw new IOException("Failed save image."); } os.write(buf.toArray()); } /** {@inheritDoc} */ @Override public void drawBoundingBoxes(DetectedObjects detections, float opacity) { int imageWidth = image.width(); int imageHeight = image.height(); List<DetectedObjects.DetectedObject> list = detections.items(); for (DetectedObjects.DetectedObject result : list) { String className = result.getClassName(); BoundingBox box = result.getBoundingBox(); Rectangle rectangle = box.getBounds(); int x = (int) (rectangle.getX() * imageWidth); int y = (int) (rectangle.getY() * imageHeight); Rect rect = new Rect( x, y, (int) (rectangle.getWidth() * imageWidth), (int) (rectangle.getHeight() * imageHeight)); Scalar color = new Scalar( RandomUtils.nextInt(178), RandomUtils.nextInt(178), RandomUtils.nextInt(178)); Imgproc.rectangle(image, rect.tl(), rect.br(), color, 2); Size size = Imgproc.getTextSize(className, Imgproc.FONT_HERSHEY_PLAIN, 1.3, 1, null); Point br = new Point(x + size.width + 4, y + size.height + 4); Imgproc.rectangle(image, rect.tl(), br, color, -1); Point point = new Point(x, y + size.height + 2); color = new Scalar(255, 255, 255); Imgproc.putText(image, className, point, Imgproc.FONT_HERSHEY_PLAIN, 1.3, color, 1); // If we have a mask instead of a plain rectangle, draw tha mask if (box instanceof Mask) { Mask mask = (Mask) box; BufferedImage img = mat2Image(image); drawMask(img, mask, 0.5f); image = image2Mat(img); } else if (box instanceof Landmark) { drawLandmarks(box); } } } /** {@inheritDoc} */ @Override public void drawRectangle(Rectangle rectangle, int rgb, int stroke) { Rect rect = new Rect( (int) rectangle.getX(), (int) rectangle.getY(), (int) rectangle.getWidth(), (int) rectangle.getHeight()); int r = (rgb & 0xff0000) >> 16; int g = (rgb & 0x00ff00) >> 8; int b = rgb & 0x0000ff; Scalar color = new Scalar(b, g, r); Imgproc.rectangle(image, rect.tl(), rect.br(), color, stroke); } /** {@inheritDoc} */ @Override public void drawMarks(List<ai.djl.modality.cv.output.Point> points, int radius) { Scalar color = new Scalar(190, 150, 37); for (ai.djl.modality.cv.output.Point point : points) { int[][] star = createStar(point, radius); Point[] mat = new Point[10]; for (int i = 0; i < 10; ++i) { mat[i] = new Point(star[0][i], star[1][i]); } MatOfPoint mop = new MatOfPoint(); mop.fromArray(mat); List<MatOfPoint> ppt = Collections.singletonList(mop); Imgproc.fillPoly(image, ppt, color, Imgproc.LINE_AA); } } /** {@inheritDoc} */ @Override public void drawJoints(Joints joints) { int imageWidth = image.width(); int imageHeight = image.height(); List<Joints.Joint> list = joints.getJoints(); if (list.size() == 17) { Scalar color = new Scalar(37, 255, 224); drawLine(list.get(5), list.get(7), imageWidth, imageHeight, color); drawLine(list.get(7), list.get(9), imageWidth, imageHeight, color); drawLine(list.get(6), list.get(8), imageWidth, imageHeight, color); drawLine(list.get(8), list.get(10), imageWidth, imageHeight, color); drawLine(list.get(11), list.get(13), imageWidth, imageHeight, color); drawLine(list.get(12), list.get(14), imageWidth, imageHeight, color); drawLine(list.get(13), list.get(15), imageWidth, imageHeight, color); drawLine(list.get(14), list.get(16), imageWidth, imageHeight, color); drawLine(list.get(5), list.get(6), imageWidth, imageHeight, color); drawLine(list.get(11), list.get(12), imageWidth, imageHeight, color); drawLine(list.get(5), list.get(11), imageWidth, imageHeight, color); drawLine(list.get(6), list.get(12), imageWidth, imageHeight, color); } Scalar color = new Scalar(190, 150, 37); for (Joints.Joint joint : list) { int x = (int) (joint.getX() * imageWidth); int y = (int) (joint.getY() * imageHeight); Point point = new Point(x, y); Imgproc.circle(image, point, 6, color, -1, Imgproc.LINE_AA); } } /** {@inheritDoc} */ @Override public void drawImage(Image overlay, boolean resize) { if (!(overlay instanceof OpenCVImage)) { throw new IllegalArgumentException("Only OpenCVImage allowed"); } if (resize) { overlay = overlay.resize(getWidth(), getHeight(), false); } Mat mat = (Mat) overlay.getWrappedImage(); if (mat.elemSize() != 4) { mat.copyTo(image); return; } int w = Math.min(image.width(), mat.width()); int h = Math.min(image.height(), mat.height()); for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { /* * RA = SA + DA × (1 − SA) * R[0] = (S[0]×SA + D[0]×DA×(1 − SA)) / RA */ double[] src = mat.get(y, x); double[] dest = image.get(y, x); double sa = src[3]; double da; double ra; if (dest.length == 3) { da = 255 - sa; ra = 255; } else { da = dest[3] * (255 - sa) / 255; ra = sa + da; dest[3] = ra; } dest[0] = (src[0] * sa + dest[0] * da) / ra; dest[1] = (src[1] * sa + dest[1] * da) / ra; dest[2] = (src[2] * sa + dest[2] * da) / ra; image.put(y, x, dest); } } } /** {@inheritDoc} */ @Override public List<BoundingBox> findBoundingBoxes() { List<MatOfPoint> points = new ArrayList<>(); Imgproc.findContours( image, points, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE); return points.parallelStream() .map( point -> { Rect rect = Imgproc.boundingRect(point); return new Rectangle( rect.x * 1.0 / image.width(), rect.y * 1.0 / image.height(), rect.width * 1.0 / image.width(), rect.height * 1.0 / image.height()); }) .collect(Collectors.toList()); } /** * Converting from bgr mapping to rgb. * * @return rgb format image */ public OpenCVImage bgr2rgb() { Mat converted = new Mat(); Imgproc.cvtColor(image, converted, Imgproc.COLOR_BGR2RGB); return new OpenCVImage(converted); } /** * Converting from channel-first to channel-last format. * * @return channel last image */ public OpenCVImage chw2hwc() { int c = image.channels(); int h = image.height(); int w = image.width(); Mat cHW = image.reshape(0, new int[] {c, h * w}); Mat result = new Mat(); result.create(h, w, CvType.makeType(image.depth(), c)); result = result.reshape(c, new int[] {h, w}); Core.transpose(cHW, result); return new OpenCVImage(result); } /** * Converting from channel-las tto channel-first format. * * @return channel first image */ public OpenCVImage hwc2chw() { int c = image.channels(); int h = image.height(); int w = image.width(); Mat hWC = image.reshape(1, h * w); Mat result = new Mat(); Core.transpose(hWC, result); result = result.reshape(1, new int[] {c, h, w}); return new OpenCVImage(result); } /** * Apply normalization on the image. * * @param mean mean value apply on each color channel * @param std standard div apply on each color channel * @return converted image */ public OpenCVImage normalize(float[] mean, float[] std) { Mat result = new Mat(); Core.subtract(image, new Scalar(mean[0], mean[1], mean[2]), result); Core.divide(result, new Scalar(std[0], std[1], std[2]), result); return new OpenCVImage(result); } private void drawLine(Joints.Joint from, Joints.Joint to, int width, int height, Scalar color) { int x0 = (int) (from.getX() * width); int y0 = (int) (from.getY() * height); int x1 = (int) (to.getX() * width); int y1 = (int) (to.getY() * height); Imgproc.line(image, new Point(x0, y0), new Point(x1, y1), color, 2, Imgproc.LINE_AA); } private void drawLandmarks(BoundingBox box) { Scalar color = new Scalar(0, 96, 246); for (ai.djl.modality.cv.output.Point point : box.getPath()) { Point lt = new Point(point.getX() - 4, point.getY() - 4); Point rb = new Point(point.getX() + 4, point.getY() + 4); Imgproc.rectangle(image, lt, rb, color, -1); } } private void drawMask(BufferedImage img, Mask mask, float ratio) { // TODO: use OpenCV native way to draw mask float r = RandomUtils.nextFloat(); float g = RandomUtils.nextFloat(); float b = RandomUtils.nextFloat(); int imageWidth = img.getWidth(); int imageHeight = img.getHeight(); int x = 0; int y = 0; int w = imageWidth; int h = imageHeight; if (!mask.isFullImageMask()) { x = (int) (mask.getX() * imageWidth); y = (int) (mask.getY() * imageHeight); w = (int) (mask.getWidth() * imageWidth); h = (int) (mask.getHeight() * imageHeight); // Correct some coordinates of box when going out of image if (x < 0) { x = 0; } if (y < 0) { y = 0; } } float[][] probDist = mask.getProbDist(); if (ratio < 0 || ratio > 1) { float max = 0; for (float[] row : probDist) { for (float f : row) { max = Math.max(max, f); } } ratio = 0.5f / max; } BufferedImage maskImage = new BufferedImage(probDist[0].length, probDist.length, BufferedImage.TYPE_INT_ARGB); for (int yCor = 0; yCor < probDist.length; yCor++) { for (int xCor = 0; xCor < probDist[0].length; xCor++) { float opacity = probDist[yCor][xCor] * ratio; maskImage.setRGB(xCor, yCor, new Color(r, g, b, opacity).darker().getRGB()); } } java.awt.Image scaled = maskImage.getScaledInstance(w, h, java.awt.Image.SCALE_SMOOTH); Graphics2D gR = (Graphics2D) img.getGraphics(); gR.drawImage(scaled, x, y, null); gR.dispose(); } private static BufferedImage mat2Image(Mat mat) { int width = mat.width(); int height = mat.height(); byte[] data = new byte[width * height * (int) mat.elemSize()]; Imgproc.cvtColor(mat, mat, Imgproc.COLOR_BGR2RGB); mat.get(0, 0, data); BufferedImage ret = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); ret.getRaster().setDataElements(0, 0, width, height, data); return ret; } private static Mat image2Mat(BufferedImage img) { int width = img.getWidth(); int height = img.getHeight(); byte[] data; Mat mat; DataBuffer buf = img.getRaster().getDataBuffer(); if (buf instanceof DataBufferByte) { data = ((DataBufferByte) buf).getData(); mat = new Mat(height, width, CvType.CV_8UC3); } else if (buf instanceof DataBufferInt) { int[] intData = ((DataBufferInt) buf).getData(); data = new byte[intData.length * 4]; ByteBuffer bb = ByteBuffer.wrap(data); bb.asIntBuffer().put(intData); mat = new Mat(height, width, CvType.CV_8UC4); } else { throw new IllegalArgumentException("Unsupported image type: " + buf.getClass()); } mat.put(0, 0, data); return mat; } }
0
java-sources/ai/djl/opencv/opencv/0.34.0/ai/djl
java-sources/ai/djl/opencv/opencv/0.34.0/ai/djl/opencv/OpenCVImageFactory.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.opencv; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.ImageFactory; import ai.djl.modality.cv.util.NDImageUtils; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.util.Utils; import nu.pattern.OpenCV; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.MatOfByte; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.nio.file.Path; /** {@code OpenCVImageFactory} is a high performance implementation of {@link ImageFactory}. */ public class OpenCVImageFactory extends ImageFactory { static { OpenCV.loadLocally(); if (System.getProperty("apple.awt.UIElement") == null) { // disables coffee cup image showing up on macOS System.setProperty("apple.awt.UIElement", "true"); } } /** {@inheritDoc} */ @Override public Image fromFile(Path path) throws IOException { // Load image without alpha channel Mat img = Imgcodecs.imread(path.toAbsolutePath().toString()); if (img.empty()) { throw new IOException("Read image failed: " + path); } return new OpenCVImage(img); } /** {@inheritDoc} */ @Override public Image fromInputStream(InputStream is) throws IOException { byte[] buf = Utils.toByteArray(is); Mat mat = new MatOfByte(buf); Mat img = Imgcodecs.imdecode(mat, Imgcodecs.IMREAD_COLOR); if (img.empty()) { throw new IOException("Read image failed."); } return new OpenCVImage(img); } /** {@inheritDoc} */ @Override public Image fromImage(Object image) { return new OpenCVImage((Mat) image); } /** {@inheritDoc} */ @Override public Image fromNDArray(NDArray array) { Shape shape = array.getShape(); if (shape.dimension() == 4) { throw new UnsupportedOperationException("Batch is not supported"); } array = array.toType(DataType.UINT8, false); boolean grayScale = shape.get(0) == 1 || shape.get(2) == 1; if (grayScale) { // expected CHW int width = Math.toIntExact(shape.get(2)); int height = Math.toIntExact(shape.get(1)); Mat img = new Mat(height, width, CvType.CV_8UC1); img.put(0, 0, array.toByteArray()); return new OpenCVImage(img); } if (NDImageUtils.isCHW(shape)) { array = array.transpose(1, 2, 0); shape = array.getShape(); } int width = Math.toIntExact(shape.get(1)); int height = Math.toIntExact(shape.get(0)); Mat img = new Mat(height, width, CvType.CV_8UC3); img.put(0, 0, array.toByteArray()); Imgproc.cvtColor(img, img, Imgproc.COLOR_RGB2BGR); return new OpenCVImage(img); } /** {@inheritDoc} */ @Override public Image fromPixels(int[] pixels, int width, int height) { Mat img = new Mat(height, width, CvType.CV_8UC4); byte[] data = new byte[width * height * 4]; IntBuffer buf = ByteBuffer.wrap(data).asIntBuffer(); for (int pixel : pixels) { int r = pixel >> 8 & 0xff00; int g = pixel << 8 & 0xff0000; int b = pixel << 24 & 0xff000000; buf.put(pixel >>> 24 | b | g | r); } img.put(0, 0, data); return new OpenCVImage(img); } }
0
java-sources/ai/djl/opencv/opencv/0.34.0/ai/djl
java-sources/ai/djl/opencv/opencv/0.34.0/ai/djl/opencv/package-info.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** Contains classes that provides high performance image processing functionalities. */ package ai.djl.opencv;
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle/engine/PaddlePredictor.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.engine; import ai.djl.paddlepaddle.jni.JniUtils; import ai.djl.util.NativeResource; /** PaddlePaddle C++ Predictor. */ public class PaddlePredictor extends NativeResource<Long> { PaddlePredictor(long handle) { super(handle); } /** {@inheritDoc} */ public PaddlePredictor copy() { return new PaddlePredictor(JniUtils.clonePredictor(this)); } /** {@inheritDoc} */ @Override public void close() { JniUtils.deletePredictor(this); } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle/engine/PpDataType.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.engine; import ai.djl.ndarray.types.DataType; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** Helper to convert between {@link DataType} an the PaddlePaddle internal DataTypes. */ public final class PpDataType { private static Map<DataType, Integer> toPaddlePaddleMap = createMapToPaddlePaddle(); private static Map<Integer, DataType> fromPaddlePaddleMap = createMapFromPaddlePaddle(); private PpDataType() {} private static Map<DataType, Integer> createMapToPaddlePaddle() { Map<DataType, Integer> map = new ConcurrentHashMap<>(); map.put(DataType.FLOAT32, 0); map.put(DataType.INT64, 1); map.put(DataType.INT32, 2); map.put(DataType.UINT8, 3); map.put(DataType.INT8, 4); map.put(DataType.FLOAT16, 5); return map; } private static Map<Integer, DataType> createMapFromPaddlePaddle() { Map<Integer, DataType> map = new ConcurrentHashMap<>(); map.put(0, DataType.FLOAT32); map.put(1, DataType.INT64); map.put(2, DataType.INT32); map.put(3, DataType.UINT8); map.put(4, DataType.INT8); map.put(5, DataType.FLOAT16); return map; } /** * Converts a PaddlePaddle type String into a {@link DataType}. * * @param ppType the type String to convert * @return the {@link DataType} */ public static DataType fromPaddlePaddle(int ppType) { return fromPaddlePaddleMap.get(ppType); } /** * Converts a {@link DataType} into the corresponding PaddlePaddle type String. * * @param jType the java {@link DataType} to convert * @return the converted PaddlePaddle type string */ public static int toPaddlePaddle(DataType jType) { Integer ppType = toPaddlePaddleMap.get(jType); if (ppType == null) { throw new UnsupportedOperationException( "PaddlePaddle doesn't support dataType: " + jType); } return ppType; } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle/engine/PpEngine.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.engine; import ai.djl.Device; import ai.djl.Model; import ai.djl.engine.Engine; import ai.djl.ndarray.NDManager; import ai.djl.paddlepaddle.jni.LibUtils; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * The {@code PpEngine} is an implementation of the {@link Engine} based on the <a * href="https://github.com/PaddlePaddle/Paddle/">PaddlePaddle</a>. * * <p>To get an instance of the {@code PpEngine} when it is not the default Engine, call {@link * Engine#getEngine(String)} with the Engine name "PaddlePaddle". */ public final class PpEngine extends Engine { public static final String ENGINE_NAME = "PaddlePaddle"; static final int RANK = 10; private Engine alternativeEngine; private boolean initialized; private PpEngine() {} static Engine newInstance() { LibUtils.loadLibrary(); return new PpEngine(); } /** {@inheritDoc} */ @Override public Engine getAlternativeEngine() { if (!initialized && !Boolean.getBoolean("ai.djl.paddlepaddle.disable_alternative")) { Engine engine = Engine.getInstance(); if (engine.getRank() < getRank()) { // alternativeEngine should not have the same rank as PaddlePaddle alternativeEngine = engine; } initialized = true; } return alternativeEngine; } /** {@inheritDoc} */ @Override public String getEngineName() { return ENGINE_NAME; } /** {@inheritDoc} */ @Override public int getRank() { return RANK; } /** {@inheritDoc} */ @Override public String getVersion() { try (InputStream is = PpEngine.class.getResourceAsStream("/paddlepaddle-engine.properties")) { Properties prop = new Properties(); prop.load(is); return prop.getProperty("paddlepaddle_version"); } catch (IOException e) { throw new AssertionError("Failed to load paddlapaddle-engine.properties", e); } } /** {@inheritDoc} */ @Override public boolean hasCapability(String capability) { // Default device is always CPU return false; } /** {@inheritDoc} */ @Override public Model newModel(String name, Device device) { return new PpModel(name, device, newBaseManager(device)); } /** {@inheritDoc} */ @Override public NDManager newBaseManager() { return newBaseManager(null); } /** {@inheritDoc} */ @Override public NDManager newBaseManager(Device device) { return PpNDManager.getSystemManager().newSubManager(device); } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle/engine/PpEngineProvider.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.engine; import ai.djl.engine.Engine; import ai.djl.engine.EngineProvider; /** {@code PpEngineProvider} is the PaddlePaddle implementation of {@link EngineProvider}. */ public class PpEngineProvider implements EngineProvider { /** {@inheritDoc} */ @Override public String getEngineName() { return PpEngine.ENGINE_NAME; } /** {@inheritDoc} */ @Override public int getEngineRank() { return PpEngine.RANK; } /** {@inheritDoc} */ @Override public Engine getEngine() { return InstanceHolder.INSTANCE; } private static class InstanceHolder { static final Engine INSTANCE = PpEngine.newInstance(); } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle/engine/PpModel.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.engine; import ai.djl.BaseModel; import ai.djl.Device; import ai.djl.Model; import ai.djl.inference.Predictor; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.DataType; import ai.djl.paddlepaddle.jni.JniUtils; import ai.djl.translate.ArgumentsUtil; import ai.djl.translate.Translator; import ai.djl.util.Utils; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Map; /** {@code PpModel} is the PaddlePaddle implementation of {@link Model}. */ public class PpModel extends BaseModel { private PaddlePredictor paddlePredictor; private Device device; /** * Constructs a new Model on a given device. * * @param name the model name * @param device the device to load the model * @param manager the {@link NDManager} to holds the NDArray */ PpModel(String name, Device device, NDManager manager) { super(name); // Paddle doesn't support detection of CUDA capability, use has to explicitly // specify device if want to use GPU. this.device = device == null ? Device.cpu() : device; this.manager = manager; dataType = DataType.FLOAT32; manager.setName("PpModel"); } /** * Loads the PaddlePaddle model from a specified location. * * <pre> * Map&lt;String, String&gt; options = new HashMap&lt;&gt;() * <b>options.put("epoch", "3");</b> * model.load(modelPath, "squeezenet", options); * </pre> * * @param modelPath the directory of the model * @param prefix the model file name or path prefix * @param options load model options, see documentation for the specific engine * @throws IOException Exception for file loading */ @Override public void load(Path modelPath, String prefix, Map<String, ?> options) throws IOException { setModelDir(modelPath); String[] modelFiles = findModelFile(modelDir); if (modelFiles.length == 0) { throw new FileNotFoundException("no __model__ or model file found in: " + modelDir); } long config = JniUtils.createConfig(modelFiles[0], modelFiles[1], device); if (options != null) { if (options.containsKey("removePass")) { String[] values = ((String) options.get("removePass")).split(","); for (String value : values) { JniUtils.removePass(config, value); } } if (options.containsKey("enableMKLDNN")) { JniUtils.enableMKLDNN(config); } if (options.containsKey("DisableGlog")) { JniUtils.disableGLog(config); } if (options.containsKey("CMLNumThreads")) { JniUtils.cpuMathLibraryNumThreads( config, ArgumentsUtil.intValue(options, "CMLNumThreads")); } if (options.containsKey("SwitchIrOptim")) { JniUtils.switchIrOptim( config, ArgumentsUtil.booleanValue(options, "SwitchIrOptim")); } if (options.containsKey("enableONNXRuntime")) { JniUtils.enableONNXRuntime(config); } if (options.containsKey("enableOrtOptimization")) { JniUtils.enableOrtOptimization(config); } } paddlePredictor = new PaddlePredictor(JniUtils.createPredictor(config)); JniUtils.deleteConfig(config); setBlock(new PpSymbolBlock(paddlePredictor, (PpNDManager) manager)); } private String[] findModelFile(Path dir) { String[] paths = new String[2]; String[][] patterns = { {"model", "params"}, {"__model__", "__params__"}, {"inference.pdmodel", "inference.pdiparams"} }; for (String[] pattern : patterns) { Path modelFile = dir.resolve(pattern[0]); if (Files.isRegularFile(modelFile)) { paths[0] = modelFile.toString(); Path paramFile = dir.resolve(pattern[1]); if (Files.isRegularFile(paramFile)) { paths[1] = paramFile.toString(); } else { paths[0] = dir.toString(); } return paths; } } return Utils.EMPTY_ARRAY; } /** {@inheritDoc} */ @Override public <I, O> Predictor<I, O> newPredictor(Translator<I, O> translator, Device device) { return new PpPredictor<>(this, paddlePredictor.copy(), translator, device); } /** {@inheritDoc} */ @Override public void close() { if (paddlePredictor != null) { JniUtils.deletePredictor(paddlePredictor); paddlePredictor = null; } super.close(); } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle/engine/PpNDArray.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.engine; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDArrayAdapter; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.paddlepaddle.jni.JniUtils; import com.sun.jna.Pointer; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicReference; /** {@code PpNDArray} is the PaddlePaddle implementation of {@link NDArray}. */ public class PpNDArray extends NDArrayAdapter { // we keep the data to prevent GC from early collecting native memory private ByteBuffer data; private AtomicReference<Long> handle; /** * Constructs an PpNDArray from a native handle (internal. Use {@link NDManager} instead). * * @param manager the manager to attach the new array to * @param alternativeManager the alternative manager if available * @param data bytebuffer that holds the native memory * @param handle the pointer to the native MxNDArray memory */ PpNDArray(NDManager manager, NDManager alternativeManager, ByteBuffer data, long handle) { super(manager, alternativeManager, null, null, String.valueOf(handle)); this.data = data; this.handle = new AtomicReference<>(handle); manager.attachInternal(uid, this); } /** * Sets the Level-of-Detail field of the NDArray. * * <p>checkout https://www.bookstack.cn/read/PaddlePaddle-1.3-fluid/27.md * * @param lod the Level-of-Detail representation */ public void setLoD(long[][] lod) { JniUtils.setNdLoD(this, lod); } /** * Gets the Level-of-Detail field of the NDArray. * * @return the Level-of-Detail representation */ public long[][] getLoD() { return JniUtils.getNdLoD(this); } /** {@inheritDoc} */ @Override public String getName() { return JniUtils.getNameFromNd(this); } /** {@inheritDoc} */ @Override public void setName(String name) { JniUtils.setNdName(this, name); } /** {@inheritDoc} */ @Override public DataType getDataType() { if (isClosed) { throw new IllegalStateException("Native resource has been release already."); } if (dataType == null) { dataType = JniUtils.getDTypeFromNd(this); } return dataType; } /** {@inheritDoc} */ @Override public Shape getShape() { if (shape == null) { shape = JniUtils.getShapeFromNd(this); } return shape; } /** {@inheritDoc} */ @Override public void intern(NDArray replaced) { Long pointer = handle.getAndSet(null); if (pointer != null) { JniUtils.deleteNd(pointer); } this.data = ((PpNDArray) replaced).data; this.handle = ((PpNDArray) replaced).handle; } /** {@inheritDoc} */ @Override public void detach() { manager.detachInternal(getUid()); manager = PpNDManager.getSystemManager(); } /** {@inheritDoc} */ @Override public ByteBuffer toByteBuffer() { if (data == null) { data = JniUtils.getByteBufferFromNd(this); } data.rewind(); return data; } /** * Gets the {@link Pointer} to this resource. * * @return the {@link Pointer} to this resource */ public long getHandle() { Long reference = handle.get(); if (reference == null) { throw new IllegalStateException("Native resource has been release already."); } return reference; } /** {@inheritDoc} */ @Override public void close() { super.close(); Long pointer = handle.getAndSet(null); if (pointer != null) { JniUtils.deleteNd(pointer); data = null; } } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle/engine/PpNDManager.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.engine; import ai.djl.Device; import ai.djl.engine.Engine; import ai.djl.ndarray.BaseNDManager; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.paddlepaddle.jni.JniUtils; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; /** {@code PpNDManager} is the PaddlePaddle implementation of {@link NDManager}. */ public class PpNDManager extends BaseNDManager { private static final PpNDManager SYSTEM_MANAGER = new SystemManager(); private PpNDManager(NDManager parent, Device device) { super(parent, device); } static PpNDManager getSystemManager() { return SYSTEM_MANAGER; } /** {@inheritDoc} */ @Override public PpNDManager newSubManager() { return newSubManager(device); } /** {@inheritDoc} */ @Override public PpNDManager newSubManager(Device device) { PpNDManager manager = new PpNDManager(this, device); attachInternal(manager.uid, manager); return manager; } /** {@inheritDoc} */ @Override public Engine getEngine() { return Engine.getEngine(PpEngine.ENGINE_NAME); } /** {@inheritDoc} */ @Override public ByteBuffer allocateDirect(int capacity) { return ByteBuffer.allocateDirect(capacity).order(ByteOrder.nativeOrder()); } /** {@inheritDoc} */ @Override public PpNDArray from(NDArray array) { if (array == null || array instanceof PpNDArray) { return (PpNDArray) array; } PpNDArray result = create(array.toByteBuffer(), array.getShape(), array.getDataType()); result.setName(array.getName()); return result; } /** * Creates a new instance of {@code PpNDArray}. * * <p>For internal use only. * * @param data bytebuffer that holds the native memory * @param handle the pointer to the native MxNDArray memory * @return a new instance of {@code PpNDArray} */ public PpNDArray createInternal(ByteBuffer data, long handle) { return new PpNDArray(this, alternativeManager, data, handle); } /** {@inheritDoc} */ @Override public PpNDArray create(Buffer data, Shape shape, DataType dataType) { int size = Math.toIntExact(shape.size()); BaseNDManager.validateBuffer(data, dataType, size); if (data.isDirect() && data instanceof ByteBuffer) { return JniUtils.createNdArray(this, (ByteBuffer) data, shape, dataType); } ByteBuffer buf = allocateDirect(size * dataType.getNumOfBytes()); copyBuffer(data, buf); return JniUtils.createNdArray(this, buf, shape, dataType); } /** {@inheritDoc} */ @Override public void close() { super.close(); if (alternativeManager != null) { alternativeManager.close(); alternativeManager = null; } } /** The SystemManager is the root {@link PpNDManager} of which all others are children. */ private static final class SystemManager extends PpNDManager implements SystemNDManager { SystemManager() { super(null, null); } /** {@inheritDoc} */ @Override public void close() {} } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle/engine/PpPredictor.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.engine; import ai.djl.Device; import ai.djl.Model; import ai.djl.inference.Predictor; import ai.djl.translate.Translator; /** * {@code PpPredictor} is special implementation of {@link Predictor} for PaddlePaddle. * * <p>When creating a new PpPredictor, we clone Paddle predictor handle to workaround the issue. */ public class PpPredictor<I, O> extends Predictor<I, O> { PaddlePredictor predictor; /** * Creates a new instance of {@code PaddlePredictor}. * * @param model the model on which the predictions are based * @param predictor the C++ Paddle Predictor handle * @param translator the translator to be used * @param device the device to be used */ public PpPredictor( Model model, PaddlePredictor predictor, Translator<I, O> translator, Device device) { super(model, translator, device, false); this.predictor = predictor; block = new PpSymbolBlock(predictor, (PpNDManager) model.getNDManager()); } /** {@inheritDoc} */ @Override public void close() { super.close(); this.predictor.close(); } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle/engine/PpSymbolBlock.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.engine; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.Shape; import ai.djl.nn.AbstractSymbolBlock; import ai.djl.nn.ParameterList; import ai.djl.nn.SymbolBlock; import ai.djl.paddlepaddle.jni.JniUtils; import ai.djl.training.ParameterStore; import ai.djl.util.PairList; import java.util.Arrays; /** {@code PpSymbolBlock} is the PaddlePaddle implementation of {@link SymbolBlock}. */ public class PpSymbolBlock extends AbstractSymbolBlock { private PaddlePredictor predictor; private PpNDManager manager; private String[] inputNames; /** * Constructs a new {@code PpSymbolBlock} instance. * * @param predictor {@link PaddlePredictor} that holds the model information. * @param manager the {@link NDManager} to holds the NDArray */ public PpSymbolBlock(PaddlePredictor predictor, PpNDManager manager) { this.predictor = predictor; this.manager = manager; inputNames = JniUtils.getInputNames(predictor); } /** {@inheritDoc} */ @Override protected NDList forwardInternal( ParameterStore parameterStore, NDList inputs, boolean training, PairList<String, Object> params) { if (inputNames.length != inputs.size()) { throw new IllegalArgumentException( "Input number mismatch, requires: " + Arrays.toString(inputNames)); } try (PpNDManager sub = manager.newSubManager()) { NDList output = JniUtils.predictorForward(predictor, getInputs(sub, inputs), inputNames); NDManager inputManager = inputs.head().getManager(); NDList ret = new NDList(); for (NDArray array : output) { ret.add(inputManager.from(array)); } return ret; } } private PpNDArray[] getInputs(PpNDManager sub, NDList inputs) { PpNDArray[] inputArray = new PpNDArray[inputs.size()]; for (int i = 0; i < inputArray.length; i++) { inputArray[i] = sub.from(inputs.get(i)); } return inputArray; } /** {@inheritDoc} */ @Override public ParameterList getDirectParameters() { throw new UnsupportedOperationException("Not yet supported"); } /** {@inheritDoc} */ @Override public Shape[] getOutputShapes(Shape[] inputShapes) { return new Shape[0]; } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle/engine/package-info.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** Contains implementations of interfaces within the DJL API for the PaddlePaddle Engine. */ package ai.djl.paddlepaddle.engine;
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle/jni/JniUtils.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.jni; import ai.djl.Device; import ai.djl.ndarray.NDList; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.paddlepaddle.engine.PaddlePredictor; import ai.djl.paddlepaddle.engine.PpDataType; import ai.djl.paddlepaddle.engine.PpNDArray; import ai.djl.paddlepaddle.engine.PpNDManager; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; /** * A class containing utilities to interact with the Paddle Engine's Java Native Interface (JNI) * layer. */ @SuppressWarnings("MissingJavadocMethod") public final class JniUtils { private JniUtils() {} public static PpNDArray createNdArray( PpNDManager manager, ByteBuffer data, Shape shape, DataType dtype) { int[] intShape = Arrays.stream(shape.getShape()).mapToInt(Math::toIntExact).toArray(); long handle = PaddleLibrary.LIB.paddleCreateTensor( data, data.remaining(), intShape, PpDataType.toPaddlePaddle(dtype)); return manager.createInternal(data, handle); } public static DataType getDTypeFromNd(PpNDArray array) { int type = PaddleLibrary.LIB.getTensorDType(array.getHandle()); return PpDataType.fromPaddlePaddle(type); } public static ByteBuffer getByteBufferFromNd(PpNDArray array) { ByteBuffer bb = ByteBuffer.wrap(PaddleLibrary.LIB.getTensorData(array.getHandle())); return bb.order(ByteOrder.nativeOrder()); } public static Shape getShapeFromNd(PpNDArray array) { int[] shape = PaddleLibrary.LIB.getTensorShape(array.getHandle()); return new Shape(Arrays.stream(shape).asLongStream().toArray()); } public static void setNdName(PpNDArray array, String name) { PaddleLibrary.LIB.setTensorName(array.getHandle(), name); } public static String getNameFromNd(PpNDArray array) { return PaddleLibrary.LIB.getTensorName(array.getHandle()); } public static void setNdLoD(PpNDArray array, long[][] lod) { PaddleLibrary.LIB.setTensorLoD(array.getHandle(), lod); } public static long[][] getNdLoD(PpNDArray array) { return PaddleLibrary.LIB.getTensorLoD(array.getHandle()); } public static void deleteNd(Long handle) { PaddleLibrary.LIB.deleteTensor(handle); } public static long createConfig(String modelDir, String paramDir, Device device) { int deviceId = device.getDeviceId(); return PaddleLibrary.LIB.createAnalysisConfig(modelDir, paramDir, deviceId); } public static void enableMKLDNN(long config) { PaddleLibrary.LIB.analysisConfigEnableMKLDNN(config); } public static void removePass(long config, String pass) { PaddleLibrary.LIB.analysisConfigRemovePass(config, pass); } public static void disableGLog(long config) { PaddleLibrary.LIB.analysisConfigDisableGLog(config); } public static void cpuMathLibraryNumThreads(long config, int thread) { PaddleLibrary.LIB.analysisConfigCMLNumThreads(config, thread); } public static void switchIrOptim(long config, boolean condition) { PaddleLibrary.LIB.analysisConfigSwitchIrOptim(config, condition); } public static void useFeedFetchOp(long config) { PaddleLibrary.LIB.useFeedFetchOp(config); } public static void enableONNXRuntime(long config) { PaddleLibrary.LIB.analysisConfigEnableONNXRuntime(config); } public static void enableOrtOptimization(long config) { PaddleLibrary.LIB.analysisConfigEnableORTOptimization(config); } public static void deleteConfig(long config) { PaddleLibrary.LIB.deleteAnalysisConfig(config); } public static long createPredictor(long config) { return PaddleLibrary.LIB.createPredictor(config); } public static long clonePredictor(PaddlePredictor predictor) { return PaddleLibrary.LIB.clonePredictor(predictor.getHandle()); } public static void deletePredictor(PaddlePredictor predictor) { PaddleLibrary.LIB.deletePredictor(predictor.getHandle()); } public static NDList predictorForward( PaddlePredictor predictor, PpNDArray[] inputs, String[] inputNames) { long[] inputHandles = new long[inputs.length]; for (int i = 0; i < inputs.length; i++) { inputs[i].setName(inputNames[i]); inputHandles[i] = inputs[i].getHandle(); } long[] outputs = PaddleLibrary.LIB.runInference(predictor.getHandle(), inputHandles); PpNDManager manager = (PpNDManager) inputs[0].getManager(); PpNDArray[] arrays = new PpNDArray[outputs.length]; for (int i = 0; i < outputs.length; i++) { arrays[i] = manager.createInternal(null, outputs[i]); } return new NDList(arrays); } public static String[] getInputNames(PaddlePredictor predictor) { return PaddleLibrary.LIB.getInputNames(predictor.getHandle()); } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle/jni/LibUtils.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.jni; import ai.djl.util.ClassLoaderUtils; import ai.djl.util.Platform; import ai.djl.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; /** * Utilities for finding the Paddle Engine binary on the System. * * <p>The Engine will be searched for in a variety of locations in the following order: * * <ol> * <li>In the path specified by the Paddle_LIBRARY_PATH environment variable * <li>In a jar file location in the classpath. These jars can be created with the paddle-native * module. * </ol> */ @SuppressWarnings("MissingJavadocMethod") public final class LibUtils { private static final Logger logger = LoggerFactory.getLogger(LibUtils.class); private static final String NATIVE_LIB_NAME = "paddle_inference"; private static final String LIB_NAME = "djl_paddle"; private static final Pattern VERSION_PATTERN = Pattern.compile("(\\d+\\.\\d+\\.\\d+)(-SNAPSHOT)?(-\\d+)?"); private LibUtils() {} public static void loadLibrary() { String libName = LibUtils.findOverrideLibrary(); AtomicBoolean fallback = new AtomicBoolean(false); if (libName == null) { libName = LibUtils.findLibraryInClasspath(fallback); if (libName == null) { throw new IllegalStateException("Native library not found"); } } if (System.getProperty("os.name").startsWith("Linux")) { loadLinuxDependencies(libName); } else if (System.getProperty("os.name").startsWith("Win")) { loadWindowsDependencies(libName); } else if (System.getProperty("os.name").startsWith("Mac")) { loadMacOsDependencies(libName); } logger.debug("Now loading " + libName); System.load(libName); // NOPMD // TODO: change this part to load from cache directory Path nativeLibDir = Paths.get(libName).getParent(); if (nativeLibDir == null || !nativeLibDir.toFile().isDirectory()) { throw new IllegalStateException("Native folder cannot be found"); } libName = copyJniLibraryFromClasspath(nativeLibDir); logger.debug("Loading paddle library from: {}", libName); System.load(libName); // NOPMD } public static void loadLinuxDependencies(String libName) { Path libDir = Paths.get(libName).getParent(); if (libDir != null) { logger.info( "Paddle MKL/GPU requires user to set LD_LIBRARY_PATH=" + libDir + ", the current one is set to: " + Utils.getenv("LD_LIBRARY_PATH")); List<String> names = Arrays.asList( "libdnnl.so.2", "libiomp5.so", "libmklml_intel.so", "libonnxruntime.so", "libpaddle2onnx.so"); names.forEach( name -> { Path path = libDir.resolve(name); if (Files.isRegularFile(path)) { String lib = path.toAbsolutePath().toString(); logger.debug("Now loading " + lib); System.load(lib); } else { logger.debug(name + " is not found, skip loading..."); } }); } } public static void loadWindowsDependencies(String libName) { Path libDir = Paths.get(libName).getParent(); List<String> names = Arrays.asList("openblas.dll", "mkldnn.dll", "onnxruntime.dll", "paddle2onnx.dll"); names.forEach( name -> { Path path = libDir.resolve(name); if (Files.isRegularFile(path)) { String lib = path.toAbsolutePath().toString(); logger.debug("Now loading " + lib); System.load(lib); } else { logger.debug(name + " is not found, skip loading..."); } }); } public static void loadMacOsDependencies(String libName) { Path libDir = Paths.get(libName).getParent(); List<String> names = Arrays.asList("libonnxruntime.dylib", "libpaddle2onnx.dylib"); names.forEach( name -> { Path path = libDir.resolve(name); if (Files.isRegularFile(path)) { String lib = path.toAbsolutePath().toString(); logger.debug("Now loading " + lib); System.load(lib); } else { logger.debug(name + " is not found, skip loading..."); } }); } private static String findOverrideLibrary() { String libPath = Utils.getEnvOrSystemProperty("PADDLE_LIBRARY_PATH"); if (libPath != null) { String libName = findLibraryInPath(libPath); if (libName != null) { return libName; } } libPath = System.getProperty("java.library.path"); if (libPath != null) { return findLibraryInPath(libPath); } return null; } private static String copyJniLibraryFromClasspath(Path nativeDir) { String name = System.mapLibraryName(LIB_NAME); Platform platform = Platform.detectPlatform("paddlepaddle"); String classifier = platform.getClassifier(); String djlVersion = platform.getApiVersion(); Path path = nativeDir.resolve(djlVersion + '-' + name); if (Files.exists(path)) { return path.toAbsolutePath().toString(); } Path tmp = null; // Paddle GPU and CPU share the same jni so file String libPath = "jnilib/" + classifier + "/cpu/" + name; try (InputStream is = ClassLoaderUtils.getResourceAsStream(libPath)) { logger.info("Extracting {} to cache ...", libPath); tmp = Files.createTempFile(nativeDir, "jni", "tmp"); Files.copy(is, tmp, StandardCopyOption.REPLACE_EXISTING); Utils.moveQuietly(tmp, path); return path.toAbsolutePath().toString(); } catch (IOException e) { throw new IllegalStateException("Cannot copy jni files", e); } finally { if (tmp != null) { Utils.deleteQuietly(tmp); } } } private static synchronized String findLibraryInClasspath(AtomicBoolean fallback) { Platform platform = Platform.detectPlatform("paddlepaddle"); if (platform.isPlaceholder()) { return downloadLibrary(platform, fallback); } String flavor = platform.getFlavor(); if ("cpu".equals(flavor)) { fallback.set(true); } return loadLibraryFromClasspath(platform); } private static String loadLibraryFromClasspath(Platform platform) { Path tmp = null; try { String libName = System.mapLibraryName(NATIVE_LIB_NAME); Path cacheFolder = Utils.getEngineCacheDir("paddle"); String version = platform.getVersion(); String flavor = platform.getFlavor(); String classifier = platform.getClassifier(); Path dir = cacheFolder.resolve(version + '-' + flavor + '-' + classifier); logger.debug("Using cache dir: {}", dir); Path path = dir.resolve(libName); if (Files.exists(path)) { return path.toAbsolutePath().toString(); } Files.createDirectories(cacheFolder); tmp = Files.createTempDirectory(cacheFolder, "tmp"); for (String file : platform.getLibraries()) { String libPath = "native/lib/" + file; logger.info("Extracting {} to cache ...", file); if (file.endsWith(".gz")) { // FIXME: temporary workaround for paddlepaddle-native-cu102:2.0.2 String f = file.substring(0, file.length() - 3); try (InputStream is = new GZIPInputStream(ClassLoaderUtils.getResourceAsStream(libPath))) { Files.copy(is, tmp.resolve(f), StandardCopyOption.REPLACE_EXISTING); } } else { try (InputStream is = ClassLoaderUtils.getResourceAsStream(libPath)) { Files.copy(is, tmp.resolve(file), StandardCopyOption.REPLACE_EXISTING); } } } Utils.moveQuietly(tmp, dir); return path.toAbsolutePath().toString(); } catch (IOException e) { throw new IllegalStateException("Failed to extract PaddlePaddle native library", e); } finally { if (tmp != null) { Utils.deleteQuietly(tmp); } } } private static String findLibraryInPath(String libPath) { String[] paths = libPath.split(File.pathSeparator); String mappedLibNames = System.mapLibraryName(NATIVE_LIB_NAME); for (String path : paths) { File p = new File(path); if (!p.exists()) { continue; } if (p.isFile() && p.getName().endsWith(mappedLibNames)) { return p.getAbsolutePath(); } File file = new File(path, mappedLibNames); if (file.exists() && file.isFile()) { return file.getAbsolutePath(); } } return null; } private static String downloadLibrary(Platform platform, AtomicBoolean fallback) { String version = platform.getVersion(); String flavor = platform.getFlavor(); String classifier = platform.getClassifier(); String os = platform.getOsPrefix(); String libName = System.mapLibraryName(NATIVE_LIB_NAME); Path cacheDir = Utils.getEngineCacheDir("paddle"); Path dir = cacheDir.resolve(version + '-' + flavor + '-' + classifier); logger.debug("Using cache dir: {}", dir); Path path = dir.resolve(libName); if (Files.exists(path)) { return path.toAbsolutePath().toString(); } Matcher matcher = VERSION_PATTERN.matcher(version); if (!matcher.matches()) { throw new IllegalArgumentException("Unexpected version: " + version); } Path tmp = null; String link = "https://publish.djl.ai/paddlepaddle-" + matcher.group(1); try (InputStream is = Utils.openUrl(link + "/files.txt")) { Files.createDirectories(cacheDir); List<String> lines = Utils.readLines(is); if (flavor.startsWith("cu") && !lines.contains(flavor + '/' + os + "/native/lib/" + libName + ".gz")) { logger.warn("No matching cuda flavor for {} found: {}.", os, flavor); // fallback to CPU flavor = "cpu"; fallback.set(true); // check again dir = cacheDir.resolve(version + '-' + flavor + '-' + classifier); path = dir.resolve(libName); if (Files.exists(path)) { return path.toAbsolutePath().toString(); } } tmp = Files.createTempDirectory(cacheDir, "tmp"); boolean found = false; for (String line : lines) { if (line.startsWith(flavor + '/' + os + '/')) { found = true; URL url = new URL(link + '/' + line); String fileName = line.substring(line.lastIndexOf('/') + 1, line.length() - 3); logger.info("Downloading {} ...", url); try (InputStream fis = new GZIPInputStream(Utils.openUrl(url))) { Files.copy(fis, tmp.resolve(fileName), StandardCopyOption.REPLACE_EXISTING); } } } if (!found) { throw new IllegalStateException( "No PaddlePaddle native library matches your operating system: " + platform); } Utils.moveQuietly(tmp, dir); return path.toAbsolutePath().toString(); } catch (IOException e) { throw new IllegalStateException("Failed to download PaddlePaddle native library", e); } finally { if (tmp != null) { Utils.deleteQuietly(tmp); } } } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle/jni/PaddleLibrary.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.jni; import java.nio.ByteBuffer; /** A class containing utilities to interact with the PaddlePaddle Engine's JNI layer. */ @SuppressWarnings("missingjavadocmethod") final class PaddleLibrary { static final PaddleLibrary LIB = new PaddleLibrary(); private PaddleLibrary() {} native long paddleCreateTensor(ByteBuffer data, long length, int[] shape, int dType); native void deleteTensor(long handle); native int[] getTensorShape(long handle); native int getTensorDType(long handle); native byte[] getTensorData(long handle); native void setTensorName(long handle, String name); native String getTensorName(long handle); native void setTensorLoD(long handle, long[][] lod); native long[][] getTensorLoD(long handle); native void loadExtraDir(String[] args); native long createAnalysisConfig(String modelDir, String paramDir, int deviceId); native void analysisConfigEnableMKLDNN(long handle); native void analysisConfigDisableGLog(long handle); native void analysisConfigCMLNumThreads(long handle, int threads); native void analysisConfigSwitchIrOptim(long handle, boolean condition); native void analysisConfigRemovePass(long handle, String pass); native void analysisConfigEnableONNXRuntime(long handle); native void analysisConfigEnableORTOptimization(long handle); native void useFeedFetchOp(long handle); native void deleteAnalysisConfig(long handle); native long createPredictor(long configHandle); native long clonePredictor(long handle); native void deletePredictor(long handle); native String[] getInputNames(long handle); native long[] runInference(long handle, long[] inputHandles); }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle
java-sources/ai/djl/paddlepaddle/paddlepaddle-engine/0.27.0/ai/djl/paddlepaddle/jni/package-info.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** Contains classes to interface with the underlying PaddlePaddle Engine. */ package ai.djl.paddlepaddle.jni;
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/PpModelZoo.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.zoo; import ai.djl.Application.CV; import ai.djl.paddlepaddle.engine.PpEngine; import ai.djl.repository.Repository; import ai.djl.repository.zoo.ModelZoo; import java.util.Collections; import java.util.Set; /** PpModelZoo is a repository that contains all PaddlePaddle models for DJL. */ public class PpModelZoo extends ModelZoo { private static final String DJL_REPO_URL = "https://mlrepo.djl.ai/"; private static final Repository REPOSITORY = Repository.newInstance("Paddle", DJL_REPO_URL); public static final String GROUP_ID = "ai.djl.paddlepaddle"; PpModelZoo() { addModel( REPOSITORY.model( CV.IMAGE_CLASSIFICATION, GROUP_ID, "mask_classification", "0.0.1")); addModel(REPOSITORY.model(CV.IMAGE_CLASSIFICATION, GROUP_ID, "word_rotation", "0.0.1")); addModel(REPOSITORY.model(CV.OBJECT_DETECTION, GROUP_ID, "face_detection", "0.0.1")); addModel(REPOSITORY.model(CV.OBJECT_DETECTION, GROUP_ID, "word_detection", "0.0.1")); addModel(REPOSITORY.model(CV.WORD_RECOGNITION, GROUP_ID, "word_recognition", "0.0.1")); } /** {@inheritDoc} */ @Override public String getGroupId() { return GROUP_ID; } /** {@inheritDoc} */ @Override public Set<String> getSupportedEngines() { return Collections.singleton(PpEngine.ENGINE_NAME); } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/PpZooProvider.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.zoo; import ai.djl.repository.zoo.ModelZoo; import ai.djl.repository.zoo.ZooProvider; /** * An PyTorch model zoo provider implements the {@link ai.djl.repository.zoo.ZooProvider} interface. */ public class PpZooProvider implements ZooProvider { /** {@inheritDoc} */ @Override public ModelZoo getModelZoo() { return new PpModelZoo(); } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/package-info.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** Contains the built-in {@link ai.djl.paddlepaddle.zoo.PpModelZoo}. */ package ai.djl.paddlepaddle.zoo;
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv/imageclassification/PpImageClassificationTranslatorFactory.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.zoo.cv.imageclassification; import ai.djl.Model; import ai.djl.modality.Classifications; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.transform.Normalize; import ai.djl.modality.cv.transform.Resize; import ai.djl.modality.cv.transform.ToTensor; import ai.djl.modality.cv.translator.ImageClassificationTranslator; import ai.djl.modality.cv.translator.ImageClassificationTranslatorFactory; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorFactory; import java.io.Serializable; import java.util.Map; /** * An {@link TranslatorFactory} that creates a {@link PpImageClassificationTranslatorFactory} * instance. */ public class PpImageClassificationTranslatorFactory extends ImageClassificationTranslatorFactory implements Serializable { private static final long serialVersionUID = 1L; /** {@inheritDoc} */ @Override protected Translator<Image, Classifications> buildBaseTranslator( Model model, Map<String, ?> arguments) { return ImageClassificationTranslator.builder() .addTransform(new Resize(128, 128)) .addTransform(new ToTensor()) .addTransform( new Normalize( new float[] {0.5f, 0.5f, 0.5f}, new float[] {1.0f, 1.0f, 1.0f})) .addTransform(nd -> nd.flip(0)) // RGB -> GBR .build(); } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv/imageclassification/PpWordRotateTranslator.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.zoo.cv.imageclassification; import ai.djl.modality.Classifications; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.util.NDImageUtils; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.translate.NoBatchifyTranslator; import ai.djl.translate.TranslatorContext; import java.util.Arrays; import java.util.List; /** A {@link PpWordRotateTranslator} that classify the words and rotate 90 degree if necessary. */ public class PpWordRotateTranslator implements NoBatchifyTranslator<Image, Classifications> { List<String> classes; /** The Translator for {@link PpWordRotateTranslator}. */ public PpWordRotateTranslator() { classes = Arrays.asList("No Rotate", "Rotate"); } /** {@inheritDoc} */ @Override public Classifications processOutput(TranslatorContext ctx, NDList list) { NDArray prob = list.singletonOrThrow(); return new Classifications(classes, prob); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, Image input) { NDArray img = input.toNDArray(ctx.getNDManager()); int[] hw = resize32(input.getHeight(), input.getWidth()); img = NDImageUtils.resize(img, hw[1], hw[0]); img = NDImageUtils.toTensor(img).sub(0.5f).div(0.5f); img = img.expandDims(0); return new NDList(img); } private int[] resize32(double h, double w) { double min = Math.min(h, w); if (min < 32) { h = 32.0 / min * h; w = 32.0 / min * w; } int h32 = (int) h / 32; int w32 = (int) w / 32; return new int[] {h32 * 32, w32 * 32}; } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv/imageclassification/PpWordRotateTranslatorFactory.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.zoo.cv.imageclassification; import ai.djl.Model; import ai.djl.modality.Classifications; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.translator.ImageClassificationTranslatorFactory; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorFactory; import java.io.Serializable; import java.util.Map; /** An {@link TranslatorFactory} that creates a {@link PpWordRotateTranslatorFactory} instance. */ public class PpWordRotateTranslatorFactory extends ImageClassificationTranslatorFactory implements Serializable { private static final long serialVersionUID = 1L; /** {@inheritDoc} */ @Override protected Translator<Image, Classifications> buildBaseTranslator( Model model, Map<String, ?> arguments) { return new PpWordRotateTranslator(); } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv/imageclassification/package-info.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** * Contains classes for the {@link ai.djl.Application.CV#IMAGE_CLASSIFICATION} models in the {@link * ai.djl.paddlepaddle.zoo.PpModelZoo}. */ package ai.djl.paddlepaddle.zoo.cv.imageclassification;
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv/objectdetection/BoundFinder.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.zoo.cv.objectdetection; import ai.djl.modality.cv.output.BoundingBox; import ai.djl.modality.cv.output.Point; import ai.djl.modality.cv.output.Rectangle; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.stream.Collectors; /** Compute the bound of single colored region. */ public class BoundFinder { private final int[] deltaX = {0, 1, -1, 0}; private final int[] deltaY = {1, 0, 0, -1}; private List<List<Point>> pointsCollection; private int width; private int height; /** * Compute the bound based on the boolean mask. * * @param grid the 2D boolean mask that defines the region */ public BoundFinder(boolean[][] grid) { pointsCollection = new ArrayList<>(); width = grid.length; height = grid[0].length; boolean[][] visited = new boolean[width][height]; // get all points connections for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (grid[i][j] && !visited[i][j]) { pointsCollection.add(bfs(grid, i, j, visited)); } } } } /** * Gets all points from the region. * * @return all connected points */ public List<List<Point>> getPoints() { return pointsCollection; } /** * Compute rectangle bounding boxes. * * @return the region defined by boxes */ public List<BoundingBox> getBoxes() { return pointsCollection.stream() .parallel() .map( points -> { double[] minMax = {Integer.MAX_VALUE, Integer.MAX_VALUE, -1, -1}; points.forEach( p -> { minMax[0] = Math.min(minMax[0], p.getX()); minMax[1] = Math.min(minMax[1], p.getY()); minMax[2] = Math.max(minMax[2], p.getX()); minMax[3] = Math.max(minMax[3], p.getY()); }); return new Rectangle( minMax[1], minMax[0], minMax[3] - minMax[1], minMax[2] - minMax[0]); }) .filter(rect -> rect.getWidth() * width > 5.0 && rect.getHeight() * height > 5.0) .collect(Collectors.toList()); } private List<Point> bfs(boolean[][] grid, int x, int y, boolean[][] visited) { Queue<Point> queue = new ArrayDeque<>(); queue.offer(new Point(x, y)); visited[x][y] = true; List<Point> points = new ArrayList<>(); while (!queue.isEmpty()) { Point point = queue.poll(); points.add(new Point(point.getX() / width, point.getY() / height)); for (int direction = 0; direction < 4; direction++) { int newX = (int) point.getX() + deltaX[direction]; int newY = (int) point.getY() + deltaY[direction]; if (!isVaild(grid, newX, newY, visited)) { continue; } queue.offer(new Point(newX, newY)); visited[newX][newY] = true; } } return points; } private boolean isVaild(boolean[][] grid, int x, int y, boolean[][] visited) { if (x < 0 || x >= width || y < 0 || y >= height) { return false; } if (visited[x][y]) { return false; } return grid[x][y]; } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv/objectdetection/PpFaceDetectionTranslator.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.zoo.cv.objectdetection; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.output.BoundingBox; import ai.djl.modality.cv.output.DetectedObjects; import ai.djl.modality.cv.output.Rectangle; import ai.djl.modality.cv.util.NDImageUtils; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.types.Shape; import ai.djl.translate.ArgumentsUtil; import ai.djl.translate.NoBatchifyTranslator; import ai.djl.translate.TranslatorContext; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; /** * A {@link PpFaceDetectionTranslator} that post-process the {@link NDArray} into {@link * DetectedObjects} with boundaries. */ public class PpFaceDetectionTranslator implements NoBatchifyTranslator<Image, DetectedObjects> { private float shrink; private float threshold; private List<String> className; /** * Creates the {@link PpFaceDetectionTranslator} instance. * * @param arguments the arguments for the translator */ public PpFaceDetectionTranslator(Map<String, ?> arguments) { threshold = ArgumentsUtil.floatValue(arguments, "threshold", 0.7f); shrink = ArgumentsUtil.floatValue(arguments, "shrink", 0.5f); className = Arrays.asList("Not Face", "Face"); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, Image input) { NDArray array = input.toNDArray(ctx.getNDManager()); Shape shape = array.getShape(); array = NDImageUtils.resize( array, (int) (shape.get(1) * shrink), (int) (shape.get(0) * shrink)); array = array.transpose(2, 0, 1).flip(0); // HWC -> CHW RGB -> BGR NDArray mean = array.getManager().create(new float[] {104f, 117f, 123f}, new Shape(3, 1, 1)); array = array.sub(mean).mul(0.007843f); // normalization array = array.expandDims(0); // make batch dimension return new NDList(array); } /** {@inheritDoc} */ @Override public DetectedObjects processOutput(TranslatorContext ctx, NDList list) { NDArray result = list.singletonOrThrow(); float[] probabilities = result.get(":,1").toFloatArray(); List<String> names = new ArrayList<>(); List<Double> prob = new ArrayList<>(); List<BoundingBox> boxes = new ArrayList<>(); for (int i = 0; i < probabilities.length; i++) { if (probabilities[i] >= threshold) { float[] array = result.get(i).toFloatArray(); names.add(className.get((int) array[0])); prob.add((double) probabilities[i]); boxes.add( new Rectangle( array[2], array[3], array[4] - array[2], array[5] - array[3])); } } return new DetectedObjects(names, prob, boxes); } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv/objectdetection/PpFaceDetectionTranslatorFactory.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.zoo.cv.objectdetection; import ai.djl.Model; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.output.DetectedObjects; import ai.djl.modality.cv.translator.ObjectDetectionTranslatorFactory; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorFactory; import java.util.Map; /** An {@link TranslatorFactory} that creates a {@link PpFaceDetectionTranslator} instance. */ public class PpFaceDetectionTranslatorFactory extends ObjectDetectionTranslatorFactory { /** {@inheritDoc} */ @Override protected Translator<Image, DetectedObjects> buildBaseTranslator( Model model, Map<String, ?> arguments) { return new PpFaceDetectionTranslator(arguments); } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv/objectdetection/PpWordDetectionTranslator.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.zoo.cv.objectdetection; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.ImageFactory; import ai.djl.modality.cv.output.BoundingBox; import ai.djl.modality.cv.output.DetectedObjects; import ai.djl.modality.cv.output.Rectangle; import ai.djl.modality.cv.util.NDImageUtils; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.translate.ArgumentsUtil; import ai.djl.translate.NoBatchifyTranslator; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * A {@link Translator} that post-process the {@link NDArray} into {@link DetectedObjects} with * boundaries. */ public class PpWordDetectionTranslator implements NoBatchifyTranslator<Image, DetectedObjects> { private final int maxLength; /** * Creates the {@link PpWordDetectionTranslator} instance. * * @param arguments the arguments for the translator */ public PpWordDetectionTranslator(Map<String, ?> arguments) { maxLength = ArgumentsUtil.intValue(arguments, "maxLength", 960); } /** {@inheritDoc} */ @Override public DetectedObjects processOutput(TranslatorContext ctx, NDList list) { NDArray result = list.singletonOrThrow(); ImageFactory factory = ImageFactory.getInstance(); List<BoundingBox> boxes; // faster mechanism if ("ai.djl.opencv.OpenCVImageFactory".equals(factory.getClass().getName())) { result = result.squeeze(0); Image image = factory.fromNDArray(result); boxes = image.findBoundingBoxes().parallelStream() .filter( box -> { Rectangle rect = (Rectangle) box; return rect.getWidth() * image.getWidth() > 5 || rect.getHeight() * image.getHeight() > 5; }) .collect(Collectors.toList()); } else { result = result.squeeze().mul(255f).toType(DataType.UINT8, true).neq(0); boolean[] flattened = result.toBooleanArray(); Shape shape = result.getShape(); int w = (int) shape.get(0); int h = (int) shape.get(1); boolean[][] grid = new boolean[w][h]; IntStream.range(0, flattened.length) .parallel() .forEach(i -> grid[i / h][i % h] = flattened[i]); boxes = new BoundFinder(grid).getBoxes(); } List<String> names = new ArrayList<>(); List<Double> probs = new ArrayList<>(); int boxSize = boxes.size(); for (int i = 0; i < boxSize; i++) { names.add("word"); probs.add(1.0); } return new DetectedObjects(names, probs, boxes); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, Image input) { NDArray img = input.toNDArray(ctx.getNDManager()); int h = input.getHeight(); int w = input.getWidth(); int[] hw = scale(h, w, maxLength); img = NDImageUtils.resize(img, hw[1], hw[0]); img = NDImageUtils.toTensor(img); img = NDImageUtils.normalize( img, new float[] {0.485f, 0.456f, 0.406f}, new float[] {0.229f, 0.224f, 0.225f}); img = img.expandDims(0); return new NDList(img); } private int[] scale(int h, int w, int max) { int localMax = Math.max(h, w); float scale = 1.0f; if (max < localMax) { scale = max * 1.0f / localMax; } // paddle model only take 32-based size return resize32(h * scale, w * scale); } private int[] resize32(double h, double w) { double min = Math.min(h, w); if (min < 32) { h = 32.0 / min * h; w = 32.0 / min * w; } int h32 = (int) h / 32; int w32 = (int) w / 32; return new int[] {h32 * 32, w32 * 32}; } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv/objectdetection/PpWordDetectionTranslatorFactory.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.zoo.cv.objectdetection; import ai.djl.Model; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.output.DetectedObjects; import ai.djl.modality.cv.translator.ObjectDetectionTranslatorFactory; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorFactory; import java.util.Map; /** An {@link TranslatorFactory} that creates a {@link PpWordDetectionTranslator} instance. */ public class PpWordDetectionTranslatorFactory extends ObjectDetectionTranslatorFactory { /** {@inheritDoc} */ @Override protected Translator<Image, DetectedObjects> buildBaseTranslator( Model model, Map<String, ?> arguments) { return new PpWordDetectionTranslator(arguments); } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv/objectdetection/package-info.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** * Contains classes for the {@link ai.djl.Application.CV#OBJECT_DETECTION} models in the {@link * ai.djl.paddlepaddle.zoo.PpModelZoo}. */ package ai.djl.paddlepaddle.zoo.cv.objectdetection;
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv/wordrecognition/PpWordRecognitionTranslator.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.zoo.cv.wordrecognition; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.util.NDImageUtils; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.translate.NoBatchifyTranslator; import ai.djl.translate.TranslatorContext; import ai.djl.util.Utils; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * A {@link PpWordRecognitionTranslator} that preprocess {@link Image} post-process the {@link * NDArray} into text. */ public class PpWordRecognitionTranslator implements NoBatchifyTranslator<Image, String> { private List<String> table; /** {@inheritDoc} */ @Override public void prepare(TranslatorContext ctx) throws IOException { try (InputStream is = ctx.getModel().getArtifact("ppocr_keys_v1.txt").openStream()) { table = Utils.readLines(is, true); table.add(0, "blank"); table.add(""); } } /** {@inheritDoc} */ @Override public String processOutput(TranslatorContext ctx, NDList list) { StringBuilder sb = new StringBuilder(); NDArray tokens = list.singletonOrThrow(); long[] indices = tokens.get(0).argMax(1).toLongArray(); int lastIdx = 0; for (int i = 0; i < indices.length; i++) { if (indices[i] > 0 && !(i > 0 && indices[i] == lastIdx)) { sb.append(table.get((int) indices[i])); } } return sb.toString(); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, Image input) { NDArray img = input.toNDArray(ctx.getNDManager()); int[] hw = resize32(input.getWidth()); img = NDImageUtils.resize(img, hw[1], hw[0]); img = NDImageUtils.toTensor(img).sub(0.5f).div(0.5f); img = img.expandDims(0); return new NDList(img); } private int[] resize32(double w) { // Paddle doesn't rely on aspect ratio int width = ((int) Math.max(32, w)) / 32 * 32; return new int[] {32, width}; } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv/wordrecognition/PpWordRecognitionTranslatorFactory.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.paddlepaddle.zoo.cv.wordrecognition; import ai.djl.Model; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.translator.BaseImageTranslatorFactory; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorFactory; import java.util.Map; /** An {@link TranslatorFactory} that creates a {@link PpWordRecognitionTranslator} instance. */ public class PpWordRecognitionTranslatorFactory extends BaseImageTranslatorFactory<String> { /** {@inheritDoc} */ @Override protected Translator<Image, String> buildBaseTranslator(Model model, Map<String, ?> arguments) { return new PpWordRecognitionTranslator(); } /** {@inheritDoc} */ @Override public Class<String> getBaseOutputType() { return String.class; } }
0
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv
java-sources/ai/djl/paddlepaddle/paddlepaddle-model-zoo/0.27.0/ai/djl/paddlepaddle/zoo/cv/wordrecognition/package-info.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** * Contains classes for the {@link ai.djl.Application.CV#WORD_RECOGNITION} models in the {@link * ai.djl.paddlepaddle.zoo.PpModelZoo}. */ package ai.djl.paddlepaddle.zoo.cv.wordrecognition;
0
java-sources/ai/djl/python/python/0.28.0/ai/djl/python
java-sources/ai/djl/python/python/0.28.0/ai/djl/python/engine/CodecUtils.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.python.engine; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.CorruptedFrameException; import java.nio.charset.StandardCharsets; /** This is a utility class for reading and writing to netty ByteBuf. */ public final class CodecUtils { public static final int MAX_BUFFER_SIZE = 20 * 1024 * 1024; private CodecUtils() {} /** * Reads the specified length of data. * * @param in byte buffer * @param maxLength length of the data to be read * @return read data */ public static byte[] readBytes(ByteBuf in, int maxLength) { int len = in.readInt(); if (len < 0) { return null; // NOPMD } if (len > maxLength) { throw new CorruptedFrameException("Message size exceed limit: " + len); } byte[] buf = new byte[len]; in.readBytes(buf); return buf; } /** * Read a String from the {@code ByteBuf}. * * @param in the {@code ByteBuf}. * @return a string read from the buffer. */ public static String readUtf8(ByteBuf in) { int len = in.readInt(); if (len < 0) { return null; } byte[] buf = new byte[len]; in.readBytes(buf); return new String(buf, StandardCharsets.UTF_8); } /** * Encode a String in UTF-8 and write it to the {@code ByteBuf}. * * @param buf the {@code ByteBuf}. * @param value the string to write into a buffer. */ public static void writeUtf8(ByteBuf buf, String value) { if (value == null) { buf.writeInt(-1); } else { byte[] bytes = value.getBytes(StandardCharsets.UTF_8); buf.writeInt(bytes.length); buf.writeBytes(bytes); } } }
0
java-sources/ai/djl/python/python/0.28.0/ai/djl/python
java-sources/ai/djl/python/python/0.28.0/ai/djl/python/engine/Connection.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.python.engine; import ai.djl.Device; import ai.djl.Model; import ai.djl.engine.EngineException; import ai.djl.inference.streaming.ChunkedBytesSupplier; import ai.djl.modality.Input; import ai.djl.modality.Output; import ai.djl.ndarray.BytesSupplier; import ai.djl.util.PairList; import ai.djl.util.Utils; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.epoll.Epoll; import io.netty.channel.epoll.EpollDomainSocketChannel; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.kqueue.KQueue; import io.netty.channel.kqueue.KQueueDomainSocketChannel; import io.netty.channel.kqueue.KQueueEventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.channel.unix.DomainSocketAddress; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.MessageToByteEncoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ThreadFactory; import java.util.stream.Stream; class Connection { private static final Logger logger = LoggerFactory.getLogger(Connection.class); private static final String MASTER_ADDR = "127.0.0.1"; private int port; private SocketAddress socketAddress; private Channel channel; private RequestHandler requestHandler; Connection(PyEnv pyEnv, int basePort, int rank) { requestHandler = new RequestHandler(); port = 19000 + basePort; socketAddress = getSocketAddress(pyEnv.isMpiMode(), rank); } static Process startPython(PyEnv pyEnv, Model model, int workerId, int port) throws IOException { Path tmp = Paths.get(System.getProperty("java.io.tmpdir")); try (Stream<Path> stream = Files.list(tmp)) { stream.forEach( p -> { try { String name = p.toFile().getName(); if (name.startsWith("djl_sock." + port) && name.endsWith(".pid")) { long pid = Long.parseLong(Files.readString(p)); Optional<ProcessHandle> handle = ProcessHandle.of(pid); if (handle.isPresent()) { logger.warn("Kill dangling process: {}", pid); handle.get().destroyForcibly(); } Utils.deleteQuietly(p); } } catch (IOException e) { logger.warn("", e); } }); } File modelPath = model.getModelPath().toFile(); String[] args = getPythonStartCmd(pyEnv, model, workerId, port); String[] envp = pyEnv.getEnvironmentVars(model); logger.debug("cmd: {}", (Object) args); return Runtime.getRuntime().exec(args, envp, modelPath); } int getPort() { return port; } CompletableFuture<Output> send(Input input) throws InterruptedException { CompletableFuture<Output> f = new CompletableFuture<>(); requestHandler.setResponseFuture(f); if (!channel.isActive() || !channel.writeAndFlush(input).sync().isSuccess()) { throw new IllegalStateException("Failed to send data to python."); } return f; } static String[] getPythonStartCmd(PyEnv pyEnv, Model model, int workerId, int port) { Device device = model.getNDManager().getDevice(); int deviceId = device.getDeviceId(); int tensorParallelDegree = pyEnv.getTensorParallelDegree(); if (pyEnv.isMpiMode()) { String cudaDevices = getVisibleDevices(workerId, tensorParallelDegree); logger.info("Set CUDA_VISIBLE_DEVICES={}", cudaDevices); String[] args = new String[40]; args[0] = "mpirun"; args[1] = "-np"; // TODO: When we support multi nodes, change it to the product of tensor parallel value // and // pipeline parallel value. args[2] = String.valueOf(tensorParallelDegree); args[3] = "--allow-run-as-root"; args[4] = "--bind-to"; args[5] = "none"; args[6] = "--mca"; args[7] = "btl_vader_single_copy_mechanism"; args[8] = "none"; args[9] = "--tag-output"; args[10] = "-x"; args[11] = "FI_PROVIDER=efa"; args[12] = "-x"; args[13] = "RDMAV_FORK_SAFE=1"; args[14] = "-x"; args[15] = "FI_EFA_USE_DEVICE_RDMA=1"; args[16] = "-x"; args[17] = "LD_LIBRARY_PATH"; args[18] = "-x"; args[19] = "PYTHONPATH"; args[20] = "-x"; args[21] = "CUDA_VISIBLE_DEVICES=" + cudaDevices; args[22] = "-x"; args[23] = "MASTER_ADDR=" + MASTER_ADDR; args[24] = "-x"; args[25] = "MASTER_PORT=" + port; args[26] = "-x"; args[27] = "MKL_DYNAMIC=FALSE"; args[28] = pyEnv.getPythonExecutable(); args[29] = PyEnv.getEngineCacheDir() + "/djl_python_engine.py"; args[30] = "--model-dir"; args[31] = model.getModelPath().toAbsolutePath().toString(); args[32] = "--entry-point"; args[33] = pyEnv.getEntryPoint(); args[34] = "--sock-type"; args[35] = "unix"; args[36] = "--sock-name"; args[37] = getSocketPath(port); args[38] = "--tensor-parallel-degree"; args[39] = String.valueOf(tensorParallelDegree); return args; } // TP settings if (tensorParallelDegree > 0 && device.isGpu()) { String cudaDevices = getVisibleDevices(deviceId, tensorParallelDegree); deviceId = 0; // re-map logic device to 0 pyEnv.addEnv("CUDA_VISIBLE_DEVICES", cudaDevices); logger.info("Set CUDA_VISIBLE_DEVICES={}", cudaDevices); } if ("nc".equals(device.getDeviceType())) { String visibleCores = getNeuronVisibleCores(deviceId, tensorParallelDegree); // TODO: re-map logic device once neuron fixed bug pyEnv.addEnv("NEURON_RT_VISIBLE_CORES", visibleCores); logger.info("Set NEURON_RT_VISIBLE_CORES={}", visibleCores); String neuronThreads = getNeuronThreads(tensorParallelDegree); pyEnv.addEnv("OMP_NUM_THREADS", neuronThreads); logger.info("Set OMP_NUM_THREADS={}", neuronThreads); } boolean uds = Epoll.isAvailable() || KQueue.isAvailable(); String[] args = new String[12]; args[0] = pyEnv.getPythonExecutable(); args[1] = PyEnv.getEngineCacheDir() + "/djl_python_engine.py"; args[2] = "--sock-type"; args[3] = uds ? "unix" : "tcp"; args[4] = uds ? "--sock-name" : "--port"; args[5] = uds ? getSocketPath(port) : String.valueOf(port); args[6] = "--model-dir"; args[7] = model.getModelPath().toAbsolutePath().toString(); args[8] = "--entry-point"; args[9] = pyEnv.getEntryPoint(); args[10] = "--device-id"; args[11] = String.valueOf(deviceId); return args; } private static String getVisibleDevices(int deviceId, int tensorParallelDegree) { StringBuilder sb = new StringBuilder(20); // CUDA_VISIBLE_DEVICES=0,2,3,7 TP2 // -> 0,2 and 3,7 if (Utils.getenv("CUDA_VISIBLE_DEVICES") != null) { String[] devices = Utils.getenv("CUDA_VISIBLE_DEVICES").split(","); sb.append(devices[deviceId]); for (int i = 1; i < tensorParallelDegree; ++i) { sb.append(',').append(devices[deviceId + i]); } } else { sb.append(deviceId); for (int i = 1; i < tensorParallelDegree; ++i) { sb.append(',').append(deviceId + i); } } return sb.toString(); } private static String getNeuronVisibleCores(int deviceId, int tensorParallelDegree) { if (tensorParallelDegree > 0) { return deviceId + "-" + (deviceId + tensorParallelDegree - 1); } return String.valueOf(deviceId); } private static String getNeuronThreads(int tensorParallelDegree) { if (tensorParallelDegree > 0) { return String.valueOf(tensorParallelDegree * 2); } return String.valueOf(1); } void connect() throws InterruptedException { EventLoopGroup group = PyEnv.getEventLoopGroup(); Bootstrap clientBootstrap = new Bootstrap(); clientBootstrap .group(group) .channel(getClientChannel()) .remoteAddress(socketAddress) .handler( new ChannelInitializer<>() { @Override protected void initChannel(Channel ch) { ch.pipeline() .addLast("encoder", new RequestEncoder()) .addLast("decoder", new OutputDecoder()) .addLast("handler", requestHandler); } }); ChannelFuture future = clientBootstrap.connect().sync(); if (!future.isSuccess()) { throw new EngineException("Connection to worker process is failed."); } channel = future.awaitUninterruptibly().channel(); } void disconnect() { try { if (channel != null) { channel.close().sync(); } else { logger.warn("Connection channel is null."); } } catch (InterruptedException ignore) { // ignore } if (socketAddress instanceof DomainSocketAddress) { String path = ((DomainSocketAddress) socketAddress).path(); Utils.deleteQuietly(Paths.get(path)); } } private static String getSocketPath(int port) { return System.getProperty("java.io.tmpdir") + "/djl_sock." + port; } private SocketAddress getSocketAddress(boolean mpiMode, int rank) { if (mpiMode) { return new DomainSocketAddress(getSocketPath(port) + '.' + rank); } boolean uds = Epoll.isAvailable() || KQueue.isAvailable(); if (uds) { return new DomainSocketAddress(getSocketPath(port)); } return new InetSocketAddress("127.0.0.1", port); } static EventLoopGroup newEventLoopGroup() { if (Epoll.isAvailable()) { return new EpollEventLoopGroup(new DaemonThreadFactory()); } else if (KQueue.isAvailable()) { return new KQueueEventLoopGroup(new DaemonThreadFactory()); } return new NioEventLoopGroup(new DaemonThreadFactory()); } private static Class<? extends Channel> getClientChannel() { if (Epoll.isAvailable()) { return EpollDomainSocketChannel.class; } else if (KQueue.isAvailable()) { return KQueueDomainSocketChannel.class; } return NioSocketChannel.class; } @ChannelHandler.Sharable private static final class RequestHandler extends SimpleChannelInboundHandler<Output> { private CompletableFuture<Output> future; /** {@inheritDoc} */ @Override protected void channelRead0(ChannelHandlerContext ctx, Output msg) { future.complete(msg); } /** {@inheritDoc} */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { logger.error("Exception reading Output from python process", cause); ctx.close(); } /** {@inheritDoc} */ @Override public void channelInactive(ChannelHandlerContext ctx) { ctx.fireChannelInactive(); if (future != null) { future.completeExceptionally(new IOException("Python worker disconnected.")); } } /** * Sets the response future object. It gets completed when response is sent by the python * server. * * @param future response future */ public void setResponseFuture(CompletableFuture<Output> future) { this.future = future; } } private static final class RequestEncoder extends MessageToByteEncoder<Input> { /** {@inheritDoc} */ @Override protected void encode(ChannelHandlerContext ctx, Input msg, ByteBuf out) { Map<String, String> prop = msg.getProperties(); out.writeShort(prop.size()); for (Map.Entry<String, String> entry : prop.entrySet()) { CodecUtils.writeUtf8(out, entry.getKey()); CodecUtils.writeUtf8(out, entry.getValue()); } PairList<String, BytesSupplier> content = msg.getContent(); int size = content.size(); out.writeShort(size); for (int i = 0; i < size; ++i) { CodecUtils.writeUtf8(out, content.keyAt(i)); BytesSupplier supplier = content.valueAt(i); if (supplier != null) { ByteBuffer bb = supplier.toByteBuffer(); out.writeInt(bb.remaining()); out.writeBytes(bb); } else { out.writeInt(0); } } } } private static final class OutputDecoder extends ByteToMessageDecoder { private int maxBufferSize; private boolean hasMoreChunk; private ChunkedBytesSupplier data; OutputDecoder() { String val = Utils.getEnvOrSystemProperty( "MAX_NETTY_BUFFER_SIZE", String.valueOf(CodecUtils.MAX_BUFFER_SIZE)); this.maxBufferSize = Integer.parseInt(val); } /** {@inheritDoc} */ @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) { // this index of the reader is marked, // so that future reads can be done from this index. in.markReaderIndex(); boolean completed = false; try { if (hasMoreChunk) { hasMoreChunk = in.readByte() == 1; data.appendContent(CodecUtils.readBytes(in, maxBufferSize), !hasMoreChunk); } else { int code = in.readShort(); String message = CodecUtils.readUtf8(in); Output output = new Output(code, message); int size = in.readShort(); for (int i = 0; i < size; ++i) { output.addProperty(CodecUtils.readUtf8(in), CodecUtils.readUtf8(in)); } int contentSize = in.readShort(); if (contentSize == -1) { hasMoreChunk = true; data = new ChunkedBytesSupplier(); output.add(data); } else { for (int i = 0; i < contentSize; ++i) { String key = CodecUtils.readUtf8(in); output.add(key, CodecUtils.readBytes(in, maxBufferSize)); } } out.add(output); } completed = true; } catch (IndexOutOfBoundsException | NegativeArraySizeException ignore) { // ignore } finally { if (!completed) { // resetting the marked index. Index will be set to 0 in.resetReaderIndex(); } } } /** {@inheritDoc} */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { logger.error("Exception occurred during request handler of python worker", cause); ctx.close(); } } private static final class DaemonThreadFactory implements ThreadFactory { /** {@inheritDoc} */ @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setDaemon(true); return t; } } }
0
java-sources/ai/djl/python/python/0.28.0/ai/djl/python
java-sources/ai/djl/python/python/0.28.0/ai/djl/python/engine/MpiEngineProvider.java
/* * Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.python.engine; import ai.djl.engine.EngineProvider; /** {@code MpiEngineProvider} is the DeepSpeed implementation of {@link EngineProvider}. */ public class MpiEngineProvider extends PyEngineProvider { /** Constructs a new {@code MpiEngineProvider} instance. */ public MpiEngineProvider() { mpiMode = true; } /** {@inheritDoc} */ @Override public String getEngineName() { return "MPI"; } /** {@inheritDoc} */ @Override public int getEngineRank() { return PyEngine.RANK + 1; } }
0
java-sources/ai/djl/python/python/0.28.0/ai/djl/python
java-sources/ai/djl/python/python/0.28.0/ai/djl/python/engine/PyEngine.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.python.engine; import ai.djl.Device; import ai.djl.Model; import ai.djl.engine.Engine; import ai.djl.ndarray.NDManager; import ai.djl.util.passthrough.PassthroughNDManager; /** The {@code PyEngine} is an implementation of the {@link Engine} that runs Python worker. */ public final class PyEngine extends Engine { static final int RANK = 10; private String engineName; private boolean mpiMode; private Engine alternativeEngine; private boolean initialized; PyEngine(String engineName, boolean mpiMode) { this.engineName = engineName; this.mpiMode = mpiMode; } /** {@inheritDoc} */ @Override public Engine getAlternativeEngine() { if (!mpiMode && !initialized && !Boolean.getBoolean("ai.djl.python.disable_alternative")) { Engine engine = Engine.getInstance(); if (engine.getRank() < getRank()) { // alternativeEngine should not have the same rank as OnnxRuntime alternativeEngine = engine; } initialized = true; } return alternativeEngine; } /** {@inheritDoc} */ @Override public String getEngineName() { return engineName; } /** {@inheritDoc} */ @Override public int getRank() { return RANK; } /** {@inheritDoc} */ @Override public String getVersion() { return PyEnv.getVersion(); } /** {@inheritDoc} */ @Override public boolean hasCapability(String capability) { return true; } /** {@inheritDoc} */ @Override public Model newModel(String name, Device device) { return new PyModel(name, newBaseManager(device)); } /** {@inheritDoc} */ @Override public NDManager newBaseManager() { return newBaseManager(null); } /** {@inheritDoc} */ @Override public NDManager newBaseManager(Device device) { return new PassthroughNDManager(this, device); } /** * Returns the MPI mode. * * @return the MPI mode */ boolean isMpiMode() { return mpiMode; } }
0
java-sources/ai/djl/python/python/0.28.0/ai/djl/python
java-sources/ai/djl/python/python/0.28.0/ai/djl/python/engine/PyEngineProvider.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.python.engine; import ai.djl.engine.Engine; import ai.djl.engine.EngineProvider; /** {@code PyEngineProvider} is the Python implementation of {@link EngineProvider}. */ public class PyEngineProvider implements EngineProvider { private static final String ENGINE_NAME = "Python"; private volatile Engine engine; // NOPMD private volatile boolean initialized; // NOPMD protected boolean mpiMode; /** {@inheritDoc} */ @Override public String getEngineName() { return ENGINE_NAME; } /** {@inheritDoc} */ @Override public int getEngineRank() { return PyEngine.RANK; } /** {@inheritDoc} */ @Override public Engine getEngine() { if (!initialized) { synchronized (this) { if (!initialized) { initialized = true; PyEnv.init(); engine = new PyEngine(getEngineName(), mpiMode); } } } return engine; } }
0
java-sources/ai/djl/python/python/0.28.0/ai/djl/python
java-sources/ai/djl/python/python/0.28.0/ai/djl/python/engine/PyEnv.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.python.engine; import ai.djl.Model; import ai.djl.engine.EngineException; import ai.djl.util.NeuronUtils; import ai.djl.util.Platform; import ai.djl.util.Utils; import ai.djl.util.cuda.CudaUtils; import io.netty.channel.EventLoopGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** Python engine environment. */ public class PyEnv { static final Logger logger = LoggerFactory.getLogger(PyEnv.class); private static String engineCacheDir; private static String version; private static EventLoopGroup eventLoopGroup; private boolean mpiMode; private String pythonExecutable; private String entryPoint; private String handler; private int predictTimeout; private int modelLoadingTimeout; private int tensorParallelDegree; private Map<String, String> envs; private Map<String, String> initParameters; private boolean initialized; private boolean failOnInitialize = true; private boolean enableVenv; private boolean venvCreated; /** * Constructs a new {@code PyEnv} instance. * * @param mpiMode true to use MPI launcher */ public PyEnv(boolean mpiMode) { this.mpiMode = mpiMode; pythonExecutable = Utils.getenv("PYTHON_EXECUTABLE"); if (pythonExecutable == null) { pythonExecutable = "python3"; } handler = "handle"; envs = new ConcurrentHashMap<>(); initParameters = new ConcurrentHashMap<>(); } static synchronized void init() { if (eventLoopGroup != null) { return; } eventLoopGroup = Connection.newEventLoopGroup(); Path tmp = null; try { Platform platform = Platform.detectPlatform("python"); version = platform.getVersion(); Path cacheDir = Utils.getEngineCacheDir("python"); logger.debug("Using cache dir: {}", cacheDir); Path path = cacheDir.resolve(version); engineCacheDir = path.toAbsolutePath().toString(); if (Files.exists(path)) { return; } Files.createDirectories(cacheDir); tmp = Files.createTempDirectory(cacheDir, "tmp"); Files.createDirectories(tmp.resolve("djl_python")); for (String file : platform.getLibraries()) { String libPath = '/' + file; logger.info("Extracting {} to cache ...", libPath); try (InputStream is = PyEnv.class.getResourceAsStream(libPath)) { if (is == null) { throw new AssertionError("Python engine script not found: " + libPath); } Path f = tmp.resolve(file); Path dir = f.getParent(); if (dir == null) { throw new AssertionError("Parent direct cannot be null"); } Files.createDirectories(dir); Files.copy(is, f, StandardCopyOption.REPLACE_EXISTING); } } Utils.moveQuietly(tmp, path); tmp = null; } catch (IOException e) { throw new EngineException("Failed to initialize python engine.", e); } finally { if (tmp != null) { Utils.deleteQuietly(tmp); } } } static String getVersion() { return version; } static String getEngineCacheDir() { return engineCacheDir; } static EventLoopGroup getEventLoopGroup() { return eventLoopGroup; } /** * Adds an environment variable. * * @param key the environment variable name * @param value the environment variable value */ public void addEnv(String key, String value) { envs.put(key, value); } /** * Adds a model initialization parameter. * * @param key the environment variable name * @param value the environment variable value */ public void addParameter(String key, String value) { initParameters.put(key, value); } /** * Returns the python model initialization parameters. * * @return the python model initialization parameters */ public Map<String, String> getInitParameters() { return initParameters; } /** * Creates python virtual environment if needed. * * @param name the virtual environment name */ public void createVirtualEnv(String name) { synchronized (PyEnv.class) { if (venvCreated) { return; } Path path = getVenvDir().resolve(name).toAbsolutePath(); if (Files.exists(path)) { logger.info("Virtual environment already exists at {}.", path); setPythonExecutable(path.resolve("bin").resolve("python").toString()); venvCreated = true; return; } String[] cmd = { pythonExecutable, "-m", "venv", path.toString(), "--system-site-packages" }; try { Process process = new ProcessBuilder(cmd).redirectErrorStream(true).start(); String logOutput; try (InputStream is = process.getInputStream()) { logOutput = Utils.toString(is); } int ret = process.waitFor(); logger.debug("{}", logOutput); if (ret != 0) { throw new EngineException("Failed to create venv with error code: " + ret); } logger.info("Python virtual environment created successfully at {}!", path); setPythonExecutable(path.resolve("bin").resolve("python").toString()); venvCreated = true; } catch (IOException | InterruptedException e) { throw new EngineException("Create venv failed", e); } } } /** * Deletes python virtual environment. * * @param name the virtual environment name */ public synchronized void deleteVirtualEnv(String name) { Path path = getVenvDir().resolve(name); Utils.deleteQuietly(path); } /** * Installs model dependencies if needed. * * @param modelDir the model directory */ public synchronized void installDependency(Path modelDir) { if (initialized) { return; } Path file = modelDir.resolve("requirements.txt"); if (Files.isRegularFile(file)) { List<String> cmd = new ArrayList<>(9); cmd.add(pythonExecutable); cmd.add("-m"); cmd.add("pip"); if (!logger.isDebugEnabled()) { cmd.add("-q"); } cmd.add("install"); cmd.add("-r"); cmd.add(file.toAbsolutePath().toString()); Path dir = modelDir.resolve("requirements"); boolean offline = Utils.isOfflineMode(); if (Files.isDirectory(dir)) { if (offline) { // if folder exists, we assume user want to resolve dependencies in the folder cmd.add("--no-index"); } cmd.add("-f"); cmd.add(dir.toAbsolutePath().toString()); } else if (offline) { cmd.add("--no-deps"); } try { logger.info("Found requirements.txt, start installing Python dependencies..."); logger.debug("{}", cmd); Process process = new ProcessBuilder(cmd).redirectErrorStream(true).start(); String logOutput; try (InputStream is = process.getInputStream()) { logOutput = Utils.toString(is); } int ret = process.waitFor(); if (ret == 0) { logger.info("pip install requirements succeed!"); logger.debug("{}", logOutput); } else { logger.warn("pip install failed with error code: {}", ret); logger.warn("{}", logOutput); } } catch (IOException | InterruptedException e) { logger.warn("pip install requirements failed.", e); } } initialized = true; } void setMpiMode(boolean mpiMode) { this.mpiMode = mpiMode; } boolean isMpiMode() { return mpiMode; } /** * Returns the python executable path. * * @return the python executable path */ public String getPythonExecutable() { return pythonExecutable; } /** * Sets the python executable path. * * @param pythonExecutable the python executable path */ public void setPythonExecutable(String pythonExecutable) { this.pythonExecutable = pythonExecutable; } /** * Returns the tensor parallel degree. * * @return the tensor parallel degree */ public int getTensorParallelDegree() { if (tensorParallelDegree == 0) { String value = Utils.getenv("TENSOR_PARALLEL_DEGREE"); if ("max".equals(value)) { tensorParallelDegree = getDefaultTensorParallelDegree(); } else if (value != null) { tensorParallelDegree = Integer.parseInt(value); } } return tensorParallelDegree; } static int getDefaultTensorParallelDegree() { int gpus = CudaUtils.getGpuCount(); if (gpus > 0) { return gpus; } return NeuronUtils.getNeuronCores(); } /** * Sets the tensor parallel degree. * * @param tensorParallelDegree the tensor parallel degree */ public void setTensorParallelDegree(int tensorParallelDegree) { this.tensorParallelDegree = tensorParallelDegree; } int getMpiWorkers() { int gpuCount = CudaUtils.getGpuCount(); String visibleDevices = Utils.getenv("CUDA_VISIBLE_DEVICES"); if (gpuCount > 0 && visibleDevices != null) { int visibleCount = visibleDevices.split(",").length; if (visibleCount > gpuCount || visibleCount < 1) { throw new AssertionError("Invalid CUDA_VISIBLE_DEVICES: " + visibleDevices); } gpuCount = visibleCount; } return gpuCount / getTensorParallelDegree(); } /** * Returns the model's entrypoint file path. * * @return the model's entrypoint file path */ public String getEntryPoint() { return entryPoint == null ? "model.py" : entryPoint; } /** * Sets the model's entrypoint file path. * * @param entryPoint the model's entrypoint file path */ public void setEntryPoint(String entryPoint) { this.entryPoint = entryPoint; } /** * Returns the python model's handler function. * * @return the python file's handler function */ public String getHandler() { return handler; } /** * Sets the python model's handler function. * * @param handler the python file's handler function */ public void setHandler(String handler) { this.handler = handler; } /** * Returns the prediction timeout in seconds. * * @return the prediction timeout in seconds */ public int getPredictTimeout() { if (predictTimeout == 0) { predictTimeout = getDefaultTimeout("PREDICT_TIMEOUT", 120); } return predictTimeout; } /** * Sets the prediction timeout in seconds. * * @param predictTimeout the prediction timeout in seconds */ public void setPredictTimeout(int predictTimeout) { this.predictTimeout = predictTimeout; } /** * Returns the model loading timeout in seconds. * * @return the model loading timeout in seconds */ public int getModelLoadingTimeout() { if (modelLoadingTimeout == 0) { modelLoadingTimeout = getDefaultTimeout("MODEL_LOADING_TIMEOUT", 240); } return modelLoadingTimeout; } /** * Returns true to forcibly fail if initialize process in python failed. * * @return true if forcibly failed */ public boolean isFailOnInitialize() { return failOnInitialize; } /** * Enables to forcibly fail if initialize process in python failed. * * @param failOnInitialize the flag */ public void setFailOnInitialize(boolean failOnInitialize) { this.failOnInitialize = failOnInitialize; } /** * Returns whether the python virtual environment is enabled. * * @return {@code true} if the virtual environment is enabled, {@code false} otherwise. */ public boolean isEnableVenv() { return enableVenv; } /** * Sets whether to enable the python virtual environment. * * @param enableVenv {@code true} to enable the virtual environment, {@code false} to disable * it. */ public void setEnableVenv(boolean enableVenv) { this.enableVenv = enableVenv; } /** * Sets the model loading timeout in seconds. * * @param modelLoadingTimeout the model loading timeout in seconds */ public void setModelLoadingTimeout(int modelLoadingTimeout) { this.modelLoadingTimeout = modelLoadingTimeout; } String[] getEnvironmentVars(Model model) { ArrayList<String> envList = new ArrayList<>(); StringBuilder pythonPath = new StringBuilder(); HashMap<String, String> environment = new HashMap<>(Utils.getenv()); if (Utils.getenv("PYTHONPATH") != null) { pythonPath.append(Utils.getenv("PYTHONPATH")).append(File.pathSeparatorChar); } pythonPath.append(engineCacheDir).append(File.pathSeparatorChar); pythonPath.append(model.getModelPath().toAbsolutePath()); environment.put("PYTHONPATH", pythonPath.toString()); environment.putAll(envs); for (Map.Entry<String, String> entry : environment.entrySet()) { envList.add(entry.getKey() + '=' + entry.getValue()); } return envList.toArray(new String[0]); } private static int getDefaultTimeout(String key, int def) { String timeout = Utils.getenv(key); if (timeout == null) { return def; } try { return Integer.parseInt(timeout); } catch (NumberFormatException e) { logger.warn("Invalid timeout value: {}.", timeout); } return def; } /** * Utility function to get python virtual env directory. * * @return DJL venv directory */ private Path getVenvDir() { String venvDir = Utils.getEnvOrSystemProperty("DJL_VENV_DIR"); if (venvDir == null || venvDir.isEmpty()) { return Utils.getCacheDir().resolve("venv"); } return Paths.get(venvDir); } }
0
java-sources/ai/djl/python/python/0.28.0/ai/djl/python
java-sources/ai/djl/python/python/0.28.0/ai/djl/python/engine/PyModel.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.python.engine; import ai.djl.BaseModel; import ai.djl.Device; import ai.djl.Model; import ai.djl.engine.EngineException; import ai.djl.inference.Predictor; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.DataType; import ai.djl.translate.Translator; import ai.djl.util.Utils; import ai.djl.util.cuda.CudaUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingDeque; /** {@code PyModel} is the Python engine implementation of {@link Model}. */ public class PyModel extends BaseModel { private static final Logger logger = LoggerFactory.getLogger(PyModel.class); private PyEnv pyEnv; private boolean parallelLoading; private LinkedBlockingDeque<PyProcess> workerQueue; /** * Constructs a new Model on a given device. * * @param name the model name * @param manager the {@link NDManager} to holds the NDArray */ PyModel(String name, NDManager manager) { super(name); this.manager = manager; this.manager.setName("pythonModel"); boolean mpiMode = ((PyEngine) manager.getEngine()).isMpiMode(); pyEnv = new PyEnv(mpiMode); dataType = DataType.FLOAT32; workerQueue = new LinkedBlockingDeque<>(); } /** {@inheritDoc} */ @Override public void load(Path modelPath, String prefix, Map<String, ?> options) throws IOException { setModelDir(modelPath); if (block != null) { throw new UnsupportedOperationException( "Python engine does not support dynamic blocks"); } String entryPoint = null; if (options != null) { logger.debug("options in serving.properties for model: {}", modelName); for (Map.Entry<String, ?> entry : options.entrySet()) { String key = entry.getKey(); String value = (String) entry.getValue(); if (!"env".equals(key)) { pyEnv.addParameter(key, value); properties.put(key, value); } logger.debug("{}={}", key, value); switch (key) { case "pythonExecutable": pyEnv.setPythonExecutable(value); break; case "env": String[] envs = value.split(","); for (String e : envs) { String[] kv = e.split("=", 2); if (kv.length > 1) { pyEnv.addEnv(kv[0].trim(), kv[1].trim()); } } break; case "predict_timeout": try { int timeoutSeconds = Integer.parseInt(value); pyEnv.setPredictTimeout(timeoutSeconds); } catch (NumberFormatException ignore) { logger.warn("Invalid predict_timeout value: {}", value); } break; case "model_loading_timeout": try { int timeoutSeconds = Integer.parseInt(value); pyEnv.setModelLoadingTimeout(timeoutSeconds); } catch (NumberFormatException ignore) { logger.warn("Invalid model_loading_timeout value: {}", value); } break; case "entryPoint": entryPoint = value; break; case "parallel_loading": parallelLoading = Boolean.parseBoolean(value); break; case "tensor_parallel_degree": if ("max".equals(value)) { pyEnv.setTensorParallelDegree(PyEnv.getDefaultTensorParallelDegree()); } else { pyEnv.setTensorParallelDegree(Integer.parseInt(value)); } break; case "handler": pyEnv.setHandler(value); break; case "enable_venv": pyEnv.setEnableVenv(Boolean.parseBoolean(value)); break; case "mpi_mode": pyEnv.setMpiMode(Boolean.parseBoolean(value)); break; default: break; } } } // MMS and TorchServe Bcc if (Files.isDirectory(modelDir.resolve("MAR-INF"))) { pyEnv.setFailOnInitialize(false); } if (entryPoint == null) { entryPoint = Utils.getenv("DJL_ENTRY_POINT"); if (entryPoint == null) { Path modelFile = findModelFile(prefix); String features = Utils.getEnvOrSystemProperty("SERVING_FEATURES"); // find default entryPoint if (modelFile != null) { entryPoint = modelFile.toFile().getName(); } else if ("nc".equals(manager.getDevice().getDeviceType()) && pyEnv.getTensorParallelDegree() > 0) { entryPoint = "djl_python.transformers_neuronx"; } else if ("trtllm".equals(features)) { entryPoint = "djl_python.tensorrt_llm"; } else if (pyEnv.getInitParameters().containsKey("model_id") || Files.exists(modelPath.resolve("config.json"))) { entryPoint = "djl_python.huggingface"; } else { throw new FileNotFoundException(".py file not found in: " + modelPath); } } } else if (entryPoint.toLowerCase(Locale.ROOT).startsWith("http")) { String hash = Utils.hash(entryPoint); Path dir = Utils.getCacheDir().resolve("tmp").resolve(hash); Path modelFile = dir.resolve("model.py"); if (Files.exists(modelFile)) { logger.info("entryPoint file already exist: {}", dir); } else { logger.info("downloading entryPoint file: {}", entryPoint); Files.createDirectories(dir); Path tmp = Files.createTempFile(dir, "download", ".tmp"); try (InputStream is = Utils.openUrl(entryPoint)) { Files.copy(is, tmp, StandardCopyOption.REPLACE_EXISTING); Utils.moveQuietly(tmp, modelFile); } finally { Utils.deleteQuietly(tmp); } } entryPoint = modelFile.toAbsolutePath().toString(); } pyEnv.setEntryPoint(entryPoint); if (pyEnv.isEnableVenv()) { pyEnv.createVirtualEnv(Utils.hash(modelDir.toString())); } if (pyEnv.isMpiMode()) { int partitions = pyEnv.getTensorParallelDegree(); if (partitions == 0) { partitions = CudaUtils.getGpuCount(); pyEnv.setTensorParallelDegree(partitions); setProperty("tensor_parallel_degree", String.valueOf(partitions)); logger.info( "No tensor parallel degree specified. Defaulting to all available GPUs."); } logger.info("Loading model in MPI mode with TP: {}.", partitions); int mpiWorkers = pyEnv.getMpiWorkers(); if (mpiWorkers <= 0) { throw new EngineException( "GPU devices are not enough to run " + partitions + " partitions."); } if (getProperty("minWorkers") == null && getProperty("gpu.minWorkers") == null) { setProperty("minWorkers", String.valueOf(mpiWorkers)); setProperty("gpu.minWorkers", String.valueOf(mpiWorkers)); } if (getProperty("gpu.maxWorkers") == null) { if (getProperty("maxWorkers") == null) { setProperty("maxWorkers", String.valueOf(mpiWorkers)); } setProperty("gpu.maxWorkers", getProperty("maxWorkers")); } if (mpiWorkers < intProperty("gpu.maxWorkers", -1)) { throw new IllegalArgumentException( "We can only expand worker to " + mpiWorkers + " but the value is set to " + getProperty("gpu.maxWorkers")); } mpiWorkers = intProperty("gpu.maxWorkers", -1); properties.forEach((k, v) -> pyEnv.addParameter(k, v)); createAllPyProcesses(mpiWorkers, partitions); } else { int tensorParallelDegree = pyEnv.getTensorParallelDegree(); if (tensorParallelDegree > 0) { if (getProperty("maxWorkers") == null && getProperty("gpu.maxWorkers") == null) { setProperty("gpu.minWorkers", "1"); setProperty("gpu.maxWorkers", "1"); } setProperty("tensor_parallel_degree", String.valueOf(tensorParallelDegree)); } properties.forEach((k, v) -> pyEnv.addParameter(k, v)); } } /** {@inheritDoc} */ @Override public <I, O> Predictor<I, O> newPredictor(Translator<I, O> translator, Device device) { int timeout = pyEnv.getPredictTimeout(); if (pyEnv.isMpiMode()) { if (workerQueue.isEmpty()) { throw new EngineException("There are no devices left to create new workers"); } return new PyPredictor<>(this, workerQueue.poll(), timeout, translator, device); } PyProcess worker = new PyProcess(this, pyEnv, -1); worker.startPythonProcess(); return new PyPredictor<>(this, worker, timeout, translator, device); } /** {@inheritDoc} */ @Override public void close() { super.close(); shutdown(); } private Path findModelFile(String prefix) { if (Files.isRegularFile(modelDir)) { Path file = modelDir; modelDir = modelDir.getParent(); if (file.toString().endsWith(".py")) { return file; } } else if (Files.isRegularFile(modelDir.resolve("MAR-INF/MANIFEST.json"))) { return Paths.get(""); } if (prefix == null) { prefix = modelName; } Path modelFile = modelDir.resolve(prefix); if (Files.notExists(modelFile) || !Files.isRegularFile(modelFile)) { if (prefix.endsWith(".py")) { return null; } modelFile = modelDir.resolve("model.py"); if (Files.notExists(modelFile) || !Files.isRegularFile(modelFile)) { return null; } } return modelFile; } private void createAllPyProcesses(int mpiWorkers, int tp) { long begin = System.currentTimeMillis(); ExecutorService pool = null; List<Future<?>> futures = new ArrayList<>(); if (parallelLoading) { pool = Executors.newFixedThreadPool(mpiWorkers); } logger.info("Start {} mpiWorkers ...", mpiWorkers); int deviceId = manager.getDevice().getDeviceId(); for (int i = 0; i < mpiWorkers; ++i) { logger.debug("Pre-creating python worker: {} ", i); PyProcess worker = new PyProcess(this, pyEnv, deviceId + i * tp); workerQueue.offer(worker); if (pool != null) { logger.debug("Submitting to pool: {}", i); futures.add(pool.submit(worker::startPythonProcess)); } else { worker.startPythonProcess(); } } if (pool != null) { pool.shutdown(); for (Future<?> future : futures) { try { future.get(); } catch (ExecutionException e) { shutdown(); throw new EngineException("Failed to start worker", e.getCause()); // NOPMD } catch (InterruptedException e) { shutdown(); throw new AssertionError("Worker startup interrupted.", e); } } } long duration = System.currentTimeMillis() - begin; logger.info("{} model loaded in {} ms.", modelName, duration); } private void shutdown() { for (PyProcess process : workerQueue) { process.stopPythonProcess(false); } workerQueue.clear(); if (pyEnv.isEnableVenv()) { pyEnv.deleteVirtualEnv(Utils.hash(modelDir.toString())); } } }
0
java-sources/ai/djl/python/python/0.28.0/ai/djl/python
java-sources/ai/djl/python/python/0.28.0/ai/djl/python/engine/PyPredictor.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.python.engine; import ai.djl.Device; import ai.djl.Model; import ai.djl.inference.Predictor; import ai.djl.modality.Input; import ai.djl.modality.Output; import ai.djl.ndarray.BytesSupplier; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.translate.TranslateException; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; import ai.djl.util.Pair; import ai.djl.util.PairList; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; class PyPredictor<I, O> extends Predictor<I, O> { private static final Pattern BATCH_PATTERN = Pattern.compile("batch_(\\d+)\\.(.*)"); private PyProcess process; private int timeout; private boolean isRollingBatch; private RollingBatch rollingBatch; public PyPredictor( Model model, PyProcess process, int timeout, Translator<I, O> translator, Device device) { super(model, translator, device, false); this.process = process; this.timeout = timeout; isRollingBatch = model.getProperty("rolling_batch") != null && !"disable".equals(model.getProperty("rolling_batch")); if (isRollingBatch) { rollingBatch = new RollingBatch(process, model, timeout); } } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public List<O> batchPredict(List<I> inputs) throws TranslateException { if (process.isStopped()) { // TODO: wait for restart throw new TranslateException("Backend Python process is stopped."); } Object first = inputs.get(0); if (first instanceof Input) { int size = inputs.size(); if (size == 1) { Output output; Input input = (Input) first; if (isRollingBatch && !input.getProperties().containsKey("handler")) { output = rollingBatch.addInput(input, timeout); } else { output = process.predict(input, timeout, false); } return Collections.singletonList((O) output); } Input batch = new Input(); List<O> ret = new ArrayList<>(size); batch.addProperty("batch_size", String.valueOf(size)); for (int i = 0; i < size; ++i) { Input in = (Input) inputs.get(i); // TODO: max 999 batch size String prefix; if (i > 99) { prefix = "batch_" + i + '.'; } else if (i > 9) { prefix = "batch_0" + i + '.'; } else { prefix = "batch_00" + i + '.'; } for (Map.Entry<String, String> entry : in.getProperties().entrySet()) { String key = prefix + entry.getKey(); batch.addProperty(key, entry.getValue()); } PairList<String, BytesSupplier> content = in.getContent(); for (Pair<String, BytesSupplier> pair : content) { String key = pair.getKey(); key = key == null ? "data" : key; batch.add(prefix + key, pair.getValue()); } } Output output = process.predict(batch, timeout, false); if (output.getCode() >= 300) { for (int i = 0; i < size; ++i) { ret.add((O) output); } return ret; } if (output.getContent().size() != size) { throw new TranslateException( "Batch output size mismatch, expected: " + size + ", actual: " + output.getContent().size()); } for (int i = 0; i < size; ++i) { Output out = new Output(); out.setCode(output.getCode()); out.setMessage(output.getMessage()); out.setProperties(output.getProperties()); ret.add((O) out); } PairList<String, BytesSupplier> content = output.getContent(); for (Pair<String, BytesSupplier> pair : content) { String key = pair.getKey(); Matcher m = BATCH_PATTERN.matcher(key); if (!m.matches()) { throw new TranslateException("Unexpected batch output key: " + key); } int index = Integer.parseInt(m.group(1)); Output out = (Output) ret.get(index); out.add(m.group(2), pair.getValue()); } return ret; } return super.batchPredict(inputs); } /** {@inheritDoc} */ @Override protected NDList predictInternal(TranslatorContext ctx, NDList ndList) { Input inputs = new Input(); inputs.addProperty("Content-Type", "tensor/ndlist"); inputs.add(ndList.encode()); Output output = process.predict(inputs, timeout, false); NDManager manager = ndList.head().getManager(); return output.getDataAsNDList(manager); } /** {@inheritDoc} */ @Override public void close() { super.close(); process.stopPythonProcess(false); if (rollingBatch != null) { rollingBatch.shutdown(); } } }
0
java-sources/ai/djl/python/python/0.28.0/ai/djl/python
java-sources/ai/djl/python/python/0.28.0/ai/djl/python/engine/PyProcess.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.python.engine; import ai.djl.Model; import ai.djl.engine.EngineException; import ai.djl.metric.Metric; import ai.djl.modality.Input; import ai.djl.modality.Output; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; class PyProcess { static final Logger logger = LoggerFactory.getLogger(PyProcess.class); static final Logger MODEL_METRIC = LoggerFactory.getLogger("model_metric"); private PyEnv pyEnv; private Model model; private int workerId; private Process process; private String pid; private List<Connection> connections; private CountDownLatch latch; private volatile boolean started; // NOPMD private AtomicInteger restartCount; private CompletableFuture<Void> restartFuture; private boolean trtLlmMode; private static AtomicInteger counter = new AtomicInteger(0); PyProcess(Model model, PyEnv pyEnv, int workerId) { this.model = model; this.pyEnv = pyEnv; this.workerId = workerId; int port = counter.getAndIncrement(); if (pyEnv.isMpiMode()) { int tensorParallelDegree = pyEnv.getTensorParallelDegree(); connections = new ArrayList<>(tensorParallelDegree); for (int i = 0; i < tensorParallelDegree; ++i) { connections.add(new Connection(pyEnv, port, i)); } counter.set(port + tensorParallelDegree); } else { connections = Collections.singletonList(new Connection(pyEnv, port, -1)); } restartCount = new AtomicInteger(0); // TODO: avoid using this hack when TRT-LLM improve its behavior trtLlmMode = "trtllm".equals(model.getProperty("rolling_batch")); } Output predict(Input inputs, int timeout, boolean initialLoad) { try { if (inputs.getProperty("handler", null) == null) { String handler = pyEnv.getHandler(); if (handler != null) { inputs.addProperty("handler", handler); } } List<CompletableFuture<Output>> futures = new ArrayList<>(connections.size()); if (initialLoad || !trtLlmMode) { for (Connection conn : connections) { futures.add(conn.send(inputs)); } } else { futures.add(connections.get(0).send(inputs)); } Output output = null; if (trtLlmMode) { output = futures.get(0).get(timeout, TimeUnit.SECONDS); } else { for (CompletableFuture<Output> future : futures) { output = future.get(timeout, TimeUnit.SECONDS); } } if (initialLoad && output != null) { int code = output.getCode(); if (code >= 300) { if (code == 507) { throw new EngineException("OOM"); } if (pyEnv.isFailOnInitialize()) { throw new EngineException( "Failed to initialize model: " + output.getMessage()); } logger.warn("Model doesn't support initialize: {}", output.getMessage()); } else { logger.info("Model [{}] initialized.", model.getName()); } } return output; } catch (Throwable e) { // use Throwable to workaround spotbug false alarm logger.debug("predict[init={}] exception: {}", initialLoad, e.getClass().getName()); stopPythonProcess(!initialLoad); if (!initialLoad) { logger.info("Restart python process ..."); restartFuture = CompletableFuture.runAsync(this::startPythonProcess); } if (e instanceof EngineException) { throw (EngineException) e; } throw new EngineException(e); } } synchronized void startPythonProcess() { try { int id = restartCount.get(); int port = connections.get(0).getPort(); logger.info("Start process: {} - retry: {}", port, id); pyEnv.installDependency(model.getModelPath()); process = Connection.startPython(pyEnv, model, workerId, port); pid = process.toString().split(", ")[0].replace("Process[pid=", ""); String modelName = model.getName(); modelName = modelName.substring(0, Math.min(modelName.length(), 15)); String threadName = "W-" + pid + '-' + modelName; ReaderThread err = new ReaderThread(threadName, process.getErrorStream(), true, this, id); ReaderThread out = new ReaderThread(threadName, process.getInputStream(), false, this, id); latch = new CountDownLatch(connections.size()); err.start(); out.start(); if (!latch.await(2, TimeUnit.MINUTES)) { throw new EngineException("Python process startup time out."); } if (!started) { logger.warn("Process not started, waiting for process end ..."); int exitCode = process.waitFor(); throw new IllegalThreadStateException( "Python stream closed unexpectedly, exit code: " + exitCode); } for (Connection conn : connections) { conn.connect(); } // initialize model with an empty request Input init = new Input(); init.setProperties(pyEnv.getInitParameters()); predict(init, pyEnv.getModelLoadingTimeout(), true); } catch (EngineException e) { started = false; throw e; } catch (InterruptedException e) { started = false; throw new EngineException("Worker startup cancelled.", e); } catch (IOException e) { started = false; throw new EngineException("Failed connect to Python worker process.", e); } catch (Exception e) { started = false; throw new EngineException("Failed to loaded model.", e); } finally { if (!started) { stopPythonProcess(true); } } } synchronized void stopPythonProcess(boolean error) { restartCount.getAndIncrement(); logger.info("Stop process: {}:{}, failure={}", workerId, pid, error); if (error) { int failures = model.intProperty("failed", 0); model.setProperty("failed", String.valueOf(failures + 1)); logger.info("Failure count: {}", failures); } if (restartFuture != null) { try { if (!restartFuture.isDone()) { if (!restartFuture.cancel(true)) { logger.warn("Failed to cancel restart python process task."); } else { logger.info("Python process restart is cancelled."); } } } catch (CancellationException ignore) { // ignore } restartFuture = null; } for (Connection conn : connections) { conn.disconnect(); } if (process != null) { started = false; process.destroyForcibly(); process = null; } } void setStarted(boolean started, int id) { if (restartCount.get() == id) { this.started = started; if (started) { latch.countDown(); } else { while (latch.getCount() > 0) { latch.countDown(); } } } } boolean isStopped() { return !started; } static final class ReaderThread extends Thread { private InputStream is; private boolean error; private PyProcess lifeCycle; private int processId; public ReaderThread( String name, InputStream is, boolean error, PyProcess lifeCycle, int processId) { super(name + (error ? "-stderr" : "-stdout")); this.is = is; this.error = error; this.lifeCycle = lifeCycle; this.processId = processId; } @Override @SuppressWarnings("PMD.UseTryWithResources") public void run() { try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8)) { while (scanner.hasNext()) { String result = scanner.nextLine(); if (result == null) { logger.warn("Got EOF: {}", getName()); break; } if (result.contains("Python engine started.")) { logger.info("{}: {}", getName(), result); lifeCycle.setStarted(true, processId); continue; } int metricLoc = result.indexOf("[METRICS]"); if (metricLoc != -1) { MODEL_METRIC.info("{}", Metric.parse(result.substring(metricLoc + 9))); continue; } if (error) { logger.warn("{}: {}", getName(), result); } else { logger.info("{}: {}", getName(), result); } } } catch (Exception e) { logger.error("Couldn't create scanner - {}", getName(), e); } finally { logger.info("ReaderThread({}) stopped - {}", processId, getName()); lifeCycle.setStarted(false, processId); try { is.close(); } catch (IOException e) { logger.warn("Failed to close stream for thread - " + getName(), e); } } } } }
0
java-sources/ai/djl/python/python/0.28.0/ai/djl/python
java-sources/ai/djl/python/python/0.28.0/ai/djl/python/engine/RollingBatch.java
/* * Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.python.engine; import ai.djl.Model; import ai.djl.engine.EngineException; import ai.djl.inference.streaming.ChunkedBytesSupplier; import ai.djl.metric.Dimension; import ai.djl.metric.Metric; import ai.djl.metric.Metrics; import ai.djl.metric.Unit; import ai.djl.modality.Input; import ai.djl.modality.Output; import ai.djl.ndarray.BytesSupplier; import ai.djl.translate.TranslateException; import ai.djl.util.JsonUtils; import ai.djl.util.PairList; import ai.djl.util.RandomUtils; import com.google.gson.JsonObject; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; class RollingBatch implements Runnable { private static final Logger logger = LoggerFactory.getLogger(RollingBatch.class); private static final Logger MODEL_METRIC = LoggerFactory.getLogger("model_metric"); private static ExecutorService threadPool = Executors.newCachedThreadPool( r -> { Thread t = Executors.defaultThreadFactory().newThread(r); t.setDaemon(true); return t; }); private PyProcess process; private int maxRollingBatchSize; private int timeout; private boolean stop; private List<Request> list; private Thread currentThread; private ReentrantLock lock; private Condition canAdd; private Condition canRead; private boolean resetRollingBatch; private Metrics metrics; private Dimension dimension; RollingBatch(PyProcess process, Model model, int timeout) { this.process = process; this.timeout = timeout; this.dimension = new Dimension("Model", model.getProperty("metric_dimension", "model")); maxRollingBatchSize = model.intProperty("max_rolling_batch_size", 32); // TODO: find a way to support custom output_formatter list = new ArrayList<>(3); lock = new ReentrantLock(true); canAdd = lock.newCondition(); canRead = lock.newCondition(); threadPool.submit(this); if (Boolean.parseBoolean(model.getProperty("log_request_metric"))) { int metricsAggregation = model.intProperty("metrics_aggregation", 1000); metrics = new Metrics(); metrics.setLimit(metricsAggregation); metrics.setOnLimit( (m, s) -> { MODEL_METRIC.info("{}", m.percentile(s, 50)); MODEL_METRIC.info("{}", m.percentile(s, 90)); }); } } /** {@inheritDoc} */ @Override public void run() { currentThread = Thread.currentThread(); while (!stop) { int size; Input batch = new Input(); try { lock.lock(); if (list.isEmpty()) { canRead.await(); } if (resetRollingBatch) { batch.addProperty("reset_rollingbatch", "true"); resetRollingBatch = false; } size = list.size(); for (int i = 0; i < size; ++i) { Request req = list.get(i); // TODO: max 999 batch size String prefix; if (i > 99) { prefix = "batch_" + i + '.'; } else if (i > 9) { prefix = "batch_0" + i + '.'; } else { prefix = "batch_00" + i + '.'; } for (Map.Entry<String, String> entry : req.getProperties()) { String key = prefix + entry.getKey(); batch.addProperty(key, entry.getValue()); } batch.add(prefix + "data", req.getRequest()); String seed = req.getSeed(); if (seed != null) { batch.add(prefix + "seed", req.seed); } } batch.addProperty("batch_size", String.valueOf(size)); } catch (InterruptedException e) { logger.warn("rolling batch loop interrupted.", e); break; } finally { lock.unlock(); } Output output; try { output = process.predict(batch, timeout, false); } catch (EngineException e) { logger.warn("prediction failed.", e); list.clear(); resetRollingBatch = true; continue; } try { lock.lock(); PairList<String, BytesSupplier> content = output.getContent(); // TODO: optimize for conditional killing int code = output.getCode(); Map<String, String> prop = output.getProperties(); if (code != 200 || content.size() != size) { if (code != 200) { logger.warn("Batch inference failed: {}", output.getMessage()); } else { logger.error( "Batch output size mismatch, expected: {}, actual: {}", size, content.size()); } Output out = new Output(output.getCode(), "Batch inference failed"); BytesSupplier err = BytesSupplier.wrap(JsonUtils.GSON.toJson(out)); for (Request req : list) { req.last = true; req.data.appendContent(err, true); } list.clear(); resetRollingBatch = true; canAdd.signal(); continue; } Iterator<Map.Entry<String, String>> it = prop.entrySet().iterator(); Map<Integer, Map<String, String>> map = new ConcurrentHashMap<>(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); String key = entry.getKey(); if (key.startsWith("batch_")) { it.remove(); int pos = key.indexOf('_', 7); if (pos > 0) { int index = Integer.parseInt(key.substring(6, pos)); Map<String, String> p = map.computeIfAbsent(index, i -> new ConcurrentHashMap<>()); p.put(key.substring(pos + 1), entry.getValue()); } } } for (int i = 0; i < size; ++i) { Request status = list.get(i); byte[] resp = content.get(i).getValue().getAsBytes(); Map<String, String> properties = map.get(i); status.addResponse(resp, properties); } if (list.removeIf(status -> status.last) || list.size() < maxRollingBatchSize) { canAdd.signal(); } logger.trace("rolling batch size: {}", size); if (metrics != null) { metrics.addMetric("RollingBatchSize", size, Unit.COUNT_PER_ITEM, dimension); } } finally { lock.unlock(); } } } public Output addInput(Input input, int timeout) throws TranslateException { try { lock.lock(); if (list.size() >= maxRollingBatchSize) { logger.debug("exceed max_rolling_batch_size: {}", maxRollingBatchSize); if (!canAdd.await(timeout, TimeUnit.SECONDS)) { Metric metric = new Metric("RollingBatchTimeout", list.size(), Unit.COUNT, dimension); MODEL_METRIC.info("{}", metric); throw new TranslateException("Time out in: " + timeout); } } String seed = String.valueOf(RandomUtils.nextInt()); Request req = new Request(input, seed, metrics, dimension); list.add(req); canRead.signal(); return req.output; } catch (InterruptedException e) { throw new TranslateException("Interrupted", e); } finally { lock.unlock(); } } public void shutdown() { this.stop = true; threadPool.shutdown(); currentThread.interrupt(); } private static final class Request { Input input; ChunkedBytesSupplier data; Output output; String nextToken; boolean last; String seed; Metrics metrics; Dimension dimension; int count; long creationTime; Request(Input input, String seed, Metrics metrics, Dimension dimension) { this.input = input; data = new ChunkedBytesSupplier(); output = new Output(); output.add(data); this.seed = seed; this.metrics = metrics; this.dimension = dimension; creationTime = System.nanoTime(); } BytesSupplier getRequest() { if (nextToken != null) { return BytesSupplier.wrap(""); } return input.getData(); } Set<Map.Entry<String, String>> getProperties() { if (nextToken != null) { return Collections.emptySet(); } return input.getProperties().entrySet(); } /** * Seed is required for LMI Dist for sampling for all processes in the MPI to generate the * same token. NextTokenChooserParameters is constructed during first forward and preserved * for all forward calls of the request. * * @return seed, only for first forward */ String getSeed() { if (nextToken != null) { return null; } return seed; } void addResponse(byte[] json, Map<String, String> properties) { if (properties != null) { output.getProperties().putAll(properties); } ++count; if (json[0] == '{') { // TODO: backward compatible for 0.23.0 release in case user // customize huggingface.parse_input() String s = new String(json, StandardCharsets.UTF_8); JsonObject element = JsonUtils.GSON.fromJson(s, JsonObject.class); last = element.get("last").getAsBoolean(); nextToken = element.get("data").getAsString(); try { JsonObject content = JsonUtils.GSON.fromJson(nextToken, JsonObject.class); output.setCode(content.get("code").getAsInt()); output.setMessage(content.get("error").getAsString()); } catch (Throwable ignore) { // ignore } data.appendContent(nextToken.getBytes(StandardCharsets.UTF_8), last); return; } ByteBuf buf = Unpooled.wrappedBuffer(json); int size = buf.readShort(); String code = null; String error = null; for (int i = 0; i < size; ++i) { String key = Objects.requireNonNull(CodecUtils.readUtf8(buf)); String value = Objects.requireNonNull(CodecUtils.readUtf8(buf)); switch (key) { case "data": nextToken = value; break; case "last": last = "true".equalsIgnoreCase(value); break; case "code": code = value; break; case "error": error = value; break; default: break; } } if (code != null) { Map<String, Object> map = new ConcurrentHashMap<>(2); map.put("code", Integer.parseInt(code)); if (error != null) { map.put("error", error); } byte[] buffer = JsonUtils.GSON.toJson(map).getBytes(StandardCharsets.UTF_8); data.appendContent(buffer, true); } else { if (last && metrics != null) { long duration = System.nanoTime() - creationTime; double throughput = count * 1_000_000_000d / duration; long latency = duration / count / 1000; metrics.addMetric("TokenLatency", latency, Unit.MICROSECONDS, dimension); metrics.addMetric( "TokenThroughput", throughput, Unit.COUNT_PER_SECOND, dimension); metrics.addMetric("OutputTokens", count, Unit.COUNT_PER_ITEM, dimension); } data.appendContent(nextToken.getBytes(StandardCharsets.UTF_8), last); } } } }
0
java-sources/ai/djl/python/python/0.28.0/ai/djl/python
java-sources/ai/djl/python/python/0.28.0/ai/djl/python/engine/package-info.java
/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** Contains classes to interface with the underlying Python worker. */ package ai.djl.python.engine;
0
java-sources/ai/djl/pytorch/pytorch-engine/0.34.0/ai/djl/pytorch
java-sources/ai/djl/pytorch/pytorch-engine/0.34.0/ai/djl/pytorch/engine/PtDeviceType.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.pytorch.engine; import ai.djl.Device; /** DeviceType is the PyTorch equivalent of the types in {@link Device}. */ public final class PtDeviceType { private PtDeviceType() {} /** * Converts a {@link Device} to the corresponding PyTorch device number. * * @param device the java {@link Device} * @return the PyTorch device number */ public static int toDeviceType(Device device) { String deviceType = device.getDeviceType(); if (Device.Type.CPU.equals(deviceType)) { return 0; } else if (Device.Type.GPU.equals(deviceType)) { return 1; } else if ("mps".equals(deviceType)) { return 13; } else { throw new IllegalArgumentException("Unsupported device: " + device); } } /** * Converts from an PyTorch device number to {@link Device}. * * @param deviceType the PyTorch device number * @return the corresponding {@link Device} */ public static String fromDeviceType(int deviceType) { switch (deviceType) { case 0: return Device.Type.CPU; case 1: return Device.Type.GPU; case 13: return "mps"; default: throw new IllegalArgumentException("Unsupported deviceType: " + deviceType); } } }
0
java-sources/ai/djl/pytorch/pytorch-engine/0.34.0/ai/djl/pytorch
java-sources/ai/djl/pytorch/pytorch-engine/0.34.0/ai/djl/pytorch/engine/PtEngine.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.pytorch.engine; import ai.djl.Device; import ai.djl.Model; import ai.djl.engine.Engine; import ai.djl.engine.EngineException; import ai.djl.ndarray.NDManager; import ai.djl.nn.SymbolBlock; import ai.djl.pytorch.jni.JniUtils; import ai.djl.pytorch.jni.LibUtils; import ai.djl.training.GradientCollector; import ai.djl.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.FileNotFoundException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * The {@code PtEngine} is an implementation of the {@link Engine} based on the <a * href="https://pytorch.org/">PyTorch Deep Learning Framework</a>. * * <p>To get an instance of the {@code PtEngine} when it is not the default Engine, call {@link * Engine#getEngine(String)} with the Engine name "PyTorch". */ public final class PtEngine extends Engine { private static final Logger logger = LoggerFactory.getLogger(PtEngine.class); public static final String ENGINE_NAME = "PyTorch"; static final int RANK = 2; private PtEngine() {} @SuppressWarnings("PMD.AvoidRethrowingException") static Engine newInstance() { try { LibUtils.loadLibrary(); JniUtils.setGradMode(false); if (Integer.getInteger("ai.djl.pytorch.num_interop_threads") != null) { JniUtils.setNumInteropThreads( Integer.getInteger("ai.djl.pytorch.num_interop_threads")); } if (Integer.getInteger("ai.djl.pytorch.num_threads") != null) { JniUtils.setNumThreads(Integer.getInteger("ai.djl.pytorch.num_threads")); } // for ConvNN related model speed up if (Boolean.getBoolean("ai.djl.pytorch.cudnn_benchmark")) { JniUtils.setBenchmarkCuDNN(true); } if ("true".equals(System.getProperty("ai.djl.pytorch.graph_optimizer", "true"))) { logger.info( "PyTorch graph executor optimizer is enabled, this may impact your" + " inference latency and throughput. See:" + " https://docs.djl.ai/master/docs/development/inference_performance_optimization.html#graph-executor-optimization"); } logger.info("Number of inter-op threads is {}", JniUtils.getNumInteropThreads()); logger.info("Number of intra-op threads is {}", JniUtils.getNumThreads()); String paths = Utils.getEnvOrSystemProperty("PYTORCH_EXTRA_LIBRARY_PATH"); if (paths != null) { String[] files = paths.split(","); for (String file : files) { Path path = Paths.get(file); if (Files.notExists(path)) { throw new FileNotFoundException("PyTorch extra Library not found: " + file); } System.load(path.toAbsolutePath().toString()); // NOPMD } } return new PtEngine(); } catch (EngineException e) { throw e; } catch (Throwable t) { throw new EngineException("Failed to load PyTorch native library", t); } } /** {@inheritDoc} */ @Override public Engine getAlternativeEngine() { return null; } /** {@inheritDoc} */ @Override public String getEngineName() { return ENGINE_NAME; } /** {@inheritDoc} */ @Override public int getRank() { return RANK; } /** {@inheritDoc} */ @Override public String getVersion() { return LibUtils.getVersion(); } /** {@inheritDoc} */ @Override public boolean hasCapability(String capability) { return JniUtils.getFeatures().contains(capability); } /** {@inheritDoc} */ @Override public SymbolBlock newSymbolBlock(NDManager manager) { return new PtSymbolBlock((PtNDManager) manager); } /** {@inheritDoc} */ @Override public Model newModel(String name, Device device) { return new PtModel(name, device); } /** {@inheritDoc} */ @Override public NDManager newBaseManager() { return PtNDManager.getSystemManager().newSubManager(); } /** {@inheritDoc} */ @Override public NDManager newBaseManager(Device device) { return PtNDManager.getSystemManager().newSubManager(device); } /** {@inheritDoc} */ @Override public GradientCollector newGradientCollector() { return new PtGradientCollector(); } /** {@inheritDoc} */ @Override public void setRandomSeed(int seed) { super.setRandomSeed(seed); JniUtils.setSeed(seed); } /** {@inheritDoc} */ @Override public String toString() { StringBuilder sb = new StringBuilder(200); sb.append(getEngineName()).append(':').append(getVersion()).append(", capabilities: [\n"); for (String feature : JniUtils.getFeatures()) { sb.append("\t").append(feature).append(",\n"); // NOPMD } sb.append("]\nPyTorch Library: ").append(LibUtils.getLibtorchPath()); return sb.toString(); } }
0
java-sources/ai/djl/pytorch/pytorch-engine/0.34.0/ai/djl/pytorch
java-sources/ai/djl/pytorch/pytorch-engine/0.34.0/ai/djl/pytorch/engine/PtEngineProvider.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.pytorch.engine; import ai.djl.engine.Engine; import ai.djl.engine.EngineProvider; /** {@code PtEngineProvider} is the PyTorch implementation of {@link EngineProvider}. */ public class PtEngineProvider implements EngineProvider { private static volatile Engine engine; // NOPMD /** {@inheritDoc} */ @Override public String getEngineName() { return PtEngine.ENGINE_NAME; } /** {@inheritDoc} */ @Override public int getEngineRank() { return PtEngine.RANK; } /** {@inheritDoc} */ @Override public Engine getEngine() { if (engine == null) { synchronized (PtEngineProvider.class) { if (engine == null) { engine = PtEngine.newInstance(); } } } return engine; } }
0
java-sources/ai/djl/pytorch/pytorch-engine/0.34.0/ai/djl/pytorch
java-sources/ai/djl/pytorch/pytorch-engine/0.34.0/ai/djl/pytorch/engine/PtGradientCollector.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.pytorch.engine; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; import ai.djl.pytorch.jni.JniUtils; import ai.djl.training.GradientCollector; import java.util.concurrent.atomic.AtomicBoolean; /** {@code PtGradientCollector} is the PyTorch implementation of {@link GradientCollector}. */ public final class PtGradientCollector implements GradientCollector { private boolean gradModel; private static AtomicBoolean isCollecting = new AtomicBoolean(); /** Constructs a new {@code PtGradientCollector} instance. */ public PtGradientCollector() { gradModel = JniUtils.isGradMode(); JniUtils.setGradMode(true); boolean wasCollecting = isCollecting.getAndSet(true); if (wasCollecting) { throw new IllegalStateException( "A PtGradientCollector is already collecting. Only one can be collecting at a" + " time"); } // TODO Currently has performance implications and so has been disabled // Should fix and re-enable support for PyTorch gradient accumulation // See https://github.com/deepjavalibrary/djl/pull/2304 // zeroGradients(); } /** {@inheritDoc} */ @Override public void backward(NDArray target) { // TODO manager should create the new NDArray on the same device NDArray grad = target.getManager() .ones(target.getShape(), target.getDataType()) .toDevice(target.getDevice(), false); backward(target, grad, false, false); } /** * Computes the gradients of the NDArray w.r.t variables. * * @param target the target/head array to run backward on * @param grad The “vector” in the Jacobian-vector product, usually gradients w.r.t. each * element of corresponding tensors * @param keepGraph whether to retain the computation graph for another backward pass on the * same graph. By default the computation history is cleared. * @param createGraph If true, graph of the derivative will be constructed, allowing to compute * higher order derivative products. Defaults to false. */ private void backward(NDArray target, NDArray grad, boolean keepGraph, boolean createGraph) { JniUtils.backward((PtNDArray) target, (PtNDArray) grad, keepGraph, createGraph); } /** {@inheritDoc} */ @Override public void zeroGradients() { NDManager systemManager = PtNDManager.getSystemManager(); for (NDArray array : systemManager.getManagedArrays()) { if (array.hasGradient()) { array.getGradient().subi(array.getGradient()); } } } /** {@inheritDoc} */ @Override public void close() { if (!gradModel) { JniUtils.setGradMode(false); } isCollecting.set(false); // TODO: do some clean up if necessary } }
0
java-sources/ai/djl/pytorch/pytorch-engine/0.34.0/ai/djl/pytorch
java-sources/ai/djl/pytorch/pytorch-engine/0.34.0/ai/djl/pytorch/engine/PtModel.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.pytorch.engine; import ai.djl.BaseModel; import ai.djl.Device; import ai.djl.MalformedModelException; import ai.djl.Model; import ai.djl.ndarray.types.DataType; import ai.djl.nn.Parameter; import ai.djl.nn.Parameter.Type; import ai.djl.pytorch.jni.JniUtils; import ai.djl.training.Trainer; import ai.djl.training.TrainingConfig; import ai.djl.training.initializer.Initializer; import ai.djl.util.Pair; import ai.djl.util.PairList; import ai.djl.util.Utils; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; /** * {@code PtModel} is the PyTorch implementation of {@link Model}. * * <p>PtModel contains all the methods in Model to load and process a model. In addition, it * provides PyTorch Specific functionality */ public class PtModel extends BaseModel { /** * Constructs a new Model on a given device. * * @param name the model name * @param device the device the model should be located on */ PtModel(String name, Device device) { super(name); manager = PtNDManager.getSystemManager().newSubManager(device); manager.setName("ptModel"); dataType = DataType.FLOAT32; } /** {@inheritDoc} */ @Override public void load(Path modelPath, String prefix, Map<String, ?> options) throws IOException, MalformedModelException { setModelDir(modelPath); wasLoaded = true; Path modelFile; if (prefix != null) { modelFile = findModelFile(prefix); } else { // search for .pt file with modelName, folder name or "model.pt" modelFile = findModelFile(modelName, modelDir.toFile().getName(), "model.pt"); prefix = modelName; } if (block == null) { if (modelFile == null) { String fileName = prefix.endsWith(".pt") ? prefix : prefix + ".pt"; throw new FileNotFoundException(fileName + " file not found in: " + modelDir); } String[] extraFileKeys = Utils.EMPTY_ARRAY; String[] extraFileValues = Utils.EMPTY_ARRAY; boolean mapLocation = false; boolean trainParam = false; // load jit extra files if (options != null) { if (options.containsKey("extraFiles")) { extraFileKeys = ((String) options.get("extraFiles")).split(","); extraFileValues = new String[extraFileKeys.length]; } trainParam = Boolean.parseBoolean((String) options.get("trainParam")); mapLocation = Boolean.parseBoolean((String) options.get("mapLocation")); } block = JniUtils.loadModule( (PtNDManager) manager, modelFile, mapLocation, extraFileKeys, extraFileValues, trainParam); for (int i = 0; i < extraFileKeys.length; i++) { properties.put(extraFileKeys[i], extraFileValues[i]); } /* * By default, the parameters are frozen, since the previous version before adding this * trainParam, they were frozen due to the setting JITCallGuard guard, which disables * autograd. Also, the pretrained parameters usually should not be updated too much. It * is safe to freeze it. Users may unfreeze it and set their learning rate small. */ block.freezeParameters(!trainParam); } else { loadBlock(prefix, options); } } /** {@inheritDoc} */ @Override public void load(InputStream modelStream, Map<String, ?> options) throws IOException, MalformedModelException { boolean mapLocation = false; if (options != null) { mapLocation = Boolean.parseBoolean((String) options.get("mapLocation")); } load(modelStream, mapLocation); } /** * Load PyTorch model from {@link InputStream}. * * @param modelStream the stream of the model file * @param mapLocation force load to specified device if true * @throws IOException model loading error * @throws MalformedModelException if model file is corrupted */ public void load(InputStream modelStream, boolean mapLocation) throws IOException, MalformedModelException { wasLoaded = true; if (block == null) { modelDir = Files.createTempDirectory("pt-model"); modelDir.toFile().deleteOnExit(); block = JniUtils.loadModule((PtNDManager) manager, modelStream, mapLocation, false); /* * By default, the parameters are frozen, since the previous version before adding this * trainParam, they were frozen due to the setting JITCallGuard guard, which disables * autograd. Also, the pretrained parameters usually should not be updated too much. It * is safe to freeze it. Users may unfreeze it and set their learning rate small. */ block.freezeParameters(true); } else { readParameters(modelStream, Collections.emptyMap()); } } private Path findModelFile(String... prefixes) { if (Files.isRegularFile(modelDir)) { Path file = modelDir; modelDir = modelDir.getParent(); String fileName = file.toFile().getName(); if (fileName.endsWith(".pt")) { modelName = fileName.substring(0, fileName.length() - 3); } else { modelName = fileName; } return file; } for (String prefix : prefixes) { Path modelFile = modelDir.resolve(prefix); if (Files.isRegularFile(modelFile)) { return modelFile; } if (!prefix.endsWith(".pt")) { modelFile = modelDir.resolve(prefix + ".pt"); if (Files.isRegularFile(modelFile)) { return modelFile; } } } return null; } /** {@inheritDoc} */ @Override public Trainer newTrainer(TrainingConfig trainingConfig) { PairList<Initializer, Predicate<Parameter>> initializer = trainingConfig.getInitializers(); if (block == null) { throw new IllegalStateException( "You must set a block for the model before creating a new trainer"); } if (wasLoaded) { // Unfreeze parameters if training directly block.freezeParameters( false, p -> p.getType() != Type.RUNNING_MEAN && p.getType() != Type.RUNNING_VAR); } for (Pair<Initializer, Predicate<Parameter>> pair : initializer) { if (pair.getKey() != null && pair.getValue() != null) { block.setInitializer(pair.getKey(), pair.getValue()); } } return new Trainer(this, trainingConfig); } /** {@inheritDoc} */ @Override public String[] getArtifactNames() { try (Stream<Path> stream = Files.walk(modelDir)) { List<Path> files = stream.filter(Files::isRegularFile).collect(Collectors.toList()); List<String> ret = new ArrayList<>(files.size()); for (Path path : files) { String fileName = path.toFile().getName(); if (fileName.endsWith(".pt")) { // ignore model files. continue; } Path relative = modelDir.relativize(path); ret.add(relative.toString()); } return ret.toArray(Utils.EMPTY_ARRAY); } catch (IOException e) { throw new AssertionError("Failed list files", e); } } }
0
java-sources/ai/djl/pytorch/pytorch-engine/0.34.0/ai/djl/pytorch
java-sources/ai/djl/pytorch/pytorch-engine/0.34.0/ai/djl/pytorch/engine/PtNDArray.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.pytorch.engine; import ai.djl.Device; import ai.djl.ndarray.BaseNDManager; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.NDScope; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.ndarray.types.SparseFormat; import ai.djl.pytorch.jni.JniUtils; import ai.djl.util.NativeResource; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; /** {@code PtNDArray} is the PyTorch implementation of {@link NDArray}. */ public class PtNDArray extends NativeResource<Long> implements NDArray { private String name; private Device device; private DataType dataType; private Shape shape; private SparseFormat sparseFormat; // use Boolean object to maintain three status: null, false, true private Boolean hasGradient; private PtNDManager manager; private PtNDArrayEx ptNDArrayEx; private String[] strs; // keep a reference to direct buffer to avoid GC release the memory @SuppressWarnings("PMD.UnusedPrivateField") private ByteBuffer dataRef; /** * Constructs a PyTorch {@code NDArray} from a native handle (internal. Use {@link NDManager} * instead). * * @param manager the manager to attach the new array to * @param handle the pointer to the native PyTorch memory */ @SuppressWarnings("this-escape") public PtNDArray(PtNDManager manager, long handle) { super(handle); this.manager = manager; this.ptNDArrayEx = new PtNDArrayEx(this); manager.attachInternal(getUid(), this); NDScope.register(this); } /** * Constructs a PyTorch {@code NDArray} from a native handle (internal. Use {@link NDManager} * instead) with the data that is hold on Java side. * * @param manager the manager to attach the new array to * @param handle the pointer to the native PyTorch memory * @param data the direct buffer of the data */ @SuppressWarnings("this-escape") public PtNDArray(PtNDManager manager, long handle, ByteBuffer data) { super(handle); this.manager = manager; this.ptNDArrayEx = new PtNDArrayEx(this); manager.attachInternal(getUid(), this); dataRef = data; NDScope.register(this); } /** * Constructs a PyTorch {@code NDArray} to hold string array with a dummy native handle * (internal. Use {@link NDManager} instead) with the data that is hold on Java side. * * @param manager the manager to attach the new array to * @param strs the string array * @param shape the {@link Shape} of the {@link NDArray} */ @SuppressWarnings("this-escape") public PtNDArray(PtNDManager manager, String[] strs, Shape shape) { super(-1L); this.manager = manager; this.strs = strs; this.sparseFormat = SparseFormat.DENSE; this.shape = shape; this.dataType = DataType.STRING; NDScope.register(this); } /** {@inheritDoc} */ @Override public PtNDManager getManager() { return manager; } /** {@inheritDoc} */ @Override public String getName() { return name; } /** {@inheritDoc} */ @Override public void setName(String name) { this.name = name; } /** {@inheritDoc} */ @Override public DataType getDataType() { if (dataType == null) { dataType = JniUtils.getDataType(this); } return dataType; } /** {@inheritDoc} */ @Override public Device getDevice() { if (device == null) { device = JniUtils.getDevice(this); } return device; } /** {@inheritDoc} */ @Override public Shape getShape() { if (shape == null) { shape = JniUtils.getShape(this); } return shape; } /** {@inheritDoc} */ @Override public SparseFormat getSparseFormat() { if (sparseFormat == null) { sparseFormat = JniUtils.getSparseFormat(this); } return sparseFormat; } /** {@inheritDoc} */ @Override public PtNDArray toDevice(Device device, boolean copy) { if (device.equals(getDevice()) && !copy) { return this; } PtNDArray array = JniUtils.to(this, getDataType(), device); array.setName(getName()); return array; } /** {@inheritDoc} */ @Override public PtNDArray toType(DataType dataType, boolean copy) { if (dataType.equals(getDataType()) && !copy) { return this; } PtNDArray array = JniUtils.to(this, dataType, getDevice()); array.setName(array.getName()); return array; } /** {@inheritDoc} */ @Override public void setRequiresGradient(boolean requiresGrad) { JniUtils.attachGradient(this, requiresGrad); hasGradient = requiresGrad; } /** {@inheritDoc} */ @Override public PtNDArray getGradient() { if (!hasGradient()) { throw new IllegalStateException( "No gradient attached to this NDArray, please call array.setRequiresGradient()" + " on your NDArray or block.setInitializer() on your Block"); } PtNDArray res = JniUtils.getGradient(this); // If you call getGradient() before you run the backward, // you will get nothing in PyTorch engine. // To align with MXNet's behavior, we will create a zeros NDArray. // TODO should we access the grad NDArray after we close the parameter NDArray? if (res == null) { res = (PtNDArray) manager.zeros(getShape()); } return res; } /** {@inheritDoc} */ @Override public boolean hasGradient() { if (hasGradient == null) { hasGradient = JniUtils.requiresGrad(this); } return hasGradient; } /** {@inheritDoc} */ @Override public NDArray stopGradient() { return JniUtils.detachGradient(this); } /** {@inheritDoc} */ @Override public ByteBuffer toByteBuffer(boolean tryDirect) { if (getDataType() == DataType.STRING) { throw new UnsupportedOperationException( "toByteBuffer is not supported for String tensor."); } return JniUtils.getByteBuffer(this, tryDirect); } /** {@inheritDoc} */ @Override public String[] toStringArray(Charset charset) { return strs; } /** {@inheritDoc} */ @Override public void set(Buffer buffer) { int size = Math.toIntExact(size()); DataType type = getDataType(); BaseNDManager.validateBuffer(buffer, type, size); // TODO how do we handle the exception happened in the middle dataRef = null; if (buffer.isDirect() && buffer instanceof ByteBuffer) { // If NDArray is on the GPU, it is native code responsibility to control the data life // cycle if (!getDevice().isGpu()) { dataRef = (ByteBuffer) buffer; } JniUtils.set(this, (ByteBuffer) buffer); return; } // int8, uint8, boolean use ByteBuffer, so need to explicitly input DataType ByteBuffer buf = manager.allocateDirect(size * type.getNumOfBytes()); BaseNDManager.copyBuffer(buffer, buf); // If NDArray is on the GPU, it is native code responsibility to control the data life cycle if (!getDevice().isGpu()) { dataRef = buf; } JniUtils.set(this, buf); } /** {@inheritDoc} */ @Override public NDArray get(NDManager manager, long... indices) { return JniUtils.getItem(this, indices, (PtNDManager) manager); } /** {@inheritDoc} */ @Override public NDArray gather(NDArray index, int axis) { if (!(index instanceof PtNDArray)) { throw new IllegalArgumentException("Only PtNDArray index is supported."); } return JniUtils.gather(this, (PtNDArray) index, axis); } /** {@inheritDoc} */ @Override public NDArray gatherNd(NDArray index) { if (!(index instanceof PtNDArray)) { throw new IllegalArgumentException("Only PtNDArray index is supported."); } Shape indexShape = index.getShape(); Shape dataShape = getShape(); int indexingDepth = (int) indexShape.get(0); if (indexingDepth > dataShape.dimension()) { throw new IllegalArgumentException( "Indexing rank " + indexShape.get(0) + " exceeds the data rank " + dataShape.dimension()); } // Row-first order, the linear index is accumulated from z->y->x. // For example, dataShape = (3, 2, 3), indexShape = (2, 3, 3) // The method is: indexLinear = index[1] + index[0] * dataShape[1], row-first order // indexLinear has shape (3, 3), is from combining the index along 0 axis. // Each number in indexLinear is an indexing to an element in data (3, 2, ...). // data is flattened to be (3*2, ...) which can be indexed by indexLinear. // Finally, reshape the output to (3, 3, ...). Thus // totalShape = indexShape.slice(1).addAll(dataShape.slice(indexingDepth)); NDArray indexLinear = index.get("{}, ...", indexingDepth - 1); long dim = 1; for (int i = indexingDepth - 2; i > -1; i--) { dim = dim * dataShape.get(i + 1); indexLinear = indexLinear.addi(index.get("{}, ...", i).muli(dim)); } NDArray dataFlatten = this.flatten(0, indexingDepth - 1); return dataFlatten.get(indexLinear); } /** {@inheritDoc} */ @Override public NDArray take(NDManager manager, NDArray index) { if (!(index instanceof PtNDArray)) { throw new IllegalArgumentException("Only PtNDArray is supported."); } return JniUtils.take(this, (PtNDArray) index, (PtNDManager) manager); } /** {@inheritDoc} */ @Override public NDArray put(NDArray index, NDArray value) { if (!(index instanceof PtNDArray) || !(value instanceof PtNDArray)) { throw new IllegalArgumentException("Only PtNDArray is supported."); } return JniUtils.put(this, (PtNDArray) index, (PtNDArray) value); } /** {@inheritDoc} */ @Override public NDArray scatter(NDArray index, NDArray value, int axis) { if (!(index instanceof PtNDArray) || !(value instanceof PtNDArray)) { throw new IllegalArgumentException("Only PtNDArray is supported."); } return JniUtils.scatter(this, (PtNDArray) index, (PtNDArray) value, axis); } /** {@inheritDoc} */ @Override public void attach(NDManager manager) { detach(); this.manager = (PtNDManager) manager; manager.attachInternal(getUid(), this); } /** {@inheritDoc} */ @Override public void returnResource(NDManager manager) { detach(); this.manager = (PtNDManager) manager; manager.attachUncappedInternal(getUid(), this); } /** {@inheritDoc} */ @Override public void tempAttach(NDManager manager) { NDManager original = this.manager; detach(); this.manager = (PtNDManager) manager; manager.tempAttachInternal(original, getUid(), this); } /** {@inheritDoc} */ @Override public void detach() { manager.detachInternal(getUid()); manager = PtNDManager.getSystemManager(); } /** {@inheritDoc} */ @Override public NDArray duplicate() { NDArray array = JniUtils.clone(this); array.setName(getName()); return array; } /** {@inheritDoc} */ @Override public PtNDArray booleanMask(NDArray index, int axis) { Shape indexShape = index.getShape(); if (indexShape.equals(getShape())) { // Result is flattened since shape is undetermined return JniUtils.booleanMask(this, manager.from(index)); } else if (indexShape.equals(getShape().slice(axis))) { // index will be broadcast by default try (PtNDArray flattedResult = JniUtils.booleanMask(this, manager.from(index))) { // Shape recovery Shape remainder = getShape().slice(0, axis); long selectedSize = flattedResult.getShape().size() / remainder.size(); return flattedResult.reshape(remainder.addAll(new Shape(selectedSize))); } } else { throw new UnsupportedOperationException( "Not supported for shape not broadcastable " + indexShape + " vs " + getShape()); } } /** {@inheritDoc} */ @Override public NDArray sequenceMask(NDArray sequenceLength, float value) { throw new UnsupportedOperationException("Not implemented yet"); } /** {@inheritDoc} */ @Override public NDArray sequenceMask(NDArray sequenceLength) { throw new UnsupportedOperationException("Not implemented yet"); } /** {@inheritDoc} */ @Override public boolean contentEquals(Number number) { return contentEquals(manager.create(number)); } /** {@inheritDoc} */ @Override public boolean contentEquals(NDArray other) { if (other == null || (!shapeEquals(other))) { return false; } if (getDataType() != other.getDataType()) { return false; } if (getDataType() == DataType.STRING) { return Arrays.equals(toStringArray(), other.toStringArray()); } return JniUtils.contentEqual(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray eq(Number n) { try (NDArray number = manager.create(n)) { return eq(number); } } /** {@inheritDoc} */ @Override public PtNDArray eq(NDArray other) { return JniUtils.eq(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray neq(Number n) { try (NDArray number = manager.create(n)) { return neq(number); } } /** {@inheritDoc} */ @Override public PtNDArray neq(NDArray other) { return JniUtils.neq(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray gt(Number n) { try (NDArray number = manager.create(n)) { return gt(number); } } /** {@inheritDoc} */ @Override public PtNDArray gt(NDArray other) { return JniUtils.gt(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray gte(Number n) { try (NDArray number = manager.create(n)) { return gte(number); } } /** {@inheritDoc} */ @Override public PtNDArray gte(NDArray other) { return JniUtils.gte(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray lt(Number n) { try (NDArray number = manager.create(n)) { return lt(number); } } /** {@inheritDoc} */ @Override public PtNDArray lt(NDArray other) { return JniUtils.lt(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray lte(Number n) { try (NDArray number = manager.create(n)) { return lte(number); } } /** {@inheritDoc} */ @Override public PtNDArray lte(NDArray other) { return JniUtils.lte(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray add(Number n) { try (NDArray number = manager.create(n)) { return add(number); } } /** {@inheritDoc} */ @Override public PtNDArray add(NDArray other) { return JniUtils.add(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray sub(Number n) { try (NDArray number = manager.create(n)) { return sub(number); } } /** {@inheritDoc} */ @Override public PtNDArray sub(NDArray other) { return JniUtils.sub(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray mul(Number n) { try (NDArray number = manager.create(n)) { return mul(number); } } /** {@inheritDoc} */ @Override public PtNDArray mul(NDArray other) { return JniUtils.mul(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray div(Number n) { try (NDArray number = manager.create(n)) { return div(number); } } /** {@inheritDoc} */ @Override public PtNDArray div(NDArray other) { return JniUtils.div(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray mod(Number n) { try (NDArray number = manager.create(n)) { return mod(number); } } /** {@inheritDoc} */ @Override public PtNDArray mod(NDArray other) { return JniUtils.remainder(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray pow(Number n) { try (NDArray number = manager.create(n)) { return pow(number); } } /** {@inheritDoc} */ @Override public PtNDArray pow(NDArray other) { return JniUtils.pow(this, manager.from(other)); } /** {@inheritDoc} */ @Override public NDArray xlogy(NDArray other) { if (isScalar() || other.isScalar()) { throw new IllegalArgumentException("scalar is not allowed for xlogy()"); } return JniUtils.xlogy(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray addi(Number n) { try (NDArray number = manager.create(n)) { return addi(number); } } /** {@inheritDoc} */ @Override public PtNDArray addi(NDArray other) { JniUtils.addi(this, manager.from(other)); return this; } /** {@inheritDoc} */ @Override public PtNDArray subi(Number n) { try (NDArray number = manager.create(n)) { return subi(number); } } /** {@inheritDoc} */ @Override public PtNDArray subi(NDArray other) { JniUtils.subi(this, manager.from(other)); return this; } /** {@inheritDoc} */ @Override public PtNDArray muli(Number n) { try (NDArray number = manager.create(n)) { return muli(number); } } /** {@inheritDoc} */ @Override public PtNDArray muli(NDArray other) { JniUtils.muli(this, manager.from(other)); return this; } /** {@inheritDoc} */ @Override public PtNDArray divi(Number n) { try (NDArray number = manager.create(n)) { return divi(number); } } /** {@inheritDoc} */ @Override public PtNDArray divi(NDArray other) { JniUtils.divi(this, manager.from(other)); return this; } /** {@inheritDoc} */ @Override public PtNDArray modi(Number n) { try (NDArray number = manager.create(n)) { return modi(number); } } /** {@inheritDoc} */ @Override public PtNDArray modi(NDArray other) { JniUtils.remainderi(this, manager.from(other)); return this; } /** {@inheritDoc} */ @Override public PtNDArray powi(Number n) { try (NDArray number = manager.create(n)) { return powi(number); } } /** {@inheritDoc} */ @Override public PtNDArray powi(NDArray other) { JniUtils.powi(this, manager.from(other)); return this; } /** {@inheritDoc} */ @Override public PtNDArray sign() { return JniUtils.sign(this); } /** {@inheritDoc} */ @Override public PtNDArray signi() { JniUtils.signi(this); return this; } /** {@inheritDoc} */ @Override public PtNDArray maximum(Number n) { try (NDArray number = manager.create(n)) { return maximum(number); } } /** {@inheritDoc} */ @Override public PtNDArray maximum(NDArray other) { return JniUtils.max(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray minimum(Number n) { try (NDArray number = manager.create(n)) { return minimum(number); } } /** {@inheritDoc} */ @Override public PtNDArray minimum(NDArray other) { return JniUtils.min(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray all() { try (PtNDArray bool = toType(DataType.BOOLEAN, true)) { return JniUtils.all(bool); } } /** {@inheritDoc} */ @Override public PtNDArray any() { try (PtNDArray bool = toType(DataType.BOOLEAN, true)) { return JniUtils.any(bool); } } /** {@inheritDoc} */ @Override public PtNDArray none() { try (PtNDArray bool = toType(DataType.BOOLEAN, true)) { return JniUtils.none(bool); } } /** {@inheritDoc} */ @Override public PtNDArray neg() { return JniUtils.neg(this); } /** {@inheritDoc} */ @Override public PtNDArray negi() { JniUtils.negi(this); return this; } /** {@inheritDoc} */ @Override public PtNDArray abs() { return JniUtils.abs(this); } /** {@inheritDoc} */ @Override public PtNDArray square() { return JniUtils.square(this); } /** {@inheritDoc} */ @Override public NDArray sqrt() { return JniUtils.sqrt(this); } /** {@inheritDoc} */ @Override public PtNDArray cbrt() { return JniUtils.pow(this, (PtNDArray) manager.create(1.0 / 3)); } /** {@inheritDoc} */ @Override public PtNDArray floor() { return JniUtils.floor(this); } /** {@inheritDoc} */ @Override public PtNDArray ceil() { return JniUtils.ceil(this); } /** {@inheritDoc} */ @Override public PtNDArray round() { return JniUtils.round(this); } /** {@inheritDoc} */ @Override public PtNDArray trunc() { return JniUtils.trunc(this); } /** {@inheritDoc} */ @Override public PtNDArray exp() { return JniUtils.exp(this); } /** {@inheritDoc} */ @Override public NDArray gammaln() { return JniUtils.gammaln(this); } /** {@inheritDoc} */ @Override public PtNDArray log() { return JniUtils.log(this); } /** {@inheritDoc} */ @Override public PtNDArray log10() { return JniUtils.log10(this); } /** {@inheritDoc} */ @Override public PtNDArray log2() { return JniUtils.log2(this); } /** {@inheritDoc} */ @Override public PtNDArray sin() { return JniUtils.sin(this); } /** {@inheritDoc} */ @Override public PtNDArray cos() { return JniUtils.cos(this); } /** {@inheritDoc} */ @Override public PtNDArray tan() { return JniUtils.tan(this); } /** {@inheritDoc} */ @Override public PtNDArray asin() { return JniUtils.asin(this); } /** {@inheritDoc} */ @Override public PtNDArray acos() { return JniUtils.acos(this); } /** {@inheritDoc} */ @Override public PtNDArray atan() { return JniUtils.atan(this); } /** {@inheritDoc} */ @Override public PtNDArray atan2(NDArray other) { return JniUtils.atan2(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray sinh() { return JniUtils.sinh(this); } /** {@inheritDoc} */ @Override public PtNDArray cosh() { return JniUtils.cosh(this); } /** {@inheritDoc} */ @Override public PtNDArray tanh() { return JniUtils.tanh(this); } /** {@inheritDoc} */ @Override public PtNDArray asinh() { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public PtNDArray acosh() { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public PtNDArray atanh() { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public PtNDArray toDegrees() { return mul(180.0).div(Math.PI); } /** {@inheritDoc} */ @Override public PtNDArray toRadians() { return mul(Math.PI).div(180.0); } /** {@inheritDoc} */ @Override public PtNDArray max() { return JniUtils.max(this); } /** {@inheritDoc} */ @Override public PtNDArray max(int[] axes, boolean keepDims) { if (axes.length > 1) { // TODO fix this throw new UnsupportedOperationException("Only 1 axis is support!"); } return JniUtils.max(this, axes[0], keepDims); } /** {@inheritDoc} */ @Override public PtNDArray min() { return JniUtils.min(this); } /** {@inheritDoc} */ @Override public PtNDArray min(int[] axes, boolean keepDims) { if (axes.length > 1) { // TODO fix this throw new UnsupportedOperationException("Only 1 axis is support!"); } return JniUtils.min(this, axes[0], keepDims); } /** {@inheritDoc} */ @Override public PtNDArray sum() { return JniUtils.sum(this); } /** {@inheritDoc} */ @Override public PtNDArray sum(int[] axes, boolean keepDims) { return JniUtils.sum(this, Arrays.stream(axes).mapToLong(i -> i).toArray(), keepDims); } /** {@inheritDoc} */ @Override public NDArray cumProd(int axis) { return JniUtils.cumProd(this, axis, null); } /** {@inheritDoc} */ @Override public NDArray cumProd(int axis, DataType dataType) { return JniUtils.cumProd(this, axis, dataType); } /** {@inheritDoc} */ @Override public PtNDArray prod() { return JniUtils.prod(this); } /** {@inheritDoc} */ @Override public PtNDArray prod(int[] axes, boolean keepDims) { if (axes.length > 1) { throw new UnsupportedOperationException("Only 1 axis is support!"); } return JniUtils.prod(this, axes[0], keepDims); } /** {@inheritDoc} */ @Override public PtNDArray mean() { return JniUtils.mean(this); } /** {@inheritDoc} */ @Override public PtNDArray mean(int[] axes, boolean keepDims) { if (axes.length > 1) { // TODO fix this throw new UnsupportedOperationException("Only 1 axis is support!"); } return JniUtils.mean(this, axes[0], keepDims); } /** {@inheritDoc} */ @Override public PtNDArray normalize(double p, long dim, double eps) { return JniUtils.normalize(this, p, dim, eps); } /** {@inheritDoc} */ @Override public PtNDArray rotate90(int times, int[] axes) { if (axes.length != 2) { throw new IllegalArgumentException("Axes must be 2"); } return JniUtils.rot90(this, times, axes); } /** {@inheritDoc} */ @Override public PtNDArray trace(int offset, int axis1, int axis2) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public NDList split(long sections, int axis) { long size = getShape().get(axis) / sections; return JniUtils.split(this, size, axis); } /** {@inheritDoc} */ @Override public NDList split(long[] indices, int axis) { if (indices.length == 0) { return new NDList(this); } List<Long> ptIndex = new ArrayList<>(); ptIndex.add(indices[0]); for (int i = 1; i < indices.length; i++) { ptIndex.add(indices[i] - indices[i - 1]); } ptIndex.add(size(axis) - indices[indices.length - 1]); return JniUtils.split(this, ptIndex.stream().mapToLong(i -> i).toArray(), axis); } /** {@inheritDoc} */ @Override public PtNDArray flatten() { return JniUtils.flatten(this, 0, -1); } /** {@inheritDoc} */ @Override public NDArray flatten(int startDim, int endDim) { return JniUtils.flatten(this, startDim, endDim); } /** {@inheritDoc} */ @Override public NDArray fft(long length, long axis) { return JniUtils.fft(this, length, axis); } /** {@inheritDoc} */ @Override public NDArray rfft(long length, long axis) { return JniUtils.rfft(this, length, axis); } /** {@inheritDoc} */ @Override public NDArray ifft(long length, long axis) { return JniUtils.ifft(this, length, axis); } /** {@inheritDoc} */ @Override public NDArray irfft(long length, long axis) { return JniUtils.irfft(this, length, axis); } /** {@inheritDoc} */ @Override public NDArray stft( long nFft, long hopLength, boolean center, NDArray window, boolean normalize, boolean returnComplex) { return JniUtils.stft( this, nFft, hopLength, (PtNDArray) window, center, normalize, returnComplex); } /** {@inheritDoc} */ @Override public NDArray fft2(long[] sizes, long[] axes) { return JniUtils.fft2(this, sizes, axes); } /** {@inheritDoc} */ @Override public NDArray ifft2(long[] sizes, long[] axes) { return JniUtils.ifft2(this, sizes, axes); } /** {@inheritDoc} */ @Override public NDArray pad(Shape padding, double value) { return JniUtils.pad(this, padding.getShape(), value); } /** {@inheritDoc} */ @Override public PtNDArray reshape(Shape shape) { return JniUtils.reshape(this, shape.getShape()); } /** {@inheritDoc} */ @Override public PtNDArray expandDims(int axis) { return JniUtils.unsqueeze(this, axis); } /** {@inheritDoc} */ @Override public PtNDArray squeeze() { return JniUtils.squeeze(this); } /** {@inheritDoc} */ @Override public PtNDArray squeeze(int axis) { return JniUtils.squeeze(this, axis); } /** {@inheritDoc} */ @Override public PtNDArray squeeze(int[] axes) { if (isScalar()) { if (axes.length == 0 || (axes.length == 1 && axes[0] == 0)) { return (PtNDArray) duplicate(); } throw new IllegalArgumentException( "axis " + axes[0] + " is out of bounds for array of dimension 0"); } long[] shapeArr = getShape().getShape(); List<Long> newShape = new ArrayList<>(); Set<Integer> set = IntStream.of(axes).boxed().collect(Collectors.toCollection(HashSet::new)); // check input for (int axis : axes) { if (shapeArr[axis] != 1) { throw new IllegalArgumentException( "cannot select an axis to squeeze out which has size not equal to one"); } } for (int i = 0; i < shapeArr.length; i++) { if (!set.contains(i)) { newShape.add(shapeArr[i]); } } return (PtNDArray) reshape(newShape.stream().mapToLong(i -> i).toArray()); } /** {@inheritDoc} */ @Override public NDList unique(Integer dim, boolean sorted, boolean returnInverse, boolean returnCounts) { return JniUtils.unique(this, dim, sorted, returnInverse, returnCounts); } /** {@inheritDoc} */ @Override public PtNDArray logicalAnd(NDArray other) { return JniUtils.logicalAnd(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray logicalOr(NDArray other) { return JniUtils.logicalOr(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray logicalXor(NDArray other) { return JniUtils.logicalXor(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray logicalNot() { return JniUtils.logicalNot(this); } /** {@inheritDoc} */ @Override public PtNDArray argSort(int axis, boolean ascending) { PtNDArray arr = JniUtils.argSort(this, axis, false); if (ascending) { return arr; } PtNDArray flip = JniUtils.flip(arr, new long[] {axis}); arr.close(); return flip; } /** {@inheritDoc} */ @Override public PtNDArray sort() { return sort(-1); } /** {@inheritDoc} */ @Override public PtNDArray sort(int axis) { return JniUtils.sort(this, axis, false); } /** {@inheritDoc} */ @Override public PtNDArray softmax(int axis) { return JniUtils.softmax(this, axis, getDataType()); } /** {@inheritDoc} */ @Override public PtNDArray logSoftmax(int axis) { return JniUtils.logSoftmax(this, axis, getDataType()); } /** {@inheritDoc} */ @Override public PtNDArray cumSum() { // TODO: change default behavior on cumSum if (isScalar()) { return (PtNDArray) reshape(1); } if (isEmpty()) { return (PtNDArray) reshape(0); } return cumSum(0); } /** {@inheritDoc} */ @Override public PtNDArray cumSum(int axis) { return JniUtils.cumSum(this, axis); } /** {@inheritDoc} */ @Override public NDArray diagonal() { return JniUtils.diagonal(this, 0, 0, 1); } /** {@inheritDoc} */ @Override public NDArray diagonal(int offset) { return JniUtils.diagonal(this, offset, 0, 1); } /** {@inheritDoc} */ @Override public NDArray diagonal(int offset, int axis1, int axis2) { return JniUtils.diagonal(this, offset, axis1, axis2); } /** {@inheritDoc} */ @Override public void intern(NDArray replaced) { PtNDArray arr = (PtNDArray) replaced; Long oldHandle = handle.getAndSet(arr.handle.getAndSet(null)); JniUtils.deleteNDArray(oldHandle); // dereference old ndarray arr.close(); } /** {@inheritDoc} */ @Override public PtNDArray isInfinite() { return JniUtils.isInf(this); } /** {@inheritDoc} */ @Override public PtNDArray isNaN() { return JniUtils.isNaN(this); } /** {@inheritDoc} */ @Override public PtNDArray tile(long repeats) { // zero-dim if (isEmpty()) { return (PtNDArray) duplicate(); } // scalar int dim = (isScalar()) ? 1 : getShape().dimension(); long[] repeatsArray = new long[dim]; Arrays.fill(repeatsArray, repeats); return tile(repeatsArray); } /** {@inheritDoc} */ @Override public PtNDArray tile(int axis, long repeats) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public PtNDArray tile(long[] repeats) { return JniUtils.tile(this, repeats); } /** {@inheritDoc} */ @Override public PtNDArray tile(Shape desiredShape) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public PtNDArray repeat(long repeats) { // zero-dim if (isEmpty()) { return (PtNDArray) duplicate(); } // scalar int dim = (isScalar()) ? 1 : getShape().dimension(); long[] repeatsArray = new long[dim]; Arrays.fill(repeatsArray, repeats); return repeat(repeatsArray); } /** {@inheritDoc} */ @Override public PtNDArray repeat(int axis, long repeats) { return JniUtils.repeat(this, repeats, axis); } /** {@inheritDoc} */ @Override public PtNDArray repeat(long[] repeats) { PtNDArray result = this; for (int dim = 0; dim < repeats.length; dim++) { PtNDArray temp = result; result = JniUtils.repeat(result, repeats[dim], dim); if (temp != this) { temp.close(); } } return result; } /** {@inheritDoc} */ @Override public PtNDArray repeat(Shape desiredShape) { return repeat(repeatsToMatchShape(desiredShape)); } private long[] repeatsToMatchShape(Shape desiredShape) { Shape curShape = getShape(); int dimension = curShape.dimension(); if (desiredShape.dimension() > dimension) { throw new IllegalArgumentException("The desired shape has too many dimensions"); } if (desiredShape.dimension() < dimension) { int additionalDimensions = dimension - desiredShape.dimension(); desiredShape = curShape.slice(0, additionalDimensions).addAll(desiredShape); } long[] repeats = new long[dimension]; for (int i = 0; i < dimension; i++) { if (curShape.get(i) == 0 || desiredShape.get(i) % curShape.get(i) != 0) { throw new IllegalArgumentException( "The desired shape is not a multiple of the original shape"); } repeats[i] = Math.round(Math.ceil((double) desiredShape.get(i) / curShape.get(i))); } return repeats; } /** {@inheritDoc} */ @Override public PtNDArray dot(NDArray other) { int selfDim = this.getShape().dimension(); int otherDim = other.getShape().dimension(); if (selfDim != otherDim || selfDim > 2) { throw new UnsupportedOperationException( "Dimension mismatch or dimension is greater than 2. Dot product is only" + " applied on two 1D vectors. For high dimensions, please use .matMul" + " instead."); } return JniUtils.dot(this, manager.from(other)); } /** {@inheritDoc} */ @Override public NDArray matMul(NDArray other) { if (isScalar() || other.isScalar()) { throw new IllegalArgumentException("scalar is not allowed for matMul()"); } return JniUtils.matmul(this, manager.from(other)); } /** {@inheritDoc} */ @Override public NDArray batchMatMul(NDArray other) { if (isScalar() || other.isScalar()) { throw new IllegalArgumentException("scalar is not allowed for batchMatMul()"); } return JniUtils.bmm(this, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray clip(Number min, Number max) { return JniUtils.clip(this, min, max); } /** {@inheritDoc} */ @Override public PtNDArray swapAxes(int axis1, int axis2) { return JniUtils.transpose(this, axis1, axis2); } /** {@inheritDoc} */ @Override public NDArray flip(int... axes) { return JniUtils.flip(this, Arrays.stream(axes).mapToLong(ele -> (long) ele).toArray()); } /** {@inheritDoc} */ @Override public PtNDArray transpose() { int dim = getShape().dimension(); int[] reversedShape = IntStream.range(0, dim).map(i -> dim - i - 1).toArray(); return transpose(reversedShape); } /** {@inheritDoc} */ @Override public PtNDArray transpose(int... axes) { if (isScalar() && axes.length > 0) { throw new IllegalArgumentException("axes don't match NDArray"); } return JniUtils.permute(this, Arrays.stream(axes).mapToLong(i -> i).toArray()); } /** {@inheritDoc} */ @Override public PtNDArray broadcast(Shape shape) { return JniUtils.broadcast(this, shape); } /** {@inheritDoc} */ @Override public PtNDArray argMax() { if (isEmpty()) { throw new IllegalArgumentException("attempt to get argMax of an empty NDArray"); } if (isScalar()) { return (PtNDArray) manager.create(0L); } return JniUtils.argMax(this); } /** {@inheritDoc} */ @Override public PtNDArray argMax(int axis) { // TODO pytorch bug: https://github.com/pytorch/pytorch/issues/37084 if (isScalar()) { return (PtNDArray) manager.create(0L); } return JniUtils.argMax(this, axis, false); } /** {@inheritDoc} */ @Override public NDList topK(int k, int axis, boolean largest, boolean sorted) { return JniUtils.topK(this, k, axis, largest, sorted); } /** {@inheritDoc} */ @Override public PtNDArray argMin() { if (isEmpty()) { throw new IllegalArgumentException("attempt to get argMin of an empty NDArray"); } if (isScalar()) { return (PtNDArray) manager.create(0L); } return JniUtils.argMin(this); } /** {@inheritDoc} */ @Override public PtNDArray argMin(int axis) { // TODO pytorch bug: https://github.com/pytorch/pytorch/issues/37084 if (isScalar()) { return (PtNDArray) manager.create(0L); } return JniUtils.argMin(this, axis, false); } /** {@inheritDoc} */ @Override public PtNDArray percentile(Number percentile) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public PtNDArray percentile(Number percentile, int[] axes) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public PtNDArray median() { return median(new int[] {-1}); } /** {@inheritDoc} */ @Override public PtNDArray median(int[] axes) { if (axes.length != 1) { throw new UnsupportedOperationException( "Not supporting zero or multi-dimension median"); } NDList result = JniUtils.median(this, axes[0], false); result.get(1).close(); return (PtNDArray) result.get(0); } /** {@inheritDoc} */ @Override public PtNDArray toDense() { if (!isSparse() && JniUtils.getLayout(this) != 2) { return (PtNDArray) duplicate(); } return JniUtils.toDense(this); } /** {@inheritDoc} */ @Override public PtNDArray toSparse(SparseFormat fmt) { if (fmt == SparseFormat.DENSE) { throw new IllegalArgumentException("Default type is not allowed"); } if (fmt != SparseFormat.COO) { throw new UnsupportedOperationException("Only COO sparse type supported for PyTorch"); } if (fmt == getSparseFormat()) { return (PtNDArray) duplicate(); } return JniUtils.toSparse(this); } /** {@inheritDoc} */ @Override public PtNDArray nonzero() { return JniUtils.nonZeros(this); } /** {@inheritDoc} */ @Override public PtNDArray erfinv() { return JniUtils.erfinv(this); } /** {@inheritDoc} */ @Override public PtNDArray erf() { return JniUtils.erf(this); } /** {@inheritDoc} */ @Override public PtNDArray inverse() { return JniUtils.inverse(this); } /** {@inheritDoc} */ @Override public NDArray norm(boolean keepDims) { return JniUtils.norm(this, 2, new int[] {}, keepDims); } /** {@inheritDoc} */ @Override public NDArray norm(int order, int[] axes, boolean keepDims) { return JniUtils.norm(this, order, axes, keepDims); } /** {@inheritDoc} */ @Override public NDArray oneHot(int depth) { return JniUtils.oneHot(this, depth, DataType.FLOAT32); } /** {@inheritDoc} */ @Override public NDArray oneHot(int depth, DataType dataType) { return JniUtils.oneHot(this, depth, dataType); } /** {@inheritDoc} */ @Override public NDArray oneHot(int depth, float onValue, float offValue, DataType dataType) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public NDArray batchDot(NDArray other) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public NDArray complex() { return JniUtils.complex(this); } /** {@inheritDoc} */ @Override public NDArray real() { return JniUtils.real(this); } /** {@inheritDoc} */ @Override public NDArray conj() { return JniUtils.conj(this); } /** {@inheritDoc} */ @Override public NDArray diff(int n, int dim) { return JniUtils.diff(this, n, dim); } /** {@inheritDoc} */ @Override public PtNDArrayEx getNDArrayInternal() { if (ptNDArrayEx == null) { throw new UnsupportedOperationException( "NDArray operation is not supported for String tensor"); } return ptNDArrayEx; } /** {@inheritDoc} */ @Override public String toString() { if (isReleased()) { return "This array is already closed"; } if (getDataType() == DataType.STRING) { return Arrays.toString(strs); } // index operator in toDebugString is not supported for MKLDNN & Sparse layout if (JniUtils.getLayout(this) != 0) { try (NDArray tmp = toDense()) { return tmp.toDebugString(); } } return toDebugString(); } /** {@inheritDoc} */ @Override public boolean equals(Object obj) { if (obj instanceof NDArray) { return contentEquals((NDArray) obj); } return false; } /** {@inheritDoc} */ @Override public int hashCode() { return 0; } /** {@inheritDoc} */ @Override public void close() { onClose(); Long pointer = handle.getAndSet(null); if (pointer != null && pointer != -1) { JniUtils.deleteNDArray(pointer); } manager.detachInternal(getUid()); dataRef = null; } }
0
java-sources/ai/djl/pytorch/pytorch-engine/0.34.0/ai/djl/pytorch
java-sources/ai/djl/pytorch/pytorch-engine/0.34.0/ai/djl/pytorch/engine/PtNDArrayEx.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.pytorch.engine; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDArrays; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.NDUtils; import ai.djl.ndarray.index.NDArrayIndexer; import ai.djl.ndarray.internal.NDArrayEx; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.ndarray.types.SparseFormat; import ai.djl.nn.recurrent.RNN; import ai.djl.pytorch.jni.JniUtils; import java.util.Arrays; import java.util.Comparator; import java.util.List; /** {@code PtNDArrayEx} is the PyTorch implementation of the {@link NDArrayEx}. */ public class PtNDArrayEx implements NDArrayEx { private PtNDArray array; /** * Constructs an {@code PtNDArrayEx} given a {@link NDArray}. * * @param parent the {@link NDArray} to extend */ PtNDArrayEx(PtNDArray parent) { this.array = parent; } /** {@inheritDoc} */ @Override public PtNDArray rdivi(NDArray b) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public PtNDArray rmodi(NDArray b) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public PtNDArray rpowi(Number n) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public PtNDArray relu() { return JniUtils.relu(array); } /** {@inheritDoc} */ @Override public PtNDArray sigmoid() { return JniUtils.sigmoid(array); } /** {@inheritDoc} */ @Override public PtNDArray tanh() { return JniUtils.tanh(array); } /** {@inheritDoc} */ @Override public PtNDArray softPlus() { return JniUtils.softPlus(array); } /** {@inheritDoc} */ @Override public PtNDArray softSign() { return JniUtils.softSign(array); } /** {@inheritDoc} */ @Override public PtNDArray leakyRelu(float alpha) { return JniUtils.leakyRelu(array, alpha); } /** {@inheritDoc} */ @Override public PtNDArray elu(float alpha) { return JniUtils.elu(array, alpha); } /** {@inheritDoc} */ @Override public PtNDArray selu() { return JniUtils.selu(array); } /** {@inheritDoc} */ @Override public PtNDArray gelu() { return JniUtils.gelu(array); } /** {@inheritDoc} */ @Override public PtNDArray maxPool(Shape kernelShape, Shape stride, Shape padding, boolean ceilMode) { return JniUtils.maxPool(array, kernelShape, stride, padding, ceilMode); } /** {@inheritDoc} */ @Override public PtNDArray globalMaxPool() { Shape shape = getPoolShape(array); try (NDArray temp = JniUtils.adaptiveMaxPool(array, shape)) { return (PtNDArray) temp.reshape(array.getShape().slice(0, 2)); } } /** {@inheritDoc} */ @Override public PtNDArray avgPool( Shape kernelShape, Shape stride, Shape padding, boolean ceilMode, boolean countIncludePad) { return JniUtils.avgPool(array, kernelShape, stride, padding, ceilMode, countIncludePad); } /** {@inheritDoc} */ @Override public PtNDArray globalAvgPool() { Shape shape = getPoolShape(array); try (NDArray temp = JniUtils.adaptiveAvgPool(array, shape)) { return (PtNDArray) temp.reshape(array.getShape().slice(0, 2)); } } /** {@inheritDoc} */ @Override public PtNDArray lpPool( float normType, Shape kernelShape, Shape stride, Shape padding, boolean ceilMode) { if (padding.size() != 0) { throw new IllegalArgumentException("padding is not supported for PyTorch engine"); } return JniUtils.lpPool(array, normType, kernelShape, stride, ceilMode); } /** {@inheritDoc} */ @Override public PtNDArray globalLpPool(float normType) { try (NDArray temp = JniUtils.lpPool( array, normType, array.getShape().slice(2), getPoolShape(array), false)) { return (PtNDArray) temp.reshape(array.getShape().slice(0, 2)); } } /** {@inheritDoc} */ @Override public void adadeltaUpdate( NDList inputs, NDList weights, float weightDecay, float rescaleGrad, float clipGrad, float rho, float epsilon) { throw new UnsupportedOperationException( "AdaDelta optimzier is not supported for PyTorch engine!"); } /** {@inheritDoc} */ @Override public void adagradUpdate( NDList inputs, NDList weights, float learningRate, float weightDecay, float rescaleGrad, float clipGrad, float epsilon) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public void adamUpdate( NDList inputs, NDList weights, float learningRate, float learningRateBiasCorrection, float weightDecay, float rescaleGrad, float clipGrad, float beta1, float beta2, float epsilon, boolean lazyUpdate, boolean adamw) { // TODO: Lazy update not used PtNDManager manager = array.getManager(); JniUtils.adamUpdate( manager.from(inputs.get(0)), manager.from(inputs.get(1)), manager.from(inputs.get(2)), manager.from(inputs.get(3)), learningRate, learningRateBiasCorrection, weightDecay, rescaleGrad, clipGrad, beta1, beta2, epsilon, adamw); // call zero-grad JniUtils.zeroGrad(manager.from(weights.singletonOrThrow())); } /** {@inheritDoc} */ @Override public void nagUpdate( NDList inputs, NDList weights, float learningRate, float weightDecay, float rescaleGrad, float clipGrad, float momentum) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public void rmspropUpdate( NDList inputs, NDList weights, float learningRate, float weightDecay, float rescaleGrad, float clipGrad, float rho, float momentum, float epsilon, boolean centered) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public void sgdUpdate( NDList inputs, NDList weights, float learningRate, float weightDecay, float rescaleGrad, float clipGrad, float momentum, boolean lazyUpdate) { // TODO: Lazy update not used PtNDManager manager = array.getManager(); JniUtils.sgdUpdate( manager.from(inputs.get(0)), manager.from(inputs.get(1)), (momentum == 0f) ? null : manager.from(inputs.get(2)), learningRate, weightDecay, rescaleGrad, clipGrad, momentum); // call zero-grad JniUtils.zeroGrad(manager.from(weights.singletonOrThrow())); } /** {@inheritDoc} */ @Override public NDList convolution( NDArray input, NDArray weight, NDArray bias, Shape stride, Shape padding, Shape dilation, int groups) { PtNDManager manager = array.getManager(); return new NDList( JniUtils.convolution( manager.from(input), manager.from(weight), manager.from(bias), stride, padding, dilation, groups)); } /** {@inheritDoc} */ @Override public NDList deconvolution( NDArray input, NDArray weight, NDArray bias, Shape stride, Shape padding, Shape outPadding, Shape dilation, int groups) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public NDList linear(NDArray input, NDArray weight, NDArray bias) { PtNDManager manager = array.getManager(); return new NDList( JniUtils.linear(manager.from(input), manager.from(weight), manager.from(bias))); } /** {@inheritDoc} */ @Override public NDList embedding(NDArray input, NDArray weight, SparseFormat sparseFormat) { if (!sparseFormat.equals(SparseFormat.DENSE) && !sparseFormat.equals(SparseFormat.COO)) { throw new IllegalArgumentException("PyTorch only supports COO"); } PtNDManager manager = array.getManager(); return new NDList( JniUtils.embedding( manager.from(input), manager.from(weight), sparseFormat.equals(SparseFormat.COO))); } /** {@inheritDoc} */ @Override public NDList prelu(NDArray input, NDArray alpha) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public NDList dropout(NDArray input, float rate, boolean training) { PtNDManager manager = array.getManager(); return new NDList(JniUtils.dropout(manager.from(input), rate, training)); } /** {@inheritDoc} */ @Override public NDList layerNorm( NDArray input, Shape normalizedShape, NDArray gamma, NDArray beta, float eps) { PtNDManager manager = array.getManager(); return new NDList( JniUtils.layerNorm( manager.from(input), normalizedShape, manager.from(gamma), manager.from(beta), eps)); } /** {@inheritDoc} */ @Override public NDList batchNorm( NDArray input, NDArray runningMean, NDArray runningVar, NDArray gamma, NDArray beta, int axis, float momentum, float eps, boolean training) { // TODO PyTorch will support axis argument // https://github.com/pytorch/pytorch/issues/21856 PtNDManager manager = array.getManager(); if (axis == -1) { return new NDList( JniUtils.batchNorm( manager.from(input), manager.from(runningMean), manager.from(runningVar), manager.from(gamma), manager.from(beta), training, // momentum is defined differently in PyTorch 1f - momentum, eps)); } // apply the swapAxes to simulate BatchNorm with axis try (NDManager subManager = input.getManager().newSubManager()) { input.attach(subManager); NDArray result = input; result = result.swapAxes(1, axis); result = JniUtils.batchNorm( manager.from(result), manager.from(runningMean), manager.from(runningVar), manager.from(gamma), manager.from(beta), training, // momentum is defined differently in PyTorch 1f - momentum, eps); result = result.swapAxes(1, axis); input.attach(subManager.getParentManager()); result.attach(subManager.getParentManager()); return new NDList(result); } } /** {@inheritDoc} */ @Override public NDList rnn( NDArray input, NDArray state, NDList params, boolean hasBiases, int numLayers, RNN.Activation activation, double dropRate, boolean training, boolean bidirectional, boolean batchFirst) { PtNDManager manager = array.getManager(); return JniUtils.rnn( manager.from(input), manager.from(state), params, hasBiases, numLayers, activation, dropRate, training, bidirectional, batchFirst); } /** {@inheritDoc} */ @Override public NDList gru( NDArray input, NDArray state, NDList params, boolean hasBiases, int numLayers, double dropRate, boolean training, boolean bidirectional, boolean batchFirst) { PtNDManager manager = array.getManager(); return JniUtils.gru( manager.from(input), manager.from(state), params, hasBiases, numLayers, dropRate, training, bidirectional, batchFirst); } /** {@inheritDoc} */ @Override public NDList lstm( NDArray input, NDList states, NDList params, boolean hasBiases, int numLayers, double dropRate, boolean training, boolean bidirectional, boolean batchFirst) { return JniUtils.lstm( array.getManager().from(input), states, params, hasBiases, numLayers, dropRate, training, bidirectional, batchFirst); } /** {@inheritDoc} */ @Override public NDArray interpolation(long[] size, int mode, boolean alignCorners) { return JniUtils.interpolate( array.getManager().from(array), size, getInterpolationMode(mode), false); } /** {@inheritDoc} */ @Override public PtNDArray resize(int width, int height, int interpolation) { // create subManager to help close intermediate NDArray PtNDManager manager = array.getManager(); try (NDManager subManager = manager.newSubManager()) { array.attach(subManager); NDArray result = array; if (result.isEmpty()) { throw new IllegalArgumentException("attempt to resize of an empty NDArray"); } if (result.getDataType() != DataType.FLOAT32) { result = result.toType(DataType.FLOAT32, true); } int dim = result.getShape().dimension(); if (dim == 3) { result = result.expandDims(0); } // change from HWC to CHW order result = result.transpose(0, 3, 1, 2); result = JniUtils.interpolate( array.getManager().from(result), new long[] {height, width}, getInterpolationMode(interpolation), false) .transpose(0, 2, 3, 1); if (dim == 3) { result = result.squeeze(0); } result = result.toType(array.getDataType(), false); array.attach(subManager.getParentManager()); result.attach(subManager.getParentManager()); return (PtNDArray) result; } } /** {@inheritDoc} */ @Override public NDArray randomFlipLeftRight() { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public NDArray randomFlipTopBottom() { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public NDArray randomBrightness(float brightness) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public NDArray randomHue(float hue) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public NDArray randomColorJitter( float brightness, float contrast, float saturation, float hue) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public NDArrayIndexer getIndexer(NDManager manager) { return new PtNDArrayIndexer((PtNDManager) manager); } /** {@inheritDoc} */ @Override public PtNDArray where(NDArray condition, NDArray other) { // Try to broadcast if shape mismatch if (!condition.getShape().equals(array.getShape())) { throw new UnsupportedOperationException( "condition and self shape mismatch, broadcast is not supported"); } PtNDManager manager = array.getManager(); return JniUtils.where(manager.from(condition), array, manager.from(other)); } /** {@inheritDoc} */ @Override public PtNDArray stack(NDList arrays, int axis) { PtNDArray[] srcArray = new PtNDArray[arrays.size() + 1]; srcArray[0] = array; int i = 1; PtNDManager manager = array.getManager(); for (NDArray arr : arrays) { srcArray[i++] = manager.from(arr); } return JniUtils.stack(srcArray, axis); } /** {@inheritDoc} */ @Override public PtNDArray concat(NDList list, int axis) { NDUtils.checkConcatInput(list); PtNDArray[] srcArray = new PtNDArray[list.size() + 1]; srcArray[0] = array; int i = 1; PtNDManager manager = array.getManager(); for (NDArray arr : list) { srcArray[i++] = manager.from(arr); } return JniUtils.cat(srcArray, axis); } /** {@inheritDoc} */ @Override public NDList multiBoxTarget( NDList inputs, float iouThreshold, float ignoreLabel, float negativeMiningRatio, float negativeMiningThreshold, int minNegativeSamples) { throw new UnsupportedOperationException("Not implemented"); } /** {@inheritDoc} */ @Override public NDList multiBoxPrior( List<Float> sizes, List<Float> ratios, List<Float> steps, List<Float> offsets, boolean clip) { NDManager ndManager = array.getManager(); Shape input = array.getShape(); int inHeight = Math.toIntExact(input.get(2)); int inWidth = Math.toIntExact(input.get(3)); if (steps.get(0) <= 0 || steps.get(1) <= 0) { // estimate using layer shape steps.set(0, 1.f / inHeight); steps.set(1, 1.f / inWidth); } float stepX = steps.get(1); float stepY = steps.get(0); int numSizes = sizes.size(); int numRatios = ratios.size(); int count = 0; float[][] out = new float[inHeight * inWidth * numSizes * 2][4]; for (int r = 0; r < inHeight; ++r) { float centerY = (r + offsets.get(0)) * stepY; for (int c = 0; c < inWidth; ++c) { float centerX = (c + offsets.get(1)) * stepX; // ratio = first ratio, various sizes float ratio = numRatios > 0 ? (float) Math.sqrt(ratios.get(0)) : 1.f; for (int i = 0; i < numSizes; ++i) { float size = sizes.get(i); float w = size * inHeight / inWidth * ratio / 2; float h = size / ratio / 2; out[count][0] = centerX - w; // xmin out[count][1] = centerY - h; // ymin out[count][2] = centerX + w; // xmax out[count][3] = centerY + h; // ymax ++count; } // various ratios, size = min_size = size[0] float size = sizes.get(0); for (int j = 1; j < numRatios; ++j) { float ratioLocal = (float) Math.sqrt(ratios.get(j)); float w = size * inHeight / inWidth * ratioLocal / 2; float h = size / ratioLocal / 2; out[count][0] = centerX - w; // xmin out[count][1] = centerY - h; // ymin out[count][2] = centerX + w; // xmax out[count][3] = centerY + h; // ymax ++count; } } } NDArray ndArray = ndManager.create(out).expandDims(0); return new NDList(ndArray); } /** {@inheritDoc} */ @Override public NDList multiBoxDetection( NDList inputs, boolean clip, float threshold, int backgroundId, float nmsThreshold, boolean forceSuppress, int nmsTopK) { assert (inputs.size() == 3); NDArray clsProb = inputs.get(0); NDArray locPred = inputs.get(1); NDArray anchors = inputs.get(2).reshape(new Shape(-1, 4)); NDManager ndManager = array.getManager(); NDArray variances = ndManager.create(new float[] {0.1f, 0.1f, 0.2f, 0.2f}); assert (variances.size() == 4); // << "Variance size must be 4"; final int numClasses = (int) clsProb.size(1); final int numAnchors = (int) clsProb.size(2); final int numBatches = (int) clsProb.size(0); final float[] pAnchor = anchors.toFloatArray(); // [id, prob, xmin, ymin, xmax, ymax] // TODO Move to NDArray-based implementation NDList batchOutputs = new NDList(); for (int nbatch = 0; nbatch < numBatches; ++nbatch) { float[][] outputs = new float[numAnchors][6]; final float[] pClsProb = clsProb.get(nbatch).toFloatArray(); final float[] pLocPred = locPred.get(nbatch).toFloatArray(); for (int i = 0; i < numAnchors; ++i) { // find the predicted class id and probability float score = -1; int id = 0; for (int j = 1; j < numClasses; ++j) { float temp = pClsProb[j * numAnchors + i]; if (temp > score) { score = temp; id = j; } } if (id > 0 && score < threshold) { id = 0; } // [id, prob, xmin, ymin, xmax, ymax] outputs[i][0] = id - 1; outputs[i][1] = score; int offset = i * 4; float[] pAnchorRow4 = new float[4]; pAnchorRow4[0] = pAnchor[offset]; pAnchorRow4[1] = pAnchor[offset + 1]; pAnchorRow4[2] = pAnchor[offset + 2]; pAnchorRow4[3] = pAnchor[offset + 3]; float[] pLocPredRow4 = new float[4]; pLocPredRow4[0] = pLocPred[offset]; pLocPredRow4[1] = pLocPred[offset + 1]; pLocPredRow4[2] = pLocPred[offset + 2]; pLocPredRow4[3] = pLocPred[offset + 3]; float[] outRowLast4 = transformLocations( pAnchorRow4, pLocPredRow4, clip, variances.toFloatArray()[0], variances.toFloatArray()[1], variances.toFloatArray()[2], variances.toFloatArray()[3]); outputs[i][2] = outRowLast4[0]; outputs[i][3] = outRowLast4[1]; outputs[i][4] = outRowLast4[2]; outputs[i][5] = outRowLast4[3]; } outputs = Arrays.stream(outputs) .filter(o -> o[0] >= 0) .sorted(Comparator.comparing(o -> -o[1])) .toArray(float[][]::new); // apply nms for (int i = 0; i < outputs.length; ++i) { for (int j = i + 1; j < outputs.length; ++j) { if (outputs[i][0] == outputs[j][0]) { float[] outputsIRow4 = new float[4]; float[] outputsJRow4 = new float[4]; outputsIRow4[0] = outputs[i][2]; outputsIRow4[1] = outputs[i][3]; outputsIRow4[2] = outputs[i][4]; outputsIRow4[3] = outputs[i][5]; outputsJRow4[0] = outputs[j][2]; outputsJRow4[1] = outputs[j][3]; outputsJRow4[2] = outputs[j][4]; outputsJRow4[3] = outputs[j][5]; float iou = calculateOverlap(outputsIRow4, outputsJRow4); if (iou >= nmsThreshold) { outputs[j][0] = -1; } } } } batchOutputs.add(ndManager.create(outputs)); } // end iter batch NDArray pOutNDArray = NDArrays.stack(batchOutputs); NDList resultNDList = new NDList(); resultNDList.add(pOutNDArray); assert (resultNDList.size() == 1); return resultNDList; } private float[] transformLocations( final float[] anchors, final float[] locPred, final boolean clip, final float vx, final float vy, final float vw, final float vh) { float[] outRowLast4 = new float[4]; // transform predictions to detection results float al = anchors[0]; float at = anchors[1]; float ar = anchors[2]; float ab = anchors[3]; float aw = ar - al; float ah = ab - at; float ax = (al + ar) / 2.f; float ay = (at + ab) / 2.f; float px = locPred[0]; float py = locPred[1]; float pw = locPred[2]; float ph = locPred[3]; float ox = px * vx * aw + ax; float oy = py * vy * ah + ay; float ow = (float) (Math.exp(pw * vw) * aw / 2); float oh = (float) (Math.exp(ph * vh) * ah / 2); outRowLast4[0] = clip ? Math.max(0f, Math.min(1f, ox - ow)) : (ox - ow); outRowLast4[1] = clip ? Math.max(0f, Math.min(1f, oy - oh)) : (oy - oh); outRowLast4[2] = clip ? Math.max(0f, Math.min(1f, ox + ow)) : (ox + ow); outRowLast4[3] = clip ? Math.max(0f, Math.min(1f, oy + oh)) : (oy + oh); return outRowLast4; } private float calculateOverlap(final float[] a, final float[] b) { float w = Math.max(0f, Math.min(a[2], b[2]) - Math.max(a[0], b[0])); float h = Math.max(0f, Math.min(a[3], b[3]) - Math.max(a[1], b[1])); float i = w * h; float u = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - i; return u <= 0.f ? 0f : (i / u); } /** {@inheritDoc} */ @Override public PtNDArray getArray() { return array; } private Shape getPoolShape(NDArray array) { switch (array.getShape().dimension() - 2) { case 1: return new Shape(1); case 2: return new Shape(1, 1); case 3: return new Shape(1, 1, 1); default: throw new IllegalArgumentException("the input dimension should be in [3, 5]"); } } // Here is the list of PyTorch C++ interpolation mapping: kNearest, kLinear, kBilinear, // kBicubic, kTrilinear, kArea private int getInterpolationMode(int interpolation) { switch (interpolation) { case 0: return 0; case 1: return 2; case 2: return 5; case 3: return 3; default: throw new UnsupportedOperationException( "The kind of interpolation is not supported."); } } }
0
java-sources/ai/djl/pytorch/pytorch-engine/0.34.0/ai/djl/pytorch
java-sources/ai/djl/pytorch/pytorch-engine/0.34.0/ai/djl/pytorch/engine/PtNDArrayIndexer.java
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.pytorch.engine; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.index.NDArrayIndexer; import ai.djl.ndarray.index.NDIndex; import ai.djl.ndarray.index.dim.NDIndexBooleans; import ai.djl.ndarray.index.full.NDIndexFullPick; import ai.djl.ndarray.index.full.NDIndexFullSlice; import ai.djl.ndarray.index.full.NDIndexFullTake; import ai.djl.ndarray.types.Shape; import ai.djl.pytorch.jni.JniUtils; import java.util.Stack; /** The {@link NDArrayIndexer} used by the {@link PtNDArray}. */ public class PtNDArrayIndexer extends NDArrayIndexer { private PtNDManager manager; PtNDArrayIndexer(PtNDManager manager) { this.manager = manager; } /** {@inheritDoc} */ @Override public NDArray get(NDArray array, NDIndexFullPick fullPick) { return JniUtils.pick( manager.from(array), manager.from(fullPick.getIndices()), fullPick.getAxis()); } /** {@inheritDoc} */ @Override public NDArray get(NDArray array, NDIndexFullTake fullTake) { return JniUtils.take(manager.from(array), manager.from(fullTake.getIndices()), manager); } /** {@inheritDoc} */ @Override public NDArray get(NDArray array, NDIndexFullSlice fullSlice) { long[] min = fullSlice.getMin(); long[] max = fullSlice.getMax(); long[] step = fullSlice.getStep(); try (PtNDArray res = JniUtils.index(manager.from(array), min, max, step, manager)) { return res.squeeze(fullSlice.getToSqueeze()); } } /** {@inheritDoc} */ @Override public NDArray get(NDArray array, NDIndex index) { if (index.getRank() == 0) { if (array.getShape().isScalar()) { return array.getManager() == manager ? array.duplicate() : manager.create( array.toByteBuffer(), array.getShape(), array.getDataType()); } index.addAllDim(); } if (array == null || array instanceof PtNDArray) { return JniUtils.indexAdv((PtNDArray) array, index, manager); } else { PtNDArray arrayNew = manager.create(array.toByteBuffer(), array.getShape(), array.getDataType()); return JniUtils.indexAdv(arrayNew, index, manager); } } /** {@inheritDoc} */ @Override public void set(NDArray array, NDIndex index, Object data) { PtNDArray ptArray = array instanceof PtNDArray ? (PtNDArray) array : manager.create( array.toByteBuffer(), array.getShape(), array.getDataType()); if (data instanceof Number) { JniUtils.indexAdvPut(ptArray, index, (PtNDArray) manager.create((Number) data)); } else if (data instanceof NDArray) { JniUtils.indexAdvPut(ptArray, index, manager.from((NDArray) data)); } else { throw new IllegalArgumentException( "The type of value to assign cannot be other than NDArray and Number."); } } /** {@inheritDoc} */ @Override public void set(NDArray array, NDIndexFullSlice fullSlice, NDArray value) { Stack<NDArray> prepareValue = new Stack<>(); prepareValue.add(value); prepareValue.add(prepareValue.peek().toDevice(array.getDevice(), false)); // Deal with the case target: (1, 10, 1), original (10) // try to find (10, 1) and reshape (10) to that Shape targetShape = fullSlice.getShape(); while (targetShape.size() > value.size()) { targetShape = targetShape.slice(1); } prepareValue.add(prepareValue.peek().reshape(targetShape)); prepareValue.add(prepareValue.peek().broadcast(fullSlice.getShape())); JniUtils.indexSet( manager.from(array), manager.from(prepareValue.peek()), fullSlice.getMin(), fullSlice.getMax(), fullSlice.getStep()); for (NDArray toClean : prepareValue) { if (toClean != value) { toClean.close(); } } } /** {@inheritDoc} */ @Override public void set(NDArray array, NDIndexBooleans indices, NDArray value) { try (NDArray mask = indices.getIndex()) { JniUtils.booleanMaskSet(manager.from(array), manager.from(value), manager.from(mask)); } } /** {@inheritDoc} */ @Override public void set(NDArray array, NDIndexFullSlice fullSlice, Number value) { set(array, fullSlice, array.getManager().create(value)); } }