index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/YoloV5Translator.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.modality.cv.translator; import ai.djl.modality.cv.output.BoundingBox; import ai.djl.modality.cv.output.DetectedObjects; import ai.djl.modality.cv.output.Rectangle; import ai.djl.ndarray.NDList; import ai.djl.ndarray.types.DataType; import ai.djl.translate.ArgumentsUtil; import ai.djl.translate.TranslatorContext; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; /** * A translator for YoloV5 models. This was tested with ONNX exported Yolo models. For details check * <a href="https://github.com/ultralytics/yolov5">here</a> */ public class YoloV5Translator extends ObjectDetectionTranslator { private YoloOutputType yoloOutputLayerType; private float nmsThreshold; /** * Constructs an ImageTranslator with the provided builder. * * @param builder the data to build with */ protected YoloV5Translator(Builder builder) { super(builder); yoloOutputLayerType = builder.outputType; nmsThreshold = builder.nmsThreshold; } /** * Creates a builder to build a {@link YoloV5Translator}. * * @return a new builder */ public static YoloV5Translator.Builder builder() { return new YoloV5Translator.Builder(); } /** * Creates a builder to build a {@code YoloV5Translator} with specified arguments. * * @param arguments arguments to specify builder options * @return a new builder */ public static YoloV5Translator.Builder builder(Map<String, ?> arguments) { YoloV5Translator.Builder builder = new YoloV5Translator.Builder(); builder.configPreProcess(arguments); builder.configPostProcess(arguments); return builder; } protected DetectedObjects nms( int imageWidth, int imageHeight, List<Rectangle> boxes, List<Integer> classIds, List<Float> scores) { List<String> retClasses = new ArrayList<>(); List<Double> retProbs = new ArrayList<>(); List<BoundingBox> retBB = new ArrayList<>(); for (int classId = 0; classId < classes.size(); classId++) { List<Rectangle> r = new ArrayList<>(); List<Double> s = new ArrayList<>(); List<Integer> map = new ArrayList<>(); for (int j = 0; j < classIds.size(); ++j) { if (classIds.get(j) == classId) { r.add(boxes.get(j)); s.add(scores.get(j).doubleValue()); map.add(j); } } if (r.isEmpty()) { continue; } List<Integer> nms = Rectangle.nms(r, s, nmsThreshold); for (int index : nms) { int pos = map.get(index); int id = classIds.get(pos); retClasses.add(classes.get(id)); retProbs.add(scores.get(pos).doubleValue()); Rectangle rect = boxes.get(pos); if (removePadding) { int padW = (width - imageWidth) / 2; int padH = (height - imageHeight) / 2; rect = new Rectangle( (rect.getX() - padW) / imageWidth, (rect.getY() - padH) / imageHeight, rect.getWidth() / imageWidth, rect.getHeight() / imageHeight); } else if (applyRatio) { rect = new Rectangle( rect.getX() / width, rect.getY() / height, rect.getWidth() / width, rect.getHeight() / height); } retBB.add(rect); } } return new DetectedObjects(retClasses, retProbs, retBB); } protected DetectedObjects processFromBoxOutput(int imageWidth, int imageHeight, NDList list) { float[] flattened = list.get(0).toFloatArray(); int sizeClasses = classes.size(); int stride = 5 + sizeClasses; int size = flattened.length / stride; ArrayList<Rectangle> boxes = new ArrayList<>(); ArrayList<Float> scores = new ArrayList<>(); ArrayList<Integer> classIds = new ArrayList<>(); for (int i = 0; i < size; i++) { int indexBase = i * stride; float maxClass = 0; int maxIndex = 0; for (int c = 0; c < sizeClasses; c++) { if (flattened[indexBase + c + 5] > maxClass) { maxClass = flattened[indexBase + c + 5]; maxIndex = c; } } float score = maxClass * flattened[indexBase + 4]; if (score > threshold) { float xPos = flattened[indexBase]; float yPos = flattened[indexBase + 1]; float w = flattened[indexBase + 2]; float h = flattened[indexBase + 3]; Rectangle rect = new Rectangle(Math.max(0, xPos - w / 2), Math.max(0, yPos - h / 2), w, h); boxes.add(rect); scores.add(score); classIds.add(maxIndex); } } return nms(imageWidth, imageHeight, boxes, classIds, scores); } private DetectedObjects processFromDetectOutput() { throw new UnsupportedOperationException( "detect layer output is not supported yet, check correct YoloV5 export format"); } /** {@inheritDoc} */ @Override public DetectedObjects processOutput(TranslatorContext ctx, NDList list) { int imageWidth = (Integer) ctx.getAttachment("width"); int imageHeight = (Integer) ctx.getAttachment("height"); switch (yoloOutputLayerType) { case DETECT: return processFromDetectOutput(); case AUTO: if (list.get(0).getShape().dimension() > 2) { return processFromDetectOutput(); } else { return processFromBoxOutput(imageWidth, imageHeight, list); } case BOX: default: return processFromBoxOutput(imageWidth, imageHeight, list); } } /** A enum represents the Yolo output type. */ public enum YoloOutputType { BOX, DETECT, AUTO } /** The builder for {@link YoloV5Translator}. */ public static class Builder extends ObjectDetectionBuilder<Builder> { YoloOutputType outputType = YoloOutputType.AUTO; float nmsThreshold = 0.4f; /** * Sets the {@code YoloOutputType}. * * @param outputType the {@code YoloOutputType} * @return this builder */ public Builder optOutputType(YoloOutputType outputType) { this.outputType = outputType; return this; } /** * Sets the NMS threshold. * * @param nmsThreshold the NMS threshold * @return this builder */ public Builder optNmsThreshold(float nmsThreshold) { this.nmsThreshold = nmsThreshold; return this; } /** {@inheritDoc} */ @Override protected Builder self() { return this; } /** {@inheritDoc} */ @Override protected void configPostProcess(Map<String, ?> arguments) { super.configPostProcess(arguments); String type = ArgumentsUtil.stringValue(arguments, "outputType", "AUTO"); outputType = YoloOutputType.valueOf(type.toUpperCase(Locale.ENGLISH)); nmsThreshold = ArgumentsUtil.floatValue(arguments, "nmsThreshold", 0.4f); } /** * Builds the translator. * * @return the new translator */ public YoloV5Translator build() { // custom pipeline to match default YoloV5 input layer if (pipeline == null) { addTransform( array -> array.transpose(2, 0, 1).toType(DataType.FLOAT32, false).div(255)); } validate(); return new YoloV5Translator(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/YoloV5TranslatorFactory.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.modality.cv.translator; import ai.djl.Model; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.output.DetectedObjects; 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 YoloV5Translator} instance. */ public class YoloV5TranslatorFactory extends ObjectDetectionTranslatorFactory implements Serializable { private static final long serialVersionUID = 1L; /** {@inheritDoc} */ @Override protected Translator<Image, DetectedObjects> buildBaseTranslator( Model model, Map<String, ?> arguments) { return YoloV5Translator.builder(arguments).build(); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/YoloV8Translator.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.modality.cv.translator; import ai.djl.modality.cv.output.DetectedObjects; import ai.djl.modality.cv.output.Rectangle; 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 java.util.ArrayList; import java.util.Map; /** * A translator for YoloV8 models. This was tested with ONNX exported Yolo models. For details check * <a href="https://github.com/ultralytics/ultralytics">here</a> */ public class YoloV8Translator extends YoloV5Translator { private int maxBoxes; /** * Constructs an ImageTranslator with the provided builder. * * @param builder the data to build with */ protected YoloV8Translator(Builder builder) { super(builder); maxBoxes = builder.maxBox; } /** * Creates a builder to build a {@code YoloV8Translator} with specified arguments. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** * Creates a builder to build a {@code YoloV8Translator} with specified arguments. * * @param arguments arguments to specify builder options * @return a new builder */ public static Builder builder(Map<String, ?> arguments) { Builder builder = new Builder(); builder.configPreProcess(arguments); builder.configPostProcess(arguments); return builder; } /** {@inheritDoc} */ @Override protected DetectedObjects processFromBoxOutput(int imageWidth, int imageHeight, NDList list) { NDArray rawResult = list.get(0); NDArray reshapedResult = rawResult.transpose(); Shape shape = reshapedResult.getShape(); float[] buf = reshapedResult.toFloatArray(); int numberRows = Math.toIntExact(shape.get(0)); int nClasses = Math.toIntExact(shape.get(1)); int padding = nClasses - classes.size(); if (padding != 0 && padding != 4) { throw new IllegalStateException( "Expected classes: " + (nClasses - 4) + ", got " + classes.size()); } ArrayList<Rectangle> boxes = new ArrayList<>(); ArrayList<Float> scores = new ArrayList<>(); ArrayList<Integer> classIds = new ArrayList<>(); // reverse order search in heap; searches through #maxBoxes for optimization when set for (int i = numberRows - 1; i > numberRows - maxBoxes; --i) { int index = i * nClasses; float maxClassProb = -1f; int maxIndex = -1; for (int c = 4; c < nClasses; c++) { float classProb = buf[index + c]; if (classProb > maxClassProb) { maxClassProb = classProb; maxIndex = c; } } maxIndex -= padding; if (maxClassProb > threshold) { float xPos = buf[index]; // center x float yPos = buf[index + 1]; // center y float w = buf[index + 2]; float h = buf[index + 3]; Rectangle rect = new Rectangle(Math.max(0, xPos - w / 2), Math.max(0, yPos - h / 2), w, h); boxes.add(rect); scores.add(maxClassProb); classIds.add(maxIndex); } } return nms(imageWidth, imageHeight, boxes, classIds, scores); } /** The builder for {@link YoloV8Translator}. */ public static class Builder extends YoloV5Translator.Builder { private int maxBox = 8400; /** * Builds the translator. * * @return the new translator */ @Override public YoloV8Translator build() { if (pipeline == null) { addTransform( array -> array.transpose(2, 0, 1).toType(DataType.FLOAT32, false).div(255)); } validate(); return new YoloV8Translator(this); } /** {@inheritDoc} */ @Override protected void configPostProcess(Map<String, ?> arguments) { super.configPostProcess(arguments); maxBox = ArgumentsUtil.intValue(arguments, "maxBox", 8400); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/YoloV8TranslatorFactory.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.modality.cv.translator; import ai.djl.Model; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.output.DetectedObjects; import ai.djl.translate.Translator; import java.io.Serializable; import java.util.Map; /** A translatorFactory that creates a {@link YoloV8Translator} instance. */ public class YoloV8TranslatorFactory extends ObjectDetectionTranslatorFactory implements Serializable { private static final long serialVersionUID = 1L; /** {@inheritDoc} */ @Override protected Translator<Image, DetectedObjects> buildBaseTranslator( Model model, Map<String, ?> arguments) { return YoloV8Translator.builder(arguments).build(); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/YoloWorldTranslator.java
/* * Copyright 2025 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.modality.cv.translator; import ai.djl.Model; import ai.djl.inference.Predictor; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.VisionLanguageInput; 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.translator.BaseImageTranslator.BaseBuilder; import ai.djl.modality.nlp.NlpUtils; import ai.djl.modality.nlp.preprocess.LowerCaseConvertor; import ai.djl.modality.nlp.preprocess.PunctuationSeparator; import ai.djl.modality.nlp.preprocess.TextCleaner; import ai.djl.modality.nlp.preprocess.TextProcessor; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.translate.ArgumentsUtil; import ai.djl.translate.NoBatchifyTranslator; import ai.djl.translate.NoopTranslator; import ai.djl.translate.TranslateException; import ai.djl.translate.TranslatorContext; import ai.djl.util.JsonUtils; import ai.djl.util.Pair; import ai.djl.util.Utils; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.io.Reader; import java.lang.reflect.Type; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; 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 translator for Yolo-world models. */ public class YoloWorldTranslator implements NoBatchifyTranslator<VisionLanguageInput, DetectedObjects> { private static final int MAX_DETECTION = 300; private static final int[] AXIS_0 = {0}; private SimpleBpeTokenizer tokenizer; private BaseImageTranslator<?> imageProcessor; private Predictor<NDList, NDList> predictor; private String clipModelPath; private float threshold; private float nmsThreshold; YoloWorldTranslator(Builder builder) { this.imageProcessor = new BaseImagePreProcessor(builder); this.threshold = builder.threshold; this.nmsThreshold = builder.nmsThreshold; this.clipModelPath = builder.clipModelPath; } /** {@inheritDoc} */ @Override public void prepare(TranslatorContext ctx) throws Exception { Model model = ctx.getModel(); Path modelPath = model.getModelPath(); Path path = Paths.get(clipModelPath); if (!path.isAbsolute() && Files.notExists(path)) { path = modelPath.resolve(clipModelPath); } if (!Files.exists(path)) { throw new IOException("clip model not found: " + clipModelPath); } NDManager manager = ctx.getNDManager(); Model clip = manager.getEngine().newModel("clip", manager.getDevice()); clip.load(path); predictor = clip.newPredictor(new NoopTranslator(null)); model.getNDManager().attachInternal(NDManager.nextUid(), predictor); model.getNDManager().attachInternal(NDManager.nextUid(), clip); tokenizer = SimpleBpeTokenizer.newInstance(modelPath); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, VisionLanguageInput input) throws TranslateException { NDManager manager = ctx.getNDManager(); String[] candidates = input.getCandidates(); if (candidates == null || candidates.length == 0) { throw new TranslateException("Missing candidates in input"); } int[][] tokenIds = tokenizer.batchEncode(candidates); NDArray textFeature = predictor.predict(new NDList(manager.create(tokenIds))).get(0); Image img = input.getImage(); NDList imageFeatures = imageProcessor.processInput(ctx, img); NDArray array = imageFeatures.get(0).expandDims(0); ctx.setAttachment("candidates", candidates); return new NDList(textFeature, array); } /** {@inheritDoc} */ @Override public DetectedObjects processOutput(TranslatorContext ctx, NDList list) { List<String> classes = Arrays.asList((String[]) ctx.getAttachment("candidates")); int width = (Integer) ctx.getAttachment("width"); int height = (Integer) ctx.getAttachment("height"); NDArray pred = list.get(0); pred = pred.squeeze(0); int boxIndex = classes.size() + 4; NDArray candidates = pred.get("4:" + boxIndex).max(AXIS_0).gt(threshold); pred = pred.transpose(); NDArray sub = pred.get("..., :4"); sub = YoloTranslator.xywh2xyxy(sub); pred = sub.concat(pred.get("..., 4:"), -1); pred = pred.get(candidates); NDList split = pred.split(new long[] {4, boxIndex}, 1); NDArray box = split.get(0); int numBox = Math.toIntExact(box.getShape().get(0)); float[] buf = box.toFloatArray(); float[] confidences = split.get(1).toFloatArray(); long[] ids = split.get(1).argMax(1).toLongArray(); List<Rectangle> boxes = new ArrayList<>(numBox); List<Double> scores = new ArrayList<>(numBox); for (int i = 0; i < numBox; ++i) { float xPos = buf[i * 4]; float yPos = buf[i * 4 + 1]; float w = buf[i * 4 + 2] - xPos; float h = buf[i * 4 + 3] - yPos; Rectangle rect = new Rectangle(xPos, yPos, w, h); boxes.add(rect); scores.add((double) confidences[i]); } List<Integer> nms = Rectangle.nms(boxes, scores, nmsThreshold); if (nms.size() > MAX_DETECTION) { nms = nms.subList(0, MAX_DETECTION); } List<String> retClasses = new ArrayList<>(); List<Double> retProbs = new ArrayList<>(); List<BoundingBox> retBB = new ArrayList<>(); for (int index : nms) { int id = (int) ids[index]; retClasses.add(classes.get(id)); retProbs.add((double) confidences[id]); Rectangle rect = boxes.get(index); rect = new Rectangle( rect.getX() / width, rect.getY() / height, rect.getWidth() / width, rect.getHeight() / height); retBB.add(rect); } return new DetectedObjects(retClasses, retProbs, retBB); } /** * Creates a builder to build a {@link YoloWorldTranslator}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** * Creates a builder to build a {@code YoloWorldTranslator} with specified arguments. * * @param arguments arguments to specify builder options * @return a new builder */ public static Builder builder(Map<String, ?> arguments) { Builder builder = builder(); builder.configPreProcess(arguments); builder.configPostProcess(arguments); return builder; } /** The builder for {@link YoloWorldTranslator}. */ public static class Builder extends BaseBuilder<Builder> { float threshold = 0.25f; float nmsThreshold = 0.7f; String clipModelPath = "clip.pt"; /** {@inheritDoc} */ @Override protected Builder self() { return this; } /** * Sets the threshold for prediction accuracy. * * <p>Predictions below the threshold will be dropped. * * @param threshold the threshold for prediction accuracy * @return the builder */ public Builder optThreshold(float threshold) { this.threshold = threshold; return self(); } /** * Sets the NMS threshold. * * @param nmsThreshold the NMS threshold * @return this builder */ public Builder optNmsThreshold(float nmsThreshold) { this.nmsThreshold = nmsThreshold; return this; } /** * Sets the clip model file path, default value "clip.pt". * * @param clipModelPath the clip model file path * @return this builder */ public Builder optClipModelPath(String clipModelPath) { this.clipModelPath = clipModelPath; return this; } /** {@inheritDoc} */ @Override protected void configPostProcess(Map<String, ?> arguments) { super.configPostProcess(arguments); optThreshold(ArgumentsUtil.floatValue(arguments, "threshold", threshold)); optNmsThreshold(ArgumentsUtil.floatValue(arguments, "nmsThreshold", nmsThreshold)); optClipModelPath(ArgumentsUtil.stringValue(arguments, "clipModelPath", "clip.pt")); } /** * Builds the translator. * * @return the new translator */ public YoloWorldTranslator build() { return new YoloWorldTranslator(this); } } static final class SimpleBpeTokenizer { private static final int MIN_CONTEXT_LENGTH = 77; private static final int MAX_CONTEXT_LENGTH = 512; private static final Type MAP_TYPE = new TypeToken<Map<String, Integer>>() {}.getType(); private Map<String, Integer> vocabulary; private Map<Pair<String, String>, Integer> ranks; private int sot; private int eot; SimpleBpeTokenizer( Map<String, Integer> vocabulary, Map<Pair<String, String>, Integer> ranks) { this.vocabulary = vocabulary; this.ranks = ranks; sot = vocabulary.get("<|startoftext|>"); eot = vocabulary.get("<|endoftext|>"); } static SimpleBpeTokenizer newInstance(Path modelPath) throws IOException { Path vocab = modelPath.resolve("vocab.json"); Path merges = modelPath.resolve("merges.txt"); Map<Pair<String, String>, Integer> ranks = new ConcurrentHashMap<>(); List<String> lines = Utils.readLines(merges); lines = lines.subList(1, lines.size()); int index = 0; for (String line : lines) { String[] tok = line.split(" "); ranks.put(new Pair<>(tok[0], tok[1]), index++); } try (Reader reader = Files.newBufferedReader(vocab)) { Map<String, Integer> vocabulary = JsonUtils.GSON.fromJson(reader, MAP_TYPE); return new SimpleBpeTokenizer(vocabulary, ranks); } } int[][] batchEncode(String[] inputs) { List<List<Integer>> list = new ArrayList<>(); int contextLength = 0; for (String input : inputs) { List<Integer> ids = encode(input); int size = ids.size(); if (size > MAX_CONTEXT_LENGTH) { ids = ids.subList(0, MAX_CONTEXT_LENGTH); } contextLength = Math.max(contextLength, size); list.add(ids); } contextLength = Math.max(contextLength, MIN_CONTEXT_LENGTH); int[][] tokenIds = new int[inputs.length][contextLength]; int row = 0; for (List<Integer> ids : list) { for (int col = 0; col < ids.size(); ++col) { tokenIds[row][col] = ids.get(col); } ++row; } return tokenIds; } List<Integer> encode(String text) { List<String> tokens = new ArrayList<>(Collections.singletonList(text)); List<TextProcessor> processors = new ArrayList<>(); processors.add(new LowerCaseConvertor()); processors.add(new TextCleaner(NlpUtils::isWhiteSpace, ' ')); processors.add(new PunctuationSeparator()); for (TextProcessor processor : processors) { tokens = processor.preprocess(tokens); } List<Integer> idx = new ArrayList<>(); idx.add(sot); for (String token : tokens) { String bpe = bpe(token); idx.add(vocabulary.get(bpe)); } idx.add(eot); return idx; } private String bpe(String token) { char[] chars = token.toCharArray(); List<String> word = new ArrayList<>(chars.length); for (char c : chars) { word.add(String.valueOf(c)); } word.set(word.size() - 1, word.get(word.size() - 1) + "</w>"); Set<Pair<String, String>> pairs = getPairs(word); if (pairs.isEmpty()) { return token + "</w>"; } while (true) { Pair<String, String> min = Collections.min( pairs, (o1, o2) -> Integer.compare( ranks.getOrDefault(o1, Integer.MAX_VALUE), ranks.getOrDefault(o2, Integer.MAX_VALUE))); if (!ranks.containsKey(min)) { break; } List<String> newWord = new ArrayList<>(); String first = min.getKey(); String second = min.getValue(); int i = 0; while (i < word.size()) { List<String> subList = word.subList(i, word.size()); int j = subList.indexOf(first); if (j < 0) { newWord.addAll(word.subList(i, word.size())); break; } else { j += i; } newWord.addAll(word.subList(i, j)); i = j; if (word.get(i).equals(first) && i < word.size() - 1 && word.get(i + 1).equals(second)) { newWord.add(first + second); i += 2; } else { newWord.add(word.get(i)); i++; } } word = newWord; if (word.size() == 1) { break; } else { pairs = getPairs(word); } } return String.join(" ", word); } private Set<Pair<String, String>> getPairs(List<String> word) { if (word.size() < 2) { return Collections.emptySet(); } Set<Pair<String, String>> pairs = new HashSet<>(); String prev = word.get(0); for (int i = 1; i < word.size(); ++i) { pairs.add(new Pair<>(prev, word.get(i))); prev = word.get(i); } return pairs; } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/YoloWorldTranslatorFactory.java
/* * Copyright 2025 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.modality.cv.translator; import ai.djl.Model; import ai.djl.modality.Input; import ai.djl.modality.Output; import ai.djl.modality.cv.VisionLanguageInput; import ai.djl.modality.cv.output.DetectedObjects; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorFactory; import ai.djl.util.Pair; import java.io.Serializable; import java.lang.reflect.Type; import java.util.HashSet; import java.util.Map; import java.util.Set; /** A {@link Translator} that can serve yolo-world model. */ public class YoloWorldTranslatorFactory implements TranslatorFactory, Serializable { private static final long serialVersionUID = 1L; private static final Set<Pair<Type, Type>> SUPPORTED_TYPES = new HashSet<>(); static { SUPPORTED_TYPES.add(new Pair<>(VisionLanguageInput.class, DetectedObjects.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) { YoloWorldTranslator translator = YoloWorldTranslator.builder(arguments).build(); if (input == VisionLanguageInput.class && output == DetectedObjects.class) { return (Translator<I, O>) translator; } else if (input == Input.class && output == Output.class) { return (Translator<I, O>) new ZeroShotObjectDetectionServingTranslator(translator); } throw new IllegalArgumentException("Unsupported input/output types."); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/ZeroShotImageClassificationServingTranslator.java
/* * Copyright 2025 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.modality.cv.translator; import ai.djl.modality.Classifications; import ai.djl.modality.Input; import ai.djl.modality.Output; import ai.djl.modality.cv.VisionLanguageInput; import ai.djl.ndarray.BytesSupplier; import ai.djl.ndarray.NDList; import ai.djl.translate.Batchifier; import ai.djl.translate.NoBatchifyTranslator; import ai.djl.translate.TranslateException; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; /** * A {@link Translator} that can handle generic zero-shot-image-classification {@link Input} and * {@link Output}. */ public class ZeroShotImageClassificationServingTranslator implements NoBatchifyTranslator<Input, Output> { private Translator<VisionLanguageInput, Classifications> translator; /** * Constructs a {@code ZeroShotImageClassificationTranslator} instance. * * @param translator a {@code Translator} processes token classification input */ public ZeroShotImageClassificationServingTranslator( Translator<VisionLanguageInput, Classifications> translator) { this.translator = translator; } /** {@inheritDoc} */ @Override public void prepare(TranslatorContext ctx) throws Exception { translator.prepare(ctx); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, Input input) throws Exception { if (input.getContent().isEmpty()) { throw new TranslateException("Input data is empty."); } VisionLanguageInput prompt = VisionLanguageInput.parseInput(input); NDList ret = translator.processInput(ctx, prompt); Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { NDList[] batch = {ret}; return batchifier.batchify(batch); } return ret; } /** {@inheritDoc} */ @Override public Output processOutput(TranslatorContext ctx, NDList list) throws Exception { Output output = new Output(); output.addProperty("Content-Type", "application/json"); Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { list = batchifier.unbatchify(list)[0]; } output.add(BytesSupplier.wrapAsJson(translator.processOutput(ctx, list))); return output; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/ZeroShotObjectDetectionServingTranslator.java
/* * Copyright 2025 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.modality.cv.translator; import ai.djl.modality.Input; import ai.djl.modality.Output; import ai.djl.modality.cv.VisionLanguageInput; import ai.djl.modality.cv.output.DetectedObjects; import ai.djl.ndarray.BytesSupplier; import ai.djl.ndarray.NDList; import ai.djl.translate.Batchifier; import ai.djl.translate.NoBatchifyTranslator; import ai.djl.translate.TranslateException; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; /** A {@link Translator} that can serve ZeroShotObjectDetection model. */ public class ZeroShotObjectDetectionServingTranslator implements NoBatchifyTranslator<Input, Output> { private Translator<VisionLanguageInput, DetectedObjects> translator; /** * Constructs a {@code ZeroShotObjectDetectionServingTranslator} instance. * * @param translator a {@code Translator} processes token classification input */ public ZeroShotObjectDetectionServingTranslator( Translator<VisionLanguageInput, DetectedObjects> translator) { this.translator = translator; } /** {@inheritDoc} */ @Override public void prepare(TranslatorContext ctx) throws Exception { translator.prepare(ctx); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, Input input) throws Exception { if (input.getContent().isEmpty()) { throw new TranslateException("Input data is empty."); } VisionLanguageInput prompt = VisionLanguageInput.parseInput(input); NDList ret = translator.processInput(ctx, prompt); Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { NDList[] batch = {ret}; return batchifier.batchify(batch); } return ret; } /** {@inheritDoc} */ @Override public Output processOutput(TranslatorContext ctx, NDList list) throws Exception { Output output = new Output(); output.addProperty("Content-Type", "application/json"); Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { list = batchifier.unbatchify(list)[0]; } output.add(BytesSupplier.wrapAsJson(translator.processOutput(ctx, list))); return output; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/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 translators used for computer vision applications. */ package ai.djl.modality.cv.translator;
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/wrapper/FileImagePreProcessor.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.modality.cv.translator.wrapper; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.ImageFactory; import ai.djl.ndarray.NDList; import ai.djl.translate.PreProcessor; import ai.djl.translate.TranslatorContext; import java.nio.file.Path; /** Built-in {@code PreProcessor} that provides image pre-processing from file path. */ public class FileImagePreProcessor implements PreProcessor<Path> { private PreProcessor<Image> preProcessor; /** * Creates a {@code FileImagePreProcessor} instance. * * @param preProcessor a {@code PreProcessor} that can process image */ public FileImagePreProcessor(PreProcessor<Image> preProcessor) { this.preProcessor = preProcessor; } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, Path input) throws Exception { Image image = ImageFactory.getInstance().fromFile(input); return preProcessor.processInput(ctx, image); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/wrapper/InputStreamImagePreProcessor.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.modality.cv.translator.wrapper; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.ImageFactory; import ai.djl.ndarray.NDList; import ai.djl.translate.PreProcessor; import ai.djl.translate.TranslatorContext; import java.io.InputStream; /** Built-in {@code PreProcessor} that provides image pre-processing from {@code InputStream}. */ public class InputStreamImagePreProcessor<T> implements PreProcessor<InputStream> { private PreProcessor<Image> preProcessor; /** * Creates a {@code InputStreamImagePreProcessor} instance. * * @param preProcessor a {@code PreProcessor} that can process image */ public InputStreamImagePreProcessor(PreProcessor<Image> preProcessor) { this.preProcessor = preProcessor; } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, InputStream input) throws Exception { Image image = ImageFactory.getInstance().fromInputStream(input); return preProcessor.processInput(ctx, image); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/wrapper/StringImagePreProcessor.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.modality.cv.translator.wrapper; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.ImageFactory; import ai.djl.ndarray.NDList; import ai.djl.translate.PreProcessor; import ai.djl.translate.TranslatorContext; /** * Built-in {@code PreProcessor} that provides image pre-processing from url or base64 encoded * string. */ public class StringImagePreProcessor implements PreProcessor<String> { private PreProcessor<Image> preProcessor; /** * Creates a {@code StringImagePreProcessor} instance. * * @param preProcessor a {@code PreProcessor} that can process image */ public StringImagePreProcessor(PreProcessor<Image> preProcessor) { this.preProcessor = preProcessor; } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, String input) throws Exception { Image image = ImageFactory.getInstance().fromUrl(input); return preProcessor.processInput(ctx, image); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/wrapper/UrlImagePreProcessor.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.modality.cv.translator.wrapper; import ai.djl.modality.cv.Image; import ai.djl.modality.cv.ImageFactory; import ai.djl.ndarray.NDList; import ai.djl.translate.PreProcessor; import ai.djl.translate.TranslatorContext; import java.net.URL; /** * Built-in {@code PreProcessor} that provides image pre-processing from URL. * * @param <T> the output object type */ public class UrlImagePreProcessor<T> implements PreProcessor<URL> { private PreProcessor<Image> preProcessor; /** * Creates a {@code UrlImagePreProcessor} instance. * * @param preProcessor a {@code PreProcessor} that can process image */ public UrlImagePreProcessor(PreProcessor<Image> preProcessor) { this.preProcessor = preProcessor; } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, URL input) throws Exception { Image image = ImageFactory.getInstance().fromUrl(input); return preProcessor.processInput(ctx, image); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/translator/wrapper/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 wrappers to for multiple input formats to a {@link * ai.djl.modality.cv.translator.BaseImageTranslator}. */ package ai.djl.modality.cv.translator.wrapper;
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/util/NDImageUtils.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.modality.cv.util; import ai.djl.modality.cv.Image; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.types.Shape; import ai.djl.util.RandomUtils; /** * {@code NDImageUtils} is an image processing utility to load, reshape, and convert images using * {@link NDArray} images. */ public final class NDImageUtils { private NDImageUtils() {} /** * Resizes an image to the given width and height. * * @param image the image to resize * @param size the desired size * @return the resized NDArray */ public static NDArray resize(NDArray image, int size) { return resize(image, size, size, Image.Interpolation.BILINEAR); } /** * Resizes an image to the given width and height. * * @param image the image to resize * @param width the desired width * @param height the desired height * @return the resized NDArray */ public static NDArray resize(NDArray image, int width, int height) { return resize(image, width, height, Image.Interpolation.BILINEAR); } /** * Resizes an image to the given width and height with given interpolation. * * @param image the image to resize * @param width the desired width * @param height the desired height * @param interpolation the desired interpolation * @return the resized NDArray */ public static NDArray resize( NDArray image, int width, int height, Image.Interpolation interpolation) { return image.getNDArrayInternal().resize(width, height, interpolation.ordinal()); } /** * Rotate an image NDArray counter-clockwise 90 degree. * * @param image the image to rotate * @param times the image to rotate * @return the rotated Image */ public static NDArray rotate90(NDArray image, int times) { Shape shape = image.getShape(); int batchDim = shape.dimension() == 4 ? 1 : 0; if (isCHW(shape)) { return image.rotate90(times, new int[] {1 + batchDim, 2 + batchDim}); } else { return image.rotate90(times, new int[] {batchDim, 1 + batchDim}); } } /** * Normalizes an image NDArray of shape CHW or NCHW with a single mean and standard deviation to * apply to all channels. TensorFlow enforce HWC instead. * * @param input the image to normalize * @param mean the mean to normalize with (for all channels) * @param std the standard deviation to normalize with (for all channels) * @return the normalized NDArray * @see NDImageUtils#normalize(NDArray, float[], float[]) */ public static NDArray normalize(NDArray input, float mean, float std) { return normalize(input, new float[] {mean, mean, mean}, new float[] {std, std, std}); } /** * Normalizes an image NDArray of shape CHW or NCHW with mean and standard deviation. TensorFlow * enforce HWC instead. * * <p>Given mean {@code (m1, ..., mn)} and standard deviation {@code (s1, ..., sn} for {@code n} * channels, this transform normalizes each channel of the input tensor with: {@code output[i] = * (input[i] - m1) / (s1)}. * * @param input the image to normalize * @param mean the mean to normalize with for each channel * @param std the standard deviation to normalize with for each channel * @return the normalized NDArray */ public static NDArray normalize(NDArray input, float[] mean, float[] std) { boolean chw = isCHW(input.getShape()); boolean tf = "TensorFlow".equals(input.getManager().getEngine().getEngineName()); if ((chw && tf) || (!chw && !tf)) { throw new IllegalArgumentException( "normalize requires CHW format. TensorFlow requires HWC"); } return input.getNDArrayInternal().normalize(mean, std); } /** * Converts an image NDArray from preprocessing format to Neural Network format. * * <p>Converts an image NDArray of shape HWC in the range {@code [0, 255]} to a {@link * ai.djl.ndarray.types.DataType#FLOAT32} tensor NDArray of shape CHW in the range {@code [0, * 1]}. * * @param image the image to convert * @return the converted image */ public static NDArray toTensor(NDArray image) { return image.getNDArrayInternal().toTensor(); } /** * Crops an image to a square of size {@code min(width, height)}. * * @param image the image to crop * @return the cropped image * @see NDImageUtils#centerCrop(NDArray, int, int) */ public static NDArray centerCrop(NDArray image) { Shape shape = image.getShape(); int w = (int) shape.get(1); int h = (int) shape.get(0); if (w == h) { return image; } if (w > h) { return centerCrop(image, h, h); } return centerCrop(image, w, w); } /** * Crops an image to a given width and height from the center of the image. * * @param image the image to crop * @param width the desired width of the cropped image * @param height the desired height of the cropped image * @return the cropped image */ public static NDArray centerCrop(NDArray image, int width, int height) { Shape shape = image.getShape(); if (isCHW(image.getShape()) || shape.dimension() == 4) { throw new IllegalArgumentException("CenterCrop only support for HWC image format"); } int w = (int) shape.get(1); int h = (int) shape.get(0); int x; int y; int dw = (w - width) / 2; int dh = (h - height) / 2; if (dw > 0) { x = dw; w = width; } else { x = 0; } if (dh > 0) { y = dh; h = height; } else { y = 0; } return crop(image, x, y, w, h); } /** * Crops an image with a given location and size. * * @param image the image to crop * @param x the x coordinate of the top-left corner of the crop * @param y the y coordinate of the top-left corner of the crop * @param width the width of the cropped image * @param height the height of the cropped image * @return the cropped image */ public static NDArray crop(NDArray image, int x, int y, int width, int height) { return image.getNDArrayInternal().crop(x, y, width, height); } /** * Randomly flip the input image left to right with a probability of 0.5. * * @param image the image with HWC format * @return the flipped image */ public static NDArray randomFlipLeftRight(NDArray image) { return image.getNDArrayInternal().randomFlipLeftRight(); } /** * Randomly flip the input image top to bottom with a probability of 0.5. * * @param image the image with HWC format * @return the flipped image */ public static NDArray randomFlipTopBottom(NDArray image) { return image.getNDArrayInternal().randomFlipTopBottom(); } /** * Crop the input image with random scale and aspect ratio. * * @param image the image with HWC format * @param width the output width of the image * @param height the output height of the image * @param minAreaScale minimum targetArea/srcArea value * @param maxAreaScale maximum targetArea/srcArea value * @param minAspectRatio minimum aspect ratio * @param maxAspectRatio maximum aspect ratio * @return the cropped image */ public static NDArray randomResizedCrop( NDArray image, int width, int height, double minAreaScale, double maxAreaScale, double minAspectRatio, double maxAspectRatio) { Shape shape = image.getShape(); if (isCHW(image.getShape()) || shape.dimension() == 4) { throw new IllegalArgumentException( "randomResizedCrop only support for HWC image format"); } int h = (int) shape.get(0); int w = (int) shape.get(1); int srcArea = h * w; double targetArea = minAreaScale * srcArea + (maxAreaScale - minAreaScale) * srcArea * RandomUtils.nextFloat(); // get ratio from maximum achievable h and w double minRatio = (targetArea / h) / h; double maxRatio = w / (targetArea / w); double[] intersectRatio = { Math.max(minRatio, minAspectRatio), Math.min(maxRatio, maxAspectRatio) }; if (intersectRatio[1] < intersectRatio[0]) { return centerCrop(image, width, height); } // compute final area to crop float finalRatio = RandomUtils.nextFloat((float) intersectRatio[0], (float) intersectRatio[1]); int newWidth = (int) Math.round(Math.sqrt(targetArea * finalRatio)); int newHeight = (int) (newWidth / finalRatio); // num in nextInt(num) should be greater than 0 // otherwise it throws IllegalArgumentException: bound must be positive int x = w == newWidth ? 0 : RandomUtils.nextInt(w - newWidth); int y = h == newHeight ? 0 : RandomUtils.nextInt(h - newHeight); try (NDArray cropped = crop(image, x, y, newWidth, newHeight)) { return resize(cropped, width, height); } } /** * Randomly jitters image brightness with a factor chosen from [max(0, 1 - brightness), 1 + * brightness]. * * @param image the image with HWC format * @param brightness the brightness factor from 0 to 1 * @return the transformed image */ public static NDArray randomBrightness(NDArray image, float brightness) { return image.getNDArrayInternal().randomBrightness(brightness); } /** * Randomly jitters image hue with a factor chosen from [max(0, 1 - hue), 1 + hue]. * * @param image the image with HWC format * @param hue the hue factor from 0 to 1 * @return the transformed image */ public static NDArray randomHue(NDArray image, float hue) { return image.getNDArrayInternal().randomHue(hue); } /** * Randomly jitters the brightness, contrast, saturation, and hue of an image. * * @param image the image with HWC format * @param brightness the brightness factor from 0 to 1 * @param contrast the contrast factor from 0 to 1 * @param saturation the saturation factor from 0 to 1 * @param hue the hue factor from 0 to 1 * @return the transformed image */ public static NDArray randomColorJitter( NDArray image, float brightness, float contrast, float saturation, float hue) { return image.getNDArrayInternal().randomColorJitter(brightness, contrast, saturation, hue); } /** * Check if the shape of the image follows CHW/NCHW. * * @param shape the shape of the image * @return true for (N)CHW, false for (N)HWC */ public static boolean isCHW(Shape shape) { if (shape.dimension() < 3) { throw new IllegalArgumentException( "Not a valid image shape, require at least three dimensions"); } if (shape.dimension() == 4) { shape = shape.slice(1); } if (shape.get(0) == 1 || shape.get(0) == 3) { return true; } else if (shape.get(2) == 1 || shape.get(2) == 3) { return false; } throw new IllegalArgumentException("Image is neither CHW nor HWC"); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv
java-sources/ai/djl/api/0.34.0/ai/djl/modality/cv/util/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 utility classes for image manipulation. */ package ai.djl.modality.cv.util;
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/Decoder.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.modality.nlp; import ai.djl.MalformedModelException; 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.AbstractBlock; import ai.djl.nn.Block; import ai.djl.training.ParameterStore; import ai.djl.util.PairList; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; /** * {@code Decoder} is an abstract block that be can used as decoder in encoder-decoder architecture. * This abstraction, along with {@link Encoder}, comes into play in the {@link EncoderDecoder} * class, and facilitate implementing encoder-decoder models for different tasks and inputs. */ public abstract class Decoder extends AbstractBlock { protected Block block; /** * Constructs a new instance of {@code Decoder} with the given block. Use this constructor if * you are planning to use pre-trained embeddings that don't need further training. * * @param block the block to be used to decode * @param version the version to use for parameter and metadata serialization */ @SuppressWarnings("this-escape") public Decoder(byte version, Block block) { super(version); this.block = addChildBlock("Block", block); } /** {@inheritDoc} */ @Override protected NDList forwardInternal( ParameterStore parameterStore, NDList inputs, boolean training, PairList<String, Object> params) { return block.forward(parameterStore, inputs, training, params); } /** {@inheritDoc} */ @Override public void initializeChildBlocks(NDManager manager, DataType dataType, Shape... inputShapes) { block.initialize(manager, dataType, inputShapes); } /** {@inheritDoc} */ @Override public Shape[] getOutputShapes(Shape[] inputShapes) { return block.getOutputShapes(inputShapes); } /** {@inheritDoc} */ @Override public void saveParameters(DataOutputStream os) throws IOException { block.saveParameters(os); } /** {@inheritDoc} */ @Override public void loadParameters(NDManager manager, DataInputStream is) throws IOException, MalformedModelException { block.loadParameters(manager, is); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/DefaultVocabulary.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.modality.nlp; import ai.djl.util.Utils; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; /** The default implementation of Vocabulary. */ public class DefaultVocabulary implements Vocabulary { private Map<String, TokenInfo> tokens; private List<String> indexToToken; private Set<String> reservedTokens; private String unknownToken; /** * Creates a {@code DefaultVocabulary} object with the given list of tokens. * * @param tokens the {@link List} of tokens to build the vocabulary with */ public DefaultVocabulary(List<String> tokens) { this(builder().add(tokens)); } /** * Creates a {@code DefaultVocabulary} object with a {@link Builder}. * * @param builder the {@link Builder} to build the vocabulary with */ public DefaultVocabulary(Builder builder) { tokens = new ConcurrentHashMap<>(); reservedTokens = builder.reservedTokens; unknownToken = builder.unknownToken; if (unknownToken != null) { reservedTokens.add(unknownToken); } for (List<String> sentence : builder.sentences) { for (String token : sentence) { addToken(token); } } // Preserve order in vocab file, add reservedTokens after original vocab for (String token : reservedTokens) { addToken(token); } boolean pruned = pruneTokens(builder.minFrequency, builder.maxTokens); if (pruned) { initializeIndexToTokenReplacingIndices(); } else { initializeIndexToTokenKeepingIndices(); } } private void addToken(String token) { int index = tokens.size(); tokens.compute( token, (k, v) -> { if (v == null) { v = new TokenInfo(); // Set index only when adding a new token v.index = index; } // Update the frequency for both old and new tokens if (reservedTokens.contains(k)) { v.frequency = Integer.MAX_VALUE; } else if (v.frequency < Integer.MAX_VALUE) { ++v.frequency; } return v; }); } /** * Removes tokens from {@code tokens} based on the arguments. * * @param minFrequency a minimum frequency where all tokens below it are pruned. -1 for no * minFrequency. * @param maxSize a maximum number of tokens where only the maxSize most frequent are kept. -1 * for no maxSize * @return returns true if pruning occurred */ private boolean pruneTokens(int minFrequency, int maxSize) { boolean pruned = false; // Prune tokens below min frequency if (minFrequency > 1) { for (Entry<String, TokenInfo> token : tokens.entrySet()) { if (token.getValue().frequency < minFrequency) { tokens.remove(token.getKey()); } } pruned = true; } // Prune number of tokens to maxSize if (maxSize > 0 && tokens.size() > maxSize) { tokens.entrySet().stream() .sorted( Map.Entry.comparingByValue( Comparator.comparingInt( tokenInfo -> -tokenInfo.frequency))) // most frequent first .skip(maxSize) .forEach(token -> tokens.remove(token.getKey())); pruned = true; } return pruned; } /** * Initializes indexToToken using the indices in tokens. * * <p>This is used when not pruning to preserve the order tokens were given to this vocabulary. */ private void initializeIndexToTokenKeepingIndices() { indexToToken = Arrays.asList(new String[tokens.size()]); for (Entry<String, TokenInfo> token : tokens.entrySet()) { indexToToken.set(Math.toIntExact(token.getValue().index), token.getKey()); } } /** * Initializes indexToToken while replacing the indices in tokens. * * <p>When pruning, there will be unused indices. So, this will redo the indexing to be fully * compact without indexing gaps. The order of the original indices is preserved. */ private void initializeIndexToTokenReplacingIndices() { indexToToken = tokens.entrySet().stream() .sorted(Comparator.comparingLong(token -> token.getValue().index)) .map(Entry::getKey) .collect(Collectors.toList()); for (int i = 0; i < indexToToken.size(); i++) { tokens.get(indexToToken.get(i)).index = i; } } /** {@inheritDoc} */ @Override public boolean contains(String token) { return tokens.containsKey(token); } /** {@inheritDoc} */ @Override public String getToken(long index) { if (index < 0 || index >= indexToToken.size()) { return unknownToken; } return indexToToken.get((int) index); } /** {@inheritDoc} */ @Override public long getIndex(String token) { if (tokens.containsKey(token)) { return tokens.get(token).index; } if (unknownToken != null) { return tokens.get(unknownToken).index; } throw new IllegalStateException( "Unexpected token in getIndex. Define an unknownToken for the vocabulary to enable" + " support for unknown tokens."); } /** {@inheritDoc} */ @Override public long size() { return tokens.size(); } /** * Creates a new builder to build a {@code DefaultVocabulary}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** Builder class that is used to build the {@link DefaultVocabulary}. */ public static final class Builder { List<List<String>> sentences = new ArrayList<>(); Set<String> reservedTokens = new HashSet<>(); int minFrequency = -1; int maxTokens = -1; String unknownToken; private Builder() {} /** * Sets the optional parameter that specifies the minimum frequency to consider a token to * be part of the {@link DefaultVocabulary}. Defaults to no minimum. * * @param minFrequency the minimum frequency to consider a token to be part of the {@link * DefaultVocabulary} or -1 for no minimum * @return this {@code VocabularyBuilder} */ public Builder optMinFrequency(int minFrequency) { this.minFrequency = minFrequency; return this; } /** * Sets the optional limit on the size of the vocabulary. * * <p>The size includes the reservedTokens. If the number of added tokens exceeds the * maxToken limit, it keeps the most frequent tokens. * * @param maxTokens the maximum number of tokens or -1 for no maximum * @return this {@link Builder} */ public Builder optMaxTokens(int maxTokens) { this.maxTokens = maxTokens; return this; } /** * Sets the optional parameter that specifies the unknown token's string value with * "&gt;unk&lt;". * * @return this {@code VocabularyBuilder} */ public Builder optUnknownToken() { return optUnknownToken("<unk>"); } /** * Sets the optional parameter that specifies the unknown token's string value. * * @param unknownToken the string value of the unknown token * @return this {@code VocabularyBuilder} */ public Builder optUnknownToken(String unknownToken) { this.unknownToken = unknownToken; return this; } /** * Sets the optional parameter that sets the list of reserved tokens. * * @param reservedTokens the list of reserved tokens * @return this {@code VocabularyBuilder} */ public Builder optReservedTokens(Collection<String> reservedTokens) { this.reservedTokens.addAll(reservedTokens); return this; } /** * Adds the given sentence to the {@link DefaultVocabulary}. * * @param sentence the sentence to be added * @return this {@code VocabularyBuilder} */ public Builder add(List<String> sentence) { this.sentences.add(sentence); return this; } /** * Adds the given list of sentences to the {@link DefaultVocabulary}. * * @param sentences the list of sentences to be added * @return this {@code VocabularyBuilder} */ public Builder addAll(List<List<String>> sentences) { this.sentences.addAll(sentences); return this; } /** * Adds a text vocabulary to the {@link DefaultVocabulary}. * * <pre> * Example text file(vocab.txt): * token1 * token2 * token3 * will be mapped to index of 0 1 2 * </pre> * * @param path the path to the text file * @return this {@code VocabularyBuilder} * @throws IOException if failed to read vocabulary file */ public Builder addFromTextFile(Path path) throws IOException { add(Utils.readLines(path, true)); return this; } /** * Adds a text vocabulary to the {@link DefaultVocabulary}. * * @param url the text file url * @return this {@code VocabularyBuilder} * @throws IOException if failed to read vocabulary file */ public Builder addFromTextFile(URL url) throws IOException { try (InputStream is = url.openStream()) { add(Utils.readLines(is, true)); } return this; } /** * Adds a customized vocabulary to the {@link DefaultVocabulary}. * * @param url the text file url * @param lambda the function to parse the vocabulary file * @return this {@code VocabularyBuilder} */ public Builder addFromCustomizedFile(URL url, Function<URL, List<String>> lambda) { return add(lambda.apply(url)); } /** * Builds the {@link DefaultVocabulary} object with the set arguments. * * @return the {@link DefaultVocabulary} object built */ public DefaultVocabulary build() { if (maxTokens > 0 && maxTokens < reservedTokens.size()) { throw new IllegalArgumentException( "The vocabulary maxTokens can not be smaller than the number of reserved" + " tokens"); } return new DefaultVocabulary(this); } } /** * {@code TokenInfo} represents the information stored in the {@link DefaultVocabulary} about a * given token. */ private static final class TokenInfo { int frequency; long index = -1; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/EmbeddingOutput.java
/* * Copyright 2025 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.modality.nlp; import com.google.gson.annotations.SerializedName; import java.util.LinkedHashMap; import java.util.Map; /** A class represents text embedding output. */ public class EmbeddingOutput { @SerializedName("dense_vecs") private float[] denseEmbedding; @SerializedName("lexical_weights") private LinkedHashMap<String, Float> lexicalWeights; // NOPMD /** * Returns the dense embedding. * * @return the dense embedding */ public float[] getDenseEmbedding() { return denseEmbedding; } /** * Sets the dense embedding. * * @param denseEmbedding the dense embedding */ public void setDenseEmbedding(float[] denseEmbedding) { this.denseEmbedding = denseEmbedding; } /** * Returns the token weights map. * * @return the token weights map */ public Map<String, Float> getLexicalWeights() { return lexicalWeights; } /** * Adds the token weights to the output. * * @param tokenId the token id * @param weights the token weights */ public void addTokenWeights(String tokenId, float weights) { if (lexicalWeights == null) { lexicalWeights = new LinkedHashMap<>(); // NOPMD } lexicalWeights.put(tokenId, weights); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/Encoder.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.modality.nlp; import ai.djl.MalformedModelException; 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.AbstractBlock; import ai.djl.nn.Block; import ai.djl.training.ParameterStore; import ai.djl.util.PairList; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; /** * {@code Encoder} is an abstract block that be can used as encoder in encoder-decoder architecture. * This abstraction, along with {@link Decoder}, comes into play in the {@link EncoderDecoder} * class, and facilitate implementing encoder-decoder models for different tasks and inputs. */ public abstract class Encoder extends AbstractBlock { protected Block block; /** * Constructs a new instance of {@code Encoder} with the given block. * * @param version the version to use for parameter and metadata serialization * @param block the encoder block */ @SuppressWarnings("this-escape") public Encoder(byte version, Block block) { super(version); this.block = addChildBlock("Block", block); } /** * Gets the state of the encoder from the given encoder output. * * @param encoderOutput an {@link NDList} that contains the encoder output * @return the state of the encoder */ public abstract NDList getStates(NDList encoderOutput); /** {@inheritDoc} */ @Override protected NDList forwardInternal( ParameterStore parameterStore, NDList inputs, boolean training, PairList<String, Object> params) { return block.forward(parameterStore, inputs, training, params); } @Override protected NDList forwardInternal( ParameterStore parameterStore, NDList data, NDList labels, PairList<String, Object> params) { return super.forwardInternal(parameterStore, data, labels, params); } /** {@inheritDoc} */ @Override public void initializeChildBlocks(NDManager manager, DataType dataType, Shape... inputShapes) { block.initialize(manager, dataType, inputShapes); } /** {@inheritDoc} */ @Override public Shape[] getOutputShapes(Shape[] inputShapes) { return block.getOutputShapes(inputShapes); } /** {@inheritDoc} */ @Override public void saveParameters(DataOutputStream os) throws IOException { block.saveParameters(os); } /** {@inheritDoc} */ @Override public void loadParameters(NDManager manager, DataInputStream is) throws IOException, MalformedModelException { block.loadParameters(manager, is); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/EncoderDecoder.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.modality.nlp; import ai.djl.MalformedModelException; 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.AbstractBlock; import ai.djl.training.ParameterStore; import ai.djl.util.PairList; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; /** * {@code EncoderDecoder} is a general implementation of the very popular encoder-decoder * architecture. This class depends on implementations of {@link Encoder} and {@link Decoder} to * provide encoder-decoder architecture for different tasks and inputs such as machine * translation(text-text), image captioning(image-text) etc. */ public class EncoderDecoder extends AbstractBlock { private static final byte VERSION = 1; protected Encoder encoder; protected Decoder decoder; /** * Constructs a new instance of {@code EncoderDecoder} class with the given {@link Encoder} and * {@code Decoder}. * * @param encoder the {@link Encoder} * @param decoder the {@link Decoder} */ @SuppressWarnings("this-escape") public EncoderDecoder(Encoder encoder, Decoder decoder) { super(VERSION); this.encoder = addChildBlock("Encoder", encoder); this.decoder = addChildBlock("Decoder", decoder); inputNames = Arrays.asList("encoderInput", "decoderInput"); } /** {@inheritDoc} */ @Override public PairList<String, Shape> describeInput() { if (!isInitialized()) { throw new IllegalStateException("Parameter of this block are not initialised"); } return new PairList<>(inputNames, Arrays.asList(inputShapes)); } /** {@inheritDoc} */ @Override protected NDList forwardInternal( ParameterStore parameterStore, NDList inputs, boolean training, PairList<String, Object> params) { if (training) { throw new IllegalArgumentException("You must use forward with labels when training"); } throw new UnsupportedOperationException( "EncoderDecoder prediction has not been implemented yet"); } /** {@inheritDoc} */ @Override public NDList forward( ParameterStore parameterStore, NDList data, NDList labels, PairList<String, Object> params) { NDList encoderOutputs = encoder.forward(parameterStore, data, true, params); // add hidden states & cell states to decoder inputs labels.addAll(encoder.getStates(encoderOutputs)); return decoder.forward(parameterStore, labels, true, params); } /** * Initializes the parameters of the block. This method must be called before calling `forward`. * * <p>This method assumes that inputShapes contains encoder and decoder inputs in index 0 and 1 * respectively. * * @param manager the NDManager to initialize the parameters * @param dataType the datatype of the parameters * @param inputShapes the shapes of the inputs to the block */ @Override public void initialize(NDManager manager, DataType dataType, Shape... inputShapes) { beforeInitialize(inputShapes); encoder.initialize(manager, dataType, inputShapes[0]); decoder.initialize(manager, dataType, inputShapes[1]); } /** {@inheritDoc} */ @Override public Shape[] getOutputShapes(Shape[] inputShapes) { return decoder.getOutputShapes(new Shape[] {inputShapes[1]}); } /** {@inheritDoc} */ @Override public void saveParameters(DataOutputStream os) throws IOException { encoder.saveParameters(os); decoder.saveParameters(os); } /** {@inheritDoc} */ @Override public void loadParameters(NDManager manager, DataInputStream is) throws IOException, MalformedModelException { encoder.loadParameters(manager, is); decoder.loadParameters(manager, is); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/NlpUtils.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.modality.nlp; import java.util.regex.Pattern; /** Utility functions for processing String and Characters in NLP problems. */ public final class NlpUtils { private NlpUtils() {} /** * Check whether a character is is considered as a whitespace. * * <p>tab, newline and unicode space characters are all considered as whitespace. * * @param c input character to be checked. * @return whether a character is considered as a whitespace */ public static boolean isWhiteSpace(char c) { return Character.isWhitespace(c) || Character.isSpaceChar(c); } /** * Check whether a character is is considered as a control character. * * <p>tab, newline and ios control characters are all considered as control character. * * @param c input character to be checked. * @return whether a character is considered as control character */ public static boolean isControl(char c) { if (c == '\t' || c == '\n' || c == '\r') { return false; } return Character.isISOControl(c); } /** * Check whether a character is considered as a punctuation. * * <p>We treat all non-letter/number ASCII as punctuation. Characters such as "^", "$", and "`" * are not in the Unicode Punctuation class but we treat them as punctuation anyways, for * consistency. * * @param c input character to be checked * @return whether the character is considered as a punctuation */ public static boolean isPunctuation(char c) { return Pattern.matches("[\\p{Punct}\\p{IsPunctuation}]", String.valueOf(c)); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/TextPrompt.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.modality.nlp; import ai.djl.modality.Input; import ai.djl.translate.TranslateException; import ai.djl.util.JsonUtils; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import java.util.List; /** The input container for NLP text prompt. */ public final class TextPrompt { private String text; private List<String> batch; private TextPrompt(String text) { this.text = text; } private TextPrompt(List<String> batch) { this.batch = batch; } /** * Returns if the prompt is a batch. * * @return {@code true} if the prompt is a batch */ public boolean isBatch() { return batch != null; } /** * Returns the single prompt. * * @return the single prompt */ public String getText() { return text; } /** * Returns the batch prompt. * * @return the batch prompt */ public List<String> getBatch() { return batch; } /** * Returns the {@code TextPrompt} from the {@link Input}. * * @param input the input object * @return the {@code TextPrompt} from the {@link Input} * @throws TranslateException if the input is invalid */ public static TextPrompt parseInput(Input input) throws TranslateException { String contentType = input.getProperty("Content-Type", null); if (contentType != null) { int pos = contentType.indexOf(';'); if (pos > 0) { contentType = contentType.substring(0, pos); } } String text = input.getData().getAsString(); if (!"application/json".equals(contentType)) { return new TextPrompt(text); } try { JsonElement element = JsonUtils.GSON.fromJson(text, JsonElement.class); if (element != null && element.isJsonObject()) { element = element.getAsJsonObject().get("inputs"); } if (element == null) { throw new TranslateException("Missing \"inputs\" in json."); } else if (element.isJsonArray()) { List<String> batch = JsonUtils.GSON.fromJson(element, JsonUtils.LIST_TYPE); return new TextPrompt(batch); } else { return new TextPrompt(element.getAsString()); } } catch (JsonParseException e) { throw new TranslateException("Input is not a valid json.", e); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/Vocabulary.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.modality.nlp; /** * {@code Vocabulary} is a collection of tokens. The primary purpose of a vocabulary is the map a * token to an index. */ public interface Vocabulary { /** * Returns the token corresponding to the given index. * * @param index the index * @return the token corresponding to the given index */ String getToken(long index); /** * Check if the vocabulary contains a token. * * @param token String token to be checked * @return whether this vocabulary contains the token */ boolean contains(String token); /** * Returns the index of the given token. * * @param token the token * @return the index of the given token. */ long getIndex(String token); /** * Returns the size of the {@link Vocabulary}. * * @return the size of the {@link Vocabulary} */ long size(); }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/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 utility classes for natural language processing tasks. */ package ai.djl.modality.nlp;
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/bert/BertFullTokenizer.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.modality.nlp.bert; import ai.djl.modality.nlp.NlpUtils; import ai.djl.modality.nlp.Vocabulary; import ai.djl.modality.nlp.preprocess.LambdaProcessor; import ai.djl.modality.nlp.preprocess.LowerCaseConvertor; import ai.djl.modality.nlp.preprocess.PunctuationSeparator; import ai.djl.modality.nlp.preprocess.SimpleTokenizer; import ai.djl.modality.nlp.preprocess.TextCleaner; import ai.djl.modality.nlp.preprocess.TextProcessor; import ai.djl.modality.nlp.preprocess.UnicodeNormalizer; import java.text.Normalizer; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * BertFullTokenizer runs end to end tokenization of input text * * <p>It will run basic preprocessors to clean the input text and then run {@link * WordpieceTokenizer} to split into word pieces. * * <p>Reference implementation: <a * href="https://github.com/google-research/bert/blob/master/tokenization.py#L161">Google Research * Bert Tokenizer</a> */ public class BertFullTokenizer extends BertTokenizer { private Vocabulary vocabulary; private List<TextProcessor> basicBertPreprocessors; private WordpieceTokenizer wordpieceTokenizer; /** * Creates an instance of {@code BertFullTokenizer}. * * @param vocabulary the BERT vocabulary * @param lowerCase whether to convert tokens to lowercase */ public BertFullTokenizer(Vocabulary vocabulary, boolean lowerCase) { this.vocabulary = vocabulary; basicBertPreprocessors = getPreprocessors(lowerCase); wordpieceTokenizer = new WordpieceTokenizer(vocabulary, "[UNK]", 200); } /** * Returns the {@link Vocabulary} used for tokenization. * * @return the {@link Vocabulary} used for tokenization */ public Vocabulary getVocabulary() { return vocabulary; } /** {@inheritDoc} */ @Override public List<String> tokenize(String input) { List<String> tokens = new ArrayList<>(Collections.singletonList(input)); for (TextProcessor processor : basicBertPreprocessors) { tokens = processor.preprocess(tokens); } return wordpieceTokenizer.preprocess(tokens); } /** {@inheritDoc} */ @Override public String buildSentence(List<String> tokens) { return String.join(" ", tokens).replace(" ##", "").trim(); } /** * Get a list of {@link TextProcessor}s to process input text for Bert models. * * @param lowerCase whether to convert input to lowercase * @return List of {@code TextProcessor}s */ public static List<TextProcessor> getPreprocessors(boolean lowerCase) { List<TextProcessor> processors = new ArrayList<>(10); processors.add(new TextCleaner(c -> c == 0 || c == 0xfffd || NlpUtils.isControl(c), '\0')); processors.add(new TextCleaner(NlpUtils::isWhiteSpace, ' ')); processors.add(new LambdaProcessor(String::trim)); processors.add(new SimpleTokenizer()); if (lowerCase) { processors.add(new LowerCaseConvertor()); } processors.add(new UnicodeNormalizer(Normalizer.Form.NFD)); processors.add( new TextCleaner(c -> Character.getType(c) == Character.NON_SPACING_MARK, '\0')); processors.add(new PunctuationSeparator()); processors.add(new LambdaProcessor(String::trim)); return processors; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/bert/BertToken.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.modality.nlp.bert; import java.util.List; /** BertToken contains all the information for Bert model after encoding question and paragraph. */ public class BertToken { private List<String> tokens; private List<Long> tokenType; private List<Long> attentionMask; private int validLength; /** * Creates an instance of BertToken which includes information for Bert model. * * @param tokens indices of input sequence tokens in the vocabulary. * @param tokenType segment token indices to indicate first and second portions of the inputs. * @param attentionMask mask to avoid performing attention on padding token indices. * @param validLength length that indicates the original input sequence. */ public BertToken( List<String> tokens, List<Long> tokenType, List<Long> attentionMask, int validLength) { this.tokens = tokens; this.tokenType = tokenType; this.attentionMask = attentionMask; this.validLength = validLength; } /** * Gets the indices of input sequence tokens in the vocabulary. * * @return indices of input sequence tokens */ public List<String> getTokens() { return tokens; } /** * Gets segment token indices to indicate first and second portions of the inputs. * * @return segment token indices */ public List<Long> getTokenTypes() { return tokenType; } /** * Gets the mask to avoid performing attention on padding token indices. * * @return mask that performs attention on non-padding token indices */ public List<Long> getAttentionMask() { return attentionMask; } /** * Gets the length of the original sentence which has question and paragraph. * * @return length of the original sentence which has question and paragraph */ public int getValidLength() { return validLength; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/bert/BertTokenizer.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.modality.nlp.bert; import ai.djl.modality.nlp.preprocess.SimpleTokenizer; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** BertTokenizer is a class to help you encode question and paragraph sentence. */ public class BertTokenizer extends SimpleTokenizer { private static final Pattern PATTERN = Pattern.compile("(\\S+?)([.,?!])?(\\s+|$)"); /** {@inheritDoc} */ @Override public List<String> tokenize(String input) { List<String> ret = new LinkedList<>(); Matcher m = PATTERN.matcher(input); while (m.find()) { ret.add(m.group(1)); String token = m.group(2); if (token != null) { ret.add(token); } } return ret; } /** * Returns a string presentation of the tokens. * * @param tokens a list of tokens * @return a string presentation of the tokens */ public String tokenToString(List<String> tokens) { return String.join(" ", tokens); } /** * Pads the tokens to the required length. * * @param <E> the type of the List * @param tokens the input tokens * @param padItem the things to pad at the end * @param num the total length after padding * @return a list of padded tokens */ public <E> List<E> pad(List<E> tokens, E padItem, int num) { if (tokens.size() >= num) { return tokens; } List<E> padded = new ArrayList<>(num); padded.addAll(tokens); for (int i = tokens.size(); i < num; ++i) { padded.add(padItem); } return padded; } /** * Encodes questions and paragraph sentences. * * @param question the input question * @param paragraph the input paragraph * @return BertToken */ public BertToken encode(String question, String paragraph) { List<String> qToken = tokenize(question); List<String> pToken = tokenize(paragraph); int validLength = qToken.size() + pToken.size(); qToken.add(0, "[CLS]"); qToken.add("[SEP]"); pToken.add("[SEP]"); List<String> tokens = new ArrayList<>(qToken); tokens.addAll(pToken); int tokenTypeStartIdx = qToken.size(); long[] tokenTypeArr = new long[tokens.size()]; Arrays.fill(tokenTypeArr, tokenTypeStartIdx, tokenTypeArr.length, 1); long[] attentionMaskArr = new long[tokens.size()]; Arrays.fill(attentionMaskArr, 1); return new BertToken( tokens, Arrays.stream(tokenTypeArr).boxed().collect(Collectors.toList()), Arrays.stream(attentionMaskArr).boxed().collect(Collectors.toList()), validLength); } /** * Encodes questions and paragraph sentences with max length. * * @param question the input question * @param paragraph the input paragraph * @param maxLength the maxLength * @return BertToken */ public BertToken encode(String question, String paragraph, int maxLength) { BertToken bertToken = encode(question, paragraph); return new BertToken( pad(bertToken.getTokens(), "[PAD]", maxLength), pad(bertToken.getTokenTypes(), 0L, maxLength), pad(bertToken.getAttentionMask(), 0L, maxLength), bertToken.getValidLength()); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/bert/WordpieceTokenizer.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.modality.nlp.bert; import ai.djl.modality.nlp.Vocabulary; import ai.djl.modality.nlp.preprocess.SimpleTokenizer; import java.util.ArrayList; import java.util.List; /** * WordpieceTokenizer tokenizes a piece of text into its word pieces. * * <p>This uses a greedy longest-match-first algorithm to perform tokenization using the given * vocabulary. The input text should already be cleaned and preprocessed. * * <pre> * jshell&gt; String input = "unaffable"; * jshell&gt; wordpieceTokenizer.tokenize(intput); * ["un", "##aff", "##able"] * </pre> * * <p>Reference implementation: <a * href="https://github.com/google-research/bert/blob/master/tokenization.py#L300">Google Research * Bert Tokenizer</a> */ public class WordpieceTokenizer extends SimpleTokenizer { private String unknown; private int maxInputChars; private Vocabulary vocabulary; /** * Creates an instance of {@code WordpieceTokenizer}. * * @param vocabulary a {@code DefaultVocabulary} used for wordpiece tokenization * @param unknown String that represent unknown token * @param maxInputChars maximum number of input characters */ public WordpieceTokenizer(Vocabulary vocabulary, String unknown, int maxInputChars) { this.unknown = unknown; this.maxInputChars = maxInputChars; this.vocabulary = vocabulary; } /** {@inheritDoc} */ @Override public List<String> tokenize(String sentence) { StringBuilder sb = new StringBuilder(); List<String> subTokens = new ArrayList<>(); List<String> outputTokens = new ArrayList<>(); for (String token : super.tokenize(sentence.trim())) { char[] chars = token.toCharArray(); if (chars.length > maxInputChars) { outputTokens.add(unknown); continue; } boolean isBad = false; int start = 0; subTokens.clear(); String currentSubString = null; while (start < chars.length) { int end = chars.length; while (start < end) { sb.setLength(0); sb.append(token, start, end); if (start > 0) { sb.insert(0, "##"); } String subString = sb.toString(); if (vocabulary.contains(subString)) { currentSubString = subString; break; } else { currentSubString = null; } end--; } if (currentSubString == null) { isBad = true; break; } subTokens.add(currentSubString); if (subTokens.size() > maxInputChars) { throw new IllegalStateException("Too many subTokens for: '" + sentence + '\''); } start = end; } if (isBad) { outputTokens.add(unknown); } else { outputTokens.addAll(subTokens); } } return outputTokens; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/bert/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 that deal with BERT for natural language pre-processing tasks. */ package ai.djl.modality.nlp.bert;
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/embedding/EmbeddingException.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.modality.nlp.embedding; import ai.djl.translate.TranslateException; /** Thrown to indicate that there was some error while loading embeddings. */ public class EmbeddingException extends TranslateException { private static final long serialVersionUID = 1L; /** * Constructs a new exception with the specified detail message. The cause is not initialized, * and may subsequently be initialized by a call to {@link #initCause}. * * @param message the detail message that is saved for later retrieval by the {@link * #getMessage()} method */ public EmbeddingException(String message) { super(message); } /** * Constructs a new exception with the specified detail message and cause. * * <p>Note that the detail message associated with {@code cause} is <i>not</i> automatically * incorporated in this exception's detail message. * * @param message the detail message that is saved for later retrieval by the {@link * #getMessage()} method * @param cause the cause that is saved for later retrieval by the {@link #getCause()} method. A * {@code null} value is permitted, and indicates that the cause is nonexistent or unknown */ public EmbeddingException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new exception with the specified cause and a detail message of {@code * (cause==null ? null : cause.toString())} which typically contains the class and detail * message of {@code cause}. This constructor is useful for exceptions that are little more than * wrappers for other throwables. For example, {@link java.security.PrivilegedActionException}. * * @param cause the cause that is saved for later retrieval by the {@link #getCause()} method. A * {@code null} value is permitted, and indicates that the cause is nonexistent or unknown */ public EmbeddingException(Throwable cause) { super(cause); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/embedding/ModelZooTextEmbedding.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.modality.nlp.embedding; import ai.djl.Model; import ai.djl.inference.Predictor; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.nn.core.Embedding; import ai.djl.repository.zoo.ZooModel; import ai.djl.translate.Batchifier; import ai.djl.translate.NoopTranslator; import ai.djl.translate.TranslateException; import java.util.List; /** A {@link WordEmbedding} using a {@link ZooModel}. */ public class ModelZooTextEmbedding implements TextEmbedding, AutoCloseable { private Predictor<NDList, NDList> predictor; private Embedding<String> embedding; /** * Constructs a {@link ModelZooTextEmbedding}. * * @param model the model for the embedding. The model's block must consist of only an {@link * Embedding}&lt;{@link String}&gt;. */ @SuppressWarnings("unchecked") public ModelZooTextEmbedding(Model model) { predictor = model.newPredictor(new NoopTranslator(Batchifier.STACK)); try { embedding = (Embedding<String>) model.getBlock(); } catch (ClassCastException e) { throw new IllegalArgumentException("The model was not an embedding", e); } } /** {@inheritDoc} */ @Override public long[] preprocessTextToEmbed(List<String> tokens) { return tokens.stream().mapToLong(token -> embedding.embed(token)).toArray(); } /** {@inheritDoc} */ @Override public NDArray embedText(NDArray indices) throws EmbeddingException { try { return predictor.predict(new NDList(indices)).singletonOrThrow(); } catch (TranslateException e) { throw new EmbeddingException("Could not embed word", e); } } /** {@inheritDoc} */ @Override public List<String> unembedText(NDArray word) { throw new UnsupportedOperationException("Not implemented yet"); } /** {@inheritDoc} */ @Override public void close() { predictor.close(); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/embedding/SimpleTextEmbedding.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.modality.nlp.embedding; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDArrays; import ai.djl.ndarray.NDList; import java.util.ArrayList; import java.util.List; /** A {@link TextEmbedding} that applies a {@link WordEmbedding} to each word independently. */ public class SimpleTextEmbedding implements TextEmbedding { private WordEmbedding wordEmbedding; /** * Constructs a {@link SimpleTextEmbedding}. * * @param wordEmbedding the word embedding to embed each word */ public SimpleTextEmbedding(WordEmbedding wordEmbedding) { this.wordEmbedding = wordEmbedding; } /** {@inheritDoc} */ @Override public long[] preprocessTextToEmbed(List<String> text) { long[] result = new long[text.size()]; for (int i = 0; i < text.size(); i++) { result[i] = wordEmbedding.preprocessWordToEmbed(text.get(i)); } return result; } /** {@inheritDoc} */ @Override public NDArray embedText(NDArray textIndices) throws EmbeddingException { NDList result = new NDList(); for (int i = 0; i < textIndices.size(); i++) { result.add(wordEmbedding.embedWord(textIndices.get(i))); } return NDArrays.stack(result); } /** {@inheritDoc} */ @Override public List<String> unembedText(NDArray textEmbedding) { NDList split = textEmbedding.split(textEmbedding.getShape().get(0)); List<String> result = new ArrayList<>(split.size()); for (NDArray token : split) { result.add(wordEmbedding.unembedWord(token.get(0))); } return result; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/embedding/TextEmbedding.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.modality.nlp.embedding; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; import java.util.List; /** * A class to manage 1-D {@link NDArray} representations of multiple words. * * <p>A text embedding differs from a {@link ai.djl.modality.nlp.embedding.WordEmbedding} because * the text embedding does not have to be applied to each word independently. * * <p>A text embedding maps text to a {@link NDArray} that attempts to represent the key ideas in * the words. Each of the values in the dimension can represent different pieces of meaning such as * young-old, object-living, etc. * * <p>These text embeddings can be used in two different ways in models. First, they can be used * purely for preprocessing the model. In this case, it is a requirement for most models that use * text as an input. The model is not trained. For this use case, use {@link #embedText}. * * <p>In the second option, the embedding can be trained using the standard deep learning techniques * to better handle the current dataset. For this case, you need two methods. First, call {@link * #preprocessTextToEmbed(List)} within your dataset. Then, the first step in your model should be * to call {@link #embedText(NDManager, long[])}. */ public interface TextEmbedding { /** * Preprocesses the text to embed into an array to pass into the model. * * <p>Make sure to call {@link #embedText(NDManager, long[])} after this. * * @param text the text to embed * @return the indices of text that is ready to embed */ long[] preprocessTextToEmbed(List<String> text); /** * Embeds a text. * * @param manager the manager for the embedding array * @param text the text to embed * @return the embedded text * @throws EmbeddingException if there is an error while trying to embed */ default NDArray embedText(NDManager manager, List<String> text) throws EmbeddingException { return embedText(manager, preprocessTextToEmbed(text)); } /** * Embeds the text after preprocessed using {@link #preprocessTextToEmbed(List)}. * * @param manager the manager to create the embedding array * @param textIndices the indices of text to embed * @return the embedded text * @throws EmbeddingException if there is an error while trying to embed */ default NDArray embedText(NDManager manager, long[] textIndices) throws EmbeddingException { return embedText(manager.create(textIndices)); } /** * Embeds the text after preprocessed using {@link #preprocessTextToEmbed(List)}. * * @param textIndices the indices of text to embed * @return the embedded text * @throws EmbeddingException if there is an error while trying to embed */ NDArray embedText(NDArray textIndices) throws EmbeddingException; /** * Returns the closest matching text for a given embedding. * * @param textEmbedding the text embedding to find the matching string text for. * @return text similar to the passed in embedding * @throws EmbeddingException if the input is not unembeddable */ List<String> unembedText(NDArray textEmbedding) throws EmbeddingException; }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/embedding/TrainableTextEmbedding.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.modality.nlp.embedding; 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.AbstractBlock; import ai.djl.training.ParameterStore; import ai.djl.util.PairList; import java.util.ArrayList; import java.util.List; /** * {@code TrainableTextEmbedding} is an implementation of {@link TextEmbedding} based on {@link * TrainableWordEmbedding} block. This {@link TextEmbedding} is ideal when there are no pre-trained * embeddings available, or when the pre-trained embedding needs to be further trained. */ public class TrainableTextEmbedding extends AbstractBlock implements TextEmbedding { private TrainableWordEmbedding trainableWordEmbedding; /** * Constructs a {@link TrainableTextEmbedding}. * * @param wordEmbedding the word embedding to embed each word */ @SuppressWarnings("this-escape") public TrainableTextEmbedding(TrainableWordEmbedding wordEmbedding) { this.trainableWordEmbedding = addChildBlock("trainableWordEmbedding", wordEmbedding); } /** {@inheritDoc} */ @Override public long[] preprocessTextToEmbed(List<String> text) { long[] result = new long[text.size()]; for (int i = 0; i < text.size(); i++) { result[i] = trainableWordEmbedding.preprocessWordToEmbed(text.get(i)); } return result; } /** {@inheritDoc} */ @Override public NDArray embedText(NDArray textIndices) throws EmbeddingException { throw new UnsupportedOperationException( "EmbedText operation is not supported by this class."); } /** {@inheritDoc} */ @Override public List<String> unembedText(NDArray textEmbedding) { NDList split = textEmbedding.split(textEmbedding.getShape().get(0)); List<String> result = new ArrayList<>(split.size()); for (NDArray token : split) { result.add(trainableWordEmbedding.unembedWord(token.get(0))); } return result; } /** {@inheritDoc} */ @Override protected NDList forwardInternal( ParameterStore parameterStore, NDList inputs, boolean training, PairList<String, Object> params) { return trainableWordEmbedding.forward(parameterStore, inputs, training, params); } /** {@inheritDoc} */ @Override public void initializeChildBlocks(NDManager manager, DataType dataType, Shape... inputShapes) { trainableWordEmbedding.initialize(manager, dataType, inputShapes); } /** {@inheritDoc} */ @Override public Shape[] getOutputShapes(Shape[] inputShapes) { return trainableWordEmbedding.getOutputShapes(inputShapes); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/embedding/TrainableWordEmbedding.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.modality.nlp.embedding; import ai.djl.modality.nlp.DefaultVocabulary; import ai.djl.modality.nlp.Vocabulary; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.types.SparseFormat; import ai.djl.nn.Block; import ai.djl.nn.core.Embedding; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Optional; /** * {@code TrainableWordEmbedding} is an implementation of {@link WordEmbedding} and {@link * Embedding} based on a {@link DefaultVocabulary}. This {@link WordEmbedding} is ideal when there * are no pre-trained embeddings available. */ public class TrainableWordEmbedding extends Embedding<String> implements WordEmbedding { private static final String DEFAULT_UNKNOWN_TOKEN = "<unk>"; private Vocabulary vocabulary; /** * Constructs a new instance of {@code TrainableWordEmbedding} from the {@link Builder}. * * @param builder the {@link Builder} */ public TrainableWordEmbedding(Builder builder) { super(builder); this.vocabulary = builder.vocabulary; } /** * Constructs a new instance of {@code TrainableWordEmbedding} from a {@link DefaultVocabulary} * and a given embedding size. * * @param vocabulary a {@link Vocabulary} to get tokens from * @param embeddingSize the required embedding size */ public TrainableWordEmbedding(Vocabulary vocabulary, int embeddingSize) { this( builder() .setVocabulary(vocabulary) .setEmbeddingSize(embeddingSize) .optDefaultItem(DEFAULT_UNKNOWN_TOKEN) .optUseDefault(false)); } private TrainableWordEmbedding(NDArray embedding, List<String> items) { super(embedding); this.fallthroughEmbedding = new DefaultItem(DEFAULT_UNKNOWN_TOKEN); this.vocabulary = new DefaultVocabulary(items); } private TrainableWordEmbedding( NDArray embedding, List<String> items, SparseFormat sparseFormat) { super(embedding, sparseFormat); this.fallthroughEmbedding = new DefaultItem(DEFAULT_UNKNOWN_TOKEN); this.vocabulary = new DefaultVocabulary(items); } /** * Constructs a pretrained embedding. * * <p>Because it is created with preTrained data, it is created as a frozen block. If you with * to update it, call {@link Block#freezeParameters(boolean)}. * * @param embedding the embedding array * @param items the items in the embedding (in matching order to the embedding array) * @return the created embedding */ public static TrainableWordEmbedding fromPretrained(NDArray embedding, List<String> items) { return new TrainableWordEmbedding(embedding, items); } /** * Constructs a pretrained embedding. * * <p>Because it is created with preTrained data, it is created as a frozen block. If you with * to update it, call {@link Block#freezeParameters(boolean)}. * * @param embedding the embedding array * @param items the items in the embedding (in matching order to the embedding array) * @param sparseFormat whether to compute row sparse gradient in the backward calculation * @return the created embedding */ public static TrainableWordEmbedding fromPretrained( NDArray embedding, List<String> items, SparseFormat sparseFormat) { return new TrainableWordEmbedding(embedding, items, sparseFormat); } /** {@inheritDoc} */ @Override public boolean vocabularyContains(String word) { return vocabulary.getIndex(word) >= 0; } /** {@inheritDoc} */ @Override public long preprocessWordToEmbed(String word) { return embed(word); } /** {@inheritDoc} */ @Override public NDArray embedWord(NDArray index) throws EmbeddingException { throw new UnsupportedOperationException( "EmbedWord operation is not supported by this class."); } /** {@inheritDoc} */ @Override public String unembedWord(NDArray word) { if (!word.isScalar()) { throw new IllegalArgumentException("NDArray word must be scalar index"); } long wordIndex = word.toLongArray()[0]; Optional<String> result = unembed(wordIndex); if (result.isPresent()) { return result.get(); } result = fallthroughEmbedding.unembed(wordIndex); if (result.isPresent()) { return result.get(); } throw new IllegalArgumentException("Failed to unembed word"); } /** {@inheritDoc} */ @Override public byte[] encode(String input) { byte[] encodedInput; encodedInput = input.getBytes(StandardCharsets.UTF_8); return encodedInput; } /** {@inheritDoc} */ @Override public String decode(byte[] byteArray) { return new String(byteArray, StandardCharsets.UTF_8); } /** {@inheritDoc} */ @Override public long embed(String item) { if (vocabularyContains(item)) { return vocabulary.getIndex(item); } else { if (fallthroughEmbedding != null) { return fallthroughEmbedding.embed(item); } else { throw new IllegalArgumentException("The provided item was not found"); } } } /** {@inheritDoc} */ @Override public Optional<String> unembed(long index) { if (index == -1) { if (fallthroughEmbedding == null) { throw new IllegalArgumentException( "Index -1 is reserved for the fallThrough but no fallThrough is found"); } return fallthroughEmbedding.unembed(index); } return Optional.ofNullable(vocabulary.getToken(index)); } /** * Creates a builder to build an {@link Embedding}. * * @return a new builder */ public static Builder builder() { return new TrainableWordEmbedding.Builder(); } /** {@inheritDoc} */ @Override public boolean hasItem(String item) { return false; } /** A builder for a {@link TrainableWordEmbedding}. */ public static class Builder extends Embedding.BaseBuilder<String, Builder> { private Vocabulary vocabulary; Builder() { super(); this.embeddingType = String.class; this.defaultItem = DEFAULT_UNKNOWN_TOKEN; } /** * Sets the {@link Vocabulary} to be used. * * @param vocabulary the {@link Vocabulary} to be set * @return this Builder */ public Builder setVocabulary(Vocabulary vocabulary) { this.vocabulary = vocabulary; numEmbeddings = Math.toIntExact(vocabulary.size()); return self(); } /** {@inheritDoc} */ @Override protected Builder setType(Class<String> embeddingType) { return self(); } /** {@inheritDoc} */ @Override protected Builder self() { return this; } /** * Sets the optional {@link String} value for the unknown token. * * @param unknownToken the {@link String} value of unknown token * @return this Builder */ public Builder optUnknownToken(String unknownToken) { return optDefaultItem(unknownToken); } /** * Builds a new instance of {@link TrainableWordEmbedding} based on the arguments in this * builder. * * @return a new instance of {@link TrainableWordEmbedding} */ public TrainableWordEmbedding build() { if (numEmbeddings != vocabulary.size()) { throw new IllegalArgumentException( "The numEmbeddings is " + numEmbeddings + " and the vocabulary has size " + vocabulary.size() + " but they should be equal."); } return new TrainableWordEmbedding(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/embedding/WordEmbedding.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.modality.nlp.embedding; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; /** * A class to manage 1-D {@link NDArray} representations of words. * * <p>A word embedding maps words to a {@link NDArray} that attempts to represent the key ideas in * the words. Each of the values in the dimension can represent different pieces of meaning such as * young-old, object-living, etc. * * <p>These word embeddings can be used in two different ways in models. First, they can be used * purely for preprocessing the model. In this case, it is a requirement for most models that use * text as an input. The model is not trained. For this use case, use {@link #embedWord(NDManager, * String)}. * * <p>In the second option, the embedding can be trained using the standard deep learning techniques * to better handle the current dataset. For this case, you need two methods. First, call {@link * #preprocessWordToEmbed(String)} within your dataset. Then, the first step in your model should be * to call {@link #embedWord(NDManager, long)}. */ public interface WordEmbedding { /** * Returns whether an embedding exists for a word. * * @param word the word to check * @return true if an embedding exists */ boolean vocabularyContains(String word); /** * Pre-processes the word to embed into an array to pass into the model. * * <p>Make sure to call {@link #embedWord(NDManager, long)} after this. * * @param word the word to embed * @return the word that is ready to embed */ long preprocessWordToEmbed(String word); /** * Embeds a word. * * @param manager the manager for the embedding array * @param word the word to embed * @return the embedded word * @throws EmbeddingException if there is an error while trying to embed */ default NDArray embedWord(NDManager manager, String word) throws EmbeddingException { return embedWord(manager, preprocessWordToEmbed(word)); } /** * Embeds the word after preprocessed using {@link #preprocessWordToEmbed(String)}. * * @param manager the manager for the embedding array * @param index the index of the word to embed * @return the embedded word * @throws EmbeddingException if there is an error while trying to embed */ default NDArray embedWord(NDManager manager, long index) throws EmbeddingException { return embedWord(manager.create(index)); } /** * Embeds the word after preprocessed using {@link #preprocessWordToEmbed(String)}. * * @param index the index of the word to embed * @return the embedded word * @throws EmbeddingException if there is an error while trying to embed */ NDArray embedWord(NDArray index) throws EmbeddingException; /** * Returns the closest matching word for the given index. * * @param word the word embedding to find the matching string word for. * @return a word similar to the passed in embedding */ String unembedWord(NDArray word); }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/embedding/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 that deal with word embeddings for natural language pre-processing tasks. */ package ai.djl.modality.nlp.embedding;
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/generate/BatchTensorList.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.modality.nlp.generate; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; /** * BatchTensorList represents a search state, and the NDArrays inside are updated in each iteration * of the autoregressive loop. * * <p>It is a struct consisting of NDArrays, whose first dimension is batch, and also contains * sequence dimension (whose position in tensor's shape is specified by seqDimOrder). The SeqBatcher * batch operations will operate on these two dimensions. */ public abstract class BatchTensorList { // [batch, seq_past]. seq-dim-size == |past_seq| + |inputIds|. Will grow. private NDArray pastOutputIds; // [batch, seq_past] // The cache of past attentionMask. seq-dim-size == |past_seq| + |inputIds|. Will grow. private NDArray pastAttentionMask; // (k, v) * numLayer, // kv: [batch, heads, seq_past, kvfeature] // The cache of past sequence. seq-dim-size == |past_seq| + |inputIds|. Will grow. private NDList pastKeyValues; // Sequence dimension order among all dimensions for each element in the batch list. private long[] seqDimOrder; BatchTensorList() {} /** * Constructs a new {@code BatchTensorList} instance. * * @param list the NDList that contains the serialized version of the batch tensors * @param seqDimOrder the sequence dimension order that specifies where the sequence dimension * is in a tensor's shape */ BatchTensorList(NDList list, long[] seqDimOrder) { this.seqDimOrder = seqDimOrder; pastOutputIds = list.get(0); pastAttentionMask = list.get(1); pastKeyValues = list.subNDList(2); } /** * Constructs a new {@code BatchTensorList} instance. * * @param pastOutputIds past output token ids * @param pastAttentionMask past attention mask * @param pastKeyValues past kv cache * @param seqDimOrder the sequence dimension order that specifies where the sequence dimension * is in a tensor's shape */ BatchTensorList( NDArray pastOutputIds, NDArray pastAttentionMask, NDList pastKeyValues, long[] seqDimOrder) { this.pastKeyValues = pastKeyValues; this.pastOutputIds = pastOutputIds; this.pastAttentionMask = pastAttentionMask; this.seqDimOrder = seqDimOrder; } /** * Constructs a new {@code BatchTensorList} instance from the serialized version of the batch * tensors. * * <p>The pastOutputIds has to be the first in the output list. * * @param inputList the serialized version of the batch tensors * @param seqDimOrder the sequence dimension order that specifies where the sequence dimension * is in a tensor's shape * @return BatchTensorList */ public abstract BatchTensorList fromList(NDList inputList, long[] seqDimOrder); /** * Returns the serialized version of the BatchTensorList. The pastOutputIds has to be the first * in the output list. * * @return the NDList that contains the serialized BatchTensorList */ public abstract NDList getList(); /** * Returns the sequence dimension order which specifies where the sequence dimension is in a * tensor's shape. * * @return the sequence dimension order which specifies where the sequence dimension is in a * tensor's shape */ public long[] getSeqDimOrder() { return seqDimOrder; } /** * Returns the value of the pastOutputIds. * * @return the value of pastOutputIds */ public NDArray getPastOutputIds() { return pastOutputIds; } /** * Sets the past output token ids. * * @param pastOutputIds the past output token ids */ public void setPastOutputIds(NDArray pastOutputIds) { this.pastOutputIds = pastOutputIds; } /** * Returns the value of the pastAttentionMask. * * @return the value of pastAttentionMask */ public NDArray getPastAttentionMask() { return pastAttentionMask; } /** * Sets the attention mask. * * @param pastAttentionMask the attention mask */ public void setPastAttentionMask(NDArray pastAttentionMask) { this.pastAttentionMask = pastAttentionMask; } /** * Returns the value of the pastKeyValues. * * @return the value of pastKeyValues */ public NDList getPastKeyValues() { return pastKeyValues; } /** * Sets the kv cache. * * @param pastKeyValues the kv cache */ public void setPastKeyValues(NDList pastKeyValues) { this.pastKeyValues = pastKeyValues; } /** * Sets the sequence dimension order which specifies where the sequence dimension is in a * tensor's shape. * * @param seqDimOrder the sequence dimension order which specifies where the sequence dimension * is in a tensor's shape */ public void setSeqDimOrder(long[] seqDimOrder) { this.seqDimOrder = seqDimOrder; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/generate/BeamBatchTensorList.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.modality.nlp.generate; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; class BeamBatchTensorList extends BatchTensorList { // [batch, beam, seq=1] private NDArray nextInputIds; // [batch, beam] private NDArray lastProbs; // [batch, beam, seq_past + new_seq] // The cache of past attentionMask. seq-dim-size == |past_seq| + |inputIds|. Will grow. private NDArray pastAttentionMask; /* Variables below are one time step behind the above state variables. Ie, they contain all the past sequence but excludes the time step that corresponds to the above input. */ // [batch, beam, seq_past]. seq-dim-size == |past_seq| + |inputIds|. Will grow. private NDArray pastOutputIds; // (k, v) * numLayer, // kv: [batch, beam, heads, seq_past, kvfeature] // The cache of past sequence. seq-dim-size == |past_seq| + |inputIds|. Will grow. private NDList pastKeyValues; BeamBatchTensorList() {} BeamBatchTensorList( NDArray nextInputIds, NDArray pastOutputIds, NDList pastKeyValues, NDArray pastAttentionMask, NDArray lastProb) { this.nextInputIds = nextInputIds; this.pastKeyValues = pastKeyValues; this.pastOutputIds = pastOutputIds; this.pastAttentionMask = pastAttentionMask; this.lastProbs = lastProb; } /** {@inheritDoc} */ @Override public BatchTensorList fromList(NDList inputList, long[] seqDimOrder) { return new BeamBatchTensorList(); } /** {@inheritDoc} */ @Override public NDList getList() { return new NDList(); } /** * Returns the value of the nextInputIds. * * @return the value of nextInputIds */ public NDArray getNextInputIds() { return nextInputIds; } public void setNextInputIds(NDArray nextInputIds) { this.nextInputIds = nextInputIds; } /** * Returns the value of the lastProbs. * * @return the value of lastProbs */ public NDArray getLastProbs() { return lastProbs; } public void setLastProbs(NDArray lastProbs) { this.lastProbs = lastProbs; } /** {@inheritDoc} */ @Override public NDArray getPastAttentionMask() { return pastAttentionMask; } /** {@inheritDoc} */ @Override public void setPastAttentionMask(NDArray pastAttentionMask) { this.pastAttentionMask = pastAttentionMask; } /** {@inheritDoc} */ @Override public NDArray getPastOutputIds() { return pastOutputIds; } /** {@inheritDoc} */ @Override public void setPastOutputIds(NDArray pastOutputIds) { this.pastOutputIds = pastOutputIds; } /** {@inheritDoc} */ @Override public NDList getPastKeyValues() { return pastKeyValues; } /** {@inheritDoc} */ @Override public void setPastKeyValues(NDList pastKeyValues) { this.pastKeyValues = pastKeyValues; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/generate/CausalLMOutput.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.modality.nlp.generate; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; /** CausalLMOuput is used to contain multiple output of a language model. */ public class CausalLMOutput { // [batch, seq, feature] // The prob. conditional on a sequence that ends at an element in seq-dim. seq-dim-size = // |inputIds| private NDArray logits; // [batch, seq, dim] * (layers+1) -> take -1 // The vec. rep. of a sequence that ends at an element in seq-dim. seq-dim-size = |inputIds| private NDArray hiddenStates; // (k, v) * numLayer, // kv: [batch, heads, seq_past, feature] // The cache of past sequence. seq-dim-size == |seq_past| + |inputIds| private NDList pastKeyValuesList; /** * Constructs a new {@code CausalLMOutput} instance. * * @param logits the logits NDArray * @param pastKeyValues the key-value cache */ public CausalLMOutput(NDArray logits, NDList pastKeyValues) { this.logits = logits; this.pastKeyValuesList = pastKeyValues; } /** * Constructs a new {@code CausalLMOutput} intance. * * @param logits the logits NDArray * @param hiddenState the first layer hiddenStates used as word embedding * @param pastKeyValueList the key-value cache */ public CausalLMOutput(NDArray logits, NDArray hiddenState, NDList pastKeyValueList) { this.logits = logits; this.pastKeyValuesList = pastKeyValueList; this.hiddenStates = hiddenState; } /** * Returns the value of the logits. * * @return the value of logits */ public NDArray getLogits() { return logits; } /** * Sets the value of the logits. * * @param logits value of logits NDArray */ public void setLogits(NDArray logits) { this.logits = logits; } /** * Returns the value of the allHiddenStates. * * @return the value of allHiddenStates */ public NDArray getHiddenState() { return hiddenStates; } /** * Returns the value of the pastKeyValuesList. * * @return the value of pastKeyValuesList */ public NDList getPastKeyValuesList() { return pastKeyValuesList; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/generate/ContrastiveBatchTensorList.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.modality.nlp.generate; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; class ContrastiveBatchTensorList extends BatchTensorList { // [batch, seq_past, hiddenDim] // The embed vector of the past seq. seq-dim-size = |past_seq|. Will grow. private NDArray pastHiddenStates; // [batch, vacabSize]. Only the last logits, used to recall candidate token. private NDArray logits; ContrastiveBatchTensorList(NDList list, long[] seqDimOrder) { super(list.get(0), list.get(1), list.subNDList(4), seqDimOrder); pastHiddenStates = list.get(2); logits = list.get(3); } ContrastiveBatchTensorList( NDArray pastOutputIds, NDArray pastAttentionMask, NDArray pastHiddenStates, NDArray logits, NDList pastKeyValues, long[] seqDimOrder) { super(pastOutputIds, pastAttentionMask, pastKeyValues, seqDimOrder); this.pastHiddenStates = pastHiddenStates; this.logits = logits; } public ContrastiveBatchTensorList() {} /** {@inheritDoc} */ @Override public ContrastiveBatchTensorList fromList(NDList inputList, long[] seqDimOrder) { return new ContrastiveBatchTensorList(inputList, seqDimOrder); } /** {@inheritDoc} */ @Override public NDList getList() { // The pastOutputIds has to be the first in the output list return new NDList( getPastOutputIds(), getPastAttentionMask(), getPastHiddenStates(), getLogits()) .addAll(getPastKeyValues()); } /** * Returns the value of the pastHiddenStates. * * @return the value of pastHiddenStates */ public NDArray getPastHiddenStates() { return pastHiddenStates; } public void setPastHiddenStates(NDArray pastHiddenStates) { this.pastHiddenStates = pastHiddenStates; } /** * Returns the value of the logits. * * @return the value of logits */ public NDArray getLogits() { return logits; } public void setLogits(NDArray logits) { this.logits = logits; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/generate/ContrastiveSeqBatchScheduler.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.modality.nlp.generate; import ai.djl.inference.Predictor; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDScope; import ai.djl.ndarray.index.NDIndex; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.translate.TranslateException; import java.util.Arrays; import java.util.function.Function; import java.util.stream.Collectors; /** * {@code ContrastiveSeqBatchScheduler} is a class which implements the contrastive search algorithm * used in SeqBatchScheduler. */ public class ContrastiveSeqBatchScheduler extends SeqBatchScheduler { /** * Constructs a new {@code ContrastiveSeqBatchScheduler} instance. * * @param lmBlock the predictor containing language model * @param config the autoregressive search configuration */ public ContrastiveSeqBatchScheduler( Predictor<NDList, CausalLMOutput> lmBlock, SearchConfig config) { super(lmBlock, config); } /** {@inheritDoc} */ @Override public SeqBatcher initForward(NDArray inputIds, NDArray batchUids) throws TranslateException { try (NDScope scope = new NDScope()) { scope.suppressNotUsedWarning(); manager = inputIds.getManager(); NDArray initOffSets = computeOffSets(inputIds, config); NDArray attentionMask = computeAttentionMask(inputIds, config); NDArray positionIds = computePositionIds(inputIds, initOffSets, 0, 1); CausalLMOutput output = predictor.predict(new NDList(inputIds, positionIds, attentionMask)); NDArray lastLogits = output.getLogits().get(":, -1, :"); // Used to mark the sequence dimension's ordinal number for each tensor in the // serialized // batchTensorList long[] seqDimOrder = new long[28]; Arrays.fill(seqDimOrder, 0, 3, 1); seqDimOrder[3] = -1; // -1 means no sequence dimension Arrays.fill(seqDimOrder, 4, seqDimOrder.length, 2); BatchTensorList batchTensorList = new ContrastiveBatchTensorList( inputIds, attentionMask, output.getHiddenState(), lastLogits, output.getPastKeyValuesList(), seqDimOrder); SeqBatcher ret = new SeqBatcher(batchTensorList, batchUids, initOffSets, manager); // memory management NDScope.unregister(output.getPastKeyValuesList()); NDScope.unregister(output.getHiddenState(), attentionMask, lastLogits); NDScope.unregister(ret.offSets, ret.batchUid); return ret; } } /** {@inheritDoc} */ @Override public NDArray inferenceCall() throws TranslateException { NDArray outputIds; try (NDScope scope = new NDScope()) { scope.suppressNotUsedWarning(); /* Prepare input for one inference call */ NDArray logits = ((ContrastiveBatchTensorList) seqBatcher.getData()).getLogits(); NDArray topKIds = logits.topK(config.getK(), -1, true, false).get(1); // [batch, topK] ContrastiveBatchTensorList searchState = (ContrastiveBatchTensorList) seqBatcher.data; // Embed the topk dimension into batch dimension for an inference all // [batch, topK] -> [batch * [topK]] -> [[batch * [topK]], seqLength=1] NDArray candidateInputIds = topKIds.flatten().reshape(-1, 1); assert candidateInputIds.getDataType() == DataType.INT64 : "inputIds datatype should be int64"; assert candidateInputIds.getShape().getShape().length == 2 : "shape not right"; // [batch, heads, seq_past, feature] -> [batch * topK, head, seq_past, feature] NDList kCopyPastKeyValues = new NDList( searchState.getPastKeyValues().stream() .map(ndarray -> ndarray.repeat(0, config.getK())) .collect(Collectors.toList())); assert kCopyPastKeyValues.get(0).getDataType() == DataType.FLOAT32 : "inputIds datatype should be Float32"; // [batch, seq_past] -> [batch * topK, seq_past] -> [batch * topK, seq_past + 1] long numBatch = topKIds.getShape().get(0); NDArray kCopyPastAttentionMask = searchState.getPastAttentionMask().repeat(0, config.getK()); kCopyPastAttentionMask = kCopyPastAttentionMask.concat( manager.ones(new Shape(numBatch * config.getK(), 1), DataType.INT64), 1); assert kCopyPastKeyValues.get(0).getShape().get(2) + 1 == kCopyPastAttentionMask.getShape().getLastDimension() : "attentionMask_seq = past_seq + new_input_seq"; // Forward with candidates in batch input NDArray candidatePositionIds = computePositionIds( candidateInputIds, seqBatcher.offSets, searchState.getPastOutputIds().getShape().getLastDimension(), config.getK()); NDList modelInputs = new NDList(candidateInputIds, candidatePositionIds, kCopyPastAttentionMask); modelInputs.addAll(kCopyPastKeyValues); CausalLMOutput candidateOutput = predictor.predict(modelInputs); NDList generatedOutput = StepGeneration.constrastiveStepGeneration( topKIds, logits, searchState.getPastHiddenStates(), candidateOutput.getHiddenState(), seqBatcher.offSets, config.getAlpha()); /* Update searchState for next loop */ long logitsDim = logits.getShape().get(1); long numHeads = searchState.getPastKeyValues().get(0).getShape().get(1); long kvDim = searchState.getPastKeyValues().get(0).getShape().get(3); long currentSeqLength = searchState.getPastOutputIds().getShape().get(1); long hiddenDim = searchState.getPastHiddenStates().getShape().get(2); // [batch, 1] NDArray select = generatedOutput.get(1); NDIndex selectIndex = new NDIndex( "{}, {}, ...", manager.arange(0, numBatch, 1, DataType.INT64), select.flatten()); // Take from candidateOutput // [batch, k, inputSeq=1, logitsDim] --select--> [batch, logitDim] NDArray nextLogits = candidateOutput .getLogits() .reshape(numBatch, config.getK(), logitsDim) .get(selectIndex); // Take from candidateOutput // [batch * k, heads, seq_past, feature] --select--> [batch, heads, seq_past, feature] Function<NDArray, NDArray> fn = ndarray -> ndarray.reshape( numBatch, config.getK(), numHeads, currentSeqLength + 1, kvDim) .get(selectIndex); NDList nextPastKeyValue = new NDList( candidateOutput.getPastKeyValuesList().stream() .map(fn) .collect(Collectors.toList())); // To be concatenated into searchState.pastHiddenStates // [batch * k, inputSeq=1, hiddenDim] NDArray newHiddenState = candidateOutput.getHiddenState(); assert newHiddenState.getManager() == manager : "possible leaky memory"; NDArray nextPastHiddenStates = searchState .getPastHiddenStates() .concat( newHiddenState .reshape(numBatch, config.getK(), 1, hiddenDim) .get(selectIndex), 1); // To be concatenated into searchState.outputIds // [batch, seq_past] outputIds = generatedOutput.get(0); NDArray nextOutputIds = searchState.getPastOutputIds().concat(outputIds, 1); // [batch, seq_past] NDArray nextPastAttentionMask = searchState .getPastAttentionMask() .concat(manager.ones(new Shape(numBatch, 1), DataType.INT64), 1); seqBatcher.seqLength++; seqBatcher.data = new ContrastiveBatchTensorList( nextOutputIds, nextPastAttentionMask, nextPastHiddenStates, nextLogits, nextPastKeyValue, searchState.getSeqDimOrder()); /* Exit criteria */ seqBatcher.exitCriteria(outputIds, config.getMaxSeqLength(), config.getEosTokenId()); // Memory management NDScope.unregister(nextOutputIds); NDScope.unregister(nextPastAttentionMask); NDScope.unregister(nextPastHiddenStates); NDScope.unregister(nextLogits); NDScope.unregister(nextPastKeyValue); NDScope.unregister(outputIds); } return outputIds; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/generate/GreedyBatchTensorList.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.modality.nlp.generate; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; class GreedyBatchTensorList extends BatchTensorList { // [batch, 1] private NDArray nextInputIds; // [batch, seq_past + new_seq] // The cache of past attentionMask. seq-dim-size == |past_seq| + |inputIds|. Will grow. private NDArray pastAttentionMask; /* Variables below are one time step behind the above state variables. Ie, they contain all the past sequence but excludes the time step that corresponds to the above input. */ // [batch, seq_past]. seq-dim-size == |past_seq| + |inputIds|. Will grow. private NDArray pastOutputIds; // (k, v) * numLayer, // kv: [batch, heads, seq_past, kvfeature] // The cache of past sequence. seq-dim-size == |past_seq| + |inputIds|. Will grow. private NDList pastKeyValues; GreedyBatchTensorList( NDArray nextInputIds, NDArray pastOutputIds, NDList pastKeyValues, NDArray pastAttentionMask) { this.nextInputIds = nextInputIds; this.pastKeyValues = pastKeyValues; this.pastOutputIds = pastOutputIds; this.pastAttentionMask = pastAttentionMask; } public GreedyBatchTensorList() {} /** {@inheritDoc} */ @Override public BatchTensorList fromList(NDList inputList, long[] seqDimOrder) { return new GreedyBatchTensorList(); } /** {@inheritDoc} */ @Override public NDList getList() { return new NDList(); } /** * Returns the value of the nextInputIds. * * @return the value of nextInputIds */ public NDArray getNextInputIds() { return nextInputIds; } public void setNextInputIds(NDArray nextInputIds) { this.nextInputIds = nextInputIds; } /** {@inheritDoc} */ @Override public NDArray getPastAttentionMask() { return pastAttentionMask; } /** {@inheritDoc} */ @Override public void setPastAttentionMask(NDArray pastAttentionMask) { this.pastAttentionMask = pastAttentionMask; } /** {@inheritDoc} */ @Override public NDArray getPastOutputIds() { return pastOutputIds; } /** {@inheritDoc} */ @Override public void setPastOutputIds(NDArray pastOutputIds) { this.pastOutputIds = pastOutputIds; } /** {@inheritDoc} */ @Override public NDList getPastKeyValues() { return pastKeyValues; } /** {@inheritDoc} */ @Override public void setPastKeyValues(NDList pastKeyValues) { this.pastKeyValues = pastKeyValues; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/generate/SearchConfig.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.modality.nlp.generate; /** * {@code SearchConfig} is a class whose fields are parameters used for autoregressive search / text * generation. */ public class SearchConfig { private int k; private float alpha; private int beam; private int maxSeqLength; private long padTokenId; private long eosTokenId; private boolean suffixPadding; /** Constructs a new {@code ContrastiveSearchConfig} instance with default values. */ public SearchConfig() { this.k = 4; this.alpha = 0.6f; this.beam = 3; this.maxSeqLength = 30; this.eosTokenId = 50256; this.padTokenId = 50256; } /** * Returns the value of the k. * * @return the value of k */ public int getK() { return k; } /** * Sets the value for the topk choice. * * @param k the value for topk choice */ public void setK(int k) { this.k = k; } /** * Returns the value of the alpha. * * @return the value of alpha */ public float getAlpha() { return alpha; } /** * Sets the value of alpha the penalty for repetition. * * @param alpha the value of the penalty for repetition */ public void setAlpha(float alpha) { this.alpha = alpha; } /** * Returns the value of the beam. * * @return the value of beam */ public int getBeam() { return beam; } /** * Sets the value of beam size. * * @param beam the value of beam size */ public void setBeam(int beam) { this.beam = beam; } /** * Returns the value of the maxSeqLength. * * @return the value of maxSeqLength */ public int getMaxSeqLength() { return maxSeqLength; } /** * Sets the value of max sequence length. * * @param maxSeqLength the value max sequence length */ public void setMaxSeqLength(int maxSeqLength) { this.maxSeqLength = maxSeqLength; } /** * Returns the value of the padTokenId. * * @return the value of padTokenId */ public long getPadTokenId() { return padTokenId; } /** * Sets the value of padTokenId. * * @param padTokenId the token id for padding */ public void setPadTokenId(long padTokenId) { this.padTokenId = padTokenId; } /** * Returns the value of the eosTokenId. * * @return the value of eosTokenId */ public long getEosTokenId() { return eosTokenId; } /** * Returns the value of the suffixPadding. * * @return the value of suffixPadding */ public boolean isSuffixPadding() { return suffixPadding; } /** * Sets the value of suffixPadding or rightPadding. * * @param suffixPadding whether the padding is from right */ public void setSuffixPadding(boolean suffixPadding) { this.suffixPadding = suffixPadding; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/generate/SeqBatchScheduler.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.modality.nlp.generate; import ai.djl.inference.Predictor; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.index.NDIndex; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.translate.TranslateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * This is a scheduler, serving as an API to the consumer of the system, allowing for three major * actions: initForward, addBatch, fastForward, collectResults. An optimal control sequence should * be solved, after considering the time consumption of each action, the batch size and sequence * length of queueing requests. Such optimal control solver needs additional effort. Primitive * policy is setting several thresholds. */ public abstract class SeqBatchScheduler { private static final Logger logger = LoggerFactory.getLogger(SeqBatchScheduler.class); Predictor<NDList, CausalLMOutput> predictor; SeqBatcher seqBatcher; NDManager manager; SearchConfig config; Map<Long, NDArray> results; /** * Constructs a new {@code SeqBatchScheduler} instance. * * @param lmBlock the predictor that cont * @param config the search parameter configuration */ public SeqBatchScheduler(Predictor<NDList, CausalLMOutput> lmBlock, SearchConfig config) { this.predictor = lmBlock; this.config = config; results = new ConcurrentHashMap<>(); } /** * Initializes the iteration and SeqBatcher. * * @param inputIds the input token ids. * @param batchUids the request uid identifying a sequence * @return SeqBatcher Stores the search state and operate on the BatchTensorList * @throws TranslateException if forward fails */ public abstract SeqBatcher initForward(NDArray inputIds, NDArray batchUids) throws TranslateException; /** * Executes forward for a given number of iterations. * * @param count the time of forward calls * @return boolean Indicate whether the Batch is empty * @throws TranslateException if forward fails */ public boolean incrementForward(int count) throws TranslateException { int i = 0; while (i++ < count) { if (seqBatcher == null || seqBatcher.getData() == null) { logger.info( "seqBatcher not set or is empty. Please call addBatch. Current inference" + " times is " + i); return true; } inferenceCall(); if (seqBatcher.sequenceComplete()) { results.putAll(seqBatcher.collectAndTrim()); } } return false; } /** * An inference call in an iteration. * * @return the output token ids * @throws TranslateException if forward fails */ protected abstract NDArray inferenceCall() throws TranslateException; /** * Adds new batch. * * @param inputIds the input token ids. * @param batchUids the request uid identifying a sequence * @throws TranslateException if forward fails */ public void addRequest(NDArray inputIds, NDArray batchUids) throws TranslateException { SeqBatcher seqBatcherNew = initForward(inputIds, batchUids); if (seqBatcher == null) { seqBatcher = seqBatcherNew; } else { seqBatcher.addBatch(seqBatcherNew); } } /** * Collects finished results. * * @return the outputs stored as a map from requestUid to output token ids */ public Map<Long, NDArray> collectResults() { Map<Long, NDArray> output = results; results = new ConcurrentHashMap<>(); return output; } /** * Computes the offSets by linear search from the left. * * @param inputIds input token ids * @param config search configuration * @return the offsets NDArray */ static NDArray computeOffSets(NDArray inputIds, SearchConfig config) { int numBatch = Math.toIntExact(inputIds.getShape().get(0)); int initSeqSize = Math.toIntExact(inputIds.getShape().get(1)); // Linear search from left to find the first position that's not padTokenId. long[] offSetsArray = new long[numBatch]; for (int i = 0; i < numBatch; i++) { long[] aSequence = inputIds.get("{},:", i).toLongArray(); int idx = 0; while (idx < initSeqSize) { if (aSequence[idx] != config.getPadTokenId()) { break; } idx++; } offSetsArray[i] = idx; } NDManager manager = inputIds.getManager(); return manager.create(offSetsArray).reshape(-1, 1); } /** * Computes the attention mask by linear search from the left. * * @param inputIds input token ids * @param config search configuration * @return the attention mask NDArray */ static NDArray computeAttentionMask(NDArray inputIds, SearchConfig config) { int numBatch = Math.toIntExact(inputIds.getShape().get(0)); int initSeqSize = Math.toIntExact(inputIds.getShape().get(1)); NDManager manager = inputIds.getManager(); NDArray attentionMask = manager.ones(new Shape(1, inputIds.getShape().getLastDimension()), DataType.INT64) .reshape(1, -1) .repeat(0, numBatch); // Linear search to find the offset and set the mask for (int i = 0; i < numBatch; i++) { long[] aSequence = inputIds.get("{},:", i).toLongArray(); int idx = 0; while (idx < initSeqSize) { if (aSequence[idx] != config.getPadTokenId()) { break; } idx++; } attentionMask.set(new NDIndex("{},{}:{}", i, 0, idx), 0); } // [batch, pastSeq] return attentionMask; } /** * Computes the position ids by linear search from the left. * * @param inputIds input token ids * @param offSets the offset * @param pastSeqLength past sequence length * @param repeat the number of repeats used in interleave-repeating the position_ids to multiple * rows * @return the position ids NDArray */ static NDArray computePositionIds( NDArray inputIds, NDArray offSets, long pastSeqLength, int repeat) { NDManager manager = inputIds.getManager(); NDArray positionIds = manager.arange( pastSeqLength, pastSeqLength + inputIds.getShape().getLastDimension(), 1, DataType.INT64) .expandDims(0) .repeat(0, inputIds.getShape().get(0)); NDArray positionIdsShifted = positionIds.subi(offSets.reshape(-1, 1).repeat(0, repeat)); positionIds = positionIdsShifted.maximum(positionIdsShifted.zerosLike()); // [batch, inputSeq] return positionIds; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/generate/SeqBatcher.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.modality.nlp.generate; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.NDScope; import ai.djl.ndarray.index.NDIndex; import ai.djl.ndarray.types.Shape; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * {@code SeqBatcher} stores the search state (BatchTensorList), the control variables (e.g. * seqLength, offSets, etc), and batch operations (merge, trim, exitCriteria, etc) on * BatchTensorList. */ public class SeqBatcher { NDManager manager; long batchSize; long seqLength; /** [batch] stores the uid and is trimmed or enhanced correspondingly to the batch. */ NDArray batchUid; /** Minheap with lazy removal, map: batchIdx -> offset. */ NDArray offSets; /** This is a struct that contains NDArrays with batch dimension. */ BatchTensorList data; /** batchIndex -> seqEndPosition. */ private Map<Long, Long> exitIndexEndPosition; SeqBatcher(BatchTensorList data, NDArray batchUid, NDArray offSets, NDManager manager) { this.manager = manager.newSubManager(); this.data = data; this.batchUid = batchUid.getShape().dimension() == 2 ? batchUid : batchUid.reshape(-1, 1); this.offSets = offSets.getShape().dimension() == 2 ? offSets : offSets.reshape(-1, 1); batchSize = data.getPastOutputIds().getShape().get(0); seqLength = data.getPastOutputIds().getShape().get(1); exitIndexEndPosition = new ConcurrentHashMap<>(); } /** * Returns the batch data which is stored as a {@code BatchTensorList}. * * @return the batch data stored as BatchTensorList */ public BatchTensorList getData() { return data; } /** * Adds new batch. * * <p>Modify the batch dimension and the left padding. * * @param seqBatcherNew the seqBatcher to add. */ public void addBatch(SeqBatcher seqBatcherNew) { merge(this, seqBatcherNew, seqLength - seqBatcherNew.seqLength); // manager and finishedSequences stay the same; } /** * Merges two batchers together. * * <p>Modify the batch dimension and the left padding. * * @param seqBatcher1 the first seqBatcher * @param seqBatcher2 the second seqBatcher * @param seqDelta the sequence length difference */ private void merge(SeqBatcher seqBatcher1, SeqBatcher seqBatcher2, long seqDelta) { if (seqDelta < 0) { SeqBatcher swapTmp = seqBatcher1; seqBatcher1 = seqBatcher2; seqBatcher2 = swapTmp; seqDelta = -seqDelta; } try (NDScope scope = new NDScope()) { scope.suppressNotUsedWarning(); NDList list1 = seqBatcher1.data.getList(); NDList list2 = seqBatcher2.data.getList(); NDList merged = new NDList(list1.size()); long[] seqDimOrder = seqBatcher1.data.getSeqDimOrder(); for (int i = 0; i < list1.size(); i++) { NDArray batch1 = list1.get(i); NDArray batch2 = list2.get(i); if (seqDelta == 0) { // no need to pad batch1 = batch1.concat(batch2, 0); merged.add(batch1); continue; } long[] shape1 = batch1.getShape().getShape(); long[] shape2 = batch2.getShape().getShape(); long padTokenId = 220; // Augment the larger, batch1 long[] shapeDelta = batch1.getShape().getShape(); shapeDelta[0] = shape2[0]; NDArray deltaArray; if (i == 0) { // The outputTokenIds is padded with padTokenId deltaArray = manager.full(new Shape(shapeDelta), padTokenId, batch1.getDataType()); } else { // The rest e.g. attentionMask, kvCache, hiddenStates are padded with 0 deltaArray = manager.zeros(new Shape(shapeDelta), batch1.getDataType()); } batch1 = batch1.concat(deltaArray, 0); // Get the ndIndex used to set the extended part of batch1 to be batch2. NDIndex ndIndex; // Find the ordinal number of the sequence dimension if (seqDimOrder[i] > 0) { // Has a valid sequence dimension ndIndex = new NDIndex("{}:", seqBatcher1.batchSize); int order = 1; while (order < seqDimOrder[i]) { ndIndex = ndIndex.addAllDim(); order++; } assert seqDelta + shape2[order] == shape1[order] : "Wrong shapes. batch1 and batch2 are not mergable"; ndIndex = ndIndex.addSliceDim(seqDelta, shape1[order]).addEllipseDim(); } else { // Only batch dimension, no valid sequence dimension ndIndex = new NDIndex("{}:, ...", seqBatcher1.batchSize); } // Copy batch2 to the extended part in batch1 batch1.set(ndIndex, batch2); merged.add(batch1); } data = data.fromList(merged, data.getSeqDimOrder()); batchSize = seqBatcher1.batchSize + seqBatcher2.batchSize; batchUid = seqBatcher1.batchUid.concat(seqBatcher2.batchUid, 0); offSets = seqBatcher1.offSets.concat(seqBatcher2.offSets.addi(seqDelta), 0); seqLength = seqBatcher1.seqLength; // memory NDScope.unregister(batchUid, offSets); NDScope.unregister(merged); } } /** * Checks which batch needs to exit, according certain criteria like EOS or maxLength. * * <p>It is an iteration over batch and is thus also considered as batch operation. * * @param outputIds output token ids in an incremental forward call * @param maxLength max total sequence length * @param eosTokenId end of sentence token id */ public void exitCriteria(NDArray outputIds, long maxLength, long eosTokenId) { long[] outputIdsArray = outputIds.toLongArray(); long[] offSetsArray = offSets.toLongArray(); for (int i = 0; i < outputIdsArray.length; i++) { if (seqLength - offSetsArray[i] >= maxLength || outputIdsArray[i] == eosTokenId) { if (!exitIndexEndPosition.containsKey((long) i)) { exitIndexEndPosition.put((long) i, seqLength); } } } } /** * Collects the finished sequences and trim the left padding. * * @return a map that stores request id to output token ids */ public Map<Long, NDArray> collectAndTrim() { if (exitIndexEndPosition.isEmpty()) { return new ConcurrentHashMap<>(); } Map<Long, NDArray> finishedSequences = new ConcurrentHashMap<>(); try (NDScope scope = new NDScope()) { scope.suppressNotUsedWarning(); // Collect the results into finishedSequences Set<Long> exitIndices = new HashSet<>(); for (Map.Entry<Long, Long> entry : exitIndexEndPosition.entrySet()) { // batchIndex -> seqEndPosition long batchIndex = entry.getKey(); long seqEndPosition = entry.getValue(); long uid = batchUid.getLong(batchIndex); long offSet = offSets.getLong(batchIndex); NDArray output = data.getPastOutputIds() .get("{}, {}:{}", batchIndex, offSet, seqEndPosition); finishedSequences.put(uid, output); exitIndices.add(batchIndex); NDScope.unregister(output); } // Find the batch indices of the non-finished sequences. long[] keepIndices = new long[Math.toIntExact(batchSize) - exitIndices.size()]; int j = 0; for (long i = 0; i < batchSize; i++) { if (!exitIndices.contains(i)) { keepIndices[j++] = i; } } if (keepIndices.length == 0) { batchUid = manager.create(new Shape(0, 1), batchUid.getDataType()); offSets = manager.create(new Shape(0, 1), offSets.getDataType()); data = null; batchSize = 0; seqLength = 0; exitIndexEndPosition = new ConcurrentHashMap<>(); NDScope.unregister(batchUid, offSets); return finishedSequences; } NDIndex ndIndex = new NDIndex("{}", manager.create(keepIndices)); batchUid = batchUid.get(ndIndex).reshape(-1, 1); offSets = offSets.get(ndIndex).reshape(-1, 1); long trimSeq = offSets.min(new int[] {0}).toLongArray()[0]; offSets = offSets.subi(trimSeq); // Trim batch, and sequence dim if needed NDList list = data.getList(); NDList newList = new NDList(list.size()); long[] seqDimOrder = data.getSeqDimOrder(); for (int i = 0; i < list.size(); i++) { NDArray batch = list.get(i); if (trimSeq == 0) { // no need to trim ndIndex = new NDIndex("{}, ...", manager.create(keepIndices)); newList.add(batch.get(ndIndex)); continue; } // Get the ndIndex used to keep the entries and trim the rest // Find the ordinal number of the sequence dimension if (seqDimOrder[i] > 0) { // Has a valid sequence dimension ndIndex = new NDIndex("{}", manager.create(keepIndices)); int order = 1; while (order < seqDimOrder[i]) { ndIndex = ndIndex.addAllDim(); order++; } ndIndex = ndIndex.addSliceDim(trimSeq, seqLength).addEllipseDim(); } else { // Only batch dimension, no valid sequence dimension ndIndex = new NDIndex("{}, ...", manager.create(keepIndices)); } // Keep the indexed entries and trim the rest newList.add(batch.get(ndIndex)); } data = data.fromList(newList, data.getSeqDimOrder()); batchSize -= exitIndexEndPosition.size(); seqLength -= trimSeq; exitIndexEndPosition = new ConcurrentHashMap<>(); // memory NDScope.unregister(newList); NDScope.unregister(batchUid, offSets); return finishedSequences; } } /** * Computes the position ids by linear search from the left. * * @return the boolean indicating whether all sequences are empty */ public boolean sequenceComplete() { return !exitIndexEndPosition.isEmpty(); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/generate/StepGeneration.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.modality.nlp.generate; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.index.NDIndex; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; /** * {@code StepGeneration} is a utility class containing the step generation utility functions used * in autoregressive search. */ public final class StepGeneration { private StepGeneration() {} /** * Generate the output token id and selecting indices used in contrastive search. * * @param topKIds the topk candidate token ids * @param logits the logits from the language model * @param contextHiddenStates the embedding of the past generated token ids * @param topkHiddenStates the embedding of the topk candidate token ids * @param offSets the offsets * @param alpha the repetition penalty * @return the output token ids and selecting indices */ public static NDList constrastiveStepGeneration( NDArray topKIds, NDArray logits, NDArray contextHiddenStates, NDArray topkHiddenStates, NDArray offSets, float alpha) { /* topKIds: [batch, topK] attentionMask: [batch, past_seq] logits: [batch, vocabSize] contextHiddenStates: [batch, past_seq, dim] topkHiddenStates: [batch*topK, seq=1, dim] attentionMaskSlice: [batch, 2]: (startPosition, endPosition) */ long batch = topKIds.getShape().get(0); long topK = topKIds.getShape().get(1); long hiddenDim = topkHiddenStates.getShape().getLastDimension(); // [batch*topK, seq=1, dim] -> [batch, topK, dim] topkHiddenStates = topkHiddenStates.reshape(batch, topK, hiddenDim); // [batch, topK, dim] * [batch, past_seq, dim] -> [batch, topK, past_seq] topkHiddenStates = topkHiddenStates.normalize(2, 2); contextHiddenStates = contextHiddenStates.normalize(2, 2); NDArray cosSimilarity = topkHiddenStates.batchMatMul(contextHiddenStates.transpose(0, 2, 1)); // Deactivate entries (batch_idx, :, zero_attention_idx_slice) in max{cosSim} step long[] offSetsArray = offSets.toLongArray(); for (int i = 0; i < offSetsArray.length; i++) { cosSimilarity.set(new NDIndex("{}, :, {}:{}", i, 0, offSetsArray[i]), -1); } // [batch, topK, past_seq] -> [batch, topK] NDArray topkScorePart1 = cosSimilarity.max(new int[] {2}); assert topkScorePart1.getShape().getShape().length == 2 : "Wrong output size"; // [batch, logitDim].gather([batch, topK) -> [batch, topK] NDArray topkScorePart2 = logits.softmax(1).gather(topKIds, 1); NDArray topkScore = topkScorePart2.muli(1 - alpha).subi(topkScorePart1.muli(alpha)); // [batch, topK] => [batch, 1] NDArray select = topkScore.argMax(1); NDIndex selectIndex = new NDIndex( "{}, {}, ...", logits.getManager().arange(0, topKIds.getShape().get(0), 1, DataType.INT64), select); NDArray outputIds = topKIds.get(selectIndex).reshape(-1, 1); return new NDList(outputIds, select); } // TODO: add support of Einstein summation: // a = torch.randn(batch, past_seq, dim) // b = torch.randn(batch, topK, dim) // result = torch.einsum('bik,bjk->bij', a, b) /** * Generates the output token id for greedy search. * * @param logits the logits from the language model * @return the output token ids */ public static NDArray greedyStepGen(NDArray logits) { // logits: [batch, seq, probDim] assert logits.getShape().getShape().length == 3 : "unexpected input"; logits = logits.get(":, -1, :"); return logits.argMax(-1).expandDims(1); // [batch, vacDim] } /** * Generates the output token id and selecting indices used in beam search. * * @param lastProbs the probabilities of the past prefix sequences * @param logits the logits * @param numBatch number of batch * @param numBeam number of beam * @return the output token ids and selecting indices */ public static NDList beamStepGeneration( NDArray lastProbs, NDArray logits, long numBatch, long numBeam) { // [batch * beamSource, seq, probDim] -> [batch, beamSource, probDim] NDArray allProbs = logits.get(":, -1, :").softmax(1).reshape(numBatch, numBeam, -1); // Argmax over the probs in the prob dimension. // [batch, beamSource, probDim] -> [batch, beamSource, beamChild] NDList topK = allProbs.topK(Math.toIntExact(numBeam), -1, true, false); NDArray outputIs = topK.get(1); NDArray stepProbs = topK.get(0); // Chain the probability // [batch, beamSource] -> [batch, beamSource, 1] lastProbs = lastProbs.reshape(numBatch, numBeam, 1); // [batch, beamSource, beamChild] NDArray newProbs = stepProbs.muli(lastProbs); // Argmax over the (beamSource * beamChild) dimension topK = newProbs.reshape(numBatch, numBeam * numBeam) .topK(Math.toIntExact(numBeam), -1, true, false); // The select indices act on (beamSource, beamChild) dimension. Decides how the new // generated tokenIds correspond to the past tokenIds. // [batch, beamNew]. NDArray select = topK.get(1); // Act on [batch, beam, ...] dimension and the output will be [batch, beam, ...] NDIndex selectIndex = new NDIndex( "{}, {}, ...", logits.getManager() .arange(0, numBatch, 1, DataType.INT64) .expandDims(1) .repeat(1, numBeam), select); // [batch, beamNew] outputIs = outputIs.reshape(numBatch, numBeam * numBeam).get(selectIndex).expandDims(2); // [batch, beamNew] newProbs = newProbs.reshape(numBatch, numBeam * numBeam).get(selectIndex).normalize(1, 1); /* During the beam selection process, some source beams are selected several times while some source beams are not selected even once. The pastOutputs should be reselected to have the right correspondence to the newInputIds. */ // [batch, beamNew] assert select.getDataType() == DataType.INT64 : "Wrong output! Expect integer division"; assert select.getShape().getShape().length == 2 : "Wrong size. Expect [batch, beamNew]"; // For each batch, convert the index1 in beamSource*beamChild dimension to its index2 in // beamSource dimension: index2 = index1 / numBeam. long[] index = select.toLongArray(); for (int i = 0; i < index.length; i++) { index[i] = Math.floorDiv(index[i], numBeam); } NDArray sourceBeamSelected = logits.getManager().create(index, new Shape(numBatch, numBeam)); return new NDList(outputIs, newProbs, sourceBeamSelected); } // TODO: implement pytorch floor_divide. }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/generate/TextGenerator.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.modality.nlp.generate; import ai.djl.inference.Predictor; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.NDScope; import ai.djl.ndarray.index.NDIndex; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.translate.TranslateException; import java.util.Arrays; import java.util.function.Function; import java.util.stream.Collectors; /** * {@code TextGenerator} is an LMSearch (language model search) which contains multiple * autoregressive search methods. * * <p>It has a Predictor from NDList to CausalLMOutput, which is called inside an autoregressive * inference loop. */ public class TextGenerator { private String searchName; private SearchConfig config; private Predictor<NDList, CausalLMOutput> predictor; private NDArray positionOffset; private long[] endPosition; /** * Constructs a new {@code TextGenerator} instance. * * @param predictor the language model * @param searchName the autoregressive search name * @param searchConfig the autoregressive search configuration */ public TextGenerator( Predictor<NDList, CausalLMOutput> predictor, String searchName, SearchConfig searchConfig) { this.predictor = predictor; this.searchName = searchName; this.config = searchConfig; } /** * Executes greedy search. * * @param inputIds the input token ids. * @return the output token ids stored as NDArray and the endPosition of each sentence * @throws TranslateException if forward fails */ @SuppressWarnings("try") public NDArray greedySearch(NDArray inputIds) throws TranslateException { // Initialize the end position of each sentence endPosition = new long[Math.toIntExact(inputIds.getShape().get(0))]; Arrays.fill(endPosition, config.getMaxSeqLength()); NDArray attentionMask = prepareAttentionMaskOffset(inputIds, config); NDManager manager = inputIds.getManager(); GreedyBatchTensorList searchState = new GreedyBatchTensorList(inputIds, null, null, attentionMask); while (true) { try (NDScope ignore = new NDScope()) { NDArray pastOutputIds = searchState.getPastOutputIds(); NDArray nextInputIds = searchState.getNextInputIds(); NDArray pastAttentionMask = searchState.getPastAttentionMask(); NDList pastKeyValues = searchState.getPastKeyValues(); long pastSeqLength = pastOutputIds == null ? 0 : pastOutputIds.getShape().getLastDimension(); NDList modelInput = prepareInput(nextInputIds, pastAttentionMask, pastSeqLength, 1); if (pastKeyValues != null) { modelInput.addAll(pastKeyValues); } CausalLMOutput modelOutput = predictor.predict(modelInput); NDArray outputIds = StepGeneration.greedyStepGen(modelOutput.getLogits()); // Update searchState if (pastOutputIds == null) { pastOutputIds = nextInputIds; searchState.setPastOutputIds(pastOutputIds); } else { pastOutputIds = pastOutputIds.concat(nextInputIds, 1); searchState.setPastOutputIds(pastOutputIds); } nextInputIds = outputIds; searchState.setNextInputIds(nextInputIds); pastKeyValues = modelOutput.getPastKeyValuesList(); searchState.setPastKeyValues(pastKeyValues); pastAttentionMask = pastAttentionMask.concat( manager.ones( new Shape(inputIds.getShape().get(0), 1), DataType.INT64), 1); searchState.setPastAttentionMask(pastAttentionMask); // memory management NDScope.unregister(nextInputIds, pastAttentionMask, pastOutputIds); NDScope.unregister(pastKeyValues); } // Termination Criteria long[] outputIdsArray = searchState.getNextInputIds().toLongArray(); for (int i = 0; i < endPosition.length; ++i) { for (long tokenId : outputIdsArray) { if (tokenId == config.getEosTokenId()) { endPosition[i] = searchState.getPastOutputIds().getShape().get(1) + 1; break; } } } if (searchState.getPastOutputIds().getShape().get(1) + 1 >= config.getMaxSeqLength()) { break; } } return searchState.getPastOutputIds().concat(searchState.getNextInputIds(), 1); } /** * Generates text using beam search. * * @param inputIds input tokens ids * @return the output token ids stored as NDArray and the endPosition of each sentence * @throws TranslateException if failed run forward * @see <a href="https://huggingface.co/blog/how-to-generate">Beam Search</a> */ @SuppressWarnings("try") public NDArray beamSearch(NDArray inputIds) throws TranslateException { // Initialize the end position of each sentence endPosition = new long[Math.toIntExact(inputIds.getShape().get(0))]; Arrays.fill(endPosition, config.getMaxSeqLength()); NDArray attentionMask = prepareAttentionMaskOffset(inputIds, config); NDManager manager = inputIds.getManager(); long numBeam = config.getBeam(); long numBatch = inputIds.getShape().get(0); BeamBatchTensorList searchState = new BeamBatchTensorList(); long numHeads = 0; long kvDim = 0; while (true) { if (searchState.getPastAttentionMask() == null) { // Initial beams NDList modelInput = prepareInput(inputIds, attentionMask, 0, 1); CausalLMOutput modelOutput = predictor.predict(modelInput); // [batch, probDim] NDArray allProbs = modelOutput.getLogits().get(":, -1, :").softmax(1); // [batch, beam] NDList topK = allProbs.topK(Math.toIntExact(numBeam), -1, true, false); NDArray outputIds = topK.get(1).expandDims(2); NDArray lastProbs = topK.get(0).normalize(1, 1); assert outputIds.getShape().getShape().length == 3 : "Wrong shape"; assert lastProbs.getShape().getShape().length == 2 : "Wrong Shape"; // [batch, beam, seq + 1] attentionMask = attentionMask .concat(manager.ones(new Shape(numBatch, 1), DataType.INT64), -1) .expandDims(1) .repeat(1, numBeam); // [batch, beam, heads, seq_past, kvFeature] Function<NDArray, NDArray> fn = ndarray -> ndarray.expandDims(1).repeat(1, numBeam); NDList pastKeyValues = new NDList( modelOutput.getPastKeyValuesList().stream() .map(fn) .collect(Collectors.toList())); // [batch, beam, seq_past] NDArray pastOutputIds = inputIds.expandDims(1).repeat(1, numBeam); searchState = new BeamBatchTensorList( outputIds, pastOutputIds, pastKeyValues, attentionMask, lastProbs); numHeads = pastKeyValues.get(0).getShape().get(2); kvDim = pastKeyValues.get(0).getShape().getLastDimension(); } try (NDScope ignore = new NDScope()) { long pastSeqLength = searchState.getPastOutputIds().getShape().getLastDimension(); NDList modelInput = prepareInput( searchState.getNextInputIds().reshape(numBatch * numBeam, 1), searchState.getPastAttentionMask().reshape(numBatch * numBeam, -1), pastSeqLength, config.getBeam()); final long finalNumHeads = numHeads; final long finalKvDim = kvDim; Function<NDArray, NDArray> fn = ndarray -> ndarray.reshape( numBatch * numBeam, finalNumHeads, pastSeqLength, finalKvDim); NDList pastKeyValues = new NDList( searchState.getPastKeyValues().stream() .map(fn) .collect(Collectors.toList())); modelInput.addAll(pastKeyValues); CausalLMOutput modelOutput = predictor.predict(modelInput); NDList generatedOutput = StepGeneration.beamStepGeneration( searchState.getLastProbs(), modelOutput.getLogits(), numBatch, numBeam); // Update searchState searchState = updateSearchState(searchState, modelOutput, generatedOutput, manager); // Memory management NDScope.unregister( searchState.getNextInputIds(), searchState.getPastOutputIds(), searchState.getPastAttentionMask(), searchState.getLastProbs()); NDScope.unregister(searchState.getPastKeyValues()); } // Termination Criteria long[] outputIdsArray = searchState.getNextInputIds().toLongArray(); for (int i = 0; i < endPosition.length; ++i) { for (long tokenId : outputIdsArray) { if (tokenId == config.getEosTokenId()) { endPosition[i] = searchState.getPastOutputIds().getShape().get(1) + 1; break; } } } if (searchState.getPastOutputIds().getShape().getLastDimension() + 1 >= config.getMaxSeqLength()) { break; } } return searchState .getPastOutputIds() .concat(searchState.getNextInputIds(), -1) .reshape(numBatch * numBeam, -1); } /** * Generates text using contrastive search. * * @param inputIds input token ids * @return the output token ids stored as NDArray * @throws TranslateException if forward failed * @see <a href="https://huggingface.co/blog/introducing-csearch">Contrastive Search</a> */ @SuppressWarnings("try") public NDArray contrastiveSearch(NDArray inputIds) throws TranslateException { // inputIds: [batchSize, seqLength: t_init] // attentionMask: [batchSize, pastSeq]. seq-dim-size = |past_seq| + |inputIds|. // Initialize the end position of each sentence endPosition = new long[Math.toIntExact(inputIds.getShape().get(0))]; Arrays.fill(endPosition, config.getMaxSeqLength()); NDManager manager = inputIds.getManager(); NDArray attentionMask = prepareAttentionMaskOffset(inputIds, config); ContrastiveBatchTensorList searchState = new ContrastiveBatchTensorList(); while (true) { if (searchState.getPastKeyValues() == null) { NDList modelInput = prepareInput(inputIds, attentionMask, 0, 1); CausalLMOutput output = predictor.predict(modelInput); NDArray lastLogits = output.getLogits().get(":, -1, :"); searchState = new ContrastiveBatchTensorList( inputIds, attentionMask, output.getHiddenState(), lastLogits, output.getPastKeyValuesList(), new long[] {}); } /* Contrastive search loop main part */ // (1) candidate tokens recall; // (2) candidate re-rank by degeneration penalty try (NDScope ignore = new NDScope()) { NDArray topKIds = searchState .getLogits() .topK(config.getK(), -1, true, false) .get(1); // [batch, topK] // Generate model inputs and put candidates together into batch // [batch, topK] -> [batch * [topK]] -> [[batch * [topK]], seqLength=1] NDArray candidateInputIds = topKIds.flatten().reshape(-1, 1); assert candidateInputIds.getDataType() == DataType.INT64 : "inputIds datatype should be int64"; assert candidateInputIds.getShape().getShape().length == 2 : "shape not right"; // [batch, heads, seq_past, feature] -> [batch * topK, head, seq_past, feature] NDList kCopyPastKeyValues = new NDList( searchState.getPastKeyValues().stream() .map(ndarray -> ndarray.repeat(0, config.getK())) .collect(Collectors.toList())); assert kCopyPastKeyValues.get(0).getDataType() == DataType.FLOAT32 : "inputIds datatype should be Float32"; // [batch, seq_past] -> [batch * topK, seq_past] -> [batch * topK, seq_past + 1] long numBatch = topKIds.getShape().get(0); NDArray kCopyPastAttentionMask = searchState.getPastAttentionMask().repeat(0, config.getK()); kCopyPastAttentionMask = kCopyPastAttentionMask.concat( manager.ones( new Shape(numBatch * config.getK(), 1), DataType.INT64), 1); assert kCopyPastKeyValues.get(0).getShape().get(2) + 1 == kCopyPastAttentionMask.getShape().getLastDimension() : "attentionMask_seq = past_seq + new_input_seq"; // Forward with candidates in batch input NDList candidateModelInput = prepareInput( candidateInputIds, kCopyPastAttentionMask, searchState.getPastOutputIds().getShape().getLastDimension(), config.getK()); candidateModelInput.addAll(kCopyPastKeyValues); CausalLMOutput candidateOutput = predictor.predict(candidateModelInput); NDList generatedOutput = StepGeneration.constrastiveStepGeneration( topKIds, searchState.getLogits(), searchState.getPastHiddenStates(), candidateOutput.getHiddenState(), positionOffset, config.getAlpha()); // Update searchState for next loop searchState = updateSearchState(searchState, candidateOutput, generatedOutput, manager); // Memory NDScope.unregister( searchState.getPastOutputIds(), searchState.getPastAttentionMask(), searchState.getLogits(), searchState.getPastHiddenStates()); NDScope.unregister(searchState.getPastKeyValues()); } // Termination Criteria long[] outputIdsArray = searchState.getPastOutputIds().toLongArray(); for (int i = 0; i < endPosition.length; ++i) { for (long tokenId : outputIdsArray) { if (tokenId == config.getEosTokenId()) { endPosition[i] = searchState.getPastOutputIds().getShape().get(1); break; } } } if (searchState.getPastOutputIds().getShape().get(1) >= config.getMaxSeqLength()) { break; } } return searchState.getPastOutputIds(); } private static BeamBatchTensorList updateSearchState( BeamBatchTensorList searchState, CausalLMOutput modelOutput, NDList generatedOutput, NDManager manager) { NDList pastKeyValues = searchState.getPastKeyValues(); long numHeads = pastKeyValues.get(0).getShape().get(2); long kvDim = pastKeyValues.get(0).getShape().getLastDimension(); long numBatch = searchState.getPastOutputIds().getShape().get(0); long numBeam = searchState.getPastOutputIds().getShape().get(1); long pastSeqLength = searchState.getPastOutputIds().getShape().getLastDimension(); NDArray nextInputIds = generatedOutput.get(0); assert nextInputIds.getShape().getShape().length == 3 : "Wrong Shape"; NDArray newProbs = generatedOutput.get(1); // [batch, beamNew] NDArray sourceBeamSelected = generatedOutput.get(2); // Act on [batch, beam, ...] dimension and the output will be [batch, beam, ...] NDIndex sourceBeamIndex = new NDIndex( "{}, {}, ...", manager.arange(0, numBatch, 1, DataType.INT64) .expandDims(1) .repeat(1, numBeam), sourceBeamSelected); // A simple concatenation is not enough. During the beam selection process, some source // beams are selected several times while some source beams are not selected even once. // The pastOutput should be reselected to have the right correspondence to the // newInputIds. NDArray pastOutputIds = searchState .getPastOutputIds() .concat(searchState.getNextInputIds(), -1) .get(sourceBeamIndex); Function<NDArray, NDArray> fn = ndarray -> ndarray.reshape(numBatch, numBeam, numHeads, pastSeqLength + 1, kvDim) .get(sourceBeamIndex); pastKeyValues = new NDList( modelOutput.getPastKeyValuesList().stream() .map(fn) .collect(Collectors.toList())); NDArray pastAttentionMask = searchState .getPastAttentionMask() .concat(manager.ones(new Shape(numBatch, numBeam, 1), DataType.INT64), -1) .get(sourceBeamIndex); return new BeamBatchTensorList( nextInputIds, pastOutputIds, pastKeyValues, pastAttentionMask, newProbs); } private static ContrastiveBatchTensorList updateSearchState( ContrastiveBatchTensorList searchState, CausalLMOutput candidateOutput, NDList generatedOutput, NDManager manager) { // Update searchState for next iteration assert candidateOutput.getLogits().getShape().get(1) == 1 : "dimension check: here, outputLogits corresponds to inputSeq == 1"; long numBatch = searchState.getLogits().getShape().get(0); long logitsDim = searchState.getLogits().getShape().get(1); long pastSeqLengthPriorUpdate = searchState.getPastOutputIds().getShape().get(1); long numHeads = searchState.getPastKeyValues().get(0).getShape().get(1); long kvDim = searchState.getPastKeyValues().get(0).getShape().get(3); long hiddenDim = searchState.getPastHiddenStates().getShape().get(2); long k = candidateOutput.getLogits().getShape().get(0) / numBatch; // [batch, 1] NDArray select = generatedOutput.get(1); NDIndex selectIndex = new NDIndex( "{}, {}, ...", manager.arange(0, numBatch, 1, DataType.INT64), select.flatten()); // Take from candidateOutput // [batch, k, inputSeq=1, logitsDim] --select--> [batch, logitDim] NDArray nextLogits = candidateOutput.getLogits().reshape(numBatch, k, logitsDim).get(selectIndex); // Take from candidateOutput // [batch * k, heads, seq_past, feature] --select--> [batch, heads, seq_past, feature] Function<NDArray, NDArray> fn = ndarray -> ndarray.reshape(numBatch, k, numHeads, pastSeqLengthPriorUpdate + 1, kvDim) .get(selectIndex); NDList nextPastKeyValue = new NDList( candidateOutput.getPastKeyValuesList().stream() .map(fn) .collect(Collectors.toList())); // To be concatenated into searchState.pastHiddenStates // [batch * k, inputSeq=1, hiddenDim] NDArray newHiddenState = candidateOutput.getHiddenState(); assert newHiddenState.getManager() == manager : "possible leaky memory"; NDArray nextPastHiddenStates = searchState .getPastHiddenStates() .concat( newHiddenState.reshape(numBatch, k, 1, hiddenDim).get(selectIndex), 1); // To be concatenated into searchState.outputIds // [batch, seq_past] NDArray outputIds = generatedOutput.get(0); NDArray nextOutputIds = searchState.getPastOutputIds().concat(outputIds, 1); // [batch, seq_past] NDArray nextPastAttentionMask = searchState .getPastAttentionMask() .concat(manager.ones(new Shape(numBatch, 1), DataType.INT64), 1); return new ContrastiveBatchTensorList( nextOutputIds, nextPastAttentionMask, nextPastHiddenStates, nextLogits, nextPastKeyValue, new long[] {}); } private NDArray prepareAttentionMaskOffset(NDArray inputIds, SearchConfig config) { // prepare attentionMask and positionOffset // Used to initialize the search boolean suffixPadding = config.isSuffixPadding(); NDManager manager = inputIds.getManager(); int numBatch = Math.toIntExact(inputIds.getShape().get(0)); int initSeqSize = Math.toIntExact(inputIds.getShape().get(1)); NDArray attentionMask = manager.ones(new Shape(1, inputIds.getShape().getLastDimension()), DataType.INT64) .reshape(1, -1) .repeat(0, numBatch); // Linear search from left to find the first position that's not padTokenId. long[][] offset = new long[numBatch][1]; for (int i = 0; i < numBatch; i++) { long[] aSequence = inputIds.get("{},:", i).toLongArray(); int idx = 0; while (idx < initSeqSize) { if (suffixPadding && aSequence[idx] == config.getPadTokenId() || !suffixPadding && aSequence[idx] != config.getPadTokenId()) { break; } idx++; } attentionMask.set( new NDIndex( "{},{}:{}", i, suffixPadding ? idx : 0, suffixPadding ? initSeqSize : idx), 0); if (!suffixPadding) { offset[i][0] = idx; } } positionOffset = manager.create(offset); return attentionMask; } private NDList prepareInput( NDArray inputIds, NDArray attentionMask, long pastSeqLength, int repeat) { // Pack the model input NDArray positionIds = inputIds.getManager() .arange( pastSeqLength, pastSeqLength + inputIds.getShape().getLastDimension(), 1, DataType.INT64) .expandDims(0) .repeat(0, inputIds.getShape().get(0)); NDArray positionIdsShifted = positionIds.subi(positionOffset.repeat(0, repeat)); positionIds = positionIdsShifted.maximum(positionIdsShifted.zerosLike()); return new NDList(inputIds, positionIds, attentionMask); } /** * Generate function call to generate text. * * @param inputIds the input token ids * @return generated token ids * @throws TranslateException if prediction fails */ public NDArray generate(NDArray inputIds) throws TranslateException { switch (searchName) { case "greedy": return greedySearch(inputIds); case "beam": return beamSearch(inputIds); case "contrastive": return contrastiveSearch(inputIds); default: throw new IllegalArgumentException( "searchName not correctly specified. Please choose among: {greedy, beam," + " contrastive}"); } } /** * Returns the value of the positionOffset. * * @return the value of positionOffset */ public NDArray getPositionOffset() { return positionOffset; } /** * Returns the end position of each sentence induced by EOS tokenId or reaching maxSeqLength. * * @return the end position of each sentence */ public long[] getEndPosition() { return endPosition; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/generate/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 utility classes for image manipulation. */ package ai.djl.modality.nlp.generate;
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/preprocess/HyphenNormalizer.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.modality.nlp.preprocess; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * Unicode normalization does not take care of "exotic" hyphens that we normally do not want in NLP * input. This preprocessor turns all Hyphens into "normal" ASCII minus-hyphen characters (U+002D). * Invisible soft hyphens are dropped from the input. */ public class HyphenNormalizer implements TextProcessor { private static final int SOFT_HYPHEN = 0x00AD; private static final Set<Integer> HYPHENS = new HashSet<>( Arrays.asList( 0x002D, 0x007E, 0x00AD, 0x058A, 0x05BE, 0x2010, 0x2011, 0x2012, 0x2013, 0x2014, 0x2015, 0x2053, 0x207B, 0x208B, 0x2212, 0x2E3A, 0x2E3B, 0x301C, 0x3030, 0xFE31, 0xFE32, 0xFE58, 0xFE63, 0xFF0D)); /** * Returns whether the given code point is a hyphen-like codepoint. Tests for hyphen-minus, * tilde, soft hyphen, armenian hyphen, hebrew punctuation maqaf, canadian syllabics hyphen, * mongolian hyphen, non-breaking hyphen, figure dash, en dash, em dash, horizontal bar, swung * dash, superscript minus, subscript minus, minus sign, double oblique hyphen, two-em dash, * three-em dash, wave dash, wavy dash, katakana-hiragana double hyphen * * @param codePoint A unicode code point. (not a char!) * @return true: given code point represents a hyphen-like glyph */ public static boolean isHyphenLike(final Integer codePoint) { return HYPHENS.contains(codePoint); } /** * Replaces hyphen like codepoints by ASCII "-", removes soft hyphens. * * @param s input string to replace hyphens in * @return the same string with soft hyphens dropped and hyphen-like codepoints replaced by an * ASCII minus. */ @SuppressWarnings("PMD.EmptyControlStatement") public static String normalizeHyphens(final String s) { final StringBuilder temp = new StringBuilder(s.length()); int position = 0; while (position < s.length()) { final int cp = s.codePointAt(position); if (cp == SOFT_HYPHEN) { // drop soft hyphens // do nothing } else if (isHyphenLike(cp)) { // replace "exotic" hyphens by a simple ASCII '-' temp.append('-'); } else { temp.appendCodePoint(cp); } position += Character.isBmpCodePoint(cp) ? 1 : 2; } return temp.toString(); } /** {@inheritDoc} */ @Override public List<String> preprocess(final List<String> tokens) { return tokens.stream().map(HyphenNormalizer::normalizeHyphens).collect(Collectors.toList()); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/preprocess/LambdaProcessor.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.modality.nlp.preprocess; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; /** * {@code TextProcessor} will apply user defined lambda function on input tokens. * * <p>The function can only support single input and output. */ public class LambdaProcessor implements TextProcessor { private Function<String, String> processor; /** * Creates a {@code LambdaProcessor} and specify the function to apply. * * @param processor The lambda function to apply on input String */ public LambdaProcessor(Function<String, String> processor) { this.processor = processor; } /** {@inheritDoc} */ @Override public List<String> preprocess(List<String> tokens) { return tokens.stream().map(processor).collect(Collectors.toList()); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/preprocess/LowerCaseConvertor.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.modality.nlp.preprocess; import java.util.List; import java.util.Locale; import java.util.stream.Collectors; /** * {@code LowerCaseConvertor} converts every character of the input tokens to it's respective lower * case character. */ public class LowerCaseConvertor implements TextProcessor { private static final Locale DEFAULT_LOCALE = Locale.ENGLISH; private final Locale locale; /** * Creates a {@link TextProcessor} that converts input text into lower case character given the * {@link Locale}. * * @param locale the expected {@link Locale} of the input text */ public LowerCaseConvertor(Locale locale) { this.locale = locale; } /** * Creates a {@link TextProcessor} that converts input text into lower case character with the * default english {@link Locale}. */ public LowerCaseConvertor() { this(DEFAULT_LOCALE); } /** {@inheritDoc} */ @Override public List<String> preprocess(List<String> tokens) { return tokens.stream().map(s -> s.toLowerCase(locale)).collect(Collectors.toList()); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/preprocess/PunctuationSeparator.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.modality.nlp.preprocess; import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Collectors; /** {@code PunctuationSeparator} separates punctuation into a separate token. */ public class PunctuationSeparator implements TextProcessor { private static final Pattern PATTERN = Pattern.compile( "\\s+|(?<=[\\p{Punct}\\p{IsPunctuation}])|(?=[\\p{Punct}\\p{IsPunctuation}])"); /** {@inheritDoc} */ @Override public List<String> preprocess(List<String> tokens) { return tokens.stream() .map(PATTERN::split) .flatMap(Arrays::stream) .filter(s -> !s.isEmpty()) .collect(Collectors.toList()); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/preprocess/SimpleTokenizer.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.modality.nlp.preprocess; import java.util.Arrays; import java.util.List; /** * {@code SimpleTokenizer} is an implementation of the {@link Tokenizer} interface that converts * sentences into token by splitting them by a given delimiter. */ public class SimpleTokenizer implements Tokenizer { private String delimiter = " "; /** * Creates an instance of {@code SimpleTokenizer} with the given delimiter. * * @param delimiter the delimiter */ public SimpleTokenizer(String delimiter) { this.delimiter = delimiter; } /** Creates an instance of {@code SimpleTokenizer} with the default delimiter (" "). */ public SimpleTokenizer() {} /** {@inheritDoc} */ @Override public List<String> tokenize(String sentence) { return Arrays.asList(sentence.split(delimiter)); } /** {@inheritDoc} */ @Override public String buildSentence(List<String> tokens) { return String.join(delimiter, tokens); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/preprocess/TextCleaner.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.modality.nlp.preprocess; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; /** Applies remove or replace of certain characters based on condition. */ public class TextCleaner implements TextProcessor { private Function<Character, Boolean> condition; private char replace; /** * Remove a character if it meets the condition supplied. * * @param condition lambda function that defines whether a character meets condition */ public TextCleaner(Function<Character, Boolean> condition) { this.condition = condition; } /** * Replace a character if it meets the condition supplied. * * @param condition lambda function that defines whether a character meets condition * @param replace the character to replace */ public TextCleaner(Function<Character, Boolean> condition, char replace) { this.condition = condition; this.replace = replace; } private String cleanText(String text) { StringBuilder sb = new StringBuilder(); for (char c : text.toCharArray()) { if (condition.apply(c)) { if (replace == '\u0000') { continue; } else { sb.append(replace); } } else { sb.append(c); } } return sb.toString(); } /** {@inheritDoc} */ @Override public List<String> preprocess(List<String> tokens) { return tokens.stream().map(this::cleanText).collect(Collectors.toList()); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/preprocess/TextProcessor.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.modality.nlp.preprocess; import java.util.List; /** * {@code TextProcessor} allows applying pre-processing to input tokens for natural language * applications. Multiple implementations of {@code TextProcessor} can be applied on the same input. * The order of application of different implementations of {@code TextProcessor} can make a * difference in the final output. */ public interface TextProcessor { /** * Applies the preprocessing defined to the given input tokens. * * @param tokens the tokens created after the input text is tokenized * @return the preprocessed tokens */ List<String> preprocess(List<String> tokens); }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/preprocess/TextTerminator.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.modality.nlp.preprocess; import java.util.ArrayList; import java.util.List; /** A {@link TextProcessor} that adds a beginning of string and end of string token. */ public class TextTerminator implements TextProcessor { private static final String DEFAULT_EOS_TOKEN = "<eos>"; private static final String DEFAULT_BOS_TOKEN = "<bos>"; private boolean addBosToken; private boolean addEosToken; private String eosToken; private String bosToken; /** Constructs a default {@link TextTerminator}. */ public TextTerminator() { this(true, true); } /** * Constructs a {@link TextTerminator} using the default tokens. * * @param addBosToken true to add a beginning of text token * @param addEosToken true to add an end of text token */ public TextTerminator(boolean addBosToken, boolean addEosToken) { this.addBosToken = addBosToken; this.addEosToken = addEosToken; this.bosToken = DEFAULT_BOS_TOKEN; this.eosToken = DEFAULT_EOS_TOKEN; } /** * Constructs a {@link TextTerminator}. * * @param addBosToken true to add a beginning of text token * @param addEosToken true to add an end of text token * @param bosToken the token to add to the beginning of the text * @param eosToken the token to add to the end of the text */ public TextTerminator( boolean addBosToken, boolean addEosToken, String bosToken, String eosToken) { this.addBosToken = addBosToken; this.addEosToken = addEosToken; this.bosToken = bosToken; this.eosToken = eosToken; } /** {@inheritDoc} */ @Override public List<String> preprocess(List<String> tokens) { List<String> list = new ArrayList<>(tokens.size() + 2); if (addBosToken) { list.add(bosToken); } list.addAll(tokens); if (addEosToken) { list.add(eosToken); } return list; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/preprocess/TextTruncator.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.modality.nlp.preprocess; import java.util.List; /** {@link TextProcessor} that truncates text to a maximum size. */ public class TextTruncator implements TextProcessor { int maxSize; /** * Constructs a {@link TextTruncator}. * * @param maxSize the size to limit the text to */ public TextTruncator(int maxSize) { this.maxSize = maxSize; } /** {@inheritDoc} */ @Override public List<String> preprocess(List<String> tokens) { if (tokens.size() <= maxSize) { return tokens; } return tokens.subList(0, maxSize); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/preprocess/Tokenizer.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.modality.nlp.preprocess; import java.util.List; import java.util.stream.Collectors; /** * {@code Tokenizer} interface provides the ability to break-down sentences into embeddable tokens. */ public interface Tokenizer extends TextProcessor { /** {@inheritDoc} */ @Override default List<String> preprocess(List<String> tokens) { return tokens.stream() .map(this::tokenize) .flatMap(List::stream) .collect(Collectors.toList()); } /** * Breaks down the given sentence into a list of tokens that can be represented by embeddings. * * @param sentence the sentence to tokenize * @return a {@link List} of tokens */ List<String> tokenize(String sentence); /** * Combines a list of tokens to form a sentence. * * @param tokens the {@link List} of tokens * @return the sentence built from the given tokens */ String buildSentence(List<String> tokens); }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/preprocess/UnicodeNormalizer.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.modality.nlp.preprocess; import java.text.Normalizer; import java.util.List; import java.util.stream.Collectors; /** * Applies unicode normalization to input strings. This is particularly important if you are dealing * with non-English input or with text originating from OCR applications. */ public class UnicodeNormalizer implements TextProcessor { public static final Normalizer.Form DEFAULT_FORM = Normalizer.Form.NFKC; private final Normalizer.Form normalForm; /** * Unicode normalizer with a configurable normal form. * * @param normalForm The normal form to use. */ public UnicodeNormalizer(final Normalizer.Form normalForm) { this.normalForm = normalForm; } /** * Default version of the Unicode Normalizer using NFKC normal form. If you do not know what * normal form you need, this is the normal form you need. */ public UnicodeNormalizer() { this(DEFAULT_FORM); } /** * Normalizes a String using a sensible default normal form. Use this if you do not want to * think about unicode preprocessing. * * @param s Any non-null string * @return The given string with default unicode normalization applied. */ public static String normalizeDefault(final String s) { return Normalizer.normalize(s, DEFAULT_FORM); } /** {@inheritDoc} */ @Override public List<String> preprocess(final List<String> tokens) { return tokens.stream() .map((s) -> Normalizer.normalize(s, normalForm)) .collect(Collectors.toList()); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/preprocess/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 utility classes for natural language pre-processing tasks. */ package ai.djl.modality.nlp.preprocess;
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/qa/QAInput.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.modality.nlp.qa; /** The input container for a {@link ai.djl.Application.NLP#QUESTION_ANSWER} model. */ public class QAInput { private String question; private String paragraph; private String context; /** * Creates the BERT QA model. * * @param question the question for the model * @param paragraph the resource document that contains the answer */ public QAInput(String question, String paragraph) { this.question = question; this.paragraph = paragraph; } /** * Returns the question for the model. * * @return the question for the model */ public String getQuestion() { return question; } /** * Returns the resource document that contains the answer. * * @return the resource document that contains the answer */ public String getParagraph() { return paragraph == null ? context : paragraph; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/qa/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 utility classes for question and answer processing. */ package ai.djl.modality.nlp.qa;
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/translator/CrossEncoderServingTranslator.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.modality.nlp.translator; import ai.djl.modality.Input; import ai.djl.modality.Output; import ai.djl.ndarray.BytesSupplier; import ai.djl.ndarray.NDList; import ai.djl.translate.Batchifier; import ai.djl.translate.TranslateException; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; import ai.djl.util.JsonUtils; import ai.djl.util.PairList; import ai.djl.util.StringPair; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import java.util.ArrayList; import java.util.List; /** A {@link Translator} that can handle generic cross encoder {@link Input} and {@link Output}. */ public class CrossEncoderServingTranslator implements Translator<Input, Output> { private Translator<StringPair, float[]> translator; /** * Constructs a {@code CrossEncoderServingTranslator} instance. * * @param translator a {@code Translator} processes question answering input */ public CrossEncoderServingTranslator(Translator<StringPair, float[]> translator) { this.translator = translator; } /** {@inheritDoc} */ @Override public void prepare(TranslatorContext ctx) throws Exception { translator.prepare(ctx); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, Input input) throws Exception { ReRankingInput in = ReRankingInput.parseInput(input); if (in.batch != null) { ctx.setAttachment("batch", Boolean.TRUE); return translator.batchProcessInput(ctx, in.batch); } NDList ret = translator.processInput(ctx, in.pair); Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { NDList[] batch = {ret}; return batchifier.batchify(batch); } return ret; } /** {@inheritDoc} */ @Override @SuppressWarnings("PMD.SignatureDeclareThrowsException") public NDList batchProcessInput(TranslatorContext ctx, List<Input> inputs) throws Exception { int[] mapping = new int[inputs.size()]; List<StringPair> prompts = new ArrayList<>(mapping.length); for (int i = 0; i < mapping.length; ++i) { ReRankingInput in = ReRankingInput.parseInput(inputs.get(i)); if (in.batch != null) { List<StringPair> batch = in.batch; mapping[i] = batch.size(); prompts.addAll(batch); } else { mapping[i] = -1; prompts.add(in.pair); } } ctx.setAttachment("mapping", mapping); return translator.batchProcessInput(ctx, prompts); } /** {@inheritDoc} */ @Override public Output processOutput(TranslatorContext ctx, NDList list) throws Exception { Output output = new Output(); output.addProperty("Content-Type", "application/json"); if (ctx.getAttachment("batch") != null) { output.add(BytesSupplier.wrapAsJson(translator.batchProcessOutput(ctx, list))); } else { Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { list = batchifier.unbatchify(list)[0]; } output.add(BytesSupplier.wrapAsJson(translator.processOutput(ctx, list))); } return output; } /** {@inheritDoc} */ @Override @SuppressWarnings("PMD.SignatureDeclareThrowsException") public List<Output> batchProcessOutput(TranslatorContext ctx, NDList list) throws Exception { List<float[]> outputs = translator.batchProcessOutput(ctx, list); int[] mapping = (int[]) ctx.getAttachment("mapping"); List<Output> ret = new ArrayList<>(mapping.length); int index = 0; for (int size : mapping) { Output output = new Output(); output.addProperty("Content-Type", "application/json"); if (size == -1) { // non-batching output.add(BytesSupplier.wrapAsJson(outputs.get(index++))); } else { // client side batching float[][] embeddings = new float[size][]; for (int j = 0; j < size; ++j) { embeddings[j] = outputs.get(index++); } output.add(BytesSupplier.wrapAsJson(embeddings)); } ret.add(output); } return ret; } private static final class ReRankingInput { private StringPair pair; private List<StringPair> batch; ReRankingInput(StringPair pair) { this.pair = pair; } ReRankingInput(List<StringPair> batch) { this.batch = batch; } static ReRankingInput parseInput(Input input) throws TranslateException { PairList<String, BytesSupplier> content = input.getContent(); if (content.isEmpty()) { throw new TranslateException("Input data is empty."); } String contentType = input.getProperty("Content-Type", null); if (contentType != null) { int pos = contentType.indexOf(';'); if (pos > 0) { contentType = contentType.substring(0, pos); } } StringPair pair = null; if ("application/json".equals(contentType)) { String json = input.getData().getAsString(); try { JsonElement element = JsonUtils.GSON.fromJson(json, JsonElement.class); if (element.isJsonArray()) { JsonArray array = element.getAsJsonArray(); int size = array.size(); List<StringPair> batch = new ArrayList<>(size); for (int i = 0; i < size; ++i) { JsonObject obj = array.get(i).getAsJsonObject(); batch.add(parseStringPair(obj)); } return new ReRankingInput(batch); } else if (element.isJsonObject()) { JsonObject obj = element.getAsJsonObject(); JsonElement query = obj.get("query"); if (query != null) { String key = query.getAsString(); JsonArray texts = obj.get("texts").getAsJsonArray(); int size = texts.size(); List<StringPair> batch = new ArrayList<>(size); for (int i = 0; i < size; ++i) { String value = texts.get(i).getAsString(); batch.add(new StringPair(key, value)); } return new ReRankingInput(batch); } else { pair = parseStringPair(obj); } } else { throw new TranslateException("Unexpected json type"); } } catch (JsonParseException e) { throw new TranslateException("Input is not a valid json.", e); } } else { String text = input.getAsString("text"); String textPair = input.getAsString("text_pair"); if (text != null && textPair != null) { pair = new StringPair(text, textPair); } String key = input.getAsString("key"); String value = input.getAsString("value"); if (key != null && value != null) { pair = new StringPair(key, value); } } if (pair == null) { throw new TranslateException("Missing key or value in input."); } return new ReRankingInput(pair); } private static StringPair parseStringPair(JsonObject json) throws TranslateException { JsonElement text = json.get("text"); JsonElement textPair = json.get("text_pair"); if (text != null && textPair != null) { return new StringPair(text.getAsString(), textPair.getAsString()); } JsonElement key = json.get("key"); JsonElement value = json.get("value"); if (key != null && value != null) { return new StringPair(key.getAsString(), value.getAsString()); } throw new TranslateException("Missing text or text_pair in json."); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/translator/NamedEntity.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.modality.nlp.translator; import ai.djl.util.JsonUtils; /** A class that represents a {@code NamedEntity} object. */ public class NamedEntity { private String entity; private float score; private int index; private String word; private int start; private int end; /** * Constructs a new instance of {@code NamedEntity}. * * @param entity the class of the entity * @param score the score of the entity * @param index the position of the entity in the original sentence * @param word the token of the entity * @param start the start index of the word in the sentence * @param end the end index of the word in the sentence */ public NamedEntity(String entity, float score, int index, String word, int start, int end) { this.entity = entity; this.score = score; this.index = index; this.word = word; this.start = start; this.end = end; } /** * Returns the class of the entity. * * @return the class of the entity */ public String getEntity() { return entity; } /** * Returns the score of the entity. * * @return the score of the entity */ public float getScore() { return score; } /** * Returns the position of the entity in the original sentence. * * @return the position of the entity in the original sentence */ public int getIndex() { return index; } /** * Returns the token of the entity. * * @return the token of the entity */ public String getWord() { return word; } /** * Returns the start index of the word in the sentence. * * @return the start index of the word in the sentence */ public int getStart() { return start; } /** * Returns the end index of the word in the sentence. * * @return the end index of the word in the sentence */ public int getEnd() { return end; } /** {@inheritDoc} */ @Override public String toString() { return JsonUtils.toJson(this); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/translator/QATranslator.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.modality.nlp.translator; import ai.djl.modality.nlp.qa.QAInput; import ai.djl.translate.ArgumentsUtil; import ai.djl.translate.Batchifier; import ai.djl.translate.Translator; import java.util.Locale; import java.util.Map; /** An abstract class to define the question answering translator. */ public abstract class QATranslator implements Translator<QAInput, String> { protected Batchifier batchifier; protected String tokenizerName; protected String vocab; protected Locale locale; protected boolean toLowerCase; protected boolean includeTokenTypes; protected boolean padding; protected boolean truncation; protected int maxLength; protected int maxLabels; protected QATranslator(BaseBuilder<?> builder) { this.batchifier = builder.batchifier; this.tokenizerName = builder.tokenizerName; this.vocab = builder.vocab; this.locale = builder.locale; this.toLowerCase = builder.toLowerCase; this.includeTokenTypes = builder.includeTokenTypes; this.padding = builder.padding; this.truncation = builder.truncation; this.maxLength = builder.maxLength; this.maxLabels = builder.maxLabels; } /** {@inheritDoc} */ @Override public Batchifier getBatchifier() { return batchifier; } /** The builder for question answering translator. */ @SuppressWarnings("rawtypes") public abstract static class BaseBuilder<T extends BaseBuilder> { Batchifier batchifier = Batchifier.STACK; String tokenizerName; String vocab = "vocab.txt"; Locale locale = Locale.ROOT; boolean toLowerCase; boolean includeTokenTypes; boolean padding; boolean truncation; int maxLength = 128; int maxLabels; /** * Sets the {@link Batchifier} for the {@link Translator}. * * @param batchifier the {@link Batchifier} to be set * @return this builder */ public T optBatchifier(Batchifier batchifier) { this.batchifier = batchifier; return self(); } /** * Sets the name of the tokenizer for the {@link Translator}. * * @param tokenizer the name of the tokenizer * @return this builder */ public T optTokenizer(String tokenizer) { this.tokenizerName = tokenizer; return self(); } /** * Sets the name of the vocabulary file for the {@link Translator}. * * @param vocab name of the vocabulary file * @return this builder */ public T optVocab(String vocab) { if (vocab != null) { this.vocab = vocab; } return self(); } /** * Sets the name of the locale for the {@link Translator}. * * @param locale the name of the locale * @return this builder */ public T optLocale(String locale) { if (locale != null) { this.locale = Locale.forLanguageTag(locale); } return self(); } /** * Sets the if convert text to lower case for the {@link Translator}. * * @param toLowerCase if convert text to lower case * @return this builder */ public T optToLowerCase(boolean toLowerCase) { this.toLowerCase = toLowerCase; return self(); } /** * Sets the if include token types for the {@link Translator}. * * @param includeTokenTypes if include token types * @return this builder */ public T optIncludeTokenTypes(boolean includeTokenTypes) { this.includeTokenTypes = includeTokenTypes; return self(); } /** * Sets the if pad the tokens for the {@link Translator}. * * @param padding if pad the tokens * @return this builder */ public T optPadding(boolean padding) { this.padding = padding; return self(); } /** * Sets the if truncate the tokens for the {@link Translator}. * * @param truncation if truncate the tokens * @return this builder */ public T optTruncation(boolean truncation) { this.truncation = truncation; return self(); } /** * Sets the max number of tokens for the {@link Translator}. * * @param maxLength the max number of tokens * @return this builder */ public T optMaxLength(int maxLength) { this.maxLength = maxLength; return self(); } /** * Sets the max number of labels for the {@link Translator}. * * @param maxLabels the max number of labels * @return this builder */ public T optMaxLabels(int maxLabels) { this.maxLabels = maxLabels; return self(); } /** * Configures the builder with the model arguments. * * @param arguments the model arguments */ public void configure(Map<String, ?> arguments) { optTokenizer(ArgumentsUtil.stringValue(arguments, "tokenizer")); optVocab(ArgumentsUtil.stringValue(arguments, "vocab")); optLocale(ArgumentsUtil.stringValue(arguments, "locale")); optToLowerCase(ArgumentsUtil.booleanValue(arguments, "toLowerCase")); optIncludeTokenTypes(ArgumentsUtil.booleanValue(arguments, "includeTokenTypes")); optPadding(ArgumentsUtil.booleanValue(arguments, "padding")); optTruncation(ArgumentsUtil.booleanValue(arguments, "truncation")); optMaxLength(ArgumentsUtil.intValue(arguments, "maxLength", 128)); optMaxLabels(ArgumentsUtil.intValue(arguments, "maxLabels")); } protected abstract T self(); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/translator/QaServingTranslator.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.modality.nlp.translator; import ai.djl.modality.Input; import ai.djl.modality.Output; import ai.djl.modality.nlp.qa.QAInput; import ai.djl.ndarray.BytesSupplier; import ai.djl.ndarray.NDList; import ai.djl.translate.Batchifier; import ai.djl.translate.NoBatchifyTranslator; import ai.djl.translate.TranslateException; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; import ai.djl.util.JsonUtils; import ai.djl.util.PairList; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * A {@link Translator} that can handle generic question answering {@link Input} and {@link Output}. */ public class QaServingTranslator implements NoBatchifyTranslator<Input, Output> { private static final Type LIST_TYPE = new TypeToken<List<QAInput>>() {}.getType(); private Translator<QAInput, String> translator; /** * Constructs a {@code QaServingTranslator} instance. * * @param translator a {@code Translator} processes question answering input */ public QaServingTranslator(Translator<QAInput, String> translator) { this.translator = translator; } /** {@inheritDoc} */ @Override public void prepare(TranslatorContext ctx) throws Exception { translator.prepare(ctx); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, Input input) throws Exception { PairList<String, BytesSupplier> content = input.getContent(); if (content.isEmpty()) { throw new TranslateException("Input data is empty."); } String contentType = input.getProperty("Content-Type", null); if (contentType != null) { int pos = contentType.indexOf(';'); if (pos > 0) { contentType = contentType.substring(0, pos); } } QAInput qa; if ("application/json".equals(contentType)) { String json = input.getData().getAsString(); try { JsonElement element = JsonUtils.GSON.fromJson(json, JsonElement.class); if (element.isJsonArray()) { ctx.setAttachment("batch", Boolean.TRUE); List<QAInput> inputs = JsonUtils.GSON.fromJson(json, LIST_TYPE); return translator.batchProcessInput(ctx, inputs); } qa = JsonUtils.GSON.fromJson(json, QAInput.class); if (qa.getQuestion() == null || qa.getParagraph() == null) { throw new TranslateException("Missing question or context in json."); } } catch (JsonParseException e) { throw new TranslateException("Input is not a valid json.", e); } } else { String question = input.getAsString("question"); String context = input.getAsString("context"); if (context == null) { context = input.getAsString("paragraph"); } if (question == null || context == null) { throw new TranslateException("Missing question or context in input."); } qa = new QAInput(question, context); } NDList ret = translator.processInput(ctx, qa); Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { NDList[] batch = {ret}; return batchifier.batchify(batch); } return ret; } /** {@inheritDoc} */ @Override public Output processOutput(TranslatorContext ctx, NDList list) throws Exception { Output output = new Output(); output.addProperty("Content-Type", "application/json"); if (ctx.getAttachment("batch") != null) { List<String> answers = translator.batchProcessOutput(ctx, list); List<Map<String, String>> ret = new ArrayList<>(); for (String answer : answers) { ret.add(Collections.singletonMap("answer", answer)); } output.add(BytesSupplier.wrapAsJson(ret)); } else { Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { list = batchifier.unbatchify(list)[0]; } String answer = translator.processOutput(ctx, list); Map<String, String> ret = Collections.singletonMap("answer", answer); output.add(BytesSupplier.wrapAsJson(ret)); } return output; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/translator/SimpleText2TextTranslator.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.modality.nlp.translator; import ai.djl.Model; import ai.djl.modality.nlp.Decoder; import ai.djl.modality.nlp.Encoder; import ai.djl.modality.nlp.EncoderDecoder; import ai.djl.modality.nlp.embedding.TrainableTextEmbedding; import ai.djl.modality.nlp.preprocess.LowerCaseConvertor; import ai.djl.modality.nlp.preprocess.PunctuationSeparator; import ai.djl.modality.nlp.preprocess.SimpleTokenizer; import ai.djl.modality.nlp.preprocess.TextProcessor; import ai.djl.modality.nlp.preprocess.TextTruncator; 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.BlockList; import ai.djl.nn.SequentialBlock; import ai.djl.translate.Batchifier; import ai.djl.translate.PaddingStackBatchifier; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; /** * A {@link Translator} that performs pre-process and post-processing for a sequence-to-sequence * text model. */ public class SimpleText2TextTranslator implements Translator<String, String> { private SimpleTokenizer tokenizer = new SimpleTokenizer(); private TrainableTextEmbedding sourceEmbedding; private TrainableTextEmbedding targetEmbedding; private List<TextProcessor> textProcessors = Arrays.asList( new SimpleTokenizer(), new LowerCaseConvertor(Locale.ENGLISH), new PunctuationSeparator(), new TextTruncator(10)); /** {@inheritDoc} */ @Override public String processOutput(TranslatorContext ctx, NDList list) { if (list.singletonOrThrow().getShape().dimension() > 2) { throw new IllegalArgumentException( "Input must correspond to one sentence. Shape must be of 2 or less dimensions"); } if (targetEmbedding == null) { Model model = ctx.getModel(); EncoderDecoder encoderDecoder = (EncoderDecoder) model.getBlock(); BlockList children = encoderDecoder.getChildren(); Decoder decoder = (Decoder) children.get(1).getValue(); SequentialBlock sequentialBlock = (SequentialBlock) decoder.getChildren().get(0).getValue(); targetEmbedding = (TrainableTextEmbedding) sequentialBlock.getChildren().get(0).getValue(); } List<String> output = new ArrayList<>(); for (String token : targetEmbedding.unembedText( list.singletonOrThrow().toType(DataType.INT32, false).flatten())) { if ("<eos>".equals(token)) { break; } output.add(token); } return tokenizer.buildSentence(output); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, String input) { Model model = ctx.getModel(); if (sourceEmbedding == null) { EncoderDecoder encoderDecoder = (EncoderDecoder) model.getBlock(); BlockList children = encoderDecoder.getChildren(); Encoder encoder = (Encoder) children.get(0).getValue(); SequentialBlock sequentialBlock = (SequentialBlock) encoder.getChildren().get(0).getValue(); sourceEmbedding = (TrainableTextEmbedding) sequentialBlock.getChildren().get(0).getValue(); } List<String> tokens = Collections.singletonList(input); for (TextProcessor textProcessor : textProcessors) { tokens = textProcessor.preprocess(tokens); } return new NDList( model.getNDManager().create(sourceEmbedding.preprocessTextToEmbed(tokens)), model.getNDManager() .create(sourceEmbedding.preprocessTextToEmbed(Arrays.asList("<bos>")))); } /** {@inheritDoc} */ @Override public Batchifier getBatchifier() { return PaddingStackBatchifier.builder() .optIncludeValidLengths(false) .addPad(0, 0, this::get, 10) .build(); } private NDArray get(NDManager manager) { return manager.ones(new Shape(1)) .mul(sourceEmbedding.preprocessTextToEmbed(Collections.singletonList("<pad>"))[0]); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/translator/SparseRetrievalServingTranslator.java
/* * Copyright 2025 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.modality.nlp.translator; import ai.djl.modality.Input; import ai.djl.modality.Output; import ai.djl.modality.nlp.EmbeddingOutput; import ai.djl.modality.nlp.TextPrompt; import ai.djl.ndarray.BytesSupplier; import ai.djl.ndarray.NDList; import ai.djl.translate.Batchifier; import ai.djl.translate.TranslateException; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; import java.util.ArrayList; import java.util.List; /** A {@link Translator} that can handle generic text embedding {@link Input} and {@link Output}. */ public class SparseRetrievalServingTranslator implements Translator<Input, Output> { private Translator<String, EmbeddingOutput> translator; /** * Constructs a {@code SparseRetrievalServingTranslator} instance. * * @param translator a {@code Translator} processes text embedding input */ public SparseRetrievalServingTranslator(Translator<String, EmbeddingOutput> translator) { this.translator = translator; } /** {@inheritDoc} */ @Override public void prepare(TranslatorContext ctx) throws Exception { translator.prepare(ctx); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, Input input) throws Exception { if (input.getContent().isEmpty()) { throw new TranslateException("Input data is empty."); } TextPrompt prompt = TextPrompt.parseInput(input); if (prompt.isBatch()) { ctx.setAttachment("batch", Boolean.TRUE); return translator.batchProcessInput(ctx, prompt.getBatch()); } NDList ret = translator.processInput(ctx, prompt.getText()); Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { NDList[] batch = {ret}; return batchifier.batchify(batch); } return ret; } /** {@inheritDoc} */ @Override @SuppressWarnings("PMD.SignatureDeclareThrowsException") public NDList batchProcessInput(TranslatorContext ctx, List<Input> inputs) throws Exception { int[] mapping = new int[inputs.size()]; List<String> prompts = new ArrayList<>(mapping.length); for (int i = 0; i < mapping.length; ++i) { TextPrompt prompt = TextPrompt.parseInput(inputs.get(i)); if (prompt.isBatch()) { List<String> batch = prompt.getBatch(); mapping[i] = batch.size(); prompts.addAll(batch); } else { mapping[i] = -1; prompts.add(prompt.getText()); } } ctx.setAttachment("mapping", mapping); return translator.batchProcessInput(ctx, prompts); } /** {@inheritDoc} */ @Override public Output processOutput(TranslatorContext ctx, NDList list) throws Exception { Output output = new Output(); output.addProperty("Content-Type", "application/json"); if (ctx.getAttachment("batch") != null) { output.add(BytesSupplier.wrapAsJson(translator.batchProcessOutput(ctx, list))); } else { Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { list = batchifier.unbatchify(list)[0]; } output.add(BytesSupplier.wrapAsJson(translator.processOutput(ctx, list))); } return output; } /** {@inheritDoc} */ @Override @SuppressWarnings("PMD.SignatureDeclareThrowsException") public List<Output> batchProcessOutput(TranslatorContext ctx, NDList list) throws Exception { List<EmbeddingOutput> outputs = translator.batchProcessOutput(ctx, list); int[] mapping = (int[]) ctx.getAttachment("mapping"); List<Output> ret = new ArrayList<>(mapping.length); int index = 0; for (int size : mapping) { Output output = new Output(); output.addProperty("Content-Type", "application/json"); if (size == -1) { // non-batching output.add(BytesSupplier.wrapAsJson(outputs.get(index++))); } else { // client side batching List<EmbeddingOutput> embeddings = new ArrayList<>(size); for (int j = 0; j < size; ++j) { embeddings.add(outputs.get(index++)); } output.add(BytesSupplier.wrapAsJson(embeddings)); } ret.add(output); } return ret; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/translator/TextClassificationServingTranslator.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.modality.nlp.translator; import ai.djl.modality.Classifications; import ai.djl.modality.Input; import ai.djl.modality.Output; import ai.djl.modality.nlp.TextPrompt; import ai.djl.ndarray.BytesSupplier; import ai.djl.ndarray.NDList; import ai.djl.translate.Batchifier; import ai.djl.translate.NoBatchifyTranslator; import ai.djl.translate.TranslateException; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; /** * A {@link Translator} that can handle generic text classification {@link Input} and {@link * Output}. */ public class TextClassificationServingTranslator implements NoBatchifyTranslator<Input, Output> { private Translator<String, Classifications> translator; /** * Constructs a {@code TextClassificationServingTranslator} instance. * * @param translator a {@code Translator} processes text classification input */ public TextClassificationServingTranslator(Translator<String, Classifications> translator) { this.translator = translator; } /** {@inheritDoc} */ @Override public void prepare(TranslatorContext ctx) throws Exception { translator.prepare(ctx); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, Input input) throws Exception { if (input.getContent().isEmpty()) { throw new TranslateException("Input data is empty."); } TextPrompt prompt = TextPrompt.parseInput(input); if (prompt.isBatch()) { ctx.setAttachment("batch", Boolean.TRUE); return translator.batchProcessInput(ctx, prompt.getBatch()); } NDList ret = translator.processInput(ctx, prompt.getText()); Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { NDList[] batch = {ret}; return batchifier.batchify(batch); } return ret; } /** {@inheritDoc} */ @Override public Output processOutput(TranslatorContext ctx, NDList list) throws Exception { Output output = new Output(); output.addProperty("Content-Type", "application/json"); if (ctx.getAttachment("batch") != null) { output.add(BytesSupplier.wrapAsJson(translator.batchProcessOutput(ctx, list))); } else { Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { list = batchifier.unbatchify(list)[0]; } output.add(translator.processOutput(ctx, list)); } return output; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/translator/TextEmbeddingServingTranslator.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.modality.nlp.translator; import ai.djl.modality.Input; import ai.djl.modality.Output; import ai.djl.modality.nlp.TextPrompt; import ai.djl.ndarray.BytesSupplier; import ai.djl.ndarray.NDList; import ai.djl.translate.Batchifier; import ai.djl.translate.TranslateException; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; import java.util.ArrayList; import java.util.List; /** A {@link Translator} that can handle generic text embedding {@link Input} and {@link Output}. */ public class TextEmbeddingServingTranslator implements Translator<Input, Output> { private Translator<String, float[]> translator; /** * Constructs a {@code TextEmbeddingServingTranslator} instance. * * @param translator a {@code Translator} processes text embedding input */ public TextEmbeddingServingTranslator(Translator<String, float[]> translator) { this.translator = translator; } /** {@inheritDoc} */ @Override public void prepare(TranslatorContext ctx) throws Exception { translator.prepare(ctx); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, Input input) throws Exception { if (input.getContent().isEmpty()) { throw new TranslateException("Input data is empty."); } TextPrompt prompt = TextPrompt.parseInput(input); if (prompt.isBatch()) { ctx.setAttachment("batch", Boolean.TRUE); return translator.batchProcessInput(ctx, prompt.getBatch()); } NDList ret = translator.processInput(ctx, prompt.getText()); Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { NDList[] batch = {ret}; return batchifier.batchify(batch); } return ret; } /** {@inheritDoc} */ @Override @SuppressWarnings("PMD.SignatureDeclareThrowsException") public NDList batchProcessInput(TranslatorContext ctx, List<Input> inputs) throws Exception { int[] mapping = new int[inputs.size()]; List<String> prompts = new ArrayList<>(mapping.length); for (int i = 0; i < mapping.length; ++i) { TextPrompt prompt = TextPrompt.parseInput(inputs.get(i)); if (prompt.isBatch()) { List<String> batch = prompt.getBatch(); mapping[i] = batch.size(); prompts.addAll(batch); } else { mapping[i] = -1; prompts.add(prompt.getText()); } } ctx.setAttachment("mapping", mapping); return translator.batchProcessInput(ctx, prompts); } /** {@inheritDoc} */ @Override public Output processOutput(TranslatorContext ctx, NDList list) throws Exception { Output output = new Output(); output.addProperty("Content-Type", "application/json"); if (ctx.getAttachment("batch") != null) { output.add(BytesSupplier.wrapAsJson(translator.batchProcessOutput(ctx, list))); } else { Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { list = batchifier.unbatchify(list)[0]; } output.add(BytesSupplier.wrapAsJson(translator.processOutput(ctx, list))); } return output; } /** {@inheritDoc} */ @Override @SuppressWarnings("PMD.SignatureDeclareThrowsException") public List<Output> batchProcessOutput(TranslatorContext ctx, NDList list) throws Exception { List<float[]> outputs = translator.batchProcessOutput(ctx, list); int[] mapping = (int[]) ctx.getAttachment("mapping"); List<Output> ret = new ArrayList<>(mapping.length); int index = 0; for (int size : mapping) { Output output = new Output(); output.addProperty("Content-Type", "application/json"); if (size == -1) { // non-batching output.add(BytesSupplier.wrapAsJson(outputs.get(index++))); } else { // client side batching float[][] embeddings = new float[size][]; for (int j = 0; j < size; ++j) { embeddings[j] = outputs.get(index++); } output.add(BytesSupplier.wrapAsJson(embeddings)); } ret.add(output); } return ret; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/translator/TokenClassificationServingTranslator.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.modality.nlp.translator; import ai.djl.modality.Input; import ai.djl.modality.Output; import ai.djl.modality.nlp.TextPrompt; import ai.djl.ndarray.BytesSupplier; import ai.djl.ndarray.NDList; import ai.djl.translate.Batchifier; import ai.djl.translate.NoBatchifyTranslator; import ai.djl.translate.TranslateException; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; /** * A {@link Translator} that can handle generic token classification {@link Input} and {@link * Output}. */ public class TokenClassificationServingTranslator implements NoBatchifyTranslator<Input, Output> { private Translator<String, NamedEntity[]> translator; /** * Constructs a {@code TokenClassificationServingTranslator} instance. * * @param translator a {@code Translator} processes token classification input */ public TokenClassificationServingTranslator(Translator<String, NamedEntity[]> translator) { this.translator = translator; } /** {@inheritDoc} */ @Override public void prepare(TranslatorContext ctx) throws Exception { translator.prepare(ctx); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, Input input) throws Exception { if (input.getContent().isEmpty()) { throw new TranslateException("Input data is empty."); } TextPrompt prompt = TextPrompt.parseInput(input); if (prompt.isBatch()) { ctx.setAttachment("batch", Boolean.TRUE); return translator.batchProcessInput(ctx, prompt.getBatch()); } NDList ret = translator.processInput(ctx, prompt.getText()); Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { NDList[] batch = {ret}; return batchifier.batchify(batch); } return ret; } /** {@inheritDoc} */ @Override public Output processOutput(TranslatorContext ctx, NDList list) throws Exception { Output output = new Output(); output.addProperty("Content-Type", "application/json"); if (ctx.getAttachment("batch") != null) { output.add(BytesSupplier.wrapAsJson(translator.batchProcessOutput(ctx, list))); } else { Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { list = batchifier.unbatchify(list)[0]; } output.add(BytesSupplier.wrapAsJson(translator.processOutput(ctx, list))); } return output; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/translator/ZeroShotClassificationInput.java
/* * Copyright 2025 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.modality.nlp.translator; import ai.djl.modality.Input; import ai.djl.translate.TranslateException; import ai.djl.util.JsonUtils; import com.google.gson.JsonParseException; import com.google.gson.annotations.SerializedName; /** A class that represents a {@code ZeroShotClassificationInput} object. */ public class ZeroShotClassificationInput { private String text; @SerializedName("candidate_labels") private String[] candidates; @SerializedName("multi_label") private boolean multiLabel; @SerializedName("hypothesis_template") private String hypothesisTemplate; /** * Constructs a new {@code ZeroShotClassificationInput} instance. * * @param text the text to classify * @param candidates the candidate labels */ public ZeroShotClassificationInput(String text, String[] candidates) { this(text, candidates, false); } /** * Constructs a new {@code ZeroShotClassificationInput} instance. * * @param text the text to classify * @param candidates the candidate labels * @param multiLabel true to classify multiple labels */ public ZeroShotClassificationInput(String text, String[] candidates, boolean multiLabel) { this(text, candidates, multiLabel, null); } /** * Constructs a new {@code ZeroShotClassificationInput} instance. * * @param text the text to classify * @param candidates the candidate labels * @param multiLabel true to classify multiple labels * @param hypothesisTemplate the custom template */ public ZeroShotClassificationInput( String text, String[] candidates, boolean multiLabel, String hypothesisTemplate) { this.text = text; this.candidates = candidates; this.multiLabel = multiLabel; this.hypothesisTemplate = hypothesisTemplate; } /** * Returns the {@code ZeroShotClassificationInput} from the {@link Input}. * * @param input the input object * @return the {@code ZeroShotClassificationInput} from the {@link Input} * @throws TranslateException if the input is invalid */ public static ZeroShotClassificationInput parseInput(Input input) throws TranslateException { String text = input.getData().getAsString(); try { return JsonUtils.GSON.fromJson(text, ZeroShotClassificationInput.class); } catch (JsonParseException e) { throw new TranslateException("Input is not a valid json.", e); } } /** * Returns the text. * * @return the text to be classified */ public String getText() { return text; } /** * Returns the candidate labels. * * @return the candidate labels */ public String[] getCandidates() { return candidates; } /** * Returns {@code true} if to classify multiple labels. * * @return {@code true} if to classify multiple labels */ public boolean isMultiLabel() { return multiLabel; } /** * Returns the custom template. * * @return the custom template */ public String getHypothesisTemplate() { return hypothesisTemplate == null ? "This example is {}." : hypothesisTemplate; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/translator/ZeroShotClassificationOutput.java
/* * Copyright 2025 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.modality.nlp.translator; /** A class that represents a {@code ZeroShotClassificationOutput} object. */ public class ZeroShotClassificationOutput { private String sequence; private String[] labels; private double[] scores; /** * Constructs a new {@code ZeroShotClassificationOutput} instance. * * @param sequence the input text * @param labels the labels * @param scores the scores of the labels */ public ZeroShotClassificationOutput(String sequence, String[] labels, double[] scores) { this.sequence = sequence; this.labels = labels; this.scores = scores; } /** * Returns the input text. * * @return the input text */ public String getSequence() { return sequence; } /** * Returns the labels in sorted order. * * @return the labels in sorted order */ public String[] getLabels() { return labels; } /** * Returns the scores of the labels. * * @return the scores of the labels */ public double[] getScores() { return scores; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/translator/ZeroShotClassificationServingTranslator.java
/* * Copyright 2025 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.modality.nlp.translator; import ai.djl.modality.Input; import ai.djl.modality.Output; import ai.djl.ndarray.BytesSupplier; import ai.djl.ndarray.NDList; import ai.djl.translate.Batchifier; import ai.djl.translate.NoBatchifyTranslator; import ai.djl.translate.TranslateException; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; /** * A {@link Translator} that can handle generic zero-shot-classification {@link Input} and {@link * Output}. */ public class ZeroShotClassificationServingTranslator implements NoBatchifyTranslator<Input, Output> { private Translator<ZeroShotClassificationInput, ZeroShotClassificationOutput> translator; /** * Constructs a {@code ZeroShotClassificationServingTranslator} instance. * * @param translator a {@code Translator} processes zero-shot-classification input */ public ZeroShotClassificationServingTranslator( Translator<ZeroShotClassificationInput, ZeroShotClassificationOutput> translator) { this.translator = translator; } /** {@inheritDoc} */ @Override public void prepare(TranslatorContext ctx) throws Exception { translator.prepare(ctx); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, Input input) throws Exception { if (input.getContent().isEmpty()) { throw new TranslateException("Input data is empty."); } ZeroShotClassificationInput prompt = ZeroShotClassificationInput.parseInput(input); NDList ret = translator.processInput(ctx, prompt); Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { NDList[] batch = {ret}; return batchifier.batchify(batch); } return ret; } /** {@inheritDoc} */ @Override public Output processOutput(TranslatorContext ctx, NDList list) throws Exception { Output output = new Output(); output.addProperty("Content-Type", "application/json"); Batchifier batchifier = translator.getBatchifier(); if (batchifier != null) { list = batchifier.unbatchify(list)[0]; } output.add(BytesSupplier.wrapAsJson(translator.processOutput(ctx, list))); return output; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp
java-sources/ai/djl/api/0.34.0/ai/djl/modality/nlp/translator/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 utility classes for each of the predefined translator. */ package ai.djl.modality.nlp.translator;
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality
java-sources/ai/djl/api/0.34.0/ai/djl/modality/rl/ActionSpace.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.modality.rl; import ai.djl.ndarray.NDList; import ai.djl.util.RandomUtils; import java.util.ArrayList; /** Contains the available actions that can be taken in an {@link ai.djl.modality.rl.env.RlEnv}. */ public class ActionSpace extends ArrayList<NDList> { private static final long serialVersionUID = 8683452581122892189L; /** * Returns a random action. * * @return a random action */ public NDList randomAction() { return get(RandomUtils.nextInt(size())); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality
java-sources/ai/djl/api/0.34.0/ai/djl/modality/rl/LruReplayBuffer.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.modality.rl; import ai.djl.modality.rl.env.RlEnv.Step; import ai.djl.util.RandomUtils; /** * A simple {@link ReplayBuffer} that randomly selects across the whole buffer, but always removes * the oldest items in the buffer once it is full. */ public class LruReplayBuffer implements ReplayBuffer { private int batchSize; private Step[] steps; private int firstStepIndex; private int stepsActualSize; /** * Constructs a {@link LruReplayBuffer}. * * @param batchSize the number of steps to train on per batch * @param bufferSize the number of steps to hold in the buffer */ public LruReplayBuffer(int batchSize, int bufferSize) { this.batchSize = batchSize; steps = new Step[bufferSize]; firstStepIndex = 0; stepsActualSize = 0; } /** {@inheritDoc} */ @Override @SuppressWarnings("PMD.AvoidArrayLoops") public Step[] getBatch() { Step[] batch = new Step[batchSize]; for (int i = 0; i < batchSize; i++) { int baseIndex = RandomUtils.nextInt(stepsActualSize); int index = Math.floorMod(firstStepIndex + baseIndex, steps.length); batch[i] = steps[index]; } return batch; } /** {@inheritDoc} */ @Override public void addStep(Step step) { if (stepsActualSize == steps.length) { int stepToReplace = Math.floorMod(firstStepIndex, steps.length); steps[stepToReplace].close(); steps[stepToReplace] = step; firstStepIndex = Math.floorMod(firstStepIndex + 1, steps.length); } else { steps[stepsActualSize] = step; stepsActualSize++; } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality
java-sources/ai/djl/api/0.34.0/ai/djl/modality/rl/ReplayBuffer.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.modality.rl; import ai.djl.modality.rl.env.RlEnv.Step; /** * Records {@link Step}s so that they can be trained on. * * <p>Using a replay buffer ensures that a variety of states are trained on for every training batch * making the training more stable. */ public interface ReplayBuffer { /** * Returns a batch of steps from this buffer. * * @return a batch of steps from this buffer */ Step[] getBatch(); /** * Adds a new step to the buffer. * * @param step the step to add */ void addStep(Step step); }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality
java-sources/ai/djl/api/0.34.0/ai/djl/modality/rl/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 utility classes for reinforcement learning. */ package ai.djl.modality.rl;
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/rl
java-sources/ai/djl/api/0.34.0/ai/djl/modality/rl/agent/EpsilonGreedy.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.modality.rl.agent; import ai.djl.modality.rl.env.RlEnv; import ai.djl.modality.rl.env.RlEnv.Step; import ai.djl.ndarray.NDList; import ai.djl.training.tracker.Tracker; import ai.djl.util.RandomUtils; /** * The {@link EpsilonGreedy} is a simple exploration/excitation agent. * * <p>It helps other agents explore their environments during training by sometimes picking random * actions. * * <p>If a model based agent is used, it will only explore paths through the environment that have * already been seen. While this is sometimes good, it is also important to sometimes explore new * paths as well. This agent exhibits a tradeoff that takes random paths a fixed percentage of the * time during training. */ public class EpsilonGreedy implements RlAgent { private RlAgent baseAgent; private Tracker exploreRate; private int counter; /** * Constructs an {@link EpsilonGreedy}. * * @param baseAgent the (presumably model-based) agent to use for exploitation and to train * @param exploreRate the probability of taking a random action */ public EpsilonGreedy(RlAgent baseAgent, Tracker exploreRate) { this.baseAgent = baseAgent; this.exploreRate = exploreRate; } /** {@inheritDoc} */ @Override public NDList chooseAction(RlEnv env, boolean training) { if (training && RandomUtils.random() < exploreRate.getNewValue(counter++)) { return env.getActionSpace().randomAction(); } return baseAgent.chooseAction(env, training); } /** {@inheritDoc} */ @Override public void trainBatch(Step[] batchSteps) { baseAgent.trainBatch(batchSteps); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/rl
java-sources/ai/djl/api/0.34.0/ai/djl/modality/rl/agent/QAgent.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.modality.rl.agent; import ai.djl.modality.rl.ActionSpace; import ai.djl.modality.rl.env.RlEnv; import ai.djl.modality.rl.env.RlEnv.Step; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.training.GradientCollector; import ai.djl.training.Trainer; import ai.djl.training.listener.TrainingListener.BatchData; import ai.djl.translate.Batchifier; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Stream; /** * An {@link RlAgent} that implements Q or Deep-Q Learning. * * <p>Deep-Q Learning estimates the total reward that will be given until the environment ends in a * particular state after taking a particular action. Then, it is trained by ensuring that the * prediction before taking the action match what would be predicted after taking the action. More * information can be found in the <a * href="https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf">paper</a>. * * <p>It is one of the earliest successful techniques for reinforcement learning with Deep learning. * It is also a good introduction to the field. However, many better techniques are commonly used * now. */ public class QAgent implements RlAgent { private Trainer trainer; private float rewardDiscount; private Batchifier batchifier; /** * Constructs a {@link QAgent}. * * <p>It uses the {@link ai.djl.translate.StackBatchifier} as the default batchifier. * * @param trainer the trainer for the model to learn * @param rewardDiscount the reward discount to apply to rewards from future states */ public QAgent(Trainer trainer, float rewardDiscount) { this(trainer, rewardDiscount, Batchifier.STACK); } /** * Constructs a {@link QAgent} with a custom {@link Batchifier}. * * @param trainer the trainer for the model to learn * @param rewardDiscount the reward discount to apply to rewards from future states * @param batchifier the batchifier to join inputs with */ public QAgent(Trainer trainer, float rewardDiscount, Batchifier batchifier) { this.trainer = trainer; this.rewardDiscount = rewardDiscount; this.batchifier = batchifier; } /** {@inheritDoc} */ @Override public NDList chooseAction(RlEnv env, boolean training) { ActionSpace actionSpace = env.getActionSpace(); NDList[] inputs = buildInputs(env.getObservation(), actionSpace); NDArray actionScores = trainer.evaluate(batchifier.batchify(inputs)).singletonOrThrow().squeeze(-1); int bestAction = Math.toIntExact(actionScores.argMax().getLong()); return actionSpace.get(bestAction); } /** {@inheritDoc} */ @Override public void trainBatch(Step[] batchSteps) { BatchData batchData = new BatchData(null, new ConcurrentHashMap<>(), new ConcurrentHashMap<>()); for (Step step : batchSteps) { NDList[] preInput = buildInputs( step.getPreObservation(), Collections.singletonList(step.getAction())); NDList[] postInputs = buildInputs(step.getPostObservation(), step.getPostActionSpace()); NDList[] allInputs = Stream.concat(Arrays.stream(preInput), Arrays.stream(postInputs)) .toArray(NDList[]::new); try (GradientCollector collector = trainer.newGradientCollector()) { NDArray results = trainer.forward(batchifier.batchify(allInputs)) .singletonOrThrow() .squeeze(-1); NDList preQ = new NDList(results.get(0)); NDList postQ; if (step.isDone()) { postQ = new NDList(step.getReward()); } else { NDArray bestAction = results.get("1:").max(); postQ = new NDList(bestAction.mul(rewardDiscount).add(step.getReward())); } NDArray lossValue = trainer.getLoss().evaluate(postQ, preQ); collector.backward(lossValue); batchData.getLabels().put(postQ.get(0).getDevice(), postQ); batchData.getPredictions().put(preQ.get(0).getDevice(), preQ); } } trainer.notifyListeners(listener -> listener.onTrainingBatch(trainer, batchData)); } private NDList[] buildInputs(NDList observation, List<NDList> actions) { NDList[] inputs = new NDList[actions.size()]; for (int i = 0; i < actions.size(); i++) { NDList nextData = new NDList().addAll(observation).addAll(actions.get(i)); inputs[i] = nextData; } return inputs; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/rl
java-sources/ai/djl/api/0.34.0/ai/djl/modality/rl/agent/RlAgent.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.modality.rl.agent; import ai.djl.modality.rl.env.RlEnv; import ai.djl.modality.rl.env.RlEnv.Step; import ai.djl.ndarray.NDList; /** * An {@link RlAgent} is the model or technique to decide the actions to take in an {@link RlEnv}. */ public interface RlAgent { /** * Chooses the next action to take within the {@link RlEnv}. * * @param env the current environment * @param training true if the agent is currently traning * @return the action to take */ NDList chooseAction(RlEnv env, boolean training); /** * Trains this {@link RlAgent} on a batch of {@link Step}s. * * @param batchSteps the steps to train on */ void trainBatch(Step[] batchSteps); }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/rl
java-sources/ai/djl/api/0.34.0/ai/djl/modality/rl/agent/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 agents to learn using reinforcement learning. * * <p>It has the main interface {@link ai.djl.modality.rl.agent.RlAgent} and various agents * implementing it. */ package ai.djl.modality.rl.agent;
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/rl
java-sources/ai/djl/api/0.34.0/ai/djl/modality/rl/env/RlEnv.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.modality.rl.env; import ai.djl.modality.rl.ActionSpace; import ai.djl.modality.rl.agent.RlAgent; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; /** An environment to use for reinforcement learning. */ public interface RlEnv extends AutoCloseable { /** Resets the environment to it's default state. */ void reset(); /** * Returns the observation detailing the current state of the environment. * * @return the observation detailing the current state of the environment */ NDList getObservation(); /** * Returns the current actions that can be taken in the environment. * * @return the current actions that can be taken in the environment */ ActionSpace getActionSpace(); /** * Takes a step by performing an action in this environment. * * @param action the action to perform * @param training true if the step is during training * @return the {@link Step} with the result of the action */ Step step(NDList action, boolean training); /** * Runs the environment from reset until done. * * @param agent the agent to choose the actions with * @param training true to run while training. When training, the steps will be recorded * @return the total reward */ default float runEnvironment(RlAgent agent, boolean training) { float totalReward = 0; reset(); while (true) { NDList action = agent.chooseAction(this, training); Step step = step(action, training); totalReward += step.getReward().getFloat(); if (step.isDone()) { return totalReward; } } } /** * Returns a batch of steps from the environment {@link ai.djl.modality.rl.ReplayBuffer}. * * @return a batch of steps from the environment {@link ai.djl.modality.rl.ReplayBuffer} */ Step[] getBatch(); /** {@inheritDoc} */ @Override void close(); /** A record of taking a step in the environment. */ interface Step extends AutoCloseable { /** * Returns the observation detailing the state before the action. * * @return the observation detailing the state before the action */ NDList getPreObservation(); /** * Returns the action taken. * * @return the action taken */ NDList getAction(); /** * Returns the observation detailing the state after the action. * * @return the observation detailing the state after the action */ NDList getPostObservation(); /** * Returns the available actions after the step. * * @return the available actions after the step */ ActionSpace getPostActionSpace(); /** * Returns the reward given for the action. * * @return the reward given for the action */ NDArray getReward(); /** * Returns whether the environment is finished or can accept further actions. * * @return true if the environment is finished and can no longer accept further actions. */ boolean isDone(); /** {@inheritDoc} */ @Override void close(); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/modality/rl
java-sources/ai/djl/api/0.34.0/ai/djl/modality/rl/env/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 environments to train reinforcement learning in. * * <p>It has a base interface {@link ai.djl.modality.rl.env.RlEnv} as well as class implementing it. */ package ai.djl.modality.rl.env;
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/ndarray/BaseNDManager.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.ndarray; import ai.djl.Device; import ai.djl.engine.Engine; import ai.djl.engine.StandardCapabilities; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.util.PairList; import ai.djl.util.RandomUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import java.util.stream.Stream; /** {@code BaseNDManager} is the default implementation of {@link NDManager}. */ public abstract class BaseNDManager implements NDManager { private static final Logger logger = LoggerFactory.getLogger(BaseNDManager.class); protected NDManager parent; protected NDManager alternativeManager; protected String uid; protected String name; protected Device device; protected ConcurrentHashMap<String, AutoCloseable> resources; protected ConcurrentHashMap<String, TempResource> tempResources; protected AtomicBoolean closed = new AtomicBoolean(false); protected AtomicBoolean capped = new AtomicBoolean(false); @SuppressWarnings("this-escape") protected BaseNDManager(NDManager parent, Device device) { this.parent = parent; this.device = device == null ? defaultDevice() : device; resources = new ConcurrentHashMap<>(); tempResources = new ConcurrentHashMap<>(); uid = NDManager.nextUid(); Engine engine = getEngine().getAlternativeEngine(); if (engine != null) { // Use the same device if possible for efficiency if (this.device.isGpu() && engine.hasCapability(StandardCapabilities.CUDA)) { alternativeManager = engine.newBaseManager(this.device); } else { // Use the default device alternativeManager = engine.newBaseManager(); } } } /** {@inheritDoc} */ @Override public final Device defaultDevice() { return getEngine().defaultDevice(); } /** {@inheritDoc} */ @Override public NDArray create(String[] data, Charset charset, Shape shape) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray create(Shape shape, DataType dataType) { return zeros(shape, dataType); } /** {@inheritDoc} */ @Override public NDArray createCSR(Buffer data, long[] indptr, long[] indices, Shape shape) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray createRowSparse(Buffer data, Shape dataShape, long[] indices, Shape shape) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray createCoo(Buffer data, long[][] indices, Shape shape) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDList load(Path path) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public void setName(String name) { this.name = name; } /** {@inheritDoc} */ @Override public String getName() { return this.name == null ? uid : this.name; } /** {@inheritDoc} */ @Override public NDArray full(Shape shape, float value, DataType dataType) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray arange(float start, float stop, float step, DataType dataType) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray eye(int rows, int cols, int k, DataType dataType) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray linspace(float start, float stop, int num, boolean endpoint) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray randomInteger(long low, long high, Shape shape, DataType dataType) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray randomPermutation(long n) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray randomUniform(float low, float high, Shape shape, DataType dataType) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray randomNormal(float loc, float scale, Shape shape, DataType dataType) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray truncatedNormal(float loc, float scale, Shape shape, DataType dataType) { int sampleSize = (int) shape.size(); double[] dist = new double[sampleSize]; for (int i = 0; i < sampleSize; i++) { double sample = RandomUtils.nextGaussian(); while (sample < -2 || sample > 2) { sample = RandomUtils.nextGaussian(); } dist[i] = sample; } return create(dist).muli(scale).addi(loc).reshape(shape).toType(dataType, false); } /** {@inheritDoc} */ @Override public NDArray randomMultinomial(int n, NDArray pValues) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray randomMultinomial(int n, NDArray pValues, Shape shape) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray sampleNormal(NDArray mu, NDArray sigma) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray sampleNormal(NDArray mu, NDArray sigma, Shape shape) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray samplePoisson(NDArray lam) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray samplePoisson(NDArray lam, Shape shape) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray sampleGamma(NDArray alpha, NDArray beta) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDArray sampleGamma(NDArray alpha, NDArray beta, Shape shape) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public boolean isOpen() { return !closed.get(); } /** {@inheritDoc} */ @Override public void cap() { this.capped.set(true); } /** {@inheritDoc} */ @Override public NDManager getParentManager() { return parent; } /** {@inheritDoc} */ @Override public NDManager newSubManager() { return newSubManager(device); } /** {@inheritDoc} */ @Override public Device getDevice() { return device; } /** {@inheritDoc} */ @Override public List<NDArray> getManagedArrays() { return Stream.concat( // Main resources resources.values().stream() .flatMap( r -> { if (r instanceof NDResource) { return ((NDResource) r) .getResourceNDArrays().stream(); } else if (r instanceof NDManager) { return ((NDManager) r).getManagedArrays().stream(); } else { return Stream.empty(); } }), // Temp resouces tempResources.values().stream() .flatMap(tr -> tr.resource.getResourceNDArrays().stream())) .collect(Collectors.toList()); } /** {@inheritDoc} */ @Override public String toString() { String parentName = parent == null ? "No Parent" : parent.getName(); return "Name: " + getName() + " Parent Name: " + parentName + " isOpen: " + isOpen() + " Resource size: " + resources.size(); } /** {@inheritDoc} */ @Override public synchronized void attachInternal(String resourceId, AutoCloseable... resources) { if (capped.get()) { throw new IllegalStateException("NDManager is capped for addition of resources."); } for (int i = 0; i < resources.length; i++) { attachUncappedInternal( resources.length == 1 ? resourceId : resourceId + "_" + i, resources[i]); } } /** {@inheritDoc} */ @Override public synchronized void attachUncappedInternal(String resourceId, AutoCloseable resource) { if (closed.get()) { throw new IllegalStateException("NDManager has been closed already."); } tempResources.compute( resourceId, (key, tempResource) -> { if (tempResource != null) { // This state occurs when this manager (manA) tempAttaches a resource that // is later // tempAttached to another manager (manB) // When manB is closed, it will use attach to return the resource to this // (manA) // In that case, it should stay as a tempResource in this (manA) tempResource.detached = false; } else { resources.put(resourceId, resource); } return tempResource; }); } /** {@inheritDoc} */ @Override public void tempAttachInternal( NDManager originalManager, String resourceId, NDResource resource) { if (this instanceof SystemNDManager) { throw new IllegalStateException( "System manager cannot be temp attached because it can't be closed.."); } if (closed.get()) { throw new IllegalStateException("NDManager has been closed already."); } tempResources.put(resourceId, new TempResource(resource, originalManager)); } /** {@inheritDoc} */ @Override public synchronized void detachInternal(String resourceId) { if (closed.get()) { // This may happen in the middle of BaseNDManager.close() return; } tempResources.computeIfPresent( resourceId, (key, tempResource) -> { tempResource.detached = true; return tempResource; }); resources.remove(resourceId); } /** {@inheritDoc} */ @Override public void invoke( String operation, NDArray[] src, NDArray[] dest, PairList<String, ?> params) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public NDList invoke(String operation, NDList src, PairList<String, ?> params) { throw new UnsupportedOperationException("Not supported!"); } /** {@inheritDoc} */ @Override public void close() { if (this instanceof SystemNDManager) { throw new IllegalStateException( "The SystemNDManager can not be closed. It is global and lives for the duration" + " of the process"); } if (!closed.getAndSet(true)) { for (AutoCloseable closeable : resources.values()) { try { closeable.close(); } catch (Exception e) { logger.error("Resource close failed.", e); } } for (TempResource resource : tempResources.values()) { resource.returnResource(); } parent.detachInternal(uid); resources.clear(); tempResources.clear(); } } /** * Prints information about this {@link NDManager} and all sub-managers to the console. * * @param level the level of this {@link NDManager} in the hierarchy */ public void debugDump(int level) { StringBuilder sb = new StringBuilder(100); for (int i = 0; i < level; ++i) { sb.append(" "); } sb.append("\\--- NDManager(") .append(uid.substring(24)) .append(") resource count: ") .append(resources.size()); System.out.println(sb); // NOPMD for (AutoCloseable c : resources.values()) { if (c instanceof BaseNDManager) { ((BaseNDManager) c).debugDump(level + 1); } } } NDManager getAlternativeManager() { return alternativeManager; } /** * Checks if the input buffer size is match expected data type. * * @param buffer the input buffer * @param dataType the desired {@code DataType} * @param expected the expected size * @throws IllegalArgumentException if buffer size is invalid */ public static void validateBuffer(Buffer buffer, DataType dataType, int expected) { boolean isByteBuffer = buffer instanceof ByteBuffer; DataType type = DataType.fromBuffer(buffer); if (!isCompatible(type, dataType) && !isByteBuffer) { // It's ok if type != datatype and buffer is ByteBuffer, // since buffer will be copied into ByteBuffer throw new IllegalArgumentException( "The input data type: " + type + " does not match target array data type: " + dataType); } int remaining = buffer.remaining(); int expectedSize = isByteBuffer ? dataType.getNumOfBytes() * expected : expected; if (remaining < expectedSize) { throw new IllegalArgumentException( "The NDArray size is: " + expected + ", but buffer size is: " + remaining); } if (remaining > expectedSize) { logger.warn( "Input buffer size is greater than the NDArray size, please set limit" + " explicitly."); buffer.limit(expectedSize); } } private static boolean isCompatible(DataType type1, DataType type2) { if (type1.getNumOfBytes() != type1.getNumOfBytes()) { return false; } if (type1.getNumOfBytes() == 2) { // fp16, bf16, int16, uint16 all uses ShortBuffer return true; } if (type1.getFormat() == type2.getFormat()) { return true; } return type1.isInteger() && type2.isInteger(); } /** * Copies data from the source {@code Buffer} to the target {@code ByteBuffer}. * * @param src the source {@code Buffer} * @param target the target {@code ByteBuffer} */ public static void copyBuffer(Buffer src, ByteBuffer target) { target.rewind(); DataType inputType = DataType.fromBuffer(src); switch (inputType) { case FLOAT16: target.asShortBuffer().put((ShortBuffer) src); break; case FLOAT32: target.asFloatBuffer().put((FloatBuffer) src); break; case FLOAT64: target.asDoubleBuffer().put((DoubleBuffer) src); break; case UINT8: case INT8: case BOOLEAN: target.put((ByteBuffer) src); break; case INT32: target.asIntBuffer().put((IntBuffer) src); break; case INT64: target.asLongBuffer().put((LongBuffer) src); break; default: throw new AssertionError("Unsupported datatype: " + inputType); } target.rewind(); } protected static final class TempResource { private NDResource resource; private NDManager manager; private boolean detached; public TempResource(NDResource resource, NDManager manager) { this.resource = resource; this.manager = manager; this.detached = false; } public void returnResource() { try { if (!detached) { if (manager.isOpen()) { resource.returnResource(manager); } else { resource.close(); } } } catch (Exception e) { logger.error("Temporary resource return failed.", e); } } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/ndarray/BytesSupplier.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.ndarray; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; /** Represents a supplier of {@code byte[]}. */ public interface BytesSupplier { /** * Returns the {@code byte[]} presentation of the object. * * @return the {@code byte[]} presentation of the object */ default byte[] getAsBytes() { ByteBuffer bb = toByteBuffer(); if (bb.hasArray() && bb.remaining() == bb.array().length) { return bb.array(); } byte[] buf = new byte[bb.remaining()]; bb.get(buf); return buf; } /** * Returns the {@code String} presentation of the object. * * @return the {@code String} presentation of the object */ default String getAsString() { return new String(getAsBytes(), StandardCharsets.UTF_8); } /** * Returns the object that backs this {@code BytesSupplier}. * * @return the object that backs this {@code BytesSupplier} */ default Object getAsObject() { return this; } /** * Returns the {@code ByteBuffer} presentation of the object. * * @return the {@code ByteBuffer} presentation of the object */ ByteBuffer toByteBuffer(); /** * Wraps a byte array into a {code BytesSupplier}. * * @param buf the byte array that will back this {code BytesSupplier} * @return a {@code BytesSupplier} */ static BytesSupplier wrap(byte[] buf) { return new BytesSupplierImpl(buf); } /** * Wraps a string into a {code BytesSupplier}. * * @param value the string that will back this {code BytesSupplier} * @return a {@code BytesSupplier} */ static BytesSupplier wrap(String value) { return new BytesSupplierImpl(value); } /** * Wraps an object as json into a {code BytesSupplier}. * * @param object the object that will back this {code BytesSupplier} * @return a {@code BytesSupplier} */ static BytesSupplier wrapAsJson(Object object) { return new BytesSupplierImpl(object); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/ndarray/BytesSupplierImpl.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.ndarray; import ai.djl.util.JsonUtils; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; class BytesSupplierImpl implements BytesSupplier { private byte[] buf; private String value; private Object obj; BytesSupplierImpl(byte[] buf) { this.buf = buf; } BytesSupplierImpl(String value) { this.value = value; } BytesSupplierImpl(Object obj) { this.obj = obj; } /** {@inheritDoc} */ @Override public byte[] getAsBytes() { if (buf == null) { if (value == null) { value = JsonUtils.toJson(obj); } buf = value.getBytes(StandardCharsets.UTF_8); } return buf; } /** {@inheritDoc} */ @Override public String getAsString() { if (value == null) { if (obj != null) { value = JsonUtils.toJson(obj); } else { value = new String(buf, StandardCharsets.UTF_8); } } return value; } /** {@inheritDoc} */ @Override public Object getAsObject() { if (obj != null) { return obj; } else if (value != null) { return value; } return buf; } /** {@inheritDoc} */ @Override public ByteBuffer toByteBuffer() { return ByteBuffer.wrap(getAsBytes()); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/ndarray/LazyNDArray.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.ndarray; /** An {@link NDArray} that waits to compute values until they are needed. */ public interface LazyNDArray extends NDArray { /** Runs the current NDArray and sleeps until the value is ready to read. */ void waitToRead(); /** Runs the current NDArray and sleeps until the value is ready to write. */ void waitToWrite(); /** Runs all NDArrays and sleeps until their values are fully computed. */ void waitAll(); }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/ndarray/NDArray.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.ndarray; import ai.djl.Device; import ai.djl.ndarray.index.NDIndex; import ai.djl.ndarray.internal.NDArrayEx; import ai.djl.ndarray.internal.NDFormat; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.ndarray.types.SparseFormat; import ai.djl.util.Float16Utils; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.LongStream; /** * An interface representing an n-dimensional array. * * <p>NDArray is the core data structure for all mathematical computations. An NDArray represents a * multidimensional, fixed-size homogeneous array. It has very similar behaviour to the Numpy python * package with the addition of efficient computing. To understand how to manage NDArray lifecycle, * please refer to <a * href="https://github.com/deepjavalibrary/djl/blob/master/docs/development/memory_management.md">NDArray * Memory Management Guide</a> */ public interface NDArray extends NDResource, BytesSupplier { /** * Decodes {@code NDArray} from bytes. * * @param manager {@link NDManager} used to create this {@code NDArray} * @param byteArray data used to decode * @return decoded {@code NDArray} */ static NDArray decode(NDManager manager, byte[] byteArray) { return manager.decode(byteArray); } /** * Returns the name of this {@code NDArray}. * * @return the name of this {@code NDArray} */ String getName(); /** * Sets name of this {@code NDArray}. * * @param name the name of this {@code NDArray} */ void setName(String name); /** * Returns unique identifier of this {@code NDArray}. * * @return unique identifier of this {@code NDArray} */ String getUid(); /** * Returns the {@link DataType} of this {@code NDArray}. * * <p>{@link DataType} is a definition of the precision level of the {@code NDArray}. All values * inside the same {@code NDArray} would have the same {@link DataType}. * * @return the {@link DataType} of this {@code NDArray} */ DataType getDataType(); /** * Returns the {@link Device} of this {@code NDArray}. * * <p>{@link Device} class contains the information where this {@code NDArray} stored in memory, * like CPU/GPU. * * @return the {@link Device} of this {@code NDArray} */ Device getDevice(); /** * Returns the {@link Shape} of this {@code NDArray}. * * <p>{@link Shape} defines how this {@code NDArray} is represented multi-dimensionally. * * @return the {@link Shape} of this {@code NDArray} */ Shape getShape(); /** * Returns the {@link SparseFormat} of this {@code NDArray}. * * @return the {@link SparseFormat} of this {@code NDArray} */ SparseFormat getSparseFormat(); /** * Returns {@code true} if this {@code NDArray} is a {@link SparseNDArray}. * * @return {@code true} if this {@code NDArray} is a {@link SparseNDArray} */ default boolean isSparse() { return getSparseFormat() != SparseFormat.DENSE; } /** * Returns {@code true} if this {@code NDArray} is a scalar {@code NDArray} with empty {@link * Shape}. * * @return {@code true} if this {@code NDArray} is a scalar {@code NDArray} with empty {@link * Shape} */ default boolean isScalar() { return getShape().isScalar(); } /** * Encodes {@code NDArray} to byte array. * * @return byte array */ default byte[] encode() { return NDSerializer.encode(this); } /** * Moves this {@code NDArray} to a different {@link Device}. * * @param device the {@link Device} to be set * @param copy set {@code true} if you want to return a copy of the Existing {@code NDArray} * @return the result {@code NDArray} with the new {@link Device} */ NDArray toDevice(Device device, boolean copy); /** * Converts this {@code NDArray} to a different {@link DataType}. * * @param dataType the {@link DataType} to be set * @param copy set {@code true} if you want to return a copy of the Existing {@code NDArray} * @return the result {@code NDArray} with the new {@link DataType} */ NDArray toType(DataType dataType, boolean copy); /** * Attaches a gradient {@code NDArray} to this {@code NDArray} and marks it so {@link * ai.djl.training.GradientCollector#backward(NDArray)} can compute the gradient with respect to * it. * * @param requiresGrad if {@code NDArray} requires gradient or not */ void setRequiresGradient(boolean requiresGrad); /** * Returns the gradient {@code NDArray} attached to this {@code NDArray}. * * @return the gradient {@code NDArray} * @throws NullPointerException when gradient is not initialized */ NDArray getGradient(); /** * Returns true if the gradient calculation is required for this {@code NDArray}. * * @return true if the gradient calculation is required for this {@code NDArray} else false */ boolean hasGradient(); /** * Returns an NDArray equal to this that stop gradient propagation through it. * * @return an NDArray equal to this that stops gradient propagation through it */ NDArray stopGradient(); /** * Returns an NDArray equal to this that magnifies the gradient propagated to this by a * constant. * * @param scale how to much to magnify the gradient propagated to this * @return an NDArray equal to this that magnifies the gradient propagated to this by a constant */ default NDArray scaleGradient(double scale) { return this.mul(scale).add(this.stopGradient().mul(1 - scale)); } /** * Returns the size of this {@code NDArray} along a given axis. * * @param axis the axis to return the size for * @return the size of this {@code NDArray} along a given axis */ default long size(int axis) { return getShape().size(axis); } /** * Returns the total number of elements in this {@code NDArray}. * * @return the number of elements in this {@code NDArray} */ default long size() { return getShape().size(); } /** {@inheritDoc} */ @Override default ByteBuffer toByteBuffer() { return toByteBuffer(false); } /** * Returns the {@code ByteBuffer} presentation of the object. * * <p>If returned ByteBuffer is a DirectByteBuffer, it shared the same native memory as the * NDArray. The native memory will be deleted when NDArray is closed. * * <p>Not all the engine support return DirectByteBuffer. * * @param tryDirect use DirectBuffer if possible * @return the {@code ByteBuffer} presentation of the object */ ByteBuffer toByteBuffer(boolean tryDirect); /** * Converts this {@code NDArray} to a double array. * * @return a double array * @throws IllegalStateException when {@link DataType} of this {@code NDArray} mismatches */ default double[] toDoubleArray() { if (getDataType() != DataType.FLOAT64) { throw new IllegalStateException( "DataType mismatch, Required double" + " Actual " + getDataType()); } DoubleBuffer db = toByteBuffer(true).asDoubleBuffer(); double[] ret = new double[db.remaining()]; db.get(ret); return ret; } /** * Converts this {@code NDArray} to a float array. * * @return a float array * @throws IllegalStateException when {@link DataType} of this {@code NDArray} mismatches */ default float[] toFloatArray() { if (getDataType() == DataType.FLOAT16) { return Float16Utils.fromByteBuffer(toByteBuffer()); } else if (getDataType() != DataType.FLOAT32) { throw new IllegalStateException( "DataType mismatch, Required float, Actual " + getDataType()); } FloatBuffer fb = toByteBuffer(true).asFloatBuffer(); float[] ret = new float[fb.remaining()]; fb.get(ret); return ret; } /** * Converts this {@code NDArray} to an short array. * * @return an int array * @throws IllegalStateException when {@link DataType} of this {@code NDArray} mismatches */ default short[] toShortArray() { if (getDataType() != DataType.INT16) { throw new IllegalStateException( "DataType mismatch, Required int" + " Actual " + getDataType()); } ShortBuffer ib = toByteBuffer(true).asShortBuffer(); short[] ret = new short[ib.remaining()]; ib.get(ret); return ret; } /** * Converts this {@code NDArray} to an short array. * * @return an int array * @throws IllegalStateException when {@link DataType} of this {@code NDArray} mismatches */ default int[] toUnsignedShortArray() { if (getDataType() != DataType.UINT16) { throw new IllegalStateException( "DataType mismatch, Required int" + " Actual " + getDataType()); } ShortBuffer ib = toByteBuffer(true).asShortBuffer(); int[] ret = new int[ib.remaining()]; for (int i = 0; i < ret.length; ++i) { ret[i] = ib.get() & 0xffff; } return ret; } /** * Converts this {@code NDArray} to an int array. * * @return an int array * @throws IllegalStateException when {@link DataType} of this {@code NDArray} mismatches */ default int[] toIntArray() { DataType dType = getDataType(); if (dType != DataType.INT32 && dType != DataType.UINT32) { throw new IllegalStateException( "DataType mismatch, Required int" + " Actual " + getDataType()); } IntBuffer ib = toByteBuffer(true).asIntBuffer(); int[] ret = new int[ib.remaining()]; ib.get(ret); return ret; } /** * Converts this {@code NDArray} to an unsigned int array. * * @return a long array * @throws IllegalStateException when {@link DataType} of this {@code NDArray} mismatches */ default long[] toUnsignedIntArray() { if (getDataType() != DataType.UINT32) { throw new IllegalStateException( "DataType mismatch, Required int" + " Actual " + getDataType()); } IntBuffer ib = toByteBuffer(true).asIntBuffer(); long[] ret = new long[ib.remaining()]; for (int i = 0; i < ret.length; ++i) { ret[i] = ib.get() & 0X00000000FFFFFFFFL; } return ret; } /** * Converts this {@code NDArray} to a long array. * * @return a long array * @throws IllegalStateException when {@link DataType} of this {@code NDArray} mismatches */ default long[] toLongArray() { if (getDataType() != DataType.INT64) { throw new IllegalStateException( "DataType mismatch, Required long" + " Actual " + getDataType()); } LongBuffer lb = toByteBuffer(true).asLongBuffer(); long[] ret = new long[lb.remaining()]; lb.get(ret); return ret; } /** * Converts this {@code NDArray} to a byte array. * * @return a byte array * @throws IllegalStateException when {@link DataType} of this {@code NDArray} mismatches */ default byte[] toByteArray() { ByteBuffer bb = toByteBuffer(true); if (bb.hasArray() && bb.remaining() == bb.array().length) { return bb.array(); } byte[] buf = new byte[bb.remaining()]; bb.get(buf); return buf; } /** * Converts this {@code NDArray} to a uint8 array. * * @return a uint8 array * @throws IllegalStateException when {@link DataType} of this {@code NDArray} mismatches */ default int[] toUint8Array() { ByteBuffer bb = toByteBuffer(true); int[] buf = new int[bb.remaining()]; for (int i = 0; i < buf.length; ++i) { buf[i] = bb.get() & 0xff; } return buf; } /** * Converts this {@code NDArray} to a boolean array. * * @return a boolean array * @throws IllegalStateException when {@link DataType} of this {@code NDArray} mismatches */ default boolean[] toBooleanArray() { if (getDataType() != DataType.BOOLEAN) { throw new IllegalStateException( "DataType mismatch, Required boolean" + " Actual " + getDataType()); } ByteBuffer bb = toByteBuffer(true); boolean[] ret = new boolean[bb.remaining()]; for (int i = 0; i < ret.length; ++i) { ret[i] = bb.get() != 0; } return ret; } /** * Converts this {@code NDArray} to a String array. * * <p>This method is only applicable to the String typed NDArray and not for printing purpose * * @return Array of Strings */ default String[] toStringArray() { return toStringArray(StandardCharsets.UTF_8); } /** * Converts this {@code NDArray} to a String array with the specified charset. * * <p>This method is only applicable to the String typed NDArray and not for printing purpose * * @param charset to charset for the string * @return Array of Strings */ String[] toStringArray(Charset charset); /** * Converts this {@code NDArray} to a Number array based on its {@link DataType}. * * @return a Number array */ @SuppressWarnings("PMD.AvoidArrayLoops") default Number[] toArray() { switch (getDataType()) { case FLOAT16: case FLOAT32: float[] floatArray = toFloatArray(); return IntStream.range(0, floatArray.length) .mapToObj(i -> floatArray[i]) .toArray(Number[]::new); case FLOAT64: return Arrays.stream(toDoubleArray()).boxed().toArray(Double[]::new); case INT16: short[] buf = toShortArray(); Short[] sbuf = new Short[buf.length]; for (int i = 0; i < buf.length; ++i) { sbuf[i] = buf[i]; } return sbuf; case UINT16: return Arrays.stream(toUnsignedShortArray()).boxed().toArray(Integer[]::new); case INT32: return Arrays.stream(toIntArray()).boxed().toArray(Integer[]::new); case UINT32: return Arrays.stream(toUnsignedIntArray()).boxed().toArray(Long[]::new); case INT64: case UINT64: return Arrays.stream(toLongArray()).boxed().toArray(Long[]::new); case BOOLEAN: case INT8: ByteBuffer bb = toByteBuffer(); Byte[] ret = new Byte[bb.remaining()]; for (int i = 0; i < ret.length; ++i) { ret[i] = bb.get(); } return ret; case UINT8: return Arrays.stream(toUint8Array()).boxed().toArray(Integer[]::new); default: throw new IllegalStateException("Unsupported DataType: " + getDataType()); } } /** * Sets this {@code NDArray} value from {@link Buffer}. * * @param buffer the input buffered data */ void set(Buffer buffer); /** * Sets this {@code NDArray} value from an array of floats. * * @param data the array of floats to set */ default void set(float[] data) { set(FloatBuffer.wrap(data)); } /** * Sets this {@code NDArray} value from an array of ints. * * @param data the array of integers to set */ default void set(int[] data) { set(IntBuffer.wrap(data)); } /** * Sets this {@code NDArray} value from an array of doubles. * * @param data the array of doubles to set */ default void set(double[] data) { set(DoubleBuffer.wrap(data)); } /** * Sets this {@code NDArray} value from an array of longs. * * @param data the array of longs to set */ default void set(long[] data) { set(LongBuffer.wrap(data)); } /** * Sets this {@code NDArray} value from an array of bytes. * * @param data the array of bytes to set */ default void set(byte[] data) { set(ByteBuffer.wrap(data)); } /** * Sets the specified index in this {@code NDArray} with the given values. * * @param index the locations to update * @param value the value to replace with. Can broadcast if given smaller dimensions than the * index */ default void set(NDIndex index, NDArray value) { getNDArrayInternal().getIndexer(getManager()).set(this, index, value); } /** * Sets the specified index in this {@code NDArray} with the given value. * * @param index the locations to update * @param value the value to replace with */ default void set(NDIndex index, Number value) { getNDArrayInternal().getIndexer(getManager()).set(this, index, value); } /** * Sets the specific index by a function. * * @param index the locations to update * @param function the function to change the value */ default void set(NDIndex index, Function<NDArray, NDArray> function) { NDArray array = get(index); set(index, function.apply(array)); } /** * Sets the {@code NDArray} by boolean mask or integer index. * * @param index the boolean or integer {@code NDArray} that indicates what to get * @param value the value to replace with */ default void set(NDArray index, Number value) { set(new NDIndex("{}", index), value); } /** * Sets the specified scalar in this {@code NDArray} with the given value. * * @param index the single index to update * @param value the value to replace with * @throws IllegalArgumentException thrown if the index does not correspond to a single element */ default void setScalar(NDIndex index, Number value) { getNDArrayInternal().getIndexer(getManager()).setScalar(this, index, value); } /** * Returns a partial {@code NDArray}. * * @param index the section of this {@code NDArray} to return * @return the partial {@code NDArray} */ default NDArray get(NDIndex index) { return get(getManager(), index); } /** * Returns a partial {@code NDArray}. * * @param manager the manager used to create the arrays * @param index the section of this {@code NDArray} to return * @return the partial {@code NDArray} */ default NDArray get(NDManager manager, NDIndex index) { return getNDArrayInternal().getIndexer(manager).get(this, index); } /** * Returns a partial {@code NDArray}. * * @param index the boolean or integer {@code NDArray} that indicates what to get * @return the partial {@code NDArray} */ default NDArray get(NDArray index) { return get(new NDIndex("{}", index)); } /** * Returns a partial {@code NDArray}. * * @param indices the indices used to indicate what to get * @param args arguments to replace the varaible "{}" in the indices string. Can be an integer, * long, boolean {@link NDArray}, or integer {@link NDArray}. * @return the partial {@code NDArray} * @see NDIndex#NDIndex(String, Object...) */ default NDArray get(String indices, Object... args) { return get(new NDIndex(indices, args)); } /** * Returns a partial {@code NDArray}. * * @param indices the indices with each index corresponding to the dimensions and negative * indices starting from the end * @return the partial {@code NDArray} */ default NDArray get(long... indices) { return get(new NDIndex(indices)); } /** * Returns a partial {@code NDArray}. * * @param manager the manager used to create the arrays * @param indices the indices with each index corresponding to the dimensions and negative * indices starting from the end * @return the partial {@code NDArray} */ default NDArray get(NDManager manager, long... indices) { return get(manager, new NDIndex(indices)); } /** * Returns a partial {@code NDArray} pointed by the indexed array. * * <pre> * out[i][j][k] = input[index[i][j][k]][j][k] # if axis == 0 * out[i][j][k] = input[i][index[i][j][k]][k] # if axis == 1 * out[i][j][k] = input[i][j][index[i][j][k]] # if axis == 2 * </pre> * * @param index picks the elements of an NDArray to the same position as index * @param axis the entries of index are indices of axis * @return the partial {@code NDArray} of the same shape as index */ NDArray gather(NDArray index, int axis); /** * Returns a partial {@code NDArray} pointed by the indexed array. * * <pre> * Given NDArray arr and NDArray idx. idx is the following structure: * \( idx = [ idx[0, ...], idx[1, ...],..., idx[indexingDepth,...] ] \) * corresponding to x, y, z index, i.e. [idx_x, idx_y, idx_z, ...]. * </pre> * * <p>So indexingDepth smaller than or equal to data.shape[0] If indexingDepth is smaller than * data.shape[0], for instance, data.shape[0]=3, i.e. x,y,z but indexingDepth = 2, i.e. [idx_x, * idx_y], then the tail co-rank = data.shape[0] - indexingDepth will be kept. * * <p>With it, the output shape = idx_y.shape appended by data.shape[indexingDepth:] <a * href="https://mxnet.apache.org/versions/1.6/api/r/docs/api/mx.symbol.gather_nd.html?highlight=gather_nd">mx.symbol.gather_nd</a> * * @param index picks the elements of an NDArray to the same position as index * @return the partial {@code NDArray} of the same shape as index */ NDArray gatherNd(NDArray index); /** * Returns a partial {@code NDArray} pointed by index according to linear indexing, and the of * output is of the same shape as index. * * @param index picks the elements of an NDArray and output to the same entry as in index * @return the partial {@code NDArray} of the same shape as index */ default NDArray take(NDArray index) { return take(this.getManager(), index); } /** * Returns a partial {@code NDArray} pointed by index according to linear indexing, and the of * output is of the same shape as index. * * @param manager the manager used to create the arrays * @param index picks the elements of an NDArray and output to the same entry as in index * @return the partial {@code NDArray} of the same shape as index */ NDArray take(NDManager manager, NDArray index); /** * Sets the entries of {@code NDArray} pointed by index, according to linear indexing, to be the * numbers in value. * * <p>Value has to be of the same shape as index. * * @param index select the entries of an {@code NDArray} * @param value numbers to assign to the indexed entries * @return the NDArray with updated values */ NDArray put(NDArray index, NDArray value); /** * Writes all values from the tensor value into self at the indices specified in the index * tensor. * * <pre> * This is the reverse operation of the manner described in gather(). * * self[index[i][j][k]][j][k] = value[i][j][k] # if axis == 0 * self[i][index[i][j][k]][k] = value[i][j][k] # if axis == 1 * self[i][j][index[i][j][k]] = value[i][j][k] # if axis == 2 * </pre> * * <a * href="https://pytorch.org/docs/1.13/generated/torch.Tensor.scatter_.html#torch.Tensor.scatter">torch.Tensor.scatter_</a> * * @param axis the axis along which to index * @param index the indices of elements to scatter, can be either empty or of the same * dimensionality as value. When empty, the operation returns self unchanged * @param value the source element(s) to scatter * @return the NDArray with updated values */ NDArray scatter(NDArray index, NDArray value, int axis); /** * Returns a scalar {@code NDArray} corresponding to a single element. * * @param indices the indices of the scalar to return. Must return only a single element * @return a scalar {@code NDArray} corresponding to the element * @throws IllegalArgumentException thrown if the result is not a single element */ default NDArray getScalar(long... indices) { NDArray value = get(new NDIndex(indices)); if (value.size() != 1) { throw new IllegalArgumentException("The supplied Index does not produce a scalar"); } return value; } /** * Returns a long element from this {@code NDArray}. * * @param indices the indices of the long element to return * @return the element in the specified index as a long * @throws IllegalArgumentException thrown if the result is not a single element */ default long getLong(long... indices) { try (NDArray scalar = getScalar(indices)) { return scalar.toLongArray()[0]; } } /** * Returns a double element from this {@code NDArray}. * * @param indices the indices of the double element to return * @return the element in the specified index as a double * @throws IllegalArgumentException thrown if the result is not a single element */ default double getDouble(long... indices) { try (NDArray scalar = getScalar(indices)) { return scalar.toDoubleArray()[0]; } } /** * Returns a float element from this {@code NDArray}. * * @param indices the indices of the long element to return * @return the element in the specified index as a float * @throws IllegalArgumentException thrown if the result is not a single element */ default float getFloat(long... indices) { try (NDArray scalar = getScalar(indices)) { return scalar.toFloatArray()[0]; } } /** * Returns an int element from this {@code NDArray}. * * @param indices the indices of the int element to return * @return the element in the specified index as an integer * @throws IllegalArgumentException thrown if the result is not a single element */ default int getInt(long... indices) { try (NDArray scalar = getScalar(indices)) { return scalar.toIntArray()[0]; } } /** * Returns an byte element from this {@code NDArray}. * * @param indices the indices of the byte element to return * @return the element in the specified index as a byte * @throws IllegalArgumentException thrown if the result is not a single element */ default byte getByte(long... indices) { try (NDArray scalar = getScalar(indices)) { return scalar.toByteArray()[0]; } } /** * Returns an integer element from this {@code NDArray} that represent unsigned integer with 8 * bits. * * @param indices the indices of the unsigned 8 bits integer element to return * @return the element in the specified index as a uint8 * @throws IllegalArgumentException thrown if the result is not a single element */ default int getUint8(long... indices) { return getByte(indices) & 0xff; } /** * Returns a boolean element from this {@code NDArray}. * * @param indices the indices of the int element to return * @return the element in the specified index as a boolean * @throws IllegalArgumentException thrown if the result is not a single element */ default boolean getBoolean(long... indices) { try (NDArray scalar = getScalar(indices)) { return scalar.toBooleanArray()[0]; } } /** * Deep-copies the current {@code NDArray} to the one passed in. * * @param array this {@code NDArray} prepared to be copied to */ default void copyTo(NDArray array) { array.set(toByteBuffer()); } /** * Returns a copy of this {@code NDArray}. * * @return a copy of this {@code NDArray} */ default NDArray duplicate() { NDArray array = getManager().create(getShape(), getDataType(), getDevice()); array.setName(getName()); copyTo(array); return array; } /** * Returns portion of this {@code NDArray} given the index boolean {@code NDArray} along first * axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f, 3f, 4f, 5f, 6f}, new Shape(3, 2)); * jshell&gt; NDArray mask = manager.create(new boolean[] {true, false, true}); * jshell&gt; array.booleanMask(mask); * ND: (2, 2) cpu() float32 * [[1., 2.], * [5., 6.], * ] * </pre> * * @param index boolean {@code NDArray} mask * @return the result {@code NDArray} */ default NDArray booleanMask(NDArray index) { return booleanMask(index, 0); } /** * Returns portion of this {@code NDArray} given the index boolean {@code NDArray} along given * axis. * * @param index boolean {@code NDArray} mask * @param axis an integer that represents the axis of {@code NDArray} to mask from * @return the result {@code NDArray} */ NDArray booleanMask(NDArray index, int axis); /** * Sets all elements outside the sequence to a constant value. * * <p>This function takes an n-dimensional input array of the form [batch_size, * max_sequence_length, ....] and returns an array of the same shape. Parameter {@code * sequenceLength} is used to handle variable-length sequences. sequence_length should be an * input array of positive ints of dimension [batch_size]. * * @param sequenceLength used to handle variable-length sequences * @param value the constant value to be set * @return the result {@code NDArray} */ NDArray sequenceMask(NDArray sequenceLength, float value); /** * Sets all elements outside the sequence to 0. * * <p>This function takes an n-dimensional input array of the form [batch_size, * max_sequence_length, ....] and returns an array of the same shape. Parameter {@code * sequenceLength} is used to handle variable-length sequences. sequence_length should be an * input array of positive ints of dimension [batch_size]. * * @param sequenceLength used to handle variable-length sequences * @return the result {@code NDArray} */ NDArray sequenceMask(NDArray sequenceLength); /** * Returns an {@code NDArray} of zeros with the same {@link Shape}, {@link DataType} and {@link * SparseFormat} as the input {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(6f).reshape(2, 3); * jshell&gt; array; * ND: (2, 3) cpu() float32 * [[0., 1., 2.], * [3., 4., 5.], * ] * jshell&gt; array.zerosLike(); * ND: (2, 3) cpu() float32 * [[0., 0., 0.], * [0., 0., 0.], * ] * </pre> * * @return a {@code NDArray} filled with zeros */ default NDArray zerosLike() { return getManager().zeros(getShape(), getDataType(), getDevice()); } /** * Returns an {@code NDArray} of ones with the same {@link Shape}, {@link DataType} and {@link * SparseFormat} as the input {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(6f).reshape(2, 3); * jshell&gt; array; * ND: (2, 3) cpu() float32 * [[0., 1., 2.], * [3., 4., 5.], * ] * jshell&gt; array.onesLike(); * ND: (2, 3) cpu() float32 * [[1., 1., 1.], * [1., 1., 1.], * ] * </pre> * * @return a {@code NDArray} filled with ones */ default NDArray onesLike() { return getManager().ones(getShape(), getDataType(), getDevice()); } /** * Returns an uninitialized {@code NDArray} with the same {@link Shape}, {@link DataType} and * {@link SparseFormat} as the input {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(6f).reshape(2, 3); * jshell&gt; array; * ND: (2, 3) cpu() float32 * [[0., 1., 2.], * [3., 4., 5.], * ] * jshell&gt; array.like(); // uninitialized NDArray * ND: (2, 3) cpu() float32 * [[ 9.80908925e-45, 0.00000000e+00, 0.00000000e+00], * [ 0.00000000e+00, 7.61595174e-07, 2.80259693e-44], * ] * </pre> * * @return the result {@code NDArray} */ default NDArray like() { return getManager().create(getShape()); } /* // Operations */ /* // Operations: Element Comparison */ /** * Returns {@code true} if all elements in this {@code NDArray} are equal to the {@link Number}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.ones(new Shape(2, 3)); * jshell&gt; array.contentEquals(1); // return true instead of boolean NDArray * true * </pre> * * @param number the number to compare * @return the boolean result */ boolean contentEquals(Number number); /** * Returns {@code true} if all elements in this {@code NDArray} are equal to the other {@link * NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.arange(6f).reshape(2, 3); * jshell&gt; NDArray array2 = manager.create(new float[] {0f, 1f, 2f, 3f, 4f, 5f}, new Shape(2, 3)); * jshell&gt; array1.contentEquals(array2); // return true instead of boolean NDArray * true * </pre> * * @param other the other {@code NDArray} to compare * @return the boolean result */ boolean contentEquals(NDArray other); /** * Checks 2 {@code NDArray}s for equal shapes. * * <p>Shapes are considered equal if: * * <ul> * <li>Both {@code NDArray}s have equal rank, and * <li>size(0)...size(rank()-1) are equal for both {@code NDArray}s * </ul> * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.ones(new Shape(1, 2, 3)); * jshell&gt; NDArray array2 = manager.create(new Shape(1, 2, 3)); * jshell&gt; array1.shapeEquals(array2); // return true instead of boolean NDArray * true * </pre> * * @param other the other {@code NDArray} * @return {@code true} if the {@link Shape}s are the same */ default boolean shapeEquals(NDArray other) { return getShape().equals(other.getShape()); } /** * Returns {@code true} if two {@code NDArray}s are element-wise equal within a tolerance. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new double[] {1e10, 1e-7}); * jshell&gt; NDArray array2 = manager.create(new double[] {1.00001e10, 1e-8}); * jshell&gt; array1.allClose(array2); // return false instead of boolean NDArray * false * jshell&gt; NDArray array1 = manager.create(new double[] {1e10, 1e-8}); * jshell&gt; NDArray array2 = manager.create(new double[] {1.00001e10, 1e-9}); * jshell&gt; array1.allClose(array2); // return true instead of boolean NDArray * true * </pre> * * @param other the {@code NDArray} to compare with * @return the boolean result */ default boolean allClose(NDArray other) { return allClose(other, 1e-5, 1e-08, false); } /** * Returns {@code true} if two {@code NDArray} are element-wise equal within a tolerance. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new double[] {1e10, 1e-7}); * jshell&gt; NDArray array2 = manager.create(new double[] {1.00001e10, 1e-8}); * jshell&gt; array1.allClose(array2, 1e-05, 1e-08, false); // return false instead of boolean NDArray * false * jshell&gt; NDArray array1 = manager.create(new double[] {1e10, 1e-8}); * jshell&gt; NDArray array2 = manager.create(new double[] {1.00001e10, 1e-9}); * jshell&gt; array1.allClose(array2, 1e-05, 1e-08, false); // return true instead of boolean NDArray * true * jshell&gt; NDArray array1 = manager.create(new float[] {1f, Float.NaN}); * jshell&gt; NDArray array2 = manager.create(new float[] {1f, Float.NaN}); * jshell&gt; array1.allClose(array2, 1e-05, 1e-08, true); // return true instead of boolean NDArray * true * </pre> * * @param other the {@code NDArray} to compare with * @param rtol the relative tolerance parameter * @param atol the absolute tolerance parameter * @param equalNan whether to compare NaN’s as equal. If {@code true}, NaN’s in the {@link * NDArray} will be considered equal to NaN’s in the other {@code NDArray} * @return the boolean result */ default boolean allClose(NDArray other, double rtol, double atol, boolean equalNan) { if (!shapeEquals(other)) { return false; } Number[] actualDoubleArray = toArray(); Number[] expectedDoubleArray = other.toArray(); for (int i = 0; i < actualDoubleArray.length; i++) { double a = actualDoubleArray[i].doubleValue(); double b = expectedDoubleArray[i].doubleValue(); // handle NaN if (equalNan && Double.isNaN(a) && Double.isNaN(b)) { continue; } if (Double.isNaN(a) || Double.isNaN(b) || (Math.abs(a - b) > (atol + rtol * Math.abs(b)))) { return false; } } return true; } /** * Returns the boolean {@code NDArray} for element-wise "Equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.ones(new Shape(1)); * jshell&gt; array.eq(1); * ND: (1) cpu() boolean * [ true] * </pre> * * @param n the number to compare * @return the boolean {@code NDArray} for element-wise "Equals" comparison */ NDArray eq(Number n); /** * Returns the boolean {@code NDArray} for element-wise "Equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {0f, 1f, 3f}); * jshell&gt; NDArray array2 = manager.arange(3f); * jshell&gt; array1.eq(array2); * ND: (3) cpu() boolean * [ true, true, false] * </pre> * * @param other the {@code NDArray} to compare * @return the boolean {@code NDArray} for element-wise "Equals" comparison */ NDArray eq(NDArray other); /** * Returns the boolean {@code NDArray} for element-wise "Not equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(4f).reshape(2, 2); * jshell&gt; array.neq(1); * ND: (2, 2) cpu() boolean * [[ true, false], * [ true, true], * ] * </pre> * * @param n the number to compare * @return the boolean {@code NDArray} for element-wise "Not equals" comparison */ NDArray neq(Number n); /** * Returns the boolean {@code NDArray} for element-wise "Not equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {1f, 3f}); * jshell&gt; array1.neq(array2); * ND: (2) cpu() boolean * [false, true] * jshell&gt; NDArray array1 = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {1f, 3f, 1f, 4f}, new Shape(2, 2)); * jshell&gt; array1.neq(array2); // broadcasting * ND: (2, 2) cpu() boolean * [[false, true], * [false, true], * ] * </pre> * * @param other the {@code NDArray} to compare * @return the boolean {@code NDArray} for element-wise "Not equals" comparison */ NDArray neq(NDArray other); /** * Returns the boolean {@code NDArray} for element-wise "Greater" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {4f, 2f}); * jshell&gt; array.gt(2f); * ND: (2) cpu() boolean * [ true, false] * </pre> * * @param n the number to compare * @return the boolean {@code NDArray} for element-wise "Greater" comparison */ NDArray gt(Number n); /** * Returns the boolean {@code NDArray} for element-wise "Greater Than" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {4f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 2f}); * jshell&gt; array1.neq(array2); * ND: (2) cpu() boolean * [ true, false] * </pre> * * @param other the {@code NDArray} to compare * @return the boolean {@code NDArray} for element-wis "Greater Than" comparison */ NDArray gt(NDArray other); /** * Returns the boolean {@code NDArray} for element-wise "Greater or equals" comparison. * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {4f, 2f}); * jshell&gt; array.gte(2f); * ND: (2) cpu() boolean * [ true, true] * </pre> * * @param n the number to compare * @return the boolean {@code NDArray} for element-wise "Greater or equals" comparison */ NDArray gte(Number n); /** * Returns the boolean {@code NDArray} for element-wise "Greater or equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {4f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 2f}); * jshell&gt; array1.gte(array2); * ND: (2) cpu() boolean * [ true, true] * </pre> * * @param other the number to compare * @return the boolean {@code NDArray} for "Greater or equals" comparison */ NDArray gte(NDArray other); /** * Returns the boolean {@code NDArray} for element-wise "Less" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; array.lt(2f); * ND: (2) cpu() boolean * [ true, false] * </pre> * * @param n the number to compare * @return the boolean {@code NDArray} for element-wise "Less" comparison */ NDArray lt(Number n); /** * Returns the boolean {@code NDArray} for element-wise "Less" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 2f}); * jshell&gt; array1.lt(array2); * ND: (2) cpu() boolean * [ true, false] * </pre> * * @param other the {@code NDArray} to compare * @return the boolean {@code NDArray} for element-wise "Less" comparison */ NDArray lt(NDArray other); /** * Returns the boolean {@code NDArray} for element-wise "Less or equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; array.lte(2f); * ND: (2) cpu() boolean * [ true, true] * </pre> * * @param n the number to compare * @return the boolean {@code NDArray} for element-wise "Less or equals" comparison */ NDArray lte(Number n); /** * Returns the boolean {@code NDArray} for element-wise "Less or equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 2f}); * jshell&gt; array1.lte(array2); * ND: (2) cpu() boolean * [ true, true] * </pre> * * @param other the {@code NDArray} to compare * @return the boolean {@code NDArray} for element-wise "Less or equals" comparison */ NDArray lte(NDArray other); /* // Operations: Element Arithmetic */ /** * Adds a number to this {@code NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; array.add(2f); * ND: (2) cpu() float32 * [3., 4.] * </pre> * * @param n the number to add * @return the result {@code NDArray} */ NDArray add(Number n); /** * Adds other {@code NDArray}s to this {@code NDArray} element-wise. * * <p>The shapes of this {@code NDArray} and other {@code NDArray} must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.arange(9f).reshape(3, 3); * jshell&gt; NDArray array2 = manager.arange(3f); * jshell&gt; array1.add(array2); // broadcasting * ND: (3, 3) cpu() float32 * [[ 0., 2., 4.], * [ 3., 5., 7.], * [ 6., 8., 10.], * ] * </pre> * * @param other the other {@code NDArray}s to add * @return the result {@code NDArray} * @throws IllegalArgumentException others arrays must have at least one element */ NDArray add(NDArray other); /** * Subtracts a number from this {@code NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; array.sub(2f); * ND: (2) cpu() float32 * [-1., 0.] * </pre> * * @param n the number to subtract from * @return the result {@code NDArray} */ NDArray sub(Number n); /** * Subtracts the other {@code NDArray} from this {@code NDArray} element-wise. * * <p>The shapes of this {@code NDArray} and other {@code NDArray}s must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.arange(9).reshape(3, 3); * jshell&gt; NDArray array2 = manager.arange(3); * jshell&gt; array1.sub(array2); // broadcasting * ND: (3, 3) cpu() float32 * [[0., 0., 0.], * [3., 3., 3.], * [6., 6., 6.], * ] * </pre> * * @param other the other {@code NDArray} to subtract from * @return the result {@code NDArray} */ NDArray sub(NDArray other); /** * Multiplies this {@code NDArray} by a number element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; array.mul(3f); * ND: (2) cpu() float32 * [3., 6.] * </pre> * * @param n the number to multiply by * @return the result {@code NDArray} */ NDArray mul(Number n); /** * Multiplies this {@code NDArray} by other {@code NDArray}s element-wise. * * <p>The shapes of this {@code NDArray} and other {@code NDArray} must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.arange(9f).reshape(3, 3); * jshell&gt; NDArray array2 = manager.arange(3f); * jshell&gt; array1.mul(array2); // broadcasting * ND: (3, 3) cpu() float32 * [[ 0., 1., 4.], * [ 0., 4., 10.], * [ 0., 7., 16.], * ] * </pre> * * @param other the other {@code NDArray}s to multiply by * @return the result {@code NDArray} * @throws IllegalArgumentException others arrays must have at least one element */ NDArray mul(NDArray other); /** * Divides this {@code NDArray} by a number element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; array.div(4f); * ND: (5) cpu() float32 * [0. , 0.25, 0.5 , 0.75, 1. ] * </pre> * * @param n the number to divide by * @return the result {@code NDArray} */ NDArray div(Number n); /** * Divides this {@code NDArray} by the other {@code NDArray} element-wise. * * <p>The shapes of this {@code NDArray} and the other {@code NDArray} must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.arange(9f).reshape(3, 3); * jshell&gt; NDArray array2 = manager.ones(new Shape(3)).mul(10); * jshell&gt; array1.div(array2); // broadcasting * ND: (3, 3) cpu() float32 * [[0. , 0.1, 0.2], * [0.3, 0.4, 0.5], * [0.6, 0.7, 0.8], * ] * </pre> * * @param other the other {@code NDArray} to divide by * @return the result {@code NDArray} */ NDArray div(NDArray other); /** * Returns element-wise remainder of division. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(7f); * jshell&gt; array.mod(5f); * ND: (7) cpu() float32 * [0., 1., 2., 3., 4., 0., 1.] * </pre> * * @param n the divisor number * @return the result {@code NDArray} */ NDArray mod(Number n); /** * Returns element-wise remainder of division. * * <p>The shapes of this {@code NDArray} and the other {@code NDArray} must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {4f, 7f}); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 3f}); * jshell&gt; array1.mod(array2); * ND: (2) cpu() float32 * [0., 1.] * </pre> * * @param other the divisor {@code NDArray} * @return the result {@code NDArray} */ NDArray mod(NDArray other); /** * Takes the power of this {@code NDArray} with a number element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; array.pow(4f); * ND: (6) cpu() float32 * [ 0., 1., 8., 27., 64., 125.] * </pre> * * @param n the number to take the power with * @return the result {@code NDArray} */ NDArray pow(Number n); /** * Takes the power of this {@code NDArray} with the other {@code NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.arange(6f).reshape(3, 2); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 3f}); * jshell&gt; array1.pow(array2); // broadcasting * ND: (3, 2) cpu() float32 * [[ 0., 1.], * [ 4., 27.], * [ 16., 125.], * ] * </pre> * * @param other the other {@code NDArray} to take the power with * @return the result {@code NDArray} */ NDArray pow(NDArray other); /** * Computes this * log(other). * * @param other other the other {@code NDArray} * @return the result {@code NDArray} */ NDArray xlogy(NDArray other); /** * Adds a number to this {@code NDArray} element-wise in place. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; array.addi(2f); * ND: (2) cpu() float32 * [3., 4.] * jshell&gt; array; * ND: (2) cpu() float32 * [3., 4.] * </pre> * * @param n the number to add * @return the result {@code NDArray} */ NDArray addi(Number n); /** * Adds other {@code NDArray}s to this {@code NDArray} element-wise in place. * * <p>The shapes of this {@code NDArray} and other {@code NDArray}s must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {3f, 4f}); * jshell&gt; array1.addi(array2); * ND: (2) cpu() float32 * [4., 6.] * jshell&gt; array; * ND: (2) cpu() float32 * [4., 6.] * </pre> * * @param other the other {@code NDArray}s to add * @return the result {@code NDArray} */ NDArray addi(NDArray other); /** * Subtracts a number from this {@code NDArray} element-wise in place. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; array.subi(2f); * ND: (2) cpu() float32 * [-1., 0.] * jshell&gt; array; * ND: (2) cpu() float32 * [-1., 0.] * </pre> * * @param n the number to subtract * @return the result {@code NDArray} */ NDArray subi(Number n); /** * Subtracts the other {@code NDArray} from this {@code NDArray} element-wise in place. * * <p>The shapes of this {@code NDArray} and other {@code NDArray}s must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.arange(9f).reshape(3, 3); * jshell&gt; NDArray array2 = manager.arange(3f); * jshell&gt; array1.subi(array2); // broadcasting * ND: (3, 3) cpu() float32 * [[0., 0., 0.], * [3., 3., 3.], * [6., 6., 6.], * ] * jshell&gt; array1; * [[0., 0., 0.], * [3., 3., 3.], * [6., 6., 6.], * ] * </pre> * * @param other the other {@code NDArray} to subtract from * @return the result {@code NDArray} */ NDArray subi(NDArray other); /** * Multiplies this {@code NDArray} by a number element-wise in place. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; array.muli(3f); * ND: (2) cpu() float32 * [3., 6.] * jshell&gt; array; * ND: (2) cpu() float32 * [3., 6.] * </pre> * * @param n the number to multiply by * @return the result {@code NDArray} */ NDArray muli(Number n); /** * Multiplies this {@code NDArray} by other {@code NDArray} element-wise in place. * * <p>The shapes of this {@code NDArray} and other {@code NDArray}s must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.arange(9f).reshape(3, 3); * jshell&gt; NDArray array2 = manager.arange(3f); * jshell&gt; array1.muli(array2); // broadcasting * ND: (3, 3) cpu() float32 * [[ 0., 1., 4.], * [ 0., 4., 10.], * [ 0., 7., 16.], * ] * jshell&gt; array1; * ND: (3, 3) cpu() float32 * [[ 0., 1., 4.], * [ 0., 4., 10.], * [ 0., 7., 16.], * ] * </pre> * * @param other the other NDArrays to multiply with * @return the result {@code NDArray} */ NDArray muli(NDArray other); /** * Divides this {@code NDArray} by a number element-wise in place. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; array.divi(4f); * ND: (5) cpu() float32 * [0. , 0.25, 0.5 , 0.75, 1. ] * jshell&gt; array; * ND: (5) cpu() float32 * [0. , 0.25, 0.5 , 0.75, 1. ] * </pre> * * @param n the number to divide values by * @return the array after applying division operation */ NDArray divi(Number n); /** * Divides this {@code NDArray} by the other {@code NDArray} element-wise in place. * * <p>The shapes of this {@code NDArray} and the other {@code NDArray} must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.arange(9f).reshape(3, 3); * jshell&gt; NDArray array2 = manager.ones(new Shape(3)).mul(10); * jshell&gt; array1.divi(array2); // broadcasting * ND: (3, 3) cpu() float32 * [[0. , 0.1, 0.2], * [0.3, 0.4, 0.5], * [0.6, 0.7, 0.8], * ] * jshell&gt; array1; * [[0. , 0.1, 0.2], * [0.3, 0.4, 0.5], * [0.6, 0.7, 0.8], * ] * </pre> * * @param other the other {@code NDArray} to divide by * @return the result of the divide */ NDArray divi(NDArray other); /** * Returns element-wise remainder of division in place. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(7f); * jshell&gt; array.modi(5f); * ND: (7) cpu() float32 * [0., 1., 2., 3., 4., 0., 1.] * jshell&gt; array; * ND: (7) cpu() float32 * [0., 1., 2., 3., 4., 0., 1.] * </pre> * * @param n the divisor number * @return the result {@code NDArray} */ NDArray modi(Number n); /** * Returns in place element-wise remainder of division in place. * * <p>The shapes of this {@code NDArray} and the other {@code NDArray} must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {4f, 7f}); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 3f}); * jshell&gt; array1.modi(array2); * ND: (2) cpu() float32 * [0., 1.] * jshell&gt; array1; * ND: (2) cpu() float32 * [0., 1.] * </pre> * * @param other the divisor {@code NDArray} * @return the result of the divide */ NDArray modi(NDArray other); /** * Takes the power of this {@code NDArray} with a number element-wise in place. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; array.powi(4f); * ND: (6) cpu() float32 * [ 0., 1., 8., 27., 64., 125.] * jshell&gt; array; * ND: (6) cpu() float32 * [ 0., 1., 8., 27., 64., 125.] * </pre> * * @param n the number to raise the power to * @return the result {@code NDArray} */ NDArray powi(Number n); /** * Takes the power of this {@code NDArray} with the other {@code NDArray} element-wise in place. * * <p>The shapes of this {@code NDArray} and the other {@code NDArray} must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.arange(6f).reshape(3, 2); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 3f}); * jshell&gt; array1.powi(array2); // broadcasting * ND: (3, 2) cpu() float32 * [[ 0., 1.], * [ 4., 27.], * [ 16., 125.], * ] * jshell&gt; array1; * ND: (3, 2) cpu() float32 * [[ 0., 1.], * [ 4., 27.], * [ 16., 125.], * ] * </pre> * * @param other the other {@code NDArray} to take the power with * @return the result {@code NDArray} */ NDArray powi(NDArray other); /** * Returns the element-wise sign. * * @return the result {@code NDArray} */ NDArray sign(); /** * Returns the element-wise sign in-place. * * @return the result {@code NDArray} */ NDArray signi(); /** * Returns the maximum of this {@code NDArray} and a number element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {2f, 3f, 4f}); * jshell&gt; array.maximum(3f); * ND: (3) cpu() float32 * [3., 3., 4.] * </pre> * * @param n the number to be compared * @return the maximum of this {@code NDArray} and a number element-wise */ NDArray maximum(Number n); /** * Returns the maximum of this {@code NDArray} and the other {@code NDArray} element-wise. * * <p>The shapes of this {@code NDArray} and the other {@code NDArray} must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {2f, 3f, 4f}); * jshell&gt; NDArray array2 = manager.create(new float[] {1f, 5f, 2f}); * jshell&gt; array1.maximum(array2); * ND: (3) cpu() float32 * [2., 5., 4.] * jshell&gt; NDArray array1 = manager.eye(2); * jshell&gt; NDArray array2 = manager.create(new float[] {0.5f, 2f}); * jshell&gt; array1.maximum(array2); // broadcasting * ND: (2, 2) cpu() float32 * [[1. , 2. ], * [0.5, 2. ], * ] * </pre> * * @param other the {@code NDArray} to be compared * @return the maximum of this {@code NDArray} and the other {@code NDArray} element-wise */ NDArray maximum(NDArray other); /** * Returns the minimum of this {@code NDArray} and a number element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {2f, 3f, 4f}); * jshell&gt; array.minimum(3f); * ND: (3) cpu() float32 * [2., 3., 3.] * </pre> * * @param n the number to be compared * @return the minimum of this {@code NDArray} and a number element-wise */ NDArray minimum(Number n); /** * Returns the minimum of this {@code NDArray} and the other {@code NDArray} element-wise. * * <p>The shapes of this {@code NDArray} and the other {@code NDArray} must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {2f, 3f, 4f}); * jshell&gt; NDArray array2 = manager.create(new float[] {1f, 5f, 2f}); * jshell&gt; array1.minimum(array2); * ND: (3) cpu() float32 * [1., 3., 2.] * jshell&gt; NDArray array1 = manager.eye(2); * jshell&gt; NDArray array2 = manager.create(new float[] {0.5f, 2f}); * jshell&gt; array1.minimum(array2); // broadcasting * ND: (2, 2) cpu() float32 * [[0.5, 0. ], * [0. , 1. ], * ] * </pre> * * @param other the {@code NDArray} to be compared * @return the minimum of this {@code NDArray} and the other {@code NDArray} element-wise */ NDArray minimum(NDArray other); /* // Operations: Basic Numeric */ /** * Returns the numerical negative {@code NDArray} element-wise. * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; array.neg(); * ND: (5) cpu() float32 * [-0., -1., -2., -3., -4.] * </pre> * * @return the result {@code NDArray} */ NDArray neg(); /** * Returns the numerical negative {@code NDArray} element-wise in place. * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; array.negi(); * jshell&gt; array; * ND: (5) cpu() float32 * [-0., -1., -2., -3., -4.] * </pre> * * @return the result {@code NDArray} */ NDArray negi(); /** * Returns the absolute value of this {@code NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {-1f, -2f}); * jshell&gt; array.abs(); * ND: (2) cpu() float32 * [1., 2.] * </pre> * * @return the result {@code NDArray} */ NDArray abs(); /** * Returns the square of this {@code NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {2f, -3f}); * jshell&gt; array.square(); * ND: (2) cpu() float32 * [4., 9.] * </pre> * * @return the result {@code NDArray} */ NDArray square(); /** * Returns the square root of this {@code NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {4f}); * jshell&gt; array.sqrt(); * ND: (1) cpu() float32 * [2., ] * </pre> * * @return the result {@code NDArray} */ NDArray sqrt(); /** * Returns the cube-root of this {@code NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 8f, 27f}); * jshell&gt; array.cbrt(); * ND: (3) cpu() float32 * [1., 2., 3.] * </pre> * * @return the result {@code NDArray} */ NDArray cbrt(); /** * Returns the floor of this {@code NDArray} element-wise. * * <p>The floor of the scalar x is the largest integer i, such that i &lt;= x. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {-1.7f, -1.5f, -0.2f, 0.2f, 1.5f, 1.7f, 2.0f}); * jshell&gt; array.floor(); * ND: (7) cpu() float32 * [-2., -2., -1., 0., 1., 1., 2.] * </pre> * * @return the result {@code NDArray} */ NDArray floor(); /** * Returns the ceiling of this {@code NDArray} element-wise. * * <p>The ceil of the scalar x is the smallest integer i, such that i &gt;= x. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {-1.7f, -1.5f, -0.2f, 0.2f, 1.5f, 1.7f, 2.0f}); * jshell&gt; array.ceil(); * ND: (7) cpu() float32 * [-1., -1., -0., 1., 2., 2., 2.] * </pre> * * @return the result {@code NDArray} */ NDArray ceil(); /** * Returns the round of this {@code NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {-1.7f, -1.5f, -0.2f, 0.2f, 1.5f, 1.7f, 2.0f}); * jshell&gt; array.round(); * ND: (7) cpu() float32 * [-2., -2., -0., 0., 2., 2., 2.] * </pre> * * @return the result {@code NDArray} */ NDArray round(); /** * Returns the truncated value of this {@code NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {-1.7f, -1.5f, -0.2f, 0.2f, 1.5f, 1.7f, 2.0f}); * jshell&gt; array.trunc(); * ND: (7) cpu() float32 * [-1., -1., -0., 0., 1., 1., 2.] * </pre> * * @return the result {@code NDArray} */ NDArray trunc(); /** * Returns the exponential value of this {@code NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 2.5f}); * jshell&gt; array.exp(); * ND: (2) cpu() float32 * [ 1. , 12.1825] * </pre> * * @return the result {@code NDArray} */ NDArray exp(); /** * Return the log of the absolute value of the gamma function of this {@code NDArray} * element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0.5f, 1f, 1.5f}); * jshell&gt; array.gammaln(); * ND: (2) cpu() float32 * [ 0.5724, 0.0000, -0.1208] * </pre> * * @return the result {@code NDArray} */ NDArray gammaln(); /** * Returns the natural logarithmic value of this {@code NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 2.5f}); * jshell&gt; array.log(); * ND: (2) cpu() float32 * [ -inf, 0.9163] * </pre> * * @return the result {@code NDArray} */ NDArray log(); /** * Returns the base 10 logarithm of this {@code NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1000f, 1f, 150f}); * jshell&gt; array.log10(); * ND: (3) cpu() float32 * [3. , 0. , 2.1761] * </pre> * * @return the result {@code NDArray} */ NDArray log10(); /** * Returns the base 2 logarithm of this {@code NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {8, 1f, 5f}); * jshell&gt; array.log2(); * ND: (3) cpu() float32 * [3. , 0. , 2.3219] * </pre> * * @return the result {@code NDArray} */ NDArray log2(); /** * Returns the trigonometric sine of this {@code NDArray} element-wise. * * <p>The input should be in radians (2 Pi radians equals 360 degrees). * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 30f, 45f, 60f, 90f}); * jshell&gt; array = array.mul(Math.PI).div(180f); * jshell&gt; array.sin(); * ND: (5) cpu() float32 * [0. , 0.5 , 0.7071, 0.866 , 1. ] * </pre> * * @return the result {@code NDArray} */ NDArray sin(); /** * Returns the trigonometric cosine of this {@code NDArray} element-wise. * * <p>The input should be in radians (2 Pi radians equals 360 degrees). * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new double[] {0, Math.PI/2, Math.PI}); * jshell&gt; array.cos(); * ND: (3) cpu() float64 * [ 1.0000000e+00, 6.1232340e-17, -1.0000000e+00], * </pre> * * @return the result {@code NDArray} */ NDArray cos(); /** * Returns the trigonometric tangent of this {@code NDArray} element-wise. * * <p>The input should be in radians (2 Pi radians equals 360 degrees). * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new double[] {-Math.PI, Math.PI/2, Math.PI}); * jshell&gt; array.tan(); * ND: (3) cpu() float64 * [ 1.2246468e-16, 1.6331239e+16, -1.2246468e-16], * </pre> * * @return the result {@code NDArray} */ NDArray tan(); /** * Returns the inverse trigonometric sine of this {@code NDArray} element-wise. * * <p>The input should be in the range [-1, 1]. The output is in the closed interval of [-Pi/2, * Pi/2]. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, -1f, 0f}); * jshell&gt; array.asin(); * ND: (3) cpu() float64 * [ 1.5708, -1.5708, 0. ] * </pre> * * @return the result {@code NDArray} */ NDArray asin(); /** * Returns the inverse trigonometric cosine of this {@code NDArray} element-wise. * * <p>The input should be in the range [-1, 1]. The output is in the closed interval of [-Pi/2, * Pi/2]. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, -1f}); * jshell&gt; array.acos(); * ND: (2) cpu() float64 * [0. , 3.1416] * </pre> * * @return the result {@code NDArray} */ NDArray acos(); /** * Returns the inverse trigonometric tangent of this {@code NDArray} element-wise. * * <p>The input should be in the range [-1, 1]. The output is in the closed interval of [-Pi/2, * Pi/2]. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 1f}); * jshell&gt; array.atan(); * ND: (2) cpu() float64 * [0. , 0.7854] * </pre> * * @return the result {@code NDArray} */ NDArray atan(); /** * Returns the element-wise arc-tangent of this/other choosing the quadrant correctly. * * <p>Examples * * <pre> * jshell&gt; NDArray x = manager.create(new float[] {0f, 1f}); * jshell&gt; NDArray y = manager.create(new float[] {0f, -6f}); * jshell&gt; x.atan2(y); * ND: (2) cpu() float64 * [0. , 2.9764] * </pre> * * @param other The other {@code NDArray} * @return the result {@code NDArray} */ NDArray atan2(NDArray other); /** * Returns the hyperbolic sine of this {@code NDArray} element-wise. * * <p>sinh(x)=0.5*(exp(x) - exp(-x)) * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new double[] {0, Math.PI}); * jshell&gt; array.sinh(); * ND: (2) cpu() float64 * [ 0. , 11.5487] * </pre> * * @return the result {@code NDArray} */ NDArray sinh(); /** * Returns the hyperbolic cosine of this {@code NDArray} element-wise. * * <p>cosh(x)=0.5*(exp(x)+exp(-x)) * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new double[] {0, Math.PI}); * jshell&gt; array.cosh(); * ND: (2) cpu() float64 * [ 1. , 11.592 ] * </pre> * * @return the result {@code NDArray} */ NDArray cosh(); /** * Returns the hyperbolic tangent of this {@code NDArray} element-wise. * * <p>tanh(x)=sinh(x)/cosh(x) * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new double[] {0, Math.PI}); * jshell&gt; array.tanh(); * ND: (2) cpu() float64 * [0. , 0.9963] * </pre> * * @return the result {@code NDArray} */ NDArray tanh(); /** * Returns the inverse hyperbolic sine of this {@code NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new double[] {Math.E, 10}); * jshell&gt; array.asinh(); * ND: (2) cpu() float64 * [1.7254, 2.9982] * </pre> * * @return the result {@code NDArray} */ NDArray asinh(); /** * Returns the inverse hyperbolic cosine of this {@code NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new double[] {Math.E, 10}); * jshell&gt; array.acosh(); * ND: (2) cpu() float64 * [1.6575, 2.9932] * </pre> * * @return the result {@code NDArray} */ NDArray acosh(); /** * Returns the inverse hyperbolic tangent of this {@code NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new double[] {0, -0.5}); * jshell&gt; array.atanh(); * ND: (2) cpu() float64 * [ 0. , -0.5493] * </pre> * * @return the result {@code NDArray} */ NDArray atanh(); /** * Converts this {@code NDArray} from radians to degrees element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(6f).mul(Math.PI / 3); * jshell&gt; array.toDegrees(); * ND: (6) cpu() float32 * [ 0., 60., 120., 180., 240., 300.] * </pre> * * @return the result {@code NDArray} */ NDArray toDegrees(); /** * Converts this {@code NDArray} from degrees to radians element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(6f).mul(60); * jshell&gt; array.toRadians(); * ND: (6) cpu() float32 * [0. , 1.0472, 2.0944, 3.1416, 4.1888, 5.236 ] * </pre> * * @return the result {@code NDArray} */ NDArray toRadians(); /* // Operations: Reduction */ /** * Returns the maximum of this {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(4f).reshape(2,2); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[0., 1.], * [2., 3.], * ] * jshell&gt; array.max(); // Maximum of the flattened array * ND: () cpu() float32 * 3. * jshell&gt; array.max().getFloat() // Use getFloat() to get native float * 3.0 * </pre> * * @return the maximum of this {@code NDArray} */ NDArray max(); /** * Returns the maximum of this {@code NDArray} along given axes. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(4f).reshape(2,2); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[0., 1.], * [2., 3.], * ] * jshell&gt; array.max(new int[]{0}); // Maximum along the first axis * ND: (2) cpu() float32 * [2., 3.] * jshell&gt; array.max(new int[]{1}); // Maximum along the second axis * ND: (2) cpu() float32 * [1., 3.] * </pre> * * @param axes the axes along which to operate * @return the maximum of this {@code NDArray} with the specified axes removed from the Shape * containing the max * @see NDArray#max(int[], boolean) */ default NDArray max(int[] axes) { return max(axes, false); } /** * Returns the maximum of this {@code NDArray} along given axes. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(4f).reshape(2,2); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[0., 1.], * [2., 3.], * ] * jshell&gt; array.max(new int[]{0}, true); // Maximum along the first axis and keep dimension * ND: (1, 2) cpu() float32 * [[2., 3.], * ] * jshell&gt; array.max(new int[]{1}, true); // Maximum along the second axis and keep dimension * ND: (2, 1) cpu() float32 * [[1.], * [3.], * ] * </pre> * * @param axes the axes along which to operate * @param keepDims {@code true} to keep the specified axes as size 1 in the output array, {@code * false} to squeeze the values out of the output array. * @return the maximum of this {@code NDArray} */ NDArray max(int[] axes, boolean keepDims); /** * Returns the minimum of this {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(4f).reshape(2,2); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[0., 1.], * [2., 3.], * ] * jshell&gt; array.min(); // Minimum of the flattened array * ND: () cpu() float32 * 0. * jshell&gt; array.min().getFloat(); // Use getFloat() to get native float * 0.0 * </pre> * * @return the minimum of this {@code NDArray} */ NDArray min(); /** * Returns the minimum of this {@code NDArray} along given axes. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(4f).reshape(2,2); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[0., 1.], * [2., 3.], * ] * jshell&gt; array.min(new int[]{0}); // Minimum along the first axis * ND: (2) cpu() float32 * [0., 1.] * jshell&gt; array.min(new int[]{1}); // Minimum along the second axis * ND: (2) cpu() float32 * [0., 2.] * </pre> * * @param axes the axes along which to operate * @return the minimum of this {@code NDArray} with the specified axes removed from the Shape * containing the min * @see NDArray#min(int[], boolean) */ default NDArray min(int[] axes) { return min(axes, false); } /** * Returns the minimum of this {@code NDArray} along given axes. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(4f).reshape(2,2); * jshell&gt; array * ND: (2, 2) cpu() float32 * [[0., 1.], * [2., 3.], * ] * jshell&gt; array.min(new int[]{0}, true) // Minimum along the first axis and keep dimension * ND: (1, 2) cpu() float32 * [[0., 1.], * ] * jshell&gt; array.min(new int[]{1}, true) // Minimum along the second axis and keep dimension * ND: (2, 1) cpu() float32 * [[0.], * [2.], * ] * </pre> * * @param axes the axes along which to operate * @param keepDims {@code true} to keep the specified axes as size 1 in the output array, {@code * false} to squeeze the values out of the output array * @return the minimum of this {@code NDArray} */ NDArray min(int[] axes, boolean keepDims); /** * Returns the sum of this {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0.5f, 1.5f}); * jshell&gt; array.sum(); * ND: () cpu() float32 * 2. * jshell&gt; array.sum().getFloat(); // Use getFloat() to get native float * 2.0 * jshell&gt; NDArray array = manager.create(new float[] {0f, 1f, 0f, 5f}, new Shape(2, 2)); * jshell&gt; array.sum(); * ND: () cpu() float32 * 6. * </pre> * * @return the sum of this {@code NDArray} */ NDArray sum(); /** * Returns the sum of this {@code NDArray} along given axes. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 1f, 0f, 5f}, new Shape(2, 2)); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[0., 1.], * [0., 5.], * ] * jshell&gt; array.sum(new int[] {0}); * ND: (2) cpu() float32 * [0., 6.] * jshell&gt; array.sum(new int[] {1}); * ND: (2) cpu() float32 * [1., 5.] * </pre> * * @param axes the axes along which to operate * @return the sum of this {@code NDArray} with the specified axes removed from the Shape * containing the sum * @see NDArray#sum(int[], boolean) */ default NDArray sum(int[] axes) { return sum(axes, false); } /** * Returns the sum of this {@code NDArray} along given axes. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 1f, 0f, 5f}, new Shape(2, 2)); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[0., 1.], * [0., 5.], * ] * jshell&gt; array.sum(new int[] {0}, true); * ND: (1, 2) cpu() float32 * [[0., 6.], * ] * jshell&gt; array.sum(new int[] {1}, true); * ND: (2, 2) cpu() float32 * [[0., 1.], * [0., 5.], * ] * </pre> * * @param axes the axes along which to operate * @param keepDims {@code true} to keep the specified axes as size 1 in the output array, {@code * false} to squeeze the values out of the output array * @return the sum of this {@code NDArray} */ NDArray sum(int[] axes, boolean keepDims); /** * Returns the cumulative product of elements of input in the dimension dim. For example, if * input is a vector of size N, the result will also be a vector of size N, with elements. [x1, * x1 * x2, x1 * x2 *x3 ...] * * @param axis the axis along which to operate * @return the cumulative product of this */ NDArray cumProd(int axis); /** * Returns the cumulative product of elements of input in the dimension dim. For example, if * input is a vector of size N, the result will also be a vector of size N, with elements. [x1, * x1 * x2, x1 * x2 *x3 ...] * * @param axis the axis along which to operate * @param dataType the datatype of the output * @return the cumulative product of this */ NDArray cumProd(int axis, DataType dataType); /** * Returns the product of this {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {2f, 3f}); * jshell&gt; array.prod(); * ND: () cpu() float32 * 6. * jshell&gt; array.prod().getFloat(); // Use getFloat to get native float * 6.0 * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array.prod(); * ND: () cpu() float32 * 24. * </pre> * * @return the product of this {@code NDArray} */ NDArray prod(); /** * Returns the product of this {@code NDArray} elements over the given axes. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[1., 2.], * [3., 4.], * ] * jshell&gt; array.prod(new int[] {0}); * ND: (2) cpu() float32 * [3., 8.] * jshell&gt; array.prod(new int[] {1}); * ND: (2) cpu() float32 * [ 2., 12.] * </pre> * * @param axes the axes along which to operate * @return the product of this {@code NDArray} with the specified axes removed from the Shape * containing the prod * @see NDArray#prod(int[], boolean) */ default NDArray prod(int[] axes) { return prod(axes, false); } /** * Returns the product of this {@code NDArray} elements over the given axes. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[1., 2.], * [3., 4.], * ] * jshell&gt; array.prod(new int[] {0}, true); * ND: (1, 2) cpu() float32 * [[3., 8.], * ] * jshell&gt; array.prod(new int[] {1}, true); * ND: (2, 1) cpu() float32 * [[ 2.], * [12.], * ] * </pre> * * @param axes the axes along which to operate * @param keepDims {@code true} to keep the specified axes as size 1 in the output array, {@code * false} to squeeze the values out of the output array * @return the product of this {@code NDArray} */ NDArray prod(int[] axes, boolean keepDims); /** * Returns the average of this {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {2f, 3f}); * jshell&gt; array.mean(); * ND: () cpu() float32 * 2.5 * jshell&gt; array.mean().getFloat(); // Use getFloat() to get native float * 2.5 * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array.mean(); * ND: () cpu() float32 * 2.5 * </pre> * * @return the average of this {@code NDArray} */ NDArray mean(); /** * Returns the average of this {@code NDArray} along given axes. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[1., 2.], * [3., 4.], * ] * jshell&gt; array.mean(new int[] {0}); * ND: (2) cpu() float32 * [2., 3.] * jshell&gt; array.mean(new int[] {1}); * ND: (2) cpu() float32 * [1.5, 3.5] * </pre> * * @param axes the axes along which to operate * @return the average of this {@code NDArray} with the specified axes removed from the Shape * containing the mean * @see NDArray#mean(int[], boolean) */ default NDArray mean(int[] axes) { return mean(axes, false); } /** * Returns the average of this {@code NDArray} along given axes. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[1., 2.], * [3., 4.], * ] * jshell&gt; array.mean(new int[] {0}, true); * ND: (1, 2) cpu() float32 * [[2., 3.], * ] * jshell&gt; array.mean(new int[] {1}, true); * ND: (2, 1) cpu() float32 * [[1.5], * [3.5], * ] * </pre> * * @param axes the axes along which to operate * @param keepDims {@code true} to keep the specified axes as size 1 in the output array, {@code * false} to squeeze the values out of the output array * @return the average of this {@code NDArray} */ NDArray mean(int[] axes, boolean keepDims); /** * Performs Lp normalization of the array over specified dimension. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1, 2, 3, 4, 5, 6}, new Shape(2, 3)); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[1., 2., 3.], * [4., 5., 6.], * ] * jshell&gt; array.normalize(); * ND: (2, 3) cpu() float32 * [[0.2673, 0.5345, 0.8018], * [0.4558, 0.5698, 0.6838], * ] * </pre> * * @return the normalized {@code NDArray} */ default NDArray normalize() { return normalize(2, 1, 1e-12); } /** * Performs Lp normalization of the array over specified dimension. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1, 2, 3, 4, 5, 6}, new Shape(2, 3)); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[1., 2., 3.], * [4., 5., 6.], * ] * jshell&gt; array.normalize(2, 1); * ND: (2, 3) cpu() float32 * [[0.2673, 0.5345, 0.8018], * [0.4558, 0.5698, 0.6838], * ] * </pre> * * @param exponent the exponent value in the norm formulation * @param dim the dimension to reduce * @return the normalized {@code NDArray} */ default NDArray normalize(double exponent, long dim) { return normalize(exponent, dim, 1e-12); } /** * Performs Lp normalization of the array over specified dimension. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1, 2, 3, 4, 5, 6}, new Shape(2, 3)); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[1., 2., 3.], * [4., 5., 6.], * ] * jshell&gt; array.normalize(2, 1, 1e-12); * ND: (2, 3) cpu() float32 * [[0.2673, 0.5345, 0.8018], * [0.4558, 0.5698, 0.6838], * ] * </pre> * * @param exponent the exponent value in the norm formulation * @param dim the dimension to reduce * @param eps the small value to avoid division by zero * @return the normalized {@code NDArray} */ NDArray normalize(double exponent, long dim, double eps); /** * Rotates an array by 90 degrees in the plane specified by axes. * * <p>Rotation direction is from the first towards the second axis. * * @param times Number of times the array is rotated by 90 degrees. * @param axes The array is rotated in the plane defined by the axes. Axes must be different. * @return the rotated NDArray */ NDArray rotate90(int times, int[] axes); /** * Returns the sum along diagonals of this {@code NDArray}. * * <p>If this {@code NDArray} is 2-D, the sum along its diagonal is returned. If the {@link * NDArray} has more than two dimensions, then the axes specified by axis1 and axis2 are used to * determine the 2-D sub-arrays whose traces are returned. The {@link Shape} of the resulting * {@link NDArray} is the same as that of a with axis1 and axis2 removed. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.eye(3); * jshell&gt; array; * ND: (3, 3) cpu() float32 * [[1., 0., 0.], * [0., 1., 0.], * [0., 0., 1.], * ] * jshell&gt; array.trace(); * ND: () cpu() float32 * 3. * jshell&gt; NDArray array = manager.arange(8f).reshape(2, 2, 2); * jshell&gt; array; * ND: (2, 2, 2) cpu() float32 * [[[0., 1.], * [2., 3.], * ], * [[4., 5.], * [6., 7.], * ], * ] * jshell&gt; array.trace(); * ND: (2) cpu() float32 * [6., 8.] * </pre> * * @return the sum along diagonals of this {@code NDArray} */ default NDArray trace() { return trace(0, 0, 1); } /** * Returns the sum along diagonals of this {@code NDArray}. * * <p>If this {@code NDArray} is 2-D, the sum along its diagonal with the given offset is * returned, i.e., the sum of elements a[i,i+offset] for all i. If this {@code NDArray} has more * than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D * sub-arrays whose traces are returned. The {@link Shape} of the resulting array is the same as * this {@code NDArray} with axis1 and axis2 removed. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.eye(3); * jshell&gt; array; * ND: (3, 3) cpu() float32 * [[1., 0., 0.], * [0., 1., 0.], * [0., 0., 1.], * ] * jshell&gt; array.trace(1); * ND: () cpu() float32 * 0. * jshell&gt; NDArray array = manager.arange(8f).reshape(2, 2, 2); * jshell&gt; array; * ND: (2, 2, 2) cpu() float32 * [[[0., 1.], * [2., 3.], * ], * [[4., 5.], * [6., 7.], * ], * ] * jshell&gt; array.trace(1); * ND: (2) cpu() float32 * [2., 3.] * </pre> * * @param offset offset of the diagonal from the main diagonal. Can be both positive and * negative. * @return the sum along diagonals of this {@code NDArray} */ default NDArray trace(int offset) { return trace(offset, 0, 1); } /** * Returns the sum along diagonals of this {@code NDArray}. * * <p>If this {@code NDArray} is 2-D, the sum along its diagonal with the given offset is * returned, i.e., the sum of elements a[i,i+offset] for all i. If this {@code NDArray} has more * than two dimensions, then the axes specified by axis1 and axis2 are used to determine the 2-D * sub-arrays whose traces are returned. The {@link Shape} of the resulting array is the same as * this {@code NDArray} with axis1 and axis2 removed. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(8f).reshape(2, 2, 2); * jshell&gt; array; * ND: (2, 2, 2) cpu() float32 * [[[0., 1.], * [2., 3.], * ], * [[4., 5.], * [6., 7.], * ], * ] * jshell&gt; array.trace(1,1,2); * ND: (2) cpu() float32 * [1., 5.] * </pre> * * @param offset offset of the diagonal from the main diagonal. Can be both positive and * negative. * @param axis1 axes to be used as the first axis of the 2-D sub-arrays from which the diagonals * should be taken * @param axis2 axes to be used as the second axis of the 2-D sub-arrays from which the * diagonals should be taken * @return the sum along diagonals of this {@code NDArray} */ NDArray trace(int offset, int axis1, int axis2); /* // Operations: Shapes and Arrays Manipulation */ /** * Splits this {@code NDArray} into multiple sub{@code NDArray}s given sections along first * axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(9f); * jshell&gt; array.split(3).forEach(System.out::println); * ND: (3) cpu() float32 * [0., 1., 2.] * * ND: (3) cpu() float32 * [3., 4., 5.] * * ND: (3) cpu() float32 * [6., 7., 8.] * </pre> * * @param sections this {@code NDArray} will be divided into N (sections) equal {@code NDArray} * @return an {@link NDList} with size(axis) {@code NDArray}s with {@link Shape} {@code * this.shape.remove(axis) } * @see NDArray#split(long, int) */ default NDList split(long sections) { return split(sections, 0); } /** * Splits this {@code NDArray} into multiple sub-{@code NDArray}s given indices along first * axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(8f); * jshell&gt; array.split(new int[] {3, 5, 6}).forEach(System.out::println); * ND: (3) cpu() float32 * [0., 1., 2.] * * ND: (2) cpu() float32 * [3., 4.] * * ND: (1) cpu() float32 * [5.] * * ND: (2) cpu() float32 * [6., 7.] * </pre> * * @param indices the entries indicate where along axis this {@code NDArray} is split. If an * index exceeds the dimension of this {@code NDArray} along axis, an empty sub-{@link * NDArray} is returned correspondingly. * @return an NDList with size(axis) {@code NDArray}s with {@link Shape} {@code * this.shape.remove(axis) } * @see NDArray#split(long[], int) */ default NDList split(long[] indices) { return split(indices, 0); } /** * Splits this {@code NDArray} into multiple sub{@code NDArray}s given sections along the given * axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(18f).reshape(2, 9); * jshell&gt; array; * ND: (2, 9) cpu() float32 * [[ 0., 1., 2., 3., 4., 5., 6., 7., 8.], * [ 9., 10., 11., 12., 13., 14., 15., 16., 17.], * ] * jshell&gt; array.split(3, 1).forEach(System.out::println); * ND: (2, 3) cpu() float32 * [[ 0., 1., 2.], * [ 9., 10., 11.], * ] * * ND: (2, 3) cpu() float32 * [[ 3., 4., 5.], * [12., 13., 14.], * ] * * ND: (2, 3) cpu() float32 * [[ 6., 7., 8.], * [15., 16., 17.], * ] * </pre> * * @param sections this {@code NDArray} will be divided into N (sections) equal arrays along * axis * @param axis the axis to split along * @return an {@link NDList} with numOutputs {@code NDArray}s with {@link Shape} {@code * (this.shape.axis /= axis) } * @throws IllegalArgumentException thrown if the numOutputs does not equally divide the given * axis */ default NDList split(long sections, int axis) { long axisSize = getShape().getShape()[axis]; if (axisSize % sections != 0) { throw new IllegalArgumentException("array split does not result in an equal division"); } long sectionSize = axisSize / sections; long[] indices = LongStream.range(0, sections).map(i -> i * sectionSize).toArray(); return split(indices, axis); } /** * Splits this {@code NDArray} into multiple sub-{@code NDArray}s given indices along given * axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(18f).reshape(2, 9); * jshell&gt; array; * ND: (2, 9) cpu() float32 * [[ 0., 1., 2., 3., 4., 5., 6., 7., 8.], * [ 9., 10., 11., 12., 13., 14., 15., 16., 17.], * ] * jshell&gt; array.split(new int[] {2,4,5}, 1).forEach(System.out::println); * ND: (2, 2) cpu() float32 * [[ 0., 1.], * [ 9., 10.], * ] * * ND: (2, 2) cpu() float32 * [[ 2., 3.], * [11., 12.], * ] * * ND: (2, 1) cpu() float32 * [[ 4.], * [13.], * ] * * ND: (2, 4) cpu() float32 * [[ 5., 6., 7., 8.], * [14., 15., 16., 17.], * ] * </pre> * * @param indices the entries indicate where along axis this {@code NDArray} is split. If an * index exceeds the dimension of this {@code NDArray} along axis, an empty sub-array is * returned correspondingly * @param axis the axis to split along * @return an {@link NDList} with numOutputs {@code NDArray}s with {@link Shape} {@code * (this.shape.axis /= axis) } */ NDList split(long[] indices, int axis); /** * Flattens this {@code NDArray} into a 1-D {@code NDArray} in row-major order. * * <p>To flatten in column-major order, first transpose this {@code NDArray} * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[]{1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array.flatten(); * ND: (4) cpu() float32 * [1., 2., 3., 4.] * </pre> * * @return a 1-D {@code NDArray} of equal size */ NDArray flatten(); /** * Flattens this {@code NDArray} into a partially flatten {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[]{1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f}, new Shape(2, 2, 2)); * jshell&gt; array.flatten(0, 1); * ND: (4) cpu() float32 * [[1., 2], [3., 4.], [5., 6.], [7., 8.]] * </pre> * * @param startDim the first dim to flatten, inclusive * @param endDim the last dim to flatten, inclusive * @return a partially fallen {@code NDArray} */ NDArray flatten(int startDim, int endDim); /** * Computes the one-dimensional discrete Fourier Transform. * * @param length Length of the transformed axis of the output. * @return The truncated or zero-padded input, transformed along the axis indicated by axis, or * the last one if axis is not specified. */ default NDArray fft(long length) { return fft(length, -1); } /** * Computes the one-dimensional discrete Fourier Transform. * * @param length Length of the transformed axis of the output. * @param axis Axis over which to compute the FFT. * @return The truncated or zero-padded input, transformed along the axis indicated by axis, or * the last one if axis is not specified. */ NDArray fft(long length, long axis); /** * Computes the one dimensional inverse discrete Fourier transform. * * @param length Length of the transformed axis of the output. * @param axis Axis over which to compute the IFFT. * @return The truncated or zero-padded input, transformed along the axis indicated by axis, or * the last one if axis is not specified. */ NDArray ifft(long length, long axis); /** * Computes the one dimensional inverse discrete Fourier transform. * * @param length Length of the transformed axis of the output. * @return The truncated or zero-padded input, transformed along the axis indicated by axis, or * the last one if axis is not specified. */ default NDArray ifft(long length) { return ifft(length, -1); } /** * Computes the one dimensional Fourier transform of real-valued input. * * @param length Length of the transformed axis of the output. * @return The truncated or zero-padded input, transformed along the axis indicated by axis, or * the last one if axis is not specified. */ default NDArray rfft(long length) { return rfft(length, -1); } /** * Computes the one dimensional Fourier transform of real-valued input. * * @param length Length of the transformed axis of the output. * @param axis Axis over which to compute the FFT. * @return The truncated or transformed along the axis indicated by axis, or the last one if * axis is not specified. */ NDArray rfft(long length, long axis); /** * Computes the one dimensional inverse Fourier transform of real-valued input. * * @param length Length of the transformed axis of the output. * @param axis Axis over which to compute the IRFFT. * @return The truncated or transformed along the axis indicated by axis, or the last one if * axis is not specified. */ NDArray irfft(long length, long axis); /** * Computes the one dimensional inverse Fourier transform of real-valued input. * * @param length Length of the transformed axis of the output. * @return The truncated or transformed along the axis indicated by axis, or the last one if * axis is not specified. */ default NDArray irfft(long length) { return irfft(length, -1); } /** * Computes the Short Time Fourier Transform (STFT). * * @param nFft size of Fourier transform * @param hopLength the distance between neighboring sliding window frames. Default can be: * floor(n_fft / 4) * @param center whether to pad input on both sides. * @param window Desired window to use. Recommend for HanningWindow * @param returnComplex whether to return a complex tensor, or a real tensor with an extra last * dimension for the real and imaginary components. * @return A NDArray containing the STFT result with shape described above */ default NDArray stft( long nFft, long hopLength, boolean center, NDArray window, boolean returnComplex) { return stft(nFft, hopLength, center, window, false, returnComplex); } /** * Computes the Short Time Fourier Transform (STFT). * * @param nFft size of Fourier transform * @param hopLength the distance between neighboring sliding window frames. Default can be: * floor(n_fft / 4) * @param center whether to pad input on both sides. * @param window Desired window to use. Recommend for HanningWindow * @param normalize controls whether to return the normalized STFT results * @param returnComplex whether to return a complex tensor, or a real tensor with an extra last * dimension for the real and imaginary components. * @return A NDArray containing the STFT result with shape described above */ NDArray stft( long nFft, long hopLength, boolean center, NDArray window, boolean normalize, boolean returnComplex); /** * Computes the two-dimensional Discrete Fourier Transform. * * @param sizes Sizes of the transformed axes of the output. Will be zero-padded or trimmed to * this size. * @param axes Axes over which to compute the 2D-FFT. * @return The truncated or zero-padded input, transformed along the axes. */ NDArray fft2(long[] sizes, long[] axes); /** * Computes the two-dimensional Discrete Fourier Transform along the last 2 axes. * * @param sizes Sizes of the transformed axes of the output. Will be zero-padded or trimmed to * this size. * @return The truncated or zero-padded input, transformed along the last two axes */ default NDArray fft2(long[] sizes) { return fft2(sizes, new long[] {-2, -1}); } /** * Computes the two-dimensional inverse Discrete Fourier Transform. * * @param sizes Sizes of the transformed axes of the output. Will be zero-padded or trimmed to * this size. * @param axes Axes over which to compute the 2D-Inverse-FFT. * @return The truncated or zero-padded input, transformed along the axes. */ NDArray ifft2(long[] sizes, long[] axes); /** * Computes the two-dimensional inverse Discrete Fourier Transform along the last 2 axes. * * @param sizes Sizes of the transformed axes of the output. Will be zero-padded or trimmed to * this size. * @return The truncated or zero-padded input, transformed along the axes. */ default NDArray ifft2(long[] sizes) { return ifft2(sizes, new long[] {-2, -1}); } /** * Pads this {@code NDArray} with the given {@link Shape}. * * <p>Examples * * <pre> * NDArray array = manager.zeros(3, 3, 4, 2); * array.pad(new Shape(1, 1), 0); # pad last dim by 1 on each side * array.getShape() => (3, 3, 4, 4) * </pre> * * @param padding the padding shape, must be even * @return a padded {@code NDArray} * @throws IllegalArgumentException thrown if the given {@code padding} does not match the size * of the current shape */ NDArray pad(Shape padding, double value); /** * Reshapes this {@code NDArray} to the given {@link Shape}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(6f); * jshell&gt; array; * ND: (6) cpu() float32 * [0., 1., 2., 3., 4., 5.] * jshell&gt; array.reshape(2, 3); * ND: (2, 3) cpu() float32 * [[0., 1., 2.], * [3., 4., 5.], * ] * </pre> * * @param newShape the long array to reshape into. Must have equal size to the current shape * @return a reshaped {@code NDArray} * @throws IllegalArgumentException thrown if the given {@link Shape} does not match the size of * the current shape */ default NDArray reshape(long... newShape) { return reshape(new Shape(newShape)); } /** * Reshapes this {@code NDArray} to the given {@link Shape}. * * <p>You can reshape it to match another NDArray by calling {@code a.reshape(b.getShape()) } * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(6f); * jshell&gt; array; * ND: (6) cpu() float32 * [0., 1., 2., 3., 4., 5.] * jshell&gt; array.reshape(new Shape(2, 3)); * ND: (2, 3) cpu() float32 * [[0., 1., 2.], * [3., 4., 5.], * ] * </pre> * * @param shape the {@link Shape} to reshape into. Must have equal size to the current shape * @return a reshaped {@code NDArray} * @throws IllegalArgumentException thrown if the given {@link Shape} does not match the size of * the current shape */ NDArray reshape(Shape shape); /** * Expands the {@link Shape} of a {@code NDArray}. * * <p>Inserts a new axis that will appear at the axis position in the expanded {@code NDArray} * shape. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; array; * ND: (2) cpu() float32 * [1., 2.] * jshell&gt; array.expandDims(0); * ND: (1, 2) cpu() float32 * [[1., 2.], * ] * jshell&gt; array.expandDims(1); * ND: (2, 1) cpu() float32 * [[1.], * [2.], * ] * </pre> * * @param axis the position in the expanded axes where the new axis is placed * @return the result {@code NDArray}. The number of dimensions is one greater than that of the * {@code NDArray} */ NDArray expandDims(int axis); /** * Removes all singleton dimensions from this {@code NDArray} {@link Shape}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 1f, 2f}, new Shape(1, 3, 1)); * jshell&gt; array; * ND: (1, 3, 1) cpu() float32 * [[[0.], * [1.], * [2.], * ], * ] * jshell&gt; array.squeeze(); * ND: (3) cpu() float32 * [0., 1., 2.] * </pre> * * @return a result {@code NDArray} of same size and data without singleton dimensions */ default NDArray squeeze() { long[] shape = getShape().getShape(); return squeeze(IntStream.range(0, shape.length).filter(i -> shape[i] == 1).toArray()); } /** * Removes a singleton dimension at the given axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 1f, 2f}, new Shape(1, 3, 1)); * jshell&gt; array; * ND: (1, 3, 1) cpu() float32 * [[[0.], * [1.], * [2.], * ], * ] * jshell&gt; array.squeeze(0); * ND: (3, 1) cpu() float32 * [[0.], * [1.], * [2.], * ] * jshell&gt; array.squeeze(2); * ND: (1, 3) cpu() float32 * [[0., 1., 2.], * ] * </pre> * * @param axis the axis at which to remove the singleton dimension * @return a result {@code NDArray} of same size and data without the axis at part of the shape * @throws IllegalArgumentException thrown if the given axis is not a singleton dimension */ default NDArray squeeze(int axis) { return squeeze(new int[] {axis}); } /** * Removes singleton dimensions at the given axes. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 1f, 2f}, new Shape(1, 3, 1)); * jshell&gt; array; * ND: (1, 3, 1) cpu() float32 * [[[0.], * [1.], * [2.], * ], * ] * jshell&gt; array.squeeze(new int[] {0, 2}); * ND: (3) cpu() float32 * [0., 1., 2.] * </pre> * * @param axes the axes at which to remove the singleton dimensions * @return a result {@code NDArray} of same size and data without the axes at part of the shape * @throws IllegalArgumentException thrown if any of the given axes are not a singleton * dimension */ NDArray squeeze(int[] axes); /** * Returns the unique elements of the input tensor. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {3f, 1f, 2f, 3f, 1f, 2f, 1f, 3f, 2f}, new Shape(3, 3)); * jshell&gt; array; * ND: (3, 3) cpu() float32 * [[[3., 1., 2.], * [3., 1., 2.], * [1., 3., 2.], * ], * ] * jshell&gt; NDList output = array.unique(0, true, true, true); * jshell&gt; output.get(0); * jshell&gt; output.get(1); * jshell&gt; output.get(2); * * ND: (2, 3) cpu() float32 * [[1., 3., 2.], * [3., 1., 2.], * ] * * ND: (3) cpu() int64 * [ 1, 1, 0] * * ND: (2) cpu() int64 * [ 1, 2] * * </pre> * * @param dim the dimension to apply unique * @param sorted whether to sort the unique elements in ascending order before returning as * output * @param returnInverse return the indices which, fed into the output unique array as indices, * will recover the original array * @param returnCounts return the counts for each unique element * @return An {@code NDList} containing: output (Tensor): the output list of unique elements or * low-rank tensors. inverse_indices (Tensor): (optional) if return_inverse is True, there * will be an additional returned tensor (same shape as input) representing the indices for * where elements in the original input map to in the output; otherwise, this function will * only return a single tensor. counts (Tensor): (optional) if return_counts is True, there * will be an additional returned tensor (same shape as output or output.size(dim), if dim * was specified) representing the number of occurrences for each unique value or tensor. */ NDList unique(Integer dim, boolean sorted, boolean returnInverse, boolean returnCounts); /** * Returns the unique elements of the input tensor. The output is flattened. * * @param sorted whether to sort the unique elements in ascending order before returning as * output * @param returnInverse return the indices which, fed into the output unique array as indices, * will recover the original array * @param returnCounts return the counts for each unique element * @return An {@code NDList} containing: output (Tensor): the output list of unique elements or * low-rank tensors. inverse_indices (Tensor): (optional) if return_inverse is True, there * will be an additional returned tensor (same shape as input) representing the indices for * where elements in the original input map to in the output; otherwise, this function will * only return a single tensor. counts (Tensor): (optional) if return_counts is True, there * will be an additional returned tensor (same shape as output or output.size(dim), if dim * was specified) representing the number of occurrences for each unique value or tensor. */ default NDList unique(boolean sorted, boolean returnInverse, boolean returnCounts) { return unique(null, sorted, returnInverse, returnCounts); } /** * Returns the unique elements of the input tensor. The output is flattened. * * @return An {@code NDList} containing: output (Tensor): the output list of unique elements or * low-rank tensors. inverse_indices (Tensor): (optional) if return_inverse is True, there * will be an additional returned tensor (same shape as input) representing the indices for * where elements in the original input map to in the output; otherwise, this function will * only return a single tensor. counts (Tensor): (optional) if return_counts is True, there * will be an additional returned tensor (same shape as output or output.size(dim), if dim * was specified) representing the number of occurrences for each unique value or tensor. */ default NDList unique() { return unique(null, true, false, false); } /** * Joins a {@code NDArray} along the first axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {0f, 1f}); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 3f}); * jshell&gt; array1.stack(array2) * ND: (2, 2) cpu() float32 * [[0., 1.], * [2., 3.], * ] * </pre> * * @param array the input {@code NDArray} which must have the same {@link Shape}as this {@code * NDArray} * @return the result {@code NDArray}. The stacked {@code NDArray} has one more dimension than * the input {@code NDArray}. */ default NDArray stack(NDArray array) { return stack(array, 0); } /** * Joins a {@code NDArray} along a new axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {0f, 1f}); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 3f}); * jshell&gt; array1.stack(array2, 0); * ND: (2, 2) cpu() float32 * [[0., 1.], * [2., 3.], * ] * jshell&gt; array1.stack(array2, 1); * ND: (2, 2) cpu() float32 * [[0., 2.], * [1., 3.], * ] * </pre> * * @param array the input {@code NDArray} which must have the same {@link Shape}as this {@code * NDArray} * @param axis the axis in the result {@code NDArray} along which the input {@code NDArray} are * stacked * @return the result {@code NDArray}. The stacked {@code NDArray} has one more dimension than * the input {@code NDArray}. */ default NDArray stack(NDArray array, int axis) { return getNDArrayInternal().stack(new NDList(array), axis); } /** * Joins a {@code NDArray} along the first axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {0f, 1f}); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 3f}); * jshell&gt; array1.concat(array2) * ND: (4) cpu() float32 * [0., 1., 2., 3.] * </pre> * * @param array a {@code NDArray} which have the same {@link Shape}as this {@code NDArray}, * except in the dimension corresponding to axis * @return the concatenated {@code NDArray} */ default NDArray concat(NDArray array) { return concat(array, 0); } /** * Joins a {@code NDArray} along an existing axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {0f, 1f}); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 3f}); * jshell&gt; array1.concat(array2, 0); * ND: (4) cpu() float32 * [0., 1., 2., 3.] * </pre> * * @param array a {@code NDArray} which have the same {@link Shape}as this {@code NDArray}, * except in the dimension corresponding to axis * @param axis the axis along which this {@code NDArray} will be joined * @return the concatenated {@code NDArray} */ default NDArray concat(NDArray array, int axis) { return getNDArrayInternal().concat(new NDList(array), axis); } /* // Operations: Logical Op */ /** * Returns the truth value of this {@code NDArray} AND the other {@code NDArray} element-wise. * * <p>The shapes of this {@code NDArray} and the other {@code NDArray} must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new boolean[] {true}); * jshell&gt; NDArray array2 = manager.create(new boolean[] {false}); * jshell&gt; array1.logicalAnd(array2); * ND: (1) cpu() boolean * [false] * jshell&gt; array1 = manager.create(new boolean[] {true, false}); * jshell&gt; array2 = manager.create(new boolean[] {false, false}); * jshell&gt; array1.logicalAnd(array2); * ND: (2) cpu() boolean * [false, false] * </pre> * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; array.gt(1).logicalAnd(array.lt(4)); * ND: (5) cpu() boolean * [false, false, true, true, false] * </pre> * * @param other the other {@code NDArray} to operate on * @return the boolean {@code NDArray} of the logical AND operation applied to the elements of * this {@code NDArray} and the other {@code NDArray} */ NDArray logicalAnd(NDArray other); /** * Computes the truth value of this {@code NDArray} OR the other {@code NDArray} element-wise. * * <p>The shapes of this {@code NDArray} and the other {@code NDArray} must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new boolean[] {true}); * jshell&gt; NDArray array2 = manager.create(new boolean[] {false}); * jshell&gt; array1.logicalOr(array2); * ND: (1) cpu() boolean * [ true] * jshell&gt; array1 = manager.create(new boolean[] {true, false}); * jshell&gt; array2 = manager.create(new boolean[] {false, false}); * jshell&gt; array1.logicalOr(array2); * ND: (2) cpu() boolean * [ true, false] * </pre> * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; array.lt(1).logicalOr(array.gt(3)); * ND: (5) cpu() boolean * [ true, false, false, false, true] * </pre> * * @param other the other {@code NDArray} to operate on * @return the boolean {@code NDArray} of the logical OR operation applied to the elements of * this {@code NDArray} and the other {@code NDArray} */ NDArray logicalOr(NDArray other); /** * Computes the truth value of this {@code NDArray} XOR the other {@code NDArray} element-wise. * * <p>The shapes of this {@code NDArray} and the other {@code NDArray} must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new boolean[] {true}); * jshell&gt; array1.logicalXor(array2); * ND: (1) cpu() boolean * [ true] * jshell&gt; array1 = manager.create(new boolean[] {true, false}); * jshell&gt; array2 = manager.create(new boolean[] {false, false}); * jshell&gt; array1.logicalXor(array2); * ND: (2) cpu() boolean * [ true, false] * </pre> * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; array.lt(1).logicalXor(array.gt(3)); * ND: (5) cpu() boolean * [ true, false, false, false, true] * </pre> * * @param other the other {@code NDArray} to operate on * @return the boolean {@code NDArray} of the logical XOR operation applied to the elements of * this {@code NDArray} and the other {@code NDArray} */ NDArray logicalXor(NDArray other); /** * Computes the truth value of NOT this {@code NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new boolean[] {true}); * jshell&gt; array.logicalNot(); * ND: (1) cpu() boolean * [ false] * </pre> * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; array.lt(1).logicalNot(); * ND: (5) cpu() boolean * [false, true, true, true, true] * </pre> * * @return the boolean {@code NDArray} */ NDArray logicalNot(); /* // Operations: Other */ /** * Returns the indices that would sort this {@code NDArray}. * * <p>Perform an indirect sort along the given axis. It returns a {@code NDArray} of indices of * the same {@link Shape} as this {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {3f, 1f, 2f}); * jshell&gt; array.argSort(); * ND: (3) cpu() int64 * [ 1, 2, 0] * * jshell&gt; array = manager.create(new float[] {0f, 3f, 2f, 2f}, new Shape(2, 2)); * jshell&gt; array.argSort(); * ND: (2, 2) cpu() int64 * [[ 0, 1], * [ 0, 1], * ] * </pre> * * @return a {@code NDArray} of indices corresponding to elements in this {@code NDArray} on the * axis, the output DataType is always {@link DataType#INT64} * @see NDArray#argSort(int, boolean) */ default NDArray argSort() { return argSort(-1, true); } /** * Returns the indices that would sort this {@code NDArray} given the axis. * * <p>Perform an indirect sort along the given axis. It returns a {@code NDArray} of indices of * the same {@link Shape} as this {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 3f, 2f, 2f}, new Shape(2, 2)); * jshell&gt; array.argSort(0); * ND: (2, 2) cpu() int64 * [[ 0, 1], * [ 1, 0], * ] * jshell&gt; array.argSort(1); * ND: (2, 2) cpu() int64 * [[ 0, 1], * [ 0, 1], * ] * </pre> * * @param axis the axis to sort along * @return a {@code NDArray} of indices corresponding to elements in this {@code NDArray} on the * axis, the output DataType is always {@link DataType#INT64} * @see NDArray#argSort(int, boolean) */ default NDArray argSort(int axis) { return argSort(axis, true); } /** * Returns the indices that would sort this {@code NDArray} given the axis. * * <p>Perform an indirect sort along the given axis. It returns a {@code NDArray} of indices of * the same {@link Shape} as this {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 3f, 2f, 2f}, new Shape(2, 2)); * jshell&gt; array.argSort(0, false); * ND: (2, 2) cpu() int64 * [[ 1, 0], * [ 0, 1], * ] * </pre> * * @param axis the axis to sort along * @param ascending whether to sort ascending * @return a {@code NDArray} of indices corresponding to elements in this {@code NDArray} on the * axis, the output DataType is always {@link DataType#INT64} */ NDArray argSort(int axis, boolean ascending); /** * Sorts the flattened {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 4f, 3f, 1f}, new Shape(2, 2)); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[1., 4.], * [3., 1.], * ] * jshell&gt; array.sort(); // sort the flattened array * ND: (2, 2) cpu() float32 * [[1., 4.], * [1., 3.], * ] * </pre> * * @return the sorted {@code NDArray} */ NDArray sort(); /** * Sorts the flattened {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 4f, 3f, 1f}, new Shape(2, 2)); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[1., 4.], * [3., 1.], * ] * jshell&gt; array.sort(0); // sort along the first axis * ND: (2, 2) cpu() float32 * [[1., 1.], * [3., 4.], * ] * </pre> * * @param axis the axis to sort along * @return the sorted {@code NDArray} */ NDArray sort(int axis); /** * Applies the softmax function along the given axis. * * @param axis the axis along which to apply * @return the result {@code NDArray} * @see <a href="https://en.wikipedia.org/wiki/Softmax_function">softmax</a> * @see NDArray#softmax(int) */ NDArray softmax(int axis); /** * Applies the softmax function followed by a logarithm. * * <p>Mathematically equivalent to calling softmax and then log. This single operator is faster * than calling two operators and numerically more stable when computing gradients. * * @param axis the axis along which to apply * @return the result {@code NDArray} */ NDArray logSoftmax(int axis); /** * Returns the cumulative sum of the elements in the flattened {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f, 3f, 4f, 5f, 6f}, new Shape(2, 3)); * jshell&gt; array; * ND: (2, 3) cpu() float32 * [[1., 2., 3.], * [4., 5., 6.], * ] * jshell&gt; array.cumSum(); // cumSum on flattened array * ND: (6) cpu() float32 * [ 1., 3., 6., 10., 15., 21.] * </pre> * * @return the cumulative sum of the elements in the flattened {@code NDArray} */ NDArray cumSum(); /** * Return the cumulative sum of the elements along a given axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f, 3f, 4f, 5f, 6f}, new Shape(2, 3)); * jshell&gt; array; * ND: (2, 3) cpu() float32 * [[1., 2., 3.], * [4., 5., 6.], * ] * jshell&gt; array.cumSum(0); * ND: (2, 3) cpu() float32 * [[1., 2., 3.], * [5., 7., 9.], * ] * jshell&gt; array.cumSum(1); * ND: (2, 3) cpu() float32 * [[ 1., 3., 6.], * [ 4., 9., 15.], * ] * </pre> * * @param axis the axis along which the cumulative sum is computed * @return the cumulative sum along the specified axis */ NDArray cumSum(int axis); /** * Return specified diagonals. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(9.0f).reshape(3, 3); * jshell&gt; array.diagonal(); * ND: (3) cpu() float32 * [0., 4., 8.] * </pre> * * @return specified diagonals */ NDArray diagonal(); /** * Return specified diagonals. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(9.0f).reshape(3, 3); * jshell&gt; array.diagonal(1); * ND: (2) cpu() float32 * [1., 5.] * jshell&gt; array.diagonal(-1); * ND: (2) cpu() float32 * [3., 7.] * </pre> * * @param offset Offset of the diagonal from the main diagonal. Can be positive or negative. * @return specified diagonals */ NDArray diagonal(int offset); /** * Return specified diagonals. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(27f).reshape(3, 3, 3); * jshell&gt; array.diagonal(0, 1, 2); * ND: (3, 3) cpu() float32 * [[ 0., 4., 8.], * [ 9., 13., 17.], * [18., 22., 26.], * ] * </pre> * * @param offset Offset of the diagonal from the main diagonal. Can be positive or negative. * @param axis1 Axis to be used as the first axis of the 2-D sub-arrays from which the diagonals * should be taken. * @param axis2 Axis to be used as the second axis of the 2-D sub-arrays from which the * diagonals should be taken. * @return specified diagonals */ NDArray diagonal(int offset, int axis1, int axis2); /** * Replace the handle of the NDArray with the other. The NDArray used for replacement will be * killed. * * <p>Please use with caution, this method will make the input argument unusable. * * @param replaced the handle provider that will be killed */ void intern(NDArray replaced); /** * Returns the boolean {@code NDArray} with value {@code true} where this {@code NDArray}'s * entries are infinite, or {@code false} where they are not infinite. * * @return the boolean {@code NDArray} with value {@code true} if this {@code NDArray}'s entries * are infinite */ NDArray isInfinite(); /** * Computes the inverse of square {@code NDArray} if it exists. * * @return the inverse of square {@code NDArray}. */ NDArray inverse(); /** * Returns the boolean {@code NDArray} with value {@code true} where this {@code NDArray}'s * entries are NaN, or {@code false} where they are not NaN. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {Float.POSITIVE_INFINITY, 0, Float.NaN}); * jshell&gt; array.isNaN(); * ND: (3) cpu() boolean * [false, false, true] * </pre> * * @return the boolean {@code NDArray} with value {@code true} if this {@code NDArray}'s {@link * NDArray} are NaN */ NDArray isNaN(); /** * Constructs a {@code NDArray} by repeating this {@code NDArray} the number of times given * repeats. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 1f, 2f}); * jshell&gt; array.tile(2); * ND: (6) cpu() float32 * [0., 1., 2., 0., 1., 2.] * </pre> * * @param repeats the number of times to repeat for each dimension * @return a NDArray that has been tiled */ NDArray tile(long repeats); /** * Constructs a {@code NDArray} by repeating this {@code NDArray} the number of times given by * repeats along given axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 1f, 2f}); * jshell&gt; array.tile(1, 2); * ND: (1, 6) cpu() float32 * [[0., 1., 2., 0., 1., 2.], * ] * </pre> * * @param axis the axis to repeat * @param repeats the number of times to repeat for each axis * @return a {@code NDArray} that has been tiled * @throws IllegalArgumentException thrown for invalid axis */ NDArray tile(int axis, long repeats); /** * Constructs a {@code NDArray} by repeating this {@code NDArray} the number of times given by * repeats. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 1f, 2f}); * jshell&gt; array.tile(new long[] {2, 2}); * ND: (2, 6) cpu() float32 * [[0., 1., 2., 0., 1., 2.], * [0., 1., 2., 0., 1., 2.], * ] * </pre> * * @param repeats the number of times to repeat along each axis * @return a {@code NDArray} that has been tiled */ NDArray tile(long[] repeats); /** * Constructs a {@code NDArray} by repeating this {@code NDArray} the number of times to match * the desired shape. * * <p>If the desired {@link Shape}has fewer dimensions than this {@code NDArray}, it will tile * against the last axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 1f, 2f}); * jshell&gt; array.tile(new Shape(6)); * ND: (6) cpu() float32 * [0., 1., 2., 0., 1., 2.] * </pre> * * @param desiredShape the {@link Shape}that should be converted to * @return a {@code NDArray} that has been tiled */ NDArray tile(Shape desiredShape); /** * Repeats element of this {@code NDArray} the number of times given repeats. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 1f, 2f}); * jshell&gt; array.repeat(2); * ND: (6) cpu() float32 * [0., 0., 1., 1., 2., 2.] * </pre> * * @param repeats the number of times to repeat for each axis * @return an {@code NDArray} that has been repeated */ NDArray repeat(long repeats); /** * Repeats element of this {@code NDArray} the number of times given repeats along given axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 1f, 2f, 3f}, new Shape(2, 2)); * jshell&gt; array.repeat(1, 2); * ND: (6) cpu() float32 * [[0., 0., 1., 1.], * [2., 2., 3., 3.]] * </pre> * * @param axis the axis to repeat * @param repeats the number of times to repeat for each axis * @return an {@code NDArray} that has been repeated * @throws IllegalArgumentException thrown for invalid axis */ NDArray repeat(int axis, long repeats); /** * Repeats element of this {@code NDArray} the number of times given repeats along each axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 1f, 2f, 3f}, new Shape(2, 2)); * jshell&gt; array.repeat(new long[] {2, 2}); * ND: (12) cpu() float32 * [0., 0., 0., 0., 1., 1., 1., 1., 2., 2., 2., 2.] * </pre> * * @param repeats the number of times to repeat along each axis * @return a {@code NDArray} that has been repeated */ NDArray repeat(long[] repeats); /** * Repeats element of this {@code NDArray} to match the desired shape. * * <p>If the desired {@link Shape} has fewer dimensions that the array, it will repeat against * the last axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 1f, 2f, 3f}, new Shape(2, 2)); * jshell&gt; array.repeat(new Shape(4, 4)); * ND: (4, 4) cpu() float32 * [[0., 0., 1., 1.], * [0., 0., 1., 1.], * [2., 2., 3., 3.], * [2., 2., 3., 3.], * ] * </pre> * * @param desiredShape the {@link Shape} that should be converted to * @return an {@code NDArray} that has been repeated */ NDArray repeat(Shape desiredShape); /** * Dot product of this {@code NDArray} and the other {@code NDArray}. * * <ul> * <li>If both this {@code NDArray} and the other {@code NDArray} are 1-D {@code NDArray}s, it * is inner product of vectors (without complex conjugation). * <li>If both this {@code NDArray} and the other {@code NDArray} are 2-D {@code NDArray}s, it * is matrix multiplication. * <li>If either this {@code NDArray} or the other {@code NDArray} is 0-D {@code NDArray} * (scalar), it is equivalent to mul. * <li>If this {@code NDArray} is N-D {@code NDArray} and the other {@code NDArray} is 1-D * {@code NDArray}, it is a sum product over the last axis of those. * <li>If this {@code NDArray} is N-D {@code NDArray} and the other {@code NDArray} is M-D * {@code NDArray}(where M&gt;&#61;2), it is a sum product over the last axis of this * {@code NDArray} and the second-to-last axis of the other {@code NDArray} * </ul> * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {1f, 2f, 3f}); * jshell&gt; NDArray array2 = manager.create(new float[] {4f, 5f, 6f}); * jshell&gt; array1.dot(array2); // inner product * ND: () cpu() float32 * 32. * jshell&gt; array1 = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array2 = manager.create(new float[] {5f, 6f, 7f, 8f}, new Shape(2, 2)); * jshell&gt; array1.dot(array2); // matrix multiplication * ND: (2, 2) cpu() float32 * [[19., 22.], * [43., 50.], * ] * jshell&gt; array1 = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array2 = manager.create(5f); * jshell&gt; array1.dot(array2); * ND: (2, 2) cpu() float32 * [[ 5., 10.], * [15., 20.], * ] * jshell&gt; array1 = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array2 = manager.create(new float[] {1f, 2f}); * jshell&gt; array1.dot(array2); * ND: (2) cpu() float32 * [ 5., 11.] * jshell&gt; array1 = manager.create(new float[] {1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f}, new Shape(2, 2, 2)); * jshell&gt; array2 = manager.create(new float[] {1f, 2f, 3f ,4f}, new Shape(2, 2)); * jshell&gt; array1.dot(array2); * ND: (2, 2, 2) cpu() float32 * [[[ 7., 10.], * [15., 22.], * ], * [[23., 34.], * [31., 46.], * ], * ] * </pre> * * @param other the other {@code NDArray} to perform dot product with * @return the result {@code NDArray} */ NDArray dot(NDArray other); /** * Product matrix of this {@code NDArray} and the other {@code NDArray}. * * <p>The behavior depends on the arguments in the following way. * * <ul> * <li>If both this {@code NDArray} and the other {@code NDArray} are 2-D {@code NDArray}s, * they are multiplied like conventional matrices * <li>If either this {@code NDArray} or the other {@code NDArray} is N-D {@code NDArray}, N * &gt; 2 , it is treated as a stack of matrices residing in the last two indexes and * broadcast accordingly. * <li>If this {@code NDArray} is 1-D {@code NDArray}, it is promoted to a matrix by * prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is * removed. * <li>If other {@code NDArray} is 1-D {@code NDArray}, it is promoted to a matrix by * appending a 1 to its dimensions. After matrix multiplication the appended 1 is removed. * </ul> * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {1f, 0f, 0f, 1f}, new Shape(2, 2)); * jshell&gt; NDArray array2 = manager.create(new float[] {4f, 1f, 2f, 2f}, new Shape(2, 2)); * jshell&gt; array1.matMul(array2); // for 2-D arrays, it is the matrix product * ND: (2, 2) cpu() float32 * [[4., 1.], * [2., 2.], * ] * jshell&gt; array1 = manager.create(new float[] {1f, 0f, 0f, 1f}, new Shape(2, 2)); * jshell&gt; array2 = manager.create(new float[] {1f, 2f}); * jshell&gt; array1.matMul(array2); * ND: (2) cpu() float32 * [1., 2.] * jshell&gt; array1 = manager.create(new float[] {1f, 0f, 0f, 1f}, new Shape(2, 2)); * jshell&gt; array2 = manager.create(new float[] {1f, 2f}); * jshell&gt; array1.matMul(array2); * ND: (2) cpu() float32 * [1., 2.] * jshell&gt; array1 = manager.arange(2f * 2f * 4f).reshape(2, 2, 4); * jshell&gt; array2 = manager.arange(2f * 2f * 4f).reshape(2, 4, 2); * jshell&gt; array1.matMul(array2).get("0, 1, 1"); * ND: () cpu() float32 * 98. * </pre> * * @param other the other {@code NDArray} to perform matrix product with * @return the result {@code NDArray} */ NDArray matMul(NDArray other); /** * Batch product matrix of this {@code NDArray} and the other {@code NDArray}. * * @param other the other {@code NDArray} to perform matrix product with * @return the result {@code NDArray} */ NDArray batchMatMul(NDArray other); /** * Clips (limit) the values in this {@code NDArray}. * * <p>Given an interval, values outside the interval are clipped to the interval edges. For * example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values * larger than 1 become 1. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(10f); * jshell&gt; array.clip(1, 8); * ND: (10) cpu() float32 * [1., 1., 2., 3., 4., 5., 6., 7., 8., 8.] * </pre> * * @param min the minimum value * @param max the maximum value * @return an {@code NDArray} with the elements of this {@code NDArray}, but where values &lt; * min are replaced with min, and those &gt; max with max */ NDArray clip(Number min, Number max); /** * Interchanges two axes of this {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f ,3f}, new Shape(1, 3)); * jshell&gt; array; * ND: (1, 3) cpu() float32 * [[1., 2., 3.], * ] * jshell&gt; array.swapAxes(0, 1); * ND: (3, 1) cpu() float32 * [[1.], * [2.], * [3.], * ] * </pre> * * @param axis1 the first axis * @param axis2 the second axis * @return the swapped axes {@code NDArray} */ default NDArray swapAxes(int axis1, int axis2) { int[] dims = IntStream.range(0, getShape().dimension()).toArray(); int tmp = dims[axis1]; dims[axis1] = dims[axis2]; dims[axis2] = tmp; return transpose(dims); } /** * Returns the reverse order of elements in an array along the given axis. * * <p>The shape of the array is preserved, but the elements are reordered. * * @param axes the axes to flip on * @return the newly flipped array */ NDArray flip(int... axes); /** * Returns this {@code NDArray} with axes transposed. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f ,3f, 4f}, new Shape(2, 2)); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[1., 2.], * [3., 4.], * ] * jshell&gt; array.transpose(); * ND: (2, 2) cpu() float32 * [[1., 3.], * [2., 4.], * ] * </pre> * * @return the newly permuted array */ NDArray transpose(); /** * Returns this {@code NDArray} with given axes transposed. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f ,3f, 4f}, new Shape(2, 2)); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[1., 2.], * [3., 4.], * ] * jshell&gt; array.transpose(1, 0); * ND: (2, 2) cpu() float32 * [[1., 3.], * [2., 4.], * ] * jshell&gt; array = manager.arange(8f).reshape(2, 2, 2); * jshell&gt; array; * ND: (2, 2, 2) cpu() float32 * [[[0., 1.], * [2., 3.], * ], * [[4., 5.], * [6., 7.], * ], * ] * jshell&gt; array.transpose(1, 0, 2); * ND: (2, 2, 2) cpu() float32 * [[[0., 1.], * [4., 5.], * ], * [[2., 3.], * [6., 7.], * ], * ] * </pre> * * @param axes the axes to swap to * @return the transposed {@code NDArray} * @throws IllegalArgumentException thrown when passing a axis that is greater than the actual * number of dimensions */ NDArray transpose(int... axes); /** * Broadcasts this {@code NDArray} to be the given shape. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f ,3f, 4f}, new Shape(2, 2)); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[1., 2.], * [3., 4.], * ] * jshell&gt; array.broadcast(new Shape(2, 2, 2)); * ND: (2, 2, 2) cpu() float32 * [[[1., 2.], * [3., 4.], * ], * [[1., 2.], * [3., 4.], * ], * ] * </pre> * * @param shape the new {@link Shape} of this {@code NDArray} * @return the broadcasted {@code NDArray} */ NDArray broadcast(Shape shape); /** * Broadcasts this {@code NDArray} to be the given shape. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f ,3f, 4f}, new Shape(2, 2)); * jshell&gt; array; * ND: (2, 2) cpu() float32 * [[1., 2.], * [3., 4.], * ] * jshell&gt; array.broadcast(2, 2, 2); * ND: (2, 2, 2) cpu() float32 * [[[1., 2.], * [3., 4.], * ], * [[1., 2.], * [3., 4.], * ], * ] * </pre> * * @param shape the new {@link Shape} of this {@code NDArray} * @return the broadcasted {@code NDArray} */ default NDArray broadcast(long... shape) { return broadcast(new Shape(shape)); } /** * Returns the indices of the maximum values into the flattened {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(6f).reshape(2, 3); * jshell&gt; array; * ND: (2, 3) cpu() float32 * [[0., 1., 2.], * [3., 4., 5.], * ] * jshell&gt; array.argMax(); * ND: () cpu() int64 * 5. * </pre> * * @return a {@code NDArray} containing indices */ NDArray argMax(); /** * Returns the indices of the maximum values along given axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(6f).reshape(2, 3); * jshell&gt; array; * ND: (2, 3) cpu() float32 * [[0., 1., 2.], * [3., 4., 5.], * ] * jshell&gt; array.argMax(0); * ND: (3) cpu() int64 * [1, 1, 1] * jshell&gt; array.argMax(1); * ND: (2) cpu() int64 * [2, 2] * </pre> * * @param axis the axis along which to find maximum values * @return a {@code NDArray} containing indices */ NDArray argMax(int axis); /** * Returns (values, indices) of the top k values along given axis. * * @param k the number of returned values * @param axis the axis to sort along, whose shape is reduced to k * @return a {@code NDList} containing (values, indices) */ default NDList topK(int k, int axis) { return topK(k, axis, true, true); } /** * Returns (values, indices) of the top k values along given axis. * * @param k the number of returned values * @param axis the axis to sort along, whose shape is reduced to k * @param largest whether the largest or the smallest * @param sorted whether the sorted or not * @return a {@code NDList} containing (values, indices) */ NDList topK(int k, int axis, boolean largest, boolean sorted); /** * Returns the indices of the minimum values into the flattened {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(6f).reshape(2, 3); * jshell&gt; array; * ND: (2, 3) cpu() float32 * [[0., 1., 2.], * [3., 4., 5.], * ] * jshell&gt; array.argMin(); * ND: () cpu() int64 * 0. * </pre> * * @return a {@code NDArray} containing indices */ NDArray argMin(); /** * Returns the indices of the minimum values along given axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(6f).reshape(2, 3); * jshell&gt; array; * ND: (2, 3) cpu() float32 * [[0., 1., 2.], * [3., 4., 5.], * ] * jshell&gt; array.argMin(0); * ND: (3) cpu() int64 * [0, 0, 0] * jshell&gt; array.argMin(1); * ND: (2) cpu() int64 * [0, 0] * </pre> * * @param axis the axis along which to find minimum values * @return a {@code NDArray} containing indices */ NDArray argMin(int axis); /** * Returns percentile for this {@code NDArray}. * * @param percentile the target percentile in range of 0..100 * @return the result {@code NDArray} */ NDArray percentile(Number percentile); /** * Returns median along given dimension(s). * * @param percentile the target percentile in range of 0..100 * @param axes the dimension to calculate percentile for * @return the result {@code NDArray} NDArray */ NDArray percentile(Number percentile, int[] axes); /** * Returns median value for this {@code NDArray}. * * @return the median {@code NDArray} */ NDArray median(); /** * Returns median value along given axes. * * @param axes the axes along which to perform the median operation * @return the median {@code NDArray} along the specified axes */ NDArray median(int[] axes); // ------------ Sparse methods ------------ /** * Returns a dense representation of the sparse {@code NDArray}. * * @return the result {@code NDArray} */ NDArray toDense(); /** * Returns a sparse representation of {@code NDArray}. * * @param fmt the {@link SparseFormat} of this {@code NDArray} * @return the result {@code NDArray} */ NDArray toSparse(SparseFormat fmt); /** * Returns the indices of elements that are non-zero. * * <p>Note that the behavior is slightly different from numpy.nonzero. Numpy returns a tuple of * NDArray, one for each dimension of NDArray. DJL nonzero returns only one {@code NDArray} with * last dimension containing all dimension of indices. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 1f, 1f, 0f, 1f}); * jshell&gt; array.nonzero(); * ND: (4, 1) cpu() int64 * [[ 0], * [ 1], * [ 2], * [ 4], * ] * jshell&gt; array = manager.create(new float[] {3f, 0f, 0f, 0f, 4f, 0f, 5f, 6f, 0f}).reshape(3, 3); * jshell&gt; array; * ND: (3, 3) cpu() float32 * [[3., 0., 0.], * [0., 4., 0.], * [5., 6., 0.], * ] * jshell&gt; array.nonzero(); * ND: (4, 2) cpu() int64 * [[ 0, 0], * [ 1, 1], * [ 2, 0], * [ 2, 1], * ] * </pre> * * @return the indices of the elements that are non-zero */ NDArray nonzero(); /** * Returns {@code true} if this {@code NDArray} is special case: no-value {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new Shape(2, 0, 1)); * jshell&gt; array; * ND: (2, 0, 1) cpu() float32 * [] * jshell&gt; array.isEmpty(); * true * </pre> * * @return {@code true} if this NDArray is empty */ default boolean isEmpty() { return getShape().size() == 0; } /** * Returns {@code true} if all elements within this {@code NDArray} are non-zero or {@code * true}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new boolean[] {true, false, true, true}, new Shape(2, 2)); * jshell&gt; array.all(); * ND: () cpu() boolean * false * jshell&gt; NDArray array = manager.create(new float[] {-1f, 4f, 5f}); * jshell&gt; array.all(); // all elements are non-zero * ND: () cpu() boolean * true * </pre> * * @return {@code true} if all elements within this {@code NDArray} are non-zero or {@code true} */ default NDArray all() { // result of sum operation is int64 now return toType(DataType.BOOLEAN, false).sum().eq(size()); } /** * Returns {@code true} if any of the elements within this {@code NDArray} are non-zero or * {@code true}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new boolean[] {true, false, true, true}, new Shape(2, 2)); * jshell&gt; array.any(); * ND: () cpu() boolean * true * jshell&gt; NDArray array = manager.create(new float[] {-1, 0, 5}); * jshell&gt; array.any() // all elements are non-zero * ND: () cpu() boolean * true * </pre> * * @return {@code true} if any of the elements within this {@code NDArray} are non-zero or * {@code true} */ default NDArray any() { return toType(DataType.BOOLEAN, false).sum().gt(0); } /** * Returns {@code true} if none of the elements within this {@code NDArray} are non-zero or * {@code true}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new boolean[] {false, false}); * jshell&gt; array.none(); * ND: () cpu() boolean * true * jshell&gt; NDArray array = manager.create(new float[] {-1f, 0f, 5f}); * jshell&gt; array.none() // all elements are non-zero * ND: () cpu() boolean * false * </pre> * * @return {@code true} if none of the elements within this {@code NDArray} are non-zero or * {@code true} */ default NDArray none() { return toType(DataType.BOOLEAN, false).sum().eq(0); } /** * Counts the number of non-zero values in this {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 0f, 1f, 2f, 7f, 0f}, new Shape(2, 3)); * jshell&gt; array.countNonzero() * ND: () cpu() int64 * 3 * </pre> * * @return the number of non-zero values in this {@code NDArray} */ default NDArray countNonzero() { return toType(DataType.BOOLEAN, false).sum(); } /** * Counts the number of non-zero values in this {@code NDArray} along a given axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 0f, 1f, 2f, 7f, 0f}, new Shape(2, 3)); * jshell&gt; array; * ND: (2, 3) cpu() float32 * [[0., 0., 1.], * [2., 7., 0.], * ] * jshell&gt; array.countNonzero(0); * ND: (3) cpu() int64 * [ 1, 1, 1] * jshell&gt; array.countNonzero(1); * ND: (2) cpu() int64 * [ 1, 2] * </pre> * * @param axis the axis to operate on * @return the number of non-zero values in this {@code NDArray} along a given axis */ default NDArray countNonzero(int axis) { return toType(DataType.BOOLEAN, false).sum(new int[] {axis}); } /** * Returns element-wise inverse gauss error function of the {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 0.5f, -1f}); * jshell&gt; array.erfinv(); * ND: (3) cpu() float32 * [0., 0.4769, -inf] * </pre> * * @return The inverse of gauss error of the {@code NDArray}, element-wise */ NDArray erfinv(); /** * Returns element-wise gauss error function of the {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 0.4769f, Float.NEGATIVE_INFINITY}); * jshell&gt; array.erf(); * ND: (3) cpu() float32 * [0., 0.5, -1] * </pre> * * @return The gauss error of the {@code NDArray}, element-wise */ NDArray erf(); /** {@inheritDoc} */ @Override default List<NDArray> getResourceNDArrays() { return Collections.singletonList(this); } /** * Returns an internal representative of Native {@code NDArray}. * * <p>This method should only be used by Engine provider * * @return an internal representative of Native {@code NDArray} */ NDArrayEx getNDArrayInternal(); /** * Returns {@code true} if this NDArray has been released. * * @return {@code true} if this NDArray has been released */ boolean isReleased(); /** * Runs the debug string representation of this {@code NDArray}. * * @return the debug string representation of this {@code NDArray} */ default String toDebugString() { if (isReleased()) { return "This array is already closed"; } if (getDataType() == DataType.STRING) { return Arrays.toString(toStringArray(StandardCharsets.UTF_8)); } return NDFormat.format(this, 100, 10, 10, 20); } /** * Runs the debug string representation of this {@code NDArray}. * * @param withContent true to show the content of NDArray * @return the debug string representation of this {@code NDArray} */ default String toDebugString(boolean withContent) { return toDebugString(1000, 10, 10, 20, withContent); } /** * Runs the debug string representation of this {@code NDArray}. * * @param maxSize the maximum elements to print out * @param maxDepth the maximum depth to print out * @param maxRows the maximum rows to print out * @param maxColumns the maximum columns to print out * @param withContent true to show the content of NDArray * @return the debug string representation of this {@code NDArray} */ default String toDebugString( int maxSize, int maxDepth, int maxRows, int maxColumns, boolean withContent) { if (isReleased()) { return "This array is already closed"; } if (getDataType() == DataType.STRING) { return Arrays.toString(toStringArray(StandardCharsets.UTF_8)); } return NDFormat.format(this, maxSize, maxDepth, maxRows, maxColumns, withContent); } /** {@inheritDoc} */ @Override void close(); /** * Returns the norm of this {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {-3f, -4f}); * jshell&gt; array.norm(); * ND: () cpu() float32 * 5. * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array.norm(); * ND: () cpu() float32 * 5.4472 * </pre> * * @return the norm of this {@code NDArray} */ default NDArray norm() { return norm(false); } /** * Returns the norm of this {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {-3f, -4f}); * jshell&gt; array.norm(new int[] {0}); * ND: () cpu() float32 * 5. * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array.norm(new int[] {0}); * ND: (2) cpu() float32 * [3.1623, 4.4721] * </pre> * * @param axes If axes contains an integer, it specifies the axis of x along which to compute * the vector norms. If axis contains 2 integers, it specifies the axes that hold 2-D * matrices, and the matrix norms of these matrices are computed. * @return the norm of this {@code NDArray} */ default NDArray norm(int[] axes) { return norm(axes, false); } /** * Returns the norm of this {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {-3f, -4f}); * jshell&gt; array.norm(true); * ND: () cpu() float32 * 5. * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array.norm(true); * ND: () cpu() float32 * [[5.4772], * ] * </pre> * * @param keepDims If this is set to True, the axes which are normed over are left in the result * as dimensions with size one. With this option the result will broadcast correctly against * the original x. * @return the norm of this {@code NDArray} */ NDArray norm(boolean keepDims); /** * Returns the norm of this {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array.norm(new int[] {0}, true); * ND: (1, 2) cpu() float32 * [[3.1623, 4.4721], * ] * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array.norm(new int[] {0}, false); * ND: (2) cpu() float32 * [3.1623, 4.4721] * </pre> * * @param axes If axes contains an integer, it specifies the axis of x along which to compute * the vector norms. If axis contains 2 integers, it specifies the axes that hold 2-D * matrices, and the matrix norms of these matrices are computed. * @param keepDims keepDims If this is set to True, the axes which are normed over are left in * the result as dimensions with size one. With this option the result will broadcast * correctly against the original x. * @return the norm of this {@code NDArray} */ default NDArray norm(int[] axes, boolean keepDims) { return norm(2, axes, keepDims); } /** * Returns the norm of this {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array.norm(2, new int[] {0}, true); * ND: (1, 2) cpu() float32 * [[3.1623, 4.4721], * ] * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array.norm(2, new int[] {0}, false); * ND: (2) cpu() float32 * [3.1623, 4.4721] * </pre> * * @param ord Order of the norm. * @param axes If axes contains an integer, it specifies the axis of x along which to compute * the vector norms. If axis contains 2 integers, it specifies the axes that hold 2-D * matrices, and the matrix norms of these matrices are computed. * @param keepDims keepDims If this is set to True, the axes which are normed over are left in * the result as dimensions with size one. With this option the result will broadcast * correctly against the original x. * @return the norm of this {@code NDArray} */ NDArray norm(int ord, int[] axes, boolean keepDims); /** * Returns a one-hot {@code NDArray}. * * <ul> * <li>The locations represented by indices take value 1, while all other locations take value * 0. * <li>If the input {@code NDArray} is rank N, the output will have rank N+1. The new axis is * appended at the end. * <li>If {@code NDArray} is a scalar the output shape will be a vector of length depth. * <li>If {@code NDArray} is a vector of length features, the output shape will be features x * depth. * <li>If {@code NDArray} is a matrix with shape [batch, features], the output shape will be * batch x features x depth. * </ul> * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new int[] {1, 0, 2, 0}); * jshell&gt; array.oneHot(3); * ND: (4, 3) cpu() float32 * [[0., 1., 0.], * [1., 0., 0.], * [0., 0., 1.], * [1., 0., 0.], * ] * jshell&gt; NDArray array = manager.create(new int[][] {{1, 0}, {1, 0}, {2, 0}}); * jshell&gt; array.oneHot(3); * ND: (3, 2, 3) cpu() float32 * [[[0., 1., 0.], * [1., 0., 0.], * ], * [[0., 1., 0.], * [1., 0., 0.], * ], * [[0., 0., 1.], * [1., 0., 0.], * ], * ] * </pre> * * @param depth Depth of the one hot dimension. * @return one-hot encoding of this {@code NDArray} * @see <a * href=https://d2l.djl.ai/chapter_linear-networks/softmax-regression.html#classification-problems>Classification-problems</a> */ default NDArray oneHot(int depth) { return oneHot(depth, 1f, 0f, DataType.FLOAT32); } /** * Returns a one-hot {@code NDArray}. * * <ul> * <li>The locations represented by indices take value 1, while all other locations take value * 0. * <li>If the input {@code NDArray} is rank N, the output will have rank N+1. The new axis is * appended at the end. * <li>If {@code NDArray} is a scalar the output shape will be a vector of length depth. * <li>If {@code NDArray} is a vector of length features, the output shape will be features x * depth. * <li>If {@code NDArray} is a matrix with shape [batch, features], the output shape will be * batch x features x depth. * </ul> * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new int[] {1, 0, 2, 0}); * jshell&gt; array.oneHot(3); * ND: (4, 3) cpu() float32 * [[0., 1., 0.], * [1., 0., 0.], * [0., 0., 1.], * [1., 0., 0.], * ] * jshell&gt; NDArray array = manager.create(new int[][] {{1, 0}, {1, 0}, {2, 0}}); * jshell&gt; array.oneHot(3); * ND: (3, 2, 3) cpu() float32 * [[[0., 1., 0.], * [1., 0., 0.], * ], * [[0., 1., 0.], * [1., 0., 0.], * ], * [[0., 0., 1.], * [1., 0., 0.], * ], * ] * </pre> * * @param depth Depth of the one hot dimension. * @param dataType dataType of the output. * @return one-hot encoding of this {@code NDArray} * @see <a * href=https://d2l.djl.ai/chapter_linear-networks/softmax-regression.html#classification-problems>Classification-problems</a> */ default NDArray oneHot(int depth, DataType dataType) { return oneHot(depth, 1f, 0f, dataType); } /** * Returns a one-hot {@code NDArray}. * * <ul> * <li>The locations represented by indices take value onValue, while all other locations take * value offValue. * <li>If the input {@code NDArray} is rank N, the output will have rank N+1. The new axis is * appended at the end. * <li>If {@code NDArray} is a scalar the output shape will be a vector of length depth. * <li>If {@code NDArray} is a vector of length features, the output shape will be features x * depth. * <li>If {@code NDArray} is a matrix with shape [batch, features], the output shape will be * batch x features x depth. * </ul> * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new int[] {1, 0, 2, 0}); * jshell&gt; array.oneHot(3, 8f, 1f, array.getDataType()); * ND: (4, 3) cpu() int32 * [[ 1, 8, 1], * [ 8, 1, 1], * [ 1, 1, 8], * [ 8, 1, 1], * ] * </pre> * * @param depth Depth of the one hot dimension. * @param onValue The value assigned to the locations represented by indices. * @param offValue The value assigned to the locations not represented by indices. * @param dataType dataType of the output. * @return one-hot encoding of this {@code NDArray} * @see <a * href=https://d2l.djl.ai/chapter_linear-networks/softmax-regression.html#classification-problems>Classification-problems</a> */ NDArray oneHot(int depth, float onValue, float offValue, DataType dataType); /** * Batchwise product of this {@code NDArray} and the other {@code NDArray}. * * <ul> * <li>batchDot is used to compute dot product of x and y when x and y are data in batch, * namely N-D (N greater or equal to 3) arrays in shape of (B0, …, B_i, :, :). For * example, given x with shape (B_0, …, B_i, N, M) and y with shape (B_0, …, B_i, M, K), * the result array will have shape (B_0, …, B_i, N, K), which is computed by: * batch_dot(x,y)[b_0, ..., b_i, :, :] = dot(x[b_0, ..., b_i, :, :], y[b_0, ..., b_i, :, * :]) * </ul> * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.ones(new Shape(2, 1, 4)); * jshell&gt; NDArray array2 = manager.ones(new Shape(2, 4, 6)); * jshell&gt; array1.batchDot(array2); * ND: (2, 1, 6) cpu() float32 * [[[4., 4., 4., 4., 4., 4.], * ], * [[4., 4., 4., 4., 4., 4.], * ], * ] * </pre> * * @param other the other {@code NDArray} to perform batch dot product with * @return the result {@code NDArray} */ NDArray batchDot(NDArray other); /** * Convert a general NDArray to its complex math format. * * <p>example: [10f, 12f] float32 -&gt; [10+12j] in complex64 * * @return the complex NDArray */ NDArray complex(); /** * Convert a complex NDArray to its real math format. example: [10+12j] in complex64 -&gt; [10f, * 12f] float32 * * @return tje real NDArray */ NDArray real(); /** * Conjugate complex array. * * @return Returns a view of input with a flipped conjugate bit. If input has a non-complex * type, this function just returns input. */ NDArray conj(); /** * Calculates the n-th order discrete difference along a given dimension. * * @param n the number of times to apply the difference * @param dim the dimension to perform the difference along * @return a new {@link NDArray} containing the differenced values */ NDArray diff(int n, int dim); }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/ndarray/NDArrayAdapter.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.ndarray; import ai.djl.Device; import ai.djl.ndarray.index.NDIndex; 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 java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.Arrays; import java.util.function.Function; /** * A base implementation of the {@link NDArray} that does nothing. This can be used for overriding * the NDArray with only part of the interface implemented. * * <p>This interface should only be used for the NDArray implementations that do not plan to * implement a large portion of the interface. For the ones that do, they should directly implement * {@link NDArray} so that the unsupported operations are better highlighted in the code. */ public abstract class NDArrayAdapter implements NDArray { private static final String UNSUPPORTED_MSG = "This NDArray implementation does not currently support this operation"; protected NDManager manager; protected NDManager alternativeManager; protected NDArray alternativeArray; protected Shape shape; protected DataType dataType; protected String name; protected boolean isClosed; protected String uid; protected NDArrayAdapter( NDManager manager, NDManager alternativeManager, Shape shape, DataType dataType, String uid) { this.manager = manager; this.alternativeManager = alternativeManager; this.shape = shape; this.dataType = dataType; this.uid = uid; } /** {@inheritDoc} */ @Override public NDManager getManager() { return manager; } /** {@inheritDoc} */ @Override public void attach(NDManager manager) { detach(); this.manager = manager; manager.attachInternal(getUid(), this); alternativeManager = ((BaseNDManager) manager).getAlternativeManager(); if (alternativeManager == null) { // to prevent hybrid engine memory leak alternativeManager = manager; } } /** {@inheritDoc} */ @Override public void tempAttach(NDManager manager) { NDManager original = this.manager; detach(); this.manager = manager; manager.tempAttachInternal(original, getUid(), this); } /** {@inheritDoc} */ @Override public SparseFormat getSparseFormat() { return SparseFormat.DENSE; } /** {@inheritDoc} */ @Override public String getName() { return name; } /** {@inheritDoc} */ @Override public void setName(String name) { this.name = name; } /** {@inheritDoc} */ @Override public String getUid() { return uid; } /** {@inheritDoc} */ @Override public Device getDevice() { return manager.getDevice(); } /** {@inheritDoc} */ @Override public DataType getDataType() { if (isClosed) { throw new IllegalStateException("Native resource has been release already."); } return dataType; } /** {@inheritDoc} */ @Override public Shape getShape() { if (isClosed) { throw new IllegalStateException("Native resource has been release already."); } return shape; } /** {@inheritDoc} */ @Override public NDArray toDevice(Device device, boolean copy) { if (device.equals(getDevice())) { if (copy) { return duplicate(); } return this; } NDArray array = getManager().create(getShape(), getDataType(), device); array.setName(getName()); copyTo(array); return array; } /** {@inheritDoc} */ @Override public NDArray toType(DataType dataType, boolean copy) { if (dataType.equals(getDataType())) { if (copy) { return duplicate(); } return this; } Number[] numbers = toArray(); ByteBuffer bb = toTypeInternal(numbers, dataType); NDArray array = manager.create(bb, getShape(), dataType); array.setName(getName()); return array; } private ByteBuffer toTypeInternal(Number[] numbers, DataType dataType) { int size = dataType.getNumOfBytes() * numbers.length; ByteBuffer bb = manager.allocateDirect(size); for (Number number : numbers) { switch (dataType) { case FLOAT16: case FLOAT32: bb.putFloat(number.floatValue()); break; case FLOAT64: bb.putDouble(number.doubleValue()); break; case INT16: case UINT16: bb.putShort(number.shortValue()); break; case INT32: case UINT32: bb.putInt(number.intValue()); break; case INT64: case UINT64: bb.putLong(number.longValue()); break; case BOOLEAN: case INT8: case UINT8: bb.put(number.byteValue()); break; default: throw new IllegalStateException("Unsupported DataType: " + getDataType()); } } bb.rewind(); return bb; } /** {@inheritDoc} */ @Override public void setRequiresGradient(boolean requiresGrad) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public NDArray getGradient() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public boolean hasGradient() { return false; } /** {@inheritDoc} */ @Override public NDArray stopGradient() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public String[] toStringArray(Charset charset) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public NDArray gather(NDArray index, int axis) { return getAlternativeArray().gather(alternativeManager.from(index), axis); } /** {@inheritDoc} */ @Override public NDArray gatherNd(NDArray index) { return getAlternativeArray().gatherNd(alternativeManager.from(index)); } /** {@inheritDoc} */ @Override public NDArray take(NDManager manager, NDArray index) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public NDArray put(NDArray index, NDArray value) { throw new UnsupportedOperationException("Not implemented yet."); } /** {@inheritDoc} */ @Override public NDArray scatter(NDArray index, NDArray value, int axis) { throw new UnsupportedOperationException("Not implemented yet."); } /** {@inheritDoc} */ @Override public NDArray get(NDIndex index) { return get(alternativeManager, index); } /** {@inheritDoc} */ @Override public void set(Buffer buffer) { NDArray array = manager.create(buffer, getShape(), getDataType()); intern(array); array.detach(); } /** {@inheritDoc} */ @Override public void set(NDIndex index, NDArray value) { getAlternativeArray().set(index, value); set(alternativeArray.toByteBuffer()); } /** {@inheritDoc} */ @Override public void set(NDIndex index, Number value) { getAlternativeArray().set(index, value); set(alternativeArray.toByteBuffer()); } /** {@inheritDoc} */ @Override public void set(NDIndex index, Function<NDArray, NDArray> function) { getAlternativeArray().set(index, function); set(alternativeArray.toByteBuffer()); } /** {@inheritDoc} */ @Override public void set(NDArray index, Number value) { getAlternativeArray().set(index, value); set(alternativeArray.toByteBuffer()); } /** {@inheritDoc} */ @Override public void setScalar(NDIndex index, Number value) { getAlternativeArray().setScalar(index, value); set(alternativeArray.toByteBuffer()); } /** {@inheritDoc} */ @Override public NDArray booleanMask(NDArray index, int axis) { return getAlternativeArray().booleanMask(alternativeManager.from(index), axis); } /** {@inheritDoc} */ @Override public NDArray sequenceMask(NDArray sequenceLength, float value) { return getAlternativeArray().sequenceMask(alternativeManager.from(sequenceLength), value); } /** {@inheritDoc} */ @Override public NDArray sequenceMask(NDArray sequenceLength) { return sequenceMask(sequenceLength, 0); } /** {@inheritDoc} */ @Override public boolean contentEquals(Number number) { return Arrays.stream(toArray()).allMatch(n -> n.equals(number)); } /** {@inheritDoc} */ @Override public boolean contentEquals(NDArray other) { if (other instanceof NDArrayAdapter) { return getShape().equals(other.getShape()) && Arrays.equals(toByteArray(), other.toByteArray()); } return other.contentEquals(this); } /** {@inheritDoc} */ @Override public NDArray eq(Number n) { return getAlternativeArray().eq(n); } /** {@inheritDoc} */ @Override public NDArray eq(NDArray other) { return getAlternativeArray().eq(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray neq(Number n) { return getAlternativeArray().neq(n); } /** {@inheritDoc} */ @Override public NDArray neq(NDArray other) { return getAlternativeArray().neq(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray gt(Number n) { return getAlternativeArray().gt(n); } /** {@inheritDoc} */ @Override public NDArray gt(NDArray other) { return getAlternativeArray().gt(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray gte(Number n) { return getAlternativeArray().gte(n); } /** {@inheritDoc} */ @Override public NDArray gte(NDArray other) { return getAlternativeArray().gte(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray lt(Number n) { return getAlternativeArray().lt(n); } /** {@inheritDoc} */ @Override public NDArray lt(NDArray other) { return getAlternativeArray().lt(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray lte(Number n) { return getAlternativeArray().lte(n); } /** {@inheritDoc} */ @Override public NDArray lte(NDArray other) { return getAlternativeArray().lte(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray add(Number n) { return getAlternativeArray().add(n); } /** {@inheritDoc} */ @Override public NDArray add(NDArray other) { return getAlternativeArray().add(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray sub(Number n) { return getAlternativeArray().sub(n); } /** {@inheritDoc} */ @Override public NDArray sub(NDArray other) { return getAlternativeArray().sub(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray mul(Number n) { return getAlternativeArray().mul(n); } /** {@inheritDoc} */ @Override public NDArray mul(NDArray other) { return getAlternativeArray().mul(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray div(Number n) { return getAlternativeArray().div(n); } /** {@inheritDoc} */ @Override public NDArray div(NDArray other) { return getAlternativeArray().div(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray mod(Number n) { return getAlternativeArray().mod(n); } /** {@inheritDoc} */ @Override public NDArray mod(NDArray other) { return getAlternativeArray().mod(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray pow(Number n) { return getAlternativeArray().pow(n); } /** {@inheritDoc} */ @Override public NDArray pow(NDArray other) { return getAlternativeArray().pow(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray addi(Number n) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public NDArray addi(NDArray other) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public NDArray subi(Number n) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public NDArray subi(NDArray other) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public NDArray muli(Number n) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public NDArray muli(NDArray other) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public NDArray divi(Number n) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public NDArray divi(NDArray other) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public NDArray modi(Number n) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public NDArray modi(NDArray other) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public NDArray powi(Number n) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public NDArray powi(NDArray other) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public NDArray sign() { return getAlternativeArray().sign(); } /** {@inheritDoc} */ @Override public NDArray signi() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public NDArray maximum(Number n) { return getAlternativeArray().maximum(n); } /** {@inheritDoc} */ @Override public NDArray maximum(NDArray other) { return getAlternativeArray().maximum(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray minimum(Number n) { return getAlternativeArray().minimum(n); } /** {@inheritDoc} */ @Override public NDArray minimum(NDArray other) { return getAlternativeArray().minimum(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray neg() { return getAlternativeArray().neg(); } /** {@inheritDoc} */ @Override public NDArray negi() { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } /** {@inheritDoc} */ @Override public NDArray abs() { return getAlternativeArray().abs(); } /** {@inheritDoc} */ @Override public NDArray square() { return getAlternativeArray().square(); } /** {@inheritDoc} */ @Override public NDArray sqrt() { return getAlternativeArray().sqrt(); } /** {@inheritDoc} */ @Override public NDArray cbrt() { return getAlternativeArray().cbrt(); } /** {@inheritDoc} */ @Override public NDArray floor() { return getAlternativeArray().floor(); } /** {@inheritDoc} */ @Override public NDArray ceil() { return getAlternativeArray().ceil(); } /** {@inheritDoc} */ @Override public NDArray round() { return getAlternativeArray().round(); } /** {@inheritDoc} */ @Override public NDArray trunc() { return getAlternativeArray().trunc(); } /** {@inheritDoc} */ @Override public NDArray exp() { return getAlternativeArray().exp(); } /** {@inheritDoc} */ @Override public NDArray gammaln() { return getAlternativeArray().gammaln(); } /** {@inheritDoc} */ @Override public NDArray log() { return getAlternativeArray().log(); } /** {@inheritDoc} */ @Override public NDArray log10() { return getAlternativeArray().log10(); } /** {@inheritDoc} */ @Override public NDArray log2() { return getAlternativeArray().log2(); } /** {@inheritDoc} */ @Override public NDArray sin() { return getAlternativeArray().sin(); } /** {@inheritDoc} */ @Override public NDArray cos() { return getAlternativeArray().cos(); } /** {@inheritDoc} */ @Override public NDArray tan() { return getAlternativeArray().tan(); } /** {@inheritDoc} */ @Override public NDArray asin() { return getAlternativeArray().asin(); } /** {@inheritDoc} */ @Override public NDArray acos() { return getAlternativeArray().acos(); } /** {@inheritDoc} */ @Override public NDArray atan() { return getAlternativeArray().atan(); } /** {@inheritDoc} */ @Override public NDArray atan2(NDArray other) { return getAlternativeArray().atan2(other); } /** {@inheritDoc} */ @Override public NDArray sinh() { return getAlternativeArray().sinh(); } /** {@inheritDoc} */ @Override public NDArray cosh() { return getAlternativeArray().cosh(); } /** {@inheritDoc} */ @Override public NDArray tanh() { return getAlternativeArray().tanh(); } /** {@inheritDoc} */ @Override public NDArray asinh() { return getAlternativeArray().asinh(); } /** {@inheritDoc} */ @Override public NDArray acosh() { return getAlternativeArray().acosh(); } /** {@inheritDoc} */ @Override public NDArray atanh() { return getAlternativeArray().atanh(); } /** {@inheritDoc} */ @Override public NDArray toDegrees() { return getAlternativeArray().toDegrees(); } /** {@inheritDoc} */ @Override public NDArray toRadians() { return getAlternativeArray().toRadians(); } /** {@inheritDoc} */ @Override public NDArray max() { return getAlternativeArray().max(); } /** {@inheritDoc} */ @Override public NDArray max(int[] axes, boolean keepDims) { return getAlternativeArray().max(axes, keepDims); } /** {@inheritDoc} */ @Override public NDArray min() { return getAlternativeArray().min(); } /** {@inheritDoc} */ @Override public NDArray min(int[] axes, boolean keepDims) { return getAlternativeArray().min(axes, keepDims); } /** {@inheritDoc} */ @Override public NDArray sum() { return getAlternativeArray().sum(); } /** {@inheritDoc} */ @Override public NDArray sum(int[] axes, boolean keepDims) { return getAlternativeArray().sum(axes, keepDims); } /** {@inheritDoc} */ @Override public NDArray cumProd(int axis) { return getAlternativeArray().cumProd(axis); } /** {@inheritDoc} */ @Override public NDArray cumProd(int axis, DataType dataType) { return getAlternativeArray().cumProd(axis, dataType); } /** {@inheritDoc} */ @Override public NDArray prod() { return getAlternativeArray().prod(); } /** {@inheritDoc} */ @Override public NDArray prod(int[] axes, boolean keepDims) { return getAlternativeArray().prod(axes, keepDims); } /** {@inheritDoc} */ @Override public NDArray mean() { return getAlternativeArray().mean(); } /** {@inheritDoc} */ @Override public NDArray mean(int[] axes, boolean keepDims) { return getAlternativeArray().mean(axes, keepDims); } /** {@inheritDoc} */ @Override public NDArray normalize(double p, long dim, double eps) { return getAlternativeArray().normalize(p, dim, eps); } /** {@inheritDoc} */ @Override public NDArray rotate90(int times, int[] axes) { return getAlternativeArray().rotate90(times, axes); } /** {@inheritDoc} */ @Override public NDArray trace(int offset, int axis1, int axis2) { return getAlternativeArray().trace(offset, axis1, axis2); } /** {@inheritDoc} */ @Override public NDList split(long sections, int axis) { return getAlternativeArray().split(sections, axis); } /** {@inheritDoc} */ @Override public NDList split(long[] indices, int axis) { return getAlternativeArray().split(indices, axis); } /** {@inheritDoc} */ @Override public NDArray flatten() { return getAlternativeArray().flatten(); } /** {@inheritDoc} */ @Override public NDArray flatten(int startDim, int endDim) { throw new UnsupportedOperationException("Not implemented yet."); } /** {@inheritDoc} */ @Override public NDArray fft(long length, long axis) { throw new UnsupportedOperationException("Not implemented yet."); } /** {@inheritDoc} */ @Override public NDArray ifft(long length, long axis) { throw new UnsupportedOperationException("Not implemented yet."); } /** {@inheritDoc} */ @Override public NDArray rfft(long length, long axis) { throw new UnsupportedOperationException("Not implemented yet."); } /** {@inheritDoc} */ @Override public NDArray irfft(long length, long axis) { throw new UnsupportedOperationException("Not implemented yet."); } /** {@inheritDoc} */ @Override public NDArray stft( long nFft, long hopLength, boolean center, NDArray window, boolean normalize, boolean returnComplex) { throw new UnsupportedOperationException("Not implemented yet."); } /** {@inheritDoc} */ @Override public NDArray fft2(long[] sizes, long[] axes) { throw new UnsupportedOperationException("Not implemented yet."); } /** {@inheritDoc} */ @Override public NDArray pad(Shape padding, double value) { throw new UnsupportedOperationException("Not implemented yet."); } /** {@inheritDoc} */ @Override public NDArray ifft2(long[] sizes, long[] axes) { throw new UnsupportedOperationException("Not implemented yet."); } /** {@inheritDoc} */ @Override public NDArray reshape(Shape shape) { return getAlternativeArray().reshape(shape); } /** {@inheritDoc} */ @Override public NDArray expandDims(int axis) { return getAlternativeArray().expandDims(axis); } /** {@inheritDoc} */ @Override public NDArray squeeze(int[] axes) { return getAlternativeArray().squeeze(axes); } /** {@inheritDoc} */ @Override public NDList unique(Integer dim, boolean sorted, boolean returnInverse, boolean returnCounts) { throw new UnsupportedOperationException("Not implemented yet."); } /** {@inheritDoc} */ @Override public NDArray logicalAnd(NDArray other) { return getAlternativeArray().logicalAnd(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray logicalOr(NDArray other) { return getAlternativeArray().logicalOr(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray logicalXor(NDArray other) { return getAlternativeArray().logicalXor(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray logicalNot() { return getAlternativeArray().logicalNot(); } /** {@inheritDoc} */ @Override public NDArray argSort(int axis, boolean ascending) { return getAlternativeArray().argSort(axis, ascending); } /** {@inheritDoc} */ @Override public NDArray sort() { return getAlternativeArray().sort(); } /** {@inheritDoc} */ @Override public NDArray sort(int axis) { return getAlternativeArray().sort(axis); } /** {@inheritDoc} */ @Override public NDArray softmax(int axis) { return getAlternativeArray().softmax(axis); } /** {@inheritDoc} */ @Override public NDArray logSoftmax(int axis) { return getAlternativeArray().logSoftmax(axis); } /** {@inheritDoc} */ @Override public NDArray cumSum() { return getAlternativeArray().cumSum(); } /** {@inheritDoc} */ @Override public NDArray cumSum(int axis) { return getAlternativeArray().cumSum(axis); } /** {@inheritDoc} */ @Override public NDArray diagonal() { return getAlternativeArray().diagonal(0); } /** {@inheritDoc} */ @Override public NDArray diagonal(int offset) { return getAlternativeArray().diagonal(offset); } /** {@inheritDoc} */ @Override public NDArray diagonal(int offset, int axis1, int axis2) { return getAlternativeArray().diagonal(offset, axis1, axis2); } /** {@inheritDoc} */ @Override public NDArray isInfinite() { return getAlternativeArray().isInfinite(); } /** {@inheritDoc} */ @Override public NDArray isNaN() { return getAlternativeArray().isNaN(); } /** {@inheritDoc} */ @Override public NDArray tile(long repeats) { return getAlternativeArray().tile(repeats); } /** {@inheritDoc} */ @Override public NDArray tile(int axis, long repeats) { return getAlternativeArray().tile(axis, repeats); } /** {@inheritDoc} */ @Override public NDArray tile(long[] repeats) { return getAlternativeArray().tile(repeats); } /** {@inheritDoc} */ @Override public NDArray tile(Shape desiredShape) { return getAlternativeArray().tile(desiredShape); } /** {@inheritDoc} */ @Override public NDArray repeat(long repeats) { return getAlternativeArray().repeat(repeats); } /** {@inheritDoc} */ @Override public NDArray repeat(int axis, long repeats) { return getAlternativeArray().repeat(axis, repeats); } /** {@inheritDoc} */ @Override public NDArray repeat(long[] repeats) { return getAlternativeArray().repeat(repeats); } /** {@inheritDoc} */ @Override public NDArray repeat(Shape desiredShape) { return getAlternativeArray().repeat(desiredShape); } /** {@inheritDoc} */ @Override public NDArray dot(NDArray other) { return getAlternativeArray().dot(other); } /** {@inheritDoc} */ @Override public NDArray matMul(NDArray other) { return getAlternativeArray().matMul(other); } /** {@inheritDoc} */ @Override public NDArray batchMatMul(NDArray other) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ @Override public NDArray xlogy(NDArray other) { throw new UnsupportedOperationException(); } /** {@inheritDoc} */ @Override public NDArray clip(Number min, Number max) { return getAlternativeArray().clip(min, max); } /** {@inheritDoc} */ @Override public NDArray flip(int... axes) { return getAlternativeArray().flip(axes); } /** {@inheritDoc} */ @Override public NDArray transpose() { return getAlternativeArray().transpose(); } /** {@inheritDoc} */ @Override public NDArray transpose(int... axes) { return getAlternativeArray().transpose(axes); } /** {@inheritDoc} */ @Override public NDArray broadcast(Shape shape) { return getAlternativeArray().broadcast(shape); } /** {@inheritDoc} */ @Override public NDArray argMax() { return getAlternativeArray().argMax(); } /** {@inheritDoc} */ @Override public NDArray argMax(int axis) { return getAlternativeArray().argMax(axis); } /** {@inheritDoc} */ @Override public NDList topK(int k, int axis, boolean largest, boolean sorted) { throw new UnsupportedOperationException("Not implemented yet."); } /** {@inheritDoc} */ @Override public NDArray argMin() { return getAlternativeArray().argMin(); } /** {@inheritDoc} */ @Override public NDArray argMin(int axis) { return getAlternativeArray().argMin(axis); } /** {@inheritDoc} */ @Override public NDArray percentile(Number percentile) { return getAlternativeArray().percentile(percentile); } /** {@inheritDoc} */ @Override public NDArray percentile(Number percentile, int[] axes) { return getAlternativeArray().percentile(percentile, axes); } /** {@inheritDoc} */ @Override public NDArray median() { return getAlternativeArray().median(); } /** {@inheritDoc} */ @Override public NDArray median(int[] axes) { return getAlternativeArray().median(axes); } /** {@inheritDoc} */ @Override public NDArray toDense() { return getAlternativeArray().toDense(); } /** {@inheritDoc} */ @Override public NDArray toSparse(SparseFormat fmt) { return getAlternativeArray().toSparse(fmt); } /** {@inheritDoc} */ @Override public NDArray nonzero() { return getAlternativeArray().nonzero(); } /** {@inheritDoc} */ @Override public NDArray erfinv() { return getAlternativeArray().erfinv(); } /** {@inheritDoc} */ @Override public NDArray erf() { return getAlternativeArray().erf(); } /** {@inheritDoc} */ @Override public NDArray inverse() { return getAlternativeArray().inverse(); } /** {@inheritDoc} */ @Override public NDArray norm(boolean keepDims) { return getAlternativeArray().norm(keepDims); } /** {@inheritDoc} */ @Override public NDArray norm(int ord, int[] axes, boolean keepDims) { return getAlternativeArray().norm(ord, axes, keepDims); } /** {@inheritDoc} */ @Override public NDArray oneHot(int depth, float onValue, float offValue, DataType dataType) { return getAlternativeArray().oneHot(depth, onValue, offValue, dataType); } /** {@inheritDoc} */ @Override public NDArray batchDot(NDArray other) { return getAlternativeArray().batchDot(alternativeManager.from(other)); } /** {@inheritDoc} */ @Override public NDArray complex() { throw new UnsupportedOperationException("Not implemented yet."); } /** {@inheritDoc} */ @Override public NDArray real() { throw new UnsupportedOperationException("Not implemented yet."); } /** {@inheritDoc} */ @Override public NDArray conj() { throw new UnsupportedOperationException("Not implemented yet."); } /** {@inheritDoc} */ @Override public NDArray diff(int n, int dim) { throw new UnsupportedOperationException("Not implemented yet."); } /** {@inheritDoc} */ @Override public NDArrayEx getNDArrayInternal() { NDArray array = getAlternativeArray(); if (array instanceof NDArrayAdapter) { throw new UnsupportedOperationException("Operation not supported."); } return array.getNDArrayInternal(); } /** {@inheritDoc} */ @Override public boolean isReleased() { return isClosed; } /** {@inheritDoc} */ @Override public void close() { if (!isClosed) { manager.detachInternal(getUid()); isClosed = true; if (alternativeArray != null) { alternativeArray.close(); alternativeArray = null; } } } /** {@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 String toString() { if (isClosed) { return "This array is already closed"; } return toDebugString(); } private NDArray getAlternativeArray() { if (alternativeManager == null) { throw new UnsupportedOperationException(UNSUPPORTED_MSG); } if (alternativeArray == null) { alternativeArray = alternativeManager.from(this); } else { alternativeArray.set(getDataType().asDataType(toByteBuffer())); } NDScope.unregister(alternativeArray); return alternativeArray; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/ndarray/NDArrays.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.ndarray; import ai.djl.ndarray.types.Shape; import ai.djl.util.Preconditions; import java.util.Arrays; /** This class contains various methods for manipulating NDArrays. */ public final class NDArrays { private NDArrays() {} private static void checkInputs(NDArray[] arrays) { if (arrays == null || arrays.length < 2) { throw new IllegalArgumentException("Passed in arrays must have at least one element"); } if (arrays.length > 2 && Arrays.stream(arrays).skip(1).anyMatch(array -> !arrays[0].shapeEquals(array))) { throw new IllegalArgumentException("The shape of all inputs must be the same"); } } /* // Operations: Element Comparison */ /** * Returns {@code true} if all elements in {@link NDArray} a are equal to {@link NDArray} b. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.ones(new Shape(3)); * jshell&gt; NDArrays.contentEquals(array, 1); // return true instead of boolean NDArray * true * </pre> * * @param a the {@link NDArray} to compare * @param n the number to compare * @return the boolean result */ public static boolean contentEquals(NDArray a, Number n) { if (a == null) { return false; } return a.contentEquals(n); } /** * Returns {@code true} if all elements in {@link NDArray} a are equal to {@link NDArray} b. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.arange(6f).reshape(2, 3); * jshell&gt; NDArray array2 = manager.create(new float[] {0f, 1f, 2f, 3f, 4f, 5f}, new Shape(2, 3)); * jshell&gt; NDArrays.contentEquals(array1, array2); // return true instead of boolean NDArray * true * </pre> * * @param a the {@link NDArray} to compare * @param b the {@link NDArray} to compare * @return the boolean result */ public static boolean contentEquals(NDArray a, NDArray b) { return a.contentEquals(b); } /** * Checks 2 {@link NDArray}s for equal shapes. * * <p>Shapes are considered equal if: * * <ul> * <li>Both {@link NDArray}s have equal rank, and * <li>size(0)...size(rank()-1) are equal for both {@link NDArray}s * </ul> * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.ones(new Shape(1, 2, 3)); * jshell&gt; NDArray array2 = manager.create(new Shape(1, 2, 3)); * jshell&gt; NDArrays.shapeEquals(array1, array2); // return true instead of boolean NDArray * true * </pre> * * @param a the {@link NDArray} to compare * @param b the {@link NDArray} to compare * @return {@code true} if the {@link Shape}s are the same */ public static boolean shapeEquals(NDArray a, NDArray b) { return a.shapeEquals(b); } /** * Returns {@code true} if two {@link NDArray} are element-wise equal within a tolerance. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new double[] {1e10,1e-7}); * jshell&gt; NDArray array2 = manager.create(new double[] {1.00001e10,1e-8}); * jshell&gt; NDArrays.allClose(array1, array2); // return false instead of boolean NDArray * false * jshell&gt; NDArray array1 = manager.create(new double[] {1e10,1e-8}); * jshell&gt; NDArray array2 = manager.create(new double[] {1.00001e10,1e-9}); * jshell&gt; NDArrays.allClose(array1, array2); // return true instead of boolean NDArray * true * </pre> * * @param a the {@link NDArray} to compare with * @param b the {@link NDArray} to compare with * @return the boolean result */ public static boolean allClose(NDArray a, NDArray b) { return a.allClose(b); } /** * Returns {@code true} if two {@link NDArray} are element-wise equal within a tolerance. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new double[] {1e10, 1e-7}); * jshell&gt; NDArray array2 = manager.create(new double[] {1.00001e10, 1e-8}); * jshell&gt; NDArrays.allClose(array1, array2, 1e-05, 1e-08, false); // return false instead of boolean NDArray * false * jshell&gt; NDArray array1 = manager.create(new double[] {1e10, 1e-8}); * jshell&gt; NDArray array2 = manager.create(new double[] {1.00001e10, 1e-9}); * jshell&gt; NDArrays.allClose(array1, array2, 1e-05, 1e-08, false); // return true instead of boolean NDArray * true * jshell&gt; NDArray array1 = manager.create(new float[] {1f, Float.NaN}); * jshell&gt; NDArray array2 = manager.create(new float[] {1f, Float.NaN}); * jshell&gt; NDArrays.allClose(array1, array2, 1e-05, 1e-08, true); // return true instead of boolean NDArray * true * </pre> * * @param a the {@link NDArray} to compare with * @param b the {@link NDArray} to compare with * @param rtol the relative tolerance parameter * @param atol the absolute tolerance parameter * @param equalNan whether to compare NaN’s as equal. If {@code true}, NaN’s in the {@link * NDArray} will be considered equal to NaN’s in the other {@link NDArray} * @return the boolean result */ public static boolean allClose( NDArray a, NDArray b, double rtol, double atol, boolean equalNan) { return a.allClose(b, rtol, atol, equalNan); } /** * Returns the boolean {@link NDArray} for element-wise "Equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.ones(new Shape(1)); * jshell&gt; NDArrays.eq(array, 1); * ND: (1) cpu() boolean * [ true] * </pre> * * @param a the {@link NDArray} to compare * @param n the number to compare * @return the boolean {@link NDArray} for element-wise "Equals" comparison */ public static NDArray eq(NDArray a, Number n) { return a.eq(n); } /** * Returns the boolean {@link NDArray} for element-wise "Equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.ones(new Shape(1)); * jshell&gt; NDArrays.eq(1, array); * ND: (1) cpu() boolean * [ true] * </pre> * * @param n the number to compare * @param a the {@link NDArray} to compare * @return the boolean {@link NDArray} for element-wise "Equals" comparison */ public static NDArray eq(Number n, NDArray a) { return eq(a, n); } /** * Returns the boolean {@link NDArray} for element-wise "Equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {0f, 1f, 3f}); * jshell&gt; NDArray array2 = manager.arange(3f); * jshell&gt; NDArrays.eq(array1, array2); * ND: (3) cpu() boolean * [ true, true, false] * </pre> * * @param a the {@link NDArray} to compare * @param b the {@link NDArray} to compare * @return the boolean {@link NDArray} for element-wise "Equals" comparison */ public static NDArray eq(NDArray a, NDArray b) { return a.eq(b); } /** * Returns the boolean {@link NDArray} for element-wise "Not equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(4f).reshape(2, 2); * jshell&gt; NDArrays.neq(array, 1); * ND: (2, 2) cpu() boolean * [[ true, false], * [ true, true], * ] * </pre> * * @param a the {@link NDArray} to compare * @param n the number to compare * @return the boolean {@link NDArray} for element-wise "Not equals" comparison */ public static NDArray neq(NDArray a, Number n) { return a.neq(n); } /** * Returns the boolean {@link NDArray} for element-wise "Not equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(f4).reshape(2, 2); * jshell&gt; NDArrays.neq(1, array); * ND: (2, 2) cpu() boolean * [[ true, false], * [ true, true], * ] * </pre> * * @param n the number to compare * @param a the {@link NDArray} to compare * @return the boolean {@link NDArray} for element-wise "Not equals" comparison */ public static NDArray neq(Number n, NDArray a) { return neq(a, n); } /** * Returns the boolean {@link NDArray} for element-wise "Not equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {1f, 3f}); * jshell&gt; NDArrays.neq(array1, array2); * ND: (2) cpu() boolean * [false, true] * jshell&gt; NDArray array1 = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {1f, 3f, 1f, 4f}, new Shape(2, 2)); * jshell&gt; NDArrays.neq(array1, array2); // broadcasting * ND: (2, 2) cpu() boolean * [[false, true], * [false, true], * ] * </pre> * * @param a the {@link NDArray} to compare * @param b the {@link NDArray} to compare * @return the boolean {@link NDArray} for element-wise "Not equals" comparison */ public static NDArray neq(NDArray a, NDArray b) { return a.neq(b); } /** * Returns the boolean {@link NDArray} for element-wise "Greater Than" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {4f, 2f}); * jshell&gt; NDArrays.gt(array, 2f); * ND: (2) cpu() boolean * [ true, false] * </pre> * * @param a the {@link NDArray} to compare * @param n the number to be compared against * @return the boolean {@link NDArray} for element-wise "Greater Than" comparison */ public static NDArray gt(NDArray a, Number n) { return a.gt(n); } /** * Returns the boolean {@link NDArray} for element-wise "Greater Than" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {4f, 2f}); * jshell&gt; NDArrays.gt(2f, array); * ND: (2) cpu() boolean * [false, false] * </pre> * * @param n the number to be compared * @param a the NDArray to be compared against * @return the boolean {@link NDArray} for element-wise "Greater Than" comparison */ public static NDArray gt(Number n, NDArray a) { return a.lt(n); } /** * Returns the boolean {@link NDArray} for element-wise "Greater Than" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {4f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 2f}); * jshell&gt; NDArrays.gt(array1, array2); * ND: (2) cpu() boolean * [ true, false] * </pre> * * @param a the {@link NDArray} to be compared * @param b the {@link NDArray} to be compared against * @return the boolean {@link NDArray} for element-wise "Greater Than" comparison */ public static NDArray gt(NDArray a, NDArray b) { return a.gt(b); } /** * Returns the boolean {@link NDArray} for element-wise "Greater or equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {4f, 2f}); * jshell&gt; NDArrays.gte(array, 2); * ND: (2) cpu() boolean * [ true, true] * </pre> * * @param a the {@link NDArray} to be compared * @param n the number to be compared against * @return the boolean {@link NDArray} for element-wise "Greater or equals" comparison */ public static NDArray gte(NDArray a, Number n) { return a.gte(n); } /** * Returns the boolean {@link NDArray} for element-wise "Greater or equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {4f, 2f}); * jshell&gt; NDArrays.gte(2, array); * ND: (2) cpu() boolean * [false, true] * </pre> * * @param n the number to be compared * @param a the {@link NDArray} to be compared against * @return the boolean {@link NDArray} for element-wise "Greater or equals" comparison */ public static NDArray gte(Number n, NDArray a) { return a.lte(n); } /** * Returns the boolean {@link NDArray} for element-wise "Greater or equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {4f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 2f}); * jshell&gt; NDArrays.gte(array1, array2); * ND: (2) cpu() boolean * [ true, true] * </pre> * * @param a the {@link NDArray} to be compared * @param b the {@link NDArray} to be compared against * @return the boolean {@link NDArray} for element-wise "Greater or equals" comparison */ public static NDArray gte(NDArray a, NDArray b) { return a.gte(b); } /** * Returns the boolean {@link NDArray} for element-wise "Less" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.lt(array, 2f); * ND: (2) cpu() boolean * [ true, false] * </pre> * * @param a the {@link NDArray} to be compared * @param n the number to be compared against * @return the boolean {@link NDArray} for element-wise "Less" comparison */ public static NDArray lt(NDArray a, Number n) { return a.lt(n); } /** * Returns the boolean {@link NDArray} for element-wise "Less" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.lt(2f, array); * ND: (2) cpu() boolean * [false, false] * </pre> * * @param n the number to be compared * @param a the {@link NDArray} to be compared against * @return the boolean {@link NDArray} for element-wise "Less" comparison */ public static NDArray lt(Number n, NDArray a) { return a.gt(n); } /** * Returns the boolean {@link NDArray} for element-wise "Less" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 2f}); * jshell&gt; NDArrays.lt(array1, array2); * ND: (2) cpu() boolean * [ true, false] * </pre> * * @param a the {@link NDArray} to be compared * @param b the {@link NDArray} to be compared against * @return the boolean {@link NDArray} for element-wise "Less" comparison */ public static NDArray lt(NDArray a, NDArray b) { return a.lt(b); } /** * Returns the boolean {@link NDArray} for element-wise "Less or equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.lte(array, 2f); * ND: (2) cpu() boolean * [ true, true] * </pre> * * @param a the {@link NDArray} to be compared * @param n the number to be compared against * @return the boolean {@link NDArray} for element-wise "Less or equals" comparison */ public static NDArray lte(NDArray a, Number n) { return a.lte(n); } /** * Returns the boolean {@link NDArray} for element-wise "Less or equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.lte(2f, array); * ND: (2) cpu() boolean * [false, true] * </pre> * * @param n the number to be compared * @param a the {@link NDArray} to be compared against * @return the boolean {@link NDArray} for element-wise "Less or equals" comparison */ public static NDArray lte(Number n, NDArray a) { return a.gte(n); } /** * Returns the boolean {@link NDArray} for element-wise "Less or equals" comparison. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 2f}); * jshell&gt; NDArrays.lte(array1, array2) * ND: (2) cpu() boolean * [ true, true] * </pre> * * @param a the {@link NDArray} to be compared * @param b the {@link NDArray} to be compared against * @return the boolean {@link NDArray} for element-wise "Less or equals" comparison */ public static NDArray lte(NDArray a, NDArray b) { return a.lte(b); } /** * Returns elements chosen from the {@link NDArray} or the other {@link NDArray} depending on * condition. * * <p>Given three {@link NDArray}s, condition, a, and b, returns an {@link NDArray} with the * elements from a or b, depending on whether the elements from condition {@link NDArray} are * {@code true} or {@code false}. If condition has the same shape as a, each element in the * output {@link NDArray} is from this if the corresponding element in the condition is {@code * true}, and from other if {@code false}. * * <p>Note that all non-zero values are interpreted as {@code true} in condition {@link * NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(10f); * jshell&gt; NDArrays.where(array.lt(5), array, array.mul(10)); * ND: (10) cpu() float32 * [ 0., 1., 2., 3., 4., 50., 60., 70., 80., 90.] * jshell&gt; NDArray array = manager.create(new float[]{0f, 1f, 2f, 0f, 2f, 4f, 0f, 3f, 6f}, new Shape(3, 3)); * jshell&gt; NDArrays.where(array.lt(4), array, manager.create(-1f)); * ND: (3, 3) cpu() float32 * [[ 0., 1., 2.], * [ 0., 2., -1.], * [ 0., 3., -1.], * ] * </pre> * * @param condition the condition {@code NDArray} * @param a the first {@link NDArray} * @param b the other {@link NDArray} * @return the result {@link NDArray} */ public static NDArray where(NDArray condition, NDArray a, NDArray b) { return a.getNDArrayInternal().where(condition, b); } /** * Returns the maximum of a {@link NDArray} and a number element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {2f, 3f, 4f}); * jshell&gt; NDArrays.maximum(array, 3f); * ND: (3) cpu() float32 * [3., 3., 4.] * </pre> * * @param a the {@link NDArray} to be compared * @param n the number to be compared * @return the maximum of a {@link NDArray} and a number element-wise */ public static NDArray maximum(NDArray a, Number n) { return a.maximum(n); } /** * Returns the maximum of a number and a {@link NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {2f, 3f, 4f}); * jshell&gt; NDArrays.maximum(3f, array); * ND: (3) cpu() float32 * [3., 3., 4.] * </pre> * * @param n the number to be compared * @param a the {@link NDArray} to be compared * @return the maximum of a number and a {@link NDArray} element-wise */ public static NDArray maximum(Number n, NDArray a) { return maximum(a, n); } /** * Returns the maximum of {@link NDArray} a and {@link NDArray} b element-wise. * * <p>The shapes of {@link NDArray} a and {@link NDArray} b must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {2f, 3f, 4f}); * jshell&gt; NDArray array2 = manager.create(new float[] {1f, 5f, 2f}); * jshell&gt; NDArrays.maximum(array1, array2); * ND: (3) cpu() float32 * [2., 5., 4.] * jshell&gt; NDArray array1 = manager.eye(2); * jshell&gt; NDArray array2 = manager.create(new float[] {0.5f, 2f}); * jshell&gt; NDArrays.maximum(array1, array2); // broadcasting * ND: (2, 2) cpu() float32 * [[1. , 2. ], * [0.5, 2. ], * ] * </pre> * * @param a the {@link NDArray} to be compared * @param b the {@link NDArray} to be compared * @return the maximum of {@link NDArray} a and {@link NDArray} b element-wise */ public static NDArray maximum(NDArray a, NDArray b) { return a.maximum(b); } /** * Returns the minimum of a {@link NDArray} and a number element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {2f, 3f, 4f}); * jshell&gt; NDArrays.minimum(array, 3f); * ND: (3) cpu() float32 * [2., 3., 3.] * </pre> * * @param a the {@link NDArray} to be compared * @param n the number to be compared * @return the minimum of a {@link NDArray} and a number element-wise */ public static NDArray minimum(NDArray a, Number n) { return a.minimum(n); } /** * Returns the minimum of a number and a {@link NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {2f, 3f, 4f}); * jshell&gt; NDArrays.minimum(3f, array); * ND: (3) cpu() float32 * [2., 3., 3.] * </pre> * * @param n the number to be compared * @param a the {@link NDArray} to be compared * @return the minimum of a number and a {@link NDArray} element-wise */ public static NDArray minimum(Number n, NDArray a) { return minimum(a, n); } /** * Returns the minimum of {@link NDArray} a and {@link NDArray} b element-wise. * * <p>The shapes of {@link NDArray} a and {@link NDArray} b must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {2f, 3f, 4f}); * jshell&gt; NDArray array2 = manager.create(new float[] {1f, 5f, 2f}); * jshell&gt; NDArrays.minimum(array1, array2); * ND: (3) cpu() float32 * [1., 3., 2.] * jshell&gt; NDArray array1 = manager.eye(2); * jshell&gt; NDArray array2 = manager.create(new float[] {0.5f, 2f}); * jshell&gt; NDArrays.minimum(array1, array2); // broadcasting * ND: (2, 2) cpu() float32 * [[0.5, 0. ], * [0. , 1. ], * ] * </pre> * * @param a the {@link NDArray} to be compared * @param b the {@link NDArray} to be compared * @return the minimum of {@link NDArray} a and {@link NDArray} b element-wise */ public static NDArray minimum(NDArray a, NDArray b) { return a.minimum(b); } /** * Returns portion of the {@link NDArray} given the index boolean {@link NDArray} along first * axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f, 3f, 4f, 5f, 6f}, new Shape(3, 2)); * jshell&gt; NDArray mask = manager.create(new boolean[] {true, false, true}); * jshell&gt; NDArrays.booleanMask(array, mask); * ND: (2, 2) cpu() float32 * [[1., 2.], * [5., 6.], * ] * </pre> * * @param data the {@link NDArray} to operate on * @param index the boolean {@link NDArray} mask * @return the result {@link NDArray} */ public static NDArray booleanMask(NDArray data, NDArray index) { return booleanMask(data, index, 0); } /** * Returns portion of the {@link NDArray} given the index boolean {@link NDArray} along given * axis. * * @param data the {@link NDArray} to operate on * @param index the boolean {@link NDArray} mask * @param axis an integer that represents the axis of {@link NDArray} to mask from * @return the result {@link NDArray} */ public static NDArray booleanMask(NDArray data, NDArray index, int axis) { return data.booleanMask(index, axis); } /** * Sets all elements of the given {@link NDArray} outside the sequence {@link NDArray} to a * constant value. * * <p>This function takes an n-dimensional input array of the form [batch_size, * max_sequence_length, ....] and returns an array of the same shape. Parameter {@code * sequenceLength} is used to handle variable-length sequences. {@code sequenceLength} should be * an input array of positive ints of dimension [batch_size]. * * @param data the {@link NDArray} to operate on * @param sequenceLength used to handle variable-length sequences * @param value the constant value to be set * @return the result {@link NDArray} */ public static NDArray sequenceMask(NDArray data, NDArray sequenceLength, float value) { return data.sequenceMask(sequenceLength, value); } /** * Sets all elements of the given {@link NDArray} outside the sequence {@link NDArray} to 0. * * <p>This function takes an n-dimensional input array of the form [batch_size, * max_sequence_length, ....] and returns an array of the same shape. Parameter {@code * sequenceLength} is used to handle variable-length sequences. {@code sequenceLength} should be * an input array of positive ints of dimension [batch_size]. * * @param data the {@link NDArray} to operate on * @param sequenceLength used to handle variable-length sequences * @return the result {@link NDArray} */ public static NDArray sequenceMask(NDArray data, NDArray sequenceLength) { return data.sequenceMask(sequenceLength); } /* // Operations: Element Arithmetic */ /** * Adds a number to the {@link NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.add(array, 2f); * ND: (2) cpu() float32 * [3., 4.] * </pre> * * @param a the {@link NDArray} to be added to * @param n the number to add * @return the result {@link NDArray} */ public static NDArray add(NDArray a, Number n) { return a.add(n); } /** * Adds a {@link NDArray} to a number element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.add(2f, array); * ND: (2) cpu() float32 * [3., 4.] * </pre> * * @param n the number to be added to * @param a the {@link NDArray} to add * @return the result {@link NDArray} */ public static NDArray add(Number n, NDArray a) { return a.add(n); } /** * Adds a {@link NDArray} to a {@link NDArray} element-wise. * * <p>The shapes of all of the {@link NDArray}s must be the same. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.add(array, array, array); * ND: (2) cpu() float32 * [3., 6.] * </pre> * * @param arrays the {@link NDArray}s to add together * @return the result {@link NDArray} * @throws IllegalArgumentException arrays must have at least two elements * @throws IllegalArgumentException the shape of all inputs must be the same */ public static NDArray add(NDArray... arrays) { checkInputs(arrays); if (arrays.length == 2) { return arrays[0].add(arrays[1]); } try (NDArray array = NDArrays.stack(new NDList(arrays))) { return array.sum(new int[] {0}); } } /** * Subtracts a number from the {@link NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; array.sub(2f); * ND: (2) cpu() float32 * [-1., 0.] * </pre> * * @param a the {@link NDArray} to be subtracted * @param n the number to subtract from * @return the result {@link NDArray} */ public static NDArray sub(NDArray a, Number n) { return a.sub(n); } /** * Subtracts a {@link NDArray} from a number element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.sub(3f, array); * ND: (2) cpu() float32 * [2., 1.] * </pre> * * @param n the number to be subtracted * @param a the {@link NDArray} to subtract from * @return the result {@link NDArray} */ public static NDArray sub(Number n, NDArray a) { return a.getNDArrayInternal().rsub(n); } /** * Subtracts a {@link NDArray} from a {@link NDArray} element-wise. * * <p>The shapes of {@link NDArray} a and {@link NDArray} b must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.arange(9f).reshape(3, 3); * jshell&gt; NDArray array2 = manager.arange(3f); * jshell&gt; NDArrays.sub(array1, array2); // broadcasting * ND: (3, 3) cpu() float32 * [[0., 0., 0.], * [3., 3., 3.], * [6., 6., 6.], * ] * </pre> * * @param a the {@link NDArray} to be subtracted * @param b the {@link NDArray} to subtract from * @return the result {@link NDArray} */ public static NDArray sub(NDArray a, NDArray b) { return a.sub(b); } /** * Multiplies the {@link NDArray} by a number element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.mul(array, 3f); * ND: (2) cpu() float32 * [3., 6.] * </pre> * * @param a the NDArray to be multiplied * @param n the number to multiply by * @return the result {@link NDArray} */ public static NDArray mul(NDArray a, Number n) { return a.mul(n); } /** * Multiplies a number by a {@link NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.mul(3f, array); * ND: (2) cpu() float32 * [3., 6.] * </pre> * * @param n the number to be multiplied * @param a the {@link NDArray} to multiply by * @return the result {@link NDArray} */ public static NDArray mul(Number n, NDArray a) { return a.mul(n); } /** * Multiplies all of the {@link NDArray}s together element-wise. * * <p>The shapes of all of the {@link NDArray}s must be the same. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.mul(array, array, array); * ND: (2) cpu() float32 * [1., 8.] * </pre> * * @param arrays the {@link NDArray}s to multiply together * @return the result {@link NDArray} * @throws IllegalArgumentException arrays must have at least two elements * @throws IllegalArgumentException the shape of all inputs must be the same */ public static NDArray mul(NDArray... arrays) { checkInputs(arrays); if (arrays.length == 2) { return arrays[0].mul(arrays[1]); } try (NDArray array = NDArrays.stack(new NDList(arrays))) { return array.prod(new int[] {0}); } } /** * Divides the {@link NDArray} by a number element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; NDArrays.div(array, 4f); * ND: (5) cpu() float32 * [0. , 0.25, 0.5 , 0.75, 1. ] * </pre> * * @param a the {@link NDArray} to be be divided * @param n the number to divide by * @return the result {@link NDArray} */ public static NDArray div(NDArray a, Number n) { return a.div(n); } /** * Divides a number by a {@link NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(5f).add(1); * jshell&gt; NDArrays.div(4f, array); * ND: (5) cpu() float32 * [4. , 2. , 1.3333, 1. , 0.8 ] * </pre> * * @param n the number to be be divided * @param a the {@link NDArray} to divide by * @return the result {@link NDArray} */ public static NDArray div(Number n, NDArray a) { return a.getNDArrayInternal().rdiv(n); } /** * Divides a {@link NDArray} by a {@link NDArray} element-wise. * * <p>The shapes of {@link NDArray} a and {@link NDArray} b must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.arange(9f).reshape(3, 3); * jshell&gt; NDArray array2 = manager.ones(new Shape(3)).mul(10); * jshell&gt; NDArrays.div(array1, array2); // broadcasting * ND: (3, 3) cpu() float32 * [[0. , 0.1, 0.2], * [0.3, 0.4, 0.5], * [0.6, 0.7, 0.8], * ] * </pre> * * @param a the {@link NDArray} to be be divided * @param b the {@link NDArray} to divide by * @return the result {@link NDArray} */ public static NDArray div(NDArray a, NDArray b) { return a.div(b); } /** * Returns element-wise remainder of division. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(7f); * jshell&gt; NDArrays.mod(array, 5f); * ND: (7) cpu() float32 * [0., 1., 2., 3., 4., 0., 1.] * </pre> * * @param a the dividend {@link NDArray} * @param n the divisor number * @return the result {@link NDArray} */ public static NDArray mod(NDArray a, Number n) { return a.mod(n); } /** * Returns element-wise remainder of division. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(7f).add(1); * jshell&gt; NDArrays.mod(5f, array); * ND: (7) cpu() float32 * [0., 1., 2., 1., 0., 5., 5.] * </pre> * * @param n the dividend number * @param a the divisor {@link NDArray} * @return the result {@link NDArray} */ public static NDArray mod(Number n, NDArray a) { return a.getNDArrayInternal().rmod(n); } /** * Returns element-wise remainder of division. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {4f, 7f}); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 3f}); * jshell&gt; NDArrays.mod(array1, array2); * ND: (2) cpu() float32 * [0., 1.] * </pre> * * @param a the dividend NDArray * @param b the dividend NDArray * @return the result {@link NDArray} */ public static NDArray mod(NDArray a, NDArray b) { return a.mod(b); } /** * Takes the power of the {@link NDArray} with a number element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; NDArrays.pow(array, 4f); * ND: (6) cpu() float32 * [ 0., 1., 8., 27., 64., 125.] * </pre> * * @param a the {@link NDArray} to be taken the power with * @param n the number to take the power with * @return the result {@link NDArray} */ public static NDArray pow(NDArray a, Number n) { return a.pow(n); } /** * Takes the power of a number with a {@link NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; NDArrays.pow(4f, array); * ND: (5) cpu() float32 * [ 1., 4., 16., 64., 256.] * </pre> * * @param n the number to be taken the power with * @param a the {@link NDArray} to take the power with * @return the result {@link NDArray} */ public static NDArray pow(Number n, NDArray a) { return a.getNDArrayInternal().rpow(n); } /** * Takes the power of a {@link NDArray} with a {@link NDArray} element-wise. * * <p>The shapes of {@link NDArray} a and {@link NDArray} b must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.arange(6f).reshape(3, 2); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 3f}); * jshell&gt; NDArrays.pow(array1, array2); // broadcasting * ND: (3, 2) cpu() float32 * [[ 0., 1.], * [ 4., 27.], * [ 16., 125.], * ] * </pre> * * @param a the {@link NDArray} to be taken the power with * @param b the {@link NDArray} to take the power with * @return the result {@link NDArray} */ public static NDArray pow(NDArray a, NDArray b) { return a.pow(b); } /** * Adds a number to the {@link NDArray} element-wise in place. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.addi(array, 2f); * ND: (2) cpu() float32 * [3., 4.] * jshell&gt; array; * ND: (2) cpu() float32 * [3., 4.] * </pre> * * @param a the {@link NDArray} to be added to * @param n the number to add * @return the result {@link NDArray} */ public static NDArray addi(NDArray a, Number n) { return a.addi(n); } /** * Adds a {@link NDArray} to a number element-wise in place. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.addi(2f, array); * ND: (2) cpu() float32 * [3., 4.] * jshell&gt; array; * ND: (2) cpu() float32 * [3., 4.] * </pre> * * @param a the number to be added to * @param n the {@link NDArray} to add * @return the result {@link NDArray} */ public static NDArray addi(Number n, NDArray a) { return a.addi(n); } /** * Adds all of the {@link NDArray}s together element-wise in place. * * <p>The shapes of all of the {@link NDArray}s must be the same. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {3f, 4f}); * jshell&gt; NDArray array3 = manager.create(new float[] {5f, 6f}); * jshell&gt; NDArrays.addi(array1, array2, array3); * ND: (2) cpu() float32 * [9., 12.] * jshell&gt; array; * ND: (2) cpu() float32 * [9., 12.] * </pre> * * @param arrays the {@link NDArray}s to add together * @return the result {@link NDArray} * @throws IllegalArgumentException arrays must have at least two elements */ public static NDArray addi(NDArray... arrays) { checkInputs(arrays); Arrays.stream(arrays).skip(1).forEachOrdered(array -> arrays[0].addi(array)); return arrays[0]; } /** * Subtracts a number from the {@link NDArray} element-wise in place. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.subi(array, 2f); * ND: (2) cpu() float32 * [-1., 0.] * jshell&gt; array; * ND: (2) cpu() float32 * [-1., 0.] * </pre> * * @param a the {@link NDArray} to be subtracted * @param n the number to subtract from * @return the result {@link NDArray} */ public static NDArray subi(NDArray a, Number n) { return a.subi(n); } /** * Subtracts a {@link NDArray} from a number element-wise in place. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.subi(3f, array); * ND: (2) cpu() float32 * [2., 1.] * jshell&gt; array; * ND: (2) cpu() float32 * [2., 1.] * </pre> * * @param n the number to be subtracted * @param a the {@link NDArray} to subtract from * @return the result {@link NDArray} */ public static NDArray subi(Number n, NDArray a) { return a.getNDArrayInternal().rsubi(n); } /** * Subtracts a {@link NDArray} from a {@link NDArray} element-wise in place. * * <p>The shapes of {@link NDArray} a and {@link NDArray} b must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.arange(9f).reshape(3, 3); * jshell&gt; NDArray array2 = manager.arange(3f); * jshell&gt; NDArrays.subi(array1, array2); // broadcasting * ND: (3, 3) cpu() float32 * [[0., 0., 0.], * [3., 3., 3.], * [6., 6., 6.], * ] * jshell&gt; array1; * [[0., 0., 0.], * [3., 3., 3.], * [6., 6., 6.], * ] * </pre> * * @param a the {@link NDArray} to be subtracted * @param b the {@link NDArray} to subtract from * @return the result {@link NDArray} */ public static NDArray subi(NDArray a, NDArray b) { return a.subi(b); } /** * Multiplies the {@link NDArray} by a number element-wise in place. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.muli(array, 3f); * ND: (2) cpu() float32 * [3., 6.] * jshell&gt; array; * ND: (2) cpu() float32 * [3., 6.] * </pre> * * @param a the NDArray to be multiplied * @param n the number to multiply by * @return the result {@link NDArray} */ public static NDArray muli(NDArray a, Number n) { return a.muli(n); } /** * Multiplies a number by a {@link NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.muli(3f, array); * ND: (2) cpu() float32 * [3., 6.] * jshell&gt; array; * ND: (2) cpu() float32 * [3., 6.] * </pre> * * @param n the number to multiply by * @param a the {@link NDArray} to multiply by * @return the result {@link NDArray} */ public static NDArray muli(Number n, NDArray a) { return a.muli(n); } /** * Multiplies all of the {@link NDArray}s together element-wise in place. * * <p>The shapes of all of the {@link NDArray}s must be the same. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {3f, 4f}); * jshell&gt; NDArray array3 = manager.create(new float[] {5f, 6f}); * jshell&gt; NDArrays.muli(array1, array2, array3); * ND: (2) cpu() float32 * [15., 48.] * jshell&gt; array; * ND: (2) cpu() float32 * [15., 48.] * </pre> * * @param arrays the {@link NDArray}s to multiply together * @return the result {@link NDArray} * @throws IllegalArgumentException arrays must have at least two elements */ public static NDArray muli(NDArray... arrays) { checkInputs(arrays); Arrays.stream(arrays).skip(1).forEachOrdered(array -> arrays[0].muli(array)); return arrays[0]; } /** * Divides a number by a {@link NDArray} element-wise in place. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; NDArrays.divi(array, 4f); * ND: (5) cpu() float32 * [0. , 0.25, 0.5 , 0.75, 1. ] * jshell&gt; array; * ND: (5) cpu() float32 * [0. , 0.25, 0.5 , 0.75, 1. ] * </pre> * * @param a the {@link NDArray} to be be divided * @param n the number to divide by * @return the result {@link NDArray} */ public static NDArray divi(NDArray a, Number n) { return a.divi(n); } /** * Divides a number by a {@link NDArray} element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(5f).add(1); * jshell&gt; NDArrays.divi(4f, array); * ND: (5) cpu() float32 * [4. , 2. , 1.3333, 1. , 0.8 ] * jshell&gt; array; * ND: (5) cpu() float32 * [4. , 2. , 1.3333, 1. , 0.8 ] * </pre> * * @param n the number to be be divided * @param a the {@link NDArray} to divide by * @return the result {@link NDArray} */ public static NDArray divi(Number n, NDArray a) { return a.getNDArrayInternal().rdivi(n); } /** * Divides a {@link NDArray} by a {@link NDArray} element-wise. * * <p>The shapes of {@link NDArray} a and {@link NDArray} b must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.arange(9f).reshape(3, 3); * jshell&gt; NDArray array2 = manager.ones(new Shape(3)).mul(10); * jshell&gt; NDArrays.divi(array1, array2); // broadcasting * ND: (3, 3) cpu() float32 * [[0. , 0.1, 0.2], * [0.3, 0.4, 0.5], * [0.6, 0.7, 0.8], * ] * jshell&gt; array1; * [[0. , 0.1, 0.2], * [0.3, 0.4, 0.5], * [0.6, 0.7, 0.8], * ] * </pre> * * @param a the {@link NDArray} to be be divided * @param b the {@link NDArray} to divide by * @return the result {@link NDArray} */ public static NDArray divi(NDArray a, NDArray b) { return a.divi(b); } /** * Returns element-wise remainder of division in place. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(7f); * jshell&gt; NDArrays.modi(array, 5f); * ND: (7) cpu() float32 * [0., 1., 2., 3., 4., 0., 1.] * jshell&gt; array; * ND: (7) cpu() float32 * [0., 1., 2., 3., 4., 0., 1.] * </pre> * * @param a the dividend {@link NDArray} * @param n the divisor number * @return the result {@link NDArray} */ public static NDArray modi(NDArray a, Number n) { return a.modi(n); } /** * Returns element-wise remainder of division in place. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(7f); * jshell&gt; NDArrays.modi(5f, array); * ND: (7) cpu() float32 * [0., 0., 1., 2., 1., 0., 5.] * jshell&gt; array; * ND: (7) cpu() float32 * [0., 0., 1., 2., 1., 0., 5.] * </pre> * * @param n the dividend number * @param a the divisor {@link NDArray} * @return the result {@link NDArray} */ public static NDArray modi(Number n, NDArray a) { return a.getNDArrayInternal().rmodi(n); } /** * Returns element-wise remainder of division. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {4f, 7f}); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 3f}); * jshell&gt; NDArrays.modi(array1, array2); * ND: (2) cpu() float32 * [0., 1.] * jshell&gt; array1; * ND: (2) cpu() float32 * [0., 1.] * </pre> * * @param a the dividend NDArray * @param b the dividend NDArray * @return the result {@link NDArray} */ public static NDArray modi(NDArray a, NDArray b) { return a.modi(b); } /** * Takes the power of the {@link NDArray} with a number element-wise in place. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; NDArrays.powi(array, 4f); * ND: (6) cpu() float32 * [ 0., 1., 8., 27., 64., 125.] * jshell&gt; array; * ND: (6) cpu() float32 * [ 0., 1., 8., 27., 64., 125.] * </pre> * * @param a the {@link NDArray} to be taken the power with * @param n the number to take the power with * @return the result {@link NDArray} */ public static NDArray powi(NDArray a, Number n) { return a.powi(n); } /** * Takes the power of a number with a {@link NDArray} element-wise in place. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; NDArrays.powi(4f, array); * ND: (5) cpu() float32 * [ 1., 4., 16., 64., 256.] * jshell&gt; array; * ND: (5) cpu() float32 * [ 1., 4., 16., 64., 256.] * </pre> * * @param n the number to be taken the power with * @param a the {@link NDArray} to take the power with * @return the result {@link NDArray} */ public static NDArray powi(Number n, NDArray a) { return a.getNDArrayInternal().rpowi(n); } /** * Takes the power of a {@link NDArray} with a {@link NDArray} element-wise. * * <p>The shapes of {@link NDArray} a and {@link NDArray} b must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.arange(6f).reshape(3, 2); * jshell&gt; NDArray array2 = manager.create(new float[] {2f, 3f}); * jshell&gt; NDArrays.powi(array1, array2); // broadcasting * ND: (3, 2) cpu() float32 * [[ 0., 1.], * [ 4., 27.], * [ 16., 125.], * ] * jshell&gt; array1; * ND: (3, 2) cpu() float32 * [[ 0., 1.], * [ 4., 27.], * [ 16., 125.], * ] * </pre> * * @param a the {@link NDArray} to be taken the power with * @param b the {@link NDArray} to take the power with * @return the result {@link NDArray} */ public static NDArray powi(NDArray a, NDArray b) { return a.powi(b); } /** * Dot product of {@link NDArray} a and {@link NDArray} b. * * <ul> * <li>If both the {@link NDArray} and the other {@link NDArray} are 1-D {@link NDArray}s, it * is inner product of vectors (without complex conjugation). * <li>If both the {@link NDArray} and the other {@link NDArray} are 2-D {@link NDArray}s, it * is matrix multiplication. * <li>If either the {@link NDArray} or the other {@link NDArray} is 0-D {@link NDArray} * (scalar), it is equivalent to mul. * <li>If the {@link NDArray} is N-D {@link NDArray} and the other {@link NDArray} is 1-D * {@link NDArray}, it is a sum product over the last axis of those. * <li>If the {@link NDArray} is N-D {@link NDArray} and the other {@link NDArray} is M-D * {@link NDArray}(where M&gt;&#61;2), it is a sum product over the last axis of this * {@link NDArray} and the second-to-last axis of the other {@link NDArray} * </ul> * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {1f, 2f, 3f}); * jshell&gt; NDArray array2 = manager.create(new float[] {4f, 5f, 6f}); * jshell&gt; NDArrays.dot(array1, array2); // inner product * ND: () cpu() float32 * 32. * jshell&gt; array1 = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array2 = manager.create(new float[] {5f, 6f, 7f, 8f}, new Shape(2, 2)); * jshell&gt; NDArrays.dot(array1, array2); // matrix multiplication * ND: (2, 2) cpu() float32 * [[19., 22.], * [43., 50.], * ] * jshell&gt; array1 = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array2 = manager.create(5f); * jshell&gt; NDArrays.dot(array1, array2); * ND: (2, 2) cpu() float32 * [[ 5., 10.], * [15., 20.], * ] * jshell&gt; array1 = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; array2 = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.dot(array1, array2); * ND: (2) cpu() float32 * [ 5., 11.] * jshell&gt; array1 = manager.create(new float[] {1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f}, new Shape(2, 2, 2)); * jshell&gt; array2 = manager.create(new float[] {1f, 2f, 3f ,4f}, new Shape(2, 2)); * jshell&gt; NDArrays.dot(array1, array2); * ND: (2, 2, 2) cpu() float32 * [[[ 7., 10.], * [15., 22.], * ], * [[23., 34.], * [31., 46.], * ], * ] * </pre> * * @param a the {@link NDArray} to perform dot product with * @param b the {@link NDArray} to perform dot product with * @return the result {@link NDArray} */ public static NDArray dot(NDArray a, NDArray b) { return a.dot(b); } /** * Product matrix of this {@code NDArray} and the other {@code NDArray}. * * <p>The behavior depends on the arguments in the following way. * * <ul> * <li>If both this {@code NDArray} and the other {@code NDArray} are 2-D {@code NDArray}s, * they are multiplied like conventional matrices * <li>If either this {@code NDArray} or the other {@code NDArray} is N-D {@code NDArray}, N * &gt; 2 , it is treated as a stack of matrices residing in the last two indexes and * broadcast accordingly. * <li>If this {@code NDArray} is 1-D {@code NDArray}, it is promoted to a matrix by * prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is * removed. * <li>If other {@code NDArray} is 1-D {@code NDArray}, it is promoted to a matrix by * appending a 1 to its dimensions. After matrix multiplication the appended 1 is removed. * </ul> * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {1f, 0f, 0f, 1f}, new Shape(2, 2)); * jshell&gt; NDArray array2 = manager.create(new float[] {4f, 1f, 2f, 2f}, new Shape(2, 2)); * jshell&gt; NDArrays.matMul(array1, array2); // for 2-D arrays, it is the matrix product * ND: (2, 2) cpu() float32 * [[4., 1.], * [2., 2.], * ] * jshell&gt; array1 = manager.create(new float[] {1f, 0f, 0f, 1f}, new Shape(2, 2)); * jshell&gt; array2 = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.matMul(array1, array2); * ND: (2) cpu() float32 * [1., 2.] * jshell&gt; array1 = manager.create(new float[] {1f, 0f, 0f, 1f}, new Shape(2, 2)); * jshell&gt; array2 = manager.create(new float[] {1f, 2f}); * jshell&gt; NDArrays.matMul(array1, array2); * ND: (2) cpu() float32 * [1., 2.] * jshell&gt; array1 = manager.arange(2f * 2f * 4f).reshape(2, 2, 4); * jshell&gt; array2 = manager.arange(2f * 2f * 4f).reshape(2, 4, 2); * jshell&gt; NDArrays.matMul(array1, array2); * ND: () cpu() float32 * 98. * </pre> * * @param a the {@link NDArray} to perform matrix product with * @param b the {@link NDArray} to perform matrix product with * @return the result {@code NDArray} */ public static NDArray matMul(NDArray a, NDArray b) { return a.matMul(b); } /** * Joins a sequence of {@link NDArray}s in {@link NDList} along the first axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {0f, 1f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {3f, 4f, 5f}); * jshell&gt; NDArray array3 = manager.create(new float[] {6f, 7f, 8f}); * jshell&gt; NDArrays.stack(new NDList(array1, array2, array3)); * ND: (3, 3) cpu() float32 * [[0., 1., 2.], * [3., 4., 5.], * [6., 7., 8.], * ] * </pre> * * @param arrays the input {@link NDList}. Each {@link NDArray} in the {@link NDList} must have * the same shape as the {@link NDArray} * @return the result {@link NDArray}. The stacked {@link NDArray} has one more dimension than * the {@link NDArray}s in {@link NDList} */ public static NDArray stack(NDList arrays) { return stack(arrays, 0); } /** * Joins a sequence of {@link NDArray}s in {@link NDList} along a new axis. * * <p>The axis parameter specifies the index of the new axis in the dimensions of the result. * For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last * dimension. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {0f, 1f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {3f, 4f, 5f}); * jshell&gt; NDArrays.stack(new NDList(array1, array2), 0); * ND: (2, 3) cpu() float32 * [[0., 1., 2.], * [3., 4., 5.], * ] * jshell&gt; NDArray array1 = manager.create(new float[] {0f, 1f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {3f, 4f, 5f}); * jshell&gt; NDArrays.stack(new NDList(array1, array2), 1); * ND: (3, 2) cpu() float32 * [[0., 3.], * [1., 4.], * [2., 5.], * ] * </pre> * * @param arrays the input {@link NDList}. Each {@link NDArray} in the {@link NDList} must have * the same shape as the {@link NDArray} * @param axis the axis in the result {@link NDArray} along which the input {@link NDList} are * stacked * @return the result {@link NDArray}. The stacked {@link NDArray} has one more dimension than * the the {@link NDArray} */ public static NDArray stack(NDList arrays, int axis) { Preconditions.checkArgument(arrays.size() > 0, "need at least one array to stack"); NDArray array = arrays.head(); return array.getNDArrayInternal().stack(arrays.subNDList(1), axis); } /** * Joins a {@link NDList} along the first axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {0f, 1f, 2f}); * jshell&gt; NDArray array2 = manager.create(new float[] {3f, 4f, 5f}); * jshell&gt; NDArray array3 = manager.create(new float[] {6f, 7f, 8f}); * jshell&gt; NDArrays.concat(new NDList(array1, array2, array3)); * ND: (9) cpu() float32 * [0., 1., 2., 3., 4., 5., 6., 7., 8.] * </pre> * * @param arrays a {@link NDList} which have the same shape as the {@link NDArray}, except in * the dimension corresponding to axis * @return the concatenated {@link NDArray} */ public static NDArray concat(NDList arrays) { return concat(arrays, 0); } /** * Joins a {@link NDList} along an existing axis. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new float[] {1f, 2f, 3f, 4f}, new Shape(2, 2)); * jshell&gt; NDArray array2 = manager.create(new float[] {5f, 6f}, new Shape(1, 2)); * jshell&gt; NDArrays.concat(new NDList(array1, array2), 0); * ND: (3, 2) cpu() float32 * [[1., 2.], * [3., 4.], * [5., 6.], * ] * jshell&gt; NDArrays.concat(new NDList(array1, array2.transpose()), 1); * ND: (2, 3) cpu() float32 * [[1., 2., 5.], * [3., 4., 6.], * ] * </pre> * * @param arrays a {@link NDList} which have the same shape as the {@link NDArray}, except in * the dimension corresponding to axis * @param axis the axis along which the {@link NDList} will be joined * @return the concatenated {@link NDArray} */ public static NDArray concat(NDList arrays, int axis) { Preconditions.checkArgument(arrays.size() > 0, "need at least one array to concatenate"); if (arrays.size() == 1) { return arrays.singletonOrThrow().duplicate(); } NDArray array = arrays.head(); return array.getNDArrayInternal().concat(arrays.subNDList(1), axis); } /** * Returns the truth value of {@link NDArray} a AND {@link NDArray} b element-wise. * * <p>The shapes of {@link NDArray} a and {@link NDArray} b must be broadcastable. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new boolean[] {true}); * jshell&gt; NDArray array2 = manager.create(new boolean[] {false}); * jshell&gt; NDArrays.logicalAnd(array1, array2); * ND: (1) cpu() boolean * [false] * jshell&gt; array1 = manager.create(new boolean[] {true, false}); * jshell&gt; array2 = manager.create(new boolean[] {false, false}); * jshell&gt; NDArrays.logicalAnd(array.gt(1), array.lt(4)); * ND: (2) cpu() boolean * [false, false] * </pre> * * @param a the {@link NDArray} to operate on * @param b the {@link NDArray} to operate on * @return the boolean {@link NDArray} of the logical AND operation applied to the elements of * the {@link NDArray} a and {@link NDArray} b */ public static NDArray logicalAnd(NDArray a, NDArray b) { return a.logicalAnd(b); } /** * Computes the truth value of {@link NDArray} a AND {@link NDArray} b element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array1 = manager.create(new boolean[] {true}); * jshell&gt; NDArray array2 = manager.create(new boolean[] {false}); * jshell&gt; NDArrays.logicalOr(array1, array2); * ND: (1) cpu() boolean * [ true] * jshell&gt; array1 = manager.create(new boolean[] {true, false}); * jshell&gt; array2 = manager.create(new boolean[] {false, false}); * jshell&gt; NDArrays.logicalOr(array1, array2); * ND: (2) cpu() boolean * [ true, false] * </pre> * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; NDArrays.logicalOr(array.lt(1), array.gt(3)); * ND: (5) cpu() boolean * [ true, false, false, false, true] * </pre> * * @param a the {@link NDArray} to operate on * @param b the {@link NDArray} to operate on * @return the boolean {@link NDArray} of the logical AND operation applied to the elements of * the {@link NDArray} a and {@link NDArray} b */ public static NDArray logicalOr(NDArray a, NDArray b) { return a.logicalOr(b); } /** * Computes the truth value of {@link NDArray} a AND {@link NDArray} b element-wise. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new boolean[] {true}); * jshell&gt; NDArrays.logicalXor(array1, array2); * ND: (1) cpu() boolean * [ true] * jshell&gt; array1 = manager.create(new boolean[] {true, false}); * jshell&gt; array2 = manager.create(new boolean[] {false, false}); * jshell&gt; NDArrays.logicalXor(array1, array2); * ND: (2) cpu() boolean * [ true, false] * </pre> * * <pre> * jshell&gt; NDArray array = manager.arange(5f); * jshell&gt; NDArrays.logicalXor(array.lt(1), array.gt(3)); * ND: (5) cpu() boolean * [ true, false, false, false, true] * </pre> * * @param a the {@link NDArray} to operate on * @param b the {@link NDArray} to operate on * @return the boolean {@link NDArray} of the logical XOR operation applied to the elements of * the {@link NDArray} a and {@link NDArray} b */ public static NDArray logicalXor(NDArray a, NDArray b) { return a.logicalXor(b); } /** * Returns element-wise inverse gauss error function of the input {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 0.5f, -1f}); * jshell&gt; NDArrays.erfinv(array); * ND: (3) cpu() float32 * [0., 0.4769, -inf] * </pre> * * @param input The input {@code NDArray} * @return The inverse of gauss error of the input, element-wise */ public static NDArray erfinv(NDArray input) { return input.erfinv(); } /** * Returns element-wise gauss error function of the {@code NDArray}. * * <p>Examples * * <pre> * jshell&gt; NDArray array = manager.create(new float[] {0f, 0.4769f, Float.NEGATIVE_INFINITY}); * jshell&gt; array.erf(); * ND: (3) cpu() float32 * [0., 0.5, -1] * </pre> * * @param input The input {@code NDArray} * @return The gauss error of the {@code NDArray}, element-wise */ public static NDArray erf(NDArray input) { return input.erf(); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/ndarray/NDList.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.ndarray; import ai.djl.Device; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.util.JsonUtils; import ai.djl.util.Pair; import com.google.gson.JsonObject; import com.google.gson.annotations.SerializedName; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PushbackInputStream; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; /** * An {@code NDList} represents a sequence of {@link NDArray}s with names. * * <p>Each {@link NDArray} in this list can optionally have a name. You can use the name to look up * an NDArray in the NDList. * * @see NDArray */ public class NDList extends ArrayList<NDArray> implements NDResource, BytesSupplier { private static final long serialVersionUID = 1L; /** Constructs an empty NDList. */ public NDList() {} /** * Constructs an empty NDList with the specified initial capacity. * * @param initialCapacity the initial capacity of the list * @throws IllegalArgumentException if the specified initial capacity is negative */ public NDList(int initialCapacity) { super(initialCapacity); } /** * Constructs and initiates an NDList with the specified {@link NDArray}s. * * @param arrays the {@link NDArray}s */ public NDList(NDArray... arrays) { super(Arrays.asList(arrays)); } /** * Constructs and initiates an NDList with the specified {@link NDArray}s. * * @param other the {@link NDArray}s */ public NDList(Collection<NDArray> other) { super(other); } /** * Decodes NDList from byte array. * * @param manager manager assigned to {@link NDArray} * @param byteArray byte array to load from * @return {@code NDList} */ public static NDList decode(NDManager manager, byte[] byteArray) { if (byteArray.length < 9) { throw new IllegalArgumentException("Invalid input length: " + byteArray.length); } try { if (byteArray[0] == 'P' && byteArray[1] == 'K') { return decodeNumpy(manager, new ByteArrayInputStream(byteArray)); } else if (byteArray[0] == (byte) 0x93 && byteArray[1] == 'N' && byteArray[2] == 'U' && byteArray[3] == 'M') { return new NDList( NDSerializer.decodeNumpy(manager, new ByteArrayInputStream(byteArray))); } else if (byteArray[8] == '{') { return decodeSafetensors(manager, new ByteArrayInputStream(byteArray)); } ByteBuffer bb = ByteBuffer.wrap(byteArray); int size = bb.getInt(); if (size < 0) { throw new IllegalArgumentException("Invalid NDList size: " + size); } NDList list = new NDList(); for (int i = 0; i < size; i++) { list.add(i, NDSerializer.decode(manager, bb)); } return list; } catch (IOException | BufferUnderflowException e) { throw new IllegalArgumentException("Invalid NDArray input", e); } } /** * Decodes NDList from {@link InputStream}. * * @param manager manager assigned to {@link NDArray} * @param is input stream contains the ndlist information * @return {@code NDList} */ public static NDList decode(NDManager manager, InputStream is) { try { DataInputStream dis = new DataInputStream(is); byte[] magic = new byte[9]; dis.readFully(magic); PushbackInputStream pis = new PushbackInputStream(is, 9); pis.unread(magic); if (magic[0] == 'P' && magic[1] == 'K') { // assume this is npz file return decodeNumpy(manager, pis); } else if (magic[0] == (byte) 0x93 && magic[1] == 'N' && magic[2] == 'U' && magic[3] == 'M') { return new NDList(NDSerializer.decodeNumpy(manager, pis)); } else if (magic[8] == '{') { return decodeSafetensors(manager, pis); } dis = new DataInputStream(pis); int size = dis.readInt(); if (size < 0) { throw new IllegalArgumentException("Invalid NDList size: " + size); } NDList list = new NDList(); for (int i = 0; i < size; i++) { list.add(i, manager.decode(dis)); } return list; } catch (IOException e) { throw new IllegalArgumentException("Malformed data", e); } } private static NDList decodeSafetensors(NDManager manager, InputStream is) throws IOException { DataInputStream dis; if (is instanceof DataInputStream) { dis = (DataInputStream) is; } else { dis = new DataInputStream(is); } byte[] buf = new byte[8]; dis.readFully(buf); int len = Math.toIntExact(ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).getLong()); buf = new byte[len]; dis.readFully(buf); String json = new String(buf, StandardCharsets.UTF_8); // rust implementation sort by name, our implementation preserve the order. JsonObject jsonObject = JsonUtils.GSON.fromJson(json, JsonObject.class); List<Pair<String, SafeTensor>> list = new ArrayList<>(); int max = 0; for (String key : jsonObject.keySet()) { if ("__metadata__".equals(key)) { continue; } SafeTensor value = JsonUtils.GSON.fromJson(jsonObject.get(key), SafeTensor.class); if (value.offsets.length != 2) { throw new IOException("Malformed safetensors metadata: " + json); } max = Math.max(max, value.offsets[1]); list.add(new Pair<>(key, value)); } buf = new byte[max]; dis.readFully(buf); NDList ret = new NDList(list.size()); for (Pair<String, SafeTensor> pair : list) { if ("__metadata__".equals(pair.getKey())) { continue; } SafeTensor st = pair.getValue(); Shape shape = new Shape(st.shape); ByteBuffer bb = ByteBuffer.wrap(buf, st.offsets[0], st.size()); bb.order(ByteOrder.LITTLE_ENDIAN); DataType dataType = DataType.fromSafetensors(st.dtype); NDArray array = manager.create(bb, shape, dataType); array.setName(pair.getKey()); ret.add(array); } return ret; } private static NDList decodeNumpy(NDManager manager, InputStream is) throws IOException { NDList list = new NDList(); ZipInputStream zis = new ZipInputStream(is); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String name = entry.getName(); NDArray array = NDSerializer.decodeNumpy(manager, zis); if (!name.startsWith("arr_") && name.endsWith(".npy")) { array.setName(name.substring(0, name.length() - 4)); } list.add(array); } return list; } /** * Returns the first occurrence of the specified element from this NDList if it is present. * * @param name the name of the NDArray * @return the first occurrence */ public NDArray get(String name) { for (NDArray array : this) { if (name.equals(array.getName())) { return array; } } return null; } /** * Removes the first occurrence of the specified element from this NDList if it is present. * * <p>If this list does not contain the element, it is unchanged. More formally, removes the * element with the lowest index {@code i} such that {@code * (o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))} (if such an element exists). * * @param name the name of the NDArray to be removed from this NDList, if present * @return the element that was removed */ public NDArray remove(String name) { int index = 0; for (NDArray array : this) { if (name.equals(array.getName())) { remove(index); return array; } ++index; } return null; } /** * Returns {@code true} if this NDList contains an NDArray with the specified name. * * @param name the name of the NDArray to be removed from this NDList, if present * @return {@code true} if this list contains the specified element */ public boolean contains(String name) { for (NDArray array : this) { if (name.equals(array.getName())) { return true; } } return false; } /** * Returns the head index of the NDList. * * @return the head NDArray * @throws IndexOutOfBoundsException if the index is out of range ({@code index &lt; 0 || index * &gt;= size()}) */ public NDArray head() { return get(0); } /** * Returns the only element if this is a singleton NDList or throws an exception if multiple * elements. * * @return the head NDArray * @throws IndexOutOfBoundsException if the list does not contain exactly one element */ public NDArray singletonOrThrow() { if (size() != 1) { throw new IndexOutOfBoundsException( "Incorrect number of elements in NDList.singletonOrThrow: Expected 1 and was " + size()); } return get(0); } /** * Appends all of the NDArrays in the specified NDList to the end of this NDList, in the order * that they are returned by the specified NDList's iterator. * * @param other the NDList containing NDArray to be added to this list * @return this NDList after the addition */ public NDList addAll(NDList other) { for (NDArray array : other) { add(array); } return this; } /** * Returns a view of the portion of this NDList between the specified fromIndex, inclusive, and * to the end. * * @param fromIndex the start index (inclusive) * @return a view of the portion of this NDList */ public NDList subNDList(int fromIndex) { return subNDList(fromIndex, size()); } /** * Returns a view of the portion of this NDList between the specified fromIndex, inclusive, and * toIndex, exclusive. * * @param fromIndex the start index (inclusive) * @param toIndex the end index (exclusive) * @return a view of the portion of this NDList */ public NDList subNDList(int fromIndex, int toIndex) { return new NDList(subList(fromIndex, toIndex)); } /** * Converts all the {@code NDArray} in {@code NDList} to a different {@link Device}. * * @param device the {@link Device} to be set * @param copy set {@code true} if you want to return a copy of the underlying NDArray * @return a new {@code NDList} with the NDArrays on specified {@link Device} */ public NDList toDevice(Device device, boolean copy) { if (!copy) { // if all arrays in NDList are already on device, return itself if (stream().allMatch(array -> array.getDevice() == device)) { return this; } } NDList newNDList = new NDList(size()); forEach(a -> newNDList.add(a.toDevice(device, copy))); return newNDList; } /** {@inheritDoc} */ @Override public NDManager getManager() { return head().getManager(); } /** {@inheritDoc} */ @Override public List<NDArray> getResourceNDArrays() { return this; } /** {@inheritDoc} */ @Override public void attach(NDManager manager) { forEach(array -> array.attach(manager)); } /** {@inheritDoc} */ @Override public void tempAttach(NDManager manager) { forEach(array -> array.tempAttach(manager)); } /** {@inheritDoc} */ @Override public void detach() { forEach(NDResource::detach); } /** * Encodes the NDList to byte array. * * @return the byte array */ public byte[] encode() { return encode(Encoding.ND_LIST); } /** * Encodes the NDList to byte array. * * @param encoding encode mode, one of ndlist/npz/safetensor format * @return the byte array */ public byte[] encode(Encoding encoding) { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { encode(baos, encoding); return baos.toByteArray(); } catch (IOException e) { throw new AssertionError("NDList is not writable", e); } } /** * Writes the encoded NDList to {@code OutputStream}. * * @param os the {@code OutputStream} to be written to * @throws IOException if failed on IO operation */ public void encode(OutputStream os) throws IOException { encode(os, Encoding.ND_LIST); } /** * Writes the encoded NDList to {@code OutputStream}. * * @param os the {@code OutputStream} to be written to * @param encoding encode mode, one of ndlist/npz/safetensor format * @throws IOException if failed on IO operation */ public void encode(OutputStream os, Encoding encoding) throws IOException { if (encoding == Encoding.NPZ) { ZipOutputStream zos = new ZipOutputStream(os); int i = 0; for (NDArray nd : this) { String name = nd.getName(); if (name == null) { zos.putNextEntry(new ZipEntry("arr_" + i + ".npy")); ++i; } else { zos.putNextEntry(new ZipEntry(name + ".npy")); } NDSerializer.encodeAsNumpy(nd, zos); } zos.finish(); zos.flush(); return; } else if (encoding == Encoding.SAFETENSORS) { Map<String, SafeTensor> map = new ConcurrentHashMap<>(size()); int i = 0; int offset = 0; for (NDArray nd : this) { String name = nd.getName(); if (name == null) { name = "arr_" + i; ++i; } SafeTensor st = new SafeTensor(); st.dtype = nd.getDataType().asSafetensors(); st.shape = nd.getShape().getShape(); long size = nd.getDataType().getNumOfBytes() * nd.size(); int limit = offset + Math.toIntExact(size); st.offsets = new int[] {offset, limit}; map.put(name, st); offset = limit; } byte[] json = JsonUtils.GSON.toJson(map).getBytes(StandardCharsets.UTF_8); ByteBuffer buf = ByteBuffer.allocate(8); buf.order(ByteOrder.LITTLE_ENDIAN); buf.putLong(0, json.length); os.write(buf.array()); os.write(json); for (NDArray nd : this) { os.write(nd.toByteArray()); } return; } DataOutputStream dos = new DataOutputStream(os); dos.writeInt(size()); for (NDArray nd : this) { NDSerializer.encode(nd, dos); } dos.flush(); } /** {@inheritDoc} */ @Override public byte[] getAsBytes() { return encode(); } /** {@inheritDoc} */ @Override public ByteBuffer toByteBuffer() { return ByteBuffer.wrap(encode()); } /** * Gets all of shapes in the {@code NDList}. * * @return shapes in {@code NDList} */ public Shape[] getShapes() { return stream().map(NDArray::getShape).toArray(Shape[]::new); } /** {@inheritDoc} */ @Override public void close() { forEach(NDArray::close); clear(); } /** {@inheritDoc} */ @Override public String toString() { StringBuilder builder = new StringBuilder(200); builder.append("NDList size: ").append(size()).append('\n'); int index = 0; for (NDArray array : this) { String name = array.getName(); builder.append(index++).append(' '); if (name != null) { builder.append(name); } builder.append(": ") .append(array.getShape()) .append(' ') .append(array.getDataType()) .append('\n'); } return builder.toString(); } /** An enum represents NDList serialization format. */ public enum Encoding { ND_LIST, NPZ, SAFETENSORS } private static final class SafeTensor { String dtype; long[] shape; @SerializedName("data_offsets") int[] offsets; int size() { return offsets[1] - offsets[0]; } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/ndarray/NDManager.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.ndarray; import ai.djl.Device; import ai.djl.engine.Engine; import ai.djl.engine.EngineException; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; import ai.djl.util.Float16Utils; import ai.djl.util.PairList; import ai.djl.util.passthrough.PassthroughNDManager; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.List; import java.util.concurrent.atomic.AtomicLong; /** * NDArray managers are used to create <I>NDArrays</I> (n-dimensional array on native engine). * * <p>NDManager is implemented in each deep learning {@link Engine}. {@link NDArray}s are resources * that are allocated in each deep learning engine's native memory space. NDManager is the key class * that manages these native resources. * * <p>NDArray can only be created through NDManager. By default, NDArray's lifecycle is attached to * the creator NDManager. NDManager itself implements {@link AutoCloseable}. When NDManager is * closed, all the resource associated with it will be closed as well. * * <p>A typical place to obtain NDManager is in {@link Translator#processInput(TranslatorContext, * Object)} or {@link Translator#processOutput(TranslatorContext, NDList)}. * * <p>The following is an example of how to use NDManager: * * <pre> * public class MyTranslator implements Translator&lt;FloatBuffer, String&gt; { * * &#064;Override * public NDList processInput(TranslatorContext ctx, FloatBuffer input) { * <b>NDManager manager = ctx.getNDManager();</b> * NDArray array = <b>manager</b>.create(shape); * array.set(input); * return new NDList(array); * } // NDArrays created in this method will be closed after method return. * } * </pre> * * <p>NDManager has a hierarchical structure; it has a single parent NDManager and has child * NDManagers. When the parent NDManager is closed, all children will be closed as well. * * <p>The DJL engine manages NDManager's lifecycle by default. You only need to manage the user * created child NDManager. The child NDManager becomes useful when you create a large number of * temporary NDArrays and want to free the resources earlier than the parent NDManager's lifecycle. * * <p>The following is an example of such a use case: * * <pre> * public class MyTranslator implements Translator&lt;List&lt;FloatBuffer&gt;&gt;, String&gt; { * * &#064;Override * public NDList processInput(TranslatorContext ctx, List&lt;FloatBuffer&gt; input) { * NDManager manager = ctx.getNDManager(); * NDArray array = manager.create(shape, dataType); * for (int i = 0; i &lt; input.size(); ++i) { * try (<b>NDManager childManager = manager.newSubManager()</b>) { * NDArray tmp = <b>childManager</b>.create(itemShape); * tmp.put(input.get(i); * array.put(i, tmp); * } // NDArray <i>tmp</i> will be closed here * } * return new NDList(array); * } * } * </pre> * * <p>You can also close an individual NDArray. NDManager won't close an NDArray that's already been * closed. In certain use cases, you might want to return an NDArray outside of NDManager's scope. * * @see NDArray * @see Translator * @see TranslatorContext#getNDManager() * @see <a * href="https://github.com/deepjavalibrary/djl/blob/master/docs/development/memory_management.md">NDArray * Memory Management Guide</a> */ public interface NDManager extends AutoCloseable { AtomicLong UID_GENERATOR = new AtomicLong(); /** * Returns a low-cost unique ID. * * @return a string UID. */ static String nextUid() { return "uid-" + System.nanoTime() + "-" + UID_GENERATOR.incrementAndGet(); } /** * Creates a new top-level {@code NDManager}. * * <p>{@code NDManager} will inherit default {@link Device}. * * @return a new top-level {@code NDManager} */ static NDManager newBaseManager() { if (Engine.getAllEngines().isEmpty()) { return PassthroughNDManager.INSTANCE; } return Engine.getInstance().newBaseManager(); } /** * Creates a new top-level {@code NDManager} with specified {@link Device}. * * @param device the default {@link Device} * @return a new top-level {@code NDManager} */ static NDManager newBaseManager(Device device) { return Engine.getInstance().newBaseManager(device); } /** * Creates a new top-level {@code NDManager} with specified engine. * * @param engineName the name of the engine * @return a new top-level {@code NDManager} */ static NDManager newBaseManager(String engineName) { return Engine.getEngine(engineName).newBaseManager(); } /** * Creates a new top-level {@code NDManager} with specified {@link Device} and engine. * * @param device the default {@link Device} * @param engineName the name of the engine * @return a new top-level {@code NDManager} */ static NDManager newBaseManager(Device device, String engineName) { return Engine.getEngine(engineName).newBaseManager(device); } /** * Creates a new manager based on the given resource. * * @param resource the resource to use * @return a new memory scrope containing the array */ static NDManager subManagerOf(NDResource resource) { return resource.getManager().newSubManager(); } /** * Returns the default context used in Engine. * * <p>The default type is defined by whether the deep learning engine is recognizing GPUs * available on your machine. If there is no GPU available, CPU will be used. * * @return a {@link Device} */ Device defaultDevice(); /** * Allocates a new engine specific direct byte buffer. * * @param capacity the new buffer's capacity, in bytes * @return the new byte buffer */ ByteBuffer allocateDirect(int capacity); /** * Creates a new {@code NDArray} if the input {@link NDArray} is from an external engine. * * @param array the input {@code NDArray} * @return a new {@code NDArray} if the input {@code NDArray} is from external engine */ NDArray from(NDArray array); /** * Creates an uninitialized instance of {@link DataType#FLOAT32} {@link NDArray} with specified * {@link Shape}. * * @param shape the {@link Shape} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray create(Shape shape) { return create(shape, DataType.FLOAT32, getDevice()); } /** * Creates and initializes a scalar {@link NDArray}. * * @param data the {@link Number} that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(Number data) { if (data instanceof Integer) { return create(data.intValue()); } else if (data instanceof Float) { return create(data.floatValue()); } else if (data instanceof Double) { return create(data.doubleValue()); } else if (data instanceof Long) { return create(data.longValue()); } else if (data instanceof Byte) { return create(data.byteValue()); } else { throw new IllegalArgumentException("Short conversion not supported!"); } } /** * Creates and initializes a scalar {@link NDArray}. * * @param data the float that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(float data) { return create(new float[] {data}, new Shape()); } /** * Creates and initializes a scalar {@link NDArray}. * * @param data the float data that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(int data) { return create(new int[] {data}, new Shape()); } /** * Creates and initializes a scalar {@link NDArray}. * * @param data the double data that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(double data) { return create(new double[] {data}, new Shape()); } /** * Creates and initializes a scalar {@link NDArray}. * * @param data the long data that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(long data) { return create(new long[] {data}, new Shape()); } /** * Creates and initializes a scalar {@link NDArray}. * * @param data the byte data that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(byte data) { return create(new byte[] {data}, new Shape()); } /** * Creates and initializes a scalar {@link NDArray}. * * @param data the boolean data that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(boolean data) { return create(new boolean[] {data}, new Shape()); } /** * Creates and initializes a scalar {@link NDArray}. * * @param data the String data that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(String data) { return create(new String[] {data}, StandardCharsets.UTF_8, new Shape()); } /** * Creates and initializes 1D {@link NDArray}. * * @param data the String data that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(String[] data) { return create(data, StandardCharsets.UTF_8); } /** * Creates and initializes 1D {@link NDArray}. * * @param data the String data that needs to be set * @param charset the charset to decode the string * @return a new instance of {@link NDArray} */ default NDArray create(String[] data, Charset charset) { return create(data, charset, new Shape(data.length)); } /** * Creates a String {@link NDArray} based on the provided shape. * * @param data the flattened String array * @param shape the shape of the String NDArray * @return a new instance of {@code NDArray} */ default NDArray create(String[] data, Shape shape) { return create(data, StandardCharsets.UTF_8, shape); } /** * Creates a String {@link NDArray} based on the provided shape. * * @param data the flattened String array * @param charset the charset to decode the string * @param shape the shape of the String NDArray * @return a new instance of {@code NDArray} */ NDArray create(String[] data, Charset charset, Shape shape); /** * Creates and initializes a 1D {@link NDArray}. * * @param data the float array that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(float[] data) { return create(data, new Shape(data.length)); } /** * Creates and initializes a 1D {@link NDArray}. * * @param data the float array that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(int[] data) { return create(data, new Shape(data.length)); } /** * Creates and initializes a 1D {@link NDArray}. * * @param data the float array that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(double[] data) { return create(data, new Shape(data.length)); } /** * Creates and initializes a 1D {@link NDArray}. * * @param data the float array that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(long[] data) { return create(data, new Shape(data.length)); } /** * Creates and initializes a 1D {@link NDArray}. * * @param data the float array that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(byte[] data) { return create(data, new Shape(data.length)); } /** * Creates and initializes a 1D {@link NDArray}. * * @param data the bool array that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(boolean[] data) { return create(data, new Shape(data.length)); } /** * Creates and initializes a 2D {@link NDArray}. * * @param data the float array that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(float[][] data) { FloatBuffer buffer = allocateDirect(data.length * data[0].length * 4).asFloatBuffer(); for (float[] d : data) { buffer.put(d); } buffer.rewind(); return create(buffer, new Shape(data.length, data[0].length)); } /** * Creates and initializes a 2D {@link NDArray}. * * @param data the float array that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(int[][] data) { IntBuffer buffer = allocateDirect(data.length * data[0].length * 4).asIntBuffer(); for (int[] d : data) { buffer.put(d); } buffer.rewind(); return create(buffer, new Shape(data.length, data[0].length)); } /** * Creates and initializes a 2D {@link NDArray}. * * @param data the float array that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(double[][] data) { DoubleBuffer buffer = allocateDirect(data.length * data[0].length * 8).asDoubleBuffer(); for (double[] d : data) { buffer.put(d); } buffer.rewind(); return create(buffer, new Shape(data.length, data[0].length)); } /** * Creates and initializes a 2-D {@link NDArray}. * * @param data the float array that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(long[][] data) { LongBuffer buffer = allocateDirect(data.length * data[0].length * 8).asLongBuffer(); for (long[] d : data) { buffer.put(d); } buffer.rewind(); return create(buffer, new Shape(data.length, data[0].length)); } /** * Creates and initializes a 2-D {@link NDArray}. * * @param data the float array that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(byte[][] data) { ByteBuffer buffer = allocateDirect(data.length * data[0].length); for (byte[] d : data) { buffer.put(d); } buffer.rewind(); return create(buffer, new Shape(data.length, data[0].length)); } /** * Creates and initializes a 2-D {@link NDArray}. * * @param data the boolean array that needs to be set * @return a new instance of {@link NDArray} */ default NDArray create(boolean[][] data) { ByteBuffer buffer = allocateDirect(data.length * data[0].length); for (boolean[] d : data) { for (boolean b : d) { buffer.put((byte) (b ? 1 : 0)); } } buffer.rewind(); return create(buffer, new Shape(data.length, data[0].length), DataType.BOOLEAN); } /** * Creates and initializes a {@link NDArray} with specified {@link Shape}. * * <p>{@link DataType} of the NDArray will determined by type of Buffer. * * @param data the data to initialize the {@code NDArray} * @param shape the {@link Shape} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray create(Buffer data, Shape shape) { DataType dataType = DataType.fromBuffer(data); return create(data, shape, dataType); } /** * Creates an uninitialized instance of {@link NDArray} with specified {@link Shape}, and {@link * DataType}. * * @param shape the {@link Shape} of the {@link NDArray} * @param dataType the {@link DataType} of the {@link NDArray} * @return a new instance of {@link NDArray} */ NDArray create(Shape shape, DataType dataType); /** * Creates and initializes an instance of {@link NDArray} with specified {@link Shape} and * {@link DataType}. * * @param data the data to initialize the {@link NDArray} * @param shape the {@link Shape} of the {@link NDArray} * @param dataType the {@link DataType} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray create(Buffer data, Shape shape, DataType dataType) { NDArray array = create(shape, dataType); array.set(data); return array; } /** * Creates and initializes an instance of {@link NDArray} with specified {@link Shape} and float * array. * * @param data the float array that needs to be set * @param shape the {@link Shape} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray create(float[] data, Shape shape) { return create(FloatBuffer.wrap(data), shape); } /** * Creates and initializes an instance of {@link NDArray} with specified {@link Shape} and int * array. * * @param data the float array that needs to be set * @param shape the {@link Shape} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray create(int[] data, Shape shape) { return create(IntBuffer.wrap(data), shape); } /** * Creates and initializes an instance of {@link NDArray} with specified {@link Shape} and * double array. * * @param data the float array that needs to be set * @param shape the {@link Shape} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray create(double[] data, Shape shape) { return create(DoubleBuffer.wrap(data), shape); } /** * Creates and initializes an instance of {@link NDArray} with specified {@link Shape} and long * array. * * @param data the float array that needs to be set * @param shape the {@link Shape} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray create(long[] data, Shape shape) { return create(LongBuffer.wrap(data), shape); } /** * Creates and initializes an instance of {@link NDArray} with specified {@link Shape} and byte * array. * * @param data the float array that needs to be set * @param shape the {@link Shape} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray create(byte[] data, Shape shape) { return create(ByteBuffer.wrap(data), shape); } /** * Creates and initializes an instance of {@link NDArray} with specified {@link Shape} and * boolean array. * * @param data the boolean array that needs to be set * @param shape the {@link Shape} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray create(boolean[] data, Shape shape) { byte[] byteData = new byte[data.length]; for (int i = 0; i < data.length; i++) { byteData[i] = (byte) (data[i] ? 1 : 0); } return create(ByteBuffer.wrap(byteData), shape, DataType.BOOLEAN); } /** * Creates an uninitialized instance of {@link NDArray} with specified {@link Shape}, {@link * DataType} and {@link Device}. * * @param shape the {@link Shape} of the {@link NDArray} * @param dataType the {@link DataType} of the {@link NDArray} * @param device the {@link Device} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray create(Shape shape, DataType dataType, Device device) { if (device == null || device.equals(getDevice())) { return create(shape, dataType); } return newSubManager(device).create(shape, dataType); } /** * Creates a Compressed Sparse Row Storage (CSR) Format Matrix. * * @param data the data to set for the CSR Matrix * @param indptr the indptr array is what will help identify the rows where the data appears * @param indices the indices array stores the column index for each non-zero element in data * @param shape the {@link Shape} of the {@link NDArray} * @param device the {@link Device} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray createCSR( float[] data, long[] indptr, long[] indices, Shape shape, Device device) { return createCSR(FloatBuffer.wrap(data), indptr, indices, shape, device); } /** * Creates a Compressed Sparse Row Storage (CSR) Format Matrix. * * @param data the data to set for the CSR Matrix * @param indptr the indptr array is what will help identify the rows where the data appears * @param indices the indices array stores the column index for each non-zero element in data * @param shape the {@link Shape} of the {@link NDArray} * @param device the {@link Device} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray createCSR( Buffer data, long[] indptr, long[] indices, Shape shape, Device device) { if (device == null || device.equals(getDevice())) { return createCSR(data, indptr, indices, shape); } return newSubManager(device).createCSR(data, indptr, indices, shape); } /** * Creates a Compressed Sparse Row Storage (CSR) Format Matrix. * * @param data the data to set for the CSR Matrix * @param indptr the indptr array is what will help identify the rows where the data appears * @param indices the indices array stores the column index for each non-zero element in data * @param shape the {@link Shape} of the {@link NDArray} * @return a new instance of {@link NDArray} */ NDArray createCSR(Buffer data, long[] indptr, long[] indices, Shape shape); /** * Stores the matrix in row sparse format. * * @param data the data to set for the Row Sparse {@link NDArray} * @param dataShape the {@link Shape} of the data {@link NDArray} * @param indices the indices to store the data * @param shape the {@link Shape} of the {@link NDArray} * @param device the {@link Device} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray createRowSparse( Buffer data, Shape dataShape, long[] indices, Shape shape, Device device) { if (device == null || device.equals(getDevice())) { return createRowSparse(data, dataShape, indices, shape); } return newSubManager(device).createRowSparse(data, dataShape, indices, shape); } /** * Stores the matrix in row sparse format. * * @param data the data to set for the Row Sparse {@link NDArray} * @param dataShape the {@link Shape} of the data {@link NDArray} * @param indices the indices to store the data * @param shape the {@link Shape} of the {@link NDArray} * @return a new instance of {@link NDArray} */ NDArray createRowSparse(Buffer data, Shape dataShape, long[] indices, Shape shape); /** * Creates a Coordinate Format (COO) Matrix. * * @param data the data to set for the Coordinate format {@link NDArray} * @param indices the matrix represent indices * @param shape the {@link Shape} of the {@link NDArray} * @return a new instance of {@link NDArray} */ NDArray createCoo(Buffer data, long[][] indices, Shape shape); /** * Decodes {@link NDArray} through byte array. * * @param bytes byte array to load from * @return {@link NDArray} */ default NDArray decode(byte[] bytes) { return NDSerializer.decode(this, ByteBuffer.wrap(bytes)); } /** * Decodes {@link NDArray} through {@link DataInputStream}. * * @param is input stream data to load from * @return {@link NDArray} * @throws IOException data is not readable */ default NDArray decode(InputStream is) throws IOException { return NDSerializer.decode(this, is); } /** * Loads the NDArrays saved to a file. * * @param path the path to the file * @return the loaded arrays */ NDList load(Path path); /** * Loads the NDArrays saved to a file. * * @param path the path to the file * @param device the device to use for the loaded arrays * @return the loaded arrays */ default NDList load(Path path, Device device) { if (device == null || device.equals(getDevice())) { return load(path); } return newSubManager(device).load(path); } /** * Sets the name for the NDManager. * * @param name the name assigned to the manager */ void setName(String name); /** * Gets the name of the NDManager. * * @return name */ String getName(); /** * Creates an instance of {@link NDArray} with specified {@link Shape} filled with zeros. * * @param shape the {@link Shape} of the {@link NDArray} * @return a new instance of {@link NDArray} * @see #zeros(Shape, DataType, Device) */ default NDArray zeros(Shape shape) { return zeros(shape, DataType.FLOAT32); } /** * Creates an instance of {@link NDArray} with specified {@link Shape} filled with zeros. * * @param shape the {@link Shape} of the {@link NDArray} * @param dataType the {@link DataType} of the {@link NDArray} * @return a new instance of {@link NDArray} * @see #zeros(Shape, DataType, Device) */ default NDArray zeros(Shape shape, DataType dataType) { int size = (int) shape.size(); ByteBuffer bb = allocateDirect(size * dataType.getNumOfBytes()); return create(bb, shape, dataType); } /** * Creates an instance of {@link NDArray} with specified {@link Device}, {@link Shape}, and * {@link DataType} filled with zeros. * * @param shape the {@link Shape} of the {@link NDArray} * @param dataType the {@link DataType} of the {@link NDArray} * @param device the {@link Device} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray zeros(Shape shape, DataType dataType, Device device) { if (device == null || device.equals(getDevice())) { return zeros(shape, dataType); } return newSubManager(device).zeros(shape, dataType); } /** * Creates an instance of {@link NDArray} with specified {@link Shape} filled with ones. * * @param shape the {@link Shape} of the {@link NDArray} * @param dataType the {@link DataType} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray ones(Shape shape, DataType dataType) { int size = (int) shape.size(); ByteBuffer bb = allocateDirect(size * dataType.getNumOfBytes()); for (int i = 0; i < size; ++i) { switch (dataType) { case FLOAT16: bb.putShort(Float16Utils.ONE); break; case FLOAT32: bb.putFloat(1f); break; case FLOAT64: bb.putDouble(1d); break; case INT32: bb.putInt(1); break; case INT64: bb.putLong(1); break; case UINT8: case INT8: bb.put((byte) 1); break; case UNKNOWN: default: break; } } bb.rewind(); return create(bb, shape, dataType); } /** * Creates an instance of {@link NDArray} with specified {@link Shape} filled with ones. * * @param shape the {@link Shape} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray ones(Shape shape) { return ones(shape, DataType.FLOAT32); } /** * Creates an instance of {@link NDArray} with specified {@link Device}, {@link Shape}, and * {@link DataType} filled with ones. * * @param shape the {@link Shape} of the {@link NDArray} * @param dataType the {@link DataType} of the {@link NDArray} * @param device the {@link Device} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray ones(Shape shape, DataType dataType, Device device) { if (device == null || device.equals(getDevice())) { return ones(shape, dataType); } return newSubManager(device).ones(shape, dataType); } /** * Return a new {@code NDArray} of given shape, filled with value. * * @param shape shape of a new {@code NDArray} * @param value fill value * @return {@code NDArray} of fill value with the given shape */ default NDArray full(Shape shape, int value) { return full(shape, value, DataType.INT32); } /** * Return a new {@code NDArray} of given shape, filled with value. * * @param shape shape of a new {@code NDArray} * @param value fill value * @return {@code NDArray} of fill value with the given shape */ default NDArray full(Shape shape, float value) { return full(shape, value, DataType.FLOAT32); } /** * Return a new {@code NDArray} of given shape, filled with value. * * @param shape shape of a new {@code NDArray} * @param value fill value * @param dataType the desired data-type for the {@link NDArray} * @return {@code NDArray} of fill value with the given shape */ NDArray full(Shape shape, float value, DataType dataType); /** * Return a new {@code NDArray} of given shape, device, filled with value. * * @param shape shape of a new {@code NDArray} * @param value fill value * @param dataType the desired data-type for the {@link NDArray} * @param device the {@link Device} of the {@link NDArray} * @return {@code NDArray} of fill value with the given shape */ default NDArray full(Shape shape, float value, DataType dataType, Device device) { if (device == null || device.equals(getDevice())) { return full(shape, value, dataType); } return newSubManager(device).full(shape, value, dataType); } /** * Returns evenly spaced values starting from 0. * * <p>Values are generated within the half-open interval [start, stop) (in other words, the * interval including start but excluding stop). For integer arguments, the function is * equivalent to the Python built-in range function, but returns an instance of {@link NDArray} * rather than a list. * * @param stop the end of the interval. The interval does not include this value * @return a new instance of {@link NDArray} */ default NDArray arange(int stop) { return arange(0, stop, 1, DataType.INT32); } /** * Returns evenly spaced values starting from 0. * * <p>Values are generated within the half-open interval [start, stop) (in other words, the * interval including start but excluding stop). For integer arguments, the function is * equivalent to the Python built-in range function, but returns an instance of {@link NDArray} * rather than a list. * * @param stop the end of the interval. The interval does not include this value * @return a new instance of {@link NDArray} */ default NDArray arange(float stop) { return arange(0.0f, stop, 1.0f, DataType.FLOAT32); } /** * Returns evenly spaced values within a given interval with step 1. * * <p>Values are generated within the half-open interval [start, stop) (in other words, the * interval including start but excluding stop). For integer arguments, the function is * equivalent to the Python built-in range function, but returns an instance of {@link NDArray} * rather than a list. * * @param start the start of interval. The interval includes this value * @param stop the end of interval. The interval does not include this value * @return a new instance of {@link NDArray} */ default NDArray arange(int start, int stop) { return arange(start, stop, 1, DataType.INT32); } /** * Returns evenly spaced values within a given interval with step 1. * * <p>Values are generated within the half-open interval [start, stop) (in other words, the * interval including start but excluding stop). For integer arguments, the function is * equivalent to the Python built-in range function, but returns an instance of {@link NDArray} * rather than a list. * * @param start the start of interval. The interval includes this value * @param stop the end of interval. The interval does not include this value * @return a new instance of {@link NDArray} */ default NDArray arange(float start, float stop) { return arange(start, stop, 1.0f, DataType.FLOAT32); } /** * Returns evenly spaced values within a given interval. * * <p>Values are generated within the half-open interval [start, stop) (in other words, the * interval including start but excluding stop). For integer arguments, the function is * equivalent to the Python built-in range function, but returns an instance of {@link NDArray} * rather than a list. * * @param start the start of interval. The interval includes this value * @param stop the end of interval. The interval does not include this value * @param step the spacing between values * @return a new instance of {@link NDArray} */ default NDArray arange(int start, int stop, int step) { return arange(start, stop, step, DataType.INT32); } /** * Returns evenly spaced values within a given interval. * * <p>Values are generated within the half-open interval [start, stop) (in other words, the * interval including start but excluding stop). For integer arguments, the function is * equivalent to the Python built-in range function, but returns an instance of {@link NDArray} * rather than a list. * * @param start the start of interval. The interval includes this value * @param stop the end of interval. The interval does not include this value * @param step the spacing between values * @return a new instance of {@link NDArray} */ default NDArray arange(float start, float stop, float step) { return arange(start, stop, step, DataType.FLOAT32); } /** * Returns evenly spaced values within a given interval. * * <p>Values are generated within the half-open interval [start, stop) (in other words, the * interval including start but excluding stop). For integer arguments, the function is * equivalent to the Python built-in range function, but returns an instance of {@link NDArray} * rather than a list. * * @param start the start of interval. The interval includes this value * @param stop the end of interval. The interval does not include this value * @param step the spacing between values * @param dataType the {@link DataType} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray arange(int start, int stop, int step, DataType dataType) { return arange((float) start, (float) stop, (float) step, dataType); } /** * Returns evenly spaced values within a given interval. * * <p>Values are generated within the half-open interval [start, stop) (in other words, the * interval including start but excluding stop). For integer arguments, the function is * equivalent to the Python built-in range function, but returns an instance of {@link NDArray} * rather than a list. * * @param start the start of interval. The interval includes this value * @param stop the end of interval. The interval does not include this value * @param step the spacing between values * @param dataType the {@link DataType} of the {@link NDArray} * @return a new instance of {@link NDArray} */ NDArray arange(float start, float stop, float step, DataType dataType); /** * Returns evenly spaced values within a given interval. * * <p>Values are generated within the half-open interval [start, stop) (in other words, the * interval including start but excluding stop). For integer arguments, the function is * equivalent to the Python built-in range function, but returns an instance of {@link NDArray} * rather than a list. * * @param start the start of interval. The interval includes this value * @param stop the end of interval. The interval does not include this value * @param step the spacing between values * @param dataType the {@link DataType} of the {@link NDArray} * @param device the {@link Device} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray arange(float start, float stop, float step, DataType dataType, Device device) { if (device == null || device.equals(getDevice())) { return arange(start, stop, step, dataType); } return newSubManager(device).arange(start, stop, step, dataType); } /** * Returns a 2-D array with ones on the diagonal and zeros elsewhere. * * @param rows the number of rows and cols in the output * @return a {@link NDArray} where all elements are equal to zero, except for the k-th diagonal, * whose values are equal to one */ default NDArray eye(int rows) { return eye(rows, rows, 0, DataType.FLOAT32); } /** * Returns a 2-D array with ones on the diagonal and zeros elsewhere. * * @param rows the number of rows and cols in the output * @param k the index of the diagonal: a positive value refers to an upper diagonal, and a * negative value to a lower diagonal * @return a {@link NDArray} where all elements are equal to zero, except for the k-th diagonal, * whose values are equal to one */ default NDArray eye(int rows, int k) { return eye(rows, rows, k, DataType.FLOAT32); } /** * Returns a 2-D array with ones on the diagonal and zeros elsewhere. * * @param rows the number of rows in the output * @param cols the number of columns in the output * @param k the index of the diagonal: a positive value refers to an upper diagonal, and a * negative value to a lower diagonal * @return a {@link NDArray} where all elements are equal to zero, except for the k-th diagonal, * whose values are equal to one */ default NDArray eye(int rows, int cols, int k) { return eye(rows, cols, k, DataType.FLOAT32); } /** * Returns a 2-D array with ones on the diagonal and zeros elsewhere. * * @param rows the number of rows int the output * @param cols the number of columns in the output * @param k the index of the diagonal: a positive value refers to an upper diagonal, and a * negative value to a lower diagonal * @param dataType the {@link DataType} of the {@link NDArray} * @return a {@link NDArray} where all elements are equal to zero, except for the k-th diagonal, * whose values are equal to one */ NDArray eye(int rows, int cols, int k, DataType dataType); /** * Returns a 2-D array with ones on the diagonal and zeros elsewhere. * * @param rows the number of rows int the output * @param cols the number of columns in the output * @param k the index of the diagonal: a positive value refers to an upper diagonal, and a * negative value to a lower diagonal * @param dataType the {@link DataType} of the {@link NDArray} * @param device the {@link Device} of the {@link NDArray} * @return a {@link NDArray} where all elements are equal to zero, except for the k-th diagonal, * whose values are equal to one */ default NDArray eye(int rows, int cols, int k, DataType dataType, Device device) { if (device == null || device.equals(getDevice())) { return eye(rows, cols, k, dataType); } return newSubManager(device).eye(rows, cols, k, dataType); } /** * Returns evenly spaced numbers over a specified interval. * * <p>Returns num evenly spaced samples, calculated over the interval [start, stop]. * * @param start the starting value of the sequence * @param stop the end value of the sequence * @param num the number of samples to generate * @return a new instance of {@link NDArray} */ default NDArray linspace(int start, int stop, int num) { return linspace(start, stop, num, true); } /** * Returns evenly spaced numbers over a specified interval. * * <p>Returns num evenly spaced samples, calculated over the interval [start, stop]. * * @param start the starting value of the sequence * @param stop the end value of the sequence * @param num the number of samples to generate * @return a new instance of {@link NDArray} */ default NDArray linspace(float start, float stop, int num) { return linspace(start, stop, num, true); } /** * Returns evenly spaced numbers over a specified interval. * * <p>Returns num evenly spaced samples, calculated over the interval [start, stop].The endpoint * of the interval can optionally be excluded. * * @param start the starting value of the sequence * @param stop the end value of the sequence * @param num the number of samples to generate * @param endpoint if {@code true}, stop is the last sample, otherwise, it is not included * @return a new instance of {@link NDArray} */ default NDArray linspace(int start, int stop, int num, boolean endpoint) { return linspace((float) start, (float) stop, num, endpoint); } /** * Returns evenly spaced numbers over a specified interval. * * <p>Returns num evenly spaced samples, calculated over the interval [start, stop].The endpoint * of the interval can optionally be excluded. * * @param start the starting value of the sequence * @param stop the end value of the sequence * @param num the number of samples to generate * @param endpoint if {@code true}, stop is the last sample, otherwise, it is not included * @return a new instance of {@link NDArray} */ NDArray linspace(float start, float stop, int num, boolean endpoint); /** * Returns evenly spaced numbers over a specified interval. * * <p>Returns num evenly spaced samples, calculated over the interval [start, stop].The endpoint * of the interval can optionally be excluded. * * @param start the starting value of the sequence * @param stop the end value of the sequence * @param num the number of samples to generate * @param endpoint if {@code true}, stop is the last sample, otherwise, it is not included * @param device the {@link Device} of the {@link NDArray} * @return a new instance of {@link NDArray} */ default NDArray linspace(float start, float stop, int num, boolean endpoint, Device device) { if (device == null || device.equals(getDevice())) { return linspace(start, stop, num, endpoint); } return newSubManager(device).linspace(start, stop, num, endpoint); } /** * Returns random integer values from low (inclusive) to high (exclusive). * * @param low Lowest (signed) longs to be drawn from the distribution * @param high one above the largest (signed) long to be drawn from the distribution * @param shape the {@link Shape} of the {@link NDArray} * @param dataType the {@link DataType} of the {@link NDArray} * @return the drawn samples {@link NDArray} */ NDArray randomInteger(long low, long high, Shape shape, DataType dataType); /** * Returns a random permutation of integers from 0 to n - 1. * * @param n (int) – the upper bound (exclusive) * @return a random permutation of integers from 0 to n - 1. */ NDArray randomPermutation(long n); /** * Draws samples from a uniform distribution. * * <p>Samples are uniformly distributed over the half-open interval [low, high) (includes low, * but excludes high). In other words, any value within the given interval is equally likely to * be drawn by uniform. * * @param low the lower boundary of the output interval. All values generated will be greater * than or equal to low. * @param high the upper boundary of the output interval. All values generated will be less than * high. * @param shape the {@link Shape} of the {@link NDArray} * @return the drawn samples {@link NDArray} */ default NDArray randomUniform(float low, float high, Shape shape) { return randomUniform(low, high, shape, DataType.FLOAT32); } /** * Draws samples from a uniform distribution. * * <p>Samples are uniformly distributed over the half-open interval [low, high) (includes low, * but excludes high). In other words, any value within the given interval is equally likely to * be drawn by uniform. * * @param low the lower boundary of the output interval. All values generated will be greater * than or equal to low. * @param high the upper boundary of the output interval. All values generated will be less than * high. * @param shape the {@link Shape} of the {@link NDArray} * @param dataType the {@link DataType} of the {@link NDArray} * @return the drawn samples {@link NDArray} */ NDArray randomUniform(float low, float high, Shape shape, DataType dataType); /** * Draws samples from a uniform distribution. * * <p>Samples are uniformly distributed over the half-open interval [low, high) (includes low, * but excludes high). In other words, any value within the given interval is equally likely to * be drawn by uniform. * * @param low the lower boundary of the output interval. All values generated will be greater * than or equal to low. * @param high the upper boundary of the output interval. All values generated will be less than * high. * @param shape the {@link Shape} of the {@link NDArray} * @param dataType the {@link DataType} of the {@link NDArray} * @param device the {@link Device} of the {@link NDArray} * @return the drawn samples {@link NDArray} */ default NDArray randomUniform( float low, float high, Shape shape, DataType dataType, Device device) { if (device == null || device.equals(getDevice())) { return randomUniform(low, high, shape, dataType); } return newSubManager(device).randomUniform(low, high, shape, dataType); } /** * Draws random samples from a normal (Gaussian) distribution with mean 0 and standard deviation * 1. * * <p>Samples are distributed according to a normal distribution parametrized by mean = 0 and * standard deviation = 1. * * @param shape the output {@link Shape} * @return the drawn samples {@link NDArray} */ default NDArray randomNormal(Shape shape) { return randomNormal(0f, 1f, shape, DataType.FLOAT32); } /** * Draws random samples from a normal (Gaussian) distribution with mean 0 and standard deviation * 1. * * @param shape the output {@link Shape} * @param dataType the {@link DataType} of the {@link NDArray} * @return the drawn samples {@link NDArray} */ default NDArray randomNormal(Shape shape, DataType dataType) { return randomNormal(0.0f, 1.0f, shape, dataType); } /** * Draws random samples from a normal (Gaussian) distribution. * * @param loc the mean (centre) of the distribution * @param scale the standard deviation (spread or "width") of the distribution * @param shape the output {@link Shape} * @param dataType the {@link DataType} of the {@link NDArray} * @return the drawn samples {@link NDArray} */ NDArray randomNormal(float loc, float scale, Shape shape, DataType dataType); /** * Draws random samples from a normal (Gaussian) distribution. * * @param loc the mean (centre) of the distribution * @param scale the standard deviation (spread or "width") of the distribution * @param shape the output {@link Shape} * @param dataType the {@link DataType} of the {@link NDArray} * @param device the {@link Device} of the {@link NDArray} * @return the drawn samples {@link NDArray} */ default NDArray randomNormal( float loc, float scale, Shape shape, DataType dataType, Device device) { if (device == null || device.equals(getDevice())) { return randomNormal(loc, scale, shape, dataType); } return newSubManager(device).randomNormal(loc, scale, shape, dataType); } /** * Draws random samples from a normal (Gaussian) distribution with mean 0 and standard deviation * 1, discarding and re-drawing any samples that are more than two standard deviations from the * mean. * * <p>Samples are distributed according to a normal distribution parametrized by mean = 0 and * standard deviation = 1. * * @param shape the output {@link Shape} * @return the drawn samples {@link NDArray} */ default NDArray truncatedNormal(Shape shape) { return truncatedNormal(0f, 1f, shape, DataType.FLOAT32); } /** * Draws random samples from a normal (Gaussian) distribution with mean 0 and standard deviation * 1, discarding and re-drawing any samples that are more than two standard deviations from the * mean. * * @param shape the output {@link Shape} * @param dataType the {@link DataType} of the {@link NDArray} * @return the drawn samples {@link NDArray} */ default NDArray truncatedNormal(Shape shape, DataType dataType) { return truncatedNormal(0.0f, 1.0f, shape, dataType); } /** * Draws random samples from a normal (Gaussian) distribution, discarding and re-drawing any * samples that are more than two standard deviations from the mean. * * @param loc the mean (centre) of the distribution * @param scale the standard deviation (spread or "width") of the distribution * @param shape the output {@link Shape} * @param dataType the {@link DataType} of the {@link NDArray} * @return the drawn samples {@link NDArray} */ NDArray truncatedNormal(float loc, float scale, Shape shape, DataType dataType); /** * Draws random samples from a normal (Gaussian) distribution, discarding and re-drawing any * samples that are more than two standard deviations from the mean. * * @param loc the mean (centre) of the distribution * @param scale the standard deviation (spread or "width") of the distribution * @param shape the output {@link Shape} * @param dataType the {@link DataType} of the {@link NDArray} * @param device the {@link Device} of the {@link NDArray} * @return the drawn samples {@link NDArray} */ default NDArray truncatedNormal( float loc, float scale, Shape shape, DataType dataType, Device device) { if (device == null || device.equals(getDevice())) { return truncatedNormal(loc, scale, shape, dataType); } return newSubManager(device).truncatedNormal(loc, scale, shape, dataType); } /** * Draw samples from a multinomial distribution. * * <p>The multinomial distribution is a multivariate generalization of the binomial * distribution. Take an experiment with one of p possible outcomes. An example of such an * experiment is throwing a dice, where the outcome can be 1 through 6. Each sample drawn from * the distribution represents n such experiments. Its values, X_i = [X_0, X_1, ..., X_p], * represent the number of times the outcome was i. * * @param n the number of experiments * @param pValues the probabilities of each of the p different outcomes. These should sum to 1 * The last element is always assumed to account for the remaining probability, as long as * pValues.sum().getFloat() &lt;= 1) * @return the drawn samples {@link NDArray} */ NDArray randomMultinomial(int n, NDArray pValues); /** * Draw samples from a multinomial distribution. * * <p>The multinomial distribution is a multivariate generalization of the binomial * distribution. Take an experiment with one of p possible outcomes. An example of such an * experiment is throwing a dice, where the outcome can be 1 through 6. Each sample drawn from * the distribution represents n such experiments. Its values, X_i = [X_0, X_1, ..., X_p], * represent the number of times the outcome was i. * * @param n the number of experiments * @param pValues the probabilities of each of the p different outcomes. These should sum to 1 * The last element is always assumed to account for the remaining probability, as long as * pValues.sum().getFloat() &lt;= 1) * @param shape the output {@link Shape} * @return the drawn samples {@link NDArray} */ NDArray randomMultinomial(int n, NDArray pValues, Shape shape); /** * Concurrent sampling from multiple normal distributions with parameters *mu* (mean) and * *sigma* (standard deviation). * * @param mu Means of the distributions * @param sigma Standard deviations of the distributions * @return the drawn samples {@link NDArray} */ NDArray sampleNormal(NDArray mu, NDArray sigma); /** * Concurrent sampling from multiple normal distributions with parameters *mu* (mean) and * *sigma* (standard deviation). * * @param mu Means of the distributions * @param sigma Standard deviations of the distributions * @param shape Shape to be sampled from each random distribution * @return the drawn samples {@link NDArray} */ NDArray sampleNormal(NDArray mu, NDArray sigma, Shape shape); /** * Draw random samples from a Poisson distribution. * * <p>Samples are distributed according to a Poisson distribution parametrized by *lambda* * (rate). Samples will always be returned as a floating point data type. * * @param lam Lambda (rate) parameters of the distributions * @return the drawn samples {@link NDArray} */ NDArray samplePoisson(NDArray lam); /** * Draw random samples from a Poisson distribution. * * <p>Samples are distributed according to a Poisson distribution parametrized by *lambda* * (rate). Samples will always be returned as a floating point data type. * * @param lam Lambda (rate) parameters of the distributions * @param shape Shape to be sampled from each random distribution * @return the drawn samples {@link NDArray} */ NDArray samplePoisson(NDArray lam, Shape shape); /** * Draw random samples from a gamma distribution. * * <p>Samples are distributed according to a gamma distribution parametrized by *alpha* (shape) * and *beta* (scale). * * @param alpha The shape of the gamma distribution * @param beta The scale of the gamma distribution * @return the drawn samples {@link NDArray} */ NDArray sampleGamma(NDArray alpha, NDArray beta); /** * Draw random samples from a gamma distribution. * * <p>Samples are distributed according to a gamma distribution parametrized by *alpha* (shape) * and *beta* (scale). * * @param alpha The shape of the gamma distribution * @param beta The scale of the gamma distribution * @param shape Shape to be sampled from each random distribution * @return the drawn samples {@link NDArray} */ NDArray sampleGamma(NDArray alpha, NDArray beta, Shape shape); /** * Builds the Hanning Window. * * <p>The Hanning was named for Julius von Hann, an Austrian meteorologist. It is also known as * the Cosine Bell. Some authors prefer that it be called a Hann window, to help avoid confusion * with the very similar Hamming window. * * @param numPoints Number of points in the output window. * @return the window */ default NDArray hanningWindow(long numPoints) { float[] data = new float[(int) numPoints]; // shift from N -1 to N to trims off the last duplicate value from the symmetric window for (int i = 1; i < data.length; i++) { data[i] = (float) (0.5 * (1 - Math.cos((2 * Math.PI * i) / numPoints))); } return create(data); } /** * Check if the manager is still valid. * * @return the current status */ boolean isOpen(); /** * Caps this manager to prevent unintentional attachment of resources. This is useful to detect * memory leaks at an early point in time. The attachment of sub managers is still allowed after * this method has been called. */ void cap(); /** * Returns the parent {@code NDManager}. * * @return the parent {@code NDManager} */ NDManager getParentManager(); /** * Creates a child {@code NDManager}. * * <p>Child {@code NDManager} will inherit default {@link Device} from this {@code NDManager}. * * @return a child {@code NDManager} */ NDManager newSubManager(); /** * Creates a child {@code NDManager} with specified default {@link Device}. * * @param device the default {@link Device} * @return a child {@code NDManager} */ NDManager newSubManager(Device device); /** * Returns the default {@link Device} of this {@code NDManager}. * * @return the default {@link Device} of this {@code NDManager} */ Device getDevice(); /** * Returns all {@link NDArray}s managed by this manager (including recursively). * * @return all {@link NDArray}s managed by this manager (including recursively) */ List<NDArray> getManagedArrays(); /** * Attaches a resource to this {@code NDManager}. * * <p>The attached resource will be closed when this {@code NDManager} is closed. * * <p>This attachment is internal. Many resources will internally track which manager they are * attached to. In that case, you should call {@link NDResource#attach(NDManager)} instead and * that should then call attachInternal. * * @param resourceId the unique resourceId * @param resource the {@link AutoCloseable} resource to be attached */ void attachInternal(String resourceId, AutoCloseable... resource); /** * Attaches a resource to this {@code NDManager} circumventing any cap protection. * * <p>The attached resource will be closed when this {@code NDManager} is closed. * * <p>This attachment is internal. Many resources will internally track which manager they are * attached to. In that case, you should call {@link NDResource#attach(NDManager)} instead and * that should then call attachInternal. * * @param resourceId the unique resourceId * @param resource the {@link AutoCloseable} resource to be attached */ void attachUncappedInternal(String resourceId, AutoCloseable resource); /** * Temporarily attaches a resource to this {@code NDManager} to be returned when this is closed. * * <p>The attached resource will be returned to it's original manager when this {@code * NDManager} is closed. * * <p>This attachment is internal. Many resources will internally track which manager they are * attached to. In that case, you should call {@link NDResource#attach(NDManager)} instead and * that should then call tempAttachInternal. * * @param originalManager the original manager to return the resource to * @param resourceId the unique resourceId * @param resource the {@link AutoCloseable} resource to be attached */ void tempAttachInternal(NDManager originalManager, String resourceId, NDResource resource); /** * Detaches a {@link NDArray} from this {@code NDManager}'s lifecycle. * * <p>The detached {@link NDArray} become un-managed, it's user's responsibility to close the * resource. Failed to close the resource has to wait on GC to be freed, and might cause out of * native memory. * * <p>This detach is internal. Many resources will internally track which manager they are * attached to. In that case, you should call {@link NDResource#detach()} instead and that * should then call detachInternal. * * @param resourceId the resourceId to be removed from this {@code NDManager}'s lifecycle */ void detachInternal(String resourceId); /** * Returns a value outside of this manager by attaching to this manager's parent. * * @param resource the resource to return * @param <T> the type of the resource * @return the passed in resource, after attaching to a new manager */ default <T extends NDResource> T ret(T resource) { resource.attach(getParentManager()); return resource; } /** * Attaches all resources to this manager. * * @param resources the resources to attach * @see NDResource#attach(NDManager) */ default void attachAll(NDResource... resources) { for (NDResource resource : resources) { resource.attach(this); } } /** * Temporarily attaches all resources to this manager. * * @param resources the resources to attach * @see NDResource#tempAttach(NDManager) */ default void tempAttachAll(NDResource... resources) { for (NDResource resource : resources) { resource.tempAttach(this); } } /** * An engine specific generic invocation to native operation. * * <p>You should avoid using this function if possible. Since this function is engine specific, * using this API may cause a portability issue. Native operation may not be compatible between * each version. * * @param operation the native operation to perform * @param src the {@link NDList} of source {@link NDArray} * @param dest the {@link NDList} to save output to * @param params the parameters to be passed to the native operation * @throws IllegalArgumentException if operation is not supported by Engine * @throws EngineException if operation failed in native engine */ void invoke(String operation, NDArray[] src, NDArray[] dest, PairList<String, ?> params); /** * An engine specific generic invocation to native operation. * * <p>You should avoid using this function if possible. Since this function is engine specific, * using this API may cause a portability issue. Native operation may not compatible between * each version. * * @param operation the native operation to perform * @param src the {@link NDList} of source {@link NDArray} * @param params the parameters to be passed to the native operation * @return the output array of {@link NDArray} * @throws IllegalArgumentException if operation is not supported by Engine * @throws EngineException if operation failed in native engine */ NDList invoke(String operation, NDList src, PairList<String, ?> params); /** * Returns the {@link Engine} associated with this manager. * * @return the {@link Engine} associated with this manager */ Engine getEngine(); /** {@inheritDoc} */ @Override void close(); /** * A {@link SystemNDManager} is a marker class for a base NDManager. * * <p>Unlike a typical {@link NDManager}, they can not be closed and don't track memory. */ interface SystemNDManager {} }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/ndarray/NDResource.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.ndarray; import java.util.List; /** An object which is managed by an {@link NDManager} and tracks the manager it is attached to. */ public interface NDResource extends AutoCloseable { /** * Returns the {@link NDManager} that manages this. * * @return the {@link NDManager} that manages this. */ NDManager getManager(); /** * Returns the {@link NDArray} or {@link NDArray}s contained within this resource. * * @return the {@link NDArray} or {@link NDArray}s contained within this resource */ List<NDArray> getResourceNDArrays(); /** * Attaches this {@link NDResource} to the specified {@link NDManager}. * * <p>Attached resource will be closed when the {@link NDManager} is closed. * * @param manager the {@link NDManager} to be attached to */ void attach(NDManager manager); /** * Attaches this {@link NDResource} to the specified {@link NDManager} from which it was * previously detached and temp-attached to the current manager of this resource. This is * functionally equivalent to the attach method, however the cap-state disregarded when adding * the resource back to the original manager. * * @param manager the {@link NDManager} to be attached to */ default void returnResource(NDManager manager) { attach(manager); } /** * Temporarily attaches this {@link NDResource} to the specified {@link NDManager}. * * <p>Attached resource will be returned to the original manager when the {@link NDManager} is * closed. * * @param manager the {@link NDManager} to be attached to */ void tempAttach(NDManager manager); /** * Detaches the {@link NDResource} from current {@link NDManager}'s lifecycle. * * <p>This becomes un-managed and it is the user's responsibility to close this. Failure to * close the resource might cause your machine to run out of native memory. * * @see NDManager */ void detach(); /** {@inheritDoc} */ @Override void close(); }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/ndarray/NDScope.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.ndarray; import java.util.ArrayDeque; import java.util.Deque; import java.util.IdentityHashMap; /** * A class that tracks {@link NDResource} objects created in the try-with-resource block and close * them automatically when out of the block scope. * * <p>This class has been derived from {@code org.bytedeco.javacpp.PointerScope} by Samuel Audet */ public class NDScope implements AutoCloseable { private static final ThreadLocal<Deque<NDScope>> SCOPE_STACK = ThreadLocal.withInitial(ArrayDeque::new); private IdentityHashMap<NDArray, NDArray> resources; /** Constructs a new {@code NDScope} instance. */ @SuppressWarnings("this-escape") public NDScope() { resources = new IdentityHashMap<>(); SCOPE_STACK.get().addLast(this); } /** * Registers {@link NDArray} object to this scope. * * @param array the {@link NDArray} object */ public static void register(NDArray array) { Deque<NDScope> queue = SCOPE_STACK.get(); if (queue.isEmpty()) { return; } queue.getLast().resources.put(array, array); } /** * Unregisters {@link NDArray} object from this scope. * * @param array the {@link NDArray} object */ public static void unregister(NDArray array) { Deque<NDScope> queue = SCOPE_STACK.get(); if (queue.isEmpty()) { return; } queue.getLast().resources.remove(array); } /** * Unregisters {@link NDArray} object from this scope. * * @param arrays the array of {@link NDArray} object */ public static void unregister(NDArray... arrays) { for (NDArray array : arrays) { unregister(array); } } /** * Unregisters {@link NDArray} object from this scope. * * @param ndlist the {@link NDList} object */ public static void unregister(NDList ndlist) { ndlist.forEach(NDScope::unregister); } /** {@inheritDoc} */ @Override public void close() { for (NDArray array : resources.keySet()) { array.close(); } SCOPE_STACK.get().remove(this); } /** * A method that does nothing. * * <p>You may use it if you do not have a better way to suppress the warning of a created but * not explicitly used scope. */ public void suppressNotUsedWarning() { // do nothing } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/ndarray/NDSerializer.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.ndarray; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; /** A class contains encoding and decoding logic for NDArray. */ final class NDSerializer { private static final int VERSION = 3; private static final int BUFFER_SIZE = 1024 * 1024; private static final String MAGIC_NUMBER = "NDAR"; private static final byte[] NUMPY_MAGIC = {(byte) 0x93, 'N', 'U', 'M', 'P', 'Y'}; private static final int ARRAY_ALIGN = 64; private static final Pattern PATTERN = Pattern.compile("\\{'descr': '(.+)', 'fortran_order': False, 'shape': \\((.*)\\),"); private NDSerializer() {} /** * Encodes {@link NDArray} to byte array. * * @param array the input {@link NDArray} * @return byte array */ static byte[] encode(NDArray array) { int total = Math.toIntExact(array.size()) * array.getDataType().getNumOfBytes() + 100; try (ByteArrayOutputStream baos = new ByteArrayOutputStream(total)) { encode(array, baos); return baos.toByteArray(); } catch (IOException e) { throw new AssertionError("This should never happen", e); } } static void encode(NDArray array, OutputStream os) throws IOException { DataOutputStream dos; if (os instanceof DataOutputStream) { dos = (DataOutputStream) os; } else { dos = new DataOutputStream(os); } // magic string for version identification dos.writeUTF(MAGIC_NUMBER); dos.writeInt(VERSION); String name = array.getName(); if (name == null) { dos.write(0); } else { dos.write(1); dos.writeUTF(name); } dos.writeUTF(array.getSparseFormat().name()); dos.writeUTF(array.getDataType().name()); Shape shape = array.getShape(); dos.write(shape.getEncoded()); if (array.getDataType() == DataType.STRING) { String[] data = array.toStringArray(); dos.writeInt(data.length); for (String str : data) { dos.writeUTF(str); } dos.flush(); return; } ByteBuffer bb = array.toByteBuffer(); dos.write(bb.order() == ByteOrder.BIG_ENDIAN ? '>' : '<'); int length = bb.remaining(); dos.writeInt(length); if (length > 0) { if (bb.hasArray() && bb.remaining() == bb.array().length) { dos.write(bb.array(), bb.position(), length); } else { if (length > BUFFER_SIZE) { byte[] buf = new byte[BUFFER_SIZE]; while (length > BUFFER_SIZE) { bb.get(buf); dos.write(buf); length = bb.remaining(); } } byte[] buf = new byte[length]; bb.get(buf); dos.write(buf); } } dos.flush(); } static void encodeAsNumpy(NDArray array, OutputStream os) throws IOException { StringBuilder sb = new StringBuilder(80); sb.append("{'descr': '") .append(array.getDataType().asNumpy()) .append("', 'fortran_order': False, 'shape': "); long[] shape = array.getShape().getShape(); if (shape.length == 1) { sb.append('(').append(shape[0]).append(",)"); } else { sb.append(array.getShape()); } sb.append(", }"); int len = sb.length() + 1; int padding = ARRAY_ALIGN - (NUMPY_MAGIC.length + len + 4) % ARRAY_ALIGN; ByteBuffer bb = ByteBuffer.allocate(2); bb.order(ByteOrder.LITTLE_ENDIAN); bb.putShort((short) (padding + len)); os.write(NUMPY_MAGIC); os.write(1); os.write(0); // version 1.0 os.write(bb.array()); os.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); for (int i = 0; i < padding; ++i) { os.write(' '); } os.write('\n'); os.write(array.toByteArray()); } static NDArray decode(NDManager manager, ByteBuffer bb) { if (!"NDAR".equals(readUTF(bb))) { throw new IllegalArgumentException("Malformed NDArray data"); } // NDArray encode version int version = bb.getInt(); if (version < 1 || version > VERSION) { throw new IllegalArgumentException("Unexpected NDArray encode version " + version); } String name = null; if (version > 1) { byte flag = bb.get(); if (flag == 1) { name = readUTF(bb); } } readUTF(bb); // ignore SparseFormat // DataType DataType dataType = DataType.valueOf(readUTF(bb)); // Shape Shape shape = Shape.decode(bb); if (dataType == DataType.STRING) { int size = bb.getInt(); String[] data = new String[size]; for (int i = 0; i < size; ++i) { data[i] = readUTF(bb); } NDArray array = manager.create(data, StandardCharsets.UTF_8, shape); array.setName(name); return array; } // Data ByteOrder order; if (version > 2) { order = bb.get() == '>' ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN; } else { order = ByteOrder.nativeOrder(); } int length = bb.getInt(); ByteBuffer data = bb.slice(); data.limit(length); data.order(order); NDArray array = manager.create(data, shape, dataType); array.setName(name); bb.position(bb.position() + length); return array; } /** * Decodes {@link NDArray} through {@link DataInputStream}. * * @param manager the {@link NDManager} assigned to the {@link NDArray} * @param is input stream data to load from * @return {@link NDArray} * @throws IOException data is not readable */ static NDArray decode(NDManager manager, InputStream is) throws IOException { DataInputStream dis; if (is instanceof DataInputStream) { dis = (DataInputStream) is; } else { dis = new DataInputStream(is); } if (!"NDAR".equals(dis.readUTF())) { throw new IllegalArgumentException("Malformed NDArray data"); } // NDArray encode version int version = dis.readInt(); if (version < 1 || version > VERSION) { throw new IllegalArgumentException("Unexpected NDArray encode version " + version); } String name = null; if (version > 1) { byte flag = dis.readByte(); if (flag == 1) { name = dis.readUTF(); } } dis.readUTF(); // ignore SparseFormat // DataType DataType dataType = DataType.valueOf(dis.readUTF()); // Shape Shape shape = Shape.decode(dis); // Data ByteOrder order; if (version > 2) { order = dis.readByte() == '>' ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN; } else { order = ByteOrder.nativeOrder(); } int length = dis.readInt(); ByteBuffer data = manager.allocateDirect(length); data.order(order); readData(dis, data, length); NDArray array = manager.create(data, shape, dataType); array.setName(name); return array; } static NDArray decodeNumpy(NDManager manager, InputStream is) throws IOException { DataInputStream dis; if (is instanceof DataInputStream) { dis = (DataInputStream) is; } else { dis = new DataInputStream(is); } byte[] buf = new byte[NUMPY_MAGIC.length]; dis.readFully(buf); if (!Arrays.equals(buf, NUMPY_MAGIC)) { throw new IllegalArgumentException("Malformed numpy data"); } byte major = dis.readByte(); byte minor = dis.readByte(); if (major < 1 || major > 3 || minor != 0) { throw new IllegalArgumentException("Unknown numpy version: " + major + '.' + minor); } int len = major == 1 ? 2 : 4; dis.readFully(buf, 0, len); ByteBuffer bb = ByteBuffer.wrap(buf, 0, len); bb.order(ByteOrder.LITTLE_ENDIAN); if (major == 1) { len = bb.getShort(); } else { len = bb.getInt(); } buf = new byte[len]; dis.readFully(buf); String header = new String(buf, StandardCharsets.UTF_8).trim(); Matcher m = PATTERN.matcher(header); if (!m.find()) { throw new IllegalArgumentException("Invalid numpy header: " + header); } String typeStr = m.group(1); DataType dataType = DataType.fromNumpy(typeStr); String shapeStr = m.group(2); long[] longs; if (shapeStr.isEmpty()) { longs = new long[0]; } else { String[] tokens = shapeStr.split(", ?"); longs = Arrays.stream(tokens).mapToLong(Long::parseLong).toArray(); } Shape shape = new Shape(longs); len = Math.toIntExact(shape.size() * dataType.getNumOfBytes()); ByteBuffer data = manager.allocateDirect(len); char order = typeStr.charAt(0); if (order == '>') { data.order(ByteOrder.BIG_ENDIAN); } else if (order == '<') { data.order(ByteOrder.LITTLE_ENDIAN); } readData(dis, data, len); return manager.create(data, shape, dataType); } private static void readData(DataInputStream dis, ByteBuffer data, int len) throws IOException { if (len > 0) { byte[] buf = new byte[BUFFER_SIZE]; while (len > BUFFER_SIZE) { dis.readFully(buf); data.put(buf); len -= BUFFER_SIZE; } dis.readFully(buf, 0, len); data.put(buf, 0, len); data.rewind(); } } private static String readUTF(ByteBuffer bb) { int len = (bb.get() & 0xFF << 8) + (bb.get() & 0xFF); byte[] buf = new byte[len]; char[] chars = new char[len]; bb.get(buf); int chararrCount = 0; int count = 0; while (count < len) { int c = (int) buf[count] & 0xff; if (c > 127) { break; } count++; chars[chararrCount++] = (char) c; } while (count < len) { int c = (int) buf[count] & 0xff; switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: /* 0xxxxxxx */ count++; chars[chararrCount++] = (char) c; break; case 12: case 13: // 110x xxxx 10xx xxxx count += 2; if (count > len) { throw new IllegalArgumentException("malformed UTF-8 input"); } int char2 = buf[count - 1]; if ((char2 & 0xC0) != 0x80) { throw new IllegalArgumentException("malformed input around byte " + count); } chars[chararrCount++] = (char) (((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: // 1110 xxxx 10xx xxxx 10xx xxxx count += 3; if (count > len) { throw new IllegalArgumentException("malformed UTF-8 input"); } char2 = (int) buf[count - 2]; int char3 = (int) buf[count - 1]; if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) { throw new IllegalArgumentException("malformed UTF-8 input"); } chars[chararrCount++] = (char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | (char3 & 0x3F)); break; default: // 10xx xxxx, 1111 xxxx throw new IllegalArgumentException("malformed input around byte " + count); } } return new String(chars, 0, chararrCount); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/ndarray/NDUtils.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.ndarray; import ai.djl.ndarray.types.Shape; import java.util.stream.IntStream; import java.util.stream.Stream; /** A class containing utility methods for NDArray operations. */ public final class NDUtils { private NDUtils() {} /** * Returns {@link Shape} of the empty {@link NDArray} after applying reduction operations. * * @param shape input shape * @param axis axis to apply reduction * @return the result {@link Shape} */ public static Shape getShapeFromEmptyNDArrayForReductionOp(Shape shape, int axis) { final long[] shapeArr = shape.getShape(); if (shapeArr[axis] == 0) { throw new IllegalArgumentException("attempt to apply reduction of an empty NDArray"); } long[] newShape = IntStream.range(0, shapeArr.length) .filter(i -> i != axis) .mapToLong(i -> shapeArr[i]) .toArray(); return new Shape(newShape); } /** * Check two criteria of concat input: 1. no scalar 2. dimensions of all the array must be the * same. * * @param list input {@link NDList} */ public static void checkConcatInput(NDList list) { NDArray[] arrays = list.toArray(new NDArray[0]); if (Stream.of(arrays).allMatch(array -> array.getShape().dimension() == 0)) { throw new IllegalArgumentException( "scalar(zero-dimensional) arrays cannot be concatenated"); } int dimension = arrays[0].getShape().dimension(); for (int i = 1; i < arrays.length; i++) { if (arrays[i].getShape().dimension() != dimension) { throw new IllegalArgumentException( "all the input arrays must have same number of dimensions, but the array at" + " index 0 has " + dimension + " dimension(s) and the array at index " + i + " has " + arrays[i].getShape().dimension() + " dimension(s)"); } } } }