use of com.simiacryptus.mindseye.lang.TensorArray in project MindsEye by SimiaCryptus.
the class L1NormalizationLayer method eval.
@Nonnull
@Override
public Result eval(@Nonnull final Result... input) {
Arrays.stream(input).forEach(nnResult -> nnResult.addRef());
final Result in = input[0];
final TensorList inData = in.getData();
inData.addRef();
return new Result(TensorArray.wrap(IntStream.range(0, inData.length()).mapToObj(dataIndex -> {
@Nullable final Tensor value = inData.get(dataIndex);
try {
final double sum = value.sum();
if (!Double.isFinite(sum) || 0 == sum) {
value.addRef();
return value;
} else {
return value.scale(1.0 / sum);
}
} finally {
value.freeRef();
}
}).toArray(i -> new Tensor[i])), (@Nonnull final DeltaSet<Layer> buffer, @Nonnull final TensorList outDelta) -> {
if (in.isAlive()) {
final Tensor[] passbackArray = IntStream.range(0, outDelta.length()).mapToObj(dataIndex -> {
Tensor inputTensor = inData.get(dataIndex);
@Nullable final double[] value = inputTensor.getData();
Tensor outputTensor = outDelta.get(dataIndex);
@Nullable final double[] delta = outputTensor.getData();
final double dot = ArrayUtil.dot(value, delta);
final double sum = Arrays.stream(value).sum();
@Nonnull final Tensor passback = new Tensor(outputTensor.getDimensions());
@Nullable final double[] passbackData = passback.getData();
if (0 != sum || Double.isFinite(sum)) {
for (int i = 0; i < value.length; i++) {
passbackData[i] = (delta[i] - dot / sum) / sum;
}
}
outputTensor.freeRef();
inputTensor.freeRef();
return passback;
}).toArray(i -> new Tensor[i]);
assert Arrays.stream(passbackArray).flatMapToDouble(x -> Arrays.stream(x.getData())).allMatch(v -> Double.isFinite(v));
@Nonnull TensorArray tensorArray = TensorArray.wrap(passbackArray);
in.accumulate(buffer, tensorArray);
}
}) {
@Override
protected void _free() {
inData.freeRef();
Arrays.stream(input).forEach(nnResult -> nnResult.freeRef());
}
@Override
public boolean isAlive() {
return in.isAlive();
}
};
}
use of com.simiacryptus.mindseye.lang.TensorArray in project MindsEye by SimiaCryptus.
the class SingleDerivativeTester method testUnFrozen.
/**
* Test un frozen.
*
* @param component the component
* @param inputPrototype the input prototype
*/
public void testUnFrozen(@Nonnull final Layer component, Tensor[] inputPrototype) {
inputPrototype = Arrays.stream(inputPrototype).map(tensor -> tensor.copy()).toArray(i -> new Tensor[i]);
@Nonnull final AtomicBoolean reachedInputFeedback = new AtomicBoolean(false);
@Nonnull final Layer frozen = component.copy().setFrozen(false);
List<TensorArray> inputCopies = Arrays.stream(inputPrototype).map(TensorArray::wrap).collect(Collectors.toList());
Result[] inputs = inputCopies.stream().map(tensor -> new Result(tensor, (@Nonnull final DeltaSet<Layer> buffer, @Nonnull final TensorList data) -> {
reachedInputFeedback.set(true);
}) {
@Override
public boolean isAlive() {
return true;
}
}).toArray(i -> new Result[i]);
@Nullable final Result eval;
try {
eval = frozen.eval(inputs);
} finally {
for (@Nonnull Result result : inputs) {
result.freeRef();
}
for (@Nonnull TensorArray tensorArray : inputCopies) {
tensorArray.freeRef();
}
}
@Nonnull final DeltaSet<Layer> buffer = new DeltaSet<Layer>();
TensorList tensorList = eval.getData();
eval.accumulate(buffer, tensorList);
eval.freeRef();
@Nullable final List<double[]> stateList = frozen.state();
final List<Delta<Layer>> deltas = stateList.stream().map(doubles -> {
return buffer.stream().filter(x -> x.target == doubles).findFirst().orElse(null);
}).filter(x -> x != null).collect(Collectors.toList());
if (deltas.isEmpty() && !stateList.isEmpty()) {
throw new AssertionError("Nonfrozen component not listed in delta. Deltas: " + deltas);
}
frozen.freeRef();
buffer.freeRef();
if (!reachedInputFeedback.get() && inputPrototype.length != 0) {
throw new RuntimeException("Nonfrozen component did not pass input backwards");
}
}
use of com.simiacryptus.mindseye.lang.TensorArray in project MindsEye by SimiaCryptus.
the class ObjectLocation method renderAlpha.
/**
* Render alpha tensor.
*
* @param alphaPower the alpha power
* @param img the img
* @param locationResult the location result
* @param classification the classification
* @param category the category
* @return the tensor
*/
public Tensor renderAlpha(final double alphaPower, final Tensor img, final Result locationResult, final Tensor classification, final int category) {
TensorArray tensorArray = TensorArray.wrap(new Tensor(classification.getDimensions()).set(category, 1));
DeltaSet<Layer> deltaSet = new DeltaSet<>();
locationResult.accumulate(deltaSet, tensorArray);
double[] rawDelta = deltaSet.getMap().entrySet().stream().filter(x -> x.getValue().target == img.getData()).findAny().get().getValue().getDelta();
Tensor deltaColor = new Tensor(rawDelta, img.getDimensions()).mapAndFree(x -> Math.abs(x));
Tensor delta1d = blur(reduce(deltaColor), 3);
return TestUtil.normalizeBands(TestUtil.normalizeBands(delta1d, 1).mapAndFree(x -> Math.pow(x, alphaPower)));
}
use of com.simiacryptus.mindseye.lang.TensorArray in project MindsEye by SimiaCryptus.
the class PerformanceTester method testPerformance.
/**
* Test learning performance double statistics.
*
* @param component the component
* @param inputPrototype the input prototype
* @return the double statistics
*/
@Nonnull
protected Tuple2<Double, Double> testPerformance(@Nonnull final Layer component, final Tensor... inputPrototype) {
final Tensor[][] data = IntStream.range(0, batches).mapToObj(x -> x).flatMap(x -> Stream.<Tensor[]>of(inputPrototype)).toArray(i -> new Tensor[i][]);
@Nonnull TimedResult<Result> timedEval = TimedResult.time(() -> {
Result[] input = ConstantResult.batchResultArray(data);
@Nullable Result result;
try {
result = component.eval(input);
} finally {
for (@Nonnull Result nnResult : input) {
nnResult.freeRef();
nnResult.getData().freeRef();
}
}
return result;
});
final Result result = timedEval.result;
@Nonnull final DeltaSet<Layer> buffer = new DeltaSet<Layer>();
try {
long timedBackprop = TimedResult.time(() -> {
@Nonnull TensorArray tensorArray = TensorArray.wrap(result.getData().stream().map(x -> {
return x.mapAndFree(v -> 1.0);
}).toArray(i -> new Tensor[i]));
result.accumulate(buffer, tensorArray);
assert tensorArray.currentRefCount() == 0;
return buffer;
}).timeNanos;
return new Tuple2<>(timedEval.timeNanos / 1e9, timedBackprop / 1e9);
} finally {
buffer.freeRef();
result.freeRef();
result.getData().freeRef();
}
}
use of com.simiacryptus.mindseye.lang.TensorArray in project MindsEye by SimiaCryptus.
the class BatchDerivativeTester method getLearningGradient.
@Nonnull
private Tensor getLearningGradient(@Nonnull final Layer component, final int layerNum, @Nonnull final Tensor outputPrototype, final Tensor... inputPrototype) {
component.setFrozen(false);
final double[] stateArray = component.state().get(layerNum);
final int stateLen = stateArray.length;
@Nonnull final Tensor gradient = new Tensor(stateLen, outputPrototype.length());
for (int j = 0; j < outputPrototype.length(); j++) {
final int j_ = j;
@Nonnull final DeltaSet<Layer> buffer = new DeltaSet<Layer>();
@Nonnull final Tensor data = new Tensor(outputPrototype.getDimensions()).set((k) -> k == j_ ? 1 : 0);
@Nullable final Result eval = component.eval(ConstantResult.singleResultArray(new Tensor[][] { inputPrototype }));
eval.getData().get(0);
@Nonnull TensorArray tensorArray = TensorArray.wrap(data);
eval.accumulate(buffer, tensorArray);
final DoubleBuffer<Layer> deltaFlushBuffer = buffer.getMap().values().stream().filter(x -> x.target == stateArray).findFirst().orElse(null);
if (null != deltaFlushBuffer) {
for (int i = 0; i < stateLen; i++) {
gradient.set(new int[] { i, j_ }, deltaFlushBuffer.getDelta()[i]);
}
}
}
return gradient;
}
Aggregations