Commit 10ef6bbe authored by Abdullah Rashwan's avatar Abdullah Rashwan Committed by A. Unique TensorFlower
Browse files

Internal change

PiperOrigin-RevId: 407843815
parent 6b2e7683
# 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.
...@@ -128,7 +128,7 @@ class MeanIoU(tf.keras.metrics.MeanIoU): ...@@ -128,7 +128,7 @@ class MeanIoU(tf.keras.metrics.MeanIoU):
class PerClassIoU(iou.PerClassIoU): class PerClassIoU(iou.PerClassIoU):
"""Per Class IoU metric for semantic segmentation. """Per Class IoU metric for semantic segmentation.
This class utilizes keras_cv.metrics.PerClassIoU to perform batched per class This class utilizes iou.PerClassIoU to perform batched per class
iou when both input images and groundtruth masks are resized to the same size iou when both input images and groundtruth masks are resized to the same size
(rescale_predictions=False). It also computes per class iou on groundtruth (rescale_predictions=False). It also computes per class iou on groundtruth
original sizes, in which case, each prediction is rescaled back to the original sizes, in which case, each prediction is rescaled back to the
......
...@@ -17,7 +17,6 @@ ...@@ -17,7 +17,6 @@
import tensorflow as tf import tensorflow as tf
@tf.keras.utils.register_keras_serializable(package='keras_cv')
class SpatialPyramidPooling(tf.keras.layers.Layer): class SpatialPyramidPooling(tf.keras.layers.Layer):
"""Implements the Atrous Spatial Pyramid Pooling. """Implements the Atrous Spatial Pyramid Pooling.
......
...@@ -14,10 +14,13 @@ ...@@ -14,10 +14,13 @@
"""Contains definitions of ROI sampler.""" """Contains definitions of ROI sampler."""
# Import libraries # Import libraries
import tensorflow as tf import tensorflow as tf
from official.vision import keras_cv
from official.vision.beta.modeling.layers import box_sampler from official.vision.beta.modeling.layers import box_sampler
from official.vision.beta.ops import box_matcher
from official.vision.beta.ops import iou_similarity
from official.vision.beta.ops import target_gather
@tf.keras.utils.register_keras_serializable(package='Vision') @tf.keras.utils.register_keras_serializable(package='Vision')
...@@ -64,14 +67,14 @@ class ROISampler(tf.keras.layers.Layer): ...@@ -64,14 +67,14 @@ class ROISampler(tf.keras.layers.Layer):
'skip_subsampling': skip_subsampling, 'skip_subsampling': skip_subsampling,
} }
self._sim_calc = keras_cv.ops.IouSimilarity() self._sim_calc = iou_similarity.IouSimilarity()
self._box_matcher = keras_cv.ops.BoxMatcher( self._box_matcher = box_matcher.BoxMatcher(
thresholds=[ thresholds=[
background_iou_low_threshold, background_iou_high_threshold, background_iou_low_threshold, background_iou_high_threshold,
foreground_iou_threshold foreground_iou_threshold
], ],
indicators=[-3, -1, -2, 1]) indicators=[-3, -1, -2, 1])
self._target_gather = keras_cv.ops.TargetGather() self._target_gather = target_gather.TargetGather()
self._sampler = box_sampler.BoxSampler( self._sampler = box_sampler.BoxSampler(
num_sampled_rois, foreground_fraction) num_sampled_rois, foreground_fraction)
......
...@@ -15,9 +15,15 @@ ...@@ -15,9 +15,15 @@
"""Anchor box and labeler definition.""" """Anchor box and labeler definition."""
import collections import collections
# Import libraries # Import libraries
import tensorflow as tf import tensorflow as tf
from official.vision import keras_cv
from official.vision.beta.ops import anchor_generator
from official.vision.beta.ops import box_matcher
from official.vision.beta.ops import iou_similarity
from official.vision.beta.ops import target_gather
from official.vision.detection.utils.object_detection import balanced_positive_negative_sampler from official.vision.detection.utils.object_detection import balanced_positive_negative_sampler
from official.vision.detection.utils.object_detection import box_list from official.vision.detection.utils.object_detection import box_list
from official.vision.detection.utils.object_detection import faster_rcnn_box_coder from official.vision.detection.utils.object_detection import faster_rcnn_box_coder
...@@ -132,9 +138,9 @@ class AnchorLabeler(object): ...@@ -132,9 +138,9 @@ class AnchorLabeler(object):
upper-bound threshold to assign negative labels for anchors. An anchor upper-bound threshold to assign negative labels for anchors. An anchor
with a score below the threshold is labeled negative. with a score below the threshold is labeled negative.
""" """
self.similarity_calc = keras_cv.ops.IouSimilarity() self.similarity_calc = iou_similarity.IouSimilarity()
self.target_gather = keras_cv.ops.TargetGather() self.target_gather = target_gather.TargetGather()
self.matcher = keras_cv.ops.BoxMatcher( self.matcher = box_matcher.BoxMatcher(
thresholds=[unmatched_threshold, match_threshold], thresholds=[unmatched_threshold, match_threshold],
indicators=[-1, -2, 1], indicators=[-1, -2, 1],
force_match_for_each_col=True) force_match_for_each_col=True)
...@@ -343,7 +349,7 @@ def build_anchor_generator(min_level, max_level, num_scales, aspect_ratios, ...@@ -343,7 +349,7 @@ def build_anchor_generator(min_level, max_level, num_scales, aspect_ratios,
stride = 2**level stride = 2**level
strides[str(level)] = stride strides[str(level)] = stride
anchor_sizes[str(level)] = anchor_size * stride anchor_sizes[str(level)] = anchor_size * stride
anchor_gen = keras_cv.ops.AnchorGenerator( anchor_gen = anchor_generator.AnchorGenerator(
anchor_sizes=anchor_sizes, anchor_sizes=anchor_sizes,
scales=scales, scales=scales,
aspect_ratios=aspect_ratios, aspect_ratios=aspect_ratios,
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
from absl.testing import parameterized from absl.testing import parameterized
import tensorflow as tf import tensorflow as tf
from official.vision.keras_cv.ops import anchor_generator from official.vision.beta.ops import anchor_generator
class AnchorGeneratorTest(parameterized.TestCase, tf.test.TestCase): class AnchorGeneratorTest(parameterized.TestCase, tf.test.TestCase):
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
import tensorflow as tf import tensorflow as tf
from official.vision.keras_cv.ops import box_matcher from official.vision.beta.ops import box_matcher
class BoxMatcherTest(tf.test.TestCase): class BoxMatcherTest(tf.test.TestCase):
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
import tensorflow as tf import tensorflow as tf
from official.vision.keras_cv.ops import iou_similarity from official.vision.beta.ops import iou_similarity
class BoxMatcherTest(tf.test.TestCase): class BoxMatcherTest(tf.test.TestCase):
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
import tensorflow as tf import tensorflow as tf
from official.vision.keras_cv.ops import target_gather from official.vision.beta.ops import target_gather
class TargetGatherTest(tf.test.TestCase): class TargetGatherTest(tf.test.TestCase):
......
...@@ -13,14 +13,14 @@ ...@@ -13,14 +13,14 @@
# limitations under the License. # limitations under the License.
"""RetinaNet task definition.""" """RetinaNet task definition."""
from typing import Any, Optional, List, Tuple, Mapping from typing import Any, List, Mapping, Optional, Tuple
from absl import logging from absl import logging
import tensorflow as tf import tensorflow as tf
from official.common import dataset_fn from official.common import dataset_fn
from official.core import base_task from official.core import base_task
from official.core import task_factory from official.core import task_factory
from official.vision import keras_cv
from official.vision.beta.configs import retinanet as exp_cfg from official.vision.beta.configs import retinanet as exp_cfg
from official.vision.beta.dataloaders import input_reader_factory from official.vision.beta.dataloaders import input_reader_factory
from official.vision.beta.dataloaders import retinanet_input from official.vision.beta.dataloaders import retinanet_input
...@@ -28,6 +28,8 @@ from official.vision.beta.dataloaders import tf_example_decoder ...@@ -28,6 +28,8 @@ from official.vision.beta.dataloaders import tf_example_decoder
from official.vision.beta.dataloaders import tfds_factory from official.vision.beta.dataloaders import tfds_factory
from official.vision.beta.dataloaders import tf_example_label_map_decoder from official.vision.beta.dataloaders import tf_example_label_map_decoder
from official.vision.beta.evaluation import coco_evaluator from official.vision.beta.evaluation import coco_evaluator
from official.vision.beta.losses import focal_loss
from official.vision.beta.losses import loss_utils
from official.vision.beta.modeling import factory from official.vision.beta.modeling import factory
...@@ -155,9 +157,9 @@ class RetinaNetTask(base_task.Task): ...@@ -155,9 +157,9 @@ class RetinaNetTask(base_task.Task):
if head.name not in outputs['attribute_outputs']: if head.name not in outputs['attribute_outputs']:
raise ValueError(f'Attribute {head.name} not found in model outputs.') raise ValueError(f'Attribute {head.name} not found in model outputs.')
y_true_att = keras_cv.losses.multi_level_flatten( y_true_att = loss_utils.multi_level_flatten(
labels['attribute_targets'][head.name], last_dim=head.size) labels['attribute_targets'][head.name], last_dim=head.size)
y_pred_att = keras_cv.losses.multi_level_flatten( y_pred_att = loss_utils.multi_level_flatten(
outputs['attribute_outputs'][head.name], last_dim=head.size) outputs['attribute_outputs'][head.name], last_dim=head.size)
if head.type == 'regression': if head.type == 'regression':
att_loss_fn = tf.keras.losses.Huber( att_loss_fn = tf.keras.losses.Huber(
...@@ -180,7 +182,7 @@ class RetinaNetTask(base_task.Task): ...@@ -180,7 +182,7 @@ class RetinaNetTask(base_task.Task):
params = self.task_config params = self.task_config
attribute_heads = self.task_config.model.head.attribute_heads attribute_heads = self.task_config.model.head.attribute_heads
cls_loss_fn = keras_cv.losses.FocalLoss( cls_loss_fn = focal_loss.FocalLoss(
alpha=params.losses.focal_loss_alpha, alpha=params.losses.focal_loss_alpha,
gamma=params.losses.focal_loss_gamma, gamma=params.losses.focal_loss_gamma,
reduction=tf.keras.losses.Reduction.SUM) reduction=tf.keras.losses.Reduction.SUM)
...@@ -194,14 +196,14 @@ class RetinaNetTask(base_task.Task): ...@@ -194,14 +196,14 @@ class RetinaNetTask(base_task.Task):
num_positives = tf.reduce_sum(box_sample_weight) + 1.0 num_positives = tf.reduce_sum(box_sample_weight) + 1.0
cls_sample_weight = cls_sample_weight / num_positives cls_sample_weight = cls_sample_weight / num_positives
box_sample_weight = box_sample_weight / num_positives box_sample_weight = box_sample_weight / num_positives
y_true_cls = keras_cv.losses.multi_level_flatten( y_true_cls = loss_utils.multi_level_flatten(
labels['cls_targets'], last_dim=None) labels['cls_targets'], last_dim=None)
y_true_cls = tf.one_hot(y_true_cls, params.model.num_classes) y_true_cls = tf.one_hot(y_true_cls, params.model.num_classes)
y_pred_cls = keras_cv.losses.multi_level_flatten( y_pred_cls = loss_utils.multi_level_flatten(
outputs['cls_outputs'], last_dim=params.model.num_classes) outputs['cls_outputs'], last_dim=params.model.num_classes)
y_true_box = keras_cv.losses.multi_level_flatten( y_true_box = loss_utils.multi_level_flatten(
labels['box_targets'], last_dim=4) labels['box_targets'], last_dim=4)
y_pred_box = keras_cv.losses.multi_level_flatten( y_pred_box = loss_utils.multi_level_flatten(
outputs['box_outputs'], last_dim=4) outputs['box_outputs'], last_dim=4)
cls_loss = cls_loss_fn( cls_loss = cls_loss_fn(
......
...@@ -21,7 +21,7 @@ from __future__ import print_function ...@@ -21,7 +21,7 @@ from __future__ import print_function
import collections import collections
import tensorflow as tf import tensorflow as tf
from official.vision import keras_cv from official.vision.beta.ops import iou_similarity
from official.vision.detection.utils import box_utils from official.vision.detection.utils import box_utils
from official.vision.detection.utils.object_detection import argmax_matcher from official.vision.detection.utils.object_detection import argmax_matcher
from official.vision.detection.utils.object_detection import balanced_positive_negative_sampler from official.vision.detection.utils.object_detection import balanced_positive_negative_sampler
...@@ -135,7 +135,7 @@ class AnchorLabeler(object): ...@@ -135,7 +135,7 @@ class AnchorLabeler(object):
upper-bound threshold to assign negative labels for anchors. An anchor upper-bound threshold to assign negative labels for anchors. An anchor
with a score below the threshold is labeled negative. with a score below the threshold is labeled negative.
""" """
similarity_calc = keras_cv.ops.IouSimilarity() similarity_calc = iou_similarity.IouSimilarity()
matcher = argmax_matcher.ArgMaxMatcher( matcher = argmax_matcher.ArgMaxMatcher(
match_threshold, match_threshold,
unmatched_threshold=unmatched_threshold, unmatched_threshold=unmatched_threshold,
...@@ -341,7 +341,7 @@ class OlnAnchorLabeler(RpnAnchorLabeler): ...@@ -341,7 +341,7 @@ class OlnAnchorLabeler(RpnAnchorLabeler):
unmatched_threshold=unmatched_threshold, unmatched_threshold=unmatched_threshold,
rpn_batch_size_per_im=rpn_batch_size_per_im, rpn_batch_size_per_im=rpn_batch_size_per_im,
rpn_fg_fraction=rpn_fg_fraction) rpn_fg_fraction=rpn_fg_fraction)
similarity_calc = keras_cv.ops.IouSimilarity() similarity_calc = iou_similarity.IouSimilarity()
matcher = argmax_matcher.ArgMaxMatcher( matcher = argmax_matcher.ArgMaxMatcher(
match_threshold, match_threshold,
unmatched_threshold=unmatched_threshold, unmatched_threshold=unmatched_threshold,
......
Copyright 2020 The TensorFlow Authors. All rights reserved.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2015, The TensorFlow Authors.
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.
\ No newline at end of file
# keras-cv
## Losses
* [FocalLoss](losses/focal_loss.py) implements Focal loss as described in
["Focal Loss for Dense Object Detection"](https://arxiv.org/abs/1708.02002).
## Ops
Ops are used in data pipeline for pre-compute labels, weights.
* [IOUSimilarity](ops/iou_similarity.py) implements Intersection-Over-Union.
# 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.
"""Keras-CV package definition."""
# pylint: disable=wildcard-import
from official.vision.keras_cv import losses
from official.vision.keras_cv import ops
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment