-
Notifications
You must be signed in to change notification settings - Fork 214
Boolean mask ops #214
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Boolean mask ops #214
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
157 changes: 157 additions & 0 deletions
157
tensorflow-core/tensorflow-core-api/src/main/java/org/tensorflow/op/core/BooleanMask.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,157 @@ | ||
/* | ||
Copyright 2021 The TensorFlow Authors. All Rights Reserved. | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT 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 org.tensorflow.op.core; | ||
|
||
import java.util.Arrays; | ||
import java.util.Collections; | ||
import org.tensorflow.Operand; | ||
import org.tensorflow.ndarray.Shape; | ||
import org.tensorflow.ndarray.index.Indices; | ||
import org.tensorflow.op.Scope; | ||
import org.tensorflow.op.annotation.Endpoint; | ||
import org.tensorflow.op.annotation.Operator; | ||
import org.tensorflow.types.TBool; | ||
import org.tensorflow.types.TInt32; | ||
import org.tensorflow.types.TInt64; | ||
import org.tensorflow.types.family.TType; | ||
|
||
@Operator | ||
public abstract class BooleanMask { | ||
|
||
/** | ||
* Apply boolean mask to tensor. Returns the flat array of each element corresponding to a {@code true} in the mask. | ||
* <p> | ||
* Numpy equivalent is {@code tensor[mask]}. | ||
* <p> | ||
* In general, {@code 0 < dim(mask) = K <= dim(tensor)}, and {@code mask}'s shape must match | ||
* the first K dimensions of {@code tensor}'s shape. We then have: | ||
* {@code booleanMask(tensor, mask)[i, j1,...,jd] = tensor[i1,...,iK,j1,...,jd]} | ||
* where {@code (i1,...,iK)} is the ith {@code true} entry of {@code mask} (row-major order). | ||
* <p> | ||
* The {@code axis} could be used with {@code mask} to indicate the axis to mask from (it's 0 by default). | ||
* In that case, {@code axis + dim(mask) <= dim(tensor)} and {@code mask}'s shape must match | ||
* the first {@code axis + dim(mask)} dimensions of {@code tensor}'s shape. | ||
* | ||
* @param scope | ||
* @param tensor The tensor to mask. | ||
* @param mask The mask to apply. | ||
* @param options carries optional attributes values | ||
* @return The masked tensor. | ||
*/ | ||
@Endpoint(name = "booleanMask") | ||
public static <T extends TType> Operand<T> create(Scope scope, Operand<T> tensor, Operand<TBool> mask, | ||
Options... options) { | ||
|
||
scope = scope.withNameAsSubScope("BooleanMask"); | ||
|
||
int axis = 0; | ||
if (options != null) { | ||
for (Options opts : options) { | ||
if (opts.axis != null) { | ||
axis = opts.axis; | ||
} | ||
} | ||
} | ||
|
||
if (axis < 0) { | ||
axis += tensor.rank(); | ||
} | ||
|
||
Shape maskShape = mask.shape(); | ||
Shape tensorShape = tensor.shape(); | ||
|
||
if (maskShape.numDimensions() == 0) { | ||
throw new IllegalArgumentException("Mask cannot be a scalar."); | ||
} | ||
if (maskShape.hasUnknownDimension()) { | ||
throw new IllegalArgumentException("Mask cannot have unknown number of dimensions"); | ||
} | ||
|
||
Operand<TInt32> axisTensor = Constant.scalarOf(scope, axis); | ||
Shape requiredMaskShape = tensorShape.subShape(axis, axis + maskShape.numDimensions()); | ||
if (!requiredMaskShape.isCompatibleWith(maskShape)) { | ||
throw new IllegalArgumentException( | ||
"Mask shape " + maskShape + " is not compatible with the required mask shape: " + requiredMaskShape + "."); | ||
} | ||
|
||
org.tensorflow.op.core.Shape<TInt32> liveShape = org.tensorflow.op.core.Shape.create(scope, tensor); | ||
|
||
Operand<TInt32> leadingSize = ReduceProd.create(scope, | ||
StridedSliceHelper.stridedSlice(scope, | ||
liveShape, | ||
Indices.range(axis, axis + maskShape.numDimensions()) | ||
), | ||
Constant.arrayOf(scope, 0) | ||
); | ||
|
||
Operand<T> flattened = Reshape.create(scope, tensor, Concat.create( | ||
scope, | ||
Arrays.asList( | ||
StridedSliceHelper.stridedSlice(scope, liveShape, Indices.sliceTo(axis)), | ||
Reshape.create(scope, leadingSize, Constant.arrayOf(scope, 1)), | ||
StridedSliceHelper.stridedSlice(scope, liveShape, Indices.sliceFrom(axis + maskShape.numDimensions())) | ||
), | ||
Constant.scalarOf(scope, 0) | ||
)); | ||
|
||
Operand<TBool> flatMask = Reshape.create(scope, mask, Constant.arrayOf(scope, -1)); | ||
|
||
Operand<TInt64> indices = Squeeze.create(scope, Where.create(scope, flatMask), Squeeze.axis(Collections.singletonList(1L))); | ||
return Gather.create(scope, flattened, indices, axisTensor); | ||
} | ||
|
||
/** | ||
* Used to indicate the axis to mask from. | ||
* {@code axis + dim(mask) <= dim(tensor)} and {@code mask}'s shape must match | ||
* the first {@code axis + dim(mask)} dimensions of {@code tensor}'s shape. | ||
* @param axis the axis to mask from. Uses 0 if null. | ||
*/ | ||
public static Options axis(Integer axis){ | ||
return new Options().axis(axis); | ||
} | ||
|
||
|
||
/** | ||
* Used to indicate the axis to mask from. | ||
* {@code axis + dim(mask) <= dim(tensor)} and {@code mask}'s shape must match | ||
* the first {@code axis + dim(mask)} dimensions of {@code tensor}'s shape. | ||
* @param axis the axis to mask from. | ||
*/ | ||
public static Options axis(int axis){ | ||
return new Options().axis(axis); | ||
} | ||
|
||
/** | ||
* Optional attributes for {@link org.tensorflow.op.core.BooleanMask} | ||
*/ | ||
public static class Options { | ||
|
||
/** | ||
* @param axis (Optional) The axis to mask from, or 0 if not set. | ||
*/ | ||
public Options axis(Integer axis) { | ||
this.axis = axis; | ||
return this; | ||
} | ||
|
||
private Integer axis; | ||
|
||
private Options() { | ||
} | ||
} | ||
|
||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It could be interesting to update our other composite ops to make use of this new method, like this one:
java/tensorflow-core/tensorflow-core-api/src/main/java/org/tensorflow/op/core/Ones.java
Line 53 in ef6ece6