index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/loss/YOLOv3Loss.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.training.loss; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDArrays; 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.nn.Activation; /** * {@code YOLOv3Loss} is an implementation of {@link Loss}. It is used to compute the loss while * training a YOLOv3 model for object detection. It involves computing the targets given the * generated anchors, labels and predictions, and then computing the sum of class predictions and * bounding box predictions. */ public final class YOLOv3Loss extends Loss { // TODO: currently not finished, still have some bugs inside and it can only be trained with // PyTorch Engine /* PRESETANCHORS shapes come from the K-means clustering of COCO dataset, which image size is 416*416 it can be reshaped into any shape like 256*256, just multiply each value with 256/416 */ private static final float[] PRESETANCHORS = { 116, 90, 156, 198, 373, 326, 30, 61, 62, 45, 59, 119, 10, 13, 16, 30, 33, 23 }; private float[] anchors; private int numClasses; private int boxAttr; private Shape inputShape; private float ignoreThreshold; private NDManager manager; private static final float EPSILON = 1e-7f; private YOLOv3Loss(Builder builder) { super(builder.name); this.anchors = builder.anchorsArray; this.numClasses = builder.numClasses; this.boxAttr = builder.numClasses + 5; // 5 for x,y,h,w,c this.inputShape = builder.inputShape; this.ignoreThreshold = builder.ignoreThreshold; } /** * Gets the preset anchors of YoloV3. * * @return the preset anchors of YoloV3 */ public static float[] getPresetAnchors() { return PRESETANCHORS.clone(); } /** * Make the value of given NDArray between tMin and tMax. * * @param tList the given NDArray * @param tMin the min value * @param tMax the max value * @return a NDArray where values are set between tMin and tMax */ public NDArray clipByTensor(NDArray tList, float tMin, float tMax) { NDArray result = tList.gte(tMin).mul(tList).add(tList.lt(tMin).mul(tMin)); result = result.lte(tMax).mul(result).add(result.gt(tMax).mul(tMax)); return result; } /** * Calculates the MSELoss between prediction and target. * * @param prediction the prediction array * @param target the target array * @return the MSELoss between prediction and target */ public NDArray mseLoss(NDArray prediction, NDArray target) { return prediction.sub(target).pow(2); } /** * Calculates the BCELoss between prediction and target. * * @param prediction the prediction array * @param target the target array * @return the BCELoss between prediction and target */ public NDArray bceLoss(NDArray prediction, NDArray target) { prediction = clipByTensor(prediction, EPSILON, (float) (1.0 - EPSILON)); return prediction .log() .mul(target) .add(prediction.mul(-1).add(1).log().mul(target.mul(-1).add(1))) .mul(-1); } /** {@inheritDoc} */ @Override public NDArray evaluate(NDList labels, NDList predictions) { manager = predictions.getManager(); /* three outputs in total NDArray out0 = predictions.get(0), //Shape = (batchSize * 75 * 13 * 13) 75 = 3*(20+5) out1 = predictions.get(1), //Shape = (batchSize * 75 * 26 * 26) out2 = predictions.get(2); //Shape = (batchSize * 75 * 52 * 52) */ NDArray[] lossComponents = new NDArray[3]; for (int i = 0; i < 3; i++) { lossComponents[i] = evaluateOneOutput(i, predictions.get(i), labels.singletonOrThrow()); } // calculate the final loss return NDArrays.add(lossComponents); } /** * Computes the Loss for one outputLayer. * * @param componentIndex which outputLayer does current input represent. the shape should be * (13*13,26*26,52*52) * @param input one prediction layer of YOLOv3 * @param labels target labels. Must contain (offsetLabels, masks, classlabels) * @return the total loss of a outputLayer */ public NDArray evaluateOneOutput(int componentIndex, NDArray input, NDArray labels) { int batchSize = (int) input.getShape().get(0); int inW = (int) input.getShape().get(2); int inH = (int) input.getShape().get(3); NDArray prediction = input.reshape(batchSize, 3, boxAttr, inW, inH) .transpose(1, 0, 3, 4, 2); // reshape into (3,batchSize,inW,inH,attrs) // the prediction value of x,y,w,h which shape should be (3,batchSize,inW,inH) NDArray x = Activation.sigmoid(prediction.get("...,0")); NDArray y = Activation.sigmoid(prediction.get("...,1")); NDArray w = prediction.get("...,2"); NDArray h = prediction.get("...,3"); // Confidence of whether there is an object and conditional probability of each class // it should be reshaped into (batchSize,3) NDArray conf = Activation.sigmoid(prediction.get("...,4")).transpose(1, 0, 2, 3); NDArray predClass = Activation.sigmoid(prediction.get("...,5:")).transpose(1, 0, 2, 3, 4); // get an NDList of groundTruth which contains boxLossScale and groundTruth NDList truthList = getTarget(labels, inH, inW); /* boxLossScale shape should be: (batchSize,3,inW,inH) groundTruth shape should be: (3,batchSize,inW,inH,boxAttr) */ NDArray boxLossScale = truthList.get(0).transpose(1, 0, 2, 3); NDArray groundTruth = truthList.get(1); // iou shape should be: (batchSize,3 ,inW,inH) NDArray iou = calculateIOU(x, y, groundTruth.get("...,0:4"), componentIndex) .transpose(1, 0, 2, 3); // get noObjMask and objMask NDArray noObjMask = NDArrays.where( iou.lte(ignoreThreshold), manager.ones(iou.getShape()), manager.create(0f)); NDArray objMask = iou.argMax(1).oneHot(3).transpose(0, 3, 1, 2); objMask = NDArrays.where( iou.gte(ignoreThreshold / 2), objMask, manager.zeros(objMask.getShape())); // to get rid of wrong ones noObjMask = NDArrays.where(objMask.eq(1f), manager.zeros(noObjMask.getShape()), noObjMask); NDArray xTrue = groundTruth.get("...,0"); NDArray yTrue = groundTruth.get("...,1"); NDArray wTrue = groundTruth.get("...,2"); NDArray hTrue = groundTruth.get("...,3"); NDArray classTrue = groundTruth.get("...,4:").transpose(1, 0, 2, 3, 4); NDArray widths = manager.create( new float[] { anchors[componentIndex * 6], anchors[componentIndex * 6 + 2], anchors[componentIndex * 6 + 4] }) .div(inputShape.get(0)); NDArray heights = manager.create( new float[] { anchors[componentIndex * 6 + 1], anchors[componentIndex * 6 + 3], anchors[componentIndex * 6 + 5] }) .div(inputShape.get(1)); // three loss parts: box Loss, confidence Loss, and class Loss NDArray boxLoss = objMask.mul(boxLossScale) .mul( NDArrays.add( xTrue.sub(x).pow(2), yTrue.sub(y).pow(2), wTrue.sub( w.exp() .mul( widths.broadcast( inH, inW, batchSize, 3) .transpose( 3, 2, 1, 0))) .pow(2), hTrue.sub( h.exp() .mul( heights.broadcast( inH, inW, batchSize, 3) .transpose( 3, 2, 1, 0))) .pow(2)) .transpose(1, 0, 2, 3)) .sum(); NDArray confLoss = objMask.mul( conf.add(EPSILON) .log() .mul(-1) .add(bceLoss(predClass, classTrue).sum(new int[] {4}))) .sum(); NDArray noObjLoss = noObjMask.mul(conf.mul(-1).add(1 + EPSILON).log().mul(-1)).sum(); return boxLoss.add(confLoss).add(noObjLoss).div(batchSize); } /** * Gets target NDArray for a given evaluator. * * @param labels the true labels * @param inH the height of current layer * @param inW the width of current layer * @return an NDList of {boxLossScale and groundTruth} */ public NDList getTarget(NDArray labels, int inH, int inW) { int batchSize = (int) labels.size(0); // the loss Scale of a box, used to punctuate small boxes NDList boxLossComponents = new NDList(); // the groundTruth of a true object in pictures NDList groundTruthComponents = new NDList(); // Shape of labels:(batchSize,objectNum,5) for (int batch = 0; batch < batchSize; batch++) { if (labels.get(batch).size(0) == 0) { continue; // no object in current picture } NDArray boxLoss = manager.zeros(new Shape(inW, inH), DataType.FLOAT32); NDArray groundTruth = manager.zeros(new Shape(inW, inH, boxAttr - 1), DataType.FLOAT32); NDArray picture = labels.get(batch); // the shape should be (objectNums,5) NDArray xgt = picture.get("...,1").add(picture.get("...,3").div(2)).mul(inW); // Center of x should be X value in labels and add half of the width and multiplies the // input width to get which grid cell it's in NDArray ygt = picture.get("...,2").add(picture.get("...,4").div(2)).mul(inH); // Center of y is the same as well NDArray wgt = picture.get("...,3"); // the width of the ground truth box NDArray hgt = picture.get("...,4"); // the height of the ground truth box // we should transform the presentation of true class, like // [[0],[1],[2]]->[[1,0,0,...0],[0,1,0,...,0],[0,0,1,...,0]] NDArray objectClass = picture.get("...,0"); objectClass = objectClass.oneHot(numClasses); NDArray curLabel = labels.get(batch); // curLabel shape:(objectNum,5) int objectNum = (int) curLabel.size(0); for (int i = 0; i < objectNum; i++) { // for each object, the middle of the object(x and y) should be in one grid cell of // 13*13 // the tx and ty should indicate the grid cell and bx and by should indicate the // movement from top-left of the grid cell int tx = (int) xgt.get(i).getFloat(); int ty = (int) ygt.get(i).getFloat(); float bx = xgt.get(i).getFloat() - tx; float by = ygt.get(i).getFloat() - ty; String index = tx + "," + ty; // set groundTruth groundTruth.set(new NDIndex(index + ",0"), bx); groundTruth.set(new NDIndex(index + ",1"), by); groundTruth.set(new NDIndex(index + ",2"), wgt.getFloat(i)); groundTruth.set(new NDIndex(index + ",3"), hgt.getFloat(i)); groundTruth.set(new NDIndex(index + ",4:"), objectClass.get(i)); // set boxLoss boxLoss.set(new NDIndex(index), 2 - wgt.getFloat(i) * hgt.getFloat(i)); } boxLossComponents.add(boxLoss); groundTruthComponents.add(groundTruth); } NDArray boxLossScale = NDArrays.stack(boxLossComponents).broadcast(3, batchSize, inW, inH); NDArray groundTruth = NDArrays.stack(groundTruthComponents) .broadcast(3, batchSize, inW, inH, boxAttr - 1); return new NDList(boxLossScale, groundTruth); } /** * Calculates the IOU between priori Anchors and groundTruth. * * @param predx the tx value of prediction * @param predy the ty value of prediction * @param groundTruth the groundTruth value of labels * @param componentIndex the current component Index * @return an NDArray of IOU */ public NDArray calculateIOU( NDArray predx, NDArray predy, NDArray groundTruth, int componentIndex) { int inW = (int) predx.getShape().get(2); int inH = (int) predx.getShape().get(3); int strideW = (int) inputShape.get(0) / inW; int strideH = (int) inputShape.get(1) / inH; NDList iouComponent = new NDList(); // shape of predx, predy should all be (3,batchSize,inW,inH) // shape of groundTruth should be (3,batchSize,inW,inH,4) for (int i = 0; i < 3; i++) { NDArray curPredx = predx.get(i); NDArray curPredy = predy.get(i); float width = anchors[componentIndex * 6 + 2 * i] / strideW; float height = anchors[componentIndex * 6 + 2 * i + 1] / strideH; NDArray predLeft = curPredx.sub(width / 2); NDArray predRight = curPredx.add(width / 2); NDArray predTop = curPredy.sub(height / 2); NDArray predBottom = curPredy.add(height / 2); NDArray truth = groundTruth.get(i); NDArray trueLeft = truth.get("...,0").sub(truth.get("...,2").mul(inW).div(2)); NDArray trueRight = truth.get("...,0").add(truth.get("...,2").mul(inW).div(2)); NDArray trueTop = truth.get("...,1").sub(truth.get("...,3").mul(inH).div(2)); NDArray trueBottom = truth.get("...,1").add(truth.get("...,3").mul(inH).div(2)); NDArray left = NDArrays.maximum(predLeft, trueLeft); NDArray right = NDArrays.minimum(predRight, trueRight); NDArray top = NDArrays.maximum(predTop, trueTop); NDArray bottom = NDArrays.minimum(predBottom, trueBottom); NDArray inter = right.sub(left).mul(bottom.sub(top)); NDArray union = truth.get("...,2") .mul(inW) .mul(truth.get("...,3").mul(inH)) .add(width * height) .sub(inter) .add(EPSILON); // should not be divided by zero iouComponent.add(inter.div(union)); } return NDArrays.stack(iouComponent); } /** * Creates a new builder to build a {@link YOLOv3Loss}. * * @return a new builder; */ public static Builder builder() { return new Builder(); } /** The Builder to construct a {@link YOLOv3Loss} object. */ public static class Builder { private String name = "YOLOv3Loss"; private float[] anchorsArray = PRESETANCHORS; private int numClasses = 20; private Shape inputShape = new Shape(419, 419); private float ignoreThreshold = 0.5f; /** * Sets the loss name of YoloV3Loss. * * @param name the name of loss function * @return this {@code Builder} */ public Builder setName(String name) { this.name = name; return this; } /** * Sets the preset anchors for YoloV3. * * @param anchorsArray the anchors in float array * @return this {@code Builder} */ public Builder setAnchorsArray(float[] anchorsArray) { if (anchorsArray.length != PRESETANCHORS.length) { throw new IllegalArgumentException( String.format( "setAnchorsArray requires anchors of length %d, but was given" + " filters of length %d instead", PRESETANCHORS.length, anchorsArray.length)); } this.anchorsArray = anchorsArray; return this; } /** * Sets the number of total classes. * * @param numClasses the number of total classes * @return this {@code Builder} */ public Builder setNumClasses(int numClasses) { this.numClasses = numClasses; return this; } /** * Sets the shape of the input picture. * * @param inputShape the shape of input picture. * @return this {@code Builder} */ public Builder setInputShape(Shape inputShape) { this.inputShape = inputShape; return this; } /** * Sets the ignoreThreshold for iou to check if we think it detects a picture. * * @param ignoreThreshold the ignore threshold * @return this {@code Builder} */ public Builder optIgnoreThreshold(float ignoreThreshold) { this.ignoreThreshold = ignoreThreshold; return this; } /** * Builds a {@link YOLOv3Loss} instance. * * @return a {@link YOLOv3Loss} instance. */ public YOLOv3Loss build() { return new YOLOv3Loss(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/loss/package-info.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** * Contains classes for measuring the {@link ai.djl.training.loss.Loss} of a model. * * <p>It contains a main interface {@link ai.djl.training.loss.Loss} and various losses that extend * it. */ package ai.djl.training.loss;
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/optimizer/Adadelta.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.training.optimizer; import ai.djl.Device; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.internal.NDArrayEx; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * {@code Adadelta} is an Adadelta {@code Optimizer}. * * @see <a href="https://d2l.djl.ai/chapter_optimization/adadelta.html">The D2L chapter on * Adadelta</a> */ public class Adadelta extends Optimizer { private float rho; private float epsilon; private Map<String, Map<Device, NDArray>> accumG; private Map<String, Map<Device, NDArray>> accumDelta; /** * Creates a new instance of {@code Adadelta}. * * @param builder the builder to create a new instance of {@link Adadelta} */ protected Adadelta(Builder builder) { super(builder); rho = builder.rho; epsilon = builder.epsilon; accumG = new ConcurrentHashMap<>(); accumDelta = new ConcurrentHashMap<>(); } /** {@inheritDoc} */ @Override public void update(String parameterId, NDArray weight, NDArray grad) { float weightDecay = getWeightDecay(); NDList inputs = new NDList( weight, grad, withDefaultState( accumG, parameterId, weight.getDevice(), k -> weight.zerosLike()), withDefaultState( accumDelta, parameterId, weight.getDevice(), k -> weight.zerosLike())); NDList weights = new NDList(weight); NDArrayEx ex = weight.getNDArrayInternal(); ex.adadeltaUpdate(inputs, weights, weightDecay, rescaleGrad, clipGrad, rho, epsilon); } /** The Builder to construct an {@link Adadelta} object. */ public static final class Builder extends OptimizerBuilder<Builder> { private float rho = 0.9f; private float epsilon = 1e-8f; Builder() {} /** {@inheritDoc} */ @Override protected Builder self() { return this; } /** * Sets the rho for {@link Adadelta}. * * @param rho the value of rho * @return this {@code Builder} */ public Builder optRho(float rho) { this.rho = rho; return this; } /** * Sets \(epsilon\) - a small quantity for numerical stability. * * @param epsilon a small quantity for numerical stability * @return this {@code Builder} */ public Adadelta.Builder optEpsilon(float epsilon) { this.epsilon = epsilon; return this; } /** * Builds a {@link Adadelta} block. * * @return the {@link Adadelta} block */ public Adadelta build() { return new Adadelta(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/optimizer/Adagrad.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.training.optimizer; import ai.djl.Device; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.internal.NDArrayEx; import ai.djl.ndarray.types.SparseFormat; import ai.djl.training.tracker.ParameterTracker; import ai.djl.training.tracker.Tracker; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * {@code Adagrad} is an AdaGrad {@link Optimizer}. * * <p>This class implements * * <p>Adagrad updates the weights using:<br> * <br> * \( grad = clip(grad * resc_grad, clip_grad) + wd * weight \)<br> * \( history += grad^2 \)<br> * \( weight -= lr * grad / (sqrt(history) + epsilon) \)<br> * <br> * where grad represents the gradient, wd represents weight decay, and lr represents learning rate. * * @see <a href="https://d2l.djl.ai/chapter_optimization/adagrad.html">The D2L chapter on * Adagrad</a> */ public class Adagrad extends Optimizer { private ParameterTracker learningRateTracker; private float epsilon; private Map<String, Map<Device, NDArray>> history; /** * Creates a new instance of {@code Adam} optimizer. * * @param builder the builder to create a new instance of {@code Adam} optimizer */ protected Adagrad(Builder builder) { super(builder); learningRateTracker = builder.learningRateTracker; epsilon = builder.epsilon; history = new ConcurrentHashMap<>(); } /** {@inheritDoc} */ @Override public void update(String parameterId, NDArray weight, NDArray grad) { int t = updateCount(parameterId); float newLearningRate = learningRateTracker.getNewValue(parameterId, t); float weightDecay = getWeightDecay(); if (Float.isNaN(newLearningRate) || Float.isNaN(weightDecay) || Float.isInfinite(newLearningRate) || Float.isInfinite(weightDecay)) { throw new IllegalStateException("learning rate or weight decay is nan or infinite"); } NDList inputs = new NDList( weight, grad.toSparse(SparseFormat.ROW_SPARSE), // FIXME: add regular adagrad MxNet withDefaultState( history, parameterId, weight.getDevice(), k -> weight.zerosLike())); NDList weights = new NDList(weight); NDArrayEx ex = weight.getNDArrayInternal(); // TODO: change to our own implementation ex.adagradUpdate( inputs, weights, newLearningRate, weightDecay, rescaleGrad, clipGrad, epsilon); } /** * Creates a builder to build a {@code Adam}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The Builder to construct an {@link Adagrad} object. */ public static final class Builder extends OptimizerBuilder<Builder> { private ParameterTracker learningRateTracker = Tracker.fixed(0.001f); private float epsilon = 1e-8f; Builder() {} /** {@inheritDoc} */ @Override protected Builder self() { return this; } /** * Sets the {@link ParameterTracker} for this optimizer. * * @param learningRateTracker the {@link ParameterTracker} to be set * @return this {@code Builder} */ public Builder optLearningRateTracker(ParameterTracker learningRateTracker) { this.learningRateTracker = learningRateTracker; return this; } /** * Sets \(epsilon\) - a small quantity for numerical stability. * * @param epsilon a small quantity for numerical stability * @return this {@code Builder} */ public Builder optEpsilon(float epsilon) { this.epsilon = epsilon; return this; } /** * Builds a {@link Adagrad} block. * * @return the {@link Adagrad} block */ public Adagrad build() { return new Adagrad(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/optimizer/Adam.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.training.optimizer; import ai.djl.Device; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.internal.NDArrayEx; import ai.djl.training.tracker.ParameterTracker; import ai.djl.training.tracker.Tracker; import ai.djl.util.Preconditions; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * {@code Adam} is a generalization of the AdaGrad {@link Optimizer}. <br> * \( grad += weight_decay * w\)<br> * \( m = beta1 * m + (1 - beta1) * grad\)<br> * \( v = beta2 * v + (1 - beta2) * grad^2 \)<br> * \( learning_rate_bias_correction = learning_rate / beta1**t * sqrt(beta2**t) \)<br> * \( w -= learning_rate_bias_correction * m / (sqrt(v) + epsilon) \)<br> * <br> * where g represents the gradient, and m/v are 1st and 2nd order moment estimates (mean and * variance), t is the step. * * @see <a href="https://d2l.djl.ai/chapter_optimization/adam.html">The D2L chapter on Adam</a> */ public class Adam extends Optimizer { private ParameterTracker learningRateTracker; private float beta1; private float beta2; private float epsilon; private Map<String, Map<Device, NDArray>> means; private Map<String, Map<Device, NDArray>> variances; /** * Creates a new instance of {@code Adam} optimizer. * * @param builder the builder to create a new instance of {@code Adam} optimizer */ protected Adam(Builder builder) { super(builder); learningRateTracker = builder.learningRateTracker; beta1 = builder.beta1; beta2 = builder.beta2; epsilon = builder.epsilon; means = new ConcurrentHashMap<>(); variances = new ConcurrentHashMap<>(); } /** {@inheritDoc} */ @Override public void update(String parameterId, NDArray weight, NDArray grad) { int t = updateCount(parameterId); double coef1 = 1.0 - Math.pow(beta1, t); double coef2 = 1.0 - Math.pow(beta2, t); float newLearningRate = learningRateTracker.getNewValue(parameterId, t); float learningRateBiasCorrection = (float) (newLearningRate * Math.sqrt(coef2) / coef1); float weightDecay = getWeightDecay(); Preconditions.checkArgument( !Float.isNaN(learningRateBiasCorrection) && !Float.isNaN(weightDecay) && !Float.isInfinite(learningRateBiasCorrection) && !Float.isInfinite(weightDecay), "learning rate or weight decay is nan or infinite"); NDList inputs = new NDList( weight, grad, withDefaultState( means, parameterId, weight.getDevice(), k -> weight.zerosLike()), withDefaultState( variances, parameterId, weight.getDevice(), k -> weight.zerosLike())); NDList weights = new NDList(weight); NDArrayEx ex = weight.getNDArrayInternal(); ex.adamUpdate( inputs, weights, newLearningRate, learningRateBiasCorrection, weightDecay, rescaleGrad, clipGrad, beta1, beta2, epsilon, true, false); } /** * Creates a builder to build a {@code Adam}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The Builder to construct an {@link Adam} object. */ public static final class Builder extends OptimizerBuilder<Builder> { private ParameterTracker learningRateTracker = Tracker.fixed(0.001f); private float beta1 = 0.9f; private float beta2 = 0.999f; private float epsilon = 1e-8f; Builder() {} /** {@inheritDoc} */ @Override protected Builder self() { return this; } /** * Sets the {@link ParameterTracker} for this optimizer. * * @param learningRateTracker the {@link ParameterTracker} to be set * @return this {@code Builder} */ public Builder optLearningRateTracker(ParameterTracker learningRateTracker) { this.learningRateTracker = learningRateTracker; return this; } /** * Sets the decay rate for the first moment estimates. * * @param beta1 the deacay rate for the the first moment estimates * @return this {@code Builder} */ public Builder optBeta1(float beta1) { this.beta1 = beta1; return this; } /** * Sets the decay rate for the second moment estimates. * * @param beta2 the decay rate for the the second moment estimates * @return this {@code Builder} */ public Builder optBeta2(float beta2) { this.beta2 = beta2; return this; } /** * Sets \(epsilon\) - a small quantity for numerical stability. * * @param epsilon a small quantity for numerical stability * @return this {@code Builder} */ public Builder optEpsilon(float epsilon) { this.epsilon = epsilon; return this; } /** * Builds a {@link Adam} block. * * @return the {@link Adam} block */ public Adam build() { return new Adam(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/optimizer/AdamW.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.training.optimizer; import ai.djl.Device; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.internal.NDArrayEx; import ai.djl.training.tracker.ParameterTracker; import ai.djl.training.tracker.Tracker; import ai.djl.util.Preconditions; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * {@code Adam} is a generalization of the AdaGrad {@link Optimizer}. * * <p>Adam updates the weights using:<br> * <br> * \( w *= (1 - learning_rate * weight_decay\)<br> * \( m = beta1 * m + (1 - beta1) * grad\)<br> * \( v = beta2 * v + (1 - beta2) * grad^2 \)<br> * \( learning_rate_bias_correction = learning_rate / beta1**t * sqrt(beta2**t) \)<br> * \( w -= learning_rate_bias_correction * m / (sqrt(v) + epsilon) \)<br> * <br> * where g represents the gradient, and m/v are 1st and 2nd order moment estimates (mean and * variance), t is the step. * * @see <a href="https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html">The algorithm of * AdamW</a> */ public class AdamW extends Optimizer { private ParameterTracker learningRateTracker; private float beta1; private float beta2; private float epsilon; private Map<String, Map<Device, NDArray>> means; private Map<String, Map<Device, NDArray>> variances; /** * Creates a new instance of {@code Adam} optimizer. * * @param builder the builder to create a new instance of {@code Adam} optimizer */ protected AdamW(Builder builder) { super(builder); learningRateTracker = builder.learningRateTracker; beta1 = builder.beta1; beta2 = builder.beta2; epsilon = builder.epsilon; means = new ConcurrentHashMap<>(); variances = new ConcurrentHashMap<>(); } /** {@inheritDoc} */ @Override public void update(String parameterId, NDArray weight, NDArray grad) { int t = updateCount(parameterId); double coef1 = 1.0 - Math.pow(beta1, t); double coef2 = 1.0 - Math.pow(beta2, t); float newLearningRate = learningRateTracker.getNewValue(parameterId, t); float learningRateBiasCorrection = (float) (newLearningRate * Math.sqrt(coef2) / coef1); float weightDecay = getWeightDecay(); Preconditions.checkArgument( !Float.isNaN(newLearningRate) && !Float.isNaN(weightDecay) && !Float.isInfinite(newLearningRate) && !Float.isInfinite(weightDecay), "learning rate or weight decay is nan or infinite"); NDList inputs = new NDList( weight, grad, withDefaultState( means, parameterId, weight.getDevice(), k -> weight.zerosLike()), withDefaultState( variances, parameterId, weight.getDevice(), k -> weight.zerosLike())); NDList weights = new NDList(weight); NDArrayEx ex = weight.getNDArrayInternal(); ex.adamUpdate( inputs, weights, newLearningRate, learningRateBiasCorrection, weightDecay, rescaleGrad, clipGrad, beta1, beta2, epsilon, true, true); } /** * Creates a builder to build a {@code Adam}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The Builder to construct an {@link AdamW} object. */ public static final class Builder extends OptimizerBuilder<Builder> { private ParameterTracker learningRateTracker = Tracker.fixed(0.001f); private float beta1 = 0.9f; private float beta2 = 0.999f; private float epsilon = 1e-8f; Builder() { optWeightDecays(0.01f); } /** {@inheritDoc} */ @Override protected Builder self() { return this; } /** * Sets the {@link ParameterTracker} for this optimizer. * * @param learningRateTracker the {@link ParameterTracker} to be set * @return this {@code Builder} */ public Builder optLearningRateTracker(ParameterTracker learningRateTracker) { this.learningRateTracker = learningRateTracker; return this; } /** * Sets the decay rate for the first moment estimates. * * @param beta1 the deacay rate for the the first moment estimates * @return this {@code Builder} */ public Builder optBeta1(float beta1) { this.beta1 = beta1; return this; } /** * Sets the decay rate for the second moment estimates. * * @param beta2 the decay rate for the the second moment estimates * @return this {@code Builder} */ public Builder optBeta2(float beta2) { this.beta2 = beta2; return this; } /** * Sets \(epsilon\) - a small quantity for numerical stability. * * @param epsilon a small quantity for numerical stability * @return this {@code Builder} */ public Builder optEpsilon(float epsilon) { this.epsilon = epsilon; return this; } /** * Builds a {@link AdamW} block. * * @return the {@link AdamW} block */ public AdamW build() { return new AdamW(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/optimizer/Nag.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.training.optimizer; import ai.djl.Device; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.internal.NDArrayEx; import ai.djl.training.tracker.ParameterTracker; import ai.djl.util.Preconditions; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; /** * {@code Nag} is a Nesterov accelerated gradient optimizer. * * <p>This optimizer updates each weight by:<br> * \( state = momentum * state + grad + wd *weight\)<br> * \( weight = weight - (lr * (grad + momentum * state))<br> */ public class Nag extends Optimizer { private ParameterTracker learningRateTracker; private float momentum; private Map<String, Map<Device, NDArray>> momentumStates; /** * Creates a new instance of {@code Nag} optimizer. * * @param builder the builder to create a new instance of {@code Nag} optimizer */ protected Nag(Builder builder) { super(builder); learningRateTracker = builder.learningRateTracker; momentum = builder.momentum; momentumStates = new ConcurrentHashMap<>(); } /** {@inheritDoc} */ @Override public void update(String parameterId, NDArray weight, NDArray grad) { // TODO: Support Mixed precision Sparse float newLearningRate = learningRateTracker.getNewValue(parameterId, updateCount(parameterId)); float weightDecay = getWeightDecay(); NDList inputs; if (momentum != 0f) { inputs = new NDList( weight, grad, withDefaultState( momentumStates, parameterId, weight.getDevice(), k -> weight.zerosLike())); } else { inputs = new NDList(weight, grad); } NDList weights = new NDList(weight); NDArrayEx ex = weight.getNDArrayInternal(); ex.nagUpdate( inputs, weights, newLearningRate, weightDecay, rescaleGrad, clipGrad, momentum); } /** The Builder to construct an {@link Nag} object. */ public static final class Builder extends OptimizerBuilder<Builder> { ParameterTracker learningRateTracker; float momentum; Builder() {} /** * Sets the {@link ParameterTracker} for this optimizer. * * @param learningRateTracker the {@link ParameterTracker} to be set * @return this {@code Builder} */ public Builder setLearningRateTracker(ParameterTracker learningRateTracker) { this.learningRateTracker = learningRateTracker; return this; } /** * Sets the momentum for {@link Nag}. * * @param momentum the value of momentum * @return this {@code Builder} */ public Builder setMomentum(float momentum) { this.momentum = momentum; return this; } /** {@inheritDoc} */ @Override protected Builder self() { return this; } /** * Builds a {@link Nag} block. * * @return the {@link Nag} block */ public Nag build() { Objects.requireNonNull(learningRateTracker, "No lrTracker set"); Preconditions.checkArgument(momentum != 0, "The momentum should be set"); return new Nag(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/optimizer/Optimizer.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.training.optimizer; import ai.djl.Device; import ai.djl.ndarray.NDArray; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; /** * An {@code Optimizer} updates the weight parameters to minimize the loss function. {@code * Optimizer} is an abstract class that provides the base implementation for optimizers. * * @see <a href="https://d2l.djl.ai/chapter_optimization/index.html">The D2L chapters on * optimization algorithms</a> */ public abstract class Optimizer { protected float rescaleGrad; protected float clipGrad; private float weightDecays; private int beginNumUpdate; private int numUpdate; private Map<String, Integer> updateCounts = new ConcurrentHashMap<>(); /** * Creates a new instance of {@code Optimizer}. * * @param builder the builder used to create an instance of {@code Optimizer} */ public Optimizer(OptimizerBuilder<?> builder) { this.rescaleGrad = builder.rescaleGrad; this.weightDecays = builder.weightDecays; this.clipGrad = builder.clipGrad; this.beginNumUpdate = builder.beginNumUpdate; } /** * Returns a new instance of {@link ai.djl.training.optimizer.Sgd.Builder} that can build an * {@link Sgd} optimizer. * * @return the {@link Sgd} {@link ai.djl.training.optimizer.Sgd.Builder} */ public static Sgd.Builder sgd() { return new Sgd.Builder(); } /** * Returns a new instance of {@link ai.djl.training.optimizer.Nag.Builder} that can build an * {@link Nag} optimizer. * * @return the {@link Nag} {@link ai.djl.training.optimizer.Nag.Builder} */ public static Nag.Builder nag() { return new Nag.Builder(); } /** * Returns a new instance of {@link ai.djl.training.optimizer.Adam.Builder} that can build an * {@link Adam} optimizer. * * @return the {@link Adam} {@link ai.djl.training.optimizer.Adam.Builder} */ public static Adam.Builder adam() { return new Adam.Builder(); } /** * Returns a new instance of {@link ai.djl.training.optimizer.AdamW.Builder} that can build an * {@link AdamW} optimizer. * * @return the {@link AdamW} {@link ai.djl.training.optimizer.AdamW.Builder} */ public static AdamW.Builder adamW() { return new AdamW.Builder(); } /** * Returns a new instance of {@link RmsProp.Builder} that can build an {@link RmsProp} * optimizer. * * @return the {@link RmsProp} {@link RmsProp.Builder} */ public static RmsProp.Builder rmsprop() { return new RmsProp.Builder(); } /** * Returns a new instance of {@link ai.djl.training.optimizer.Adagrad.Builder} that can build an * {@link Adagrad} optimizer. * * @return the {@link Adagrad} {@link ai.djl.training.optimizer.Adagrad.Builder} */ public static Adagrad.Builder adagrad() { return new Adagrad.Builder(); } /** * Returns a new instance of {@link ai.djl.training.optimizer.Adadelta.Builder} that can build * an {@link Adadelta} optimizer. * * @return the {@link Adadelta} {@link ai.djl.training.optimizer.Adadelta.Builder} */ public static Adadelta.Builder adadelta() { return new Adadelta.Builder(); } /** * Gets the value of weight decay. * * @return the value of weight decay */ protected float getWeightDecay() { return weightDecays; } protected int updateCount(String parameterId) { // if index exists, increment update count, if not, use begin number of update + 1 int count = updateCounts.compute( parameterId, (key, val) -> (val == null) ? beginNumUpdate + 1 : val + 1); numUpdate = Math.max(numUpdate, count); return numUpdate; } /** * Updates the parameters according to the gradients. * * @param parameterId the parameter to be updated * @param weight the weights of the parameter * @param grad the gradients */ public abstract void update(String parameterId, NDArray weight, NDArray grad); protected NDArray withDefaultState( Map<String, Map<Device, NDArray>> state, String key, Device device, Function<String, NDArray> defaultFunction) { Map<Device, NDArray> arrayMap = state.computeIfAbsent( key, k -> { Map<Device, NDArray> map = new ConcurrentHashMap<>(); NDArray s = defaultFunction.apply(k); // TODO attach s to the NDManager of ParameterStore s.detach(); // s is detached because it would be put into the optimizer // callback manager and closed after the optimizer callback // when using the MxParameterServer. For now, this will let it be closed // by the // GC when the optimizer is out of scope. Ideally, it should be put into // the // trainer manager instead. map.put(device, s); return map; }); return arrayMap.computeIfAbsent( device, k -> arrayMap.values().iterator().next().toDevice(device, true)); } /** The Builder to construct an {@link Optimizer}. */ @SuppressWarnings("rawtypes") public abstract static class OptimizerBuilder<T extends OptimizerBuilder> { private float rescaleGrad = 1.0f; private float weightDecays; private float clipGrad = -1; private int beginNumUpdate; protected OptimizerBuilder() {} /** * Sets the value used to rescale the gradient. This is used to alleviate the effect of * batching on the loss. Usually, the value is set to \( 1/batch_size \). Defaults to 1. * * @param rescaleGrad the value used to rescale the gradient * @return this {@code Builder} */ public T setRescaleGrad(float rescaleGrad) { this.rescaleGrad = rescaleGrad; return self(); } /** * Sets the value of weight decay. Weight decay augments the objective function with a * regularization term that penalizes large weights. * * @param weightDecays the value of weight decay to be set * @return this {@code Builder} */ public T optWeightDecays(float weightDecays) { this.weightDecays = weightDecays; return self(); } /** * Sets the value of the \(clipGrad\). Clips the gradient to the range of \([-clipGrad, * clipGrad]\). If \(clipGrad \lt 0\), gradient clipping is turned off. * * <p>\(grad = max(min(grad, clipGrad), -clipGrad)\) * * @param clipGrad the value of \(clipGrad\) * @return this {@code Builder} */ public T optClipGrad(float clipGrad) { this.clipGrad = clipGrad; return self(); } /** * Sets the initial value of the number of updates. * * @param beginNumUpdate the initial value of the number of updates * @return this {@code Builder} */ public T optBeginNumUpdate(int beginNumUpdate) { this.beginNumUpdate = beginNumUpdate; return self(); } protected abstract T self(); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/optimizer/RmsProp.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.training.optimizer; import ai.djl.Device; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.internal.NDArrayEx; import ai.djl.training.tracker.ParameterTracker; import ai.djl.training.tracker.Tracker; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * The {@code RMSProp} {@link Optimizer}. * * <p>Two versions of RMSProp are implemented. * * <p>If `centered = False`, the algorithm described in * http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf by Tieleman and Hinton, * 2012 is used. * * <p>If `centered = True`, the algorithm described in http://arxiv.org/pdf/1308.0850v5.pdf * (38)-(45) by Alex Graves, 2013 is used instead. * * <p>Default version is `centered = False`. * * <p>If `centered = False`: * * <p>RMSProp updates the weights using:<br> * <br> * \( var = rho * var + (1 - rho) * grad^2 \)<br> * \( weight -= learning_rate * (sqrt(v) + epsilon) \)<br> * <br> * If `centered = True`: \( mean = rho * mean + (1 - rho) * grad \)<br> * \( var = rho * var + (1 - rho) * grad^2 \)<br> * \( mom = mom^2 - lr * grad / sqrt(var - mean^2) + epsilon \)<br> * \( weight = mean / (sqrt(var) + epsilon) \)<br> * <br> * Grad represents the gradient, mean and var are the 1st and 2nd order moment estimates (mean and * variance), and mom is the momentum. * * @see <a href="https://d2l.djl.ai/chapter_optimization/rmsprop.html">The D2L chapter on * RMSProp</a> */ public class RmsProp extends Optimizer { private ParameterTracker learningRateTracker; private float rho; private float momentum; private float epsilon; private boolean centered; private Map<String, Map<Device, NDArray>> means; private Map<String, Map<Device, NDArray>> variances; private Map<String, Map<Device, NDArray>> momentums; /** * Creates a new instance of {@code RMSProp} optimizer. * * @param builder the builder to create a new instance of {@code Adam} optimizer */ protected RmsProp(Builder builder) { super(builder); learningRateTracker = builder.learningRateTracker; rho = builder.rho; momentum = builder.momentum; epsilon = builder.epsilon; centered = builder.centered; means = new ConcurrentHashMap<>(); variances = new ConcurrentHashMap<>(); momentums = new ConcurrentHashMap<>(); } /** {@inheritDoc} */ @Override public void update(String parameterId, NDArray weight, NDArray grad) { float newLearningRate = learningRateTracker.getNewValue(parameterId, updateCount(parameterId)); float weightDecay = getWeightDecay(); if (Float.isNaN(newLearningRate) || Float.isNaN(weightDecay) || Float.isInfinite(newLearningRate) || Float.isInfinite(weightDecay)) { throw new IllegalStateException("learning rate or weight decay is nan or infinite"); } NDList inputs; if (!centered) { inputs = new NDList( weight, grad, withDefaultState( means, parameterId, weight.getDevice(), k -> weight.zerosLike())); } else { inputs = new NDList( weight, grad, withDefaultState( means, parameterId, weight.getDevice(), k -> weight.zerosLike()), withDefaultState( variances, parameterId, weight.getDevice(), k -> weight.zerosLike()), withDefaultState( momentums, parameterId, weight.getDevice(), k -> weight.zerosLike())); } NDList weights = new NDList(weight); float gamma1 = rho; float gamma2 = momentum; NDArrayEx ex = weight.getNDArrayInternal(); ex.rmspropUpdate( inputs, weights, newLearningRate, weightDecay, rescaleGrad, clipGrad, gamma1, gamma2, epsilon, centered); } /** * Creates a builder to build a {@code RMSProp}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The Builder to construct an {@link RmsProp} object. */ public static final class Builder extends OptimizerBuilder<Builder> { private ParameterTracker learningRateTracker = Tracker.fixed(0.001f); private float rho = 0.9f; private float momentum = 0.9f; private float epsilon = 1e-8f; private boolean centered; Builder() {} /** {@inheritDoc} */ @Override protected Builder self() { return this; } /** * Sets the {@link ParameterTracker} for this optimizer. * * @param learningRateTracker the {@link ParameterTracker} to be set * @return this {@code Builder} */ public Builder optLearningRateTracker(ParameterTracker learningRateTracker) { this.learningRateTracker = learningRateTracker; return this; } /** * Sets the decay factor for the moving average over the past squared gradient. * * @param rho the decay factor for the moving average over past squared gradient * @return this {@code Builder} */ public Builder optRho(float rho) { this.rho = rho; return this; } /** * Sets the momentum factor. This is only used if centered is set to true. * * @param momentum the momentum factor * @return this {@code Builder} */ public Builder optMomentum(float momentum) { this.momentum = momentum; return this; } /** * Sets \(epsilon\) - a small quantity for numerical stability. * * @param epsilon a small quantity for numerical stability * @return this {@code Builder} */ public Builder optEpsilon(float epsilon) { this.epsilon = epsilon; return this; } /** * Sets which version of RMSProp to use. * * <p>True: Grave's version False: Tieleman and Hinton's version * * @param centered the RMSProp version * @return this {@code Builder} */ public Builder optCentered(boolean centered) { this.centered = centered; return this; } /** * Builds a {@link RmsProp} block. * * @return the {@link RmsProp} block */ public RmsProp build() { return new RmsProp(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/optimizer/Sgd.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.training.optimizer; import ai.djl.Device; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.internal.NDArrayEx; import ai.djl.training.tracker.ParameterTracker; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; /** * {@code Sgd} is a Stochastic Gradient Descent (SGD) optimizer. * * <p>If momentum is not set, it updates weights using the following update function:<br> * \( weight = weight - learning_rate * (gradient + wd * weight) \). * * <p>If momentum is set, it updates weights using the following update function:<br> * \( state = momentum * state + learning_rate * gradient \)<br> * \( weight -= state \)<br> * Momentum update has better convergence rates on neural networks. * * @see <a href="https://d2l.djl.ai/chapter_optimization/sgd.html">The D2L chapter on SGD</a> */ public class Sgd extends Optimizer { private ParameterTracker learningRateTracker; private float momentum; private Map<String, Map<Device, NDArray>> momentumStates; /** * Creates a new instance of {@code Sgd}. * * @param builder the builder to create a new instance of {@link Sgd} */ protected Sgd(Builder builder) { super(builder); learningRateTracker = builder.learningRateTracker; momentum = builder.momentum; momentumStates = new ConcurrentHashMap<>(); } /** {@inheritDoc} */ @Override public void update(String parameterId, NDArray weight, NDArray grad) { // TODO: Support Mixed precision Sparse float weightDecay = getWeightDecay(); float learningRate = learningRateTracker.getNewValue(parameterId, updateCount(parameterId)); NDList inputs; if (momentum != 0f) { NDArray state = withDefaultState( momentumStates, parameterId, weight.getDevice(), k -> weight.zerosLike()); inputs = new NDList(weight, grad, state); } else { inputs = new NDList(weight, grad); } NDList weights = new NDList(weight); NDArrayEx ex = weight.getNDArrayInternal(); ex.sgdUpdate( inputs, weights, learningRate, weightDecay, rescaleGrad, clipGrad, momentum, true); } /** The Builder to construct an {@link Sgd} object. */ public static final class Builder extends OptimizerBuilder<Builder> { ParameterTracker learningRateTracker; float momentum; Builder() {} /** {@inheritDoc} */ @Override protected Builder self() { return this; } /** * Sets the {@link ParameterTracker} for this optimizer. * * @param learningRateTracker the {@link ParameterTracker} to be set * @return this {@code Builder} */ public Builder setLearningRateTracker(ParameterTracker learningRateTracker) { this.learningRateTracker = learningRateTracker; return this; } /** * Sets the momentum for {@link Sgd}. * * @param momentum the value of momentum * @return this {@code Builder} */ public Builder optMomentum(float momentum) { this.momentum = momentum; return this; } /** * Builds a {@link Sgd} block. * * @return the {@link Sgd} block */ public Sgd build() { Objects.requireNonNull(learningRateTracker, "No lrTracker set"); return new Sgd(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/optimizer/package-info.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** * Contains classes for optimizing a neural network {@link ai.djl.nn.Block}. * * <p>It contains a main interface {@link ai.djl.training.optimizer.Optimizer} and various * optimizers that extend it. There are also the helpers for learning rates in {@link * ai.djl.training.tracker}. */ package ai.djl.training.optimizer;
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/tracker/CosineTracker.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.training.tracker; import ai.djl.util.Preconditions; /** * {@code CosineTracker} is an implementation of {@link Tracker} which is updated by taking sections * of a cosine curve to smoothly reduce learning rate until a specified step and base learning rate. * * @see <a href="https://d2l.djl.ai/chapter_optimization/lr-scheduler.html#cosine-tracker">For * tracking learning rates, this section in the D2L chapter on learning rate scheduling</a> */ public class CosineTracker implements Tracker { private float baseValue; private float finalValue; private int maxUpdates; /** * Creates a new instance of {@code CosineTracker}. * * @param builder the builder to create a new instance of {@code CosineTracker} */ public CosineTracker(Builder builder) { this.baseValue = builder.baseValue; this.finalValue = builder.finalValue; this.maxUpdates = builder.maxUpdates; } /** * Creates a new builder. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** {@inheritDoc} */ @Override public float getNewValue(int numUpdate) { if (numUpdate > maxUpdates) { return finalValue; } // Scale the curve to fit the number of steps float step = (baseValue - finalValue) / 2 * (1 + (float) Math.cos(Math.PI * numUpdate / maxUpdates)); return finalValue + step; } /** The Builder to construct an {@link CosineTracker} object. */ public static final class Builder { private float baseValue; private float finalValue = 0.01f; int maxUpdates; private Builder() {} /** * Sets the initial value after no steps. * * @param baseValue the initial value * @return this {@code Builder} */ public Builder setBaseValue(float baseValue) { this.baseValue = baseValue; return this; } /** * Sets the final value that the learning rate will remain constant as after the specified * max number of updates. * * @param finalValue the final value * @return this {@code Builder} */ public Builder optFinalValue(float finalValue) { this.finalValue = finalValue; return this; } /** * Sets the maximum number of updates after which the value should remain constant. * * @param maxUpdates the maximum number of updates after which the value should remain * constant * @return this {@code Builder} */ public Builder setMaxUpdates(int maxUpdates) { this.maxUpdates = maxUpdates; return this; } /** * Builds a {@link CosineTracker} block. * * @return the {@link CosineTracker} block */ public CosineTracker build() { Preconditions.checkArgument(baseValue > 0, "You must set a starting learning rate!"); Preconditions.checkArgument( maxUpdates > 0, "You must set a maximum number of updates!"); Preconditions.checkArgument( baseValue > finalValue, "Starting learning rate must be greater than final learning rate!"); return new CosineTracker(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/tracker/CyclicalTracker.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.training.tracker; import ai.djl.util.Preconditions; /** * {@code CyclicalTracker} is an implementation of {@link Tracker} which is a policy of learning * rate adjustment that increases the learning rate off a base value in a cyclical nature, as * detailed in the paper <a href="https://arxiv.org/abs/1506.01186">Cyclical Learning Rates for * Training Neural Networks</a>. */ public class CyclicalTracker implements Tracker { private float baseValue; private float maxValue; private int stepSizeUp; private int stepSizeDown; private int totalSize; private float stepRatio; private ScaleFunction scaleFunction; private boolean scaleModeCycle; /** * Creates a new instance of {@code CyclicalTracker}. * * @param builder the builder to create a new instance of {@code CyclicalTracker} */ public CyclicalTracker(Builder builder) { this.baseValue = builder.baseValue; this.maxValue = builder.maxValue; this.stepSizeUp = builder.stepSizeUp; this.stepSizeDown = builder.stepSizeDown > 0 ? builder.stepSizeDown : builder.stepSizeUp; this.totalSize = this.stepSizeUp + this.stepSizeDown; this.stepRatio = (float) this.stepSizeUp / this.totalSize; if (builder.scaleFunction != null) { this.scaleFunction = builder.scaleFunction; this.scaleModeCycle = builder.scaleModeCycle; } else { switch (builder.mode) { case TRIANGULAR: this.scaleFunction = new TriangularScaleFunction(); this.scaleModeCycle = true; break; case TRIANGULAR2: this.scaleFunction = new Triangular2ScaleFunction(); this.scaleModeCycle = true; break; case EXP_RANGE: this.scaleFunction = new ExpRangeScaleFunction(builder.gamma); this.scaleModeCycle = false; break; default: throw new UnsupportedOperationException("Unsupported Cyclical mode."); } } } /** * Creates a new builder. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** {@inheritDoc} */ @Override public float getNewValue(int numUpdate) { int cycle = (int) Math.floor(1 + (float) numUpdate / this.totalSize); float x = 1 + (float) numUpdate / this.totalSize - cycle; float scaleFactor; float res; if (x < this.stepRatio) { scaleFactor = x / this.stepRatio; } else { scaleFactor = (x - 1) / (this.stepRatio - 1); } float baseHeight = (this.maxValue - this.baseValue) * scaleFactor; if (this.scaleModeCycle) { res = this.baseValue + baseHeight * this.scaleFunction.func(cycle); } else { res = this.baseValue + baseHeight * this.scaleFunction.func(numUpdate); } return res; } /** The Builder to construct an {@link CyclicalTracker} object. */ public static final class Builder { private float baseValue = 0.001f; private float maxValue = 0.006f; private int stepSizeUp = 2000; private int stepSizeDown; private CyclicalMode mode = CyclicalMode.TRIANGULAR; private ScaleFunction scaleFunction; private boolean scaleModeCycle = true; private float gamma = 1f; private Builder() {} /** * Sets the initial value. Default: 0.001. * * @param baseValue the initial value * @return this {@code Builder} */ public Builder optBaseValue(float baseValue) { this.baseValue = baseValue; return this; } /** * Sets the initial value. Default: 0.006. * * @param maxValue the max value * @return this {@code Builder} */ public Builder optMaxValue(float maxValue) { this.maxValue = maxValue; return this; } /** * Sets the number of iterations in up half of cycle. Default: 2000. * * @param stepSizeUp number of iterations in up half of cycle * @return this {@code Builder} */ public Builder optStepSizeUp(int stepSizeUp) { this.stepSizeUp = stepSizeUp; return this; } /** * Sets the number of iterations in up half of cycle. If {@code stepSizeDown} equals 0, it * is set to {@code stepSizeUp}. Default: 0. * * @param stepSizeDown number of iterations in the down half of cycle * @return this {@code Builder} */ public Builder optStepSizeDown(int stepSizeDown) { this.stepSizeDown = stepSizeDown; return this; } /** * Sets the cyclical mode. Can be {@code CyclicalMode.TRIANGULAR}, {@code * CyclicalMode.TRIANGULAR2} or {@code CyclicalMode.EXP_RANGE}. Values correspond to * policies detailed above. * * @param mode cyclical mode * @return this {@code Builder} */ public Builder optMode(CyclicalMode mode) { this.mode = mode; return this; } /** * Constant in {@code CyclicalMode.EXP_RANGE} scaling function. Default: 1. * * @param gamma constant in 'exp_range' scaling function: gamma^cycleIterations * @return this {@code Builder} */ public Builder optGamma(float gamma) { this.gamma = gamma; return this; } /** * Custom scaling function. If set, {@code mode} will be ignored. Default: null. * * @param scaleFunction Custom scaling function * @return this {@code Builder} */ public Builder optScaleFunction(ScaleFunction scaleFunction) { this.scaleFunction = scaleFunction; return this; } /** * Defines whether scaling function is evaluated on cycle number or update number. Default: * true. * * @param scaleModeCycle if true then scaling function is evaluated on cycle number, else on * update number * @return this {@code Builder} */ public Builder optScaleModeCycle(boolean scaleModeCycle) { this.scaleModeCycle = scaleModeCycle; return this; } /** * Builds a {@link CyclicalTracker} block. * * @return the {@link CyclicalTracker} block */ public CyclicalTracker build() { Preconditions.checkArgument(baseValue > 0, "baseValue has to be positive!"); Preconditions.checkArgument(maxValue > 0, "maxValue has to be positive!"); Preconditions.checkArgument( baseValue <= maxValue, "baseValue has to lower than maxValue!"); Preconditions.checkArgument(stepSizeUp >= 1, "stepSizeUp has to be positive!"); Preconditions.checkArgument(stepSizeDown >= 0, "stepSizeUp cannot be negative!"); Preconditions.checkArgument( gamma >= 0f && gamma <= 1f, "gamma has to be between 0 and 1!"); return new CyclicalTracker(this); } } /** * {@code CyclicalTracker} provides three predefined cyclical modes and can be selected by this * enum. * * <ul> * <li>TRIANGULAR: A basic triangular cycle without amplitude scaling. * <li>TRIANGULAR2: A basic triangular cycle that scales initial amplitude by half each cycle. * <li>EXP_RANGE: A cycle that scales initial amplitude by (gamma<sup>cycleIterations</sup>) * at each cycle iteration. * </ul> */ public enum CyclicalMode { TRIANGULAR, TRIANGULAR2, EXP_RANGE } /** {@code ScaleFunction} is an interface to implement a custom scale function. */ public interface ScaleFunction { /** * Custom scaling policy. Return value has to satisfy 0&lt;=func(steps)&lt;=1 for all * steps&gt;1. * * @param steps current cycles if {@code scaleModeCycle} is true; input update number if it * is false * @return scale ratio */ float func(int steps); } private static class TriangularScaleFunction implements ScaleFunction { @Override public float func(int steps) { return 1f; } } private static class Triangular2ScaleFunction implements ScaleFunction { @Override public float func(int steps) { return (float) (1 / (Math.pow(2f, steps - 1))); } } private static class ExpRangeScaleFunction implements ScaleFunction { float gamma; ExpRangeScaleFunction(float gamma) { this.gamma = gamma; } @Override public float func(int steps) { return (float) Math.pow(this.gamma, steps); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/tracker/FactorTracker.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.training.tracker; import ai.djl.util.Preconditions; /** * {@code FactorTracker} is an implementation of {@link Tracker} which is updated by a * multiplicative factor. * * @see <a href="https://d2l.djl.ai/chapter_optimization/lr-scheduler.html#factor-tracker">For * tracking learning rates, this section in the D2L chapter on learning rate scheduling</a> */ public class FactorTracker implements Tracker { private float baseValue; private float factor; private int maxUpdates; /** * Creates a new instance of {@code FactorTracker}. * * @param builder the builder to create a new instance of {@code FactorTracker} */ public FactorTracker(Builder builder) { this.baseValue = builder.baseValue; this.factor = builder.factor; this.maxUpdates = builder.maxUpdates; } /** * Creates a new builder. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** {@inheritDoc} */ @Override public float getNewValue(int numUpdate) { if (numUpdate > maxUpdates) { numUpdate = maxUpdates; } return (float) (baseValue * Math.pow(factor, numUpdate)); } /** The Builder to construct an {@link FactorTracker} object. */ public static final class Builder { private float baseValue; private float factor; Float min; Integer maxUpdates; private Builder() {} /** * Sets the initial value after no steps. * * @param baseValue the initial value * @return this {@code Builder} */ public Builder setBaseValue(float baseValue) { this.baseValue = baseValue; return this; } /** * Sets the value of the multiplicative factor. * * @param factor the value of the multiplicative factor * @return this {@code Builder} */ public Builder setFactor(float factor) { if (factor > 1f) { throw new IllegalArgumentException("factor should be no more than 1"); } this.factor = factor; return this; } /** * Sets the minimum value. * * <p>This is equivalent to the max updates. Only one can be set. * * @param min the minimum value * @return this {@code Builder} */ public Builder optMinValue(float min) { this.min = min; return this; } /** * Sets the maximum number of updates after which the value should remain constant. * * @param maxUpdates the maximum number of updates after which the value should remain * constant * @return this {@code Builder} */ public Builder optMaxUpdates(int maxUpdates) { this.maxUpdates = maxUpdates; return this; } /** * Builds a {@link FactorTracker} block. * * @return the {@link FactorTracker} block */ public FactorTracker build() { Preconditions.checkArgument(factor != 0, "You must set a factor"); if (min != null) { Preconditions.checkArgument( maxUpdates == null, "You can not set both maxUpdates and a min value"); Preconditions.checkArgument( min < baseValue, "The min must be smaller than the base value"); maxUpdates = Math.toIntExact(Math.round(Math.log(min / baseValue) / Math.log(factor))); } else if (maxUpdates == null) { // Default to no max if none set maxUpdates = Integer.MAX_VALUE; } return new FactorTracker(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/tracker/FixedPerVarTracker.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.training.tracker; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * {@link FixedPerVarTracker} is an implementation of {@link Tracker} which returns a fixed value. * * @see Tracker */ public class FixedPerVarTracker implements ParameterTracker { private float value; private Map<String, Float> valueMap; /** * Creates a new instance of {@link FixedPerVarTracker}. * * @param builder the builder used to build this object */ public FixedPerVarTracker(Builder builder) { this.value = builder.value; this.valueMap = builder.valueMap; } /** {@inheritDoc} */ @Override public float getNewValue(String parameterId, int numUpdate) { return valueMap.getOrDefault(parameterId, this.value); } /** * Creates a builder to build a {@link FixedPerVarTracker}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The Builder to construct an {@link FixedPerVarTracker} object. */ public static final class Builder { private float value; private Map<String, Float> valueMap = new ConcurrentHashMap<>(); /** Create a builder for {@link FixedPerVarTracker}. */ private Builder() {} /** * Set the default learning rate. * * @param value the default learning rate * @return builder */ public Builder setDefaultValue(float value) { this.value = value; return this; } /** * Add a kv pair of parameter and its learning rate. * * @param parameterId the parameter id * @param value the default learning rate * @return builder */ public Builder put(String parameterId, float value) { this.valueMap.put(parameterId, value); return this; } /** * Add kv pairs of parameter and its learning rate. * * @param valueMap stores parameterId and learning rate * @return builder */ public Builder putAll(Map<String, Float> valueMap) { this.valueMap.putAll(valueMap); return this; } /** * Builds a {@link FixedPerVarTracker} block. * * @return the {@link FixedPerVarTracker} block */ public FixedPerVarTracker build() { return new FixedPerVarTracker(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/tracker/FixedTracker.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.training.tracker; /** * {@link FixedTracker} is an implementation of {@link Tracker} which returns a fixed value. * * @see Tracker */ class FixedTracker implements Tracker { private float value; /** * Creates a new instance of {@link FixedTracker}. * * @param builder the builder used to build this object */ public FixedTracker(Builder builder) { this.value = builder.value; } /** {@inheritDoc} */ @Override public float getNewValue(int numUpdate) { return value; } /** * Creates a builder to build a {@link FixedTracker}. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** The Builder to construct an {@link FixedTracker} object. */ public static final class Builder { private float value; private Builder() {} public Builder setValue(float value) { this.value = value; return this; } /** * Builds a {@link FixedTracker} block. * * @return the {@link FixedTracker} block */ public FixedTracker build() { return new FixedTracker(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/tracker/LinearTracker.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.training.tracker; import ai.djl.util.Preconditions; /** * {@code FactorTracker} is an implementation of {@link Tracker} which is updated by a constant * factor. * * @see Tracker */ public class LinearTracker implements Tracker { private float baseValue; private float slope; private int maxUpdates; /** * Creates a new instance of {@code FactorTracker}. * * @param builder the builder to create a new instance of {@code FactorTracker} */ public LinearTracker(Builder builder) { this.baseValue = builder.baseValue; this.slope = builder.slope; this.maxUpdates = builder.maxUpdates; } /** * Creates a new builder. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** {@inheritDoc} */ @Override public float getNewValue(int numUpdate) { if (numUpdate > maxUpdates) { numUpdate = maxUpdates; } return baseValue + numUpdate * slope; } /** The Builder to construct an {@link LinearTracker} object. */ public static final class Builder { float baseValue; float slope; Float min; Float max; Integer maxUpdates; private Builder() {} /** * Sets the initial value after no steps. * * @param baseValue the initial value * @return this {@code Builder} */ public Builder setBaseValue(float baseValue) { this.baseValue = baseValue; return this; } /** * Sets the value of the linear slope. * * <p>Use a positive number for an increasing value and negative for decreasing. * * @param slope the value of the linear slope * @return this {@code Builder} */ public Builder optSlope(float slope) { this.slope = slope; return this; } /** * Sets the maximum value for a positive slope. * * <p>This is equivalent to the max updates. Only one can be set. * * @param max the max value * @return this {@code Builder} */ public Builder optMaxValue(float max) { this.max = max; return this; } /** * Sets the minimum value for a negative slope. * * <p>This is equivalent to the max updates. Only one can be set. * * @param min the minimum value * @return this {@code Builder} */ public Builder optMinValue(float min) { this.min = min; return this; } /** * Sets the maximum number of updates after which the value should remain constant. * * @param maxUpdates the maximum number of updates after which the value should remain * constant * @return this {@code Builder} */ public Builder optMaxUpdates(int maxUpdates) { this.maxUpdates = maxUpdates; return this; } /** * Builds a {@link LinearTracker} block. * * @return the {@link LinearTracker} block */ public LinearTracker build() { Preconditions.checkArgument(slope != 0, "You must set a slope"); Preconditions.checkArgument( min == null || max == null, "You can not set both a max value and a min value"); if (max != null) { Preconditions.checkArgument( maxUpdates == null, "You can not set both maxUpdates and a max value"); Preconditions.checkArgument( slope > 0, "The slope must be positive for a max value"); Preconditions.checkArgument( max > baseValue, "The max must be greater than the base value"); maxUpdates = Math.round((max - baseValue) / slope); } else if (min != null) { Preconditions.checkArgument( maxUpdates == null, "You can not set both maxUpdates and a min value"); Preconditions.checkArgument( slope < 0, "The slope must be negative for a min value"); Preconditions.checkArgument( min < baseValue, "The min must be smaller than the base value"); maxUpdates = -Math.round((baseValue - min) / slope); } else if (maxUpdates == null) { // Default to no max if none set maxUpdates = Integer.MAX_VALUE; } return new LinearTracker(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/tracker/MultiFactorTracker.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.training.tracker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * {@code MultiFactorTracker} is an implementation of {@link Tracker} which returns piecewise * constant values for fixed numbers of steps. multiplicative factor, at an uneven interval of * steps, until it reaches a specified stop value. * * @see <a * href="https://d2l.djl.ai/chapter_optimization/lr-scheduler.html#multi-factor-scheduler">For * tracking learning rates, this section in the D2L chapter on learning rate scheduling</a> */ public class MultiFactorTracker implements Tracker { private static final Logger logger = LoggerFactory.getLogger(FactorTracker.class); private float baseValue; private int[] steps; private float factor; private int stepIndex; /** * Creates a new instance of {@code MultiFactorTracker}. * * @param builder the builder to create a new instance of {@code MultiFactorTracker} */ public MultiFactorTracker(Builder builder) { this.baseValue = builder.baseValue; this.steps = builder.steps; this.factor = builder.factor; } /** * Creates a new builder. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** {@inheritDoc} */ @Override public float getNewValue(int numUpdate) { while (stepIndex <= steps.length - 1) { if (numUpdate > steps[stepIndex]) { stepIndex++; baseValue *= factor; logger.debug( "Update[{}]: Change tracker value to {}", numUpdate, String.format("%.5e", baseValue)); } else { return baseValue; } } return baseValue; } /** The Builder to construct an {@link MultiFactorTracker} object. */ public static final class Builder { float baseValue; int[] steps; float factor = 1; private Builder() {} /** * Sets the initial value after no steps. * * @param baseValue the initial value * @return this {@code Builder} */ public Builder setBaseValue(float baseValue) { this.baseValue = baseValue; return this; } /** * Sets an array of integers indicating when the value should be changed, usually in an * uneven interval of steps. * * @param steps an array of integers indicating when the value should be change * @return this {@code Builder} */ public Builder setSteps(int[] steps) { if (steps.length <= 1) { throw new IllegalArgumentException( "Steps should be an array of integers indicating when the value should be" + " changed, usually in an uneven interval of stepsuse FactorTracker if" + " you want the value to be changed at a constant interval of steps"); } for (int i = 0; i < steps.length; i++) { if (i > 0 && steps[i] <= steps[i - 1]) { throw new IllegalArgumentException("Steps must be an increasing list"); } if (steps[i] < 1) { throw new IllegalArgumentException("Step must be larger or equal to 1"); } } this.steps = steps; return this; } /** * Set the value of the multiplicative factor. * * @param factor the value of the multiplicative factor * @return this {@code Builder} */ public Builder optFactor(float factor) { if (factor > 1f) { throw new IllegalArgumentException("factor should be no more than 1"); } this.factor = factor; return this; } /** * Builds a {@link MultiFactorTracker} block. * * @return the {@link MultiFactorTracker} block */ public MultiFactorTracker build() { if (steps == null) { throw new IllegalArgumentException("Steps must be set to change value"); } return new MultiFactorTracker(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/tracker/ParameterTracker.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.training.tracker; /** * A {@code Tracker} represents a collection of hyperparameters or {@link Tracker}s that changes * gradually through the training process. * * @see Tracker */ public interface ParameterTracker { /** * Fetches the value after the given number of steps/updates for the parameter. * * @param parameterId the id of the parameter to get the new value for * @param numUpdate the total number of steps/updates * @return this {@code Builder} */ float getNewValue(String parameterId, int numUpdate); }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/tracker/PolynomialDecayTracker.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.training.tracker; /** * Polynomial decay {@link Tracker}. * * @see Tracker */ public class PolynomialDecayTracker implements Tracker { private float baseValue; private float endLearningRate; private int decaySteps; private float power; /** * Builds a PolynomialDecayTracker. * * @param builder parameters */ public PolynomialDecayTracker(Builder builder) { if (Float.isNaN(builder.endLearningRate)) { throw new IllegalArgumentException("End learning rate is not set."); } if (builder.decaySteps <= 0) { throw new IllegalArgumentException("Decay steps is not set."); } this.baseValue = builder.baseValue; this.endLearningRate = builder.endLearningRate; this.decaySteps = builder.decaySteps; this.power = builder.power; } /** {@inheritDoc} */ @Override public float getNewValue(int numUpdate) { int step = Math.max(0, Math.min(numUpdate, decaySteps)); return (float) ((baseValue - endLearningRate) * Math.pow(1.0 - (double) step / (double) decaySteps, power) + endLearningRate); } /** * Creates a new builder. * * @return a new builder */ public static Builder builder() { return new Builder(); } /** Builder for PolynomialDecayTracker. */ public static final class Builder { private float baseValue; private float endLearningRate = Float.NaN; private int decaySteps = -1; private float power = 1f; private Builder() {} /** * Sets the initial value after no steps. * * @param baseValue the initial value * @return this {@code Builder} */ public Builder setBaseValue(float baseValue) { this.baseValue = baseValue; return this; } /** * Sets the learning rate at which to end rate decay. * * @param endLearningRate the learning rate at which to end rate decay. * @return this builder */ public Builder setEndLearningRate(float endLearningRate) { this.endLearningRate = endLearningRate; return this; } /** * Sets the number of training steps to decay learning rate in. * * @param decaySteps the number of training steps to decay learning rate in * @return this builder */ public Builder setDecaySteps(int decaySteps) { this.decaySteps = decaySteps; return this; } /** * Sets the power of the polynomial to decay by. * * @param power the power of the polynomial to decay by. * @return this builder */ public Builder optPower(float power) { this.power = power; return this; } /** * Builds a PolynomialDecayTracker. * * @return a PolynomialDecayTracker */ public PolynomialDecayTracker build() { return new PolynomialDecayTracker(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/tracker/Tracker.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.training.tracker; /** * A {@code Tracker} represents a hyperparameter that changes gradually through the training * process. * * @see <a href="https://d2l.djl.ai/chapter_optimization/lr-scheduler.html">For tracking learning * rates, the D2L chapter on learning rate scheduling</a> */ public interface Tracker extends ParameterTracker { /** * Fetches the value after the given number of steps/updates. * * @param numUpdate the total number of steps/updates * @return this {@code Builder} */ float getNewValue(int numUpdate); /** {@inheritDoc} */ @Override default float getNewValue(String parameterId, int numUpdate) { return getNewValue(numUpdate); } /** * Returns a new instance of {@link ai.djl.training.tracker.FactorTracker.Builder} that can * build an {@link FactorTracker}. * * @return the {@link FactorTracker} {@link ai.djl.training.tracker.FactorTracker.Builder} */ static FactorTracker.Builder factor() { return FactorTracker.builder(); } /** * Returns a new instance of {@link WarmUpTracker.Builder} that can build an {@link * WarmUpTracker}. * * @return the {@link WarmUpTracker} {@link WarmUpTracker.Builder} */ static WarmUpTracker.Builder warmUp() { return WarmUpTracker.builder(); } /** * Returns a new instance of {@link ai.djl.training.tracker.MultiFactorTracker.Builder} that can * build an {@link MultiFactorTracker}. * * @return the {@link MultiFactorTracker} {@link * ai.djl.training.tracker.MultiFactorTracker.Builder} */ static MultiFactorTracker.Builder multiFactor() { return MultiFactorTracker.builder(); } /** * Returns a new instance of {@link ai.djl.training.tracker.CosineTracker.Builder} that can * build an {@link CosineTracker}. * * @return the {@link CosineTracker} {@link ai.djl.training.tracker.CosineTracker.Builder} */ static CosineTracker.Builder cosine() { return CosineTracker.builder(); } /** * Returns a new instance of {@link ai.djl.training.tracker.CyclicalTracker.Builder} that can * build an {@link CyclicalTracker}. * * @return the {@link CyclicalTracker} {@link ai.djl.training.tracker.CyclicalTracker.Builder} */ static CyclicalTracker.Builder cyclical() { return CyclicalTracker.builder(); } /** * Returns a new instance of {@link Tracker} with a fixed value. * * @param value the fixed value * @return an instance of {@link Tracker} with a fixed value */ static Tracker fixed(float value) { return FixedTracker.builder().setValue(value).build(); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/tracker/WarmUpTracker.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.training.tracker; import ai.djl.TrainingDivergedException; /** * A {@code WarmUpTracker} applies a simple warm-up before executing a main {@link Tracker}. * * @see <a href="https://d2l.djl.ai/chapter_optimization/lr-scheduler.html#warmup">For tracking * learning rates, this section in the D2L chapter on learning rate scheduling</a> */ public final class WarmUpTracker implements Tracker { Tracker mainTracker; int warmUpSteps; float warmUpBeginValue; float warmUpFinalValue; Mode warmUpMode; /** * A tracker returns a new value based on the number of updates that have been performed. * * @param builder the builder that configures tracker options */ WarmUpTracker(Builder builder) { this.mainTracker = builder.mainTracker; this.warmUpSteps = builder.warmUpSteps; this.warmUpBeginValue = builder.warmUpBeginValue; this.warmUpMode = builder.warmUpMode; this.warmUpFinalValue = mainTracker.getNewValue(0); } /** * Creates a new builder. * * @return a new builder */ public static Builder builder() { return new Builder(); } float getWarmUpValue(int numUpdate) { float value = warmUpBeginValue; if (warmUpMode == Mode.LINEAR) { value = warmUpBeginValue + (warmUpFinalValue - warmUpBeginValue) * numUpdate / warmUpSteps; } checkValue(value); return value; } /** {@inheritDoc} */ @Override public float getNewValue(int numUpdate) { if (numUpdate < warmUpSteps) { return getWarmUpValue(numUpdate); } else { return mainTracker.getNewValue(numUpdate - warmUpSteps); } } void checkValue(float value) { if (Float.isNaN(value)) { throw new TrainingDivergedException("Value is Nan."); } } /** The Builder to construct a {@link WarmUpTracker}. */ @SuppressWarnings("rawtypes") public static final class Builder { Tracker mainTracker; int warmUpSteps; float warmUpBeginValue; Mode warmUpMode = Mode.LINEAR; private Builder() {} /** * Sets the base value. * * @param mainTracker the tracker to use after warm up ends * @return this {@code Builder} */ public Builder setMainTracker(Tracker mainTracker) { this.mainTracker = mainTracker; return this; } /** * Sets the number of steps until the point the value is updated in warm-up mode. * * @param warmUpSteps the number of steps the value is updated in warm-up mode * @return this {@code Builder} */ public Builder optWarmUpSteps(int warmUpSteps) { this.warmUpSteps = warmUpSteps; return this; } /** * Sets the value at the beginning of warm-up mode. * * @param warmUpBeginValue the value at the beginning of warm-up mode * @return this {@code Builder} */ public Builder optWarmUpBeginValue(float warmUpBeginValue) { this.warmUpBeginValue = warmUpBeginValue; return this; } /** * Sets the {@link Mode} for the {@link WarmUpTracker}. * * @param warmUpMode the {@link Mode} to be set * @return this {@code Builder} */ public Builder optWarmUpMode(Mode warmUpMode) { this.warmUpMode = warmUpMode; return this; } /** * Builds a {@link WarmUpTracker} block. * * @return the {@link WarmUpTracker} block */ public WarmUpTracker build() { return new WarmUpTracker(this); } } /** An enum that enumerates the types of warm-up modes for a {@link WarmUpTracker}. */ public enum Mode { LINEAR, CONSTANT } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/tracker/package-info.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** * Contains classes for having a gradually changing hyper-parameter. * * <p>It contains a main interface {@link ai.djl.training.tracker.Tracker} and various options that * extend it. */ package ai.djl.training.tracker;
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/util/DownloadUtils.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.training.util; import ai.djl.util.Progress; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.zip.GZIPInputStream; /** A utility class downloads the file from specified url. */ public final class DownloadUtils { private DownloadUtils() {} /** * Downloads a file from specified url. * * @param url the url to download * @param output the output location * @throws IOException when IO operation fails in downloading */ public static void download(String url, String output) throws IOException { download(url, output, null); } /** * Downloads a file from specified url. * * @param url the url to download * @param output the output location * @param progress the progress tracker to show download progress * @throws IOException when IO operation fails in downloading */ public static void download(String url, String output, Progress progress) throws IOException { download(new URL(url.trim()), Paths.get(output.trim()), progress); } /** * Downloads a file from specified url. * * @param url the url to download * @param output the output location * @param progress the progress tracker to show download progress * @throws IOException when IO operation fails in downloading */ public static void download(URL url, Path output, Progress progress) throws IOException { if (Files.exists(output)) { return; } Path dir = output.toAbsolutePath().getParent(); if (dir != null) { Files.createDirectories(dir); } URLConnection conn = url.openConnection(); if (progress != null) { long contentLength = conn.getContentLengthLong(); if (contentLength > 0) { progress.reset("Downloading", contentLength, output.toFile().getName()); } } try (InputStream is = conn.getInputStream()) { ProgressInputStream pis = new ProgressInputStream(is, progress); String fileName = url.getFile(); if (fileName.endsWith(".gz")) { Files.copy(new GZIPInputStream(pis), output, StandardCopyOption.REPLACE_EXISTING); } else { Files.copy(pis, output, StandardCopyOption.REPLACE_EXISTING); } } } private static final class ProgressInputStream extends InputStream { private InputStream is; private Progress progress; public ProgressInputStream(InputStream is, Progress progress) { this.is = is; this.progress = progress; } /** {@inheritDoc} */ @Override public int read() throws IOException { int ret = is.read(); if (progress != null) { if (ret >= 0) { progress.increment(1); } else { progress.end(); } } return ret; } /** {@inheritDoc} */ @Override public int read(byte[] b, int off, int len) throws IOException { int size = is.read(b, off, len); if (progress != null) { progress.increment(size); } return size; } /** {@inheritDoc} */ @Override public void close() throws IOException { is.close(); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/util/MinMaxScaler.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.training.util; import ai.djl.ndarray.NDArray; /** * Transform arrays by scaling each value to a given range. The desired range of transformed data * can be set using {@code optRange}. the range defaults to 0...1. * * <p>After fitting the scaler the fitted values are attached to the same NDManager as the input * array. * * @author erik.bamberg@web.de */ public class MinMaxScaler implements AutoCloseable { private NDArray fittedMin; private NDArray fittedMax; private NDArray fittedRange; private float minRange; private float maxRange = 1f; private boolean detached; /** * Computes the minimum and maximum to be used for later scaling. * * <p>After fitting the scaler the fitted values are attached to the same NDManager as the input * array. reusing the minMaxScaler in the context of other NDManager's is possible by {@code * detach()} the scaler from the NDManager. * * @param data used to compute the minimum and maximum used for later scaling * @param axises minimum maximum computation along this axises * @return the fitted MinMaxScaler */ public MinMaxScaler fit(NDArray data, int[] axises) { fittedMin = data.min(axises); fittedMax = data.max(axises); fittedRange = fittedMax.sub(fittedMin); if (detached) { detach(); } return this; } /** * Computes the minimum and maximum to be used for later scaling. * * <p>After fitting the scaler the fitted values are attached to the same NDManager as the input * array. reusing the minMaxScaler in the context of other NDManager's is possible by {@code * detach()} the scaler from the NDManager. * * @param data used to compute the minimum and maximum used for later scaling * @return the fitted MinMaxScaler */ public MinMaxScaler fit(NDArray data) { fit(data, new int[] {0}); return this; } /** * Transforms the data using the previous calculated minimum and maximum. * * <p>if {@code fit()} is not executed yet, then the minimum/maximum is computer based on the * input data array and used for later computations. X_std = (X - X.min(axis=0)) / * (X.max(axis=0) - X.min(axis=0)) X_scaled = X_std * (max - min) + min * * @param data to get transformed * @return the transformed data, the input array is not changed */ public NDArray transform(NDArray data) { if (fittedRange == null) { fit(data, new int[] {0}); } NDArray std = data.sub(fittedMin).divi(fittedRange); return scale(std); } /** * Transforms the data in-place using the previous calculated minimum and maximum. * * <p>if {@code fit()} is not called before then the minimum/maximum is computer based on the * input data array and used for later computations. X_std = (X - X.min(axis=0)) / * (X.max(axis=0) - X.min(axis=0)) X_scaled = X_std * (max - min) + min * * @param data to get transformed * @return the transformed data (reference to the input data) the input array is changed * in-place by this operation */ public NDArray transformi(NDArray data) { if (fittedRange == null) { fit(data, new int[] {0}); } NDArray std = data.subi(fittedMin).divi(fittedRange); return scale(std); } /** * Scales array from std if range is not default range otherwise return the unchanged array. * * <p>this is an in-place operation. * * @param std input array to scale * @return scaled array */ private NDArray scale(NDArray std) { // we don't have to scale by custom range when range is default 0..1 if (maxRange != 1f || minRange != 0f) { return std.muli(maxRange - minRange).addi(minRange); } return std; } /** * Inverses scale array from std if range is not default range otherwise return the unchanged * array as a duplicate. * * @param std input array to scale * @return re-scaled array */ private NDArray inverseScale(NDArray std) { // we don't have to scale by custom range when range is default 0..1 if (maxRange != 1f || minRange != 0f) { return std.sub(minRange).divi(maxRange - minRange); } return std.duplicate(); } /** * Inverses scale array from std if range is not default range otherwise return the array * itself. * * <p>this is an in-place operation. * * @param std input array to scale in-place * @return re-scaled array */ private NDArray inverseScalei(NDArray std) { // we don't have to scale by custom range when range is default 0..1 if (maxRange != 1f || minRange != 0f) { return std.subi(minRange).divi(maxRange - minRange); } return std; } /** * Undoes the transformation of X according to feature_range. * * @param data to get transformed * @return the transformed array */ public NDArray inverseTransform(NDArray data) { throwsIllegalStateWhenNotFitted(); NDArray result = inverseScale(data); return result.muli(fittedRange).addi(fittedMin); } /** * Undoes the transformation of X according to feature_range as an in-place operation. * * @param data to get transformed, the data get changed in-place * @return the transformed array */ public NDArray inverseTransformi(NDArray data) { throwsIllegalStateWhenNotFitted(); NDArray result = inverseScalei(data); return result.muli(fittedRange).addi(fittedMin); } /** * Checks if this MinMaxScaler is already fitted and throws exception otherwise. * * @throws IllegalStateException when not Fitted */ private void throwsIllegalStateWhenNotFitted() { if (fittedRange == null) { throw new IllegalStateException("Min Max Scaler is not fitted"); } } /** * Detaches this MinMaxScaler fitted value from current 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. * * <p>After fitting the scaler the fitted values are attached to the same NDManager as the input * array. * * <p>Re-fitting the scaler after detaching doesn't re-attach the scaler to any NDManager. * * @return the detached MinMaxScaler (itself) - to use as a fluent API */ public MinMaxScaler detach() { detached = true; if (fittedMin != null) { fittedMin.detach(); } if (fittedMax != null) { fittedMax.detach(); } if (fittedRange != null) { fittedRange.detach(); } return this; } /** * Sets desired range of transformed data. * * @param minRange min value for desired range * @param maxRange max value for desired range * @return the configured MinMaxScaler */ public MinMaxScaler optRange(float minRange, float maxRange) { this.minRange = minRange; this.maxRange = maxRange; return this; } /** * Returns the value of fittedMin. * * @return the fittedMin value */ public NDArray getMin() { throwsIllegalStateWhenNotFitted(); return fittedMin; } /** * Returns the value of fittedMax. * * @return the fittedMax value */ public NDArray getMax() { throwsIllegalStateWhenNotFitted(); return fittedMax; } /** {@inheritDoc} */ @Override public void close() { if (fittedMin != null) { fittedMin.close(); } if (fittedMax != null) { fittedMax.close(); } if (fittedRange != null) { fittedRange.close(); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/util/ProgressBar.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.training.util; import ai.djl.util.Progress; import ai.djl.util.Utils; /** * {@code ProgressBar} is an implementation of {@link Progress}. It can be used to display the * progress of a task in the form a bar. */ public final class ProgressBar implements Progress { private static final int TOTAL_BAR_LENGTH = 40; private String message; private String trailingMessage; private long max; private long progress; private int currentPercent; private char progressChar = getProgressChar(); private boolean disableProgressBar; /** Creates an instance of {@code ProgressBar} with a maximum value of 1. */ public ProgressBar() { max = 1; disableProgressBar = Boolean.parseBoolean(Utils.getEnvOrSystemProperty("DJL_DISABLE_PROGRESS_BAR")) || Boolean.getBoolean("disableProgressBar"); } /** * Creates an instance of {@code ProgressBar} with the given maximum value, and displays the * given message. * * @param message the message to be displayed * @param max the maximum value */ public ProgressBar(String message, long max) { this(); reset(message, max); } /** * Creates an instance of {@code ProgressBar} with the given maximum value, and displays the * given message. * * @param message the message to be displayed * @param max the maximum value * @param trailingMessage the trailing message to be shown */ public ProgressBar(String message, long max, String trailingMessage) { this(); reset(message, max); this.trailingMessage = trailingMessage; } /** {@inheritDoc} */ @Override public final void reset(String message, long max, String trailingMessage) { this.message = trimMessage(message); this.max = max; this.trailingMessage = trailingMessage; currentPercent = 0; progress = 0; } /** {@inheritDoc} */ @Override public void start(long initialProgress) { update(initialProgress); } /** {@inheritDoc} */ @Override public void end() { update(max - 1); } /** {@inheritDoc} */ @Override public void increment(long increment) { update(progress + increment); } /** {@inheritDoc} */ @Override @SuppressWarnings("PMD.SystemPrintln") public void update(long progress, String additionalMessage) { if (disableProgressBar || max <= 1) { return; } this.progress = progress; if (additionalMessage == null) { additionalMessage = trailingMessage; } int percent = (int) ((progress + 1) * 100 / max); percent = Math.min(percent, 100); if (percent == currentPercent && percent > 0) { // no need to refresh return; } currentPercent = percent; StringBuilder sb = new StringBuilder(100); sb.append('\r').append(message).append(':'); for (int i = 0; i < 12 - message.length(); ++i) { sb.append(' '); } sb.append(String.format("%3d", percent)).append("% |"); for (int i = 0; i < TOTAL_BAR_LENGTH; ++i) { if (i <= percent * TOTAL_BAR_LENGTH / 100) { sb.append(progressChar); } else { sb.append(' '); } } sb.append('|'); if (additionalMessage != null) { sb.append(' ').append(additionalMessage); } if (percent == 100) { System.out.println(sb); } else { System.out.print(sb); } } private String trimMessage(String message) { int len = message.length(); if (len < 13) { return message; } return message.substring(0, 4) + "..." + message.substring(len - 5); } private static char getProgressChar() { if (System.getProperty("os.name").startsWith("Win")) { return '='; } else if (System.getProperty("os.name").startsWith("Linux")) { String lang = Utils.getenv("LANG"); if (lang == null || !lang.contains("UTF-8")) { return '='; } } return '█'; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/training
java-sources/ai/djl/api/0.34.0/ai/djl/training/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 utilities to use during training. */ package ai.djl.training.util;
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/ArgumentsUtil.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.translate; import java.util.Map; /** A utility class to extract data from model's arguments. */ public final class ArgumentsUtil { private ArgumentsUtil() {} /** * Returns the string value from the arguments. * * @param arguments the arguments to retrieve data * @param key the key to retrieve * @return the string value form the arguments */ public static String stringValue(Map<String, ?> arguments, String key) { return stringValue(arguments, key, null); } /** * Returns the string value from the arguments. * * @param arguments the arguments to retrieve data * @param key the key to retrieve * @param def the default value if key is absent * @return the string value form the arguments */ public static String stringValue(Map<String, ?> arguments, String key, String def) { Object value = arguments.get(key); if (value == null) { return def; } return value.toString(); } /** * Returns the integer value from the arguments. * * @param arguments the arguments to retrieve data * @param key the key to retrieve * @return the integer value form the arguments */ public static int intValue(Map<String, ?> arguments, String key) { return intValue(arguments, key, 0); } /** * Returns the integer value from the arguments. * * @param arguments the arguments to retrieve data * @param key the key to retrieve * @param def the default value if key is absent * @return the integer value form the arguments */ public static int intValue(Map<String, ?> arguments, String key, int def) { Object value = arguments.get(key); if (value == null) { return def; } return (int) Double.parseDouble(value.toString()); } /** * Returns the long value from the arguments. * * @param arguments the arguments to retrieve data * @param key the key to retrieve * @return the long value form the arguments */ public static long longValue(Map<String, ?> arguments, String key) { return longValue(arguments, key, 0); } /** * Returns the long value from the arguments. * * @param arguments the arguments to retrieve data * @param key the key to retrieve * @param def the default value if key is absent * @return the long value form the arguments */ public static Long longValue(Map<String, ?> arguments, String key, long def) { Object value = arguments.get(key); if (value == null) { return def; } return (long) Double.parseDouble(value.toString()); } /** * Returns the float value from the arguments. * * @param arguments the arguments to retrieve data * @param key the key to retrieve * @return the float value form the arguments */ public static float floatValue(Map<String, ?> arguments, String key) { return floatValue(arguments, key, 0f); } /** * Returns the float value from the arguments. * * @param arguments the arguments to retrieve data * @param key the key to retrieve * @param def the default value if key is absent * @return the float value form the arguments */ public static float floatValue(Map<String, ?> arguments, String key, float def) { Object value = arguments.get(key); if (value == null) { return def; } return (float) Double.parseDouble(value.toString()); } /** * Returns the boolean value from the arguments. * * @param arguments the arguments to retrieve data * @param key the key to retrieve * @return the boolean value form the arguments */ public static boolean booleanValue(Map<String, ?> arguments, String key) { return booleanValue(arguments, key, false); } /** * Returns the boolean value from the arguments. * * @param arguments the arguments to retrieve data * @param key the key to retrieve * @param def the default value if key is absent * @return the boolean value form the arguments */ public static boolean booleanValue(Map<String, ?> arguments, String key, boolean def) { Object value = arguments.get(key); if (value == null) { return def; } return Boolean.parseBoolean(value.toString()); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/BasicTranslator.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.translate; import ai.djl.ndarray.NDList; /** * A {@link Translator} made by combining a {@link PreProcessor} and a {@link PostProcessor}. * * @param <I> the input class * @param <O> the output class */ public class BasicTranslator<I, O> implements Translator<I, O> { private PreProcessor<I> preProcessor; private PostProcessor<O> postProcessor; private Batchifier batchifier; /** * Constructs a {@link BasicTranslator} with the default {@link Batchifier}. * * @param preProcessor the preProcessor to use for pre-processing * @param postProcessor the postProcessor to use for post-processing */ public BasicTranslator(PreProcessor<I> preProcessor, PostProcessor<O> postProcessor) { this.preProcessor = preProcessor; this.postProcessor = postProcessor; } /** * Constructs a {@link BasicTranslator}. * * @param preProcessor the preProcessor to use for pre-processing * @param postProcessor the postProcessor to use for post-processing * @param batchifier the batchifier to use */ public BasicTranslator( PreProcessor<I> preProcessor, PostProcessor<O> postProcessor, Batchifier batchifier) { this.preProcessor = preProcessor; this.postProcessor = postProcessor; this.batchifier = batchifier; } /** {@inheritDoc} */ @Override public O processOutput(TranslatorContext ctx, NDList list) throws Exception { return postProcessor.processOutput(ctx, list); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, I input) throws Exception { return preProcessor.processInput(ctx, input); } /** {@inheritDoc} */ @Override public Batchifier getBatchifier() { if (batchifier != null) { return batchifier; } return Translator.super.getBatchifier(); } /** {@inheritDoc} */ @Override public void prepare(TranslatorContext ctx) throws Exception { if (preProcessor instanceof Translator) { ((Translator<?, ?>) preProcessor).prepare(ctx); } if (postProcessor instanceof Translator && postProcessor != preProcessor) { ((Translator<?, ?>) postProcessor).prepare(ctx); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/Batchifier.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.translate; import ai.djl.ndarray.NDList; import ai.djl.util.ClassLoaderUtils; import java.io.Serializable; import java.util.Arrays; import java.util.stream.IntStream; /** * An interface for different strategies to convert between {@link ai.djl.training.dataset.Record} * {@link NDList}s and {@link ai.djl.training.dataset.Batch} {@link NDList}. * * <p>Different implementations of {@code Batchifier} represent different ways of creating batches. * The most common would be the {@link StackBatchifier} that batchifies by creating a new batch axis * as axis 0. Another implementation could be a concatenated batchifier for sequence elements that * will concatenate the data elements along the time axis. */ public interface Batchifier extends Serializable { Batchifier STACK = new StackBatchifier(); /** * Returns a batchifier from a batchifier name. * * @param name the batchifier name * @return the batchifier with the given name * @throws IllegalArgumentException if an invalid name is given */ static Batchifier fromString(String name) { switch (name) { case "stack": return STACK; case "padding": return new SimplePaddingStackBatchifier(); case "none": return null; default: ClassLoader cl = ClassLoaderUtils.getContextClassLoader(); Batchifier b = ClassLoaderUtils.initClass(cl, Batchifier.class, name); if (b == null) { throw new IllegalArgumentException("Invalid batchifier name: " + name); } return b; } } /** * Converts an array of {@link ai.djl.training.dataset.Record} {@link NDList}s into a combined * {@link ai.djl.training.dataset.Batch} NDList. * * <p>The size of the input array is the batch size. The data in each of the {@link NDList} are * assumed to be the same, and are batched together to form one batched {@link NDList}. * * @param inputs the input array of {@link NDList} where each element is a * @return the batchified {@link NDList} */ NDList batchify(NDList[] inputs); /** * Splits a combined {@link ai.djl.training.dataset.Batch} {@link NDList} into it's constituent * {@link ai.djl.training.dataset.Record} {@link NDList}s. * * <p>This reverses the {@link #batchify(NDList[]) batchify} operation. * * @param inputs the {@link NDList} that needs to be 'unbatchified' * @return an array of NDLists, of size equal to batch size, where each NDList is one element * from the batch of inputs */ NDList[] unbatchify(NDList inputs); /** * Partitions the given {@link ai.djl.training.dataset.Batch} {@link NDList} into multiple * {@link ai.djl.training.dataset.Batch} lists with smaller batch size. * * <p>As an example, this function might be used for multi-GPU training where it takes the main * batch and splits it into sub-batches that can be run on each GPU. * * <p>This function unbatchifies the input {@link NDList}, redistributes them into the given * number of slices, and then batchify each of the slices to form an array of {@link NDList}. * * @param list the {@link NDList} that needs to be split * @param numOfSlices the number of slices the list must be sliced into * @param evenSplit whether each slice must have the same shape * @return an array of {@link NDList} that contains all the slices */ default NDList[] split(NDList list, int numOfSlices, boolean evenSplit) { NDList[] unbatched = unbatchify(list); int batchSize = unbatched.length; numOfSlices = Math.min(numOfSlices, batchSize); if (evenSplit && batchSize % numOfSlices != 0) { throw new IllegalArgumentException( "data with shape " + batchSize + " cannot be evenly split into " + numOfSlices + ". Use a batch size that's multiple of " + numOfSlices + " or set even_split=true to allow" + " uneven partitioning of data."); } NDList[] splitted = new NDList[numOfSlices]; Arrays.setAll(splitted, i -> new NDList()); int step = (int) Math.ceil((double) batchSize / numOfSlices); for (int i = 0; i < numOfSlices; i++) { NDList[] currentUnbatched = IntStream.range(i * step, Math.min((i + 1) * step, batchSize)) .mapToObj(j -> unbatched[j]) .toArray(NDList[]::new); splitted[i] = batchify(currentUnbatched); } return splitted; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/DefaultTranslatorFactory.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.translate; import ai.djl.Model; import ai.djl.modality.cv.translator.ImageClassificationTranslatorFactory; import ai.djl.ndarray.NDList; import ai.djl.util.Pair; import java.lang.reflect.Type; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** A default implementation of {@link TranslatorFactory}. */ public class DefaultTranslatorFactory implements TranslatorFactory { protected Map<Pair<Type, Type>, Translator<?, ?>> translators; private ServingTranslatorFactory servingTranslatorFactory = new ServingTranslatorFactory(); private ImageClassificationTranslatorFactory imageClassificationTranslatorFactory = new ImageClassificationTranslatorFactory(); /** * Registers a {@link Translator} with the {@code TranslatorFactory}. * * @param input the input data type * @param output the output data type * @param translator the {@code Translator} to be registered * @param <I> the model input type * @param <O> the model output type */ public <I, O> void registerTranslator( Class<I> input, Class<O> output, Translator<I, O> translator) { if (translators == null) { translators = new ConcurrentHashMap<>(); } translators.put(new Pair<>(input, output), translator); } /** {@inheritDoc} */ @Override public Set<Pair<Type, Type>> getSupportedTypes() { Set<Pair<Type, Type>> set = new HashSet<>(); if (translators != null) { set.addAll(translators.keySet()); } set.add(new Pair<>(NDList.class, NDList.class)); return set; } /** {@inheritDoc} */ @Override public boolean isSupported(Class<?> input, Class<?> output) { if (input == NDList.class && output == NDList.class) { return true; } if (translators != null && translators.containsKey(new Pair<Type, Type>(input, output))) { return true; } return servingTranslatorFactory.isSupported(input, output) || imageClassificationTranslatorFactory.isSupported(input, output); } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public <I, O> Translator<I, O> newInstance( Class<I> input, Class<O> output, Model model, Map<String, ?> arguments) throws TranslateException { if (translators != null) { Translator<?, ?> translator = translators.get(new Pair<Type, Type>(input, output)); if (translator != null) { return (Translator<I, O>) translator; } } if (input == NDList.class && output == NDList.class) { return (Translator<I, O>) new NoopTranslator(); } if (servingTranslatorFactory.isSupported(input, output)) { return servingTranslatorFactory.newInstance(input, output, model, arguments); } if (imageClassificationTranslatorFactory.isSupported(input, output)) { return imageClassificationTranslatorFactory.newInstance( input, output, model, arguments); } return null; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/DeferredTranslatorFactory.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.translate; import ai.djl.Model; import ai.djl.repository.zoo.Criteria; import ai.djl.util.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Constructor; import java.lang.reflect.Type; import java.util.Collections; import java.util.Map; import java.util.Set; /** * A {@link TranslatorFactory} that creates the {@link Translator} based on serving.properties file. * * <p>The {@link Criteria} API cannot access serving.properties files before it's downloaded. A * {@code DeferredTranslatorFactory} assumes serving.properties will provide proper {@link * Translator}. If no translatorFactory is provided in serving.properties, a {@link * TranslateException} will be thrown. */ public class DeferredTranslatorFactory implements TranslatorFactory { private static final Logger logger = LoggerFactory.getLogger(DeferredTranslatorFactory.class); /** {@inheritDoc} */ @Override public Set<Pair<Type, Type>> getSupportedTypes() { return Collections.emptySet(); } /** {@inheritDoc} */ @Override public boolean isSupported(Class<?> input, Class<?> output) { return true; } /** {@inheritDoc} */ @Override public <I, O> Translator<I, O> newInstance( Class<I> input, Class<O> output, Model model, Map<String, ?> arguments) throws TranslateException { String factoryClass = ArgumentsUtil.stringValue(arguments, "translatorFactory"); if (factoryClass == null || factoryClass.isEmpty()) { throw new TranslateException("No translatorFactory defined."); } TranslatorFactory factory = loadTranslatorFactory(factoryClass); if (factory == null) { throw new TranslateException("Failed to load translatorFactory: " + factoryClass); } else if (!factory.isSupported(input, output)) { throw new TranslateException(factoryClass + " doesn't support Input/Output."); } logger.info("Using TranslatorFactory: {}", factoryClass); return factory.newInstance(input, output, model, arguments); } private TranslatorFactory loadTranslatorFactory(String className) { try { Class<?> clazz = Class.forName(className); Class<? extends TranslatorFactory> subclass = clazz.asSubclass(TranslatorFactory.class); Constructor<? extends TranslatorFactory> constructor = subclass.getConstructor(); return constructor.newInstance(); } catch (Throwable e) { logger.trace("Not able to load TranslatorFactory: {}", className, e); } return null; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/Ensembleable.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.translate; import java.util.Iterator; import java.util.List; /** * Represents a class that can be ensembled (or averaged). * * <p>Typically, ensembling is used for the output of models/translators. By averaging multiple * models, it is often possible to get greater accuracy then running each model individually. */ public interface Ensembleable<T> { /** * Creates an ensembled output with a list of outputs. * * @param iterator the outputs to ensemble with. It uses the caller class to determine how to * ensemble. * @return the ensembled (averaged) output */ T ensembleWith(Iterator<T> iterator); /** * Finds the ensemble of a list of outputs. * * @param outputs the outputs to ensemble. * @param <T> the type of object to ensemble. Usually also the type returned * @return the ensembled (averaged) output */ static <T extends Ensembleable<T>> T ensemble(List<T> outputs) { if (outputs.isEmpty()) { return null; } Iterator<T> it = outputs.iterator(); T item = it.next(); return item.ensembleWith(it); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/ExpansionTranslatorFactory.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.translate; import ai.djl.Model; import ai.djl.util.Pair; import java.lang.reflect.Type; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.function.Function; /** * A {@link TranslatorFactory} based on a {@link Translator} and it's {@link TranslatorOptions}. * * @param <IbaseT> the input type for the base translator * @param <ObaseT> the output type for the base translator */ @SuppressWarnings({"PMD.GenericsNaming", "InterfaceTypeParameterName"}) public abstract class ExpansionTranslatorFactory<IbaseT, ObaseT> implements TranslatorFactory { /** {@inheritDoc} */ @Override public Set<Pair<Type, Type>> getSupportedTypes() { Set<Pair<Type, Type>> results = new HashSet<>(); results.addAll(getExpansions().keySet()); Set<Type> preProcessorTypes = new HashSet<>(); preProcessorTypes.addAll(getPreprocessorExpansions().keySet()); preProcessorTypes.add(getBaseInputType()); Set<Type> postProcessorTypes = new HashSet<>(); postProcessorTypes.addAll(getPostprocessorExpansions().keySet()); postProcessorTypes.add(getBaseOutputType()); for (Type i : preProcessorTypes) { for (Type o : postProcessorTypes) { results.add(new Pair<>(i, o)); } } return results; } /** {@inheritDoc} */ @Override public <I, O> Translator<I, O> newInstance( Class<I> input, Class<O> output, Model model, Map<String, ?> arguments) { Translator<IbaseT, ObaseT> baseTranslator = buildBaseTranslator(model, arguments); return newInstance(input, output, baseTranslator); } /** * Returns a new instance of the {@link Translator} class. * * @param <I> the input data type * @param <O> the output data type * @param input the input class * @param output the output class * @param translator the base translator to expand from * @return a new instance of the {@code Translator} class */ @SuppressWarnings("unchecked") <I, O> Translator<I, O> newInstance( Class<I> input, Class<O> output, Translator<IbaseT, ObaseT> translator) { if (input.equals(getBaseInputType()) && output.equals(getBaseOutputType())) { return (Translator<I, O>) translator; } TranslatorExpansion<IbaseT, ObaseT> expansion = getExpansions().get(new Pair<>(input, output)); if (expansion != null) { return (Translator<I, O>) expansion.apply(translator); } // Note that regular expansions take precedence over pre-processor+post-processor expansions PreProcessor<I> preProcessor = null; if (input.equals(getBaseInputType())) { preProcessor = (PreProcessor<I>) translator; } else { Function<PreProcessor<IbaseT>, PreProcessor<?>> expander = getPreprocessorExpansions().get(input); if (expander != null) { preProcessor = (PreProcessor<I>) expander.apply(translator); } } PostProcessor<O> postProcessor = null; if (output.equals(getBaseOutputType())) { postProcessor = (PostProcessor<O>) translator; } else { Function<PostProcessor<ObaseT>, PostProcessor<?>> expander = getPostprocessorExpansions().get(output); if (expander != null) { postProcessor = (PostProcessor<O>) expander.apply(translator); } } if (preProcessor != null && postProcessor != null) { return new BasicTranslator<>(preProcessor, postProcessor, translator.getBatchifier()); } throw new IllegalArgumentException("Unsupported expansion input/output types."); } /** * Creates a set of {@link TranslatorOptions} based on the expansions of a given translator. * * @param translator the translator to expand * @return the {@link TranslatorOptions} */ public ExpandedTranslatorOptions withTranslator(Translator<IbaseT, ObaseT> translator) { return new ExpandedTranslatorOptions(translator); } /** * Builds the base translator that can be expanded. * * @param model the {@link Model} that uses the {@link Translator} * @param arguments the configurations for a new {@code Translator} instance * @return a base translator that can be expanded to form the factory options */ protected abstract Translator<IbaseT, ObaseT> buildBaseTranslator( Model model, Map<String, ?> arguments); /** * Returns the input type for the base translator. * * @return the input type for the base translator */ public abstract Class<IbaseT> getBaseInputType(); /** * Returns the output type for the base translator. * * @return the output type for the base translator */ public abstract Class<ObaseT> getBaseOutputType(); /** * Returns the possible expansions of this factory. * * @return the possible expansions of this factory */ protected Map<Pair<Type, Type>, TranslatorExpansion<IbaseT, ObaseT>> getExpansions() { return Collections.emptyMap(); } /** * Returns the possible expansions of this factory. * * @return the possible expansions of this factory */ protected Map<Type, Function<PreProcessor<IbaseT>, PreProcessor<?>>> getPreprocessorExpansions() { return Collections.singletonMap(getBaseInputType(), p -> p); } /** * Returns the possible expansions of this factory. * * @return the possible expansions of this factory */ protected Map<Type, Function<PostProcessor<ObaseT>, PostProcessor<?>>> getPostprocessorExpansions() { return Collections.singletonMap(getBaseOutputType(), p -> p); } /** Represents {@link TranslatorOptions} by applying expansions to a base {@link Translator}. */ final class ExpandedTranslatorOptions implements TranslatorOptions { private Translator<IbaseT, ObaseT> translator; private ExpandedTranslatorOptions(Translator<IbaseT, ObaseT> translator) { this.translator = translator; } /** {@inheritDoc} */ @Override public Set<Pair<Type, Type>> getOptions() { return getSupportedTypes(); } /** {@inheritDoc} */ @Override public <I, O> Translator<I, O> option(Class<I> input, Class<O> output) { return newInstance(input, output, translator); } } /** * A function from a base translator to an expanded translator. * * @param <IbaseT> the base translator input type * @param <ObaseT> the base translator output type */ @FunctionalInterface @SuppressWarnings({"PMD.GenericsNaming", "InterfaceTypeParameterName"}) public interface TranslatorExpansion<IbaseT, ObaseT> extends Function<Translator<IbaseT, ObaseT>, Translator<?, ?>> {} }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/NDArraySupplier.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.translate; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; /** * Represents a supplier of {@link NDArray}. * * <p>There is no requirement that a new or distinct result be returned each time the supplier is * invoked. * * <p>This is a functional interface whose functional method is {@link #get(NDManager)}. */ @FunctionalInterface public interface NDArraySupplier { /** * Gets an {@link NDArray} from the given {@link NDManager}. * * @param manager the {@link NDManager} * @return a result {@link NDArray} */ NDArray get(NDManager manager); }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/NoBatchifyTranslator.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.translate; /** * A {@link Translator} that does not use a {@link Batchifier}. * * <p>There are two major cases for avoiding the use of a {@link Batchifier}. * * <p>First, you want to translate between {@link ai.djl.training.dataset.Batch}es rather than * {@link ai.djl.training.dataset.Record}s. For example, you might go from String[] to Int[]. * * <p>The second option is when using a model that does not use batching. Then, the model expects * only a single record at a time. * * @see Translator */ public interface NoBatchifyTranslator<I, O> extends Translator<I, O> { /** {@inheritDoc} */ @Override default Batchifier getBatchifier() { return null; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/NoopServingTranslatorFactory.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.translate; import ai.djl.Model; import ai.djl.modality.Input; import ai.djl.modality.Output; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.util.Pair; import java.lang.reflect.Type; import java.util.Collections; import java.util.Map; import java.util.Set; /** A {@link TranslatorFactory} that creates a {@code RawTranslator} instance. */ public class NoopServingTranslatorFactory implements TranslatorFactory { /** {@inheritDoc} */ @Override public Set<Pair<Type, Type>> getSupportedTypes() { return Collections.singleton(new Pair<>(Input.class, Output.class)); } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public <I, O> Translator<I, O> newInstance( Class<I> input, Class<O> output, Model model, Map<String, ?> arguments) { if (!isSupported(input, output)) { throw new IllegalArgumentException("Unsupported input/output types."); } String batchifier = ArgumentsUtil.stringValue(arguments, "batchifier", "none"); return (Translator<I, O>) new NoopServingTranslator(Batchifier.fromString(batchifier)); } static final class NoopServingTranslator implements Translator<Input, Output> { private Batchifier batchifier; NoopServingTranslator(Batchifier batchifier) { this.batchifier = batchifier; } /** {@inheritDoc} */ @Override public Batchifier getBatchifier() { return batchifier; } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, Input input) throws TranslateException { NDManager manager = ctx.getNDManager(); try { ctx.setAttachment("properties", input.getProperties()); return input.getDataAsNDList(manager); } catch (IllegalArgumentException e) { throw new TranslateException("Input is not a NDList data type", e); } } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public Output processOutput(TranslatorContext ctx, NDList list) { Map<String, String> prop = (Map<String, String>) ctx.getAttachment("properties"); String contentType = prop.get("Content-Type"); String accept = prop.get("Accept"); Output output = new Output(); if ("tensor/npz".equalsIgnoreCase(accept) || "tensor/npz".equalsIgnoreCase(contentType)) { output.add(list.encode(NDList.Encoding.NPZ)); output.addProperty("Content-Type", "tensor/npz"); } else if ("tensor/safetensors".equalsIgnoreCase(accept) || "tensor/safetensors".equalsIgnoreCase(contentType)) { output.add(list.encode(NDList.Encoding.SAFETENSORS)); output.addProperty("Content-Type", "tensor/safetensors"); } else { output.add(list.encode()); output.addProperty("Content-Type", "tensor/ndlist"); } return output; } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/NoopTranslator.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.translate; import ai.djl.ndarray.NDList; /** A no operational {@link Translator} implementation. */ public class NoopTranslator implements Translator<NDList, NDList> { private Batchifier batchifier; /** * Constructs a {@link NoopTranslator} with the given {@link Batchifier}. * * @param batchifier batchifier to use */ public NoopTranslator(Batchifier batchifier) { this.batchifier = batchifier; } /** Constructs a {@link NoopTranslator}. */ public NoopTranslator() {} /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, NDList input) { return input; } /** {@inheritDoc} */ @Override public NDList processOutput(TranslatorContext ctx, NDList list) { return list; } /** {@inheritDoc} */ @Override public Batchifier getBatchifier() { return batchifier; } /** * Sets the {@link Batchifier} for the Translator. * * @param batchifier the {@link Batchifier} for the Translator */ public void setBatchifier(Batchifier batchifier) { this.batchifier = batchifier; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/PaddingStackBatchifier.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.translate; 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.Shape; import java.util.ArrayList; import java.util.List; /** * The padding stack batchifier is a {@link StackBatchifier} that also pads elements to reach the * same length. */ public final class PaddingStackBatchifier implements Batchifier { private static final long serialVersionUID = 1L; @SuppressWarnings("serial") private List<Integer> arraysToPad; @SuppressWarnings("serial") private List<Integer> dimsToPad; private transient List<NDArraySupplier> paddingSuppliers; @SuppressWarnings("serial") private List<Integer> paddingSizes; private boolean includeValidLengths; private PaddingStackBatchifier(Builder builder) { arraysToPad = builder.arraysToPad; dimsToPad = builder.dimsToPad; paddingSuppliers = builder.paddingSuppliers; paddingSizes = builder.paddingSizes; includeValidLengths = builder.includeValidLengths; } /** {@inheritDoc} */ @Override public NDList batchify(NDList[] inputs) { NDList validLengths = new NDList(inputs.length); NDManager manager = inputs[0].get(0).getManager(); for (int i = 0; i < arraysToPad.size(); i++) { int arrayIndex = arraysToPad.get(i); int dimIndex = dimsToPad.get(i); NDArray padding = paddingSuppliers.get(i).get(manager); long paddingSize = paddingSizes.get(i); long maxSize = findMaxSize(inputs, arrayIndex, dimIndex); if (paddingSize != -1 && maxSize > paddingSize) { throw new IllegalArgumentException( "The batchifier padding size is too small " + maxSize + " " + paddingSize); } maxSize = Math.max(maxSize, paddingSize); long[] arrayValidLengths = padArrays(inputs, arrayIndex, dimIndex, padding, maxSize); validLengths.add(manager.create(arrayValidLengths)); } NDList result = Batchifier.STACK.batchify(inputs); if (includeValidLengths) { result.addAll(validLengths); } return result; } /** {@inheritDoc} */ @Override public NDList[] unbatchify(NDList inputs) { if (!includeValidLengths) { return Batchifier.STACK.unbatchify(inputs); } NDList validLengths = new NDList(inputs.subList(inputs.size() - arraysToPad.size(), inputs.size())); inputs = new NDList(inputs.subList(0, inputs.size() - arraysToPad.size())); NDList[] split = Batchifier.STACK.unbatchify(inputs); for (int i = 0; i < split.length; i++) { NDList arrays = split[i]; for (int j = 0; j < arraysToPad.size(); j++) { long validLength = validLengths.get(j).getLong(i); int arrayIndex = arraysToPad.get(j); NDArray dePadded = arrays.get(arrayIndex) .get(NDIndex.sliceAxis(dimsToPad.get(j) - 1, 0, validLength)); arrays.set(arrayIndex, dePadded); } } return split; } /** {@inheritDoc} */ @Override public NDList[] split(NDList list, int numOfSlices, boolean evenSplit) { if (!includeValidLengths) { return Batchifier.STACK.split(list, numOfSlices, evenSplit); } NDList validLengths = new NDList(list.subList(list.size() - arraysToPad.size(), list.size())); list = new NDList(list.subList(0, list.size() - arraysToPad.size())); NDList[] split = Batchifier.STACK.split(list, numOfSlices, evenSplit); long sliceSize = split[0].get(0).getShape().get(0); long totalSize = list.get(0).getShape().get(0); for (int i = 0; i < split.length; i++) { // TODO: The padding required may not be the same for all splits. For smaller splits, // we can remove some extra padding. NDList arrays = split[i]; for (int j = 0; j < arraysToPad.size(); j++) { long min = i * sliceSize; long max = Math.min((i + 1) * sliceSize, totalSize); NDArray splitValidLenghts = validLengths.get(j).get(NDIndex.sliceAxis(0, min, max)); arrays.add(splitValidLenghts); } } return split; } /** * Finds the maximum size for a particular array/dimension in a batch of inputs (which can be * padded to equalize their sizes). * * @param inputs the batch of inputs * @param arrayIndex the array (for each NDList in the batch) * @param dimIndex for the array in each NDList in the batch * @return the maximum size */ public static long findMaxSize(NDList[] inputs, int arrayIndex, int dimIndex) { long maxSize = -1; for (NDList input : inputs) { NDArray array = input.get(arrayIndex); maxSize = Math.max(maxSize, array.getShape().get(dimIndex)); } return maxSize; } /** * Pads the arrays at a particular dimension to all have the same size (updating inputs in * place). * * @param inputs the batch of inputs * @param arrayIndex the array (for each NDList in the batch) * @param dimIndex for the array in each NDList in the batch * @param padding the padding to use. Say you have a batch of arrays of Shape(10, ?, 3) and you * are padding the "?" dimension. There are two padding modes: * <ul> * <li>If you give padding of Shape(1, 3) (same dimensionality as required), it will be * repeated with {@link NDArray#repeat(long)} as necessary * <li>If you give padding of Shape(3) or Shape(0) (smaller dimensionality as required), * it will be broadcasted with {@link NDArray#broadcast(Shape)} to reach the full * required Shape(?, 3) * </ul> * * @param maxSize the size that each array will be padded to in that dimension. In the example * above, the padding to be applied to the "?" dimension. * @return the original valid length for each dimension in the batch (same length as * inputs.length). The inputs will be updated in place. */ public static long[] padArrays( NDList[] inputs, int arrayIndex, int dimIndex, NDArray padding, long maxSize) { long[] arrayValidLengths = new long[inputs.length]; for (int i = 0; i < inputs.length; i++) { NDArray array = inputs[i].get(arrayIndex); String arrayName = array.getName(); long validLength = array.getShape().get(dimIndex); if (validLength < maxSize) { // Number of dimensions the padding must be int dimensionsRequired = array.getShape().dimension() - padding.getShape().dimension(); NDArray paddingArray; if (dimensionsRequired == 0) { paddingArray = padding.repeat( Shape.update( array.getShape(), dimIndex, maxSize - validLength)); } else if (dimensionsRequired > 0) { paddingArray = padding.broadcast( Shape.update( array.getShape(), dimIndex, maxSize - validLength)); } else { throw new IllegalArgumentException( "The padding must be <=" + dimensionsRequired + " dimensions, but found " + padding.getShape().dimension()); } array = array.concat(paddingArray.toType(array.getDataType(), false), dimIndex); } // keep input name array.setName(arrayName); inputs[i].set(arrayIndex, array); arrayValidLengths[i] = validLength; } return arrayValidLengths; } /** * Returns a {@link PaddingStackBatchifier.Builder}. * * @return a {@link PaddingStackBatchifier.Builder} */ public static PaddingStackBatchifier.Builder builder() { return new Builder(); } /** Builder to build a {@link PaddingStackBatchifier}. */ public static final class Builder { private List<Integer> arraysToPad; private List<Integer> dimsToPad; private List<NDArraySupplier> paddingSuppliers; private List<Integer> paddingSizes; private boolean includeValidLengths; private Builder() { arraysToPad = new ArrayList<>(); dimsToPad = new ArrayList<>(); paddingSuppliers = new ArrayList<>(); paddingSizes = new ArrayList<>(); } /** * Sets whether to include the valid lengths (length of non-padded data) for each array. * * @param includeValidLengths true to include valid lengths * @return this builder */ public Builder optIncludeValidLengths(boolean includeValidLengths) { this.includeValidLengths = includeValidLengths; return this; } /** * Adds a new dimension to be padded in the input {@link NDList}. * * @param array which array in the {@link NDList} to pad * @param dim which dimension in the array to pad * @param supplier a supplier that produces the padding array. The padding array shape * should include both the batch and a 1 for the padded dimension. For batch array shape * NTC, the padding shape should be N x 1 x C * @return this builder */ public Builder addPad(int array, int dim, NDArraySupplier supplier) { return addPad(array, dim, supplier, -1); } /** * Adds a new dimension to be padded in the input {@link NDList}. * * @param array which array in the {@link NDList} to pad * @param dim which dimension in the array to pad * @param supplier a supplier that produces the padding array. The padding array shape * should include both the batch and a 1 for the padded dimension. For batch array shape * NTC, the padding shape should be N x 1 x C * @param paddingSize the minimum padding size to use. All sequences to pad must be less * than this size * @return this builder */ public Builder addPad(int array, int dim, NDArraySupplier supplier, int paddingSize) { arraysToPad.add(array); dimsToPad.add(dim); paddingSuppliers.add(supplier); paddingSizes.add(paddingSize); return this; } /** * Builds the {@link PaddingStackBatchifier}. * * @return the constructed {@link PaddingStackBatchifier} */ public PaddingStackBatchifier build() { return new PaddingStackBatchifier(this); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/Pipeline.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.translate; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.util.Pair; import ai.djl.util.PairList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** {@code Pipeline} allows applying multiple transforms on an input {@link NDList}. */ public class Pipeline { private PairList<IndexKey, Transform> transforms; /** Creates a new instance of {@code Pipeline} that has no {@link Transform} defined yet. */ public Pipeline() { transforms = new PairList<>(); } /** * Creates a new instance of {@code Pipeline} that can apply the given transforms on its input. * * <p>Since no keys are provided for these transforms, they will be applied to the first element * in the input {@link NDList} when the {@link #transform(NDList) transform} method is called on * this object. * * @param transforms the transforms to be applied when the {@link #transform(NDList) transform} * method is called on this object */ public Pipeline(Transform... transforms) { this.transforms = new PairList<>(); for (Transform transform : transforms) { this.transforms.add(new IndexKey(0), transform); } } /** * Adds the given {@link Transform} to the list of transforms to be applied on the input when * the {@link #transform(NDList) transform} method is called on this object. * * <p>Since no keys are provided for this {@link Transform}, it will be applied to the first * element in the input {@link NDList}. * * @param transform the {@link Transform} to be added * @return this {@code Pipeline} */ public Pipeline add(Transform transform) { transforms.add(new IndexKey(0), transform); return this; } /** * Adds the given {@link Transform} to the list of transforms to be applied on the {@link * NDArray} at the given index in the input {@link NDList}. * * @param index the index corresponding to the {@link NDArray} in the input {@link NDList} on * which the given transform must be applied to * @param transform the {@link Transform} to be added * @return this {@code Pipeline} */ public Pipeline add(int index, Transform transform) { transforms.add(new IndexKey(index), transform); return this; } /** * Adds the given {@link Transform} to the list of transforms to be applied on the {@link * NDArray} with the given key as name in the input {@link NDList}. * * @param name the key corresponding to the {@link NDArray} in the input {@link NDList} on which * the given transform must be applied to * @param transform the {@code Transform} to be applied when the {@link #transform(NDList) * transform} method is called on this object * @return this {@code Pipeline} */ public Pipeline add(String name, Transform transform) { transforms.add(new IndexKey(name), transform); return this; } /** * Inserts the given {@link Transform} to the list of transforms at the given position. * * <p>Since no keys or indices are provided for this {@link Transform}, it will be applied to * the first element in the input {@link NDList} when the {@link #transform(NDList) transform} * method is called on this object. * * @param position the position at which the {@link Transform} must be inserted * @param transform the {@code Transform} to be inserted * @return this {@code Pipeline} */ public Pipeline insert(int position, Transform transform) { transforms.add(position, new IndexKey(0), transform); return this; } /** * Inserts the given {@link Transform} to the list of transforms at the given position to be * applied on the {@link NDArray} at the given index in the input {@link NDList}. * * @param position the position at which the {@link Transform} must be inserted * @param index the index corresponding to the {@link NDArray} in the input {@link NDList} on * which the given transform must be applied to * @param transform the {@code Transform} to be inserted * @return this {@code Pipeline} */ public Pipeline insert(int position, int index, Transform transform) { transforms.add(position, new IndexKey(index), transform); return this; } /** * Inserts the given {@link Transform} to the list of transforms at the given position to be * applied on the {@link NDArray} with the given name in the input {@link NDList}. * * @param position the position at which the {@link Transform} must be inserted * @param name the key corresponding to the {@link NDArray} in the input {@link NDList} on which * the given transform must be applied to * @param transform the {@code Transform} to be inserted * @return this {@code Pipeline} */ public Pipeline insert(int position, String name, Transform transform) { transforms.add(position, new IndexKey(name), transform); return this; } /** * Applies the transforms configured in this object on the input {@link NDList}. * * <p>If a key is specified with the transform, those transforms will only be applied to the * {@link NDArray} in the input {@link NDList}. If a key is not specified, it will be applied to * the first element in the input {@link NDList}. * * @param input the input {@link NDList} on which the tranforms are to be applied * @return the output {@link NDList} after applying the tranforms */ public NDList transform(NDList input) { if (transforms.isEmpty() || input.isEmpty()) { return input; } NDArray[] arrays = input.toArray(new NDArray[0]); Map<IndexKey, Integer> map = new ConcurrentHashMap<>(); // create mapping for (int i = 0; i < input.size(); i++) { String key = input.get(i).getName(); if (key != null) { map.put(new IndexKey(key), i); } map.put(new IndexKey(i), i); } // apply transform for (Pair<IndexKey, Transform> transform : transforms) { IndexKey key = transform.getKey(); int index = map.get(key); NDArray array = arrays[index]; arrays[index] = transform.getValue().transform(array); arrays[index].setName(array.getName()); } return new NDList(arrays); } /** * Returns the list of transforms. * * @return the list of transforms */ public List<Transform> getTransforms() { return transforms.values(); } private static final class IndexKey { private String key; private int index; private IndexKey(String key) { this.key = key; } private IndexKey(int index) { this.index = index; } /** {@inheritDoc} */ @Override public int hashCode() { if (key == null) { return index; } return key.hashCode(); } /** {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof IndexKey)) { return false; } IndexKey other = (IndexKey) obj; if (key == null) { return index == other.index; } return key.equals(other.key); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/PostProcessor.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.translate; import ai.djl.ndarray.NDList; /** * An interface that provides post-processing functionality. * * @param <O> the type of the output object expected */ public interface PostProcessor<O> { /** * Processes the output NDList to the corresponding output object. * * @param ctx the toolkit used for post-processing * @param list the output NDList after inference, usually immutable in engines like * PyTorch. @see <a href="https://github.com/deepjavalibrary/djl/issues/1774">Issue 1774</a> * @return the output object of expected type * @throws Exception if an error occurs during processing output */ @SuppressWarnings("PMD.SignatureDeclareThrowsException") O processOutput(TranslatorContext ctx, NDList list) throws Exception; }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/PreProcessor.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.translate; import ai.djl.ndarray.NDList; /** * An interface that provides pre-processing functionality. * * @param <I> the type of the input object */ public interface PreProcessor<I> { /** * Processes the input and converts it to NDList. * * @param ctx the toolkit for creating the input NDArray * @param input the input object * @return the {@link NDList} after pre-processing * @throws Exception if an error occurs during processing input */ @SuppressWarnings("PMD.SignatureDeclareThrowsException") NDList processInput(TranslatorContext ctx, I input) throws Exception; }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/ServingTranslator.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.translate; import ai.djl.inference.streaming.IteratorBytesSupplier; import ai.djl.inference.streaming.PublisherBytesSupplier; import ai.djl.inference.streaming.StreamingTranslator; import ai.djl.modality.Input; import ai.djl.modality.Output; import ai.djl.ndarray.BytesSupplier; import ai.djl.ndarray.NDList; import java.util.Iterator; import java.util.Map; import java.util.stream.Stream; /** A {@link Translator} that can handle generic {@link Input} and {@link Output}. */ public interface ServingTranslator extends StreamingTranslator<Input, Output> { /** * Sets the configurations for the {@code Translator} instance. * * @param arguments the configurations for the {@code Translator} instance */ void setArguments(Map<String, ?> arguments); /** {@inheritDoc} */ @Override default Support getSupport() { return Support.BOTH; } /** {@inheritDoc} */ @Override @SuppressWarnings("PMD.AvoidThrowingRawExceptionTypes") default StreamOutput<Output> processStreamOutput(TranslatorContext ctx, Stream<NDList> list) { return new StreamOutput<Output>() { @Override protected Output buildAsyncOutput() { PublisherBytesSupplier bytesSupplier = new PublisherBytesSupplier(); Output output = new Output(); output.add(bytesSupplier); return output; } @Override protected void computeAsyncOutputInternal(Output output) { PublisherBytesSupplier bytesSupplier = (PublisherBytesSupplier) output.getData(); Iterator<NDList> it = list.iterator(); while (it.hasNext()) { try { bytesSupplier.appendContent( processOutput(ctx, it.next()).getData().getAsBytes(), !it.hasNext()); } catch (Exception e) { throw new RuntimeException(e); } } } @Override public Output getIterativeOutputInternal() { Iterator<BytesSupplier> outputs = list.map( ndList -> { try { return processOutput(ctx, ndList).getData(); } catch (Exception e) { throw new RuntimeException(e); } }) .iterator(); IteratorBytesSupplier bytesSupplier = new IteratorBytesSupplier(outputs); Output output = new Output(); output.add(bytesSupplier); return output; } }; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/ServingTranslatorFactory.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.translate; import ai.djl.Application; import ai.djl.Model; import ai.djl.modality.Input; import ai.djl.modality.Output; import ai.djl.util.ClassLoaderUtils; import ai.djl.util.Pair; import ai.djl.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Constructor; import java.lang.reflect.Type; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.Locale; import java.util.Map; import java.util.Set; /** A {@link TranslatorFactory} that creates a generic {@link Translator}. */ public class ServingTranslatorFactory implements TranslatorFactory { private static final Logger logger = LoggerFactory.getLogger(ServingTranslatorFactory.class); /** {@inheritDoc} */ @Override public Set<Pair<Type, Type>> getSupportedTypes() { return Collections.singleton(new Pair<>(Input.class, Output.class)); } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public <I, O> Translator<I, O> newInstance( Class<I> input, Class<O> output, Model model, Map<String, ?> arguments) throws TranslateException { if (!isSupported(input, output)) { throw new IllegalArgumentException("Unsupported input/output types."); } Path modelDir = model.getModelPath(); String factoryClass = ArgumentsUtil.stringValue(arguments, "translatorFactory"); if (factoryClass != null) { Translator<Input, Output> translator = getServingTranslator(factoryClass, model, arguments); if (translator != null) { return (Translator<I, O>) translator; } throw new TranslateException("Failed to load translatorFactory: " + factoryClass); } String className = (String) arguments.get("translator"); Path libPath = modelDir.resolve("libs"); if (!Files.isDirectory(libPath)) { libPath = modelDir.resolve("lib"); if (!Files.isDirectory(libPath) && className == null) { return (Translator<I, O>) loadDefaultTranslator(model, arguments); } } ServingTranslator servingTranslator = findTranslator(libPath, className); if (servingTranslator != null) { servingTranslator.setArguments(arguments); logger.info("Using translator: {}", servingTranslator.getClass().getName()); return (Translator<I, O>) servingTranslator; } else if (className != null) { throw new TranslateException("Failed to load translator: " + className); } return (Translator<I, O>) loadDefaultTranslator(model, arguments); } private ServingTranslator findTranslator(Path path, String className) { Path classesDir = path.resolve("classes"); ClassLoaderUtils.compileJavaClass(classesDir); return ClassLoaderUtils.findImplementation(path, ServingTranslator.class, className); } private TranslatorFactory loadTranslatorFactory(String className) { try { Class<?> clazz = Class.forName(className); Class<? extends TranslatorFactory> subclass = clazz.asSubclass(TranslatorFactory.class); Constructor<? extends TranslatorFactory> constructor = subclass.getConstructor(); return constructor.newInstance(); } catch (Throwable e) { logger.trace("Not able to load TranslatorFactory: {}", className, e); } return null; } private Translator<Input, Output> loadDefaultTranslator(Model model, Map<String, ?> arguments) throws TranslateException { String factoryClass = detectTranslatorFactory(arguments); Translator<Input, Output> translator = getServingTranslator(factoryClass, model, arguments); if (translator != null) { return translator; } NoopServingTranslatorFactory factory = new NoopServingTranslatorFactory(); return factory.newInstance(Input.class, Output.class, null, arguments); } private String detectTranslatorFactory(Map<String, ?> arguments) { Application application; String app = ArgumentsUtil.stringValue(arguments, "application"); if (app != null) { application = Application.of(app); } else { String task = Utils.getEnvOrSystemProperty("HF_TASK"); task = ArgumentsUtil.stringValue(arguments, "task", task); if (task != null) { task = task.replace("-", "_").toLowerCase(Locale.ROOT); application = Application.of(task); } else { application = Application.UNDEFINED; } } if (application == Application.CV.IMAGE_CLASSIFICATION) { return "ai.djl.modality.cv.translator.ImageClassificationTranslatorFactory"; } else if (application == Application.NLP.FILL_MASK) { return "ai.djl.huggingface.translator.FillMaskTranslatorFactory"; } else if (application == Application.NLP.QUESTION_ANSWER) { return "ai.djl.huggingface.translator.QuestionAnsweringTranslatorFactory"; } else if (application == Application.NLP.TEXT_CLASSIFICATION) { return "ai.djl.huggingface.translator.TextClassificationTranslatorFactory"; } else if (application == Application.NLP.TEXT_EMBEDDING) { return "ai.djl.huggingface.translator.TextEmbeddingTranslatorFactory"; } else if (application == Application.NLP.TOKEN_CLASSIFICATION) { return "ai.djl.huggingface.translator.TokenClassificationTranslatorFactory"; } return null; } private Translator<Input, Output> getServingTranslator( String factoryClass, Model model, Map<String, ?> arguments) throws TranslateException { TranslatorFactory factory = loadTranslatorFactory(factoryClass); if (factory != null && factory.isSupported(Input.class, Output.class)) { logger.info("Using TranslatorFactory: {}", factoryClass); return factory.newInstance(Input.class, Output.class, model, arguments); } return null; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/SimplePaddingStackBatchifier.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.translate; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; /** * A simpler version of the {@link PaddingStackBatchifier} that pads all dimensions rather than * specific ones. */ public final class SimplePaddingStackBatchifier implements Batchifier { private static final long serialVersionUID = 1L; private float padding; /** * A simple {@link Batchifier} that pads all arrays to same shape and then stacks them. * * @param padding the number of pad with */ public SimplePaddingStackBatchifier(float padding) { this.padding = padding; } /** * A simple {@link Batchifier} that pads all arrays to same shape (with padding 0) and then * stacks them. */ public SimplePaddingStackBatchifier() { this(0f); } /** {@inheritDoc} */ @Override public NDList batchify(NDList[] inputs) { int numArrays = inputs[0].size(); for (int i = 0; i < numArrays; i++) { int axes = inputs[0].get(i).getShape().dimension(); for (int j = 0; j < axes; j++) { long maxSize = PaddingStackBatchifier.findMaxSize(inputs, i, j); NDManager manager = inputs[0].getManager(); NDArray padArray = manager.create(padding); PaddingStackBatchifier.padArrays(inputs, i, j, padArray, maxSize); } } return Batchifier.STACK.batchify(inputs); } /** {@inheritDoc} */ @Override public NDList[] unbatchify(NDList inputs) { return Batchifier.STACK.unbatchify(inputs); } /** {@inheritDoc} */ @Override public NDList[] split(NDList list, int numOfSlices, boolean evenSplit) { return Batchifier.STACK.split(list, numOfSlices, evenSplit); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/StackBatchifier.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.translate; import ai.djl.engine.EngineException; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDArrays; import ai.djl.ndarray.NDList; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import java.util.Arrays; import java.util.stream.LongStream; /** * {@code StackBatchifier} is used to merge a list of samples to form a mini-batch of NDArray(s). * The is default {@link Batchifier} for data loading. */ public class StackBatchifier implements Batchifier { private static final long serialVersionUID = 1L; /** {@inheritDoc} */ @Override public NDList batchify(NDList[] inputs) { // each input as NDList might contain several data or labels // so those should be batchified with counterpart int batchSize = inputs.length; int numInputKinds = inputs[0].size(); // if the NDList is empty if (numInputKinds == 0) { return new NDList(); } try { // stack all the data and labels together NDList result = new NDList(numInputKinds); for (int i = 0; i < numInputKinds; i++) { NDList inputsOfKind = new NDList(batchSize); String inputName = inputs[0].get(i).getName(); for (NDList input : inputs) { inputsOfKind.add(input.get(i)); } NDArray stacked = NDArrays.stack(new NDList(inputsOfKind)); // keep the name for stacked inputs stacked.setName(inputName); result.add(stacked); } return result; } catch (IndexOutOfBoundsException | EngineException e) { // If there is an error when batchifying, check for various potential problems with the // inputs. The error is not handled in this block. It only attempts to clarify the // error's cause before rethrowing. // Check if numInputKinds is not consistant for all inputs for (NDList input : inputs) { if (input.size() != numInputKinds) { throw new IllegalArgumentException( "You cannot batch data with different numbers of inputs", e); } } // Check if data does not have a consistent shape or type for (int i = 0; i < numInputKinds; i++) { Shape kindDataShape = inputs[0].get(i).getShape(); DataType kindDataType = inputs[0].get(i).getDataType(); for (NDList input : inputs) { NDArray currInput = input.get(i); if (!currInput.getShape().equals(kindDataShape)) { throw new IllegalArgumentException( "You cannot batch data with different input shapes" + currInput.getShape() + " vs " + kindDataShape, e); } if (!currInput.getDataType().equals(kindDataType)) { throw new IllegalArgumentException( "You cannot batch data with different input data types", e); } } } // Could not clarify cause - rethrow original error. throw e; } } /** {@inheritDoc} */ @Override public NDList[] unbatchify(NDList inputs) { int numInputKinds = inputs.size(); if (numInputKinds == 0) { return new NDList[0]; } int batchSize = Math.toIntExact(inputs.head().size(0)); if (batchSize == 0) { return new NDList[0]; } NDList[] dataList = new NDList[batchSize]; for (int i = 0; i < batchSize; i++) { dataList[i] = new NDList(); } for (NDArray input : inputs) { NDList splitList = input.split(batchSize); for (int i = 0; i < batchSize; i++) { NDArray array = splitList.get(i).squeeze(0); array.setName(input.getName()); dataList[i].add(array); } } return dataList; } /** {@inheritDoc} */ @Override public NDList[] split(NDList list, int numOfSlices, boolean evenSplit) { int batchSize = Math.toIntExact(list.head().size(0)); numOfSlices = Math.min(numOfSlices, batchSize); NDList[] splitted = new NDList[numOfSlices]; Arrays.setAll(splitted, i -> new NDList()); for (NDArray nd : list) { String name = nd.getName(); NDList rows = split(nd, numOfSlices, evenSplit); for (int i = 0; i < numOfSlices; ++i) { NDArray array = rows.get(i); array.setName(name); splitted[i].add(array); } } return splitted; } /** * Splits an {@code NDArray} into the given number of slices along the given batch axis. * * <p>Usually used for data parallelism where each slice is sent to one device (i.e. GPU). * * @param array a batch of {@code NDArray} * @param numOfSlices the number of desired slices * @param evenSplit whether to force all slices to have the same number of elements * @return an NDList even if `numOfSlice` is 1 */ private NDList split(NDArray array, int numOfSlices, boolean evenSplit) { int batchSize = Math.toIntExact(array.size(0)); if (batchSize < numOfSlices) { throw new IllegalArgumentException( "Batch size(" + batchSize + ") is less then slice number(" + numOfSlices + ")."); } if (evenSplit && batchSize % numOfSlices != 0) { throw new IllegalArgumentException( "data with shape " + batchSize + " cannot be evenly split into " + numOfSlices + ". Use a batch size that's multiple of " + numOfSlices + " or set even_split=true to allow" + " uneven partitioning of data."); } if (evenSplit) { return array.split(numOfSlices); } int step = (int) Math.ceil((double) batchSize / numOfSlices); long[] indices = LongStream.range(1, numOfSlices).map(i -> i * step).toArray(); return array.split(indices); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/Transform.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.translate; import ai.djl.ndarray.NDArray; /** * An interface to apply various transforms to the input. * * <p>A transform can be any function that modifies the input. Some examples of transform are crop * and resize. */ public interface Transform { /** * Applies the {@code Transform} to the given {@link NDArray}. * * @param array the {@link NDArray} on which the {@link Transform} is applied * @return the output of the {@code Transform} */ NDArray transform(NDArray array); }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/TranslateException.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.translate; /** Thrown to indicate that an error is raised during processing of the input or output. */ public class TranslateException extends Exception { 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 TranslateException(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 TranslateException(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 TranslateException(Throwable cause) { super(cause); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/Translator.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.translate; import ai.djl.inference.Predictor; import ai.djl.ndarray.NDList; import java.util.ArrayList; import java.util.List; /** * The {@code Translator} interface provides model pre-processing and postprocessing functionality. * * <p>Users can use this in {@link Predictor} with input and output objects specified. The * recommended flow is to use the Translator to translate only a single data item at a time ({@link * ai.djl.training.dataset.Record}) rather than a Batch. For example, the input parameter would then * be {@code Image} rather than {@code Image[]}. The {@link ai.djl.training.dataset.Record}s will * then be combined using a {@link Batchifier}. If it is easier in your use case to work with * batches directly or your model uses records instead of batches, you can use the {@link * NoBatchifyTranslator}. * * <p>The following is an example of processing an image and creating classification output: * * <pre> * private static final class MyTranslator implements Translator&lt;Image, Classification&gt; { * * private int imageWidth; * private int imageHeight; * * public MyTranslator(int imageWidth, int imageHeight) { * this.imageWidth = imageWidth; * this.imageHeight = imageHeight; * } * * &#064;Override * public NDList processInput(TranslatorContext ctx, Image input) { * NDArray imageND = input.toNDArray(ctx.getNDManager()); * return new NDList(NDImageUtils.resize(imageND, imageWidth, imageHeight); * } * * &#064;Override * public Classification processOutput(TranslatorContext ctx, NDList list) throws TranslateException { * Model model = ctx.getModel(); * NDArray array = list.get(0).at(0); * NDArray sorted = array.argSort(-1, false); * NDArray top = sorted.at(0); * * float[] probabilities = array.toFloatArray(); * int topIndex = top.toIntArray()[0]; * * String[] synset; * try { * synset = model.getArtifact("synset.txt", MyTranslator::loadSynset); * } catch (IOException e) { * throw new TranslateException(e); * } * return new Classification(synset[topIndex], probabilities[topIndex]); * } * * private static String[] loadSynset(InputStream is) { * ... * } * } * </pre> * * @param <I> the input type * @param <O> the output type */ public interface Translator<I, O> extends PreProcessor<I>, PostProcessor<O> { /** * Returns the {@link Batchifier}. * * @return the {@link Batchifier} */ default Batchifier getBatchifier() { return Batchifier.STACK; } /** * Batch processes the inputs and converts it to NDList. * * @param ctx the toolkit for creating the input NDArray * @param inputs a list of the input object * @return the {@link NDList} after pre-processing * @throws Exception if an error occurs during processing input */ @SuppressWarnings("PMD.SignatureDeclareThrowsException") default NDList batchProcessInput(TranslatorContext ctx, List<I> inputs) throws Exception { NDList[] preprocessed = new NDList[inputs.size()]; int index = 0; for (I input : inputs) { preprocessed[index++] = processInput(ctx, input); } return getBatchifier().batchify(preprocessed); } /** * Batch processes the output NDList to the corresponding output objects. * * @param ctx the toolkit used for post-processing * @param list the output NDList after inference, usually immutable in engines like * PyTorch. @see <a href="https://github.com/deepjavalibrary/djl/issues/1774">Issue 1774</a> * @return a list of the output object of expected type * @throws Exception if an error occurs during processing output */ @SuppressWarnings("PMD.SignatureDeclareThrowsException") default List<O> batchProcessOutput(TranslatorContext ctx, NDList list) throws Exception { NDList[] unbatched = getBatchifier().unbatchify(list); List<O> outputs = new ArrayList<>(unbatched.length); for (NDList output : unbatched) { outputs.add(processOutput(ctx, output)); } return outputs; } /** * Prepares the translator with the manager and model to use. * * @param ctx the context for the {@code Predictor}. * @throws Exception if there is an error for preparing the translator */ @SuppressWarnings("PMD.SignatureDeclareThrowsException") default void prepare(TranslatorContext ctx) throws Exception {} /** * Returns possible {@link TranslatorOptions} that can be built using this {@link Translator}. * * @return possible options or null if not defined */ default TranslatorOptions getExpansions() { return null; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/TranslatorContext.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.translate; import ai.djl.Model; import ai.djl.metric.Metrics; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; import ai.djl.nn.Block; /** * The {@code TranslatorContext} interface provides a toolkit for pre-processing and postprocessing * functionality. * * <p>You can use this in {@link Translator} to get Model information and create an NDArray */ public interface TranslatorContext extends AutoCloseable { /** * Returns the {@link Model} object to understand the input/output. * * @return the {@link Model} */ Model getModel(); /** * Returns the {@link NDManager} to create {@link NDArray}. * * @return the {@link NDManager} */ NDManager getNDManager(); /** * Returns the Predictor's {@link NDManager}. * * @return the Predictor's {@link NDManager} */ NDManager getPredictorManager(); /** * Returns the block from the {@code TranslatorContext}. * * @return the block from the {@code TranslatorContext} */ Block getBlock(); /** * Returns the Metric tool to do benchmark. * * @return the {@link Metrics} */ Metrics getMetrics(); /** * Returns value of attached key-value pair to context. * * @param key key of attached value * @return the object stored in relevant map */ Object getAttachment(String key); /** * Set a key-value pair of attachments. * * @param key key of attached value * @param value value assosicated with key */ void setAttachment(String key, Object value); /** {@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/translate/TranslatorFactory.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.translate; import ai.djl.Model; import ai.djl.util.Pair; import java.lang.reflect.Type; import java.util.Map; import java.util.Set; /** A utility class creates {@link Translator} instances. */ public interface TranslatorFactory { /** * Returns supported input/output classes. * * @return a set of supported input/output classes */ Set<Pair<Type, Type>> getSupportedTypes(); /** * Returns if the input/output is supported by the {@code TranslatorFactory}. * * @param input the input class * @param output the output class * @return {@code true} if the input/output type is supported */ default boolean isSupported(Class<?> input, Class<?> output) { return getSupportedTypes().contains(new Pair<Type, Type>(input, output)); } /** * Returns a new instance of the {@link Translator} class. * * @param <I> the input data type * @param <O> the output data type * @param input the input class * @param output the output class * @param model the {@link Model} that uses the {@link Translator} * @param arguments the configurations for a new {@code Translator} instance * @return a new instance of the {@code Translator} class * @throws TranslateException if failed to create Translator instance */ <I, O> Translator<I, O> newInstance( Class<I> input, Class<O> output, Model model, Map<String, ?> arguments) throws TranslateException; }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/TranslatorOptions.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.translate; import ai.djl.util.Pair; import java.lang.reflect.Type; import java.util.Set; /** A set of possible options for {@link Translator}s with different input and output types. */ public interface TranslatorOptions { /** * Returns the supported wrap types. * * @return the supported wrap types * @see #option(Class, Class) */ Set<Pair<Type, Type>> getOptions(); /** * Returns if the input/output is a supported wrap type. * * @param input the input class * @param output the output class * @return {@code true} if the input/output type is supported * @see #option(Class, Class) */ default boolean isSupported(Class<?> input, Class<?> output) { return getOptions().contains(new Pair<Type, Type>(input, output)); } /** * Returns the {@link Translator} option with the matching input and output type. * * @param <I> the input data type * @param <O> the output data type * @param input the input class * @param output the output class * @return a new instance of the {@code Translator} class * @throws TranslateException if failed to create Translator instance */ <I, O> Translator<I, O> option(Class<I> input, Class<O> output) throws TranslateException; }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/translate/package-info.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** * Contains classes and interfaces that translate between java objects and NDArrays. * * @see ai.djl.translate.Translator * @see ai.djl.translate.Batchifier * @see ai.djl.translate.Pipeline */ package ai.djl.translate;
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/ClassLoaderUtils.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.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.tools.JavaCompiler; import javax.tools.ToolProvider; /** A utility class that load classes from specific URLs. */ public final class ClassLoaderUtils { private static final Logger logger = LoggerFactory.getLogger(ClassLoaderUtils.class); private ClassLoaderUtils() {} /** * scan classes files from a path to see if there is a matching implementation for a class. * * <p>For .class file, this function expects them in classes/your/package/ClassName.class * * @param path the path to scan from * @param type the type of the class * @param className the name of the classes, pass null if name is unknown * @param <T> the Template T for the output Class * @return the Class implementation */ public static <T> T findImplementation(Path path, Class<T> type, String className) { try { Path classesDir = path.resolve("classes"); // we only consider .class files and skip .java files List<Path> jarFiles; if (Files.isDirectory(path)) { try (Stream<Path> stream = Files.list(path)) { jarFiles = stream.filter(p -> p.toString().endsWith(".jar")) .collect(Collectors.toList()); } } else { jarFiles = Collections.emptyList(); } final URL[] urls = new URL[jarFiles.size() + 1]; urls[0] = classesDir.toUri().toURL(); int index = 1; for (Path p : jarFiles) { urls[index++] = p.toUri().toURL(); } final ClassLoader contextCl = getContextClassLoader(); ClassLoader cl = AccessController.doPrivileged( (PrivilegedAction<ClassLoader>) () -> new URLClassLoader(urls, contextCl)); if (className != null && !className.isEmpty()) { T impl = initClass(cl, type, className); if (impl == null) { logger.warn("Failed to load class: {}", className); } return impl; } T implemented = scanDirectory(cl, type, classesDir); if (implemented != null) { return implemented; } for (Path p : jarFiles) { implemented = scanJarFile(cl, type, p); if (implemented != null) { return implemented; } } } catch (IOException e) { logger.debug("Failed to find Translator", e); } return null; } private static <T> T scanDirectory(ClassLoader cl, Class<T> type, Path dir) throws IOException { if (!Files.isDirectory(dir)) { logger.trace("Directory not exists: {}", dir); return null; } try (Stream<Path> stream = Files.walk(dir)) { List<Path> files = stream.filter(p -> Files.isRegularFile(p) && p.toString().endsWith(".class")) .collect(Collectors.toList()); for (Path file : files) { Path p = dir.relativize(file); String className = p.toString(); className = className.substring(0, className.lastIndexOf('.')); className = className.replace(File.separatorChar, '.'); T implemented = initClass(cl, type, className); if (implemented != null) { return implemented; } } } return null; } private static <T> T scanJarFile(ClassLoader cl, Class<T> type, Path path) throws IOException { try (JarFile jarFile = new JarFile(path.toFile())) { Enumeration<JarEntry> en = jarFile.entries(); while (en.hasMoreElements()) { JarEntry entry = en.nextElement(); String fileName = entry.getName(); if (fileName.endsWith(".class")) { fileName = fileName.substring(0, fileName.lastIndexOf('.')); fileName = fileName.replace('/', '.'); T implemented = initClass(cl, type, fileName); if (implemented != null) { return implemented; } } } } return null; } /** * Loads the specified class and constructs an instance. * * @param cl the {@code ClassLoader} to use * @param type the type of the class * @param className the class to be loaded * @param <T> the type of the class * @return an instance of the class, null if the class not found */ public static <T> T initClass(ClassLoader cl, Class<T> type, String className) { try { Class<?> clazz = Class.forName(className, true, cl); Class<? extends T> sub = clazz.asSubclass(type); Constructor<? extends T> constructor = sub.getConstructor(); return constructor.newInstance(); } catch (Throwable e) { logger.trace("Not able to load Object", e); } return null; } /** * Returns the context class loader if available. * * @return the context class loader if available */ public static ClassLoader getContextClassLoader() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { return ClassLoaderUtils.class.getClassLoader(); // NOPMD } return cl; } /** * Finds all the resources with the given name. * * @param name the resource name * @return An enumeration of {@link java.net.URL URL} objects for the resource * @throws IOException if I/O errors occur */ public static Enumeration<URL> getResources(String name) throws IOException { return getContextClassLoader().getResources(name); } /** * Finds the first resource in class path with the given name. * * @param name the resource name * @return an enumeration of {@link java.net.URL URL} objects for the resource * @throws IOException if I/O errors occur */ public static URL getResource(String name) throws IOException { Enumeration<URL> en = getResources(name); if (en.hasMoreElements()) { return en.nextElement(); } return null; } /** * Returns an {@code InputStream} for reading from the resource. * * @param name the resource name * @return an {@code InputStream} for reading * @throws IOException if I/O errors occur */ public static InputStream getResourceAsStream(String name) throws IOException { URL url = getResource(name); if (url == null) { throw new IOException("Resource not found in classpath: " + name); } return url.openStream(); } /** * Uses provided nativeHelper to load native library. * * @param nativeHelper a native helper class that loads native library * @param path the native library file path */ public static void nativeLoad(String nativeHelper, String path) { try { Class<?> clazz = Class.forName(nativeHelper, true, getContextClassLoader()); Method method = clazz.getDeclaredMethod("load", String.class); method.invoke(null, path); } catch (ReflectiveOperationException e) { throw new IllegalArgumentException("Invalid native_helper: " + nativeHelper, e); } } /** * Tries to compile java classes in the directory. * * @param dir the directory to scan java file. */ public static void compileJavaClass(Path dir) { try { if (!Files.isDirectory(dir)) { logger.debug("Directory not exists: {}", dir); return; } String[] files; try (Stream<Path> stream = Files.walk(dir)) { files = stream.filter(p -> Files.isRegularFile(p) && p.toString().endsWith(".java")) .map(p -> p.toAbsolutePath().toString()) .toArray(String[]::new); } JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (files.length > 0) { compiler.run(null, null, null, files); } } catch (Throwable e) { logger.warn("Failed to compile bundled java file", e); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/Ec2Utils.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.util; import ai.djl.engine.Engine; import com.google.gson.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; /** A utility class to retrieve EC2 metadata. */ public final class Ec2Utils { private static final Logger logger = LoggerFactory.getLogger(Ec2Utils.class); private static final String ENDPOINT_METADATA_FILE = "/opt/ml/.sagemaker_infra/endpoint-metadata.json"; private static final String TOKEN_URL = "http://169.254.169.254/latest/api/token"; private static final String EC2_METADATA = "http://169.254.169.254/latest/meta-data/"; private static final long ONE_DAY = Duration.ofDays(1).toMillis(); private static long lastCheckIn; private Ec2Utils() {} /** * Check if the current environment is SageMaker. * * @return true if the current environment is SageMaker */ public static boolean isSageMaker() { try { return Files.exists(Paths.get(ENDPOINT_METADATA_FILE)); } catch (SecurityException e) { logger.warn("Security manager doesn't allow access file"); return false; } } /** * Returns the EC2 metadata for specified key. * * @param key the key to retrieve * @return the EC2 metadata for specified key */ public static String readMetadata(String key) { HttpURLConnection conn = null; try { String header = "X-aws-ec2-metadata-token"; String token = getToken(); String url = EC2_METADATA + key; conn = openConnection(new URL(url), "GET", header, token); int statusCode = conn.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_OK) { try (InputStream is = conn.getInputStream()) { return Utils.toString(is); } } else { String reason = conn.getResponseMessage(); logger.debug("Failed to get EC2 metadata: {} {}", statusCode, reason); } } catch (IOException ignore) { // ignore } finally { if (conn != null) { conn.disconnect(); } } return null; } /** * Sends telemetry information. * * @param engine the default engine name */ public static void callHome(String engine) { if (Utils.isOfflineMode() || Boolean.parseBoolean(Utils.getEnvOrSystemProperty("OPT_OUT_TRACKING")) || System.currentTimeMillis() - lastCheckIn < ONE_DAY) { return; } lastCheckIn = System.currentTimeMillis(); String instanceId; String region; // If running on SageMaker, read from endpoint metadata file if (isSageMaker()) { instanceId = readEndpointMetadata("ResourceId"); region = Utils.getenv("AWS_REGION"); } else { // Else, read from EC2 metadata API instanceId = readMetadata("instance-id"); region = readMetadata("placement/region"); } if (instanceId == null || region == null || region.length() == 0) { return; } String url = "https://djl-telemetry-" + region + ".s3." + region + ".amazonaws.com/telemetry.txt?instance-id=" + instanceId + "&version=" + Engine.getDjlVersion() + "&engine=" + engine; HttpURLConnection conn = null; try { conn = openConnection(new URL(url), "GET", null, null); int statusCode = conn.getResponseCode(); if (statusCode != HttpURLConnection.HTTP_OK) { logger.debug("telemetry: {} {}", statusCode, conn.getResponseMessage()); } else { logger.info( "DJL will collect telemetry to help us better understand our users' needs," + " diagnose issues, and deliver additional features. If you would like" + " to learn more or opt-out please go to:" + " https://docs.djl.ai/master/docs/telemetry.html for more" + " information."); } } catch (IOException e) { logger.debug("Failed call home."); } finally { if (conn != null) { conn.disconnect(); } } } private static String getToken() { HttpURLConnection conn = null; try { String header = "X-aws-ec2-metadata-token-ttl-seconds"; conn = openConnection(new URL(TOKEN_URL), "PUT", header, "21600"); int statusCode = conn.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_OK) { try (InputStream is = conn.getInputStream()) { return Utils.toString(is); } } else { logger.debug("EC2 IMDSv2: {} {}", statusCode, conn.getResponseMessage()); } } catch (IOException ignore) { // ignore } finally { if (conn != null) { conn.disconnect(); } } return null; } private static String readEndpointMetadata(String key) { Path path = Paths.get(ENDPOINT_METADATA_FILE); try (Reader reader = Files.newBufferedReader(path)) { JsonObject json = JsonUtils.GSON.fromJson(reader, JsonObject.class); return json.get(key).getAsString(); } catch (IOException e) { // ignore } return null; } private static HttpURLConnection openConnection( URL url, String method, String header, String value) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); conn.setConnectTimeout(1000); conn.setReadTimeout(1000); conn.setRequestMethod(method); conn.setDoOutput(true); conn.addRequestProperty("Accept", "*/*"); conn.addRequestProperty("User-Agent", "djl"); if (value != null) { conn.addRequestProperty(header, value); } conn.setInstanceFollowRedirects(false); conn.connect(); return conn; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/Float16Utils.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.util; import ai.djl.ndarray.NDManager; import java.nio.ByteBuffer; import java.nio.ShortBuffer; /** {@code Float16Utils} is a set of utilities for working with float16. */ @SuppressWarnings("PMD.AvoidUsingShortType") public final class Float16Utils { public static final short ONE = floatToHalf(1); private Float16Utils() {} /** * Converts a byte buffer of float16 values into a float32 array. * * @param buffer the buffer of float16 values as bytes. * @return an array of float32 values. */ public static float[] fromByteBuffer(ByteBuffer buffer) { return fromShortBuffer(buffer.asShortBuffer()); } /** * Converts a short buffer of float16 values into a float32 array. * * @param buffer the buffer of float16 values as shorts. * @return an array of float32 values. */ public static float[] fromShortBuffer(ShortBuffer buffer) { int index = 0; float[] ret = new float[buffer.remaining()]; while (buffer.hasRemaining()) { short value = buffer.get(); ret[index++] = halfToFloat(value); } return ret; } /** * Converts an array of float32 values into a byte buffer of float16 values. * * @param manager the manager to allocate the buffer from. * @param floats an array of float32 values. * @return a byte buffer with float16 values represented as shorts (2 bytes each). */ public static ByteBuffer toByteBuffer(NDManager manager, float[] floats) { ByteBuffer buffer = manager.allocateDirect(floats.length * 2); for (float f : floats) { short value = floatToHalf(f); buffer.putShort(value); } buffer.rewind(); return buffer; } /** * Converts a float32 value into a float16 value. * * @param fVal a float32 value. * @return a float16 value represented as a short. */ public static short floatToHalf(float fVal) { int bits = Float.floatToIntBits(fVal); int sign = bits >>> 16 & 0x8000; int val = (bits & 0x7fffffff) + 0x1000; if (val >= 0x47800000) { if ((bits & 0x7fffffff) >= 0x47800000) { if (val < 0x7f800000) { return (short) (sign | 0x7c00); } return (short) (sign | 0x7c00 | (bits & 0x007fffff) >>> 13); } return (short) (sign | 0x7bff); } if (val >= 0x38800000) { return (short) (sign | val - 0x38000000 >>> 13); } if (val < 0x33000000) { return (short) sign; } val = (bits & 0x7fffffff) >>> 23; return (short) (sign | ((bits & 0x7fffff | 0x800000) + (0x800000 >>> val - 102) >>> 126 - val)); } /** * Converts a float16 value into a float32 value. * * @param half a float16 value represented as a short. * @return a float32 value. */ public static float halfToFloat(short half) { int mant = half & 0x03ff; int exp = half & 0x7c00; if (exp == 0x7c00) { exp = 0x3fc00; } else if (exp != 0) { exp += 0x1c000; if (mant == 0 && exp > 0x1c400) { return Float.intBitsToFloat((half & 0x8000) << 16 | exp << 13); } } else if (mant != 0) { exp = 0x1c400; do { mant <<= 1; exp -= 0x400; } while ((mant & 0x400) == 0); mant &= 0x3ff; } return Float.intBitsToFloat((half & 0x8000) << 16 | (exp | mant) << 13); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/Hex.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.util; /** {@code Hex} is a set of utilities for working with Hexadecimal Strings. */ public final class Hex { private static final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; private Hex() {} /** * Converts a byte array to a hex string. * * @param block the bytes to convert * @return the converted hex String */ public static String toHexString(byte[] block) { return toHexString(block, 0, block.length); } /** * Converts a byte array to a hex string. * * @param block the bytes to convert * @param start the start position (inclusive) of the array * @param end the end position (exclusive) of the array * @return the converted hex String */ public static String toHexString(byte[] block, int start, int end) { if (block == null) { return null; } StringBuilder buf = new StringBuilder(); for (int i = start; i < end; ++i) { byte aBlock = block[i]; int high = ((aBlock & 0xf0) >> 4); int low = (aBlock & 0x0f); buf.append(HEX_CHARS[high]); buf.append(HEX_CHARS[low]); } return buf.toString(); } /** * Converts a hex string to a byte array. * * @param s the string to convert * @return the converted byte array */ public static byte[] toByteArray(String s) { int len = s.length(); if ((len % 2) != 0) { throw new NumberFormatException("Invalid Hex String"); } byte[] ret = new byte[len / 2]; for (int i = 0; i < len / 2; i++) { ret[i] = (byte) Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16); } return ret; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/JsonSerializable.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.util; import ai.djl.ndarray.BytesSupplier; import com.google.gson.JsonElement; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import java.io.Serializable; import java.lang.reflect.Type; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; /** * A class implements {@code JsonSerializable} indicates it can be serialized into a json string. */ public interface JsonSerializable extends Serializable, BytesSupplier { /** * Returns a json presentation of the object. * * @return a json string */ default String toJson() { return JsonUtils.GSON_COMPACT.toJson(serialize()); } /** {@inheritDoc} */ @Override default String getAsString() { return toJson(); } /** {@inheritDoc} */ @Override default ByteBuffer toByteBuffer() { return ByteBuffer.wrap(toJson().getBytes(StandardCharsets.UTF_8)); } /** {@inheritDoc} */ JsonElement serialize(); /** A customized Gson serializer to serialize the {@code JsonSerializable} object. */ final class Serializer implements JsonSerializer<JsonSerializable> { /** {@inheritDoc} */ @Override public JsonElement serialize( JsonSerializable src, Type type, JsonSerializationContext ctx) { return src.serialize(); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/JsonUtils.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.util; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializer; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.List; /** An interface containing Gson constants. */ public interface JsonUtils { boolean PRETTY_PRINT = Boolean.parseBoolean(Utils.getEnvOrSystemProperty("DJL_PRETTY_PRINT")); Gson GSON = builder().create(); Gson GSON_COMPACT = builder(false).create(); Gson GSON_PRETTY = builder(true).create(); Type LIST_TYPE = new TypeToken<List<String>>() {}.getType(); /** * Returns a custom {@code GsonBuilder} instance. * * @return a custom {@code GsonBuilder} instance. */ static GsonBuilder builder() { return builder(PRETTY_PRINT); } /** * Returns a custom {@code GsonBuilder} instance. * * @param prettyPrint true for pretty print * @return a custom {@code GsonBuilder} instance. */ static GsonBuilder builder(boolean prettyPrint) { GsonBuilder builder = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .serializeSpecialFloatingPointValues() .registerTypeHierarchyAdapter( JsonSerializable.class, new JsonSerializable.Serializer()) .registerTypeAdapter( Double.class, (JsonSerializer<Double>) (src, t, ctx) -> { long v = src.longValue(); if (src.equals(Double.valueOf(String.valueOf(v)))) { return new JsonPrimitive(v); } return new JsonPrimitive(src); }); if (prettyPrint) { builder.setPrettyPrinting(); } return builder; } /** * Serializes the specified object into its equivalent JSON representation. * * @param src the source object * @return the json string */ static String toJson(Object src) { return GSON.toJson(src); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/NativeResource.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.util; import com.sun.jna.Pointer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.atomic.AtomicReference; /** * {@code NativeResource} is an internal class for {@link AutoCloseable} blocks of memory created in * the different engines. * * @param <T> the resource that could map to a native pointer or java object */ public abstract class NativeResource<T> implements AutoCloseable { private static final Logger logger = LoggerFactory.getLogger(NativeResource.class); private static final boolean TRACK_RESOURCE = Boolean.getBoolean("ai.djl.track_resource"); protected final AtomicReference<T> handle; private String uid; private Exception exception; protected NativeResource(T handle) { this.handle = new AtomicReference<>(handle); uid = handle.toString() + System.nanoTime(); } /** * Gets the boolean that indicates whether this resource has been released. * * @return whether this resource has been released */ public boolean isReleased() { return handle.get() == null; } /** * Gets the {@link Pointer} to this resource. * * @return the {@link Pointer} to this resource */ public T getHandle() { T reference = handle.get(); if (reference == null) { if (TRACK_RESOURCE) { logger.error("Native resource {} is released. Closed at:", uid, exception); } String message = "Native resource has been released already."; throw new IllegalStateException(message); } return reference; } /** * Gets the unique ID of this resource. * * @return the unique ID of this resource */ public final String getUid() { return uid; } /** Remembers the stack trace on closing. */ public void onClose() { if (TRACK_RESOURCE) { exception = new Exception(); } } /** {@inheritDoc} */ @Override public void close() { throw new UnsupportedOperationException("Not implemented."); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/NeuronUtils.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.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** A utility class to detect number of nueron cores. */ public final class NeuronUtils { private static final Logger logger = LoggerFactory.getLogger(NeuronUtils.class); private NeuronUtils() {} /** * Returns whether Neuron runtime library is in the system. * * @return {@code true} if Neuron runtime library is in the system */ public static boolean hasNeuron() { return getNeuronCores() > 0; } /** * Returns the number of NeuronCores available in the system. * * @return the number of NeuronCores available in the system */ public static int getNeuronCores() { List<String> nd = getNeuronDevices("/dev/"); if (nd.isEmpty()) { return 0; } int cores = getNeuronCoresForDevice(nd.get(0)); return nd.size() * cores; } /** * Returns a list of neuron device file path. * * @param location the neuron device path * @return a list of neuron device name */ public static List<String> getNeuronDevices(String location) { Path path = Paths.get(location); if (!Files.exists(path)) { return Collections.emptyList(); } try (Stream<Path> dev = Files.list(path)) { return dev.filter(p -> matches(p, "neuron")) .map(p -> "/sys/devices/virtual/neuron_device/" + p.toFile().getName()) .collect(Collectors.toList()); } catch (IOException e) { logger.warn("Failed to list neuron cores", e); } return Collections.emptyList(); } /** * Returns the number of neuron cores per device. * * @param location the neuron device file path * @return the number of neuron cores */ public static int getNeuronCoresForDevice(String location) { Path path = Paths.get(location); if (!Files.exists(path)) { return 0; } Path file = path.resolve("core_count"); if (Files.exists(file) && Files.isReadable(file)) { try (InputStream is = Files.newInputStream(file)) { return Integer.parseInt(Utils.toString(is)); } catch (IOException e) { throw new AssertionError("Failed to read core_count file", e); } } int count = 0; try (Stream<Path> dev = Files.list(path)) { return Math.toIntExact(dev.filter(p -> matches(p, "neuron_core")).count()); } catch (IOException e) { logger.warn("Failed to list neuron cores", e); } return count; } private static boolean matches(Path p, String pattern) { return p.toFile().getName().startsWith(pattern); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/Pair.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.util; import java.util.Objects; /** * A class containing the key-value pair. * * @param <K> the key type * @param <V> the value type */ public class Pair<K, V> { private K key; private V value; /** * Constructs a {@code Pair} instance with key and value. * * @param key the key * @param value the value */ public Pair(K key, V value) { this.key = key; this.value = value; } /** * Returns the key of this pair. * * @return the key */ public K getKey() { return key; } /** * Returns the value of this pair. * * @return the value */ public V getValue() { return value; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Pair<?, ?> pair = (Pair<?, ?>) o; return Objects.equals(key, pair.key) && value.equals(pair.value); } /** {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(key, value); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/PairList.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.util; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * The {@code PairList} class provides an efficient way to access a list of key-value pairs. * * @param <K> the key type * @param <V> the value type */ public class PairList<K, V> implements Iterable<Pair<K, V>> { private List<K> keys; private List<V> values; /** Constructs an empty {@code PairList}. */ public PairList() { keys = new ArrayList<>(); values = new ArrayList<>(); } /** * Constructs an empty {@code PairList} with the specified initial capacity. * * @param initialCapacity the initial capacity of the list * @throws IllegalArgumentException if the specified initial capacity is negative */ public PairList(int initialCapacity) { keys = new ArrayList<>(initialCapacity); values = new ArrayList<>(initialCapacity); } /** * Constructs a {@code PairList} containing the elements of the specified keys and values. * * @param keys the key list containing elements to be placed into this PairList * @param values the value list containing elements to be placed into this PairList * @throws IllegalArgumentException if the keys and values size are different */ public PairList(List<K> keys, List<V> values) { if (keys.size() != values.size()) { throw new IllegalArgumentException("key value size mismatch."); } this.keys = keys; this.values = values; } /** * Constructs a {@code PairList} containing the elements of the specified list of Pairs. * * @param list the list containing elements to be placed into this PairList */ public PairList(List<? extends Pair<K, V>> list) { this(list.size()); for (Pair<K, V> pair : list) { keys.add(pair.getKey()); values.add(pair.getValue()); } } /** * Constructs a {@code PairList} containing the elements of the specified map. * * @param map the map contains keys and values */ public PairList(Map<K, V> map) { keys = new ArrayList<>(map.size()); values = new ArrayList<>(map.size()); for (Map.Entry<K, V> entry : map.entrySet()) { keys.add(entry.getKey()); values.add(entry.getValue()); } } /** * Inserts the specified element at the specified position in this list (optional operation), * and shifts the element currently at that position (if any) and any subsequent elements to the * right (adds one to their indices). * * @param index the index at which the specified element is to be inserted * @param key the key * @param value the value */ public void add(int index, K key, V value) { keys.add(index, key); values.add(index, value); } /** * Adds a key and value to the list. * * @param key the key * @param value the value */ public void add(K key, V value) { keys.add(key); values.add(value); } /** * Adds a key-value pair to the list. * * @param pair the key-value pair */ public void add(Pair<K, V> pair) { keys.add(pair.getKey()); values.add(pair.getValue()); } /** * Appends all of the elements in the specified pair list to the end of this list. * * @param other the {@code PairList} containing elements to be added to this list */ public void addAll(PairList<K, V> other) { if (other != null) { keys.addAll(other.keys()); values.addAll(other.values()); } } /** * Returns the size of the list. * * @return the size of the list */ public int size() { return keys.size(); } /** * Checks whether the list is empty. * * @return whether the list is empty */ public boolean isEmpty() { return size() == 0; } /** * Returns the key-value pair at the specified position in this list. * * @param index the index of the element to return * @return the key-value pair at the specified position in this list */ public Pair<K, V> get(int index) { return new Pair<>(keys.get(index), values.get(index)); } /** * Returns the value for the first key found in the list. * * @param key the key of the element to get * @return the value for the first key found in the list */ public V get(K key) { int index = keys.indexOf(key); if (index == -1) { return null; } return values.get(index); } /** * Returns the index of the first occurrence of the specified element in this list, or -1 if * this list does not contain the element. * * @param key – element to search for * @return the index of the first occurrence of the specified element in this list, or -1 if * this list does not contain the element */ public int indexOf(K key) { return keys.indexOf(key); } /** * Returns the key at the specified position in this list. * * @param index the index of the element to return * @return the key at the specified position in this list */ public K keyAt(int index) { return keys.get(index); } /** * Returns the value at the specified position in this list. * * @param index the index of the element to return * @return the value at the specified position in this list */ public V valueAt(int index) { return values.get(index); } /** * Returns all keys of the list. * * @return all keys of the list */ public List<K> keys() { return keys; } /** * Returns all values of the list. * * @return all values of the list */ public List<V> values() { return values; } /** * Returns an array containing all of the keys in this list in proper sequence (from first to * last element); the runtime type of the returned array is that of the specified array. * * <p>If the list fits in the specified array, it is returned therein. Otherwise, a new array is * allocated with the runtime type of the specified array and the size of this list. * * @param target the array into which the keys of this list are to be stored, if it is big * enough; otherwise, a new array of the same runtime type is allocated for this purpose. * @return an array containing the keys of this list */ public K[] keyArray(K[] target) { return keys.toArray(target); } /** * Returns an array containing all of the values in this list in proper sequence (from first to * last element); the runtime type of the returned array is that of the specified array. * * <p>If the list fits in the specified array, it is returned therein. Otherwise, a new array is * allocated with the runtime type of the specified array and the size of this list. * * @param target the array into which the values of this list are to be stored, if it is big * enough; otherwise, a new array of the same runtime type is allocated for this purpose. * @return an array containing the values of this list */ public V[] valueArray(V[] target) { return values.toArray(target); } /** Removes all the elements from this pair list. */ public void clear() { keys.clear(); values.clear(); } /** * Removes the key-value pair for the first key found in the list. * * @param key the key of the element to be removed * @return the value of the removed element, {@code null} if not found */ public V remove(K key) { int index = keys.indexOf(key); if (index == -1) { return null; } return remove(index); } /** * Removes the key-value pair at an index. * * @param index the index of the element to remove * @return the value of the removed element, {@code null} if not found */ public V remove(int index) { keys.remove(index); return values.remove(index); } /** * Returns a view of the portion of this PairList between the specified {@code fromIndex} * inclusive, and to the end. * * @param fromIndex the start index (inclusive) * @return a view of the portion of this PairList */ public PairList<K, V> subList(int fromIndex) { return subList(fromIndex, size()); } /** * Returns a view of the portion of this PairList between the specified {@code fromIndex} * inclusive, and {@code toIndex}, exclusive. * * @param fromIndex the start index (inclusive) * @param toIndex the end index (exclusive) * @return a view of the portion of this PairList */ public PairList<K, V> subList(int fromIndex, int toIndex) { List<K> subKeys = keys.subList(fromIndex, toIndex); List<V> subValues = values.subList(fromIndex, toIndex); return new PairList<>(subKeys, subValues); } /** * Returns the {@link Stream} type of the PairList. * * @return a {@link Stream} of PairList */ public Stream<Pair<K, V>> stream() { return StreamSupport.stream(spliterator(), false); } /** * Returns {@code true} if this list contains the specified key. * * @param key the key whose presence will be tested * @return {@code true} if this list contains the specified key */ public boolean contains(K key) { return keys.contains(key); } /** * Removes all duplicate values from the list. * * @return a new {@code PairList} with the duplicate values removed, taking the latest value for * each key */ public PairList<K, V> unique() { return new PairList<>(toMap(false)); } /** {@inheritDoc} */ @Override public Iterator<Pair<K, V>> iterator() { return new Itr(); } /** * Returns a {@code Map} that contains the key-value mappings of this list. * * @return a {@code Map} that contains the key-value mappings of this list */ public Map<K, V> toMap() { return toMap(true); } /** * Returns a {@code Map} that contains the key-value mappings of this list. * * @param checkDuplicate whether to check for duplicated keys in the list * @return a {@code Map} that contains the key-value mappings of this list */ public Map<K, V> toMap(boolean checkDuplicate) { int size = keys.size(); Map<K, V> map = new LinkedHashMap<>(size * 3 / 2); // NOPMD for (int i = 0; i < size; ++i) { if (map.put(keys.get(i), values.get(i)) != null && checkDuplicate) { throw new IllegalStateException("Duplicate keys: " + keys.get(i)); } } return map; } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PairList<?, ?> pairList = (PairList<?, ?>) o; return keys.equals(pairList.keys) && values.equals(pairList.values); } /** {@inheritDoc} */ @Override public int hashCode() { return Objects.hash(keys, values); } /** Internal Iterator implementation. */ private class Itr implements Iterator<Pair<K, V>> { private int cursor; private int size = size(); Itr() {} /** {@inheritDoc} */ @Override public boolean hasNext() { return cursor < size; } /** {@inheritDoc} */ @Override public Pair<K, V> next() { if (cursor >= size) { throw new NoSuchElementException(); } return get(cursor++); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/Platform.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.util; import ai.djl.util.cuda.CudaUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Properties; /** * The platform contains information regarding the version, os, and build flavor of the native code. */ public final class Platform { private static final Logger logger = LoggerFactory.getLogger(Platform.class); private String version; private String apiVersion; private String osPrefix; private String osArch; private String flavor; private String cudaArch; private String[] libraries; private boolean placeholder; /** Constructor used only for {@link Platform#fromSystem()}. */ private Platform() {} /** * Returns the platform that matches current operating system. * * @param engine the name of the engine * @param overrideVersion the version of the engine * @return the platform that matches current operating system */ public static Platform detectPlatform(String engine, String overrideVersion) { Platform platform = Platform.fromSystem(engine); platform.version = overrideVersion; return platform; } /** * Returns the platform that matches current operating system. * * @param engine the name of the engine * @return the platform that matches current operating system */ public static Platform detectPlatform(String engine) { String nativeProp = "native/lib/" + engine + ".properties"; Enumeration<URL> urls; try { urls = ClassLoaderUtils.getContextClassLoader().getResources(nativeProp); } catch (IOException e) { throw new AssertionError("Failed to list property files.", e); } Platform systemPlatform = Platform.fromSystem(engine); List<Platform> availablePlatforms = new ArrayList<>(); while (urls.hasMoreElements()) { URL url = urls.nextElement(); Platform platform = Platform.fromUrl(url); platform.apiVersion = systemPlatform.apiVersion; if (platform.isPlaceholder()) { availablePlatforms.add(platform); } else if (platform.matches(systemPlatform)) { logger.info("Found matching platform from: {}", url); availablePlatforms.add(platform); } else { logger.info("Ignore mismatching platform from: {}", url); } } if (availablePlatforms.isEmpty()) { if (systemPlatform.version == null) { throw new AssertionError("No " + engine + " version found in property file."); } if (systemPlatform.apiVersion == null) { throw new AssertionError("No " + engine + " djl_version found in property file."); } return systemPlatform; } else if (availablePlatforms.size() == 1) { Platform ret = availablePlatforms.get(0); if (ret.isPlaceholder()) { logger.info("Found placeholder platform from: {}", ret); } return ret; } availablePlatforms.sort( (o1, o2) -> { if (o1.isPlaceholder()) { return 1; } else if (o2.isPlaceholder()) { return -1; } // cu121-precx11 > cu121 > cu118-precss11 > cpu-precxx11 > cpu int ret = o2.getFlavor().compareTo(o1.getFlavor()); if (ret == 0) { return o2.getVersion().compareTo(o1.getVersion()); } return ret; }); return availablePlatforms.get(0); } /** * Returns the platform that parsed from "engine".properties file. * * @param url the url to the "engine".properties file * @return the platform that parsed from "engine".properties file */ static Platform fromUrl(URL url) { Platform platform = Platform.fromSystem(); try (InputStream conf = url.openStream()) { Properties prop = new Properties(); prop.load(conf); platform.version = prop.getProperty("version"); if (platform.version == null) { throw new IllegalArgumentException( "version key is required in <engine>.properties file."); } platform.placeholder = prop.getProperty("placeholder") != null; String flavor = prop.getProperty("flavor"); if (flavor != null) { platform.flavor = flavor; } String flavorPrefixedClassifier = prop.getProperty("classifier", ""); String libraryList = prop.getProperty("libraries", ""); if (libraryList.isEmpty()) { platform.libraries = Utils.EMPTY_ARRAY; } else { platform.libraries = libraryList.split(","); } if (!flavorPrefixedClassifier.isEmpty()) { String[] tokens = flavorPrefixedClassifier.split("-"); if (flavor != null) { platform.osPrefix = tokens[0]; platform.osArch = tokens[1]; } else { platform.flavor = tokens[0]; platform.osPrefix = tokens[1]; platform.osArch = tokens[2]; } } } catch (IOException e) { throw new IllegalStateException("Failed to read property file: " + url, e); } return platform; } /** * Returns the system platform. * * @param engine the name of the engine * @return the platform representing the system (without an "engine".properties file) */ public static Platform fromSystem(String engine) { String engineProp = engine + "-engine.properties"; String versionKey = engine + "_version"; Platform platform = fromSystem(); platform.placeholder = true; try { URL url = ClassLoaderUtils.getResource(engineProp); if (url != null) { try (InputStream is = url.openStream()) { Properties prop = new Properties(); prop.load(is); platform.version = prop.getProperty(versionKey); platform.apiVersion = prop.getProperty("djl_version"); } } } catch (IOException e) { throw new AssertionError("Failed to read property file: " + engineProp, e); } return platform; } /** * Returns the platform for the current system. * * @return the platform for the current system */ static Platform fromSystem() { Platform platform = new Platform(); String osName = System.getProperty("os.name"); if (osName.startsWith("Win")) { platform.osPrefix = "win"; } else if (osName.startsWith("Mac")) { platform.osPrefix = "osx"; } else if (osName.startsWith("Linux")) { platform.osPrefix = "linux"; } else { throw new AssertionError("Unsupported platform: " + osName); } platform.osArch = System.getProperty("os.arch"); if ("amd64".equals(platform.osArch)) { platform.osArch = "x86_64"; } if (CudaUtils.getGpuCount() > 0) { platform.flavor = "cu" + CudaUtils.getCudaVersionString(); platform.cudaArch = CudaUtils.getComputeCapability(0); } else { platform.flavor = "cpu"; } return platform; } /** * Returns the Engine version. * * @return the Engine version */ public String getVersion() { return version; } /** * Returns the Engine API version. * * @return the Engine API version */ public String getApiVersion() { return apiVersion; } /** * Returns the os (win, osx, or linux). * * @return the os (win, osx, or linux) */ public String getOsPrefix() { return osPrefix; } /** * Returns the os architecture (x86_64, aar64, etc). * * @return the os architecture (x86_64, aar64, etc) */ public String getOsArch() { return osArch; } /** * Returns the engine build flavor. * * @return the engine build flavor */ public String getFlavor() { return flavor; } /** * Returns the classifier for the platform. * * @return the classifier for the platform */ public String getClassifier() { return osPrefix + '-' + osArch; } /** * Returns the cuda arch. * * @return the cuda arch */ public String getCudaArch() { return cudaArch; } /** * Returns the libraries used in the platform. * * @return the libraries used in the platform */ public String[] getLibraries() { return libraries; } /** * Returns true if the platform is a placeholder. * * @return true if the platform is a placeholder */ public boolean isPlaceholder() { return placeholder; } /** * Returns true the platforms match (os and flavor). * * @param system the platform to compare it to * @return true if the platforms match */ public boolean matches(Platform system) { if (!osPrefix.equals(system.osPrefix) || !osArch.equals(system.osArch)) { return false; } if (flavor.startsWith("cpu") || "mkl".equals(flavor)) { // CPU package can run on all system platform return true; } // native package can run on system which CUDA version is greater or equal if (system.flavor.startsWith("cu") && Integer.parseInt(flavor.substring(2, 5)) <= Integer.parseInt(system.flavor.substring(2, 5))) { return true; } logger.warn("The bundled library: {}} doesn't match system: {}", this, system); return false; } /** {@inheritDoc} */ @Override public String toString() { return flavor + '-' + getClassifier() + ':' + version; } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/Preconditions.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.util; /** * Static convenience methods that help a method or constructor check whether it was invoked * correctly. */ public final class Preconditions { private Preconditions() {} /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * @param expression a boolean expression * @param errorMessage the exception message to use if the check fails */ public static void checkArgument(boolean expression, String errorMessage) { if (!expression) { throw new IllegalArgumentException(errorMessage); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/Progress.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.util; /** An interface that allows tracking the progress of a task. */ public interface Progress { /** * Resets the progress tracking indicators, and sets the message and max to the given values. * * @param message the message to be shown * @param max the max value that the progress tracking indicator can take */ default void reset(String message, long max) { reset(message, max, null); } /** * Resets the progress tracking indicators, and sets the message and max to the given values. * * @param message the message to be shown * @param max the max value that the progress tracking indicator can take * @param trailingMessage the trailing message to be shown */ void reset(String message, long max, String trailingMessage); /** * Starts tracking the progress of the progress tracking indicators at the given initial value. * * @param initialProgress the initial value of the progress */ void start(long initialProgress); /** Updates the tracking indicators to indicate that the task is complete. */ void end(); /** * Increments the progress tracking indicator by the given value. * * @param increment the value to increment the progress by */ void increment(long increment); /** * Updates the progress tracking indicator to the given value. * * @param progress the value of the progress tracking indicator */ default void update(long progress) { update(progress, null); } /** * Updates the progress tracking indicator to the given value, and displays the optional * message. * * @param progress the value of the progress tracking indicator * @param message the optional message */ void update(long progress, String message); }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/RandomUtils.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.util; import java.util.Random; /** A class that holds a static instance of {@link Random} object. */ public final class RandomUtils { public static final Random RANDOM = new Random(); private RandomUtils() {} /** * Returns the next pseudorandom, uniformly distributed {@code double} value between {@code 0.0} * and {@code 1.0} from this random number generator's sequence. * * @return a random value between {@code 0.0} and {@code 1.0} */ public static double random() { return RANDOM.nextDouble(); } /** * Returns the next pseudorandom, Gaussian ("normally") distributed {@code double} value with * mean {@code 0.0} and standard deviation {@code 1.0} from this random number generator's * sequence. * * @return a double value with mean {@code 0.0} and standard deviation {@code 1.0} */ public static double nextGaussian() { return RANDOM.nextGaussian(); } /** * Returns the next pseudorandom, uniformly distributed {@code int} value from this random * number generator's sequence. * * @return an integer value from this random number generator's sequence */ public static int nextInt() { return RANDOM.nextInt(); } /** * Returns a pseudorandom, uniformly distributed {@code int} value between 0 (inclusive) and the * specified upper bound (exclusive), drawn from his random number generator's sequence. * * @param bound the bounding value * @return an integer value between 0 (inclusive) and the specified upper bound (exclusive) */ public static int nextInt(int bound) { return RANDOM.nextInt(bound); } /** * Returns a pseudorandom, uniformly distributed {@code float} value between lower and upper, * drawn from his random number generator's sequence. * * @param lower the lower bound (inclusive) * @param upper the upper bound (exclusive) * @return an float value between lower and upper */ public static float nextFloat(float lower, float upper) { float range = upper - lower; return RANDOM.nextFloat() * range + lower; } /** * Returns a pseudorandom, uniformly distributed {@code float} value between {@code 0.0} and * {@code 1.0}, drawn from his random number generator's sequence. * * @return an float value between {@code 0.0} and {@code 1.0} */ public static float nextFloat() { return RANDOM.nextFloat(); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/StringPair.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.util; /** A class containing the string key-value pair. */ public class StringPair extends Pair<String, String> { /** * Constructs a {@code Pair} instance with key and value. * * @param key the key * @param value the value */ public StringPair(String key, String value) { super(key, value); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/TarUtils.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.util; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.apache.commons.io.input.CloseShieldInputStream; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; /** Utilities for working with zip files. */ public final class TarUtils { private TarUtils() {} /** * Un-compress a tar ball from InputStream. * * @param is the InputStream * @param dir the target directory * @param gzip if the bar ball is gzip * @throws IOException for failures to untar the input directory */ public static void untar(InputStream is, Path dir, boolean gzip) throws IOException { InputStream bis; if (gzip) { bis = new GzipCompressorInputStream(new BufferedInputStream(is)); } else { bis = new BufferedInputStream(is); } bis = CloseShieldInputStream.wrap(bis); try (TarArchiveInputStream tis = new TarArchiveInputStream(bis)) { TarArchiveEntry entry; while ((entry = tis.getNextEntry()) != null) { String entryName = entry.getName(); ZipUtils.validateArchiveEntry(entryName, dir); Path file = dir.resolve(entryName).toAbsolutePath(); if (entry.isDirectory()) { Files.createDirectories(file); } else { Path parentFile = file.getParent(); if (parentFile == null) { throw new AssertionError("Parent path should never be null: " + file); } Files.createDirectories(parentFile); Files.copy(tis, file, StandardCopyOption.REPLACE_EXISTING); } } } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/Utils.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.util; import ai.djl.ndarray.NDArray; import ai.djl.nn.Parameter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.FileVisitOption; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; /** A class containing utility methods. */ public final class Utils { private static final Logger logger = LoggerFactory.getLogger(Utils.class); public static final String[] EMPTY_ARRAY = new String[0]; private Utils() {} /** * Returns the index of the first occurrence of the specified element in {@code array}, or -1 if * this list does not contain the element. * * @param array the input array * @param value the element to search for * @param <T> the array type * @return the index of the first occurrence of the specified element in {@code array}, or -1 if * this list does not contain the element */ public static <T> int indexOf(T[] array, T value) { if (array != null) { for (int i = 0; i < array.length; ++i) { if (value.equals(array[i])) { return i; } } } return -1; } /** * Returns {@code true} if the {@code array} contains the specified element. * * @param array the input array * @param value the element whose presence in {@code array} is to be tested * @param <T> the array type * @return {@code true} if this list contains the specified element */ public static <T> boolean contains(T[] array, T value) { return indexOf(array, value) >= 0; } /** * Adds padding chars to specified StringBuilder. * * @param sb the StringBuilder to append * @param c the padding char * @param count the number characters to be added */ public static void pad(StringBuilder sb, char c, int count) { for (int i = 0; i < count; ++i) { sb.append(c); } } /** * Deletes an entire directory and ignore all errors. * * @param dir the directory to be removed */ public static void deleteQuietly(Path dir) { List<Path> list; try (Stream<Path> stream = Files.walk(dir)) { list = stream.sorted(Comparator.reverseOrder()).collect(Collectors.toList()); } catch (IOException ignore) { return; } for (Path path : list) { try { Files.deleteIfExists(path); } catch (IOException ignore) { // ignore } } } /** * Renames a file to a target file and ignore error if target already exists. * * @param source the path to the file to move * @param target the path to the target file * @throws IOException if move file failed */ public static void moveQuietly(Path source, Path target) throws IOException { try { Files.move(source, target, StandardCopyOption.ATOMIC_MOVE); } catch (IOException e) { if (!Files.exists(target)) { throw e; } } } /** * Reads {@code is} as UTF-8 string. * * @param is the InputStream to be read * @return a UTF-8 encoded string * @throws IOException if IO error occurs */ public static String toString(InputStream is) throws IOException { return new String(toByteArray(is), StandardCharsets.UTF_8.name()); } /** * Reads {@code is} as byte array. * * @param is the InputStream to be read * @return a byte array * @throws IOException if IO error occurs */ public static byte[] toByteArray(InputStream is) throws IOException { byte[] buf = new byte[81920]; int read; ByteArrayOutputStream bos = new ByteArrayOutputStream(81920); while ((read = is.read(buf)) != -1) { bos.write(buf, 0, read); } bos.close(); return bos.toByteArray(); } /** * Reads all lines from a file. * * @param file the file to be read * @return all lines in the file * @throws IOException if read file failed */ public static List<String> readLines(Path file) throws IOException { return readLines(file, false); } /** * Reads all lines from a file. * * @param file the file to be read * @param trim true if you want to trim the line and exclude empty lines * @return all lines in the file * @throws IOException if read file failed */ public static List<String> readLines(Path file, boolean trim) throws IOException { if (Files.notExists(file)) { return Collections.emptyList(); } try (InputStream is = new BufferedInputStream(Files.newInputStream(file))) { return readLines(is, trim); } } /** * Reads all lines from the specified InputStream. * * @param is the InputStream to read * @return all lines from the input */ public static List<String> readLines(InputStream is) { return readLines(is, false); } /** * Reads all lines from the specified InputStream. * * @param is the InputStream to read * @param trim true if you want to trim the line and exclude empty lines * @return all lines from the input */ public static List<String> readLines(InputStream is, boolean trim) { List<String> list = new ArrayList<>(); try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name()).useDelimiter("\\n|\\r\\n")) { while (scanner.hasNext()) { String line = scanner.next(); if (trim) { line = line.trim(); if (line.isEmpty()) { continue; } } list.add(line); } } return list; } /** * Converts a List of Number to float array. * * @param list the list to be converted * @return a float array */ public static float[] toFloatArray(List<? extends Number> list) { float[] ret = new float[list.size()]; int idx = 0; for (Number n : list) { ret[idx++] = n.floatValue(); } return ret; } /** * Gets the current epoch number. * * @param modelDir the path to the directory where the model files are stored * @param modelName the name of the model * @return the current epoch number * @throws IOException if an I/O error occurs */ public static int getCurrentEpoch(Path modelDir, String modelName) throws IOException { final Pattern pattern = Pattern.compile(Pattern.quote(modelName) + "-(\\d{4}).params"); try (Stream<Path> stream = Files.walk(modelDir, 1, FileVisitOption.FOLLOW_LINKS)) { List<Integer> checkpoints = stream.map( p -> { Matcher m = pattern.matcher(p.toFile().getName()); if (m.matches()) { return Integer.parseInt(m.group(1)); } return null; }) .filter(Objects::nonNull) .sorted() .collect(Collectors.toList()); if (checkpoints.isEmpty()) { return -1; } return checkpoints.get(checkpoints.size() - 1); } } /** * Utility function to help debug nan values in parameters and their gradients. * * @param parameters the list of parameters to check * @param checkGradient whether to check parameter value or its gradient value * @param logger the logger to log the result */ public static void checkParameterValues( PairList<String, Parameter> parameters, boolean checkGradient, Logger logger) { for (Parameter parameter : parameters.values()) { logger.debug( "Checking parameter: {} Shape: {}", parameter.getName(), parameter.getArray().getShape()); checkNDArrayValues(parameter.getArray(), logger, "weight"); if (parameter.requiresGradient() && checkGradient) { logger.debug("Checking gradient of: {}", parameter.getName()); checkNDArrayValues(parameter.getArray().getGradient(), logger, "grad"); } } } /** * Utility function to help summarize the values in an {@link NDArray}. * * @param array the {@link NDArray} to be summarized * @param logger the logger to log the result * @param prefix the prefix or name to be displayed */ public static void checkNDArrayValues(NDArray array, Logger logger, String prefix) { if (array.isNaN().any().getBoolean()) { logger.warn("There are NANs in value:"); for (int i = 0; i < array.size(0); i++) { logger.warn("{}", array.get(i)); } } logger.debug("{} sum: {}", prefix, array.sum().getFloat()); logger.debug("{} mean: {}", prefix, array.mean().getFloat()); logger.debug("{} max: {}", prefix, array.max().getFloat()); logger.debug("{} min: {}", prefix, array.min().getFloat()); logger.debug("{} shape: {}", prefix, array.getShape().toString()); } /** * Utility function to get Engine specific cache directory. * * @param engine the engine name * @return DJL engine cache directory */ public static Path getEngineCacheDir(String engine) { return getEngineCacheDir().resolve(engine); } /** * Utility function to get Engine cache directory. * * @return DJL engine cache directory */ public static Path getEngineCacheDir() { String cacheDir = getEnvOrSystemProperty("ENGINE_CACHE_DIR"); if (cacheDir == null || cacheDir.isEmpty()) { return getCacheDir(); } return Paths.get(cacheDir); } /** * Utility function to get DJL cache directory. * * @return DJL cache directory */ public static Path getCacheDir() { String cacheDir = getEnvOrSystemProperty("DJL_CACHE_DIR"); if (cacheDir == null || cacheDir.isEmpty()) { Path dir = Paths.get(System.getProperty("user.home")); if (!Files.isWritable(dir)) { dir = Paths.get(System.getProperty("java.io.tmpdir")); } return dir.resolve(".djl.ai"); } return Paths.get(cacheDir); } /** * Returns if offline mode is enabled. * * @return true if offline mode is enabled */ public static boolean isOfflineMode() { String mode = getenv("DJL_OFFLINE", System.getProperty("ai.djl.offline")); if (mode != null) { return Boolean.parseBoolean(mode); } // backward compatible return Boolean.getBoolean("offline"); } /** * Returns nested model directory if the directory contains only one subdirectory. * * @param modelDir the model directory * @return subdirectory if the model directory only contains one subdirectory */ public static Path getNestedModelDir(Path modelDir) { if (Files.isDirectory(modelDir)) { try (Stream<Path> stream = Files.list(modelDir)) { // handle actual model directory is subdirectory case List<Path> files = stream.filter(p -> !p.getFileName().toString().startsWith(".")) .collect(Collectors.toList()); if (files.size() == 1 && Files.isDirectory(files.get(0))) { return files.get(0); } } catch (IOException e) { throw new AssertionError("Failed to list files: " + modelDir, e); } } return modelDir.toAbsolutePath(); } /** * Gets the value of the specified environment variable or system property. * * @param name the name of the environment variable * @return the string value of the variable or system property */ public static String getEnvOrSystemProperty(String name) { return getEnvOrSystemProperty(name, null); } /** * Gets the value of the specified environment variable or system property. * * @param name the name of the environment variable * @param def a default value * @return the string value of the variable or system property */ public static String getEnvOrSystemProperty(String name, String def) { try { String env = System.getenv(name); if (env != null) { return env; } } catch (SecurityException e) { logger.warn("Security manager doesn't allow access to the environment variable"); } String prop = System.getProperty(name); if (prop != null) { return prop; } return def; } /** * Gets the value of the specified environment variable. * * @param name the name of the environment variable * @param def a default value * @return the string value of the variable, or {@code def} if the variable is not defined in * the system environment or security manager doesn't allow access to the environment * variable */ public static String getenv(String name, String def) { try { String val = System.getenv(name); return val == null ? def : val; } catch (SecurityException e) { logger.warn("Security manager doesn't allow access to the environment variable"); } return def; } /** * Gets the value of the specified environment variable. * * @param name the name of the environment variable * @return the string value of the variable, or {@code null} if the variable is not defined in * the system environment or security manager doesn't allow access to the environment * variable */ public static String getenv(String name) { return getenv(name, null); } /** * Returns an unmodifiable string map view of the current system environment. * * @return the environment as a map of variable names to values */ public static Map<String, String> getenv() { try { return System.getenv(); } catch (SecurityException e) { logger.warn("Security manager doesn't allow access to the environment variable"); } return Collections.emptyMap(); } /** * Opens a connection to this URL and returns an InputStream for reading from that connection. * * @param url the url to open * @return an input stream for reading from the URL connection. * @throws IOException if an I/O exception occurs */ public static InputStream openUrl(String url) throws IOException { return openUrl(new URL(url)); } /** * Opens a connection to this URL and returns an InputStream for reading from that connection. * * @param url the url to open * @return an input stream for reading from the URL connection. * @throws IOException if an I/O exception occurs */ public static InputStream openUrl(URL url) throws IOException { return openUrl(url, Collections.emptyMap()); } /** * Opens a connection to this URL and returns an InputStream for reading from that connection. * * @param url the url to open * @param headers the HTTP headers * @return an input stream for reading from the URL connection. * @throws IOException if an I/O exception occurs */ public static InputStream openUrl(URL url, Map<String, String> headers) throws IOException { String protocol = url.getProtocol(); if ("http".equalsIgnoreCase(protocol) || "https".equalsIgnoreCase(protocol)) { if (isOfflineMode()) { throw new IOException("Offline mode is enabled."); } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); for (Map.Entry<String, String> entry : headers.entrySet()) { conn.addRequestProperty(entry.getKey(), entry.getValue()); } return conn.getInputStream(); } return new BufferedInputStream(url.openStream()); } /** * Returns a hash of a string. * * @param input the input string * @return a 20 bytes hash of the input stream in hex format */ public static String hash(String input) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] buf = md.digest(input.getBytes(StandardCharsets.UTF_8)); return Hex.toHexString(buf, 0, 20); } catch (NoSuchAlgorithmException e) { throw new AssertionError("SHA256 algorithm not found.", e); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/util/ZipUtils.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.util; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; /** Utilities for working with zip files. */ public final class ZipUtils { private ZipUtils() {} /** * Unzips an input stream to a given path. * * @param is the input stream to unzip * @param dest the path to store the unzipped files * @throws IOException for failures to unzip the input stream and create files in the dest path */ public static void unzip(InputStream is, Path dest) throws IOException { ValidationInputStream vis = new ValidationInputStream(is); ZipInputStream zis = new ZipInputStream(vis); ZipEntry entry; Set<String> set = new HashSet<>(); while ((entry = zis.getNextEntry()) != null) { String entryName = entry.getName(); validateArchiveEntry(entry.getName(), dest); set.add(entryName); Path file = dest.resolve(entryName).toAbsolutePath(); if (entry.isDirectory()) { Files.createDirectories(file); } else { Path parentFile = file.getParent(); if (parentFile == null) { throw new AssertionError("Parent path should never be null: " + file); } Files.createDirectories(parentFile); Files.copy(zis, file, StandardCopyOption.REPLACE_EXISTING); } } try { // Validate local files against central directory for CVE-2007-4546 and CVE-2014-2720 vis.validate(set); } catch (IOException e) { Utils.deleteQuietly(dest); throw e; } } /** * Zips an input directory to a given file. * * @param src the input directory to zip * @param dest the path to store the zipped files * @param includeFolderName if include the source directory name in the zip entry * @throws IOException for failures to zip the input directory */ public static void zip(Path src, Path dest, boolean includeFolderName) throws IOException { try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(dest)))) { Path root = includeFolderName ? src.getParent() : src; if (root == null) { throw new AssertionError("Parent folder should not be null."); } addToZip(root, src, zos); } } private static void addToZip(Path root, Path file, ZipOutputStream zos) throws IOException { Path relative = root.relativize(file); String name = relative.toString(); if (Files.isDirectory(file)) { if (!name.isEmpty()) { ZipEntry entry = new ZipEntry(name + '/'); zos.putNextEntry(entry); } File[] files = file.toFile().listFiles(); if (files != null) { for (File f : files) { addToZip(root, f.toPath(), zos); } } } else if (Files.isRegularFile(file)) { if (name.isEmpty()) { name = file.toFile().getName(); } ZipEntry entry = new ZipEntry(name); zos.putNextEntry(entry); Files.copy(file, zos); } } static void validateArchiveEntry(String name, Path destination) throws IOException { if (name.contains("..")) { throw new IOException("Invalid archive entry, contains traversal elements: " + name); } Path expectedOutputPath = destination.resolve(name).toAbsolutePath().normalize(); if (!expectedOutputPath.startsWith(destination.normalize())) { throw new IOException( "Bad archive entry " + name + ". Attempted write outside destination " + destination); } } private static final class ValidationInputStream extends FilterInputStream { private static final int ZIP64_LOCSIG = 0x07064b50; // "PK\006\007" private static final int ZIP64_ENDSIG = 0x06064b50; // "PK\006\006" private static final int ENDSIG = 0x06054b50; // "PK\005\006" private static final int LOCSIG = 0x04034b50; // "PK\003\004" private static final int CENSIG = 0x02014b50; // "PK\001\002" private static final int ZIP64_LOCHDR = 20; // ZIP64 end loc header size private static final int ENDHDR = 22; // END header size private static final int CENHDR = 46; // CEN header size private static final int USE_UTF8 = 0x800; private byte[] buf; private boolean seenCen; private long filePosition; ValidationInputStream(InputStream in) { super(in); buf = new byte[512]; } /** {@inheritDoc} */ @Override public int read() throws IOException { int read = super.read(); if (read >= 0 && !seenCen) { System.arraycopy(buf, 1, buf, 0, buf.length - 1); buf[buf.length - 1] = (byte) read; } return read; } /** {@inheritDoc} */ @Override public int read(byte[] b, int off, int len) throws IOException { int read = super.read(b, off, len); if (read > 0 && !seenCen) { if (read < buf.length) { System.arraycopy(buf, read, buf, 0, buf.length - read); System.arraycopy(b, off, buf, buf.length - read, read); } else { System.arraycopy(b, off + read - buf.length, buf, 0, buf.length); } filePosition += read; } return read; } void validate(Set<String> set) throws IOException { seenCen = true; if (filePosition > 0) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); if (filePosition < buf.length) { bos.write(buf, (int) (buf.length - filePosition), (int) filePosition); filePosition = 0; } else { bos.write(buf); filePosition -= buf.length; } byte[] tmp = new byte[512]; int read; while ((read = read(tmp)) != -1) { bos.write(tmp, 0, read); } bos.close(); byte[] header = bos.toByteArray(); List<String> entries = initCEN(header); for (String name : entries) { if (!set.remove(name)) { throw new IOException("Malicious zip file, missing file: " + name); } } } if (!set.isEmpty()) { throw new IOException("Malicious zip file, found hidden " + set.size() + " files."); } } private End findEND(ByteBuffer bb) throws IOException { int remaining = bb.remaining(); if (bb.remaining() == 0) { throw new IOException("Zip file is empty"); } End end = new End(); // Now scan the block backwards for END header signature for (int i = remaining - ENDHDR; i >= 0; --i) { if (bb.getInt(i) == ENDSIG) { // Found ENDSIG header end.endpos = i; end.cenlen = bb.getInt(i + 12); end.cenoff = bb.getInt(i + 16); int comlen = bb.getShort(i + 20); if (end.endpos + ENDHDR + comlen != remaining) { // ENDSIG matched, however the size of file comment in it does // not match the real size. One "common" cause for this problem // is some "extra" bytes are padded at the end of the zipfile. // Let's do some extra verification, we don't care about the // performance in this situation. int cenpos = end.endpos - end.cenlen; int locpos = Math.toIntExact(cenpos - end.cenoff); if (cenpos < 0 || locpos < 0 || bb.getInt(cenpos) != CENSIG || bb.getInt(locpos) != LOCSIG) { continue; } } int cenpos = end.endpos - ZIP64_LOCHDR; if (cenpos < 0 || bb.getInt(cenpos) != ZIP64_LOCSIG) { return end; } long end64pos = bb.getLong(cenpos + 8); int relativePos = Math.toIntExact(end64pos - filePosition); if (relativePos < 0 || bb.getInt(relativePos) != ZIP64_ENDSIG) { return end; } // end64 candidate found, int cenlen64 = Math.toIntExact(bb.getLong(relativePos + 40)); long cenoff64 = bb.getLong(relativePos + 48); // double-check if (cenlen64 != end.cenlen && end.cenlen > 0 || cenoff64 != end.cenoff && end.cenoff > 0) { return end; } // to use the end64 values end.cenlen = cenlen64; end.cenoff = cenoff64; end.endpos = relativePos; return end; } } throw new IOException("Zip END header not found"); } private List<String> initCEN(byte[] header) throws IOException { ByteBuffer bb = ByteBuffer.wrap(header); bb.order(ByteOrder.LITTLE_ENDIAN); End end = findEND(bb); if (end.endpos == 0) { return Collections.emptyList(); } List<String> entries = new ArrayList<>(); int cenpos = end.endpos - end.cenlen; // position of CEN table int pos = 0; while (pos + CENHDR <= end.cenlen) { if (bb.getInt(cenpos + pos) != CENSIG) { throw new IOException("invalid CEN header (bad signature)"); } int nlen = bb.getShort(cenpos + pos + 28); int elen = bb.getShort(cenpos + pos + 30); int clen = bb.getShort(cenpos + pos + 32); int flag = bb.getShort(cenpos + pos + 8); if ((flag & 1) != 0) { throw new IOException("invalid CEN header (encrypted entry)"); } Charset charset; if ((flag & USE_UTF8) != 0) { charset = StandardCharsets.UTF_8; } else { charset = StandardCharsets.US_ASCII; } entries.add(new String(header, cenpos + pos + CENHDR, nlen, charset)); // skip ext and comment pos += (CENHDR + nlen + elen + clen); } if (pos != end.cenlen) { throw new IOException("invalid CEN header (bad header size)"); } return entries; } private static final class End { int cenlen; // 4 bytes long cenoff; // 4 bytes int endpos; // 4 bytes } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl
java-sources/ai/djl/api/0.34.0/ai/djl/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 utilities used throughout the API. */ package ai.djl.util;
0
java-sources/ai/djl/api/0.34.0/ai/djl/util
java-sources/ai/djl/api/0.34.0/ai/djl/util/cuda/CudaLibrary.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.util.cuda; import com.sun.jna.Library; /** * {@code CudaLibrary} contains methods mapping to CUDA runtime API. * * <p>see: https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__DEVICE.html */ public interface CudaLibrary extends Library { int INITIALIZATION_ERROR = 3; int INSUFFICIENT_DRIVER = 35; int ERROR_NO_DEVICE = 100; int ERROR_NOT_PERMITTED = 800; /** * Gets the number of devices with compute capability greater or equal to 1.0 that are available * for execution. * * @param deviceCount the returned device count * @return CUDA runtime API error code */ int cudaGetDeviceCount(int[] deviceCount); /** * Returns the version number of the installed CUDA Runtime. * * @param runtimeVersion output buffer of runtime version number * @return CUDA runtime API error code */ int cudaRuntimeGetVersion(int[] runtimeVersion); /** * Gets the integer value of the attribute {@code attr} on device. * * @param pi the returned device attribute value * @param attr the device attribute to query * @param device the GPU device to retrieve * @return CUDA runtime API error code */ int cudaDeviceGetAttribute(int[] pi, int attr, int device); /** * Gets free and total device memory. * * @param free the returned free memory in bytes * @param total the returned total memory in bytes * @return CUDA runtime API error code */ int cudaMemGetInfo(long[] free, long[] total); /** * Set device to be used for GPU executions. * * @param device the GPU device to retrieve * @return CUDA runtime API error code */ int cudaSetDevice(int device); /** * Gets which device is currently being used. * * @param device the returned current device * @return CUDA runtime API error code */ int cudaGetDevice(int[] device); /** * Returns the description string for an error code. * * @param code the CUDA error code to convert to string * @return the description string for an error code */ String cudaGetErrorString(int code); }
0
java-sources/ai/djl/api/0.34.0/ai/djl/util
java-sources/ai/djl/api/0.34.0/ai/djl/util/cuda/CudaUtils.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.util.cuda; import ai.djl.Device; import ai.djl.engine.EngineException; import ai.djl.util.Utils; import com.sun.jna.Native; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.management.MemoryUsage; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; /** A class containing CUDA utility methods. */ public final class CudaUtils { private static final Logger logger = LoggerFactory.getLogger(CudaUtils.class); private static final CudaLibrary LIB = loadLibrary(); private static String[] gpuInfo; private static boolean logging = true; private CudaUtils() {} /** * Gets whether CUDA runtime library is in the system. * * @return {@code true} if CUDA runtime library is in the system */ public static boolean hasCuda() { return getGpuCount() > 0; } /** * Returns the number of GPUs available in the system. * * @return the number of GPUs available in the system */ @SuppressWarnings("PMD.NonThreadSafeSingleton") public static int getGpuCount() { if (Boolean.getBoolean("ai.djl.util.cuda.fork")) { if (gpuInfo == null) { gpuInfo = execute(-1); // NOPMD } try { return Integer.parseInt(gpuInfo[0]); } catch (NumberFormatException e) { logger.warn("Unexpected output: {}", gpuInfo[0], e); return 0; } } if (LIB == null) { return 0; } int[] count = new int[1]; int result = LIB.cudaGetDeviceCount(count); switch (result) { case 0: return count[0]; case CudaLibrary.ERROR_NO_DEVICE: if (logging) { logger.debug( "No GPU device found: {} ({})", LIB.cudaGetErrorString(result), result); } return 0; case CudaLibrary.INITIALIZATION_ERROR: case CudaLibrary.INSUFFICIENT_DRIVER: case CudaLibrary.ERROR_NOT_PERMITTED: default: if (logging) { logger.warn( "Failed to detect GPU count: {} ({})", LIB.cudaGetErrorString(result), result); } return 0; } } /** * Returns the version of CUDA runtime. * * @return the version of CUDA runtime */ @SuppressWarnings("PMD.NonThreadSafeSingleton") public static int getCudaVersion() { if (Boolean.getBoolean("ai.djl.util.cuda.fork")) { if (gpuInfo == null) { gpuInfo = execute(-1); } int version = Integer.parseInt(gpuInfo[1]); if (version == -1) { throw new IllegalArgumentException("No cuda device found."); } return version; } if (LIB == null) { throw new IllegalStateException("No cuda library is loaded."); } int[] version = new int[1]; int result = LIB.cudaRuntimeGetVersion(version); checkCall(result); return version[0]; } /** * Returns the version string of CUDA runtime. * * @return the version string of CUDA runtime */ public static String getCudaVersionString() { int version = getCudaVersion(); int major = version / 1000; int minor = (version / 10) % 10; return String.format(Locale.ROOT, "%02d", major) + minor; } /** * Returns the CUDA compute capability. * * @param device the GPU {@link Device} to retrieve * @return the CUDA compute capability */ public static String getComputeCapability(int device) { if (Boolean.getBoolean("ai.djl.util.cuda.fork")) { if (gpuInfo == null) { // NOPMD gpuInfo = execute(-1); } if (device >= gpuInfo.length - 2) { throw new IllegalArgumentException("Invalid device: " + device); } return gpuInfo[device + 2]; } if (LIB == null) { throw new IllegalStateException("No cuda library is loaded."); } int attrComputeCapabilityMajor = 75; int attrComputeCapabilityMinor = 76; int[] major = new int[1]; int[] minor = new int[1]; checkCall(LIB.cudaDeviceGetAttribute(major, attrComputeCapabilityMajor, device)); checkCall(LIB.cudaDeviceGetAttribute(minor, attrComputeCapabilityMinor, device)); return String.valueOf(major[0]) + minor[0]; } /** * Returns the {@link MemoryUsage} of the specified GPU device. * * @param device the GPU {@link Device} to retrieve * @return the {@link MemoryUsage} of the specified GPU device * @throws IllegalArgumentException if {@link Device} is not GPU device or does not exist */ public static MemoryUsage getGpuMemory(Device device) { if (!device.isGpu()) { throw new IllegalArgumentException("Only GPU device is allowed."); } if (Boolean.getBoolean("ai.djl.util.cuda.fork")) { String[] ret = execute(device.getDeviceId()); if (ret.length != 3) { throw new IllegalArgumentException(ret[0]); } long total = Long.parseLong(ret[1]); long used = Long.parseLong(ret[2]); return new MemoryUsage(-1, used, used, total); } if (LIB == null) { throw new IllegalStateException("No GPU device detected."); } int[] currentDevice = new int[1]; checkCall(LIB.cudaGetDevice(currentDevice)); checkCall(LIB.cudaSetDevice(device.getDeviceId())); long[] free = new long[1]; long[] total = new long[1]; checkCall(LIB.cudaMemGetInfo(free, total)); checkCall(LIB.cudaSetDevice(currentDevice[0])); long committed = total[0] - free[0]; return new MemoryUsage(-1, committed, committed, total[0]); } /** * The main entrypoint to get CUDA information with command line. * * @param args the command line arguments. */ @SuppressWarnings("PMD.SystemPrintln") public static void main(String[] args) { logging = false; int gpuCount = getGpuCount(); if (args.length == 0) { if (gpuCount <= 0) { System.out.println("0,-1"); return; } int cudaVersion = getCudaVersion(); StringBuilder sb = new StringBuilder(); sb.append(gpuCount).append(',').append(cudaVersion); for (int i = 0; i < gpuCount; ++i) { sb.append(',').append(getComputeCapability(i)); } System.out.println(sb); return; } try { int deviceId = Integer.parseInt(args[0]); if (deviceId < 0 || deviceId >= gpuCount) { System.out.println("Invalid device: " + deviceId); return; } MemoryUsage mem = getGpuMemory(Device.gpu(deviceId)); String cc = getComputeCapability(deviceId); System.out.println(cc + ',' + mem.getMax() + ',' + mem.getUsed()); } catch (NumberFormatException e) { System.out.println("Invalid device: " + args[0]); } } private static CudaLibrary loadLibrary() { try { if (Boolean.getBoolean("ai.djl.util.cuda.fork")) { return null; } if (System.getProperty("os.name").startsWith("Win")) { String path = Utils.getenv("PATH"); if (path == null) { return null; } Pattern p = Pattern.compile("cudart64_\\d+\\.dll"); String cudaPath = Utils.getenv("CUDA_PATH"); String[] searchPath; if (cudaPath == null) { searchPath = path.split(";"); } else { searchPath = (cudaPath + "\\bin\\;" + path).split(";"); } for (String item : searchPath) { File dir = new File(item); File[] files = dir.listFiles(n -> p.matcher(n.getName()).matches()); if (files != null && files.length > 0) { String fileName = files[0].getName(); String cudaRt = fileName.substring(0, fileName.length() - 4); if (logging) { logger.debug("Found cudart: {}", files[0].getAbsolutePath()); } return Native.load(cudaRt, CudaLibrary.class); } } if (logging) { logger.debug("No cudart library found in path."); } return null; } return Native.load("cudart", CudaLibrary.class); } catch (UnsatisfiedLinkError e) { if (logging) { logger.debug("cudart library not found."); logger.trace("", e); } } catch (LinkageError e) { if (logging) { logger.warn("You have a conflict version of JNA in the classpath."); logger.debug("", e); } } catch (SecurityException e) { if (logging) { logger.warn("Access denied during loading cudart library."); logger.trace("", e); } } return null; } private static String[] execute(int deviceId) { try { String javaHome = System.getProperty("java.home"); String classPath = System.getProperty("java.class.path"); String os = System.getProperty("os.name"); List<String> cmd = new ArrayList<>(4); if (os.startsWith("Win")) { cmd.add(javaHome + "\\bin\\java.exe"); } else { cmd.add(javaHome + "/bin/java"); } cmd.add("-cp"); cmd.add(classPath); cmd.add("ai.djl.util.cuda.CudaUtils"); if (deviceId >= 0) { cmd.add(String.valueOf(deviceId)); } Process ps = new ProcessBuilder(cmd).redirectErrorStream(true).start(); try (InputStream is = ps.getInputStream()) { String line = Utils.toString(is).trim(); return line.split(","); } } catch (IOException e) { throw new IllegalArgumentException("Failed get GPU information", e); } } private static void checkCall(int ret) { if (LIB == null) { throw new IllegalStateException("No cuda library is loaded."); } if (ret != 0) { throw new EngineException( "CUDA API call failed: " + LIB.cudaGetErrorString(ret) + " (" + ret + ')'); } } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/util
java-sources/ai/djl/api/0.34.0/ai/djl/util/cuda/package-info.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ /** Contains utilities to access CUDA driver. */ package ai.djl.util.cuda;
0
java-sources/ai/djl/api/0.34.0/ai/djl/util
java-sources/ai/djl/api/0.34.0/ai/djl/util/passthrough/PassthroughNDArray.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.util.passthrough; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDArrayAdapter; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import java.nio.ByteBuffer; /** * An {@link NDArray} that stores an arbitrary Java object. * * <p>This class is mainly for use in extensions and hybrid engines. Despite it's name, it will * often not contain actual {@link NDArray}s but just any object necessary to conform to the DJL * predictor API. */ public class PassthroughNDArray extends NDArrayAdapter { private Object object; /** * Constructs a {@link PassthroughNDArray} storing an object. * * @param object the object to store */ public PassthroughNDArray(Object object) { this(PassthroughNDManager.INSTANCE, object); } /** * Constructs a {@link PassthroughNDArray} storing an object. * * @param manager {@link NDManager} of the array * @param object the object to store */ public PassthroughNDArray(NDManager manager, Object object) { this(manager, object, null, null); } /** * Constructs a {@link PassthroughNDArray} storing an object. * * @param manager {@link NDManager} of the array * @param object the object to store * @param shape the {@link Shape} of the {@link NDArray} * @param dataType the {@link DataType} of the {@link NDArray} */ public PassthroughNDArray(NDManager manager, Object object, Shape shape, DataType dataType) { super(manager, null, shape, dataType, null); this.object = object; } /** * Returns the object stored. * * @return the object stored */ public Object getObject() { return object; } /** {@inheritDoc} */ @Override public ByteBuffer toByteBuffer(boolean tryDirect) { if (object instanceof ByteBuffer) { return (ByteBuffer) object; } throw new UnsupportedOperationException("Operation not supported for PassthroughNDArray"); } /** {@inheritDoc} */ @Override public void intern(NDArray replaced) { throw new UnsupportedOperationException("Operation not supported for PassthroughNDArray"); } /** {@inheritDoc} */ @Override public void detach() {} }
0
java-sources/ai/djl/api/0.34.0/ai/djl/util
java-sources/ai/djl/api/0.34.0/ai/djl/util/passthrough/PassthroughNDManager.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.util.passthrough; import ai.djl.Device; import ai.djl.engine.Engine; import ai.djl.ndarray.BaseNDManager; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.NDResource; import ai.djl.ndarray.types.DataType; import ai.djl.ndarray.types.Shape; import ai.djl.util.PairList; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.Collections; import java.util.List; /** An {@link NDManager} that does nothing, for use in extensions and hybrid engines. */ public final class PassthroughNDManager implements NDManager { private static final String UNSUPPORTED = "Not supported by PassthroughNDManager"; public static final PassthroughNDManager INSTANCE = new PassthroughNDManager(); private Engine engine; private Device device; /** * Constructs a new {@code PassthroughNDManager} instance. * * @param engine the {@link Engine} associated with this manager * @param device the default {@link Device} */ public PassthroughNDManager(Engine engine, Device device) { this.engine = engine; this.device = device == null ? engine.defaultDevice() : device; } private PassthroughNDManager() { device = Device.cpu(); } /** {@inheritDoc} */ @Override public Device defaultDevice() { if (engine != null) { return engine.defaultDevice(); } return device; } /** {@inheritDoc} */ @Override public ByteBuffer allocateDirect(int capacity) { return ByteBuffer.allocateDirect(capacity).order(ByteOrder.nativeOrder()); } /** {@inheritDoc} */ @Override public NDArray from(NDArray array) { if (array == null || array instanceof PassthroughNDArray) { return array; } return create(array.toByteBuffer(), array.getShape(), array.getDataType()); } /** * Creates a new {@link PassthroughNDArray}. * * @param object the object to store * @return a new {@code PassthroughNDArray} */ public PassthroughNDArray create(Object object) { return new PassthroughNDArray(this, object); } /** {@inheritDoc} */ @Override public NDArray create(Buffer data, Shape shape, DataType dataType) { int size = Math.toIntExact(shape.size()); BaseNDManager.validateBuffer(data, dataType, size); if (data instanceof ByteBuffer) { return new PassthroughNDArray(this, data, shape, dataType); } ByteBuffer bb = ByteBuffer.allocate(size * dataType.getNumOfBytes()); bb.order(ByteOrder.nativeOrder()); BaseNDManager.copyBuffer(data, bb); return new PassthroughNDArray(this, bb, shape, dataType); } /** {@inheritDoc} */ @Override public NDArray create(String[] data, Charset charset, Shape shape) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray create(Shape shape, DataType dataType) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray createCSR(Buffer data, long[] indptr, long[] indices, Shape shape) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray createRowSparse(Buffer data, Shape dataShape, long[] indices, Shape shape) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray createCoo(Buffer data, long[][] indices, Shape shape) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDList load(Path path) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public void setName(String name) {} /** {@inheritDoc} */ @Override public String getName() { return "PassthroughNDManager"; } /** {@inheritDoc} */ @Override public NDArray full(Shape shape, float value, DataType dataType) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray arange(float start, float stop, float step, DataType dataType) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray eye(int rows, int cols, int k, DataType dataType) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray linspace(float start, float stop, int num, boolean endpoint) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray randomInteger(long low, long high, Shape shape, DataType dataType) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@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(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray randomNormal(float loc, float scale, Shape shape, DataType dataType) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray truncatedNormal(float loc, float scale, Shape shape, DataType dataType) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray randomMultinomial(int n, NDArray pValues) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray randomMultinomial(int n, NDArray pValues, Shape shape) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray sampleNormal(NDArray mu, NDArray sigma) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray sampleNormal(NDArray mu, NDArray sigma, Shape shape) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray samplePoisson(NDArray lam) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray samplePoisson(NDArray lam, Shape shape) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray sampleGamma(NDArray alpha, NDArray beta) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDArray sampleGamma(NDArray alpha, NDArray beta, Shape shape) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public boolean isOpen() { return true; } /** {@inheritDoc} */ @Override public void cap() {} /** {@inheritDoc} */ @Override public NDManager getParentManager() { return this; } /** {@inheritDoc} */ @Override public NDManager newSubManager() { return this; } /** {@inheritDoc} */ @Override public NDManager newSubManager(Device device) { return new PassthroughNDManager(engine, device); } /** {@inheritDoc} */ @Override public Device getDevice() { return device; } /** {@inheritDoc} */ @Override public List<NDArray> getManagedArrays() { return Collections.emptyList(); } /** {@inheritDoc} */ @Override public void attachInternal(String resourceId, AutoCloseable... resource) {} /** {@inheritDoc} */ @Override public void attachUncappedInternal(String resourceId, AutoCloseable resource) {} /** {@inheritDoc} */ @Override public void tempAttachInternal( NDManager originalManager, String resourceId, NDResource resource) {} /** {@inheritDoc} */ @Override public void detachInternal(String resourceId) {} /** {@inheritDoc} */ @Override public void invoke( String operation, NDArray[] src, NDArray[] dest, PairList<String, ?> params) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public NDList invoke(String operation, NDList src, PairList<String, ?> params) { throw new UnsupportedOperationException(UNSUPPORTED); } /** {@inheritDoc} */ @Override public Engine getEngine() { return engine; } /** {@inheritDoc} */ @Override public void close() {} }
0
java-sources/ai/djl/api/0.34.0/ai/djl/util
java-sources/ai/djl/api/0.34.0/ai/djl/util/passthrough/PassthroughTranslator.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.util.passthrough; import ai.djl.ndarray.NDList; import ai.djl.translate.NoBatchifyTranslator; import ai.djl.translate.TranslatorContext; /** * A translator that stores and removes data from a {@link PassthroughNDArray}. * * @param <I> translator input type * @param <O> translator output type */ public class PassthroughTranslator<I, O> implements NoBatchifyTranslator<I, O> { /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, I input) throws Exception { return new NDList(new PassthroughNDArray(input)); } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public O processOutput(TranslatorContext ctx, NDList list) { PassthroughNDArray wrapper = (PassthroughNDArray) list.singletonOrThrow(); return (O) wrapper.getObject(); } }
0
java-sources/ai/djl/api/0.34.0/ai/djl/util
java-sources/ai/djl/api/0.34.0/ai/djl/util/passthrough/package-info.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. */ /** Contains passthrough DJL classes for use in extensions and hybrid engines. */ package ai.djl.util.passthrough;
0
java-sources/ai/djl/audio/audio/0.34.0/ai/djl
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio/FFmpegAudioFactory.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.audio; import ai.djl.modality.audio.Audio; import ai.djl.modality.audio.AudioFactory; import org.bytedeco.javacv.FFmpegFrameGrabber; import org.bytedeco.javacv.Frame; import org.bytedeco.javacv.FrameGrabber; import java.io.IOException; import java.io.InputStream; import java.nio.Buffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; /** * {@code FFmpegAudioFactory} is a high performance implementation of {@link AudioFactory} using * FFmpeg. */ public class FFmpegAudioFactory extends AudioFactory { /** {@inheritDoc} */ @Override public Audio fromFile(Path path) throws IOException { try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(path.toFile())) { applyConfig(grabber); grabber.start(); float[] floats = grab(grabber); return new Audio(floats, grabber.getSampleRate(), grabber.getAudioChannels()); } catch (FrameGrabber.Exception e) { throw new IOException("Unsupported Audio file", e); } } /** {@inheritDoc} */ @Override public Audio fromInputStream(InputStream is) throws IOException { try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(is)) { applyConfig(grabber); grabber.start(); float[] floats = grab(grabber); return new Audio(floats, grabber.getSampleRate(), grabber.getAudioChannels()); } catch (FrameGrabber.Exception e) { throw new IOException("Unsupported Audio file", e); } } private void applyConfig(FFmpegFrameGrabber grabber) { if (channels > 0) { grabber.setAudioChannels(channels); } if (sampleRate > 0) { grabber.setSampleRate(sampleRate); } if (sampleFormat > 0) { grabber.setSampleFormat(sampleFormat); } } /** * Grabs frames from the audio using {@link FFmpegFrameGrabber}. * * <p>The default channel to grab is 0. * * @param grabber the {@link FFmpegFrameGrabber}. * @return the float array read from the audio. * @throws FFmpegFrameGrabber.Exception if error occurs */ private float[] grab(FFmpegFrameGrabber grabber) throws FFmpegFrameGrabber.Exception { List<Float> list = new ArrayList<>(); Frame frame; while ((frame = grabber.grabFrame(true, false, true, false, false)) != null) { Buffer buf = frame.samples[0]; if (buf instanceof ShortBuffer) { ShortBuffer buffer = (ShortBuffer) buf; for (int i = 0; i < buffer.limit(); i++) { list.add(buffer.get() / 32768.0f); } } else if (buf instanceof IntBuffer) { IntBuffer buffer = (IntBuffer) buf; for (int i = 0; i < buffer.limit(); i++) { list.add(buffer.get() / 2147483648.0f); } } else { throw new UnsupportedOperationException( "Unsupported sample format: " + sampleFormat); } } float[] ret = new float[list.size()]; for (int i = 0; i < list.size(); i++) { ret[i] = list.get(i); } return ret; } }
0
java-sources/ai/djl/audio/audio/0.34.0/ai/djl
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio/package-info.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. */ /** Contains audio utils and datasets for djl. */ package ai.djl.audio;
0
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio/dataset/AudioData.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.audio.dataset; import ai.djl.audio.processor.AudioNormalizer; import ai.djl.audio.processor.AudioProcessor; import ai.djl.audio.processor.LinearSpecgram; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; import org.bytedeco.javacv.FFmpegFrameGrabber; import org.bytedeco.javacv.Frame; import org.bytedeco.javacv.FrameGrabber; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.Buffer; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * {@link AudioData} is a utility for managing audio data within a {@link * ai.djl.training.dataset.Dataset}. It contains some basic information of an audio file and provide * some method to preprocess the original audio file. Since storing all the data into the memory is * impossible, this class will only store the path of the original audio data. * * <p>This class provides a list of {@link AudioProcessor} for user to featurize the data. * * <p>See {@link SpeechRecognitionDataset} for an example. */ public class AudioData { private static final Logger logger = LoggerFactory.getLogger(AudioData.class); private int sampleRate; private int audioChannels; private List<AudioProcessor> processorList; private List<String> audioPaths; /** * Constructs a new {@link AudioData}. * * @param configuration the configuration for the {@link AudioData}. */ public AudioData(Configuration configuration) { this.sampleRate = configuration.sampleRate; this.processorList = configuration.processorList; } /** * Returns a good default {@link Configuration} to use for the constructor with defaults. * * @return a good default {@link Configuration} to use for the constructor with defaults. */ public static Configuration getDefaultConfiguration() { float targetDb = -20f; float strideMs = 10f; float windowsMs = 20f; int sampleRate = 16000; List<AudioProcessor> defaultProcessors = Arrays.asList( new AudioNormalizer(targetDb), new LinearSpecgram(strideMs, windowsMs, sampleRate)); return new Configuration().setProcessorList(defaultProcessors).setSampleRate(sampleRate); } /** * This method is used for decoding the original audio data and converting it to a float array. * * @param path The path of the original audio data. * @return A float array. */ private float[] toFloat(String path) { List<Float> list = new ArrayList<>(); float scale = (float) 1.0 / (float) (1 << (8 * 2) - 1); try (FFmpegFrameGrabber audioGrabber = new FFmpegFrameGrabber(path)) { audioGrabber.start(); audioChannels = audioGrabber.getAudioChannels(); audioGrabber.setSampleRate(sampleRate); Frame frame; while ((frame = audioGrabber.grabFrame()) != null) { Buffer[] buffers = frame.samples; ShortBuffer sb = (ShortBuffer) buffers[0]; for (int i = 0; i < sb.limit(); i++) { list.add(sb.get() * scale); } } } catch (FrameGrabber.Exception e) { logger.error(e.getMessage()); } float[] floatArray = new float[list.size()]; int i = 0; for (Float f : list) { floatArray[i++] = (f != null ? f : Float.NaN); } return floatArray; } /** * This method will use a list of {@link AudioProcessor} as featurizer to process the float * array. * * @param manager the manager for converting the float array to {@link NDArray}. * @param index The index of path of the original audio data. * @return An {@link NDArray} that represent the processed audio data. */ public NDArray getPreprocessedData(NDManager manager, int index) { float[] floatArray = toFloat(audioPaths.get(index)); NDArray samples = manager.create(floatArray); for (AudioProcessor processor : processorList) { samples = processor.extractFeatures(manager, samples); } return samples; } /** * Get the number of channels of an audio file. * * @return The number of channels of an audio file. */ public int getAudioChannels() { return audioChannels; } /** * Get the sample rate used by {@link FFmpegFrameGrabber} when sampling the audio file. * * @return The sample rate used by {@link FFmpegFrameGrabber} when sampling the audio file. */ public int getSampleRate() { return sampleRate; } /** * Set the path list of original audio data. * * @param audioPaths The path list of original audio data. */ public void setAudioPaths(List<String> audioPaths) { this.audioPaths = audioPaths; } /** * Get the original audio path. * * @return The original audio path. */ public List<String> getAudioPaths() { return audioPaths; } /** * Get the total number of audio data in the dataset. * * @return The total number of audio data in the dataset. */ public int getTotalSize() { return audioPaths.size(); } /** The configuration for creating a {@code AudioData} value in a {@code AudioData}. */ public static final class Configuration { private int sampleRate; private List<AudioProcessor> processorList; /** * Set the list of processor which are used for extracting features from audio data. * * @param processorList The list of processor which are used for extracting features from * audio data. * @return this configuration. */ public Configuration setProcessorList(List<AudioProcessor> processorList) { this.processorList = processorList; return this; } /** * Set the sampleRate for {@link FFmpegFrameGrabber} to use. * * @param sampleRate The sampleRate for {@link FFmpegFrameGrabber} to use. * @return this configuration. */ public Configuration setSampleRate(int sampleRate) { this.sampleRate = sampleRate; return this; } /** * Updates this {@link Configuration} with the non-null values from another configuration. * * @param other the other configuration to use to update this * @return this configuration after updating */ public Configuration update(AudioData.Configuration other) { processorList = other.processorList; return this; } } }
0
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio/dataset/Librispeech.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.audio.dataset; import ai.djl.Application; import ai.djl.basicdataset.BasicDatasets; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.repository.Artifact; import ai.djl.repository.MRL; import ai.djl.training.dataset.Dataset; import ai.djl.training.dataset.Record; import ai.djl.translate.TranslateException; import ai.djl.util.Progress; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; /** * LibriSpeech is a corpus of approximately 1000 hours of 16kHz read English speech, prepared by * Vassil Panayotov with the assistance of Daniel Povey. The data is derived from read audiobooks * from the LibriVox project, and has been carefully segmented and aligned. */ public class Librispeech extends SpeechRecognitionDataset { private static final String VERSION = "1.0"; private static final String ARTIFACT_ID = "librispeech"; /** * Creates a new instance of {@link SpeechRecognitionDataset} with the given necessary * configurations. * * @param builder a builder with the necessary configurations */ public Librispeech(Builder builder) { super(builder); this.usage = builder.usage; this.mrl = builder.getMrl(); } /** * Creates a builder to build a {@link Librispeech}. * * @return a new {@link Librispeech.Builder} object */ public static Builder builder() { return new Builder(); } /** * Prepares the dataset for use with tracked progress. * * @param progress the progress tracker * @throws IOException for various exceptions depending on the dataset */ @Override public void prepare(Progress progress) throws IOException, TranslateException { if (prepared) { return; } Artifact artifact = mrl.getDefaultArtifact(); mrl.prepare(artifact, progress); Artifact.Item item; String subPath; switch (usage) { case TRAIN: item = artifact.getFiles().get("train"); subPath = "LibriSpeech/test-clean-100"; break; case TEST: item = artifact.getFiles().get("test"); subPath = "LibriSpeech/test-clean"; break; default: throw new UnsupportedOperationException("Unsupported usage type."); } File mainDir = mrl.getRepository().getFile(item, subPath).toFile(); File[] subDirs = mainDir.listFiles(); if (subDirs == null) { return; } List<String> lineArray = new ArrayList<>(); List<String> audioPaths = new ArrayList<>(); for (File subDir : subDirs) { File[] subSubDirs = subDir.listFiles(); String subDirName = subDir.getName(); if (subSubDirs == null) { return; } for (File subSubDir : subSubDirs) { String subSubDirName = subSubDir.getName(); File transFile = new File( String.format( "%s/%s-%s.trans.txt", subSubDir.getAbsolutePath(), subDirName, subSubDirName)); try (BufferedReader reader = Files.newBufferedReader(transFile.toPath())) { String row; while ((row = reader.readLine()) != null) { if (row.contains(" ")) { String trans = row.substring(row.indexOf(' ') + 1); String label = row.substring(0, row.indexOf(' ')); String audioIndex = label.split("-")[2]; String audioPath = String.format( "%s/%s-%s-%s.flac", subSubDir.getAbsolutePath(), subDirName, subSubDirName, audioIndex); audioPaths.add(audioPath); lineArray.add(trans); } } } } } targetPreprocess(lineArray); sourcePreprocess(audioPaths); prepared = true; } /** {@inheritDoc} */ @Override public Record get(NDManager manager, long index) { NDList data = new NDList(); NDList labels = new NDList(); data.add(sourceAudioData.getPreprocessedData(manager, (int) index)); labels.add(targetTextData.getEmbedding(manager, index)); return new Record(data, labels); } /** {@inheritDoc} */ @Override protected long availableSize() { return sourceAudioData.getTotalSize(); } /** A builder to construct a {@link Librispeech} . */ public static class Builder extends AudioBuilder<Librispeech.Builder> { /** Constructs a new builder. */ public Builder() { repository = BasicDatasets.REPOSITORY; groupId = BasicDatasets.GROUP_ID; artifactId = ARTIFACT_ID; usage = Dataset.Usage.TRAIN; } /** * Builds a new {@link Librispeech} object. * * @return the new {@link Librispeech} object */ public Librispeech build() { return new Librispeech(this); } /** * Builds a new {@link Librispeech} object. * * @return the new {@link Librispeech} object */ MRL getMrl() { return repository.dataset(Application.Audio.ANY, groupId, artifactId, VERSION); } /** {@inheritDoc} */ @Override protected Librispeech.Builder self() { return this; } } }
0
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio/dataset/SpeechRecognitionDataset.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.audio.dataset; import ai.djl.basicdataset.BasicDatasets; import ai.djl.basicdataset.utils.TextData; import ai.djl.engine.Engine; import ai.djl.modality.nlp.Vocabulary; import ai.djl.modality.nlp.embedding.EmbeddingException; import ai.djl.modality.nlp.embedding.TextEmbedding; import ai.djl.modality.nlp.embedding.TrainableWordEmbedding; import ai.djl.ndarray.NDManager; import ai.djl.repository.MRL; import ai.djl.repository.Repository; import ai.djl.training.dataset.RandomAccessDataset; import java.util.List; /** * {@code SpeechRecognitionDataset} is an abstract dataset that can be used for datasets for * Automatic Speech Recognition (ASR) where the source data is {@link AudioData} and the target data * is {@link TextData}. * * <p>For the target data, it will create embeddings for the target data. Embeddings can be either * pre-trained or trained on the go. Pre-trained {@link TextEmbedding} must be set in the {@code * TextDataset.Builder}. If no embeddings are set, the dataset creates {@link * TrainableWordEmbedding} based {@link TrainableWordEmbedding} from the {@link Vocabulary} created * within the dataset. * * <p>For the source data, it will use the {@link ai.djl.audio.processor.AudioProcessor} to * featurize data, if users want to write their own featurizer, they can get the original {@code * NDArray} from {@link AudioData} without using any {@link ai.djl.audio.processor.AudioProcessor}. */ public abstract class SpeechRecognitionDataset extends RandomAccessDataset { protected AudioData sourceAudioData; protected TextData targetTextData; protected NDManager manager; protected Usage usage; protected MRL mrl; protected boolean prepared; /** * Creates a new instance of {@code SpeechRecognitionDataset} with the given necessary * configurations. * * @param builder a builder with the necessary configurations */ public SpeechRecognitionDataset(AudioBuilder<?> builder) { super(builder); sourceAudioData = new AudioData(AudioData.getDefaultConfiguration()); targetTextData = new TextData(TextData.getDefaultConfiguration()); manager = builder.manager; usage = builder.usage; } /** * Store and preprocess target text data. * * @param newTextData list of all unprocessed sentences in the dataset. * @throws EmbeddingException if there is an error while embedding input. */ protected void targetPreprocess(List<String> newTextData) throws EmbeddingException { TextData textData = targetTextData; textData.preprocess( manager, newTextData.subList(0, (int) Math.min(limit, newTextData.size()))); } /** * This method is used to set the audio data path. * * @param audioPathList The path list of all original audio data */ protected void sourcePreprocess(List<String> audioPathList) { sourceAudioData.setAudioPaths(audioPathList); } /** Abstract AudioBuilder that helps build a {@code SpeechRecognitionDataset}. */ public abstract static class AudioBuilder<T extends AudioBuilder<T>> extends BaseBuilder<T> { protected AudioData.Configuration sourceConfiguration; protected TextData.Configuration targetConfiguration; protected NDManager manager; protected Repository repository; protected String groupId; protected Usage usage; protected String artifactId; /** Constructs a new builder. */ AudioBuilder() { repository = BasicDatasets.REPOSITORY; groupId = BasicDatasets.GROUP_ID; usage = Usage.TRAIN; sourceConfiguration = new AudioData.Configuration(); targetConfiguration = new TextData.Configuration(); manager = Engine.getInstance().newBaseManager(); } /** * Sets the {@code AudioData.Configuration} to use for the source text data. * * @param sourceConfiguration the {@link AudioData.Configuration} * @return this builder */ public T setSourceConfiguration(AudioData.Configuration sourceConfiguration) { this.sourceConfiguration = sourceConfiguration; return self(); } /** * Sets the {@code TextData.Configuration} to use for the target text data. * * @param targetConfiguration the {@code TextData.Configuration} * @return this builder */ public T setTargetConfiguration(TextData.Configuration targetConfiguration) { this.targetConfiguration = targetConfiguration; return self(); } /** * Sets the optional manager for the dataset (default follows engine default). * * @param manager the manager * @return this builder */ public T optManager(NDManager manager) { this.manager = manager.newSubManager(); return self(); } /** * Sets the optional usage. * * @param usage the usage * @return this builder */ public T optUsage(Usage usage) { this.usage = usage; return self(); } /** * Sets the optional repository. * * @param repository the repository * @return this builder */ public T optRepository(Repository repository) { this.repository = repository; return self(); } /** * Sets optional groupId. * * @param groupId the groupId} * @return this builder */ public T optGroupId(String groupId) { this.groupId = groupId; return self(); } } }
0
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio/dataset/package-info.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. */ /** Contains useful audio datasets. */ package ai.djl.audio.dataset;
0
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio/processor/AudioNormalizer.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.audio.processor; import ai.djl.audio.util.AudioUtils; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; /** Use the mean and standard values to calculate the normalized values for audio signal. */ public class AudioNormalizer implements AudioProcessor { private static final float MAX_GAIN_DB = 300.0f; private float targetDb; /** * Constructor for {@link AudioNormalizer}. * * @param targetDb target energy in decibels. */ public AudioNormalizer(float targetDb) { this.targetDb = targetDb; } /** {@inheritDoc} */ @Override public NDArray extractFeatures(NDManager manager, NDArray samples) { float gain = targetDb - AudioUtils.rmsDb(samples); gain = Math.min(gain, MAX_GAIN_DB); float factor = (float) Math.pow(10f, gain / 20f); samples = samples.mul(factor); return samples; } }
0
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio/processor/AudioProcessor.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.audio.processor; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; /** This interface is used for extracting features from origin audio samples. */ public interface AudioProcessor { /** * Extracts features by the processor. * * @param manager The manager used for extracting features * @param samples The Audio that needs to be extracting features * @return Target feature */ NDArray extractFeatures(NDManager manager, NDArray samples); }
0
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio/processor/LinearSpecgram.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.audio.processor; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDArrays; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import org.jtransforms.fft.FloatFFT_1D; /** Calculate linear spectrogram by short-time fourier transform. */ public class LinearSpecgram implements AudioProcessor { private static final float EPS = 1e-14f; private float strideMs; private float windowsMs; private float sampleRate; /** * Calculate linear spectrogram by short-time fourier transform. * * @param strideMs Stride size of window * @param windowsMs Window size * @param sampleRate Sample rate of raw data */ public LinearSpecgram(float strideMs, float windowsMs, int sampleRate) { this.strideMs = strideMs; this.windowsMs = windowsMs; this.sampleRate = sampleRate; } /** {@inheritDoc} */ @Override public NDArray extractFeatures(NDManager manager, NDArray samples) { return stft(samples); } private NDArray stft(NDArray samples) { NDManager manager = samples.getManager(); int strideSize = (int) (0.001 * sampleRate * strideMs); int windowSize = (int) (0.001 * sampleRate * windowsMs); long truncateSize = (samples.size() - windowSize) % strideSize; long len = samples.size() - truncateSize; samples = samples.get(":" + len); int rows = ((int) samples.size() - windowSize) / strideSize + 1; NDList windowList = new NDList(); for (int row = 0; row < rows; row++) { windowList.add(samples.get(strideSize * row + ":" + (strideSize * row + windowSize))); } samples = NDArrays.stack(windowList); NDArray weighting = manager.hanningWindow(windowSize); samples.muli(weighting); NDList fftList = new NDList(); for (int row = 0; row < rows; row++) { fftList.add(fft(samples.get(row))); } NDArray fft = NDArrays.stack(fftList).transpose(); fft = fft.pow(2); weighting = weighting.pow(2); NDArray scale = weighting.sum().mul(this.sampleRate); NDArray middle = fft.get("1:-1,:"); middle = middle.mul(2).div(scale); NDArray head = fft.get("0,:").div(scale).reshape(1, fft.getShape().get(1)); NDArray tail = fft.get("-1,:").div(scale).reshape(1, fft.getShape().get(1)); NDList list = new NDList(head, middle, tail); fft = NDArrays.concat(list, 0); NDArray freqsArray = manager.arange(fft.getShape().get(0)); freqsArray = freqsArray.mul(this.sampleRate / windowSize); float[] freqs = freqsArray.toFloatArray(); int ind = 0; for (int i = 0; i < freqs.length; i++) { if (freqs[i] <= (this.sampleRate / 2)) { ind = i; } else { break; } } ind = ind + 1; fft = fft.get(":" + ind + ",:").add(EPS); fft = fft.log(); return fft; } private NDArray fft(NDArray in) { float[] rawFFT = in.toFloatArray(); FloatFFT_1D fft = new FloatFFT_1D(rawFFT.length); fft.realForward(rawFFT); float[][] result; int n = rawFFT.length; if (n % 2 == 0) { // n is even result = new float[2][n / 2 + 1]; for (int i = 0; i < n / 2; i++) { result[0][i] = rawFFT[2 * i]; // the real part fo the fast fourier transform result[1][i] = rawFFT[2 * i + 1]; // the imaginary part of the fast fourier transform } result[1][0] = 0; result[0][n / 2] = rawFFT[1]; } else { // n is odd result = new float[2][(n + 1) / 2]; for (int i = 0; i < n / 2; i++) { result[0][i] = rawFFT[2 * i]; // the real part fo the fast fourier transform result[1][i] = rawFFT[2 * i + 1]; // the imaginary part of the fast fourier transform } result[1][0] = 0; result[1][(n - 1) / 2] = rawFFT[1]; } float[] re = result[0]; // the real part fo the fast fourier transform float[] im = result[1]; // the imaginary part of the fast fourier transform float[] abs = new float[re.length]; for (int i = 0; i < re.length; i++) { abs[i] = (float) Math.hypot(re[i], im[i]); } return in.getManager().create(abs); } }
0
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio/processor/LogMelSpectrogram.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.audio.processor; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; /** Apply Log Mel spectrogram to the given data. */ public class LogMelSpectrogram implements AudioProcessor { private static final int N_FFT = 400; private static final int HOP_LENGTH = 160; private NDArray melFilters; /** * Constructs a new instance of {@code LogMelSpectrogram}. * * @param melFilter the mel filter */ public LogMelSpectrogram(NDArray melFilter) { this.melFilters = melFilter; } /** * Loads the mel filterbank matrix for projecting STFT into a Mel spectrogram. * * <p>Allows decoupling librosa dependency; saved using: np.savez_compressed( "mel_filters.npz", * mel_80=librosa.filters.mel(sr=16000, n_fft=400, n_mels=80), ) * * @param melFile the mdel file saved in .npz format * @param numMel number of mel * @param manager manager to set for the content * @return a new instance of {@code LogMelSpectrogram} * @throws IOException file not loadable */ public static LogMelSpectrogram newInstance(Path melFile, int numMel, NDManager manager) throws IOException { try (InputStream is = Files.newInputStream(melFile)) { return newInstance(is, numMel, manager); } } /** * Loads the mel filterbank matrix for projecting STFT into a Mel spectrogram. * * @param is the input stream * @param numMel number of mel * @param manager manager to set for the content * @return a new instance of {@code LogMelSpectrogram} * @throws IOException file not loadable */ public static LogMelSpectrogram newInstance(InputStream is, int numMel, NDManager manager) throws IOException { return new LogMelSpectrogram(NDList.decode(manager, is).get("mel_" + numMel)); } /** {@inheritDoc} */ @Override public NDArray extractFeatures(NDManager manager, NDArray samples) { NDArray window = manager.hanningWindow(N_FFT); NDArray stft = samples.stft(N_FFT, HOP_LENGTH, true, window, true); NDArray magnitudes = stft.get(":,:-1").abs().pow(2); NDArray melSpec = melFilters.matMul(magnitudes); melSpec.attach(manager); NDArray logSpec = melSpec.clip(1e-10, Float.MAX_VALUE).log10(); logSpec = logSpec.maximum(logSpec.max().sub(8.0f)); logSpec = logSpec.add(4.0f).div(4.0f); return logSpec; } }
0
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio/processor/PadOrTrim.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.audio.processor; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDManager; import ai.djl.ndarray.types.Shape; /** Pad or trim the samples to the desired numbers. */ public class PadOrTrim implements AudioProcessor { private int desiredSamples; /** * Pad or trim the samples to the fixed length. * * @param desiredSamples the desired sample points */ public PadOrTrim(int desiredSamples) { this.desiredSamples = desiredSamples; } /** {@inheritDoc} */ @Override public NDArray extractFeatures(NDManager manager, NDArray samples) { if (samples.getShape().dimension() != 1) { throw new UnsupportedOperationException("Batch samples not supported."); } long sampleLength = samples.getShape().get(0); if (sampleLength > desiredSamples) { return samples.get(":" + desiredSamples); } return samples.concat(manager.zeros(new Shape(desiredSamples - sampleLength))); } }
0
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio/processor/package-info.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. */ /** Contains multiple processors for audio and signal processing. */ package ai.djl.audio.processor;
0
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio/translator/WhisperTranslator.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.audio.translator; import ai.djl.audio.processor.AudioProcessor; import ai.djl.audio.processor.LogMelSpectrogram; import ai.djl.audio.processor.PadOrTrim; import ai.djl.modality.audio.Audio; import ai.djl.modality.nlp.DefaultVocabulary; import ai.djl.modality.nlp.Vocabulary; import ai.djl.ndarray.NDArray; import ai.djl.ndarray.NDList; import ai.djl.ndarray.NDManager; import ai.djl.translate.NoBatchifyTranslator; import ai.djl.translate.Translator; import ai.djl.translate.TranslatorContext; import ai.djl.util.JsonUtils; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.io.Reader; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * A {@link Translator} that process the {@link Audio} into {@link String} to get a text translation * of the audio. */ public class WhisperTranslator implements NoBatchifyTranslator<Audio, String> { private static final Map<Character, Byte> BYTES_DECODER = bpeDecoder(); private List<AudioProcessor> processors; private Vocabulary vocabulary; /** Constructs a new instance of {@code WhisperTranslator}. */ public WhisperTranslator() { processors = new ArrayList<>(); } /** {@inheritDoc} */ @Override public void prepare(TranslatorContext ctx) throws IOException { Path path = ctx.getModel().getModelPath(); Path melFile = path.resolve("mel_80_filters.npz"); processors.add(new PadOrTrim(480000)); // Use model's NDManager NDManager modelManager = ctx.getModel().getNDManager(); processors.add(LogMelSpectrogram.newInstance(melFile, 80, modelManager)); Map<String, Integer> vocab; Map<String, Integer> added; Type type = new TypeToken<Map<String, Integer>>() {}.getType(); try (Reader reader = Files.newBufferedReader(path.resolve("vocab.json"))) { vocab = JsonUtils.GSON.fromJson(reader, type); } try (Reader reader = Files.newBufferedReader(path.resolve("added_tokens.json"))) { added = JsonUtils.GSON.fromJson(reader, type); } String[] result = new String[vocab.size() + added.size()]; vocab.forEach((key, value) -> result[value] = key); added.forEach((key, value) -> result[value] = key); vocabulary = new DefaultVocabulary(Arrays.asList(result)); } /** {@inheritDoc} */ @Override public NDList processInput(TranslatorContext ctx, Audio input) throws Exception { NDArray samples = ctx.getNDManager().create(input.getData()); for (AudioProcessor processor : processors) { samples = processor.extractFeatures(samples.getManager(), samples); } samples = samples.expandDims(0); NDArray placeholder = ctx.getNDManager().create(""); placeholder.setName("module_method:generate"); return new NDList(samples, placeholder); } /** {@inheritDoc} */ @Override public String processOutput(TranslatorContext ctx, NDList list) throws Exception { NDArray result = list.singletonOrThrow(); StringBuilder sb = new StringBuilder(); for (long ele : result.toLongArray()) { sb.append(vocabulary.getToken(ele)); if ("<|endoftext|>".equals(vocabulary.getToken(ele))) { break; } } byte[] buf = new byte[sb.length()]; for (int i = 0; i < sb.length(); ++i) { char c = sb.charAt(i); buf[i] = BYTES_DECODER.get(c); } return new String(buf, StandardCharsets.UTF_8); } /** * Returns list of utf-8 byte and a mapping to unicode strings. * * <p>We specifically avoids mapping to whitespace/control characters the bpe code barfs on. The * reversible bpe codes work on unicode strings. This means you need a large # of unicode * characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token * dataset you end up needing around 5K for decent coverage. This is a significant percentage of * your normal, say, 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and * unicode strings. */ private static Map<Character, Byte> bpeDecoder() { Map<Character, Byte> map = new ConcurrentHashMap<>(); for (char i = '!'; i <= '~'; ++i) { map.put(i, (byte) i); } for (char i = '¡'; i <= '¬'; ++i) { map.put(i, (byte) i); } for (char i = '®'; i <= 'ÿ'; ++i) { map.put(i, (byte) i); } int n = 0; for (char i = 0; i < 256; ++i) { if (!map.containsKey(i)) { map.put((char) (256 + n), (byte) i); ++n; } } return map; } }
0
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio/translator/WhisperTranslatorFactory.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.audio.translator; import ai.djl.Model; import ai.djl.modality.audio.Audio; 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 TranslatorFactory} that creates a {@link WhisperTranslator} instance. */ public class WhisperTranslatorFactory 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<>(Audio.class, String.class)); } /** {@inheritDoc} */ @Override public Set<Pair<Type, Type>> getSupportedTypes() { return SUPPORTED_TYPES; } /** {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public <I, O> Translator<I, O> newInstance( Class<I> input, Class<O> output, Model model, Map<String, ?> arguments) { if (input == Audio.class && output == String.class) { return (Translator<I, O>) new WhisperTranslator(); } throw new IllegalArgumentException("Unsupported input/output types."); } }
0
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio/translator/package-info.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. */ /** Contains translators for audio processing. */ package ai.djl.audio.translator;
0
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio/util/AudioUtils.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.audio.util; import ai.djl.ndarray.NDArray; /** Useful utils for audio process. */ public final class AudioUtils { private AudioUtils() {} /** * Calculate root mean square energy in decibels. * * @param samples input signal, should be 1 dimension array * @return root mean square energy */ public static float rmsDb(NDArray samples) { samples = samples.pow(2).mean().log10().mul(10); return samples.toFloatArray()[0]; } }
0
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio
java-sources/ai/djl/audio/audio/0.34.0/ai/djl/audio/util/package-info.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. */ /** Contains audio utils for djl. */ package ai.djl.audio.util;
0
java-sources/ai/djl/aws/aws-ai/0.34.0/ai/djl/aws
java-sources/ai/djl/aws/aws-ai/0.34.0/ai/djl/aws/s3/S3Repository.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.aws.s3; import ai.djl.Application; import ai.djl.repository.AbstractRepository; import ai.djl.repository.Artifact; import ai.djl.repository.FilenameUtils; import ai.djl.repository.MRL; import ai.djl.repository.Metadata; import ai.djl.repository.Repository; import ai.djl.repository.zoo.DefaultModelZoo; import ai.djl.util.Progress; import ai.djl.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.core.ResponseInputStream; import software.amazon.awssdk.core.exception.SdkException; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import software.amazon.awssdk.services.s3.model.ListObjectsRequest; import software.amazon.awssdk.services.s3.model.ListObjectsResponse; import software.amazon.awssdk.services.s3.model.S3Object; import java.io.IOException; import java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * A {@code S3Repository} is a {@link Repository} located on a AWS S3. * * @see Repository */ public class S3Repository extends AbstractRepository { private static final Logger logger = LoggerFactory.getLogger(S3Repository.class); private S3Client client; private String bucket; private String prefix; private String artifactId; private String modelName; private Metadata metadata; private boolean resolved; S3Repository(String name, URI uri, S3Client client) { super(name, uri); this.client = client; bucket = uri.getHost(); prefix = uri.getPath(); if (!prefix.isEmpty()) { prefix = prefix.substring(1); } boolean isArchive = FilenameUtils.isArchiveFile(prefix); if (!isArchive && !prefix.isEmpty() && !prefix.endsWith("/")) { prefix += '/'; // NOPMD } modelName = arguments.get("model_name"); artifactId = arguments.get("artifact_id"); if (artifactId == null) { if (prefix.isEmpty()) { artifactId = bucket; } else { Path path = Paths.get(prefix); Path fileName = path.getFileName(); if (fileName == null) { throw new AssertionError("This should never happen."); } artifactId = fileName.toString(); if (isArchive) { artifactId = FilenameUtils.getNamePart(artifactId); } } } if (modelName == null) { modelName = artifactId; } } /** {@inheritDoc} */ @Override public boolean isRemote() { return true; } /** {@inheritDoc} */ @Override public Metadata locate(MRL mrl) throws IOException { return getMetadata(); } /** {@inheritDoc} */ @Override public Artifact resolve(MRL mrl, Map<String, String> filter) throws IOException { Metadata m = locate(mrl); if (m == null) { return null; } List<Artifact> artifacts = m.getArtifacts(); if (artifacts.isEmpty()) { return null; } return artifacts.get(0); } /** {@inheritDoc} */ @Override protected void download(Path tmp, URI baseUri, Artifact.Item item, Progress progress) throws IOException { String key = item.getUri(); logger.debug("Downloading artifact from: s3://{}/{} ...", bucket, key); GetObjectRequest req = GetObjectRequest.builder().bucket(bucket).key(key).build(); try (ResponseInputStream<GetObjectResponse> is = client.getObject(req)) { save(is, tmp, item, progress); } } /** {@inheritDoc} */ @Override public List<MRL> getResources() { try { Metadata m = getMetadata(); if (m != null && !m.getArtifacts().isEmpty()) { MRL mrl = model(Application.UNDEFINED, m.getGroupId(), m.getArtifactId()); return Collections.singletonList(mrl); } } catch (IOException e) { logger.warn("Failed to scan S3: {}", bucket, e); } return Collections.emptyList(); } private synchronized Metadata getMetadata() throws IOException { if (resolved) { return metadata; } try { resolved = true; Artifact artifact = listFiles(); if (artifact == null) { logger.debug("No object found in s3 bucket."); return null; } metadata = new Metadata.MatchAllMetadata(); String hash = Utils.hash("s3://" + bucket + '/' + prefix); MRL mrl = model(Application.UNDEFINED, DefaultModelZoo.GROUP_ID, hash); metadata.setRepositoryUri(mrl.toURI()); metadata.setArtifactId(artifactId); metadata.setArtifacts(Collections.singletonList(artifact)); return metadata; } catch (SdkException e) { throw new IOException("Failed scan s3 bucket: " + bucket, e); } } private Artifact listFiles() { ListObjectsRequest req = ListObjectsRequest.builder() .bucket(bucket) .maxKeys(100) .prefix(prefix) .delimiter("/") .build(); ListObjectsResponse resp = client.listObjects(req); List<S3Object> list = resp.contents(); if (list.isEmpty()) { return null; } Artifact artifact = new Artifact(); artifact.setName(modelName); artifact.getArguments().putAll(arguments); Map<String, Artifact.Item> files = new ConcurrentHashMap<>(); for (S3Object obj : list) { Artifact.Item item = new Artifact.Item(); String key = obj.key(); if (!key.endsWith("/")) { item.setUri(key); item.setSize(obj.size()); item.setArtifact(artifact); if ("dir".equals(item.getType())) { item.setName(""); // avoid creating extra folder } files.put(key, item); } } artifact.setFiles(files); return artifact; } }
0
java-sources/ai/djl/aws/aws-ai/0.34.0/ai/djl/aws
java-sources/ai/djl/aws/aws-ai/0.34.0/ai/djl/aws/s3/S3RepositoryFactory.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.aws.s3; import ai.djl.repository.Repository; import ai.djl.repository.RepositoryFactory; import software.amazon.awssdk.services.s3.S3Client; import java.net.URI; import java.util.Collections; import java.util.Set; /** A class responsible to create {@link S3Repository} instances. */ public class S3RepositoryFactory implements RepositoryFactory { private S3Client client; /** Creates an {@code S3RepositoryFactory}. */ public S3RepositoryFactory() {} /** * Creates an {@code S3RepositoryFactory} instance with the specified {@code S3Client}. * * @param client the {@code S3Client} */ public S3RepositoryFactory(S3Client client) { this.client = client; } /** {@inheritDoc} */ @Override public Repository newInstance(String name, URI uri) { String scheme = uri.getScheme(); if (!"s3".equalsIgnoreCase(scheme)) { throw new IllegalArgumentException("Invalid s3 url: " + uri); } if (client == null) { client = S3Client.create(); } return new S3Repository(name, uri, client); } /** {@inheritDoc} */ @Override public Set<String> getSupportedScheme() { return Collections.singleton("s3"); } }
0
java-sources/ai/djl/aws/aws-ai/0.34.0/ai/djl/aws
java-sources/ai/djl/aws/aws-ai/0.34.0/ai/djl/aws/s3/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 a built-in implementation of Repository class that can be used for loading models from * AWS S3 bucket directly. */ package ai.djl.aws.s3;
0
java-sources/ai/djl/basicdataset/0.34.0/ai/djl
java-sources/ai/djl/basicdataset/0.34.0/ai/djl/basicdataset/BasicDatasets.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.basicdataset; import ai.djl.repository.RemoteRepository; import ai.djl.repository.Repository; import java.net.URI; /** An interface which contains datasets that are hosted on https://mlrepo.djl.ai/. */ public interface BasicDatasets { URI DJL_REPO_URL = URI.create("https://mlrepo.djl.ai/"); Repository REPOSITORY = new RemoteRepository("BasicDataset", DJL_REPO_URL); String GROUP_ID = "ai.djl.basicdataset"; }