repo
stringlengths 2
99
| file
stringlengths 13
225
| code
stringlengths 0
18.3M
| file_length
int64 0
18.3M
| avg_line_length
float64 0
1.36M
| max_line_length
int64 0
4.26M
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
models | models-master/official/projects/centernet/configs/backbones.py | # Copyright 2023 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.
"""Backbones configurations."""
import dataclasses
from official.modeling import hyperparams
from official.vision.configs import backbones
@dataclasses.dataclass
class Hourglass(hyperparams.Config):
"""Hourglass config."""
model_id: int = 52
input_channel_dims: int = 128
num_hourglasses: int = 2
initial_downsample: bool = True
activation: str = 'relu'
@dataclasses.dataclass
class Backbone(backbones.Backbone):
hourglass: Hourglass = dataclasses.field(default_factory=Hourglass)
| 1,110 | 29.861111 | 74 | py |
models | models-master/official/projects/centernet/configs/centernet_test.py | # Copyright 2023 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.
"""Tests for centernet."""
from absl.testing import parameterized
import tensorflow as tf
from official.core import config_definitions as cfg
from official.core import exp_factory
from official.projects.centernet.common import registry_imports # pylint: disable=unused-import
from official.projects.centernet.configs import centernet as exp_cfg
class CenterNetConfigTest(tf.test.TestCase, parameterized.TestCase):
@parameterized.parameters(('centernet_hourglass_coco',))
def test_centernet_configs(self, config_name):
config = exp_factory.get_exp_config(config_name)
self.assertIsInstance(config, cfg.ExperimentConfig)
self.assertIsInstance(config.task, exp_cfg.CenterNetTask)
self.assertIsInstance(config.task.model, exp_cfg.CenterNetModel)
self.assertIsInstance(config.task.train_data, exp_cfg.DataConfig)
config.task.train_data.is_training = None
with self.assertRaises(KeyError):
config.validate()
if __name__ == '__main__':
tf.test.main()
| 1,601 | 37.142857 | 96 | py |
models | models-master/official/projects/centernet/dataloaders/__init__.py | # Copyright 2023 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.
| 609 | 39.666667 | 74 | py |
models | models-master/official/projects/centernet/dataloaders/centernet_input.py | # Copyright 2023 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.
"""Data parser and processing for Centernet."""
from typing import Tuple
import tensorflow as tf
from official.projects.centernet.ops import box_list
from official.projects.centernet.ops import box_list_ops
from official.projects.centernet.ops import preprocess_ops as cn_prep_ops
from official.vision.dataloaders import parser
from official.vision.dataloaders import utils
from official.vision.ops import box_ops
from official.vision.ops import preprocess_ops
CHANNEL_MEANS = (104.01362025, 114.03422265, 119.9165958)
CHANNEL_STDS = (73.6027665, 69.89082075, 70.9150767)
class CenterNetParser(parser.Parser):
"""Parse an image and its annotations into a dictionary of tensors."""
def __init__(self,
output_width: int = 512,
output_height: int = 512,
max_num_instances: int = 128,
bgr_ordering: bool = True,
aug_rand_hflip=True,
aug_scale_min=1.0,
aug_scale_max=1.0,
aug_rand_saturation=False,
aug_rand_brightness=False,
aug_rand_hue=False,
aug_rand_contrast=False,
odapi_augmentation=False,
channel_means: Tuple[float, float, float] = CHANNEL_MEANS,
channel_stds: Tuple[float, float, float] = CHANNEL_STDS,
dtype: str = 'float32'):
"""Initializes parameters for parsing annotations in the dataset.
Args:
output_width: A `Tensor` or `int` for width of output image.
output_height: A `Tensor` or `int` for height of output image.
max_num_instances: An `int` number of maximum number of instances
in an image.
bgr_ordering: `bool`, if set will change the channel ordering to be in the
[blue, red, green] order.
aug_rand_hflip: `bool`, if True, augment training with random horizontal
flip.
aug_scale_min: `float`, the minimum scale applied to `output_size` for
data augmentation during training.
aug_scale_max: `float`, the maximum scale applied to `output_size` for
data augmentation during training.
aug_rand_saturation: `bool`, if True, augment training with random
saturation.
aug_rand_brightness: `bool`, if True, augment training with random
brightness.
aug_rand_hue: `bool`, if True, augment training with random hue.
aug_rand_contrast: `bool`, if True, augment training with random contrast.
odapi_augmentation: `bool`, if Ture, use OD API preprocessing.
channel_means: A tuple of floats, denoting the mean of each channel
which will be subtracted from it.
channel_stds: A tuple of floats, denoting the standard deviation of each
channel. Each channel will be divided by its standard deviation value.
dtype: `str`, data type. One of {`bfloat16`, `float32`, `float16`}.
Raises:
Exception: if datatype is not supported.
"""
self._output_width = output_width
self._output_height = output_height
self._max_num_instances = max_num_instances
self._bgr_ordering = bgr_ordering
self._channel_means = channel_means
self._channel_stds = channel_stds
if dtype == 'float16':
self._dtype = tf.float16
elif dtype == 'bfloat16':
self._dtype = tf.bfloat16
elif dtype == 'float32':
self._dtype = tf.float32
else:
raise Exception(
'Unsupported datatype used in parser only '
'{float16, bfloat16, or float32}')
# Data augmentation.
self._aug_rand_hflip = aug_rand_hflip
self._aug_scale_min = aug_scale_min
self._aug_scale_max = aug_scale_max
self._aug_rand_saturation = aug_rand_saturation
self._aug_rand_brightness = aug_rand_brightness
self._aug_rand_hue = aug_rand_hue
self._aug_rand_contrast = aug_rand_contrast
self._odapi_augmentation = odapi_augmentation
def _build_label(self,
boxes,
classes,
image_info,
unpad_image_shape,
data):
# Sets up groundtruth data for evaluation.
groundtruths = {
'source_id': data['source_id'],
'height': data['height'],
'width': data['width'],
'num_detections': tf.shape(data['groundtruth_classes'])[0],
'boxes': box_ops.denormalize_boxes(
data['groundtruth_boxes'], tf.shape(input=data['image'])[0:2]),
'classes': data['groundtruth_classes'],
'areas': data['groundtruth_area'],
'is_crowds': tf.cast(data['groundtruth_is_crowd'], tf.int32),
}
groundtruths['source_id'] = utils.process_source_id(
groundtruths['source_id'])
groundtruths = utils.pad_groundtruths_to_fixed_size(
groundtruths, self._max_num_instances)
labels = {
'boxes': preprocess_ops.clip_or_pad_to_fixed_size(
boxes, self._max_num_instances, -1),
'classes': preprocess_ops.clip_or_pad_to_fixed_size(
classes, self._max_num_instances, -1),
'image_info': image_info,
'unpad_image_shapes': unpad_image_shape,
'groundtruths': groundtruths
}
return labels
def _parse_train_data(self, data):
"""Generates images and labels that are usable for model training.
We use random flip, random scaling (between 0.6 to 1.3), cropping,
and color jittering as data augmentation
Args:
data: the decoded tensor dictionary from TfExampleDecoder.
Returns:
images: the image tensor.
labels: a dict of Tensors that contains labels.
"""
image = tf.cast(data['image'], dtype=tf.float32)
boxes = data['groundtruth_boxes']
classes = data['groundtruth_classes']
image_shape = tf.shape(input=image)[0:2]
if self._aug_rand_hflip:
image, boxes, _ = preprocess_ops.random_horizontal_flip(image, boxes)
# Image augmentation
if not self._odapi_augmentation:
# Color and lighting jittering
if self._aug_rand_hue:
image = tf.image.random_hue(
image=image, max_delta=.02)
if self._aug_rand_contrast:
image = tf.image.random_contrast(
image=image, lower=0.8, upper=1.25)
if self._aug_rand_saturation:
image = tf.image.random_saturation(
image=image, lower=0.8, upper=1.25)
if self._aug_rand_brightness:
image = tf.image.random_brightness(
image=image, max_delta=.2)
image = tf.clip_by_value(image, clip_value_min=0.0, clip_value_max=255.0)
# Converts boxes from normalized coordinates to pixel coordinates.
boxes = box_ops.denormalize_boxes(boxes, image_shape)
# Resizes and crops image.
image, image_info = preprocess_ops.resize_and_crop_image(
image,
[self._output_height, self._output_width],
padded_size=[self._output_height, self._output_width],
aug_scale_min=self._aug_scale_min,
aug_scale_max=self._aug_scale_max)
unpad_image_shape = tf.cast(tf.shape(image), tf.float32)
# Resizes and crops boxes.
image_scale = image_info[2, :]
offset = image_info[3, :]
boxes = preprocess_ops.resize_and_crop_boxes(boxes, image_scale,
image_info[1, :], offset)
else:
# Color and lighting jittering
if self._aug_rand_hue:
image = cn_prep_ops.random_adjust_hue(
image=image, max_delta=.02)
if self._aug_rand_contrast:
image = cn_prep_ops.random_adjust_contrast(
image=image, min_delta=0.8, max_delta=1.25)
if self._aug_rand_saturation:
image = cn_prep_ops.random_adjust_saturation(
image=image, min_delta=0.8, max_delta=1.25)
if self._aug_rand_brightness:
image = cn_prep_ops.random_adjust_brightness(
image=image, max_delta=.2)
sc_image, sc_boxes, classes = cn_prep_ops.random_square_crop_by_scale(
image=image,
boxes=boxes,
labels=classes,
scale_min=self._aug_scale_min,
scale_max=self._aug_scale_max)
image, unpad_image_shape = cn_prep_ops.resize_to_range(
image=sc_image,
min_dimension=self._output_width,
max_dimension=self._output_width,
pad_to_max_dimension=True)
preprocessed_shape = tf.cast(tf.shape(image), tf.float32)
unpad_image_shape = tf.cast(unpad_image_shape, tf.float32)
im_box = tf.stack([
0.0,
0.0,
preprocessed_shape[0] / unpad_image_shape[0],
preprocessed_shape[1] / unpad_image_shape[1]
])
realigned_bboxes = box_list_ops.change_coordinate_frame(
boxlist=box_list.BoxList(sc_boxes),
window=im_box)
valid_boxes = box_list_ops.assert_or_prune_invalid_boxes(
realigned_bboxes.get())
boxes = box_list_ops.to_absolute_coordinates(
boxlist=box_list.BoxList(valid_boxes),
height=self._output_height,
width=self._output_width).get()
image_info = tf.stack([
tf.cast(image_shape, dtype=tf.float32),
tf.constant([self._output_height, self._output_width],
dtype=tf.float32),
tf.cast(tf.shape(sc_image)[0:2] / image_shape, dtype=tf.float32),
tf.constant([0., 0.])
])
# Filters out ground truth boxes that are all zeros.
indices = box_ops.get_non_empty_box_indices(boxes)
boxes = tf.gather(boxes, indices)
classes = tf.gather(classes, indices)
labels = self._build_label(
unpad_image_shape=unpad_image_shape,
boxes=boxes,
classes=classes,
image_info=image_info,
data=data)
if self._bgr_ordering:
red, green, blue = tf.unstack(image, num=3, axis=2)
image = tf.stack([blue, green, red], axis=2)
image = preprocess_ops.normalize_image(
image=image,
offset=self._channel_means,
scale=self._channel_stds)
image = tf.cast(image, self._dtype)
return image, labels
def _parse_eval_data(self, data):
"""Generates images and labels that are usable for model evaluation.
Args:
data: the decoded tensor dictionary from TfExampleDecoder.
Returns:
images: the image tensor.
labels: a dict of Tensors that contains labels.
"""
image = tf.cast(data['image'], dtype=tf.float32)
boxes = data['groundtruth_boxes']
classes = data['groundtruth_classes']
image_shape = tf.shape(input=image)[0:2]
# Converts boxes from normalized coordinates to pixel coordinates.
boxes = box_ops.denormalize_boxes(boxes, image_shape)
# Resizes and crops image.
image, image_info = preprocess_ops.resize_and_crop_image(
image,
[self._output_height, self._output_width],
padded_size=[self._output_height, self._output_width],
aug_scale_min=1.0,
aug_scale_max=1.0)
unpad_image_shape = tf.cast(tf.shape(image), tf.float32)
# Resizes and crops boxes.
image_scale = image_info[2, :]
offset = image_info[3, :]
boxes = preprocess_ops.resize_and_crop_boxes(boxes, image_scale,
image_info[1, :], offset)
# Filters out ground truth boxes that are all zeros.
indices = box_ops.get_non_empty_box_indices(boxes)
boxes = tf.gather(boxes, indices)
classes = tf.gather(classes, indices)
labels = self._build_label(
unpad_image_shape=unpad_image_shape,
boxes=boxes,
classes=classes,
image_info=image_info,
data=data)
if self._bgr_ordering:
red, green, blue = tf.unstack(image, num=3, axis=2)
image = tf.stack([blue, green, red], axis=2)
image = preprocess_ops.normalize_image(
image=image,
offset=self._channel_means,
scale=self._channel_stds)
image = tf.cast(image, self._dtype)
return image, labels
| 12,562 | 35.520349 | 80 | py |
models | models-master/official/projects/centernet/utils/tf2_centernet_checkpoint_converter.py | # Copyright 2023 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.
"""A converter from a tf1 OD API checkpoint to a tf2 checkpoint."""
from absl import app
from absl import flags
from absl import logging
import tensorflow as tf
from official.projects.centernet.common import registry_imports # pylint: disable=unused-import
from official.projects.centernet.configs import backbones
from official.projects.centernet.configs import centernet
from official.projects.centernet.modeling import centernet_model
from official.projects.centernet.modeling.heads import centernet_head
from official.projects.centernet.modeling.layers import detection_generator
from official.projects.centernet.utils.checkpoints import load_weights
from official.projects.centernet.utils.checkpoints import read_checkpoints
from official.vision.modeling.backbones import factory
FLAGS = flags.FLAGS
flags.DEFINE_string("checkpoint_to_convert", None,
"Initial checkpoint from a pretrained model.")
flags.DEFINE_string("checkpoint_backbone_name", "hourglass104_512",
"IIndicate the desired backbone configuration.")
flags.DEFINE_string("checkpoint_head_name", "detection_2d",
"Indicate the desired head configuration.")
flags.DEFINE_string("converted_checkpoint_path", None,
"Output path of converted checkpoint.")
flags.DEFINE_integer("hourglass_id", 52,
"Model id of hourglass backbone.")
flags.DEFINE_integer("num_hourglasses", 2,
"Number of hourglass blocks in backbone.")
def _create_centernet_model(model_id: int = 52,
num_hourglasses: int = 2
) -> centernet_model.CenterNetModel:
"""Create centernet model to load TF1 weights."""
task_config = centernet.CenterNetTask(
model=centernet.CenterNetModel(
backbone=backbones.Backbone(
type="hourglass",
hourglass=backbones.Hourglass(
model_id=model_id, num_hourglasses=num_hourglasses))))
model_config = task_config.model
backbone = factory.build_backbone(
input_specs=tf.keras.layers.InputSpec(shape=[1, 512, 512, 3]),
backbone_config=model_config.backbone,
norm_activation_config=model_config.norm_activation)
task_outputs = task_config.get_output_length_dict()
head = centernet_head.CenterNetHead(
input_specs=backbone.output_specs,
task_outputs=task_outputs,
input_levels=model_config.head.input_levels)
detect_generator_obj = detection_generator.CenterNetDetectionGenerator()
model = centernet_model.CenterNetModel(
backbone=backbone, head=head, detection_generator=detect_generator_obj)
logging.info("Successfully created centernet model.")
return model
def _load_weights(model: centernet_model.CenterNetModel,
ckpt_dir_or_file: str,
ckpt_backbone_name: str,
ckpt_head_name: str):
"""Read TF1 checkpoint and load the weights to centernet model."""
weights_dict, _ = read_checkpoints.get_ckpt_weights_as_dict(
ckpt_dir_or_file)
load_weights.load_weights_model(
model=model,
weights_dict=weights_dict,
backbone_name=ckpt_backbone_name,
head_name=ckpt_head_name)
def _save_checkpoint(model: centernet_model.CenterNetModel,
ckpt_dir: str):
"""Save the TF2 centernet model checkpoint."""
checkpoint = tf.train.Checkpoint(model=model, **model.checkpoint_items)
manager = tf.train.CheckpointManager(checkpoint,
directory=ckpt_dir,
max_to_keep=3)
manager.save()
logging.info("Save checkpoint to %s.", ckpt_dir)
def convert_checkpoint(model_id: int,
num_hourglasses: int,
ckpt_dir_or_file: str,
ckpt_backbone_name: str,
ckpt_head_name: str,
output_ckpt_dir: str):
"""Convert the TF1 OD API checkpoint to a tf2 checkpoint."""
model = _create_centernet_model(
model_id=model_id,
num_hourglasses=num_hourglasses)
_load_weights(
model=model,
ckpt_dir_or_file=ckpt_dir_or_file,
ckpt_backbone_name=ckpt_backbone_name,
ckpt_head_name=ckpt_head_name)
_save_checkpoint(
model=model,
ckpt_dir=output_ckpt_dir)
def main(_):
convert_checkpoint(
model_id=FLAGS.hourglass_id,
num_hourglasses=FLAGS.num_hourglasses,
ckpt_dir_or_file=FLAGS.checkpoint_to_convert,
ckpt_backbone_name=FLAGS.checkpoint_backbone_name,
ckpt_head_name=FLAGS.checkpoint_head_name,
output_ckpt_dir=FLAGS.converted_checkpoint_path)
if __name__ == "__main__":
app.run(main)
| 5,327 | 37.890511 | 96 | py |
models | models-master/official/projects/centernet/utils/__init__.py | # Copyright 2023 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.
| 609 | 39.666667 | 74 | py |
models | models-master/official/projects/centernet/utils/checkpoints/load_weights.py | # Copyright 2023 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.
"""Functions used to load the ODAPI CenterNet checkpoint."""
from official.projects.centernet.modeling.layers import cn_nn_blocks
from official.projects.centernet.utils.checkpoints import config_classes
from official.projects.centernet.utils.checkpoints import config_data
from official.vision.modeling.backbones import mobilenet
from official.vision.modeling.layers import nn_blocks
Conv2DBNCFG = config_classes.Conv2DBNCFG
HeadConvCFG = config_classes.HeadConvCFG
ResidualBlockCFG = config_classes.ResidualBlockCFG
HourglassCFG = config_classes.HourglassCFG
BackboneConfigData = config_data.BackboneConfigData
HeadConfigData = config_data.HeadConfigData
def get_backbone_layer_cfgs(weights_dict, backbone_name):
"""Fetches the config classes for the backbone.
This function generates a list of config classes corresponding to
each building block in the backbone.
Args:
weights_dict: Dictionary that stores the backbone model weights.
backbone_name: String, indicating the desired backbone configuration.
Returns:
A list containing the config classe of the backbone building block
"""
print("Fetching backbone config classes for {}\n".format(backbone_name))
cfgs = BackboneConfigData(weights_dict=weights_dict).get_cfg_list(
backbone_name)
return cfgs
def load_weights_backbone(backbone, weights_dict, backbone_name):
"""Loads the weights defined in the weights_dict into the backbone.
This function loads the backbone weights by first fetching the necessary
config classes for the backbone, then loads them in one by one for
each layer that has weights associated with it.
Args:
backbone: keras.Model backbone.
weights_dict: Dictionary that stores the backbone model weights.
backbone_name: String, indicating the desired backbone configuration.
Returns:
Number of weights loaded in
"""
print("Loading backbone weights\n")
backbone_layers = backbone.layers
cfgs = get_backbone_layer_cfgs(weights_dict, backbone_name)
n_weights_total = 0
cfg = cfgs.pop(0)
for i in range(len(backbone_layers)):
layer = backbone_layers[i]
if isinstance(layer,
(mobilenet.Conv2DBNBlock,
cn_nn_blocks.HourglassBlock,
nn_blocks.ResidualBlock)):
n_weights = cfg.load_weights(layer)
print("Loading weights for: {}, weights loaded: {}".format(
cfg, n_weights))
n_weights_total += n_weights
# pylint: disable=g-explicit-length-test
if len(cfgs) == 0:
print("{} Weights have been loaded for {} / {} layers\n".format(
n_weights_total, i + 1, len(backbone_layers)))
return n_weights_total
cfg = cfgs.pop(0)
return n_weights_total
def get_head_layer_cfgs(weights_dict, head_name):
"""Fetches the config classes for the head.
This function generates a list of config classes corresponding to
each building block in the head.
Args:
weights_dict: Dictionary that stores the decoder model weights.
head_name: String, indicating the desired head configuration.
Returns:
A list containing the config classes of the backbone building block
"""
print("Fetching head config classes for {}\n".format(head_name))
cfgs = HeadConfigData(weights_dict=weights_dict).get_cfg_list(head_name)
return cfgs
def load_weights_head(head, weights_dict, head_name):
"""Loads the weights defined in the weights_dict into the head.
This function loads the head weights by first fetching the necessary
config classes for the decoder, then loads them in one by one for
each layer that has weights associated with it.
Args:
head: keras.Model head.
weights_dict: Dictionary that stores the decoder model weights.
head_name: String, indicating the desired head configuration.
Returns:
Number of weights loaded in
"""
print("Loading head weights\n")
head_layers = head.layers
cfgs = get_head_layer_cfgs(weights_dict, head_name)
n_weights_total = 0
cfg = cfgs.pop(0)
for i in range(len(head_layers)):
layer = head_layers[i]
if isinstance(layer, cn_nn_blocks.CenterNetHeadConv):
n_weights = cfg.load_weights(layer)
print("Loading weights for: {}, weights loaded: {}".format(
cfg, n_weights))
n_weights_total += n_weights
# pylint: disable=g-explicit-length-test
if len(cfgs) == 0:
print("{} Weights have been loaded for {} / {} layers\n".format(
n_weights_total, i + 1, len(head_layers)))
return n_weights_total
cfg = cfgs.pop(0)
return n_weights_total
def load_weights_model(model, weights_dict, backbone_name, head_name):
"""Loads weights into the model.
Args:
model: keras.Model to load weights into.
weights_dict: Dictionary that stores the weights of the model.
backbone_name: String, indicating the desired backbone configuration.
head_name: String, indicating the desired head configuration.
Returns:
"""
print("Loading model weights\n")
n_weights = 0
if backbone_name:
n_weights += load_weights_backbone(
model.backbone,
weights_dict["model"]["_feature_extractor"]["_network"],
backbone_name)
if head_name:
n_weights += load_weights_head(
model.head,
weights_dict["model"]["_prediction_head_dict"],
head_name)
print("Successfully loaded {} model weights.\n".format(n_weights))
return model
| 6,042 | 33.729885 | 74 | py |
models | models-master/official/projects/centernet/utils/checkpoints/config_data.py | # Copyright 2023 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.
"""Configurations for loading checkpoints."""
import dataclasses
from typing import Dict, Optional
import numpy as np
from official.projects.centernet.utils.checkpoints import config_classes
Conv2DBNCFG = config_classes.Conv2DBNCFG
HeadConvCFG = config_classes.HeadConvCFG
ResidualBlockCFG = config_classes.ResidualBlockCFG
HourglassCFG = config_classes.HourglassCFG
@dataclasses.dataclass
class BackboneConfigData:
"""Backbone Config."""
weights_dict: Optional[Dict[str, np.ndarray]] = dataclasses.field(
repr=False, default=None)
def get_cfg_list(self, name):
"""Get list of block configs for the module."""
if name == 'hourglass104_512':
return [
# Downsampling Layers
Conv2DBNCFG(
weights_dict=self.weights_dict['downsample_input']['conv_block']),
ResidualBlockCFG(
weights_dict=self.weights_dict['downsample_input'][
'residual_block']),
# Hourglass
HourglassCFG(
weights_dict=self.weights_dict['hourglass_network']['0']),
Conv2DBNCFG(
weights_dict=self.weights_dict['output_conv']['0']),
# Intermediate
Conv2DBNCFG(
weights_dict=self.weights_dict['intermediate_conv1']['0']),
Conv2DBNCFG(
weights_dict=self.weights_dict['intermediate_conv2']['0']),
ResidualBlockCFG(
weights_dict=self.weights_dict['intermediate_residual']['0']),
# Hourglass
HourglassCFG(
weights_dict=self.weights_dict['hourglass_network']['1']),
Conv2DBNCFG(
weights_dict=self.weights_dict['output_conv']['1']),
]
elif name == 'extremenet':
return [
# Downsampling Layers
Conv2DBNCFG(
weights_dict=self.weights_dict['downsample_input']['conv_block']),
ResidualBlockCFG(
weights_dict=self.weights_dict['downsample_input'][
'residual_block']),
# Hourglass
HourglassCFG(
weights_dict=self.weights_dict['hourglass_network']['0']),
Conv2DBNCFG(
weights_dict=self.weights_dict['output_conv']['0']),
# Intermediate
Conv2DBNCFG(
weights_dict=self.weights_dict['intermediate_conv1']['0']),
Conv2DBNCFG(
weights_dict=self.weights_dict['intermediate_conv2']['0']),
ResidualBlockCFG(
weights_dict=self.weights_dict['intermediate_residual']['0']),
# Hourglass
HourglassCFG(
weights_dict=self.weights_dict['hourglass_network']['1']),
Conv2DBNCFG(
weights_dict=self.weights_dict['output_conv']['1']),
]
@dataclasses.dataclass
class HeadConfigData:
"""Head Config."""
weights_dict: Optional[Dict[str, np.ndarray]] = dataclasses.field(
repr=False, default=None)
def get_cfg_list(self, name):
if name == 'detection_2d':
return [
HeadConvCFG(weights_dict=self.weights_dict['object_center']['0']),
HeadConvCFG(weights_dict=self.weights_dict['object_center']['1']),
HeadConvCFG(weights_dict=self.weights_dict['box.Soffset']['0']),
HeadConvCFG(weights_dict=self.weights_dict['box.Soffset']['1']),
HeadConvCFG(weights_dict=self.weights_dict['box.Sscale']['0']),
HeadConvCFG(weights_dict=self.weights_dict['box.Sscale']['1'])
]
| 4,085 | 35.482143 | 80 | py |
models | models-master/official/projects/centernet/utils/checkpoints/read_checkpoints.py | # Copyright 2023 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.
"""Functions used to convert a TF checkpoint into a dictionary."""
import numpy as np
import tensorflow as tf
def update_weights_dict(weights_dict, variable_key, value):
"""Inserts weight value into a weight dictionary.
This function inserts a weight value into a weights_dict based on the
variable key. It is designed to organize TF checkpoint weights by organizing
them by submodules.
Args:
weights_dict: Dictionary to store weights.
variable_key: String, name of the variable assocaited with the value.
value: An ndarray that stores the weights assocaited to the variable key.
"""
current_dict = weights_dict
variable_key_list = variable_key.split("/")
key = variable_key_list.pop(0)
# pylint: disable=g-explicit-length-test
while len(variable_key_list):
if variable_key_list[0] == ".ATTRIBUTES":
current_dict[key] = value
return
if key not in current_dict.keys():
current_dict[key] = {}
current_dict = current_dict[key]
key = variable_key_list.pop(0)
def get_ckpt_weights_as_dict(ckpt_path):
"""Converts a TF checkpoint into a nested dictionary of weights.
Args:
ckpt_path: String, indicating filepath of the TF checkpoint
Returns:
Dictionary where the checkpoint weights are stored
Number of weights read
"""
print("\nConverting model checkpoint from {} to weights dictionary\n".format(
ckpt_path))
reader = tf.train.load_checkpoint(ckpt_path)
shape_from_key = reader.get_variable_to_shape_map()
# dtype_from_key = reader.get_variable_to_dtype_map()
variable_keys = shape_from_key.keys()
weights_dict = {}
n_read = 0
for key in variable_keys:
# shape = shape_from_key[key]
# dtype = dtype_from_key[key]
value = reader.get_tensor(key)
n_read += tf.size(value)
update_weights_dict(weights_dict, key, value)
print("Successfully read {} checkpoint weights\n".format(n_read))
return weights_dict, n_read
def write_dict_as_tree(dictionary, filename, spaces=0):
"""Writes nested dictionary keys to a file.
Given a dictionary that contains nested dictionaries, this function
writes the name of the keys recursively to a specified file as a tree
Args:
dictionary: Desired dictionary to write to a file
filename: String, name of file to write dictionary to
spaces: Optional; Number of spaces to insert before writing
the dictionary key names
"""
if isinstance(dictionary, dict):
mode = "w" if spaces == 0 else "a"
for key in dictionary.keys():
with open(filename, mode) as fp:
fp.write(" " * spaces + key + "\n")
mode = "a"
write_dict_as_tree(dictionary[key], filename, spaces + 2)
def print_layer_weights_and_shape(layer):
"""Prints variables information corresponding to a Keras layer.
This function prints the name and the shape of its associated weights
of all variables (trainable and untrainable) in a Keras layer.
Args:
layer: A Keras.layer.Layer object
"""
weights = layer.get_weights()
variables = layer.variables
for i in range(len(weights)):
tf.print(np.shape(weights[i]), variables[i].name)
| 3,752 | 31.634783 | 79 | py |
models | models-master/official/projects/centernet/utils/checkpoints/__init__.py | # Copyright 2023 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.
| 609 | 39.666667 | 74 | py |
models | models-master/official/projects/centernet/utils/checkpoints/config_classes.py | # Copyright 2023 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.
"""Layer config for parsing ODAPI checkpoint.
This file contains the layers (Config objects) that are used for parsing the
ODAPI checkpoint weights for CenterNet.
Currently, the parser is incomplete and has only been tested on
CenterNet Hourglass-104 512x512.
"""
import abc
import dataclasses
from typing import Dict, Optional
import numpy as np
import tensorflow as tf
class Config(abc.ABC):
"""Base config class."""
def get_weights(self):
"""Generates the weights needed to be loaded into the layer."""
raise NotImplementedError
def load_weights(self, layer: tf.keras.layers.Layer) -> int:
"""Assign weights to layer.
Given a layer, this function retrieves the weights for that layer in an
appropriate format and order, and loads them into the layer. Additionally,
the number of weights loaded are returned.
If the weights are in an incorrect format, a ValueError
will be raised by set_weights().
Args:
layer: A `tf.keras.layers.Layer`.
Returns:
"""
weights = self.get_weights()
layer.set_weights(weights)
n_weights = 0
for w in weights:
n_weights += w.size
return n_weights
@dataclasses.dataclass
class Conv2DBNCFG(Config):
"""Config class for Conv2DBN block."""
weights_dict: Optional[Dict[str, np.ndarray]] = dataclasses.field(
repr=False, default=None)
weights: Optional[np.ndarray] = dataclasses.field(repr=False, default=None)
beta: Optional[np.ndarray] = dataclasses.field(repr=False, default=None)
gamma: Optional[np.ndarray] = dataclasses.field(repr=False, default=None)
moving_mean: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
moving_variance: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
def __post_init__(self):
conv_weights_dict = self.weights_dict['conv']
norm_weights_dict = self.weights_dict['norm']
self.weights = conv_weights_dict['kernel']
self.beta = norm_weights_dict['beta']
self.gamma = norm_weights_dict['gamma']
self.moving_mean = norm_weights_dict['moving_mean']
self.moving_variance = norm_weights_dict['moving_variance']
def get_weights(self):
return [
self.weights,
self.gamma,
self.beta,
self.moving_mean,
self.moving_variance
]
@dataclasses.dataclass
class ResidualBlockCFG(Config):
"""Config class for Residual block."""
weights_dict: Optional[Dict[str, np.ndarray]] = dataclasses.field(
repr=False, default=None)
skip_weights: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
skip_beta: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
skip_gamma: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
skip_moving_mean: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
skip_moving_variance: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
conv_weights: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
norm_beta: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
norm_gamma: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
norm_moving_mean: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
norm_moving_variance: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
conv_block_weights: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
conv_block_beta: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
conv_block_gamma: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
conv_block_moving_mean: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
conv_block_moving_variance: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
def __post_init__(self):
conv_weights_dict = self.weights_dict['conv']
norm_weights_dict = self.weights_dict['norm']
conv_block_weights_dict = self.weights_dict['conv_block']
if 'skip' in self.weights_dict:
skip_weights_dict = self.weights_dict['skip']
self.skip_weights = skip_weights_dict['conv']['kernel']
self.skip_beta = skip_weights_dict['norm']['beta']
self.skip_gamma = skip_weights_dict['norm']['gamma']
self.skip_moving_mean = skip_weights_dict['norm']['moving_mean']
self.skip_moving_variance = skip_weights_dict['norm']['moving_variance']
self.conv_weights = conv_weights_dict['kernel']
self.norm_beta = norm_weights_dict['beta']
self.norm_gamma = norm_weights_dict['gamma']
self.norm_moving_mean = norm_weights_dict['moving_mean']
self.norm_moving_variance = norm_weights_dict['moving_variance']
self.conv_block_weights = conv_block_weights_dict['conv']['kernel']
self.conv_block_beta = conv_block_weights_dict['norm']['beta']
self.conv_block_gamma = conv_block_weights_dict['norm']['gamma']
self.conv_block_moving_mean = conv_block_weights_dict['norm']['moving_mean']
self.conv_block_moving_variance = conv_block_weights_dict['norm'][
'moving_variance']
def get_weights(self):
weights = [
self.skip_weights,
self.skip_gamma,
self.skip_beta,
self.conv_block_weights,
self.conv_block_gamma,
self.conv_block_beta,
self.conv_weights,
self.norm_gamma,
self.norm_beta,
self.skip_moving_mean,
self.skip_moving_variance,
self.conv_block_moving_mean,
self.conv_block_moving_variance,
self.norm_moving_mean,
self.norm_moving_variance,
]
weights = [x for x in weights if x is not None]
return weights
@dataclasses.dataclass
class HeadConvCFG(Config):
"""Config class for HeadConv block."""
weights_dict: Optional[Dict[str, np.ndarray]] = dataclasses.field(
repr=False, default=None)
conv_1_weights: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
conv_1_bias: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
conv_2_weights: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
conv_2_bias: Optional[np.ndarray] = dataclasses.field(
repr=False, default=None)
def __post_init__(self):
conv_1_weights_dict = self.weights_dict['layer_with_weights-0']
conv_2_weights_dict = self.weights_dict['layer_with_weights-1']
self.conv_1_weights = conv_1_weights_dict['kernel']
self.conv_1_bias = conv_1_weights_dict['bias']
self.conv_2_weights = conv_2_weights_dict['kernel']
self.conv_2_bias = conv_2_weights_dict['bias']
def get_weights(self):
return [
self.conv_1_weights,
self.conv_1_bias,
self.conv_2_weights,
self.conv_2_bias
]
@dataclasses.dataclass
class HourglassCFG(Config):
"""Config class for Hourglass block."""
weights_dict: Optional[Dict[str, np.ndarray]] = dataclasses.field(
repr=False, default=None)
is_last_stage: bool = dataclasses.field(repr=False, default=None)
def __post_init__(self):
self.is_last_stage = False if 'inner_block' in self.weights_dict else True
def get_weights(self):
"""It is not used in this class."""
return None
def generate_block_weights(self, weights_dict):
"""Convert weights dict to blocks structure."""
reps = len(weights_dict.keys())
weights = []
n_weights = 0
for i in range(reps):
res_config = ResidualBlockCFG(weights_dict=weights_dict[str(i)])
res_weights = res_config.get_weights()
weights += res_weights
for w in res_weights:
n_weights += w.size
return weights, n_weights
def load_block_weights(self, layer, weight_dict):
block_weights, n_weights = self.generate_block_weights(weight_dict)
layer.set_weights(block_weights)
return n_weights
def load_weights(self, layer):
n_weights = 0
if not self.is_last_stage:
enc_dec_layers = [
layer.submodules[0],
layer.submodules[1],
layer.submodules[3]
]
enc_dec_weight_dicts = [
self.weights_dict['encoder_block1'],
self.weights_dict['encoder_block2'],
self.weights_dict['decoder_block']
]
for l, weights_dict in zip(enc_dec_layers, enc_dec_weight_dicts):
n_weights += self.load_block_weights(l, weights_dict)
if len(self.weights_dict['inner_block']) == 1:
# still in an outer hourglass
inner_weights_dict = self.weights_dict['inner_block']['0']
else:
# inner residual block chain
inner_weights_dict = self.weights_dict['inner_block']
inner_hg_layer = layer.submodules[2]
inner_hg_cfg = type(self)(weights_dict=inner_weights_dict)
n_weights += inner_hg_cfg.load_weights(inner_hg_layer)
else:
inner_layer = layer.submodules[0]
n_weights += self.load_block_weights(inner_layer, self.weights_dict)
return n_weights
| 9,665 | 31.436242 | 80 | py |
models | models-master/official/projects/centernet/modeling/centernet_model.py | # Copyright 2023 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.
"""Centernet detection models."""
from typing import Mapping, Union, Any
import tensorflow as tf
class CenterNetModel(tf.keras.Model):
"""CenterNet Model."""
def __init__(self,
backbone: tf.keras.Model,
head: tf.keras.Model,
detection_generator: tf.keras.layers.Layer,
**kwargs):
"""CenterNet Model.
Args:
backbone: a backbone network.
head: a projection head for centernet.
detection_generator: a detection generator for centernet.
**kwargs: keyword arguments to be passed.
"""
super(CenterNetModel, self).__init__(**kwargs)
# model components
self._backbone = backbone
self._detection_generator = detection_generator
self._head = head
def call(self, # pytype: disable=signature-mismatch # overriding-parameter-count-checks
inputs: tf.Tensor,
training: bool = None,
**kwargs) -> Mapping[str, tf.Tensor]:
features = self._backbone(inputs)
raw_outputs = self._head(features)
model_outputs = {'raw_output': raw_outputs}
if not training:
predictions = self._detection_generator(raw_outputs)
model_outputs.update(predictions)
return model_outputs
@property
def checkpoint_items(
self) -> Mapping[str, Union[tf.keras.Model, tf.keras.layers.Layer]]:
"""Returns a dictionary of items to be additionally checkpointed."""
items = dict(backbone=self.backbone, head=self.head)
return items
@property
def backbone(self):
return self._backbone
@property
def detection_generator(self):
return self._detection_generator
@property
def head(self):
return self._head
def get_config(self) -> Mapping[str, Any]:
config_dict = {
'backbone': self._backbone,
'head': self._head,
'detection_generator': self._detection_generator,
}
return config_dict
@classmethod
def from_config(cls, config, custom_objects=None):
return cls(**config)
| 2,616 | 29.08046 | 91 | py |
models | models-master/official/projects/centernet/modeling/centernet_model_test.py | # Copyright 2023 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.
"""Test for centernet detection model."""
from absl.testing import parameterized
import tensorflow as tf
from official.projects.centernet.configs import backbones
from official.projects.centernet.modeling import centernet_model
from official.projects.centernet.modeling.backbones import hourglass
from official.projects.centernet.modeling.heads import centernet_head
from official.projects.centernet.modeling.layers import detection_generator
from official.vision.configs import common
class CenterNetTest(parameterized.TestCase, tf.test.TestCase):
def testBuildCenterNet(self):
backbone = hourglass.build_hourglass(
input_specs=tf.keras.layers.InputSpec(shape=[None, 512, 512, 3]),
backbone_config=backbones.Backbone(type='hourglass'),
norm_activation_config=common.NormActivation(use_sync_bn=True)
)
task_config = {
'ct_heatmaps': 90,
'ct_offset': 2,
'ct_size': 2,
}
input_levels = ['2_0', '2']
head = centernet_head.CenterNetHead(
task_outputs=task_config,
input_specs=backbone.output_specs,
input_levels=input_levels)
detection_ge = detection_generator.CenterNetDetectionGenerator()
model = centernet_model.CenterNetModel(
backbone=backbone,
head=head,
detection_generator=detection_ge
)
outputs = model(tf.zeros((5, 512, 512, 3)))
self.assertLen(outputs['raw_output'], 3)
self.assertLen(outputs['raw_output']['ct_heatmaps'], 2)
self.assertLen(outputs['raw_output']['ct_offset'], 2)
self.assertLen(outputs['raw_output']['ct_size'], 2)
self.assertEqual(outputs['raw_output']['ct_heatmaps'][0].shape,
(5, 128, 128, 90))
self.assertEqual(outputs['raw_output']['ct_offset'][0].shape,
(5, 128, 128, 2))
self.assertEqual(outputs['raw_output']['ct_size'][0].shape,
(5, 128, 128, 2))
if __name__ == '__main__':
tf.test.main()
| 2,575 | 34.287671 | 75 | py |
models | models-master/official/projects/centernet/modeling/__init__.py | # Copyright 2023 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.
| 609 | 39.666667 | 74 | py |
models | models-master/official/projects/centernet/modeling/layers/detection_generator.py | # Copyright 2023 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.
"""Detection generator for centernet.
Parses predictions from the CenterNet head into the final bounding boxes,
confidences, and classes. This class contains repurposed methods from the
TensorFlow Object Detection API
in: https://github.com/tensorflow/models/blob/master/research/object_detection
/meta_architectures/center_net_meta_arch.py
"""
from typing import Any, Mapping
import tensorflow as tf
from official.projects.centernet.ops import loss_ops
from official.projects.centernet.ops import nms_ops
from official.vision.ops import box_ops
class CenterNetDetectionGenerator(tf.keras.layers.Layer):
"""CenterNet Detection Generator."""
def __init__(self,
input_image_dims: int = 512,
net_down_scale: int = 4,
max_detections: int = 100,
peak_error: float = 1e-6,
peak_extract_kernel_size: int = 3,
class_offset: int = 1,
use_nms: bool = False,
nms_pre_thresh: float = 0.1,
nms_thresh: float = 0.4,
**kwargs):
"""Initialize CenterNet Detection Generator.
Args:
input_image_dims: An `int` that specifies the input image size.
net_down_scale: An `int` that specifies stride of the output.
max_detections: An `int` specifying the maximum number of bounding
boxes generated. This is an upper bound, so the number of generated
boxes may be less than this due to thresholding/non-maximum suppression.
peak_error: A `float` for determining non-valid heatmap locations to mask.
peak_extract_kernel_size: An `int` indicating the kernel size used when
performing max-pool over the heatmaps to detect valid center locations
from its neighbors. From the paper, set this to 3 to detect valid.
locations that have responses greater than its 8-connected neighbors
class_offset: An `int` indicating to add an offset to the class
prediction if the dataset labels have been shifted.
use_nms: A `bool` for whether or not to use non-maximum suppression to
filter the bounding boxes.
nms_pre_thresh: A `float` for pre-nms threshold.
nms_thresh: A `float` for nms threshold.
**kwargs: Additional keyword arguments to be passed.
"""
super(CenterNetDetectionGenerator, self).__init__(**kwargs)
# Object center selection parameters
self._max_detections = max_detections
self._peak_error = peak_error
self._peak_extract_kernel_size = peak_extract_kernel_size
# Used for adjusting class prediction
self._class_offset = class_offset
# Box normalization parameters
self._net_down_scale = net_down_scale
self._input_image_dims = input_image_dims
self._use_nms = use_nms
self._nms_pre_thresh = nms_pre_thresh
self._nms_thresh = nms_thresh
def process_heatmap(self,
feature_map: tf.Tensor,
kernel_size: int) -> tf.Tensor:
"""Processes the heatmap into peaks for box selection.
Given a heatmap, this function first masks out nearby heatmap locations of
the same class using max-pooling such that, ideally, only one center for the
object remains. Then, center locations are masked according to their scores
in comparison to a threshold. NOTE: Repurposed from Google OD API.
Args:
feature_map: A Tensor with shape [batch_size, height, width, num_classes]
which is the center heatmap predictions.
kernel_size: An integer value for max-pool kernel size.
Returns:
A Tensor with the same shape as the input but with non-valid center
prediction locations masked out.
"""
feature_map = tf.math.sigmoid(feature_map)
if not kernel_size or kernel_size == 1:
feature_map_peaks = feature_map
else:
feature_map_max_pool = tf.nn.max_pool(
feature_map,
ksize=kernel_size,
strides=1,
padding='SAME')
feature_map_peak_mask = tf.math.abs(
feature_map - feature_map_max_pool) < self._peak_error
# Zero out everything that is not a peak.
feature_map_peaks = (
feature_map * tf.cast(feature_map_peak_mask, feature_map.dtype))
return feature_map_peaks
def get_top_k_peaks(self,
feature_map_peaks: tf.Tensor,
batch_size: int,
width: int,
num_classes: int,
k: int = 100):
"""Gets the scores and indices of the top-k peaks from the feature map.
This function flattens the feature map in order to retrieve the top-k
peaks, then computes the x, y, and class indices for those scores.
NOTE: Repurposed from Google OD API.
Args:
feature_map_peaks: A `Tensor` with shape [batch_size, height,
width, num_classes] which is the processed center heatmap peaks.
batch_size: An `int` that indicates the batch size of the input.
width: An `int` that indicates the width (and also height) of the input.
num_classes: An `int` for the number of possible classes. This is also
the channel depth of the input.
k: `int`` that controls how many peaks to select.
Returns:
top_scores: A Tensor with shape [batch_size, k] containing the top-k
scores.
y_indices: A Tensor with shape [batch_size, k] containing the top-k
y-indices corresponding to top_scores.
x_indices: A Tensor with shape [batch_size, k] containing the top-k
x-indices corresponding to top_scores.
channel_indices: A Tensor with shape [batch_size, k] containing the top-k
channel indices corresponding to top_scores.
"""
# Flatten the entire prediction per batch
feature_map_peaks_flat = tf.reshape(feature_map_peaks, [batch_size, -1])
# top_scores and top_indices have shape [batch_size, k]
top_scores, top_indices = tf.math.top_k(feature_map_peaks_flat, k=k)
# Get x, y and channel indices corresponding to the top indices in the flat
# array.
y_indices, x_indices, channel_indices = (
loss_ops.get_row_col_channel_indices_from_flattened_indices(
top_indices, width, num_classes))
return top_scores, y_indices, x_indices, channel_indices
def get_boxes(self,
y_indices: tf.Tensor,
x_indices: tf.Tensor,
channel_indices: tf.Tensor,
height_width_predictions: tf.Tensor,
offset_predictions: tf.Tensor,
num_boxes: int):
"""Organizes prediction information into the final bounding boxes.
NOTE: Repurposed from Google OD API.
Args:
y_indices: A Tensor with shape [batch_size, k] containing the top-k
y-indices corresponding to top_scores.
x_indices: A Tensor with shape [batch_size, k] containing the top-k
x-indices corresponding to top_scores.
channel_indices: A Tensor with shape [batch_size, k] containing the top-k
channel indices corresponding to top_scores.
height_width_predictions: A Tensor with shape [batch_size, height,
width, 2] containing the object size predictions.
offset_predictions: A Tensor with shape [batch_size, height, width, 2]
containing the object local offset predictions.
num_boxes: `int`, the number of boxes.
Returns:
boxes: A Tensor with shape [batch_size, num_boxes, 4] that contains the
bounding box coordinates in [y_min, x_min, y_max, x_max] format.
detection_classes: A Tensor with shape [batch_size, num_boxes] that
gives the class prediction for each box.
num_detections: Number of non-zero confidence detections made.
"""
# TF Lite does not support tf.gather with batch_dims > 0, so we need to use
# tf_gather_nd instead and here we prepare the indices for that.
# shapes of heatmap output
shape = tf.shape(height_width_predictions)
batch_size, height, width = shape[0], shape[1], shape[2]
# combined indices dtype=int32
combined_indices = tf.stack([
loss_ops.multi_range(batch_size, value_repetitions=num_boxes),
tf.reshape(y_indices, [-1]),
tf.reshape(x_indices, [-1])
], axis=1)
new_height_width = tf.gather_nd(height_width_predictions, combined_indices)
new_height_width = tf.reshape(new_height_width, [batch_size, num_boxes, 2])
height_width = tf.maximum(new_height_width, 0.0)
# height and widths dtype=float32
heights = height_width[..., 0]
widths = height_width[..., 1]
# Get the offsets of center points
new_offsets = tf.gather_nd(offset_predictions, combined_indices)
offsets = tf.reshape(new_offsets, [batch_size, num_boxes, 2])
# offsets are dtype=float32
y_offsets = offsets[..., 0]
x_offsets = offsets[..., 1]
y_indices = tf.cast(y_indices, dtype=heights.dtype)
x_indices = tf.cast(x_indices, dtype=widths.dtype)
detection_classes = channel_indices + self._class_offset
ymin = y_indices + y_offsets - heights / 2.0
xmin = x_indices + x_offsets - widths / 2.0
ymax = y_indices + y_offsets + heights / 2.0
xmax = x_indices + x_offsets + widths / 2.0
ymin = tf.clip_by_value(ymin, 0., tf.cast(height, ymin.dtype))
xmin = tf.clip_by_value(xmin, 0., tf.cast(width, xmin.dtype))
ymax = tf.clip_by_value(ymax, 0., tf.cast(height, ymax.dtype))
xmax = tf.clip_by_value(xmax, 0., tf.cast(width, xmax.dtype))
boxes = tf.stack([ymin, xmin, ymax, xmax], axis=2)
return boxes, detection_classes
def convert_strided_predictions_to_normalized_boxes(self, boxes: tf.Tensor):
boxes = boxes * tf.cast(self._net_down_scale, boxes.dtype)
boxes = boxes / tf.cast(self._input_image_dims, boxes.dtype)
boxes = tf.clip_by_value(boxes, 0.0, 1.0)
return boxes
def __call__(self, inputs):
# Get heatmaps from decoded outputs via final hourglass stack output
all_ct_heatmaps = inputs['ct_heatmaps']
all_ct_sizes = inputs['ct_size']
all_ct_offsets = inputs['ct_offset']
ct_heatmaps = all_ct_heatmaps[-1]
ct_sizes = all_ct_sizes[-1]
ct_offsets = all_ct_offsets[-1]
shape = tf.shape(ct_heatmaps)
_, width = shape[1], shape[2]
batch_size, num_channels = shape[0], shape[3]
# Process heatmaps using 3x3 max pool and applying sigmoid
peaks = self.process_heatmap(
feature_map=ct_heatmaps,
kernel_size=self._peak_extract_kernel_size)
# Get top scores along with their x, y, and class
# Each has size [batch_size, k]
scores, y_indices, x_indices, channel_indices = self.get_top_k_peaks(
feature_map_peaks=peaks,
batch_size=batch_size,
width=width,
num_classes=num_channels,
k=self._max_detections)
# Parse the score and indices into bounding boxes
boxes, classes = self.get_boxes(
y_indices=y_indices,
x_indices=x_indices,
channel_indices=channel_indices,
height_width_predictions=ct_sizes,
offset_predictions=ct_offsets,
num_boxes=self._max_detections)
# Normalize bounding boxes
boxes = self.convert_strided_predictions_to_normalized_boxes(boxes)
# Apply nms
if self._use_nms:
boxes = tf.expand_dims(boxes, axis=-2)
multi_class_scores = tf.gather_nd(
peaks, tf.stack([y_indices, x_indices], -1), batch_dims=1)
boxes, _, scores = nms_ops.nms(
boxes=boxes,
classes=multi_class_scores,
confidence=scores,
k=self._max_detections,
limit_pre_thresh=True,
pre_nms_thresh=0.1,
nms_thresh=0.4)
num_det = tf.reduce_sum(tf.cast(scores > 0, dtype=tf.int32), axis=1)
boxes = box_ops.denormalize_boxes(
boxes, [self._input_image_dims, self._input_image_dims])
return {
'boxes': boxes,
'classes': classes,
'confidence': scores,
'num_detections': num_det
}
def get_config(self) -> Mapping[str, Any]:
config = {
'max_detections': self._max_detections,
'peak_error': self._peak_error,
'peak_extract_kernel_size': self._peak_extract_kernel_size,
'class_offset': self._class_offset,
'net_down_scale': self._net_down_scale,
'input_image_dims': self._input_image_dims,
'use_nms': self._use_nms,
'nms_pre_thresh': self._nms_pre_thresh,
'nms_thresh': self._nms_thresh
}
base_config = super(CenterNetDetectionGenerator, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
@classmethod
def from_config(cls, config):
return cls(**config)
| 13,299 | 38.117647 | 80 | py |
models | models-master/official/projects/centernet/modeling/layers/cn_nn_blocks.py | # Copyright 2023 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.
"""Contains common building blocks for centernet neural networks."""
from typing import List, Optional
import tensorflow as tf
from official.vision.modeling.layers import nn_blocks
def _apply_blocks(inputs, blocks):
"""Apply blocks to inputs."""
net = inputs
for block in blocks:
net = block(net)
return net
def _make_repeated_residual_blocks(
reps: int,
out_channels: int,
use_sync_bn: bool = True,
norm_momentum: float = 0.1,
norm_epsilon: float = 1e-5,
residual_channels: Optional[int] = None,
initial_stride: int = 1,
initial_skip_conv: bool = False,
kernel_initializer: str = 'VarianceScaling',
kernel_regularizer: Optional[tf.keras.regularizers.Regularizer] = None,
bias_regularizer: Optional[tf.keras.regularizers.Regularizer] = None,
):
"""Stack Residual blocks one after the other.
Args:
reps: `int` for desired number of residual blocks
out_channels: `int`, filter depth of the final residual block
use_sync_bn: A `bool`, if True, use synchronized batch normalization.
norm_momentum: `float`, momentum for the batch normalization layers
norm_epsilon: `float`, epsilon for the batch normalization layers
residual_channels: `int`, filter depth for the first reps - 1 residual
blocks. If None, defaults to the same value as out_channels. If not
equal to out_channels, then uses a projection shortcut in the final
residual block
initial_stride: `int`, stride for the first residual block
initial_skip_conv: `bool`, if set, the first residual block uses a skip
convolution. This is useful when the number of channels in the input
are not the same as residual_channels.
kernel_initializer: A `str` for kernel initializer of convolutional layers.
kernel_regularizer: A `tf.keras.regularizers.Regularizer` object for
Conv2D. Default to None.
bias_regularizer: A `tf.keras.regularizers.Regularizer` object for Conv2D.
Default to None.
Returns:
blocks: A list of residual blocks to be applied in sequence.
"""
blocks = []
if residual_channels is None:
residual_channels = out_channels
for i in range(reps - 1):
# Only use the stride at the first block so we don't repeatedly downsample
# the input
stride = initial_stride if i == 0 else 1
# If the stride is more than 1, we cannot use an identity layer for the
# skip connection and are forced to use a conv for the skip connection.
skip_conv = stride > 1
if i == 0 and initial_skip_conv:
skip_conv = True
blocks.append(nn_blocks.ResidualBlock(
filters=residual_channels,
strides=stride,
use_explicit_padding=True,
use_projection=skip_conv,
use_sync_bn=use_sync_bn,
norm_momentum=norm_momentum,
norm_epsilon=norm_epsilon,
kernel_initializer=kernel_initializer,
kernel_regularizer=kernel_regularizer,
bias_regularizer=bias_regularizer))
if reps == 1:
# If there is only 1 block, the `for` loop above is not run,
# therefore we honor the requested stride in the last residual block
stride = initial_stride
# We are forced to use a conv in the skip connection if stride > 1
skip_conv = stride > 1
else:
stride = 1
skip_conv = residual_channels != out_channels
blocks.append(nn_blocks.ResidualBlock(
filters=out_channels,
strides=stride,
use_explicit_padding=True,
use_projection=skip_conv,
use_sync_bn=use_sync_bn,
norm_momentum=norm_momentum,
norm_epsilon=norm_epsilon,
kernel_initializer=kernel_initializer,
kernel_regularizer=kernel_regularizer,
bias_regularizer=bias_regularizer))
return tf.keras.Sequential(blocks)
class HourglassBlock(tf.keras.layers.Layer):
"""Hourglass module: an encoder-decoder block."""
def __init__(
self,
channel_dims_per_stage: List[int],
blocks_per_stage: List[int],
strides: int = 1,
use_sync_bn: bool = True,
norm_momentum: float = 0.1,
norm_epsilon: float = 1e-5,
kernel_initializer: str = 'VarianceScaling',
kernel_regularizer: Optional[tf.keras.regularizers.Regularizer] = None,
bias_regularizer: Optional[tf.keras.regularizers.Regularizer] = None,
**kwargs):
"""Initialize Hourglass module.
Args:
channel_dims_per_stage: List[int], list of filter sizes for Residual
blocks. the output channels dimensions of stages in
the network. `channel_dims[0]` is used to define the number of
channels in the first encoder block and `channel_dims[1]` is used to
define the number of channels in the second encoder block. The channels
in the recursive inner layers are defined using `channel_dims[1:]`.
For example, [nc * 2, nc * 2, nc * 3, nc * 3, nc * 3, nc*4]
where nc is the input_channel_dimension.
blocks_per_stage: List[int], list of residual block repetitions per
down/upsample. `blocks_per_stage[0]` defines the number of blocks at the
current stage and `blocks_per_stage[1:]` is used at further stages.
For example, [2, 2, 2, 2, 2, 4].
strides: `int`, stride parameter to the Residual block.
use_sync_bn: A `bool`, if True, use synchronized batch normalization.
norm_momentum: `float`, momentum for the batch normalization layers.
norm_epsilon: `float`, epsilon for the batch normalization layers.
kernel_initializer: A `str` for kernel initializer of conv layers.
kernel_regularizer: A `tf.keras.regularizers.Regularizer` object for
Conv2D. Default to None.
bias_regularizer: A `tf.keras.regularizers.Regularizer` object for Conv2D.
Default to None.
**kwargs: Additional keyword arguments to be passed.
"""
super(HourglassBlock, self).__init__(**kwargs)
if len(channel_dims_per_stage) != len(blocks_per_stage):
raise ValueError('filter size and residual block repetition '
'lists must have the same length')
self._num_stages = len(channel_dims_per_stage) - 1
self._channel_dims_per_stage = channel_dims_per_stage
self._blocks_per_stage = blocks_per_stage
self._strides = strides
self._use_sync_bn = use_sync_bn
self._norm_momentum = norm_momentum
self._norm_epsilon = norm_epsilon
self._kernel_initializer = kernel_initializer
self._kernel_regularizer = kernel_regularizer
self._bias_regularizer = bias_regularizer
self._filters = channel_dims_per_stage[0]
if self._num_stages > 0:
self._filters_downsampled = channel_dims_per_stage[1]
self._reps = blocks_per_stage[0]
def build(self, input_shape):
if self._num_stages == 0:
# base case, residual block repetitions in most inner part of hourglass
self.blocks = _make_repeated_residual_blocks(
reps=self._reps,
out_channels=self._filters,
use_sync_bn=self._use_sync_bn,
norm_momentum=self._norm_momentum,
norm_epsilon=self._norm_epsilon,
bias_regularizer=self._bias_regularizer,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer)
else:
# outer hourglass structures
self.encoder_block1 = _make_repeated_residual_blocks(
reps=self._reps,
out_channels=self._filters,
use_sync_bn=self._use_sync_bn,
norm_momentum=self._norm_momentum,
norm_epsilon=self._norm_epsilon,
bias_regularizer=self._bias_regularizer,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer)
self.encoder_block2 = _make_repeated_residual_blocks(
reps=self._reps,
out_channels=self._filters_downsampled,
initial_stride=2,
use_sync_bn=self._use_sync_bn,
norm_momentum=self._norm_momentum,
norm_epsilon=self._norm_epsilon,
bias_regularizer=self._bias_regularizer,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer,
initial_skip_conv=self._filters != self._filters_downsampled)
# recursively define inner hourglasses
self.inner_hg = type(self)(
channel_dims_per_stage=self._channel_dims_per_stage[1:],
blocks_per_stage=self._blocks_per_stage[1:],
strides=self._strides)
# outer hourglass structures
self.decoder_block = _make_repeated_residual_blocks(
reps=self._reps,
residual_channels=self._filters_downsampled,
out_channels=self._filters,
use_sync_bn=self._use_sync_bn,
norm_epsilon=self._norm_epsilon,
bias_regularizer=self._bias_regularizer,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer)
self.upsample_layer = tf.keras.layers.UpSampling2D(
size=2,
interpolation='nearest')
super(HourglassBlock, self).build(input_shape)
def call(self, x, training=None):
if self._num_stages == 0:
return self.blocks(x)
else:
encoded_outputs = self.encoder_block1(x)
encoded_downsampled_outputs = self.encoder_block2(x)
inner_outputs = self.inner_hg(encoded_downsampled_outputs)
hg_output = self.decoder_block(inner_outputs)
return self.upsample_layer(hg_output) + encoded_outputs
def get_config(self):
config = {
'channel_dims_per_stage': self._channel_dims_per_stage,
'blocks_per_stage': self._blocks_per_stage,
'strides': self._strides,
'use_sync_bn': self._use_sync_bn,
'norm_momentum': self._norm_momentum,
'norm_epsilon': self._norm_epsilon,
'kernel_initializer': self._kernel_initializer,
'kernel_regularizer': self._kernel_regularizer,
'bias_regularizer': self._bias_regularizer,
}
config.update(super(HourglassBlock, self).get_config())
return config
class CenterNetHeadConv(tf.keras.layers.Layer):
"""Convolution block for the CenterNet head."""
def __init__(self,
output_filters: int,
bias_init: float,
name: str,
**kwargs):
"""Initialize CenterNet head.
Args:
output_filters: `int`, channel depth of layer output
bias_init: `float`, value to initialize the bias vector for the final
convolution layer
name: `string`, layer name
**kwargs: Additional keyword arguments to be passed.
"""
super(CenterNetHeadConv, self).__init__(name=name, **kwargs)
self._output_filters = output_filters
self._bias_init = bias_init
def build(self, input_shape):
n_channels = input_shape[-1]
self.conv1 = tf.keras.layers.Conv2D(
filters=n_channels,
kernel_size=(3, 3),
padding='same')
self.relu = tf.keras.layers.ReLU()
# Initialize bias to the last Conv2D Layer
self.conv2 = tf.keras.layers.Conv2D(
filters=self._output_filters,
kernel_size=(1, 1),
padding='valid',
bias_initializer=tf.constant_initializer(self._bias_init))
super(CenterNetHeadConv, self).build(input_shape)
def call(self, x, training=None):
x = self.conv1(x)
x = self.relu(x)
x = self.conv2(x)
return x
def get_config(self):
config = {
'output_filters': self._output_filters,
'bias_init': self._bias_init,
}
config.update(super(CenterNetHeadConv, self).get_config())
return config
| 12,200 | 36.198171 | 80 | py |
models | models-master/official/projects/centernet/modeling/layers/__init__.py | # Copyright 2023 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.
| 609 | 39.666667 | 74 | py |
models | models-master/official/projects/centernet/modeling/layers/cn_nn_blocks_test.py | # Copyright 2023 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.
"""Tests for Centernet nn_blocks.
It is a literal translation of the PyTorch implementation.
"""
from absl.testing import parameterized
import numpy as np
import tensorflow as tf
from official.projects.centernet.modeling.layers import cn_nn_blocks
from official.vision.modeling.layers import nn_blocks
class HourglassBlockPyTorch(tf.keras.layers.Layer):
"""An CornerNet-style implementation of the hourglass block."""
def __init__(self, dims, modules, k=0, **kwargs):
"""An CornerNet-style implementation of the hourglass block.
Args:
dims: input sizes of residual blocks
modules: number of repetitions of the residual blocks in each hourglass
upsampling and downsampling
k: recursive parameter
**kwargs: Additional keyword arguments to be passed.
"""
super(HourglassBlockPyTorch).__init__()
if len(dims) != len(modules):
raise ValueError('dims and modules lists must have the same length')
self.n = len(dims) - 1
self.k = k
self.modules = modules
self.dims = dims
self._kwargs = kwargs
def build(self, input_shape):
modules = self.modules
dims = self.dims
k = self.k
kwargs = self._kwargs
curr_mod = modules[k]
next_mod = modules[k + 1]
curr_dim = dims[k + 0]
next_dim = dims[k + 1]
self.up1 = self.make_up_layer(3, curr_dim, curr_dim, curr_mod, **kwargs)
self.max1 = tf.keras.layers.MaxPool2D(strides=2)
self.low1 = self.make_hg_layer(3, curr_dim, next_dim, curr_mod, **kwargs)
if self.n - k > 1:
self.low2 = type(self)(dims, modules, k=k + 1, **kwargs)
else:
self.low2 = self.make_low_layer(
3, next_dim, next_dim, next_mod, **kwargs)
self.low3 = self.make_hg_layer_revr(
3, next_dim, curr_dim, curr_mod, **kwargs)
self.up2 = tf.keras.layers.UpSampling2D(2)
self.merge = tf.keras.layers.Add()
super(HourglassBlockPyTorch, self).build(input_shape)
def call(self, x):
up1 = self.up1(x)
max1 = self.max1(x)
low1 = self.low1(max1)
low2 = self.low2(low1)
low3 = self.low3(low2)
up2 = self.up2(low3)
return self.merge([up1, up2])
def make_layer(self, k, inp_dim, out_dim, modules, **kwargs):
layers = [
nn_blocks.ResidualBlock(out_dim, 1, use_projection=True, **kwargs)]
for _ in range(1, modules):
layers.append(nn_blocks.ResidualBlock(out_dim, 1, **kwargs))
return tf.keras.Sequential(layers)
def make_layer_revr(self, k, inp_dim, out_dim, modules, **kwargs):
layers = []
for _ in range(modules - 1):
layers.append(
nn_blocks.ResidualBlock(inp_dim, 1, **kwargs))
layers.append(
nn_blocks.ResidualBlock(out_dim, 1, use_projection=True, **kwargs))
return tf.keras.Sequential(layers)
def make_up_layer(self, k, inp_dim, out_dim, modules, **kwargs):
return self.make_layer(k, inp_dim, out_dim, modules, **kwargs)
def make_low_layer(self, k, inp_dim, out_dim, modules, **kwargs):
return self.make_layer(k, inp_dim, out_dim, modules, **kwargs)
def make_hg_layer(self, k, inp_dim, out_dim, modules, **kwargs):
return self.make_layer(k, inp_dim, out_dim, modules, **kwargs)
def make_hg_layer_revr(self, k, inp_dim, out_dim, modules, **kwargs):
return self.make_layer_revr(k, inp_dim, out_dim, modules, **kwargs)
class NNBlocksTest(parameterized.TestCase, tf.test.TestCase):
def test_hourglass_block(self):
dims = [256, 256, 384, 384, 384, 512]
modules = [2, 2, 2, 2, 2, 4]
model = cn_nn_blocks.HourglassBlock(dims, modules)
test_input = tf.keras.Input((512, 512, 256))
_ = model(test_input)
filter_sizes = [256, 256, 384, 384, 384, 512]
rep_sizes = [2, 2, 2, 2, 2, 4]
hg_test_input_shape = (1, 512, 512, 256)
# bb_test_input_shape = (1, 512, 512, 3)
x_hg = tf.ones(shape=hg_test_input_shape)
# x_bb = tf.ones(shape=bb_test_input_shape)
hg = cn_nn_blocks.HourglassBlock(
channel_dims_per_stage=filter_sizes,
blocks_per_stage=rep_sizes)
hg.build(input_shape=hg_test_input_shape)
out = hg(x_hg)
self.assertAllEqual(
tf.shape(out), hg_test_input_shape,
'Hourglass module output shape and expected shape differ')
# ODAPI Test
layer = cn_nn_blocks.HourglassBlock(
blocks_per_stage=[2, 3, 4, 5, 6],
channel_dims_per_stage=[4, 6, 8, 10, 12])
output = layer(np.zeros((2, 64, 64, 4), dtype=np.float32))
self.assertEqual(output.shape, (2, 64, 64, 4))
if __name__ == '__main__':
tf.test.main()
| 5,148 | 32.219355 | 77 | py |
models | models-master/official/projects/centernet/modeling/backbones/__init__.py | # Copyright 2023 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.
| 609 | 39.666667 | 74 | py |
models | models-master/official/projects/centernet/modeling/backbones/hourglass.py | # Copyright 2023 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.
"""Build Hourglass backbone."""
from typing import Optional
import tensorflow as tf
from official.modeling import hyperparams
from official.projects.centernet.modeling.layers import cn_nn_blocks
from official.vision.modeling.backbones import factory
from official.vision.modeling.backbones import mobilenet
from official.vision.modeling.layers import nn_blocks
HOURGLASS_SPECS = {
10: {
'blocks_per_stage': [1, 1],
'channel_dims_per_stage': [2, 2]
},
20: {
'blocks_per_stage': [1, 2, 2],
'channel_dims_per_stage': [2, 2, 3]
},
32: {
'blocks_per_stage': [2, 2, 2, 2],
'channel_dims_per_stage': [2, 2, 3, 3]
},
52: {
'blocks_per_stage': [2, 2, 2, 2, 2, 4],
'channel_dims_per_stage': [2, 2, 3, 3, 3, 4]
},
100: {
'blocks_per_stage': [4, 4, 4, 4, 4, 8],
'channel_dims_per_stage': [2, 2, 3, 3, 3, 4]
},
}
class Hourglass(tf.keras.Model):
"""CenterNet Hourglass backbone."""
def __init__(
self,
model_id: int,
input_channel_dims: int,
input_specs=tf.keras.layers.InputSpec(shape=[None, None, None, 3]),
num_hourglasses: int = 1,
initial_downsample: bool = True,
activation: str = 'relu',
use_sync_bn: bool = True,
norm_momentum=0.1,
norm_epsilon=1e-5,
kernel_initializer: str = 'VarianceScaling',
kernel_regularizer: Optional[tf.keras.regularizers.Regularizer] = None,
bias_regularizer: Optional[tf.keras.regularizers.Regularizer] = None,
**kwargs):
"""Initialize Hourglass backbone.
Args:
model_id: An `int` of the scale of Hourglass backbone model.
input_channel_dims: `int`, number of filters used to downsample the
input image.
input_specs: A `tf.keras.layers.InputSpec` of specs of the input tensor.
num_hourglasses: `int``, number of hourglass blocks in backbone. For
example, hourglass-104 has two hourglass-52 modules.
initial_downsample: `bool`, whether or not to downsample the input.
activation: A `str` name of the activation function.
use_sync_bn: If True, use synchronized batch normalization.
norm_momentum: `float`, momentum for the batch normalization layers.
norm_epsilon: `float`, epsilon for the batch normalization layers.
kernel_initializer: A `str` for kernel initializer of conv layers.
kernel_regularizer: A `tf.keras.regularizers.Regularizer` object for
Conv2D. Default to None.
bias_regularizer: A `tf.keras.regularizers.Regularizer` object for Conv2D.
Default to None.
**kwargs: Additional keyword arguments to be passed.
"""
self._input_channel_dims = input_channel_dims
self._model_id = model_id
self._num_hourglasses = num_hourglasses
self._initial_downsample = initial_downsample
self._activation = activation
self._kernel_initializer = kernel_initializer
self._kernel_regularizer = kernel_regularizer
self._bias_regularizer = bias_regularizer
self._use_sync_bn = use_sync_bn
self._norm_momentum = norm_momentum
self._norm_epsilon = norm_epsilon
specs = HOURGLASS_SPECS[model_id]
self._blocks_per_stage = specs['blocks_per_stage']
self._channel_dims_per_stage = [item * self._input_channel_dims
for item in specs['channel_dims_per_stage']]
inputs = tf.keras.layers.Input(shape=input_specs.shape[1:])
inp_filters = self._channel_dims_per_stage[0]
# Downsample the input
if initial_downsample:
prelayer_kernel_size = 7
prelayer_strides = 2
else:
prelayer_kernel_size = 3
prelayer_strides = 1
x_downsampled = mobilenet.Conv2DBNBlock(
filters=self._input_channel_dims,
kernel_size=prelayer_kernel_size,
strides=prelayer_strides,
use_explicit_padding=True,
activation=self._activation,
bias_regularizer=self._bias_regularizer,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer,
use_sync_bn=self._use_sync_bn,
norm_momentum=self._norm_momentum,
norm_epsilon=self._norm_epsilon)(inputs)
x_downsampled = nn_blocks.ResidualBlock(
filters=inp_filters,
use_projection=True,
use_explicit_padding=True,
strides=prelayer_strides,
bias_regularizer=self._bias_regularizer,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer,
use_sync_bn=self._use_sync_bn,
norm_momentum=self._norm_momentum,
norm_epsilon=self._norm_epsilon)(x_downsampled)
all_heatmaps = {}
for i in range(num_hourglasses):
# Create an hourglass stack
x_hg = cn_nn_blocks.HourglassBlock(
channel_dims_per_stage=self._channel_dims_per_stage,
blocks_per_stage=self._blocks_per_stage,
)(x_downsampled)
x_hg = mobilenet.Conv2DBNBlock(
filters=inp_filters,
kernel_size=3,
strides=1,
use_explicit_padding=True,
activation=self._activation,
bias_regularizer=self._bias_regularizer,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer,
use_sync_bn=self._use_sync_bn,
norm_momentum=self._norm_momentum,
norm_epsilon=self._norm_epsilon
)(x_hg)
# Given two down-sampling blocks above, the starting level is set to 2
# To make it compatible with implementation of remaining backbones, the
# output of hourglass backbones is organized as
# '2' -> the last layer of output
# '2_0' -> the first layer of output
# ......
# '2_{num_hourglasses-2}' -> the second to last layer of output
if i < num_hourglasses - 1:
all_heatmaps['2_{}'.format(i)] = x_hg
else:
all_heatmaps['2'] = x_hg
# Intermediate conv and residual layers between hourglasses
if i < num_hourglasses - 1:
inter_hg_conv1 = mobilenet.Conv2DBNBlock(
filters=inp_filters,
kernel_size=1,
strides=1,
activation='identity',
bias_regularizer=self._bias_regularizer,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer,
use_sync_bn=self._use_sync_bn,
norm_momentum=self._norm_momentum,
norm_epsilon=self._norm_epsilon
)(x_downsampled)
inter_hg_conv2 = mobilenet.Conv2DBNBlock(
filters=inp_filters,
kernel_size=1,
strides=1,
activation='identity',
bias_regularizer=self._bias_regularizer,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer,
use_sync_bn=self._use_sync_bn,
norm_momentum=self._norm_momentum,
norm_epsilon=self._norm_epsilon
)(x_hg)
x_downsampled = tf.keras.layers.Add()([inter_hg_conv1, inter_hg_conv2])
x_downsampled = tf.keras.layers.ReLU()(x_downsampled)
x_downsampled = nn_blocks.ResidualBlock(
filters=inp_filters,
use_projection=False,
use_explicit_padding=True,
strides=1,
bias_regularizer=self._bias_regularizer,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer,
use_sync_bn=self._use_sync_bn,
norm_momentum=self._norm_momentum,
norm_epsilon=self._norm_epsilon
)(x_downsampled)
self._output_specs = {l: all_heatmaps[l].get_shape() for l in all_heatmaps}
super().__init__(inputs=inputs, outputs=all_heatmaps, **kwargs)
def get_config(self):
config = {
'model_id': self._model_id,
'input_channel_dims': self._input_channel_dims,
'num_hourglasses': self._num_hourglasses,
'initial_downsample': self._initial_downsample,
'kernel_initializer': self._kernel_initializer,
'kernel_regularizer': self._kernel_regularizer,
'bias_regularizer': self._bias_regularizer,
'use_sync_bn': self._use_sync_bn,
'norm_momentum': self._norm_momentum,
'norm_epsilon': self._norm_epsilon
}
config.update(super(Hourglass, self).get_config())
return config
@property
def num_hourglasses(self):
return self._num_hourglasses
@property
def output_specs(self):
return self._output_specs
@factory.register_backbone_builder('hourglass')
def build_hourglass(
input_specs: tf.keras.layers.InputSpec,
backbone_config: hyperparams.Config,
norm_activation_config: hyperparams.Config,
l2_regularizer: Optional[tf.keras.regularizers.Regularizer] = None
) -> tf.keras.Model:
"""Builds Hourglass backbone from a configuration."""
backbone_type = backbone_config.type
backbone_cfg = backbone_config.get()
assert backbone_type == 'hourglass', (f'Inconsistent backbone type '
f'{backbone_type}')
return Hourglass(
model_id=backbone_cfg.model_id,
input_channel_dims=backbone_cfg.input_channel_dims,
num_hourglasses=backbone_cfg.num_hourglasses,
input_specs=input_specs,
initial_downsample=backbone_cfg.initial_downsample,
activation=norm_activation_config.activation,
use_sync_bn=norm_activation_config.use_sync_bn,
norm_momentum=norm_activation_config.norm_momentum,
norm_epsilon=norm_activation_config.norm_epsilon,
kernel_regularizer=l2_regularizer,
)
| 10,285 | 36.268116 | 80 | py |
models | models-master/official/projects/centernet/modeling/backbones/hourglass_test.py | # Copyright 2023 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.
"""Tests for hourglass module."""
from absl.testing import parameterized
import numpy as np
import tensorflow as tf
from official.projects.centernet.common import registry_imports # pylint: disable=unused-import
from official.projects.centernet.configs import backbones
from official.projects.centernet.modeling.backbones import hourglass
from official.vision.configs import common
class HourglassTest(tf.test.TestCase, parameterized.TestCase):
def test_hourglass(self):
backbone = hourglass.build_hourglass(
input_specs=tf.keras.layers.InputSpec(shape=[None, 512, 512, 3]),
backbone_config=backbones.Backbone(type='hourglass'),
norm_activation_config=common.NormActivation(use_sync_bn=True)
)
inputs = np.zeros((2, 512, 512, 3), dtype=np.float32)
outputs = backbone(inputs)
self.assertEqual(outputs['2_0'].shape, (2, 128, 128, 256))
self.assertEqual(outputs['2'].shape, (2, 128, 128, 256))
if __name__ == '__main__':
tf.test.main()
| 1,602 | 36.27907 | 96 | py |
models | models-master/official/projects/centernet/modeling/heads/centernet_head_test.py | # Copyright 2023 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.
"""Tests for Centernet Head."""
from absl.testing import parameterized
import numpy as np
import tensorflow as tf
from official.projects.centernet.modeling.heads import centernet_head
class CenterNetHeadTest(tf.test.TestCase, parameterized.TestCase):
def test_decoder_shape(self):
task_config = {
'ct_heatmaps': 90,
'ct_offset': 2,
'ct_size': 2,
}
input_specs = {
'2_0': tf.keras.layers.InputSpec(shape=(None, 128, 128, 256)).shape,
'2': tf.keras.layers.InputSpec(shape=(None, 128, 128, 256)).shape,
}
input_levels = ['2', '2_0']
head = centernet_head.CenterNetHead(
task_outputs=task_config,
input_specs=input_specs,
input_levels=input_levels)
config = head.get_config()
self.assertEqual(config['heatmap_bias'], -2.19)
# Output shape tests
outputs = head([np.zeros((2, 128, 128, 256), dtype=np.float32),
np.zeros((2, 128, 128, 256), dtype=np.float32)])
self.assertLen(outputs, 3)
self.assertEqual(outputs['ct_heatmaps'][0].shape, (2, 128, 128, 90))
self.assertEqual(outputs['ct_offset'][0].shape, (2, 128, 128, 2))
self.assertEqual(outputs['ct_size'][0].shape, (2, 128, 128, 2))
# Weight initialization tests
hm_bias_vector = np.asarray(head.layers[2].weights[-1])
off_bias_vector = np.asarray(head.layers[4].weights[-1])
size_bias_vector = np.asarray(head.layers[6].weights[-1])
self.assertArrayNear(hm_bias_vector,
np.repeat(-2.19, repeats=90), err=1.00e-6)
self.assertArrayNear(off_bias_vector,
np.repeat(0, repeats=2), err=1.00e-6)
self.assertArrayNear(size_bias_vector,
np.repeat(0, repeats=2), err=1.00e-6)
if __name__ == '__main__':
tf.test.main()
| 2,425 | 33.657143 | 76 | py |
models | models-master/official/projects/centernet/modeling/heads/centernet_head.py | # Copyright 2023 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.
"""Contains the definitions of head for CenterNet."""
from typing import Any, Dict, List, Mapping
import tensorflow as tf
from official.projects.centernet.modeling.layers import cn_nn_blocks
class CenterNetHead(tf.keras.Model):
"""CenterNet Head."""
def __init__(self,
input_specs: Dict[str, tf.TensorShape],
task_outputs: Mapping[str, int],
input_levels: List[str],
heatmap_bias: float = -2.19,
**kwargs):
"""CenterNet Head Initialization.
Args:
input_specs: A `dict` of input specifications.
task_outputs: A `dict`, with key-value pairs denoting the names of the
outputs and the desired channel depth of each output.
input_levels: list of str representing the level used as input to the
CenternetHead from the backbone. For example, ['2_0', '2'] should be
set for hourglass-104 has two hourglass-52 modules, since the output
of hourglass backbones is organized as:
'2' -> the last layer of output
'2_0' -> the first layer of output
......
'2_{num_hourglasses-2}' -> the second to last layer of output.
heatmap_bias: `float`, constant value to initialize the convolution layer
bias vector if it is responsible for generating a heatmap (not for
regressed predictions).
**kwargs: Additional keyword arguments to be passed.
Returns:
dictionary where the keys-value pairs denote the names of the output
and the respective output tensor
"""
assert input_levels, f'Please specify input levels: {input_levels}'
self._input_specs = input_specs
self._task_outputs = task_outputs
self._input_levels = input_levels
self._heatmap_bias = heatmap_bias
self._num_inputs = len(input_levels)
inputs = {level: tf.keras.layers.Input(shape=self._input_specs[level][1:])
for level in input_levels}
outputs = {}
for key in self._task_outputs:
# pylint: disable=g-complex-comprehension
outputs[key] = [
cn_nn_blocks.CenterNetHeadConv(
output_filters=self._task_outputs[key],
bias_init=self._heatmap_bias if 'heatmaps' in key else 0,
name=key + str(i),
)(inputs[i])
for i in input_levels
]
self._output_specs = {
key: [value[i].get_shape() for i in range(self._num_inputs)]
for key, value in outputs.items()
}
super().__init__(inputs=inputs, outputs=outputs,
name='CenterNetHead', **kwargs)
def get_config(self) -> Mapping[str, Any]:
config = {
'input_spec': self._input_specs,
'task_outputs': self._task_outputs,
'heatmap_bias': self._heatmap_bias,
'input_levels': self._input_levels,
}
base_config = super(CenterNetHead, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
@classmethod
def from_config(cls, config, custom_objects=None):
return cls(**config)
@property
def output_specs(self) -> Mapping[str, tf.TensorShape]:
"""A dict of {level: TensorShape} pairs for the model output."""
return self._output_specs
| 3,833 | 35.169811 | 79 | py |
models | models-master/official/projects/centernet/modeling/heads/__init__.py | # Copyright 2023 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.
| 609 | 39.666667 | 74 | py |
models | models-master/official/projects/centernet/tasks/centernet.py | # Copyright 2023 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.
"""Centernet task definition."""
from typing import Any, List, Optional, Tuple
from absl import logging
import tensorflow as tf
from official.core import base_task
from official.core import input_reader
from official.core import task_factory
from official.projects.centernet.configs import centernet as exp_cfg
from official.projects.centernet.dataloaders import centernet_input
from official.projects.centernet.losses import centernet_losses
from official.projects.centernet.modeling import centernet_model
from official.projects.centernet.modeling.heads import centernet_head
from official.projects.centernet.modeling.layers import detection_generator
from official.projects.centernet.ops import loss_ops
from official.projects.centernet.ops import target_assigner
from official.vision.dataloaders import tf_example_decoder
from official.vision.dataloaders import tfds_factory
from official.vision.dataloaders import tf_example_label_map_decoder
from official.vision.evaluation import coco_evaluator
from official.vision.modeling.backbones import factory
@task_factory.register_task_cls(exp_cfg.CenterNetTask)
class CenterNetTask(base_task.Task):
"""Task definition for centernet."""
def build_inputs(self,
params: exp_cfg.DataConfig,
input_context: Optional[tf.distribute.InputContext] = None):
"""Build input dataset."""
if params.tfds_name:
decoder = tfds_factory.get_detection_decoder(params.tfds_name)
else:
decoder_cfg = params.decoder.get()
if params.decoder.type == 'simple_decoder':
decoder = tf_example_decoder.TfExampleDecoder(
regenerate_source_id=decoder_cfg.regenerate_source_id)
elif params.decoder.type == 'label_map_decoder':
decoder = tf_example_label_map_decoder.TfExampleDecoderLabelMap(
label_map=decoder_cfg.label_map,
regenerate_source_id=decoder_cfg.regenerate_source_id)
else:
raise ValueError('Unknown decoder type: {}!'.format(
params.decoder.type))
parser = centernet_input.CenterNetParser(
output_height=self.task_config.model.input_size[0],
output_width=self.task_config.model.input_size[1],
max_num_instances=self.task_config.model.max_num_instances,
bgr_ordering=params.parser.bgr_ordering,
channel_means=params.parser.channel_means,
channel_stds=params.parser.channel_stds,
aug_rand_hflip=params.parser.aug_rand_hflip,
aug_scale_min=params.parser.aug_scale_min,
aug_scale_max=params.parser.aug_scale_max,
aug_rand_hue=params.parser.aug_rand_hue,
aug_rand_brightness=params.parser.aug_rand_brightness,
aug_rand_contrast=params.parser.aug_rand_contrast,
aug_rand_saturation=params.parser.aug_rand_saturation,
odapi_augmentation=params.parser.odapi_augmentation,
dtype=params.dtype)
reader = input_reader.InputReader(
params,
dataset_fn=tf.data.TFRecordDataset,
decoder_fn=decoder.decode,
parser_fn=parser.parse_fn(params.is_training))
dataset = reader.read(input_context=input_context)
return dataset
def build_model(self):
"""get an instance of CenterNet."""
model_config = self.task_config.model
input_specs = tf.keras.layers.InputSpec(
shape=[None] + model_config.input_size)
l2_weight_decay = self.task_config.weight_decay
# Divide weight decay by 2.0 to match the implementation of tf.nn.l2_loss.
# (https://www.tensorflow.org/api_docs/python/tf/keras/regularizers/l2)
# (https://www.tensorflow.org/api_docs/python/tf/nn/l2_loss)
l2_regularizer = (tf.keras.regularizers.l2(
l2_weight_decay / 2.0) if l2_weight_decay else None)
backbone = factory.build_backbone(
input_specs=input_specs,
backbone_config=model_config.backbone,
norm_activation_config=model_config.norm_activation,
l2_regularizer=l2_regularizer)
task_outputs = self.task_config.get_output_length_dict()
head_config = model_config.head
head = centernet_head.CenterNetHead(
input_specs=backbone.output_specs,
task_outputs=task_outputs,
input_levels=head_config.input_levels,
heatmap_bias=head_config.heatmap_bias)
# output_specs is a dict
backbone_output_spec = backbone.output_specs[head_config.input_levels[-1]]
if len(backbone_output_spec) == 4:
bb_output_height = backbone_output_spec[1]
elif len(backbone_output_spec) == 3:
bb_output_height = backbone_output_spec[0]
else:
raise ValueError
self._net_down_scale = int(model_config.input_size[0] / bb_output_height)
dg_config = model_config.detection_generator
detect_generator_obj = detection_generator.CenterNetDetectionGenerator(
max_detections=dg_config.max_detections,
peak_error=dg_config.peak_error,
peak_extract_kernel_size=dg_config.peak_extract_kernel_size,
class_offset=dg_config.class_offset,
net_down_scale=self._net_down_scale,
input_image_dims=model_config.input_size[0],
use_nms=dg_config.use_nms,
nms_pre_thresh=dg_config.nms_pre_thresh,
nms_thresh=dg_config.nms_thresh)
model = centernet_model.CenterNetModel(
backbone=backbone,
head=head,
detection_generator=detect_generator_obj)
return model
def initialize(self, model: tf.keras.Model):
"""Loading pretrained checkpoint."""
if not self.task_config.init_checkpoint:
return
ckpt_dir_or_file = self.task_config.init_checkpoint
# Restoring checkpoint.
if tf.io.gfile.isdir(ckpt_dir_or_file):
ckpt_dir_or_file = tf.train.latest_checkpoint(ckpt_dir_or_file)
if self.task_config.init_checkpoint_modules == 'all':
ckpt = tf.train.Checkpoint(**model.checkpoint_items)
status = ckpt.restore(ckpt_dir_or_file)
status.assert_consumed()
elif self.task_config.init_checkpoint_modules == 'backbone':
ckpt = tf.train.Checkpoint(backbone=model.backbone)
status = ckpt.restore(ckpt_dir_or_file)
status.expect_partial().assert_existing_objects_matched()
else:
raise ValueError(
"Only 'all' or 'backbone' can be used to initialize the model.")
logging.info('Finished loading pretrained checkpoint from %s',
ckpt_dir_or_file)
def build_losses(self,
outputs,
labels,
aux_losses=None):
"""Build losses."""
input_size = self.task_config.model.input_size[0:2]
output_size = outputs['ct_heatmaps'][0].get_shape().as_list()[1:3]
gt_label = tf.map_fn(
# pylint: disable=g-long-lambda
fn=lambda x: target_assigner.assign_centernet_targets(
labels=x,
input_size=input_size,
output_size=output_size,
num_classes=self.task_config.model.num_classes,
max_num_instances=self.task_config.model.max_num_instances,
gaussian_iou=self.task_config.losses.gaussian_iou,
class_offset=self.task_config.losses.class_offset),
elems=labels,
fn_output_signature={
'ct_heatmaps': tf.TensorSpec(
shape=[output_size[0], output_size[1],
self.task_config.model.num_classes],
dtype=tf.float32),
'ct_offset': tf.TensorSpec(
shape=[self.task_config.model.max_num_instances, 2],
dtype=tf.float32),
'size': tf.TensorSpec(
shape=[self.task_config.model.max_num_instances, 2],
dtype=tf.float32),
'box_mask': tf.TensorSpec(
shape=[self.task_config.model.max_num_instances],
dtype=tf.int32),
'box_indices': tf.TensorSpec(
shape=[self.task_config.model.max_num_instances, 2],
dtype=tf.int32),
}
)
losses = {}
# Create loss functions
object_center_loss_fn = centernet_losses.PenaltyReducedLogisticFocalLoss()
localization_loss_fn = centernet_losses.L1LocalizationLoss()
# Set up box indices so that they have a batch element as well
box_indices = loss_ops.add_batch_to_indices(gt_label['box_indices'])
box_mask = tf.cast(gt_label['box_mask'], dtype=tf.float32)
num_boxes = tf.cast(
loss_ops.get_num_instances_from_weights(gt_label['box_mask']),
dtype=tf.float32)
# Calculate center heatmap loss
output_unpad_image_shapes = tf.math.ceil(
tf.cast(labels['unpad_image_shapes'],
tf.float32) / self._net_down_scale)
valid_anchor_weights = loss_ops.get_valid_anchor_weights_in_flattened_image(
output_unpad_image_shapes, output_size[0], output_size[1])
valid_anchor_weights = tf.expand_dims(valid_anchor_weights, 2)
pred_ct_heatmap_list = outputs['ct_heatmaps']
true_flattened_ct_heatmap = loss_ops.flatten_spatial_dimensions(
gt_label['ct_heatmaps'])
true_flattened_ct_heatmap = tf.cast(true_flattened_ct_heatmap, tf.float32)
total_center_loss = 0.0
for ct_heatmap in pred_ct_heatmap_list:
pred_flattened_ct_heatmap = loss_ops.flatten_spatial_dimensions(
ct_heatmap)
pred_flattened_ct_heatmap = tf.cast(pred_flattened_ct_heatmap, tf.float32)
total_center_loss += object_center_loss_fn(
target_tensor=true_flattened_ct_heatmap,
prediction_tensor=pred_flattened_ct_heatmap,
weights=valid_anchor_weights)
center_loss = tf.reduce_sum(total_center_loss) / float(
len(pred_ct_heatmap_list) * num_boxes)
losses['ct_loss'] = center_loss
# Calculate scale loss
pred_scale_list = outputs['ct_size']
true_scale = tf.cast(gt_label['size'], tf.float32)
total_scale_loss = 0.0
for scale_map in pred_scale_list:
pred_scale = loss_ops.get_batch_predictions_from_indices(scale_map,
box_indices)
pred_scale = tf.cast(pred_scale, tf.float32)
# Only apply loss for boxes that appear in the ground truth
total_scale_loss += tf.reduce_sum(
localization_loss_fn(target_tensor=true_scale,
prediction_tensor=pred_scale),
axis=-1) * box_mask
scale_loss = tf.reduce_sum(total_scale_loss) / float(
len(pred_scale_list) * num_boxes)
losses['scale_loss'] = scale_loss
# Calculate offset loss
pred_offset_list = outputs['ct_offset']
true_offset = tf.cast(gt_label['ct_offset'], tf.float32)
total_offset_loss = 0.0
for offset_map in pred_offset_list:
pred_offset = loss_ops.get_batch_predictions_from_indices(offset_map,
box_indices)
pred_offset = tf.cast(pred_offset, tf.float32)
# Only apply loss for boxes that appear in the ground truth
total_offset_loss += tf.reduce_sum(
localization_loss_fn(target_tensor=true_offset,
prediction_tensor=pred_offset),
axis=-1) * box_mask
offset_loss = tf.reduce_sum(total_offset_loss) / float(
len(pred_offset_list) * num_boxes)
losses['ct_offset_loss'] = offset_loss
# Aggregate and finalize loss
loss_weights = self.task_config.losses.detection
total_loss = (loss_weights.object_center_weight * center_loss +
loss_weights.scale_weight * scale_loss +
loss_weights.offset_weight * offset_loss)
if aux_losses:
total_loss += tf.add_n(aux_losses)
losses['total_loss'] = total_loss
return losses
def build_metrics(self, training=True):
metrics = []
metric_names = ['total_loss', 'ct_loss', 'scale_loss', 'ct_offset_loss']
for name in metric_names:
metrics.append(tf.keras.metrics.Mean(name, dtype=tf.float32))
if not training:
if (self.task_config.validation_data.tfds_name
and self.task_config.annotation_file):
raise ValueError(
"Can't evaluate using annotation file when TFDS is used.")
self.coco_metric = coco_evaluator.COCOEvaluator(
annotation_file=self.task_config.annotation_file,
include_mask=False,
per_category_metrics=self.task_config.per_category_metrics)
return metrics
def train_step(self,
inputs: Tuple[Any, Any],
model: tf.keras.Model,
optimizer: tf.keras.optimizers.Optimizer,
metrics: Optional[List[Any]] = None):
"""Does forward and backward.
Args:
inputs: a dictionary of input tensors.
model: the model, forward pass definition.
optimizer: the optimizer for this training step.
metrics: a nested structure of metrics objects.
Returns:
A dictionary of logs.
"""
features, labels = inputs
num_replicas = tf.distribute.get_strategy().num_replicas_in_sync
with tf.GradientTape() as tape:
outputs = model(features, training=True)
# Casting output layer as float32 is necessary when mixed_precision is
# mixed_float16 or mixed_bfloat16 to ensure output is casted as float32.
outputs = tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), outputs)
losses = self.build_losses(outputs['raw_output'], labels)
scaled_loss = losses['total_loss'] / num_replicas
# For mixed_precision policy, when LossScaleOptimizer is used, loss is
# scaled for numerical stability.
if isinstance(optimizer, tf.keras.mixed_precision.LossScaleOptimizer):
scaled_loss = optimizer.get_scaled_loss(scaled_loss)
# compute the gradient
tvars = model.trainable_variables
gradients = tape.gradient(scaled_loss, tvars)
# get unscaled loss if the scaled loss was used
if isinstance(optimizer, tf.keras.mixed_precision.LossScaleOptimizer):
gradients = optimizer.get_unscaled_gradients(gradients)
if self.task_config.gradient_clip_norm > 0.0:
gradients, _ = tf.clip_by_global_norm(gradients,
self.task_config.gradient_clip_norm)
optimizer.apply_gradients(list(zip(gradients, tvars)))
logs = {self.loss: losses['total_loss']}
if metrics:
for m in metrics:
m.update_state(losses[m.name])
logs.update({m.name: m.result()})
return logs
def validation_step(self,
inputs: Tuple[Any, Any],
model: tf.keras.Model,
metrics: Optional[List[Any]] = None):
"""Validation step.
Args:
inputs: a dictionary of input tensors.
model: the keras.Model.
metrics: a nested structure of metrics objects.
Returns:
A dictionary of logs.
"""
features, labels = inputs
outputs = model(features, training=False)
outputs = tf.nest.map_structure(lambda x: tf.cast(x, tf.float32), outputs)
losses = self.build_losses(outputs['raw_output'], labels)
logs = {self.loss: losses['total_loss']}
coco_model_outputs = {
'detection_boxes': outputs['boxes'],
'detection_scores': outputs['confidence'],
'detection_classes': outputs['classes'],
'num_detections': outputs['num_detections'],
'source_id': labels['groundtruths']['source_id'],
'image_info': labels['image_info']
}
logs.update({self.coco_metric.name: (labels['groundtruths'],
coco_model_outputs)})
if metrics:
for m in metrics:
m.update_state(losses[m.name])
logs.update({m.name: m.result()})
return logs
def aggregate_logs(self, state=None, step_outputs=None):
if state is None:
self.coco_metric.reset_states()
state = self.coco_metric
self.coco_metric.update_state(step_outputs[self.coco_metric.name][0],
step_outputs[self.coco_metric.name][1])
return state
def reduce_aggregated_logs(self, aggregated_logs, global_step=None):
return self.coco_metric.result()
| 16,719 | 38.248826 | 80 | py |
models | models-master/official/projects/centernet/tasks/__init__.py | # Copyright 2023 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.
| 609 | 39.666667 | 74 | py |
models | models-master/official/projects/centernet/ops/preprocess_ops.py | # Copyright 2023 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.
"""Preprocessing ops imported from OD API."""
import functools
import tensorflow as tf
from official.projects.centernet.ops import box_list
from official.projects.centernet.ops import box_list_ops
def _get_or_create_preprocess_rand_vars(generator_func,
function_id,
preprocess_vars_cache,
key=''):
"""Returns a tensor stored in preprocess_vars_cache or using generator_func.
If the tensor was previously generated and appears in the PreprocessorCache,
the previously generated tensor will be returned. Otherwise, a new tensor
is generated using generator_func and stored in the cache.
Args:
generator_func: A 0-argument function that generates a tensor.
function_id: identifier for the preprocessing function used.
preprocess_vars_cache: PreprocessorCache object that records previously
performed augmentations. Updated in-place. If this
function is called multiple times with the same
non-null cache, it will perform deterministically.
key: identifier for the variable stored.
Returns:
The generated tensor.
"""
if preprocess_vars_cache is not None:
var = preprocess_vars_cache.get(function_id, key)
if var is None:
var = generator_func()
preprocess_vars_cache.update(function_id, key, var)
else:
var = generator_func()
return var
def _random_integer(minval, maxval, seed):
"""Returns a random 0-D tensor between minval and maxval.
Args:
minval: minimum value of the random tensor.
maxval: maximum value of the random tensor.
seed: random seed.
Returns:
A random 0-D tensor between minval and maxval.
"""
return tf.random.uniform(
[], minval=minval, maxval=maxval, dtype=tf.int32, seed=seed)
def _get_crop_border(border, size):
"""Get the border of cropping."""
border = tf.cast(border, tf.float32)
size = tf.cast(size, tf.float32)
i = tf.math.ceil(tf.math.log(2.0 * border / size) / tf.math.log(2.0))
divisor = tf.pow(2.0, i)
divisor = tf.clip_by_value(divisor, 1, border)
divisor = tf.cast(divisor, tf.int32)
return tf.cast(border, tf.int32) // divisor
def random_square_crop_by_scale(image,
boxes,
labels,
max_border=128,
scale_min=0.6,
scale_max=1.3,
num_scales=8,
seed=None,
preprocess_vars_cache=None):
"""Randomly crop a square in proportion to scale and image size.
Extract a square sized crop from an image whose side length is sampled by
randomly scaling the maximum spatial dimension of the image. If part of
the crop falls outside the image, it is filled with zeros.
The augmentation is borrowed from [1]
[1]: https://arxiv.org/abs/1904.07850
Args:
image: rank 3 float32 tensor containing 1 image ->
[height, width, channels].
boxes: rank 2 float32 tensor containing the bounding boxes -> [N, 4].
Boxes are in normalized form meaning their coordinates vary
between [0, 1]. Each row is in the form of [ymin, xmin, ymax, xmax].
Boxes on the crop boundary are clipped to the boundary and boxes
falling outside the crop are ignored.
labels: rank 1 int32 tensor containing the object classes.
max_border: The maximum size of the border. The border defines distance in
pixels to the image boundaries that will not be considered as a center of
a crop. To make sure that the border does not go over the center of the
image, we chose the border value by computing the minimum k, such that
(max_border / (2**k)) < image_dimension/2.
scale_min: float, the minimum value for scale.
scale_max: float, the maximum value for scale.
num_scales: int, the number of discrete scale values to sample between
[scale_min, scale_max]
seed: random seed.
preprocess_vars_cache: PreprocessorCache object that records previously
performed augmentations. Updated in-place. If this
function is called multiple times with the same
non-null cache, it will perform deterministically.
Returns:
image: image which is the same rank as input image.
boxes: boxes which is the same rank as input boxes.
Boxes are in normalized form.
labels: new labels.
"""
img_shape = tf.shape(image)
height, width = img_shape[0], img_shape[1]
scales = tf.linspace(scale_min, scale_max, num_scales)
scale = _get_or_create_preprocess_rand_vars(
lambda: scales[_random_integer(0, num_scales, seed)],
'square_crop_scale',
preprocess_vars_cache, 'scale')
image_size = scale * tf.cast(tf.maximum(height, width), tf.float32)
image_size = tf.cast(image_size, tf.int32)
h_border = _get_crop_border(max_border, height)
w_border = _get_crop_border(max_border, width)
def y_function():
y = _random_integer(h_border,
tf.cast(height, tf.int32) - h_border + 1,
seed)
return y
def x_function():
x = _random_integer(w_border,
tf.cast(width, tf.int32) - w_border + 1,
seed)
return x
y_center = _get_or_create_preprocess_rand_vars(
y_function,
'square_crop_scale',
preprocess_vars_cache, 'y_center')
x_center = _get_or_create_preprocess_rand_vars(
x_function,
'square_crop_scale',
preprocess_vars_cache, 'x_center')
half_size = tf.cast(image_size / 2, tf.int32)
crop_ymin, crop_ymax = y_center - half_size, y_center + half_size
crop_xmin, crop_xmax = x_center - half_size, x_center + half_size
ymin = tf.maximum(crop_ymin, 0)
xmin = tf.maximum(crop_xmin, 0)
ymax = tf.minimum(crop_ymax, height - 1)
xmax = tf.minimum(crop_xmax, width - 1)
cropped_image = image[ymin:ymax, xmin:xmax]
offset_y = tf.maximum(0, ymin - crop_ymin)
offset_x = tf.maximum(0, xmin - crop_xmin)
oy_i = offset_y
ox_i = offset_x
output_image = tf.image.pad_to_bounding_box(
cropped_image, offset_height=oy_i, offset_width=ox_i,
target_height=image_size, target_width=image_size)
if ymin == 0:
# We might be padding the image.
box_ymin = -offset_y
else:
box_ymin = crop_ymin
if xmin == 0:
# We might be padding the image.
box_xmin = -offset_x
else:
box_xmin = crop_xmin
box_ymax = box_ymin + image_size
box_xmax = box_xmin + image_size
image_box = [box_ymin / height, box_xmin / width,
box_ymax / height, box_xmax / width]
boxlist = box_list.BoxList(boxes)
boxlist = box_list_ops.change_coordinate_frame(boxlist, image_box)
boxlist, indices = box_list_ops.prune_completely_outside_window(
boxlist, [0.0, 0.0, 1.0, 1.0])
boxlist = box_list_ops.clip_to_window(boxlist, [0.0, 0.0, 1.0, 1.0],
filter_nonoverlapping=False)
return_values = [output_image,
boxlist.get(),
tf.gather(labels, indices)]
return return_values
def resize_to_range(image,
masks=None,
min_dimension=None,
max_dimension=None,
method=tf.image.ResizeMethod.BILINEAR,
pad_to_max_dimension=False,
per_channel_pad_value=(0, 0, 0)):
"""Resizes an image so its dimensions are within the provided value.
The output size can be described by two cases:
1. If the image can be rescaled so its minimum dimension is equal to the
provided value without the other dimension exceeding max_dimension,
then do so.
2. Otherwise, resize so the largest dimension is equal to max_dimension.
Args:
image: A 3D tensor of shape [height, width, channels]
masks: (optional) rank 3 float32 tensor with shape
[num_instances, height, width] containing instance masks.
min_dimension: (optional) (scalar) desired size of the smaller image
dimension.
max_dimension: (optional) (scalar) maximum allowed size
of the larger image dimension.
method: (optional) interpolation method used in resizing. Defaults to
BILINEAR.
pad_to_max_dimension: Whether to resize the image and pad it with zeros
so the resulting image is of the spatial size
[max_dimension, max_dimension]. If masks are included they are padded
similarly.
per_channel_pad_value: A tuple of per-channel scalar value to use for
padding. By default pads zeros.
Returns:
Note that the position of the resized_image_shape changes based on whether
masks are present.
resized_image: A 3D tensor of shape [new_height, new_width, channels],
where the image has been resized (with bilinear interpolation) so that
min(new_height, new_width) == min_dimension or
max(new_height, new_width) == max_dimension.
resized_masks: If masks is not None, also outputs masks. A 3D tensor of
shape [num_instances, new_height, new_width].
resized_image_shape: A 1D tensor of shape [3] containing shape of the
resized image.
Raises:
ValueError: if the image is not a 3D tensor.
"""
if len(image.get_shape()) != 3:
raise ValueError('Image should be 3D tensor')
def _resize_landscape_image(image):
# resize a landscape image
return tf.image.resize(
image, tf.stack([min_dimension, max_dimension]), method=method,
preserve_aspect_ratio=True)
def _resize_portrait_image(image):
# resize a portrait image
return tf.image.resize(
image, tf.stack([max_dimension, min_dimension]), method=method,
preserve_aspect_ratio=True)
with tf.name_scope('ResizeToRange'):
if image.get_shape().is_fully_defined():
if image.get_shape()[0] < image.get_shape()[1]:
new_image = _resize_landscape_image(image)
else:
new_image = _resize_portrait_image(image)
new_size = tf.constant(new_image.get_shape().as_list())
else:
new_image = tf.cond(
tf.less(tf.shape(image)[0], tf.shape(image)[1]),
lambda: _resize_landscape_image(image),
lambda: _resize_portrait_image(image))
new_size = tf.shape(new_image)
if pad_to_max_dimension:
channels = tf.unstack(new_image, axis=2)
if len(channels) != len(per_channel_pad_value):
raise ValueError('Number of channels must be equal to the length of '
'per-channel pad value.')
new_image = tf.stack(
[
tf.pad( # pylint: disable=g-complex-comprehension
channels[i], [[0, max_dimension - new_size[0]],
[0, max_dimension - new_size[1]]],
constant_values=per_channel_pad_value[i])
for i in range(len(channels))
],
axis=2)
new_image.set_shape([max_dimension, max_dimension, len(channels)])
result = [new_image, new_size]
if masks is not None:
new_masks = tf.expand_dims(masks, 3)
new_masks = tf.image.resize(
new_masks,
new_size[:-1],
method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
if pad_to_max_dimension:
new_masks = tf.image.pad_to_bounding_box(
new_masks, 0, 0, max_dimension, max_dimension)
new_masks = tf.squeeze(new_masks, 3)
result.append(new_masks)
return result
def _augment_only_rgb_channels(image, augment_function):
"""Augments only the RGB slice of an image with additional channels."""
rgb_slice = image[:, :, :3]
augmented_rgb_slice = augment_function(rgb_slice)
image = tf.concat([augmented_rgb_slice, image[:, :, 3:]], -1)
return image
def random_adjust_brightness(image,
max_delta=0.2,
seed=None,
preprocess_vars_cache=None):
"""Randomly adjusts brightness.
Makes sure the output image is still between 0 and 255.
Args:
image: rank 3 float32 tensor contains 1 image -> [height, width, channels]
with pixel values varying between [0, 255].
max_delta: how much to change the brightness. A value between [0, 1).
seed: random seed.
preprocess_vars_cache: PreprocessorCache object that records previously
performed augmentations. Updated in-place. If this
function is called multiple times with the same
non-null cache, it will perform deterministically.
Returns:
image: image which is the same shape as input image.
"""
with tf.name_scope('RandomAdjustBrightness'):
generator_func = functools.partial(tf.random.uniform, [],
-max_delta, max_delta, seed=seed)
delta = _get_or_create_preprocess_rand_vars(
generator_func,
'adjust_brightness',
preprocess_vars_cache)
def _adjust_brightness(image):
image = tf.image.adjust_brightness(image / 255, delta) * 255
image = tf.clip_by_value(image, clip_value_min=0.0, clip_value_max=255.0)
return image
image = _augment_only_rgb_channels(image, _adjust_brightness)
return image
def random_adjust_contrast(image,
min_delta=0.8,
max_delta=1.25,
seed=None,
preprocess_vars_cache=None):
"""Randomly adjusts contrast.
Makes sure the output image is still between 0 and 255.
Args:
image: rank 3 float32 tensor contains 1 image -> [height, width, channels]
with pixel values varying between [0, 255].
min_delta: see max_delta.
max_delta: how much to change the contrast. Contrast will change with a
value between min_delta and max_delta. This value will be
multiplied to the current contrast of the image.
seed: random seed.
preprocess_vars_cache: PreprocessorCache object that records previously
performed augmentations. Updated in-place. If this
function is called multiple times with the same
non-null cache, it will perform deterministically.
Returns:
image: image which is the same shape as input image.
"""
with tf.name_scope('RandomAdjustContrast'):
generator_func = functools.partial(tf.random.uniform, [],
min_delta, max_delta, seed=seed)
contrast_factor = _get_or_create_preprocess_rand_vars(
generator_func,
'adjust_contrast',
preprocess_vars_cache)
def _adjust_contrast(image):
image = tf.image.adjust_contrast(image / 255, contrast_factor) * 255
image = tf.clip_by_value(image, clip_value_min=0.0, clip_value_max=255.0)
return image
image = _augment_only_rgb_channels(image, _adjust_contrast)
return image
def random_adjust_hue(image,
max_delta=0.02,
seed=None,
preprocess_vars_cache=None):
"""Randomly adjusts hue.
Makes sure the output image is still between 0 and 255.
Args:
image: rank 3 float32 tensor contains 1 image -> [height, width, channels]
with pixel values varying between [0, 255].
max_delta: change hue randomly with a value between 0 and max_delta.
seed: random seed.
preprocess_vars_cache: PreprocessorCache object that records previously
performed augmentations. Updated in-place. If this
function is called multiple times with the same
non-null cache, it will perform deterministically.
Returns:
image: image which is the same shape as input image.
"""
with tf.name_scope('RandomAdjustHue'):
generator_func = functools.partial(tf.random.uniform, [],
-max_delta, max_delta, seed=seed)
delta = _get_or_create_preprocess_rand_vars(
generator_func,
'adjust_hue',
preprocess_vars_cache)
def _adjust_hue(image):
image = tf.image.adjust_hue(image / 255, delta) * 255
image = tf.clip_by_value(image, clip_value_min=0.0, clip_value_max=255.0)
return image
image = _augment_only_rgb_channels(image, _adjust_hue)
return image
def random_adjust_saturation(image,
min_delta=0.8,
max_delta=1.25,
seed=None,
preprocess_vars_cache=None):
"""Randomly adjusts saturation.
Makes sure the output image is still between 0 and 255.
Args:
image: rank 3 float32 tensor contains 1 image -> [height, width, channels]
with pixel values varying between [0, 255].
min_delta: see max_delta.
max_delta: how much to change the saturation. Saturation will change with a
value between min_delta and max_delta. This value will be
multiplied to the current saturation of the image.
seed: random seed.
preprocess_vars_cache: PreprocessorCache object that records previously
performed augmentations. Updated in-place. If this
function is called multiple times with the same
non-null cache, it will perform deterministically.
Returns:
image: image which is the same shape as input image.
"""
with tf.name_scope('RandomAdjustSaturation'):
generator_func = functools.partial(tf.random.uniform, [],
min_delta, max_delta, seed=seed)
saturation_factor = _get_or_create_preprocess_rand_vars(
generator_func,
'adjust_saturation',
preprocess_vars_cache)
def _adjust_saturation(image):
image = tf.image.adjust_saturation(image / 255, saturation_factor) * 255
image = tf.clip_by_value(image, clip_value_min=0.0, clip_value_max=255.0)
return image
image = _augment_only_rgb_channels(image, _adjust_saturation)
return image
| 19,013 | 37.257545 | 79 | py |
models | models-master/official/projects/centernet/ops/target_assigner.py | # Copyright 2023 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.
"""Generate targets (center, scale, offsets,...) for centernet."""
from typing import Dict, List
import tensorflow as tf
from official.vision.ops import sampling_ops
def smallest_positive_root(a, b, c):
"""Returns the smallest positive root of a quadratic equation."""
discriminant = tf.sqrt(b ** 2 - 4 * a * c)
return (-b + discriminant) / (2.0)
@tf.function
def cartesian_product(*tensors, repeat: int = 1) -> tf.Tensor:
"""Equivalent of itertools.product except for TensorFlow tensors.
Example:
cartesian_product(tf.range(3), tf.range(4))
array([[0, 0],
[0, 1],
[0, 2],
[0, 3],
[1, 0],
[1, 1],
[1, 2],
[1, 3],
[2, 0],
[2, 1],
[2, 2],
[2, 3]], dtype=int32)>
Args:
*tensors: a list of 1D tensors to compute the product of
repeat: an `int` number of times to repeat the tensors
Returns:
An nD tensor where n is the number of tensors
"""
tensors = tensors * repeat
return tf.reshape(tf.transpose(tf.stack(tf.meshgrid(*tensors, indexing='ij')),
[*[i + 1 for i in range(len(tensors))], 0]),
(-1, len(tensors)))
def image_shape_to_grids(height: int, width: int):
"""Computes xy-grids given the shape of the image.
Args:
height: The height of the image.
width: The width of the image.
Returns:
A tuple of two tensors:
y_grid: A float tensor with shape [height, width] representing the
y-coordinate of each pixel grid.
x_grid: A float tensor with shape [height, width] representing the
x-coordinate of each pixel grid.
"""
out_height = tf.cast(height, tf.float32)
out_width = tf.cast(width, tf.float32)
x_range = tf.range(out_width, dtype=tf.float32)
y_range = tf.range(out_height, dtype=tf.float32)
x_grid, y_grid = tf.meshgrid(x_range, y_range, indexing='xy')
return (y_grid, x_grid)
def max_distance_for_overlap(height, width, min_iou):
"""Computes how far apart bbox corners can lie while maintaining the iou.
Given a bounding box size, this function returns a lower bound on how far
apart the corners of another box can lie while still maintaining the given
IoU. The implementation is based on the `gaussian_radius` function in the
Objects as Points github repo: https://github.com/xingyizhou/CenterNet
Args:
height: A 1-D float Tensor representing height of the ground truth boxes.
width: A 1-D float Tensor representing width of the ground truth boxes.
min_iou: A float representing the minimum IoU desired.
Returns:
distance: A 1-D Tensor of distances, of the same length as the input
height and width tensors.
"""
# Given that the detected box is displaced at a distance `d`, the exact
# IoU value will depend on the angle at which each corner is displaced.
# We simplify our computation by assuming that each corner is displaced by
# a distance `d` in both x and y direction. This gives us a lower IoU than
# what is actually realizable and ensures that any box with corners less
# than `d` distance apart will always have an IoU greater than or equal
# to `min_iou`
# The following 3 cases can be worked on geometrically and come down to
# solving a quadratic inequality. In each case, to ensure `min_iou` we use
# the smallest positive root of the equation.
# Case where detected box is offset from ground truth and no box completely
# contains the other.
distance_detection_offset = smallest_positive_root(
a=1, b=-(height + width),
c=width * height * ((1 - min_iou) / (1 + min_iou))
)
# Case where detection is smaller than ground truth and completely contained
# in it.
distance_detection_in_gt = smallest_positive_root(
a=4, b=-2 * (height + width),
c=(1 - min_iou) * width * height
)
# Case where ground truth is smaller than detection and completely contained
# in it.
distance_gt_in_detection = smallest_positive_root(
a=4 * min_iou, b=(2 * min_iou) * (width + height),
c=(min_iou - 1) * width * height
)
return tf.reduce_min([distance_detection_offset,
distance_gt_in_detection,
distance_detection_in_gt], axis=0)
def compute_std_dev_from_box_size(boxes_height, boxes_width, min_overlap):
"""Computes the standard deviation of the Gaussian kernel from box size.
Args:
boxes_height: A 1D tensor with shape [num_instances] representing the height
of each box.
boxes_width: A 1D tensor with shape [num_instances] representing the width
of each box.
min_overlap: The minimum IOU overlap that boxes need to have to not be
penalized.
Returns:
A 1D tensor with shape [num_instances] representing the computed Gaussian
sigma for each of the box.
"""
# We are dividing by 3 so that points closer than the computed
# distance have a >99% CDF.
sigma = max_distance_for_overlap(boxes_height, boxes_width, min_overlap)
sigma = (2 * tf.math.maximum(tf.math.floor(sigma), 0.0) + 1) / 6.0
return sigma
@tf.function
def assign_center_targets(out_height: int,
out_width: int,
y_center: tf.Tensor,
x_center: tf.Tensor,
boxes_height: tf.Tensor,
boxes_width: tf.Tensor,
channel_onehot: tf.Tensor,
gaussian_iou: float):
"""Computes the object center heatmap target based on ODAPI implementation.
Args:
out_height: int, height of output to the model. This is used to
determine the height of the output.
out_width: int, width of the output to the model. This is used to
determine the width of the output.
y_center: A 1D tensor with shape [num_instances] representing the
y-coordinates of the instances in the output space coordinates.
x_center: A 1D tensor with shape [num_instances] representing the
x-coordinates of the instances in the output space coordinates.
boxes_height: A 1D tensor with shape [num_instances] representing the height
of each box.
boxes_width: A 1D tensor with shape [num_instances] representing the width
of each box.
channel_onehot: A 2D tensor with shape [num_instances, num_channels]
representing the one-hot encoded channel labels for each point.
gaussian_iou: The minimum IOU overlap that boxes need to have to not be
penalized.
Returns:
heatmap: A Tensor of size [output_height, output_width,
num_classes] representing the per class center heatmap. output_height
and output_width are computed by dividing the input height and width by
the stride specified during initialization.
"""
(y_grid, x_grid) = image_shape_to_grids(out_height, out_width)
sigma = compute_std_dev_from_box_size(boxes_height, boxes_width,
gaussian_iou)
num_instances, num_channels = (
sampling_ops.combined_static_and_dynamic_shape(channel_onehot))
x_grid = tf.expand_dims(x_grid, 2)
y_grid = tf.expand_dims(y_grid, 2)
# The raw center coordinates in the output space.
x_diff = x_grid - tf.math.floor(x_center)
y_diff = y_grid - tf.math.floor(y_center)
squared_distance = x_diff ** 2 + y_diff ** 2
gaussian_map = tf.exp(-squared_distance / (2 * sigma * sigma))
reshaped_gaussian_map = tf.expand_dims(gaussian_map, axis=-1)
reshaped_channel_onehot = tf.reshape(channel_onehot,
(1, 1, num_instances, num_channels))
gaussian_per_box_per_class_map = (
reshaped_gaussian_map * reshaped_channel_onehot)
# Take maximum along the "instance" dimension so that all per-instance
# heatmaps of the same class are merged together.
heatmap = tf.reduce_max(gaussian_per_box_per_class_map, axis=2)
# Maximum of an empty tensor is -inf, the following is to avoid that.
heatmap = tf.maximum(heatmap, 0)
return tf.stop_gradient(heatmap)
def assign_centernet_targets(labels: Dict[str, tf.Tensor],
output_size: List[int],
input_size: List[int],
num_classes: int = 90,
max_num_instances: int = 128,
gaussian_iou: float = 0.7,
class_offset: int = 0,
dtype='float32'):
"""Generates the ground truth labels for centernet.
Ground truth labels are generated by splatting gaussians on heatmaps for
corners and centers. Regressed features (offsets and sizes) are also
generated.
Args:
labels: A dictionary of COCO ground truth labels with at minimum the
following fields:
"bbox" A `Tensor` of shape [max_num_instances, 4], where the
last dimension corresponds to the top left x, top left y,
bottom right x, and bottom left y coordinates of the bounding box
"classes" A `Tensor` of shape [max_num_instances] that contains
the class of each box, given in the same order as the boxes
"num_detections" A `Tensor` or int that gives the number of objects
output_size: A `list` of length 2 containing the desired output height
and width of the heatmaps
input_size: A `list` of length 2 the expected input height and width of
the image
num_classes: A `Tensor` or `int` for the number of classes.
max_num_instances: An `int` for maximum number of instances in an image.
gaussian_iou: A `float` number for the minimum desired IOU used when
determining the gaussian radius of center locations in the heatmap.
class_offset: A `int` for subtracting a value from the ground truth classes
dtype: `str`, data type. One of {`bfloat16`, `float32`, `float16`}.
Returns:
Dictionary of labels with the following fields:
'ct_heatmaps': Tensor of shape [output_h, output_w, num_classes],
heatmap with splatted gaussians centered at the positions and channels
corresponding to the center location and class of the object
'ct_offset': `Tensor` of shape [max_num_instances, 2], where the first
num_boxes entries contain the x-offset and y-offset of the center of
an object. All other entires are 0
'size': `Tensor` of shape [max_num_instances, 2], where the first
num_boxes entries contain the width and height of an object. All
other entires are 0
'box_mask': `Tensor` of shape [max_num_instances], where the first
num_boxes entries are 1. All other entires are 0
'box_indices': `Tensor` of shape [max_num_instances, 2], where the first
num_boxes entries contain the y-center and x-center of a valid box.
These are used to extract the regressed box features from the
prediction when computing the loss
Raises:
Exception: if datatype is not supported.
"""
if dtype == 'float16':
dtype = tf.float16
elif dtype == 'bfloat16':
dtype = tf.bfloat16
elif dtype == 'float32':
dtype = tf.float32
else:
raise Exception(
'Unsupported datatype used in ground truth builder only '
'{float16, bfloat16, or float32}')
# Get relevant bounding box and class information from labels
# only keep the first num_objects boxes and classes
num_objects = labels['groundtruths']['num_detections']
# shape of labels['boxes'] is [max_num_instances, 4]
# [ymin, xmin, ymax, xmax]
boxes = tf.cast(labels['boxes'], dtype)
# shape of labels['classes'] is [max_num_instances, ]
classes = tf.cast(labels['classes'] - class_offset, dtype)
# Compute scaling factors for center/corner positions on heatmap
# input_size = tf.cast(input_size, dtype)
# output_size = tf.cast(output_size, dtype)
input_h, input_w = input_size[0], input_size[1]
output_h, output_w = output_size[0], output_size[1]
width_ratio = output_w / input_w
height_ratio = output_h / input_h
# Original box coordinates
# [max_num_instances, ]
ytl, ybr = boxes[..., 0], boxes[..., 2]
xtl, xbr = boxes[..., 1], boxes[..., 3]
yct = (ytl + ybr) / 2
xct = (xtl + xbr) / 2
# Scaled box coordinates (could be floating point)
# [max_num_instances, ]
scale_xct = xct * width_ratio
scale_yct = yct * height_ratio
# Floor the scaled box coordinates to be placed on heatmaps
# [max_num_instances, ]
scale_xct_floor = tf.math.floor(scale_xct)
scale_yct_floor = tf.math.floor(scale_yct)
# Offset computations to make up for discretization error
# used for offset maps
# [max_num_instances, 2]
ct_offset_values = tf.stack([scale_yct - scale_yct_floor,
scale_xct - scale_xct_floor], axis=-1)
# Get the scaled box dimensions for computing the gaussian radius
# [max_num_instances, ]
box_widths = boxes[..., 3] - boxes[..., 1]
box_heights = boxes[..., 2] - boxes[..., 0]
box_widths = box_widths * width_ratio
box_heights = box_heights * height_ratio
# Used for size map
# [max_num_instances, 2]
box_heights_widths = tf.stack([box_heights, box_widths], axis=-1)
# Center/corner heatmaps
# [output_h, output_w, num_classes]
ct_heatmap = tf.zeros((output_h, output_w, num_classes), dtype)
# Maps for offset and size features for each instance of a box
# [max_num_instances, 2]
ct_offset = tf.zeros((max_num_instances, 2), dtype)
# [max_num_instances, 2]
size = tf.zeros((max_num_instances, 2), dtype)
# Mask for valid box instances and their center indices in the heatmap
# [max_num_instances, ]
box_mask = tf.zeros((max_num_instances,), tf.int32)
# [max_num_instances, 2]
box_indices = tf.zeros((max_num_instances, 2), tf.int32)
if num_objects > 0:
# Need to gaussians around the centers and corners of the objects
ct_heatmap = assign_center_targets(
out_height=output_h,
out_width=output_w,
y_center=scale_yct_floor[:num_objects],
x_center=scale_xct_floor[:num_objects],
boxes_height=box_heights[:num_objects],
boxes_width=box_widths[:num_objects],
channel_onehot=tf.one_hot(tf.cast(classes[:num_objects], tf.int32),
num_classes, off_value=0.),
gaussian_iou=gaussian_iou)
# Indices used to update offsets and sizes for valid box instances
update_indices = cartesian_product(
tf.range(max_num_instances), tf.range(2))
# [max_num_instances, 2, 2]
update_indices = tf.reshape(update_indices, shape=[max_num_instances, 2, 2])
# Write the offsets of each box instance
ct_offset = tf.tensor_scatter_nd_update(
ct_offset, update_indices, ct_offset_values)
# Write the size of each bounding box
size = tf.tensor_scatter_nd_update(
size, update_indices, box_heights_widths)
# Initially the mask is zeros, so now we unmask each valid box instance
box_mask = tf.where(tf.range(max_num_instances) < num_objects, 1, 0)
# Write the y and x coordinate of each box center in the heatmap
box_index_values = tf.cast(
tf.stack([scale_yct_floor, scale_xct_floor], axis=-1),
dtype=tf.int32)
box_indices = tf.tensor_scatter_nd_update(
box_indices, update_indices, box_index_values)
ct_labels = {
# [output_h, output_w, num_classes]
'ct_heatmaps': ct_heatmap,
# [max_num_instances, 2]
'ct_offset': ct_offset,
# [max_num_instances, 2]
'size': size,
# [max_num_instances, ]
'box_mask': box_mask,
# [max_num_instances, 2]
'box_indices': box_indices
}
return ct_labels
| 16,235 | 37.842105 | 80 | py |
models | models-master/official/projects/centernet/ops/target_assigner_test.py | # Copyright 2023 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.
"""Tests for targets generations of centernet."""
from absl.testing import parameterized
import tensorflow as tf
from official.projects.centernet.ops import target_assigner
from official.vision.ops import preprocess_ops
class TargetAssignerTest(tf.test.TestCase, parameterized.TestCase):
def check_labels_correct(self,
boxes,
classes,
output_size,
input_size):
max_num_instances = 128
num_detections = len(boxes)
boxes = tf.constant(boxes, dtype=tf.float32)
classes = tf.constant(classes, dtype=tf.float32)
boxes = preprocess_ops.clip_or_pad_to_fixed_size(
boxes, max_num_instances, 0)
classes = preprocess_ops.clip_or_pad_to_fixed_size(
classes, max_num_instances, 0)
# pylint: disable=g-long-lambda
labels = target_assigner.assign_centernet_targets(
labels={
'boxes': boxes,
'classes': classes,
'groundtruths': {
'num_detections': num_detections,
}
},
output_size=output_size,
input_size=input_size)
ct_heatmaps = labels['ct_heatmaps']
ct_offset = labels['ct_offset']
size = labels['size']
box_mask = labels['box_mask']
box_indices = labels['box_indices']
boxes = tf.cast(boxes, tf.float32)
classes = tf.cast(classes, tf.float32)
height_ratio = output_size[0] / input_size[0]
width_ratio = output_size[1] / input_size[1]
# Shape checks
self.assertEqual(ct_heatmaps.shape, (output_size[0], output_size[1], 90))
self.assertEqual(ct_offset.shape, (max_num_instances, 2))
self.assertEqual(size.shape, (max_num_instances, 2))
self.assertEqual(box_mask.shape, (max_num_instances,))
self.assertEqual(box_indices.shape, (max_num_instances, 2))
self.assertAllInRange(ct_heatmaps, 0, 1)
for i in range(len(boxes)):
# Check sizes
self.assertAllEqual(size[i],
[(boxes[i][2] - boxes[i][0]) * height_ratio,
(boxes[i][3] - boxes[i][1]) * width_ratio,
])
# Check box indices
y = tf.math.floor((boxes[i][0] + boxes[i][2]) / 2 * height_ratio)
x = tf.math.floor((boxes[i][1] + boxes[i][3]) / 2 * width_ratio)
self.assertAllEqual(box_indices[i], [y, x])
# check offsets
true_y = (boxes[i][0] + boxes[i][2]) / 2 * height_ratio
true_x = (boxes[i][1] + boxes[i][3]) / 2 * width_ratio
self.assertAllEqual(ct_offset[i], [true_y - y, true_x - x])
for i in range(len(boxes), max_num_instances):
# Make sure rest are zero
self.assertAllEqual(size[i], [0, 0])
self.assertAllEqual(box_indices[i], [0, 0])
self.assertAllEqual(ct_offset[i], [0, 0])
# Check mask indices
self.assertAllEqual(tf.cast(box_mask[3:], tf.int32),
tf.repeat(0, repeats=max_num_instances - 3))
self.assertAllEqual(tf.cast(box_mask[:3], tf.int32),
tf.repeat(1, repeats=3))
def test_generate_targets_no_scale(self):
boxes = [
(10, 300, 15, 370),
(100, 300, 150, 370),
(15, 100, 200, 170),
]
classes = (1, 2, 3)
sizes = [512, 512]
self.check_labels_correct(boxes=boxes,
classes=classes,
output_size=sizes,
input_size=sizes)
def test_generate_targets_stride_4(self):
boxes = [
(10, 300, 15, 370),
(100, 300, 150, 370),
(15, 100, 200, 170),
]
classes = (1, 2, 3)
output_size = [128, 128]
input_size = [512, 512]
self.check_labels_correct(boxes=boxes,
classes=classes,
output_size=output_size,
input_size=input_size)
def test_generate_targets_stride_8(self):
boxes = [
(10, 300, 15, 370),
(100, 300, 150, 370),
(15, 100, 200, 170),
]
classes = (1, 2, 3)
output_size = [128, 128]
input_size = [1024, 1024]
self.check_labels_correct(boxes=boxes,
classes=classes,
output_size=output_size,
input_size=input_size)
def test_batch_generate_targets(self):
input_size = [512, 512]
output_size = [128, 128]
max_num_instances = 128
boxes = tf.constant([
(10, 300, 15, 370), # center (y, x) = (12, 335)
(100, 300, 150, 370), # center (y, x) = (125, 335)
(15, 100, 200, 170), # center (y, x) = (107, 135)
], dtype=tf.float32)
classes = tf.constant((1, 1, 1), dtype=tf.float32)
boxes = preprocess_ops.clip_or_pad_to_fixed_size(
boxes, max_num_instances, 0)
classes = preprocess_ops.clip_or_pad_to_fixed_size(
classes, max_num_instances, 0)
boxes = tf.stack([boxes, boxes], axis=0)
classes = tf.stack([classes, classes], axis=0)
# pylint: disable=g-long-lambda
labels = tf.map_fn(
fn=lambda x: target_assigner.assign_centernet_targets(
labels=x,
output_size=output_size,
input_size=input_size),
elems={
'boxes': boxes,
'classes': classes,
'groundtruths': {
'num_detections': tf.constant([3, 3]),
}
},
dtype={
'ct_heatmaps': tf.float32,
'ct_offset': tf.float32,
'size': tf.float32,
'box_mask': tf.int32,
'box_indices': tf.int32
}
)
ct_heatmaps = labels['ct_heatmaps']
ct_offset = labels['ct_offset']
size = labels['size']
box_mask = labels['box_mask']
box_indices = labels['box_indices']
self.assertEqual(ct_heatmaps.shape, (2, output_size[0], output_size[1], 90))
self.assertEqual(ct_offset.shape, (2, max_num_instances, 2))
self.assertEqual(size.shape, (2, max_num_instances, 2))
self.assertEqual(box_mask.shape, (2, max_num_instances))
self.assertEqual(box_indices.shape, (2, max_num_instances, 2))
if __name__ == '__main__':
tf.test.main()
| 6,817 | 31.62201 | 80 | py |
models | models-master/official/projects/centernet/ops/box_list_ops.py | # Copyright 2023 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.
"""Bounding Box List operations."""
import tensorflow as tf
from official.projects.centernet.ops import box_list
from official.vision.ops import sampling_ops
def _copy_extra_fields(boxlist_to_copy_to, boxlist_to_copy_from):
"""Copies the extra fields of boxlist_to_copy_from to boxlist_to_copy_to.
Args:
boxlist_to_copy_to: BoxList to which extra fields are copied.
boxlist_to_copy_from: BoxList from which fields are copied.
Returns:
boxlist_to_copy_to with extra fields.
"""
for field in boxlist_to_copy_from.get_extra_fields():
boxlist_to_copy_to.add_field(field, boxlist_to_copy_from.get_field(field))
return boxlist_to_copy_to
def scale(boxlist, y_scale, x_scale):
"""scale box coordinates in x and y dimensions.
Args:
boxlist: BoxList holding N boxes
y_scale: (float) scalar tensor
x_scale: (float) scalar tensor
Returns:
boxlist: BoxList holding N boxes
"""
with tf.name_scope('Scale'):
y_scale = tf.cast(y_scale, tf.float32)
x_scale = tf.cast(x_scale, tf.float32)
y_min, x_min, y_max, x_max = tf.split(
value=boxlist.get(), num_or_size_splits=4, axis=1)
y_min = y_scale * y_min
y_max = y_scale * y_max
x_min = x_scale * x_min
x_max = x_scale * x_max
scaled_boxlist = box_list.BoxList(
tf.concat([y_min, x_min, y_max, x_max], 1))
return _copy_extra_fields(scaled_boxlist, boxlist)
def area(boxlist):
"""Computes area of boxes.
Args:
boxlist: BoxList holding N boxes
Returns:
a tensor with shape [N] representing box areas.
"""
with tf.name_scope('Area'):
y_min, x_min, y_max, x_max = tf.split(
value=boxlist.get(), num_or_size_splits=4, axis=1)
return tf.squeeze((y_max - y_min) * (x_max - x_min), [1])
def change_coordinate_frame(boxlist, window):
"""Change coordinate frame of the boxlist to be relative to window's frame.
Given a window of the form [ymin, xmin, ymax, xmax],
changes bounding box coordinates from boxlist to be relative to this window
(e.g., the min corner maps to (0,0) and the max corner maps to (1,1)).
An example use case is data augmentation: where we are given groundtruth
boxes (boxlist) and would like to randomly crop the image to some
window (window). In this case we need to change the coordinate frame of
each groundtruth box to be relative to this new window.
Args:
boxlist: A BoxList object holding N boxes.
window: A rank 1 tensor [4].
Returns:
Returns a BoxList object with N boxes.
"""
with tf.name_scope('ChangeCoordinateFrame'):
win_height = window[2] - window[0]
win_width = window[3] - window[1]
boxlist_new = scale(box_list.BoxList(
boxlist.get() - [window[0], window[1], window[0], window[1]]),
1.0 / win_height, 1.0 / win_width)
boxlist_new = _copy_extra_fields(boxlist_new, boxlist)
return boxlist_new
def matmul_gather_on_zeroth_axis(params, indices):
"""Matrix multiplication based implementation of tf.gather on zeroth axis.
Args:
params: A float32 Tensor. The tensor from which to gather values.
Must be at least rank 1.
indices: A Tensor. Must be one of the following types: int32, int64.
Must be in range [0, params.shape[0])
Returns:
A Tensor. Has the same type as params. Values from params gathered
from indices given by indices, with shape indices.shape + params.shape[1:].
"""
with tf.name_scope('MatMulGather'):
params_shape = sampling_ops.combined_static_and_dynamic_shape(params)
indices_shape = sampling_ops.combined_static_and_dynamic_shape(indices)
params2d = tf.reshape(params, [params_shape[0], -1])
indicator_matrix = tf.one_hot(indices, params_shape[0])
gathered_result_flattened = tf.matmul(indicator_matrix, params2d)
return tf.reshape(gathered_result_flattened,
tf.stack(indices_shape + params_shape[1:]))
def gather(boxlist, indices, fields=None, use_static_shapes=False):
"""Gather boxes from BoxList according to indices and return new BoxList.
By default, `gather` returns boxes corresponding to the input index list, as
well as all additional fields stored in the boxlist (indexing into the
first dimension). However one can optionally only gather from a
subset of fields.
Args:
boxlist: BoxList holding N boxes
indices: a rank-1 tensor of type int32 / int64
fields: (optional) list of fields to also gather from. If None (default),
all fields are gathered from. Pass an empty fields list to only gather
the box coordinates.
use_static_shapes: Whether to use an implementation with static shape
gurantees.
Returns:
subboxlist: a BoxList corresponding to the subset of the input BoxList
specified by indices
Raises:
ValueError: if specified field is not contained in boxlist or if the
indices are not of type int32
"""
with tf.name_scope('Gather'):
if len(indices.shape.as_list()) != 1:
raise ValueError('indices should have rank 1')
if indices.dtype != tf.int32 and indices.dtype != tf.int64:
raise ValueError('indices should be an int32 / int64 tensor')
gather_op = tf.gather
if use_static_shapes:
gather_op = matmul_gather_on_zeroth_axis
subboxlist = box_list.BoxList(gather_op(boxlist.get(), indices))
if fields is None:
fields = boxlist.get_extra_fields()
fields += ['boxes']
for field in fields:
if not boxlist.has_field(field):
raise ValueError('boxlist must contain all specified fields')
subfieldlist = gather_op(boxlist.get_field(field), indices)
subboxlist.add_field(field, subfieldlist)
return subboxlist
def prune_completely_outside_window(boxlist, window):
"""Prunes bounding boxes that fall completely outside of the given window.
The function clip_to_window prunes bounding boxes that fall
completely outside the window, but also clips any bounding boxes that
partially overflow. This function does not clip partially overflowing boxes.
Args:
boxlist: a BoxList holding M_in boxes.
window: a float tensor of shape [4] representing [ymin, xmin, ymax, xmax]
of the window
Returns:
pruned_boxlist: a new BoxList with all bounding boxes partially or fully in
the window.
valid_indices: a tensor with shape [M_out] indexing the valid bounding boxes
in the input tensor.
"""
with tf.name_scope('PruneCompleteleyOutsideWindow'):
y_min, x_min, y_max, x_max = tf.split(
value=boxlist.get(), num_or_size_splits=4, axis=1)
win_y_min, win_x_min, win_y_max, win_x_max = tf.unstack(window)
coordinate_violations = tf.concat([
tf.greater_equal(y_min, win_y_max), tf.greater_equal(x_min, win_x_max),
tf.less_equal(y_max, win_y_min), tf.less_equal(x_max, win_x_min)
], 1)
valid_indices = tf.reshape(
tf.where(tf.logical_not(tf.reduce_any(coordinate_violations, 1))), [-1])
return gather(boxlist, valid_indices), valid_indices
def clip_to_window(boxlist, window, filter_nonoverlapping=True):
"""Clip bounding boxes to a window.
This op clips any input bounding boxes (represented by bounding box
corners) to a window, optionally filtering out boxes that do not
overlap at all with the window.
Args:
boxlist: BoxList holding M_in boxes
window: a tensor of shape [4] representing the [y_min, x_min, y_max, x_max]
window to which the op should clip boxes.
filter_nonoverlapping: whether to filter out boxes that do not overlap at
all with the window.
Returns:
a BoxList holding M_out boxes where M_out <= M_in
"""
with tf.name_scope('ClipToWindow'):
y_min, x_min, y_max, x_max = tf.split(
value=boxlist.get(), num_or_size_splits=4, axis=1)
win_y_min = window[0]
win_x_min = window[1]
win_y_max = window[2]
win_x_max = window[3]
y_min_clipped = tf.maximum(tf.minimum(y_min, win_y_max), win_y_min)
y_max_clipped = tf.maximum(tf.minimum(y_max, win_y_max), win_y_min)
x_min_clipped = tf.maximum(tf.minimum(x_min, win_x_max), win_x_min)
x_max_clipped = tf.maximum(tf.minimum(x_max, win_x_max), win_x_min)
clipped = box_list.BoxList(
tf.concat([y_min_clipped, x_min_clipped, y_max_clipped, x_max_clipped],
1))
clipped = _copy_extra_fields(clipped, boxlist)
if filter_nonoverlapping:
areas = area(clipped)
nonzero_area_indices = tf.cast(
tf.reshape(tf.where(tf.greater(areas, 0.0)), [-1]), tf.int32)
clipped = gather(clipped, nonzero_area_indices)
return clipped
def height_width(boxlist):
"""Computes height and width of boxes in boxlist.
Args:
boxlist: BoxList holding N boxes
Returns:
Height: A tensor with shape [N] representing box heights.
Width: A tensor with shape [N] representing box widths.
"""
with tf.name_scope('HeightWidth'):
y_min, x_min, y_max, x_max = tf.split(
value=boxlist.get(), num_or_size_splits=4, axis=1)
return tf.squeeze(y_max - y_min, [1]), tf.squeeze(x_max - x_min, [1])
def prune_small_boxes(boxlist, min_side):
"""Prunes small boxes in the boxlist which have a side smaller than min_side.
Args:
boxlist: BoxList holding N boxes.
min_side: Minimum width AND height of box to survive pruning.
Returns:
A pruned boxlist.
"""
with tf.name_scope('PruneSmallBoxes'):
height, width = height_width(boxlist)
is_valid = tf.logical_and(tf.greater_equal(width, min_side),
tf.greater_equal(height, min_side))
return gather(boxlist, tf.reshape(tf.where(is_valid), [-1]))
def assert_or_prune_invalid_boxes(boxes):
"""Makes sure boxes have valid sizes (ymax >= ymin, xmax >= xmin).
When the hardware supports assertions, the function raises an error when
boxes have an invalid size. If assertions are not supported (e.g. on TPU),
boxes with invalid sizes are filtered out.
Args:
boxes: float tensor of shape [num_boxes, 4]
Returns:
boxes: float tensor of shape [num_valid_boxes, 4] with invalid boxes
filtered out.
Raises:
tf.errors.InvalidArgumentError: When we detect boxes with invalid size.
This is not supported on TPUs.
"""
ymin, xmin, ymax, xmax = tf.split(
boxes, num_or_size_splits=4, axis=1)
height_check = tf.Assert(tf.reduce_all(ymax >= ymin), [ymin, ymax])
width_check = tf.Assert(tf.reduce_all(xmax >= xmin), [xmin, xmax])
with tf.control_dependencies([height_check, width_check]):
boxes_tensor = tf.concat([ymin, xmin, ymax, xmax], axis=1)
boxlist = box_list.BoxList(boxes_tensor)
boxlist = prune_small_boxes(boxlist, 0)
return boxlist.get()
def to_absolute_coordinates(boxlist,
height,
width,
check_range=True,
maximum_normalized_coordinate=1.1):
"""Converts normalized box coordinates to absolute pixel coordinates.
This function raises an assertion failed error when the maximum box coordinate
value is larger than maximum_normalized_coordinate (in which case coordinates
are already absolute).
Args:
boxlist: BoxList with coordinates in range [0, 1].
height: Maximum value for height of absolute box coordinates.
width: Maximum value for width of absolute box coordinates.
check_range: If True, checks if the coordinates are normalized or not.
maximum_normalized_coordinate: Maximum coordinate value to be considered
as normalized, default to 1.1.
Returns:
boxlist with absolute coordinates in terms of the image size.
"""
with tf.name_scope('ToAbsoluteCoordinates'):
height = tf.cast(height, tf.float32)
width = tf.cast(width, tf.float32)
# Ensure range of input boxes is correct.
if check_range:
box_maximum = tf.reduce_max(boxlist.get())
max_assert = tf.Assert(
tf.greater_equal(maximum_normalized_coordinate, box_maximum),
['maximum box coordinate value is larger '
'than %f: ' % maximum_normalized_coordinate, box_maximum])
with tf.control_dependencies([max_assert]):
width = tf.identity(width)
return scale(boxlist, height, width)
| 12,856 | 35.62963 | 80 | py |
models | models-master/official/projects/centernet/ops/nms_ops.py | # Copyright 2023 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.
"""nms computation."""
import tensorflow as tf
from official.projects.yolo.ops import box_ops
NMS_TILE_SIZE = 512
# pylint: disable=missing-function-docstring
def aggregated_comparative_iou(boxes1, boxes2=None, iou_type=0):
k = tf.shape(boxes1)[-2]
boxes1 = tf.expand_dims(boxes1, axis=-2)
boxes1 = tf.tile(boxes1, [1, 1, k, 1])
if boxes2 is not None:
boxes2 = tf.expand_dims(boxes2, axis=-2)
boxes2 = tf.tile(boxes2, [1, 1, k, 1])
boxes2 = tf.transpose(boxes2, perm=(0, 2, 1, 3))
else:
boxes2 = tf.transpose(boxes1, perm=(0, 2, 1, 3))
if iou_type == 0: # diou
_, iou = box_ops.compute_diou(boxes1, boxes2)
elif iou_type == 1: # giou
_, iou = box_ops.compute_giou(boxes1, boxes2)
else:
iou = box_ops.compute_iou(boxes1, boxes2, yxyx=True)
return iou
# pylint: disable=missing-function-docstring
def sort_drop(objectness, box, classificationsi, k):
objectness, ind = tf.math.top_k(objectness, k=k)
ind_m = tf.ones_like(ind) * tf.expand_dims(
tf.range(0,
tf.shape(objectness)[0]), axis=-1)
bind = tf.stack([tf.reshape(ind_m, [-1]), tf.reshape(ind, [-1])], axis=-1)
box = tf.gather_nd(box, bind)
classifications = tf.gather_nd(classificationsi, bind)
bsize = tf.shape(ind)[0]
box = tf.reshape(box, [bsize, k, -1])
classifications = tf.reshape(classifications, [bsize, k, -1])
return objectness, box, classifications
# pylint: disable=missing-function-docstring
def segment_nms(boxes, classes, confidence, k, iou_thresh):
mrange = tf.range(k)
mask_x = tf.tile(
tf.transpose(tf.expand_dims(mrange, axis=-1), perm=[1, 0]), [k, 1])
mask_y = tf.tile(tf.expand_dims(mrange, axis=-1), [1, k])
mask_diag = tf.expand_dims(mask_x > mask_y, axis=0)
iou = aggregated_comparative_iou(boxes, iou_type=0)
# duplicate boxes
iou_mask = iou >= iou_thresh
iou_mask = tf.logical_and(mask_diag, iou_mask)
iou *= tf.cast(iou_mask, iou.dtype)
can_suppress_others = 1 - tf.cast(
tf.reduce_any(iou_mask, axis=-2), boxes.dtype)
raw = tf.cast(can_suppress_others, boxes.dtype)
boxes *= tf.expand_dims(raw, axis=-1)
confidence *= tf.cast(raw, confidence.dtype)
classes *= tf.cast(raw, classes.dtype)
return boxes, classes, confidence
# pylint: disable=missing-function-docstring
def nms(boxes,
classes,
confidence,
k,
pre_nms_thresh,
nms_thresh,
limit_pre_thresh=False,
use_classes=True):
if limit_pre_thresh:
confidence, boxes, classes = sort_drop(confidence, boxes, classes, k)
mask = tf.fill(
tf.shape(confidence), tf.cast(pre_nms_thresh, dtype=confidence.dtype))
mask = tf.math.ceil(tf.nn.relu(confidence - mask))
confidence = confidence * mask
mask = tf.expand_dims(mask, axis=-1)
boxes = boxes * mask
classes = classes * mask
if use_classes:
confidence = tf.reduce_max(classes, axis=-1)
confidence, boxes, classes = sort_drop(confidence, boxes, classes, k)
classes = tf.cast(tf.argmax(classes, axis=-1), tf.float32)
boxes, classes, confidence = segment_nms(boxes, classes, confidence, k,
nms_thresh)
confidence, boxes, classes = sort_drop(confidence, boxes, classes, k)
classes = tf.squeeze(classes, axis=-1)
return boxes, classes, confidence
| 3,923 | 31.163934 | 76 | py |
models | models-master/official/projects/centernet/ops/__init__.py | # Copyright 2023 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.
| 609 | 39.666667 | 74 | py |
models | models-master/official/projects/centernet/ops/loss_ops.py | # Copyright 2023 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.
"""Operations for compute losses for centernet."""
import tensorflow as tf
from official.vision.ops import sampling_ops
def _get_shape(tensor, num_dims):
assert len(tensor.shape.as_list()) == num_dims
return sampling_ops.combined_static_and_dynamic_shape(tensor)
def flatten_spatial_dimensions(batch_images):
# pylint: disable=unbalanced-tuple-unpacking
batch_size, height, width, channels = _get_shape(batch_images, 4)
return tf.reshape(batch_images, [batch_size, height * width,
channels])
def multi_range(limit,
value_repetitions=1,
range_repetitions=1,
dtype=tf.int32):
"""Creates a sequence with optional value duplication and range repetition.
As an example (see the Args section for more details),
_multi_range(limit=2, value_repetitions=3, range_repetitions=4) returns:
[0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1]
NOTE: Repurposed from Google OD API.
Args:
limit: A 0-D Tensor (scalar). Upper limit of sequence, exclusive.
value_repetitions: Integer. The number of times a value in the sequence is
repeated. With value_repetitions=3, the result is [0, 0, 0, 1, 1, 1, ..].
range_repetitions: Integer. The number of times the range is repeated. With
range_repetitions=3, the result is [0, 1, 2, .., 0, 1, 2, ..].
dtype: The type of the elements of the resulting tensor.
Returns:
A 1-D tensor of type `dtype` and size
[`limit` * `value_repetitions` * `range_repetitions`] that contains the
specified range with given repetitions.
"""
return tf.reshape(
tf.tile(
tf.expand_dims(tf.range(limit, dtype=dtype), axis=-1),
multiples=[range_repetitions, value_repetitions]), [-1])
def add_batch_to_indices(indices):
shape = tf.shape(indices)
batch_size = shape[0]
num_instances = shape[1]
batch_range = multi_range(limit=batch_size, value_repetitions=num_instances)
batch_range = tf.reshape(batch_range, shape=(batch_size, num_instances, 1))
return tf.concat([batch_range, indices], axis=-1)
def get_num_instances_from_weights(gt_weights_list):
"""Computes the number of instances/boxes from the weights in a batch.
Args:
gt_weights_list: A list of float tensors with shape
[max_num_instances] representing whether there is an actual instance in
the image (with non-zero value) or is padded to match the
max_num_instances (with value 0.0). The list represents the batch
dimension.
Returns:
A scalar integer tensor incidating how many instances/boxes are in the
images in the batch. Note that this function is usually used to normalize
the loss so the minimum return value is 1 to avoid weird behavior.
"""
# This can execute in graph mode
gt_weights_list = tf.convert_to_tensor(
gt_weights_list, dtype=gt_weights_list[0].dtype)
num_instances = tf.map_fn(
fn=lambda x: tf.math.count_nonzero(x, dtype=gt_weights_list[0].dtype),
elems=gt_weights_list)
num_instances = tf.reduce_sum(num_instances)
num_instances = tf.maximum(num_instances, 1)
return num_instances
def get_batch_predictions_from_indices(batch_predictions, indices):
"""Gets the values of predictions in a batch at the given indices.
The indices are expected to come from the offset targets generation functions
in this library. The returned value is intended to be used inside a loss
function.
Args:
batch_predictions: A tensor of shape [batch_size, height, width, channels]
or [batch_size, height, width, class, channels] for class-specific
features (e.g. keypoint joint offsets).
indices: A tensor of shape [num_instances, 3] for single class features or
[num_instances, 4] for multiple classes features.
Returns:
values: A tensor of shape [num_instances, channels] holding the predicted
values at the given indices.
"""
return tf.gather_nd(batch_predictions, indices)
def get_valid_anchor_weights_in_flattened_image(true_image_shapes, height,
width):
"""Computes valid anchor weights for an image assuming pixels to be flattened.
This function is useful when we only want to penalize valid areas in the
image in the case when padding is used. The function assumes that the loss
function will be applied after flattening the spatial dimensions and returns
anchor weights accordingly.
Args:
true_image_shapes: An integer tensor of shape [batch_size, 3] representing
the true image shape (without padding) for each sample in the batch.
height: height of the prediction from the network.
width: width of the prediction from the network.
Returns:
valid_anchor_weights: a float tensor of shape [batch_size, height * width]
with 1s in locations where the spatial coordinates fall within the height
and width in true_image_shapes.
"""
indices = tf.reshape(tf.range(height * width), [1, -1])
batch_size = tf.shape(true_image_shapes)[0]
batch_indices = tf.ones((batch_size, 1), dtype=tf.int32) * indices
y_coords, x_coords, _ = get_row_col_channel_indices_from_flattened_indices(
batch_indices, width, 1)
max_y, max_x = true_image_shapes[:, 0], true_image_shapes[:, 1]
max_x = tf.cast(tf.expand_dims(max_x, 1), tf.float32)
max_y = tf.cast(tf.expand_dims(max_y, 1), tf.float32)
x_coords = tf.cast(x_coords, tf.float32)
y_coords = tf.cast(y_coords, tf.float32)
valid_mask = tf.math.logical_and(x_coords < max_x, y_coords < max_y)
return tf.cast(valid_mask, tf.float32)
def get_row_col_channel_indices_from_flattened_indices(indices: int,
num_cols: int,
num_channels: int):
"""Computes row, column and channel indices from flattened indices.
NOTE: Repurposed from Google OD API.
Args:
indices: An `int` tensor of any shape holding the indices in the flattened
space.
num_cols: `int`, number of columns in the image (width).
num_channels: `int`, number of channels in the image.
Returns:
row_indices: The row indices corresponding to each of the input indices.
Same shape as indices.
col_indices: The column indices corresponding to each of the input indices.
Same shape as indices.
channel_indices. The channel indices corresponding to each of the input
indices.
"""
# Avoid using mod operator to make the ops more easy to be compatible with
# different environments, e.g. WASM.
# all inputs and outputs are dtype int32
row_indices = (indices // num_channels) // num_cols
col_indices = (indices // num_channels) - row_indices * num_cols
channel_indices_temp = indices // num_channels
channel_indices = indices - channel_indices_temp * num_channels
return row_indices, col_indices, channel_indices
| 7,558 | 37.764103 | 80 | py |
models | models-master/official/projects/centernet/ops/box_list.py | # Copyright 2023 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.
"""Bounding Box List definition.
BoxList represents a list of bounding boxes as tensorflow
tensors, where each bounding box is represented as a row of 4 numbers,
[y_min, x_min, y_max, x_max]. It is assumed that all bounding boxes
within a given list correspond to a single image. See also
box_list_ops.py for common box related operations (such as area, iou, etc).
Optionally, users can add additional related fields (such as weights).
We assume the following things to be true about fields:
* they correspond to boxes in the box_list along the 0th dimension
* they have inferrable rank at graph construction time
* all dimensions except for possibly the 0th can be inferred
(i.e., not None) at graph construction time.
Some other notes:
* Following tensorflow conventions, we use height, width ordering,
and correspondingly, y,x (or ymin, xmin, ymax, xmax) ordering
* Tensors are always provided as (flat) [N, 4] tensors.
"""
import tensorflow as tf
def _get_dim_as_int(dim):
"""Utility to get v1 or v2 TensorShape dim as an int.
Args:
dim: The TensorShape dimension to get as an int
Returns:
None or an int.
"""
try:
return dim.value
except AttributeError:
return dim
class BoxList(object):
"""Box collection."""
def __init__(self, boxes):
"""Constructs box collection.
Args:
boxes: a tensor of shape [N, 4] representing box corners
Raises:
ValueError: if invalid dimensions for bbox data or if bbox data is not in
float32 format.
"""
if len(boxes.get_shape()) != 2 or boxes.get_shape()[-1] != 4:
raise ValueError('Invalid dimensions for box data: {}'.format(
boxes.shape))
if boxes.dtype != tf.float32:
raise ValueError('Invalid tensor type: should be tf.float32')
self.data = {'boxes': boxes}
def num_boxes(self):
"""Returns number of boxes held in collection.
Returns:
a tensor representing the number of boxes held in the collection.
"""
return tf.shape(self.data['boxes'])[0]
def num_boxes_static(self):
"""Returns number of boxes held in collection.
This number is inferred at graph construction time rather than run-time.
Returns:
Number of boxes held in collection (integer) or None if this is not
inferrable at graph construction time.
"""
return _get_dim_as_int(self.data['boxes'].get_shape()[0])
def get_all_fields(self):
"""Returns all fields."""
return self.data.keys()
def get_extra_fields(self):
"""Returns all non-box fields (i.e., everything not named 'boxes')."""
return [k for k in self.data.keys() if k != 'boxes']
def add_field(self, field, field_data):
"""Add field to box list.
This method can be used to add related box data such as
weights/labels, etc.
Args:
field: a string key to access the data via `get`
field_data: a tensor containing the data to store in the BoxList
"""
self.data[field] = field_data
def has_field(self, field):
return field in self.data
def get(self):
"""Convenience function for accessing box coordinates.
Returns:
a tensor with shape [N, 4] representing box coordinates.
"""
return self.get_field('boxes')
def set(self, boxes):
"""Convenience function for setting box coordinates.
Args:
boxes: a tensor of shape [N, 4] representing box corners
Raises:
ValueError: if invalid dimensions for bbox data
"""
if len(boxes.get_shape()) != 2 or boxes.get_shape()[-1] != 4:
raise ValueError('Invalid dimensions for box data.')
self.data['boxes'] = boxes
def get_field(self, field):
"""Accesses a box collection and associated fields.
This function returns specified field with object; if no field is specified,
it returns the box coordinates.
Args:
field: this optional string parameter can be used to specify
a related field to be accessed.
Returns:
a tensor representing the box collection or an associated field.
Raises:
ValueError: if invalid field
"""
if not self.has_field(field):
raise ValueError('field ' + str(field) + ' does not exist')
return self.data[field]
def set_field(self, field, value):
"""Sets the value of a field.
Updates the field of a box_list with a given value.
Args:
field: (string) name of the field to set value.
value: the value to assign to the field.
Raises:
ValueError: if the box_list does not have specified field.
"""
if not self.has_field(field):
raise ValueError('field %s does not exist' % field)
self.data[field] = value
def get_center_coordinates_and_sizes(self):
"""Computes the center coordinates, height and width of the boxes.
Returns:
a list of 4 1-D tensors [ycenter, xcenter, height, width].
"""
with tf.name_scope('get_center_coordinates_and_sizes'):
box_corners = self.get()
ymin, xmin, ymax, xmax = tf.unstack(tf.transpose(box_corners))
width = xmax - xmin
height = ymax - ymin
ycenter = ymin + height / 2.
xcenter = xmin + width / 2.
return [ycenter, xcenter, height, width]
def transpose_coordinates(self):
"""Transpose the coordinate representation in a boxlist."""
with tf.name_scope('transpose_coordinates'):
y_min, x_min, y_max, x_max = tf.split(
value=self.get(), num_or_size_splits=4, axis=1)
self.set(tf.concat([x_min, y_min, x_max, y_max], 1))
def as_tensor_dict(self, fields=None):
"""Retrieves specified fields as a dictionary of tensors.
Args:
fields: (optional) list of fields to return in the dictionary.
If None (default), all fields are returned.
Returns:
tensor_dict: A dictionary of tensors specified by fields.
Raises:
ValueError: if specified field is not contained in boxlist.
"""
tensor_dict = {}
if fields is None:
fields = self.get_all_fields()
for field in fields:
if not self.has_field(field):
raise ValueError('boxlist must contain all specified fields')
tensor_dict[field] = self.get_field(field)
return tensor_dict
| 6,813 | 30.546296 | 80 | py |
models | models-master/official/projects/centernet/losses/centernet_losses_test.py | # Copyright 2023 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.
"""Tests for losses of centernet model."""
import numpy as np
import tensorflow as tf
from official.projects.centernet.losses import centernet_losses
LOG_2 = np.log(2)
LOG_3 = np.log(3)
class L1LocalizationLossTest(tf.test.TestCase):
def test_returns_correct_loss(self):
def graph_fn():
loss = centernet_losses.L1LocalizationLoss()
pred = [[0.1, 0.2], [0.7, 0.5]]
target = [[0.9, 1.0], [0.1, 0.4]]
weights = [[1.0, 0.0], [1.0, 1.0]]
return loss(pred, target, weights=weights)
computed_value = graph_fn()
self.assertAllClose(computed_value, [[0.8, 0.0], [0.6, 0.1]], rtol=1e-6)
class PenaltyReducedLogisticFocalLossTest(tf.test.TestCase):
"""Testing loss function."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._prediction = np.array([
# First batch
[[1 / 2, 1 / 4, 3 / 4],
[3 / 4, 1 / 3, 1 / 3]],
# Second Batch
[[0.0, 1.0, 1 / 2],
[3 / 4, 2 / 3, 1 / 3]]], np.float32)
self._prediction = np.log(self._prediction / (1 - self._prediction))
self._target = np.array([
# First batch
[[1.0, 0.91, 1.0],
[0.36, 0.84, 1.0]],
# Second Batch
[[0.01, 1.0, 0.75],
[0.96, 1.0, 1.0]]], np.float32)
def test_returns_correct_loss(self):
def graph_fn(prediction, target):
weights = tf.constant([
[[1.0], [1.0]],
[[1.0], [1.0]],
])
loss = centernet_losses.PenaltyReducedLogisticFocalLoss(
alpha=2.0, beta=0.5)
computed_value = loss(prediction, target, weights=weights)
return computed_value
computed_value = graph_fn(self._prediction, self._target)
expected_value = np.array([
# First batch
[[1 / 4 * LOG_2,
0.3 * 0.0625 * (2 * LOG_2 - LOG_3),
1 / 16 * (2 * LOG_2 - LOG_3)],
[0.8 * 9 / 16 * 2 * LOG_2,
0.4 * 1 / 9 * (LOG_3 - LOG_2),
4 / 9 * LOG_3]],
# Second Batch
[[0.0,
0.0,
1 / 2 * 1 / 4 * LOG_2],
[0.2 * 9 / 16 * 2 * LOG_2,
1 / 9 * (LOG_3 - LOG_2),
4 / 9 * LOG_3]]])
self.assertAllClose(expected_value, computed_value, rtol=1e-3, atol=1e-3)
def test_returns_correct_loss_weighted(self):
def graph_fn(prediction, target):
weights = tf.constant([
[[1.0, 0.0, 1.0], [0.0, 0.0, 1.0]],
[[1.0, 1.0, 1.0], [0.0, 0.0, 0.0]],
])
loss = centernet_losses.PenaltyReducedLogisticFocalLoss(
alpha=2.0, beta=0.5)
computed_value = loss(prediction, target, weights=weights)
return computed_value
computed_value = graph_fn(self._prediction, self._target)
expected_value = np.array([
# First batch
[[1 / 4 * LOG_2,
0.0,
1 / 16 * (2 * LOG_2 - LOG_3)],
[0.0,
0.0,
4 / 9 * LOG_3]],
# Second Batch
[[0.0,
0.0,
1 / 2 * 1 / 4 * LOG_2],
[0.0,
0.0,
0.0]]])
self.assertAllClose(expected_value, computed_value, rtol=1e-3, atol=1e-3)
if __name__ == '__main__':
tf.test.main()
| 3,777 | 28.748031 | 77 | py |
models | models-master/official/projects/centernet/losses/centernet_losses.py | # Copyright 2023 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.
"""Losses for centernet model."""
import tensorflow as tf
class PenaltyReducedLogisticFocalLoss(object):
"""Penalty-reduced pixelwise logistic regression with focal loss."""
def __init__(self, alpha=2.0, beta=4.0, sigmoid_clip_value=1e-4):
"""Constructor.
The loss is defined in Equation (1) of the Objects as Points[1] paper.
Although the loss is defined per-pixel in the output space, this class
assumes that each pixel is an anchor to be compatible with the base class.
[1]: https://arxiv.org/abs/1904.07850
Args:
alpha: Focussing parameter of the focal loss. Increasing this will
decrease the loss contribution of the well classified examples.
beta: The local penalty reduction factor. Increasing this will decrease
the contribution of loss due to negative pixels near the keypoint.
sigmoid_clip_value: The sigmoid operation used internally will be clipped
between [sigmoid_clip_value, 1 - sigmoid_clip_value)
"""
self._alpha = alpha
self._beta = beta
self._sigmoid_clip_value = sigmoid_clip_value
super(PenaltyReducedLogisticFocalLoss, self).__init__()
def __call__(self, prediction_tensor, target_tensor, weights=1.0):
"""Compute loss function.
In all input tensors, `num_anchors` is the total number of pixels in the
the output space.
Args:
prediction_tensor: A float tensor of shape [batch_size, num_anchors,
num_classes] representing the predicted unscaled logits for each class.
The function will compute sigmoid on this tensor internally.
target_tensor: A float tensor of shape [batch_size, num_anchors,
num_classes] representing a tensor with the 'splatted' keypoints,
possibly using a gaussian kernel. This function assumes that
the target is bounded between [0, 1].
weights: a float tensor of shape, either [batch_size, num_anchors,
num_classes] or [batch_size, num_anchors, 1]. If the shape is
[batch_size, num_anchors, 1], all the classses are equally weighted.
Returns:
loss: a float tensor of shape [batch_size, num_anchors, num_classes]
representing the value of the loss function.
"""
with tf.name_scope('prlf_loss'):
is_present_tensor = tf.math.equal(target_tensor, 1.0)
prediction_tensor = tf.clip_by_value(tf.sigmoid(prediction_tensor),
self._sigmoid_clip_value,
1 - self._sigmoid_clip_value)
positive_loss = (tf.math.pow((1 - prediction_tensor), self._alpha) *
tf.math.log(prediction_tensor))
negative_loss = (tf.math.pow((1 - target_tensor), self._beta) *
tf.math.pow(prediction_tensor, self._alpha) *
tf.math.log(1 - prediction_tensor))
loss = -tf.where(is_present_tensor, positive_loss, negative_loss)
return loss * weights
class L1LocalizationLoss(object):
"""L1 loss or absolute difference."""
def __call__(self, prediction_tensor, target_tensor, weights=1.0):
"""Compute loss function.
When used in a per-pixel manner, each pixel should be given as an anchor.
Args:
prediction_tensor: A float tensor of shape [batch_size, num_anchors]
representing the (encoded) predicted locations of objects.
target_tensor: A float tensor of shape [batch_size, num_anchors]
representing the regression targets
weights: a float tensor of shape [batch_size, num_anchors]
Returns:
loss: a float tensor of shape [batch_size, num_anchors] tensor
representing the value of the loss function.
"""
with tf.name_scope('l1l_loss'):
return tf.compat.v1.losses.absolute_difference(
labels=target_tensor,
predictions=prediction_tensor,
weights=weights,
reduction=tf.losses.Reduction.NONE
)
| 4,548 | 40.354545 | 79 | py |
models | models-master/official/projects/centernet/losses/__init__.py | # Copyright 2023 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.
| 609 | 39.666667 | 74 | py |
models | models-master/official/projects/const_cl/train.py | # Copyright 2023 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.
"""Training driver."""
from absl import app
from absl import flags
import gin
# pylint: disable=unused-import
from official.common import distribute_utils
from official.common import flags as tfm_flags
from official.core import task_factory
from official.core import train_lib
from official.core import train_utils
from official.modeling import performance
from official.projects.const_cl.modeling import const_cl_model
from official.projects.const_cl.modeling.backbones import resnet_3d
from official.projects.const_cl.tasks.google import const_cl
# pylint: enable=unused-import
FLAGS = flags.FLAGS
def main(_):
gin.parse_config_files_and_bindings(FLAGS.gin_file, FLAGS.gin_params)
params = train_utils.parse_configuration(FLAGS)
model_dir = FLAGS.model_dir
if 'train' in FLAGS.mode:
# Pure eval modes do not output yaml files. Otherwise continuous eval job
# may race against the train job for writing the same file.
train_utils.serialize_config(params, model_dir)
if 'train_and_eval' in FLAGS.mode:
assert (params.task.train_data.feature_shape ==
params.task.validation_data.feature_shape), (
f'train {params.task.train_data.feature_shape} != validate '
f'{params.task.validation_data.feature_shape}')
# Set mixed_precision policy. Using 'mixed_float16' or 'mixed_bfloat16'
# can have significant impact on model speeds by utilizing float16 in case of
# GPUs, and bfloat16 in the case of TPUs. loss_scale takes effect only when
# dtype is float16
if params.runtime.mixed_precision_dtype:
performance.set_mixed_precision_policy(params.runtime.mixed_precision_dtype)
distribution_strategy = distribute_utils.get_distribution_strategy(
distribution_strategy=params.runtime.distribution_strategy,
all_reduce_alg=params.runtime.all_reduce_alg,
num_gpus=params.runtime.num_gpus,
tpu_address=params.runtime.tpu)
with distribution_strategy.scope():
task = task_factory.get_task(params.task, logging_dir=model_dir)
train_lib.run_experiment(
distribution_strategy=distribution_strategy,
task=task,
mode=FLAGS.mode,
params=params,
model_dir=model_dir)
train_utils.save_gin_config(FLAGS.mode, model_dir)
if __name__ == '__main__':
tfm_flags.define_flags()
app.run(main)
| 2,935 | 36.641026 | 80 | py |
models | models-master/official/projects/const_cl/datasets/video_ssl_inputs_test.py | # Copyright 2023 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.
"""Tests for video_ssl_inputs."""
import io
import numpy as np
from PIL import Image
import tensorflow as tf
from official.projects.const_cl.configs import const_cl as exp_cfg
from official.projects.const_cl.datasets import video_ssl_inputs
AUDIO_KEY = 'features/audio'
def fake_seq_example():
"""Creates fake data."""
random_image = np.random.randint(0, 256, size=(263, 320, 3), dtype=np.uint8)
random_image = Image.fromarray(random_image)
label = 42
with io.BytesIO() as buffer:
random_image.save(buffer, format='JPEG')
raw_image_bytes = buffer.getvalue()
seq_example = tf.train.SequenceExample()
seq_example.feature_lists.feature_list.get_or_create(
video_ssl_inputs.IMAGE_KEY).feature.add().bytes_list.value[:] = [
raw_image_bytes
]
seq_example.feature_lists.feature_list.get_or_create(
video_ssl_inputs.IMAGE_KEY).feature.add().bytes_list.value[:] = [
raw_image_bytes
]
seq_example.context.feature[
video_ssl_inputs.LABEL_KEY].int64_list.value[:] = [label]
random_audio = np.random.normal(size=(10, 256)).tolist()
for s in random_audio:
seq_example.feature_lists.feature_list.get_or_create(
AUDIO_KEY).feature.add().float_list.value[:] = s
return seq_example, label
class VideoSslInputsTest(tf.test.TestCase):
def test_video_ssl_input_pretrain(self):
params = exp_cfg.const_cl_pretrain_kinetics400().task.train_data
decoder = video_ssl_inputs.Decoder()
parser = video_ssl_inputs.Parser(params).parse_fn(params.is_training)
seq_example, _ = fake_seq_example()
input_tensor = tf.constant(seq_example.SerializeToString())
decoded_tensors = decoder.decode(input_tensor)
output_tensor = parser(decoded_tensors)
features, _ = output_tensor
image = features['image']
instances_position = features['instances_position']
instances_mask = features['instances_mask']
self.assertAllEqual(image.shape, (32, 224, 224, 3))
self.assertAllEqual(instances_position.shape, (32, 8, 4))
self.assertAllEqual(instances_mask.shape, (32, 8))
if __name__ == '__main__':
tf.test.main()
| 2,744 | 32.47561 | 78 | py |
models | models-master/official/projects/const_cl/datasets/video_ssl_inputs.py | # Copyright 2023 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.
"""Video SSL datasets."""
from typing import Dict, Tuple, Optional
import tensorflow as tf
from official.projects.video_ssl.dataloaders import video_ssl_input
IMAGE_KEY = video_ssl_input.IMAGE_KEY
LABEL_KEY = video_ssl_input.LABEL_KEY
Decoder = video_ssl_input.Decoder
class Parser(video_ssl_input.Parser):
"""Parses a video dataset for SSL."""
def __init__(self,
input_params,
image_key: str = IMAGE_KEY,
label_key: str = LABEL_KEY):
super().__init__(
input_params=input_params,
image_key=image_key,
label_key=label_key)
self._num_instances = input_params.num_instances
self._num_frames = input_params.feature_shape[0]
def _generate_random_positions(
self, seed: Optional[int] = None) -> Tuple[tf.Tensor, tf.Tensor]:
"""Generates random instance positions in videos."""
num_frames = self._num_frames * 2 if self._is_ssl else self._num_frames
shape = [num_frames, self._num_instances, 4]
xmin = tf.random.uniform(shape=shape[:-1],
minval=0.0,
maxval=1.0,
dtype=tf.float32,
seed=seed)
ymin = tf.random.uniform(shape=shape[:-1],
minval=0.0,
maxval=1.0,
dtype=tf.float32,
seed=seed)
xdelta = tf.random.uniform(shape=shape[:-1],
minval=0.1,
maxval=0.5,
dtype=tf.float32,
seed=seed)
aspect_ratio = tf.random.uniform(shape=shape[:-1],
minval=0.5,
maxval=2.0,
dtype=tf.float32,
seed=seed)
ydelta = xdelta * aspect_ratio
xmax = tf.math.minimum(xmin + xdelta, 1.0 - 1e-3)
ymax = tf.math.minimum(ymin + ydelta, 1.0 - 1e-3)
random_positions = tf.stack([ymin, xmin, ymax, xmax], axis=-1)
random_positions = tf.cast(random_positions, dtype=self._dtype)
instances_mask = tf.ones(shape[:-1], dtype=tf.bool)
return random_positions, instances_mask
def _parse_train_data(
self, decoded_tensors: Dict[str, tf.Tensor]
) -> Tuple[Dict[str, tf.Tensor], tf.Tensor]:
"""Parses data for training."""
features, label = super()._parse_train_data(decoded_tensors=decoded_tensors)
instances_position, instances_mask = self._generate_random_positions(
seed=1234)
features.update({
'instances_position': instances_position,
'instances_mask': instances_mask,
})
return features, label
class PostBatchProcessor(video_ssl_input.PostBatchProcessor):
"""Processes a video and label dataset which is batched."""
def __call__(self,
features: Dict[str, tf.Tensor],
label: tf.Tensor) -> Tuple[Dict[str, tf.Tensor], tf.Tensor]:
"""Postprocesses features and label tensors."""
features, label = super().__call__(features, label)
for key in ['instances_position', 'instances_mask']:
if key in features and self._is_ssl and self._is_training:
features[key] = tf.concat(
tf.split(features[key], num_or_size_splits=2, axis=1), axis=0)
return features, label
| 4,025 | 36.981132 | 80 | py |
models | models-master/official/projects/const_cl/configs/const_cl_test.py | # Copyright 2023 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.
# pylint: disable=unused-import
from absl.testing import parameterized
import tensorflow as tf
from official import vision
from official.core import config_definitions as cfg
from official.core import exp_factory
from official.projects.const_cl.configs import const_cl as exp_cfg
class VideoClassificationConfigTest(tf.test.TestCase, parameterized.TestCase):
@parameterized.parameters(('const_cl_pretrain_kinetics400',),
('const_cl_pretrain_kinetics600',))
def test_const_cl_pretrain_configs(self, config_name):
config = exp_factory.get_exp_config(config_name)
self.assertIsInstance(config, cfg.ExperimentConfig)
self.assertIsInstance(config.task, exp_cfg.ConstCLPretrainTask)
self.assertIsInstance(config.task.model, exp_cfg.ConstCLModel)
self.assertIsInstance(config.task.losses, exp_cfg.ConstCLLosses)
self.assertIsInstance(config.task.train_data, exp_cfg.DataConfig)
config.task.train_data.is_training = None
with self.assertRaises(KeyError):
config.validate()
if __name__ == '__main__':
tf.test.main()
| 1,694 | 38.418605 | 78 | py |
models | models-master/official/projects/const_cl/configs/backbones_3d.py | # Copyright 2023 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.
"""3D Backbones configurations."""
import dataclasses
from typing import Tuple
from official.vision.configs import backbones_3d
ResNet3DBlock = backbones_3d.ResNet3DBlock
@dataclasses.dataclass
class ResNet3DY(backbones_3d.ResNet3D):
pass
@dataclasses.dataclass
class ResNet3DY50(ResNet3DY):
"""Block specifications of the Resnet50 (3DY) model."""
model_id: int = 50
block_specs: Tuple[
ResNet3DBlock, ResNet3DBlock, ResNet3DBlock, ResNet3DBlock] = (
ResNet3DBlock(temporal_strides=1,
temporal_kernel_sizes=(3, 3, 3),
use_self_gating=True),
ResNet3DBlock(temporal_strides=1,
temporal_kernel_sizes=(3, 1, 3, 1),
use_self_gating=True),
ResNet3DBlock(temporal_strides=1,
temporal_kernel_sizes=(3, 1, 3, 1, 3, 1),
use_self_gating=True),
ResNet3DBlock(temporal_strides=1,
temporal_kernel_sizes=(1, 3, 1),
use_self_gating=True))
@dataclasses.dataclass
class Backbone3D(backbones_3d.Backbone3D):
"""Configuration for backbones.
Attributes:
type: type of backbone be used, one of the fields below.
resnet_3dy: resnet_3dy backbone config.
"""
type: str = 'resnet_3dy'
resnet_3dy: ResNet3DY = dataclasses.field(default_factory=ResNet3DY50)
| 2,013 | 32.566667 | 74 | py |
models | models-master/official/projects/const_cl/configs/backbones_3d_test.py | # Copyright 2023 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.
"""Tests for backbones_3d."""
import tensorflow as tf
from official.projects.const_cl.configs import backbones_3d
class Backbones3DTest(tf.test.TestCase):
def test_conv3dy_config(self):
config = backbones_3d.Backbone3D(
type='resnet_3dy',
resnet_3d=backbones_3d.ResNet3DY50())
config.validate()
if __name__ == '__main__':
tf.test.main()
| 981 | 28.757576 | 74 | py |
models | models-master/official/projects/const_cl/configs/head.py | # Copyright 2023 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.
"""Configs for different model heads."""
import dataclasses
from typing import Optional
from official.modeling import hyperparams
@dataclasses.dataclass
class MLP(hyperparams.Config):
"""Config for the MLP head."""
normalize_inputs: bool = True
num_hidden_channels: int = 2048
num_hidden_layers: int = 3
num_output_channels: int = 128
use_sync_bn: bool = False
norm_momentum: float = 0.997
norm_epsilon: float = 1e-5
activation: Optional[str] = 'relu'
@dataclasses.dataclass
class InstanceReconstructor(hyperparams.Config):
"""Config for the instance reconstructor head."""
normalize_inputs: bool = True
context_level: int = 5
# parameters for projector
num_output_channels: int = 2048
# parameters for RoiAligner
crop_size: int = 4
sample_offset: float = 0.5
# parameters for TxDecoder
num_tx_channels: int = 128
num_tx_layers: int = 3
num_tx_heads: int = 3
use_bias: bool = True
activation: Optional[str] = 'gelu'
dropout_rate: float = 0.0
layer_norm_epsilon: float = 1e-12
use_positional_embedding: bool = True
@dataclasses.dataclass
class ActionTransformer(hyperparams.Config):
"""Config for the action transformer head."""
# parameters for classifier
num_hidden_layers: int = 0
num_hidden_channels: int = 0
use_sync_bn: bool = True
activation: str = 'relu'
# parameters for RoiAligner
crop_size: int = 4
sample_offset: float = 0.5
# parameters for TxDecoder
num_tx_channels: int = 128
num_tx_layers: int = 3
num_tx_heads: int = 3
use_bias: bool = True
tx_activation: Optional[str] = 'gelu'
dropout_rate: float = 0.0
layer_norm_epsilon: float = 1e-12
use_positional_embedding: bool = True
| 2,298 | 28.857143 | 74 | py |
models | models-master/official/projects/const_cl/configs/head_test.py | # Copyright 2023 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.
"""Tests for head."""
import tensorflow as tf
from official.projects.const_cl.configs import head as head_cfg
class HeadTest(tf.test.TestCase):
def test_mlp_head_valid(self):
config = head_cfg.MLP(
num_hidden_channels=128,
num_hidden_layers=4,
num_output_channels=1280,
use_sync_bn=True,
norm_momentum=0.99,
norm_epsilon=1e-5,
activation='relu')
config.validate()
def test_instance_reconstructor_head_valid(self):
config = head_cfg.InstanceReconstructor(
num_output_channels=1280,
layer_norm_epsilon=1e-12,
activation='relu')
config.validate()
def test_action_transformer_head_valid(self):
config = head_cfg.ActionTransformer(
activation='relu',
tx_activation='relu')
config.validate()
if __name__ == '__main__':
tf.test.main()
| 1,473 | 28.48 | 74 | py |
models | models-master/official/projects/const_cl/configs/const_cl.py | # Copyright 2023 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.
"""Video classification configuration definition."""
import dataclasses
from official.core import config_definitions as cfg
from official.core import exp_factory
from official.modeling import hyperparams
from official.projects.const_cl.configs import backbones_3d as backbones_3d_cfg
from official.projects.const_cl.configs import head as head_cfg
from official.vision.configs import common
from official.vision.configs import video_classification
VideoClassificationTask = video_classification.VideoClassificationTask
@dataclasses.dataclass
class ConstCLPretrainTask(VideoClassificationTask):
pass
@dataclasses.dataclass
class DataConfig(video_classification.DataConfig):
"""The base configuration for building datasets."""
zero_centering_image: bool = True
is_ssl: bool = False
num_instances: int = 8
@dataclasses.dataclass
class ConstCLModel(hyperparams.Config):
"""The model config."""
model_type: str = 'video_classification'
backbone: backbones_3d_cfg.Backbone3D = dataclasses.field(
default_factory=lambda: backbones_3d_cfg.Backbone3D( # pylint: disable=g-long-lambda
type='resnet_3dy', resnet_3dy=backbones_3d_cfg.ResNet3DY50()
)
)
norm_activation: common.NormActivation = dataclasses.field(
default_factory=lambda: common.NormActivation( # pylint: disable=g-long-lambda
use_sync_bn=False, norm_momentum=0.9, norm_epsilon=1e-5
)
)
global_head: head_cfg.MLP = dataclasses.field(
default_factory=lambda: head_cfg.MLP( # pylint: disable=g-long-lambda
use_sync_bn=False, normalize_inputs=False, norm_momentum=0.9
)
)
local_head: head_cfg.InstanceReconstructor = dataclasses.field(
default_factory=head_cfg.InstanceReconstructor
)
@dataclasses.dataclass
class ConstCLLosses(hyperparams.Config):
"""The config for ConST-CL losses."""
normalize_inputs: bool = True
global_temperature: float = 0.1
local_temperature: float = 0.2
global_weight: float = 1.0
local_weight: float = 0.001
l2_weight_decay: float = 0.0
@exp_factory.register_config_factory('const_cl_pretrain_kinetics400')
def const_cl_pretrain_kinetics400() -> cfg.ExperimentConfig:
"""Pretrains SSL Video classification on Kinectics 400 with ResNet."""
exp = video_classification.video_classification_kinetics400()
exp.task = ConstCLPretrainTask(**exp.task.as_dict())
exp.task.train_data.zero_centering_image = True
exp.task.train_data = DataConfig(is_ssl=True, **exp.task.train_data.as_dict())
exp.task.train_data.feature_shape = (16, 224, 224, 3)
exp.task.train_data.temporal_stride = 2
exp.task.train_data.aug_min_area_ratio = 0.3
exp.task.model = ConstCLModel()
exp.task.model.model_type = 'const_cl_model'
exp.task.losses = ConstCLLosses()
return exp
@exp_factory.register_config_factory('const_cl_pretrain_kinetics600')
def const_cl_pretrain_kinetics600() -> cfg.ExperimentConfig:
"""Pretrains SSL Video classification on Kinectics 400 with ResNet."""
exp = video_classification.video_classification_kinetics600()
exp.task = ConstCLPretrainTask(**exp.task.as_dict())
exp.task.train_data.zero_centering_image = True
exp.task.train_data = DataConfig(is_ssl=True, **exp.task.train_data.as_dict())
exp.task.train_data.feature_shape = (16, 224, 224, 3)
exp.task.train_data.temporal_stride = 2
exp.task.train_data.aug_min_area_ratio = 0.3
exp.task.model = ConstCLModel()
exp.task.model.model_type = 'const_cl_model'
exp.task.losses = ConstCLLosses()
return exp
| 4,114 | 37.101852 | 91 | py |
models | models-master/official/projects/const_cl/modeling/const_cl_model.py | # Copyright 2023 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.
"""Builds ConST-CL SSL models."""
from typing import Mapping, Optional
import tensorflow as tf
from official.projects.const_cl.configs import const_cl as const_cl_cfg
from official.projects.const_cl.modeling.heads import instance_reconstructor
from official.projects.const_cl.modeling.heads import simple
from official.vision.modeling import backbones
from official.vision.modeling import factory_3d as model_factory
layers = tf.keras.layers
class ConstCLModel(tf.keras.Model):
"""A ConST-CL SSL model class builder."""
def __init__(
self,
backbone,
input_specs: Optional[Mapping[str, tf.keras.layers.InputSpec]] = None,
# global_head
num_hidden_layers: int = 3,
num_hidden_channels: int = 1024,
num_output_channels: int = 128,
use_sync_bn: bool = False,
norm_momentum: float = 0.99,
norm_epsilon: float = 1e-5,
activation: Optional[str] = None,
normalize_global_features: bool = False,
# local_head
context_level: int = 1,
num_tx_output_channels: int = 1024,
crop_size: int = 4,
sample_offset: float = 0.5,
num_tx_channels: int = 128,
num_tx_layers: int = 3,
num_tx_heads: int = 3,
use_bias: bool = True,
tx_activation: str = 'gelu',
dropout_rate: float = 0.0,
layer_norm_epsilon: float = 1e-6,
use_positional_embedding: bool = True,
normalize_local_features: bool = True,
**kwargs):
"""Video Classification initialization function.
Args:
backbone: a 3d backbone network.
input_specs: `tf.keras.layers.InputSpec` specs of the input tensor.
num_hidden_layers: the number of hidden layers in the MLP.
num_hidden_channels: the number of hidden nodes in the MLP.
num_output_channels: the number of final output nodes in the MLP.
use_sync_bn: whether to use sync batch norm in the MLP.
norm_momentum: the MLP batch norm momentum.
norm_epsilon: the MLP batch norm epsilon.
activation: the MLP activation function.
normalize_global_features: whether to normalize inputs to the MLP.
context_level: the number of context frame to use.
num_tx_output_channels: the number of final output channels for instance
reconstrcutor.
crop_size: the ROI aligner crop size.
sample_offset: the ROI aligner sample offset.
num_tx_channels: the Transformer decoder head channels.
num_tx_layers: the number of Transformer decoder layers.
num_tx_heads: the number of Transformer decoder heads per layer.
use_bias: whether to use bias in the Transformer.
tx_activation: the activation function to use in the Transformer.
dropout_rate: the dropout rate for Transformer.
layer_norm_epsilon: the layer norm epsilon.
use_positional_embedding: whether to use positional embedding.
normalize_local_features: whether to normalize input embeddings.
**kwargs: keyword arguments to be passed.
"""
if not input_specs:
input_specs = {
'image': layers.InputSpec(shape=[None, None, None, None, 3]),
'instances_position': layers.InputSpec(shape=[None, None, None, 4]),
'instances_mask': layers.InputSpec(shape=[None, None, None]),
}
self._self_setattr_tracking = False
self._config_dict = {
'backbone': backbone,
'num_hidden_layers': num_hidden_layers,
'num_hidden_channels': num_hidden_channels,
'num_output_channels': num_output_channels,
'use_sync_bn': use_sync_bn,
'norm_momentum': norm_momentum,
'norm_epsilon': norm_epsilon,
'activation': activation,
'normalize_global_features': normalize_global_features,
'context_level': context_level,
'num_tx_output_channels': num_tx_output_channels,
'crop_size': crop_size,
'sample_offset': sample_offset,
'num_tx_channels': num_tx_channels,
'num_tx_layers': num_tx_layers,
'num_tx_heads': num_tx_heads,
'use_bias': use_bias,
'tx_activation': tx_activation,
'dropout_rate': dropout_rate,
'layer_norm_epsilon': layer_norm_epsilon,
'use_positional_embedding': use_positional_embedding,
'normalize_local_features': normalize_local_features,
}
self._input_specs = input_specs
self._backbone = backbone
inputs = {
k: tf.keras.Input(shape=v.shape[1:]) for k, v in input_specs.items()
}
endpoints = backbone(inputs['image'])
res5 = endpoints['5']
res5 = tf.keras.layers.GlobalAveragePooling3D()(res5)
res5_1 = endpoints['5_1']
global_embeddings = simple.MLP(
num_hidden_layers=num_hidden_layers,
num_hidden_channels=num_hidden_channels,
num_output_channels=num_output_channels,
use_sync_bn=use_sync_bn,
norm_momentum=norm_momentum,
norm_epsilon=norm_epsilon,
activation=activation,
normalize_inputs=normalize_global_features)(res5)
instance_inputs = {
'features': res5_1,
'instances_position': inputs['instances_position'],
'instances_mask': inputs['instances_mask'],
}
instances_outputs = instance_reconstructor.InstanceReconstructor(
context_level=context_level,
# parameters for projector
num_output_channels=num_tx_output_channels,
# parameters for RoiAligner
crop_size=crop_size,
sample_offset=sample_offset,
# parameters for TxDecoder
num_tx_channels=num_tx_channels,
num_tx_layers=num_tx_layers,
num_tx_heads=num_tx_heads,
use_bias=use_bias,
activation=tx_activation,
dropout_rate=dropout_rate,
layer_norm_epsilon=layer_norm_epsilon,
use_positional_embedding=use_positional_embedding,
normalize_inputs=normalize_local_features)(instance_inputs)
outputs = instances_outputs
outputs['global_embeddings'] = global_embeddings
super().__init__(inputs=inputs, outputs=outputs, **kwargs)
@property
def checkpoint_items(self):
"""Returns a dictionary of items to be additionally checkpointed."""
return dict(backbone=self.backbone)
@property
def backbone(self):
return self._backbone
def get_config(self):
return self._config_dict
@classmethod
def from_config(cls, config, custom_objects=None):
return cls(**config)
@model_factory.register_model_builder('const_cl_model')
def build_const_cl_pretrain_model(
input_specs_dict: Mapping[str, tf.keras.layers.InputSpec],
model_config: const_cl_cfg.ConstCLModel,
num_classes: int,
l2_regularizer: Optional[tf.keras.regularizers.Regularizer] = None
) -> ConstCLModel:
"""Builds the ConST-CL video ssl model."""
del num_classes
backbone = backbones.factory.build_backbone(
input_specs=input_specs_dict['image'],
backbone_config=model_config.backbone,
norm_activation_config=model_config.norm_activation,
l2_regularizer=l2_regularizer)
# Norm layer type in the MLP head should same with backbone
if (model_config.norm_activation.use_sync_bn
!= model_config.global_head.use_sync_bn):
raise ValueError('Should use the same batch normalization type.')
return ConstCLModel(
backbone=backbone,
input_specs=input_specs_dict,
# global_head
num_hidden_channels=model_config.global_head.num_hidden_channels,
num_hidden_layers=model_config.global_head.num_hidden_layers,
num_output_channels=model_config.global_head.num_output_channels,
use_sync_bn=model_config.global_head.use_sync_bn,
norm_momentum=model_config.global_head.norm_momentum,
norm_epsilon=model_config.global_head.norm_epsilon,
activation=model_config.global_head.activation,
normalize_global_features=model_config.global_head.normalize_inputs,
# local_head
context_level=model_config.local_head.context_level,
num_tx_output_channels=model_config.local_head.num_output_channels,
crop_size=model_config.local_head.crop_size,
sample_offset=model_config.local_head.sample_offset,
num_tx_channels=model_config.local_head.num_tx_channels,
num_tx_layers=model_config.local_head.num_tx_layers,
num_tx_heads=model_config.local_head.num_tx_heads,
use_bias=model_config.local_head.use_bias,
tx_activation=model_config.local_head.activation,
dropout_rate=model_config.local_head.dropout_rate,
layer_norm_epsilon=model_config.local_head.layer_norm_epsilon,
use_positional_embedding=model_config.local_head.use_positional_embedding,
normalize_local_features=model_config.local_head.normalize_inputs)
| 9,301 | 38.922747 | 80 | py |
models | models-master/official/projects/const_cl/modeling/const_cl_model_test.py | # Copyright 2023 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.
"""Tests for const_cl_model."""
import tensorflow as tf
from official.projects.const_cl.configs import const_cl as const_cl_cfg
from official.projects.const_cl.modeling import const_cl_model
# pylint: disable=unused-import
from official.projects.const_cl.modeling.backbones import resnet_3d
# pylint: enable=unused-import
class ConstClModelTest(tf.test.TestCase):
def test_build_const_cl_pretrain_model(self):
model_config = const_cl_cfg.ConstCLModel()
images_input_specs = tf.keras.layers.InputSpec(
shape=[None, 16, 224, 224, 4])
boxes_input_specs = tf.keras.layers.InputSpec(shape=[None, 16, 8, 4])
masks_input_specs = tf.keras.layers.InputSpec(shape=[None, 16, 8])
input_specs_dict = {
'image': images_input_specs,
'instances_position': boxes_input_specs,
'instances_mask': masks_input_specs,
}
model = const_cl_model.build_const_cl_pretrain_model(
input_specs_dict=input_specs_dict,
model_config=model_config,
num_classes=500)
self.assertIsInstance(model, const_cl_model.ConstCLModel)
if __name__ == '__main__':
tf.test.main()
| 1,740 | 35.270833 | 74 | py |
models | models-master/official/projects/const_cl/modeling/backbones/nn_blocks_3d.py | # Copyright 2023 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.
"""Contains common building blocks for 3D networks."""
import tensorflow as tf
from official.vision.modeling.layers import nn_blocks_3d
from official.vision.modeling.layers import nn_layers
SelfGating = nn_blocks_3d.SelfGating
class BottleneckBlock3D(nn_blocks_3d.BottleneckBlock3D):
"""Creates a 3D bottleneck block."""
def build(self, input_shape):
self._shortcut_maxpool = tf.keras.layers.MaxPool3D(
pool_size=[1, 1, 1],
strides=[
self._temporal_strides, self._spatial_strides, self._spatial_strides
])
self._shortcut_conv = tf.keras.layers.Conv3D(
filters=4 * self._filters,
kernel_size=1,
strides=[
self._temporal_strides, self._spatial_strides, self._spatial_strides
],
use_bias=False,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer,
bias_regularizer=self._bias_regularizer,
name='shortcut_conv')
self._norm0 = self._norm(
axis=self._bn_axis,
momentum=self._norm_momentum,
epsilon=self._norm_epsilon,
name='shortcut_conv/batch_norm')
self._temporal_conv = tf.keras.layers.Conv3D(
filters=self._filters,
kernel_size=[self._temporal_kernel_size, 1, 1],
strides=[self._temporal_strides, 1, 1],
padding='same',
use_bias=False,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer,
bias_regularizer=self._bias_regularizer,
name='temporal_conv')
self._norm1 = self._norm(
axis=self._bn_axis,
momentum=self._norm_momentum,
epsilon=self._norm_epsilon,
name='temporal_conv/batch_norm')
self._spatial_conv = tf.keras.layers.Conv3D(
filters=self._filters,
kernel_size=[1, 3, 3],
strides=[1, self._spatial_strides, self._spatial_strides],
padding='same',
use_bias=False,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer,
bias_regularizer=self._bias_regularizer,
name='spatial_conv')
self._norm2 = self._norm(
axis=self._bn_axis,
momentum=self._norm_momentum,
epsilon=self._norm_epsilon,
name='spatial_conv/batch_norm')
self._expand_conv = tf.keras.layers.Conv3D(
filters=4 * self._filters,
kernel_size=[1, 1, 1],
strides=[1, 1, 1],
padding='same',
use_bias=False,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer,
bias_regularizer=self._bias_regularizer,
name='expand_conv')
self._norm3 = self._norm(
axis=self._bn_axis,
momentum=self._norm_momentum,
epsilon=self._norm_epsilon,
name='expand_conv/batch_norm/')
if self._se_ratio and self._se_ratio > 0 and self._se_ratio <= 1:
self._squeeze_excitation = nn_layers.SqueezeExcitation(
in_filters=self._filters * 4,
out_filters=self._filters * 4,
se_ratio=self._se_ratio,
use_3d_input=True,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer,
bias_regularizer=self._bias_regularizer,
name='se_layer')
else:
self._squeeze_excitation = None
if self._stochastic_depth_drop_rate:
self._stochastic_depth = nn_layers.StochasticDepth(
self._stochastic_depth_drop_rate)
else:
self._stochastic_depth = None
if self._use_self_gating:
self._self_gating = SelfGating(filters=4 * self._filters,
name='self_gating')
else:
self._self_gating = None
| 4,382 | 34.634146 | 80 | py |
models | models-master/official/projects/const_cl/modeling/backbones/resnet_3d_test.py | # Copyright 2023 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.
"""Tests for resnet."""
# Import libraries
from absl.testing import parameterized
import tensorflow as tf
from official.projects.const_cl.modeling.backbones import resnet_3d
class ResNet3DTest(parameterized.TestCase, tf.test.TestCase):
@parameterized.parameters(
(128, 50, 4, 'v0', False, 0.0),
(128, 50, 4, 'v0', False, 0.2),
(256, 50, 4, 'v0', True, 0.2),
)
def test_network_creation(self, input_size, model_id, endpoint_filter_scale,
stem_type, se_ratio, init_stochastic_depth_rate):
"""Test creation of ResNet3D family models."""
tf.keras.backend.set_image_data_format('channels_last')
temporal_strides = [1, 1, 1, 1]
temporal_kernel_sizes = [(3, 3, 3), (3, 1, 3, 1), (3, 1, 3, 1, 3, 1),
(1, 3, 1)]
use_self_gating = [True, False, True, False]
network = resnet_3d.ResNet3DY(
model_id=model_id,
temporal_strides=temporal_strides,
temporal_kernel_sizes=temporal_kernel_sizes,
use_self_gating=use_self_gating,
stem_type=stem_type,
se_ratio=se_ratio,
init_stochastic_depth_rate=init_stochastic_depth_rate)
inputs = tf.keras.Input(shape=(8, input_size, input_size, 3), batch_size=1)
endpoints = network(inputs)
self.assertAllEqual([
1, 2, input_size / 2**2, input_size / 2**2, 64 * endpoint_filter_scale
], endpoints['2'].shape.as_list())
self.assertAllEqual([
1, 2, input_size / 2**3, input_size / 2**3, 128 * endpoint_filter_scale
], endpoints['3'].shape.as_list())
self.assertAllEqual([
1, 2, input_size / 2**4, input_size / 2**4, 256 * endpoint_filter_scale
], endpoints['4'].shape.as_list())
self.assertAllEqual([
1, 2, input_size / 2**5, input_size / 2**5, 512 * endpoint_filter_scale
], endpoints['5'].shape.as_list())
self.assertAllEqual([
1, 2, input_size / 2**5, input_size / 2**5, 512 * endpoint_filter_scale
], endpoints['5_1'].shape.as_list())
def test_serialize_deserialize(self):
# Create a network object that sets all of its config options.
kwargs = dict(
model_id=50,
temporal_strides=[1, 1, 1, 1],
temporal_kernel_sizes=[(3, 3, 3), (3, 1, 3, 1), (3, 1, 3, 1, 3, 1),
(1, 3, 1)],
stem_type='v0',
stem_conv_temporal_kernel_size=5,
stem_conv_temporal_stride=2,
stem_pool_temporal_stride=2,
se_ratio=0.0,
use_self_gating=None,
init_stochastic_depth_rate=0.0,
use_sync_bn=False,
activation='relu',
norm_momentum=0.99,
norm_epsilon=0.001,
kernel_initializer='VarianceScaling',
kernel_regularizer=None,
bias_regularizer=None,
)
network = resnet_3d.ResNet3DY(**kwargs)
expected_config = dict(kwargs)
self.assertEqual(network.get_config(), expected_config)
# Create another network object from the first object's config.
new_network = resnet_3d.ResNet3DY.from_config(network.get_config())
# Validate that the config can be forced to JSON.
_ = new_network.to_json()
# If the serialization was successful, the new config should match the old.
self.assertAllEqual(network.get_config(), new_network.get_config())
if __name__ == '__main__':
tf.test.main()
| 3,950 | 36.273585 | 79 | py |
models | models-master/official/projects/const_cl/modeling/backbones/nn_blocks_3d_test.py | # Copyright 2023 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.
"""Tests for resnet."""
from absl.testing import parameterized
import tensorflow as tf
from official.projects.const_cl.modeling.backbones import nn_blocks_3d
class NNBlocksTest(parameterized.TestCase, tf.test.TestCase):
@parameterized.parameters(
(nn_blocks_3d.BottleneckBlock3D, 1, 1, 2, True, 0.2, 0.1),
(nn_blocks_3d.BottleneckBlock3D, 3, 2, 1, False, 0.0, 0.0),
)
def test_bottleneck_block_creation(self, block_fn, temporal_kernel_size,
temporal_strides, spatial_strides,
use_self_gating, se_ratio,
stochastic_depth):
temporal_size = 16
spatial_size = 128
filters = 256
inputs = tf.keras.Input(
shape=(temporal_size, spatial_size, spatial_size, filters * 4),
batch_size=1)
block = block_fn(
filters=filters,
temporal_kernel_size=temporal_kernel_size,
temporal_strides=temporal_strides,
spatial_strides=spatial_strides,
use_self_gating=use_self_gating,
se_ratio=se_ratio,
stochastic_depth_drop_rate=stochastic_depth)
features = block(inputs)
self.assertAllEqual([
1, temporal_size // temporal_strides, spatial_size // spatial_strides,
spatial_size // spatial_strides, filters * 4
], features.shape.as_list())
vnames = [v.name for v in block.trainable_variables]
expected_names = [
'bottleneck_block3d/temporal_conv/kernel:0',
'bottleneck_block3d/temporal_conv/batch_norm/gamma:0',
'bottleneck_block3d/temporal_conv/batch_norm/beta:0',
'bottleneck_block3d/spatial_conv/kernel:0',
'bottleneck_block3d/spatial_conv/batch_norm/gamma:0',
'bottleneck_block3d/spatial_conv/batch_norm/beta:0',
'bottleneck_block3d/expand_conv/kernel:0',
'bottleneck_block3d/expand_conv/batch_norm/gamma:0',
'bottleneck_block3d/expand_conv/batch_norm/beta:0'
]
self.assertContainsSubset(expected_names, vnames)
if __name__ == '__main__':
tf.test.main()
| 2,687 | 36.859155 | 78 | py |
models | models-master/official/projects/const_cl/modeling/backbones/resnet_3d.py | # Copyright 2023 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.
"""Contains definitions of 3D Residual Networks."""
from typing import Any, Callable, List, Optional, Tuple
import tensorflow as tf
from official.modeling import hyperparams
from official.modeling import tf_utils
from official.projects.const_cl.modeling.backbones import nn_blocks_3d
from official.vision.modeling.backbones import factory
from official.vision.modeling.backbones import resnet_3d
from official.vision.modeling.layers import nn_layers
layers = tf.keras.layers
RESNET_SPECS = resnet_3d.RESNET_SPECS
@tf.keras.utils.register_keras_serializable(package='Vision')
class ResNet3DY(tf.keras.Model):
"""Creates a 3D ResNet family model with branched res5 block."""
def __init__(
self,
model_id: int,
temporal_strides: List[int],
temporal_kernel_sizes: List[Tuple[int]],
use_self_gating: Optional[List[int]] = None,
input_specs: tf.keras.layers.InputSpec = layers.InputSpec(
shape=[None, None, None, None, 3]),
stem_type: str = 'v0',
stem_conv_temporal_kernel_size: int = 5,
stem_conv_temporal_stride: int = 2,
stem_pool_temporal_stride: int = 2,
init_stochastic_depth_rate: float = 0.0,
activation: str = 'relu',
se_ratio: Optional[float] = None,
use_sync_bn: bool = False,
norm_momentum: float = 0.99,
norm_epsilon: float = 0.001,
kernel_initializer: str = 'VarianceScaling',
kernel_regularizer: Optional[tf.keras.regularizers.Regularizer] = None,
bias_regularizer: Optional[tf.keras.regularizers.Regularizer] = None,
**kwargs):
"""Initializes a 3D ResNet model.
Args:
model_id: An `int` of depth of ResNet backbone model.
temporal_strides: A list of integers that specifies the temporal strides
for all 3d blocks.
temporal_kernel_sizes: A list of tuples that specifies the temporal kernel
sizes for all 3d blocks in different block groups.
use_self_gating: A list of booleans to specify applying self-gating module
or not in each block group. If None, self-gating is not applied.
input_specs: A `tf.keras.layers.InputSpec` of the input tensor.
stem_type: A `str` of stem type of ResNet. Default to `v0`. If set to
`v1`, use ResNet-D type stem (https://arxiv.org/abs/1812.01187).
stem_conv_temporal_kernel_size: An `int` of temporal kernel size for the
first conv layer.
stem_conv_temporal_stride: An `int` of temporal stride for the first conv
layer.
stem_pool_temporal_stride: An `int` of temporal stride for the first pool
layer.
init_stochastic_depth_rate: A `float` of initial stochastic depth rate.
activation: A `str` of name of the activation function.
se_ratio: A `float` or None. Ratio of the Squeeze-and-Excitation layer.
use_sync_bn: If True, use synchronized batch normalization.
norm_momentum: A `float` of normalization momentum for the moving average.
norm_epsilon: A `float` added to variance to avoid dividing by zero.
kernel_initializer: A str for kernel initializer of convolutional layers.
kernel_regularizer: A `tf.keras.regularizers.Regularizer` object for
Conv2D. Default to None.
bias_regularizer: A `tf.keras.regularizers.Regularizer` object for Conv2D.
Default to None.
**kwargs: Additional keyword arguments to be passed.
"""
super().__init__(**kwargs)
self._model_id = model_id
self._temporal_strides = temporal_strides
self._temporal_kernel_sizes = temporal_kernel_sizes
self._input_specs = input_specs
self._stem_type = stem_type
self._stem_conv_temporal_kernel_size = stem_conv_temporal_kernel_size
self._stem_conv_temporal_stride = stem_conv_temporal_stride
self._stem_pool_temporal_stride = stem_pool_temporal_stride
self._use_self_gating = use_self_gating
self._se_ratio = se_ratio
self._init_stochastic_depth_rate = init_stochastic_depth_rate
self._use_sync_bn = use_sync_bn
self._activation = activation
self._norm_momentum = norm_momentum
self._norm_epsilon = norm_epsilon
if use_sync_bn:
self._norm = layers.experimental.SyncBatchNormalization
else:
self._norm = layers.BatchNormalization
self._kernel_initializer = kernel_initializer
self._kernel_regularizer = kernel_regularizer
self._bias_regularizer = bias_regularizer
if tf.keras.backend.image_data_format() == 'channels_last':
self._bn_axis = -1
else:
self._bn_axis = 1
# Build ResNet3D backbone.
inputs = tf.keras.Input(shape=input_specs.shape[1:])
self._build_model(inputs)
def _build_model(self, inputs):
"""Builds model architecture.
Args:
inputs: the Keras input spec.
Returns:
endpoints: A dictionary of backbone endpoint features.
"""
# Build stem.
self._build_stem(inputs, stem_type=self._stem_type)
temporal_kernel_size = 1 if self._stem_pool_temporal_stride == 1 else 3
self._max_pool = layers.MaxPool3D(
pool_size=[temporal_kernel_size, 3, 3],
strides=[self._stem_pool_temporal_stride, 2, 2],
padding='same')
# Build intermediate blocks and endpoints.
resnet_specs = RESNET_SPECS[self._model_id]
if len(self._temporal_strides) != len(resnet_specs) or len(
self._temporal_kernel_sizes) != len(resnet_specs):
raise ValueError(
'Number of blocks in temporal specs should equal to resnet_specs.')
self._blocks = {}
for i, resnet_spec in enumerate(resnet_specs):
if resnet_spec[0] == 'bottleneck3d':
block_fn = nn_blocks_3d.BottleneckBlock3D
else:
raise ValueError('Block fn `{}` is not supported.'.format(
resnet_spec[0]))
use_self_gating = (
self._use_self_gating[i] if self._use_self_gating else False)
self._blocks[f'res_{i+2}'] = self._build_block_group(
inputs=inputs,
filters=resnet_spec[1],
temporal_kernel_sizes=self._temporal_kernel_sizes[i],
temporal_strides=self._temporal_strides[i],
spatial_strides=(1 if i == 0 else 2),
block_fn=block_fn,
block_repeats=resnet_spec[2],
stochastic_depth_drop_rate=nn_layers.get_stochastic_depth_rate(
self._init_stochastic_depth_rate, i + 2, 5),
use_self_gating=use_self_gating,
name='res_{}'.format(i + 2))
# Duplicate res5 block.
resnet_specs = RESNET_SPECS[self._model_id]
resnet_spec = resnet_specs[-1]
i = len(resnet_specs) - 1
if resnet_spec[0] == 'bottleneck3d':
block_fn = nn_blocks_3d.BottleneckBlock3D
else:
raise ValueError('Block fn `{}` is not supported.'.format(
resnet_spec[0]))
use_self_gating = (
self._use_self_gating[i] if self._use_self_gating else False)
block_layers = self._build_block_group(
inputs=inputs,
filters=resnet_spec[1],
temporal_kernel_sizes=self._temporal_kernel_sizes[i],
temporal_strides=self._temporal_strides[i],
spatial_strides=(1 if i == 0 else 2),
block_fn=block_fn,
block_repeats=resnet_spec[2],
stochastic_depth_drop_rate=nn_layers.get_stochastic_depth_rate(
self._init_stochastic_depth_rate, i + 2, 5),
use_self_gating=use_self_gating,
name='res_{}_1'.format(i + 2))
self._res_5_1_layers = block_layers
def _build_stem(self, inputs, stem_type):
"""Builds stem layer."""
del inputs
# Build stem.
if stem_type == 'v0':
self._stem_conv = layers.Conv3D(
filters=64,
kernel_size=[self._stem_conv_temporal_kernel_size, 7, 7],
strides=[self._stem_conv_temporal_stride, 2, 2],
use_bias=False,
padding='same',
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer,
bias_regularizer=self._bias_regularizer,
name='stem')
self._stem_bn = self._norm(
axis=self._bn_axis,
momentum=self._norm_momentum,
epsilon=self._norm_epsilon,
name='stem/batch_norm')
self._stem_activation = tf_utils.get_activation(self._activation)
else:
raise ValueError(f'Stem type {stem_type} not supported.')
def _build_block_group(
self,
inputs: tf.Tensor,
filters: int,
temporal_kernel_sizes: Tuple[int],
temporal_strides: int,
spatial_strides: int,
block_fn: Callable[
..., tf.keras.layers.Layer] = nn_blocks_3d.BottleneckBlock3D,
block_repeats: int = 1,
stochastic_depth_drop_rate: float = 0.0,
use_self_gating: bool = False,
name: str = 'block_group'):
"""Creates one group of blocks for the ResNet3D model.
Args:
inputs: A `tf.Tensor` of size `[batch, channels, height, width]`.
filters: An `int` of number of filters for the first convolution of the
layer.
temporal_kernel_sizes: A tuple that specifies the temporal kernel sizes
for each block in the current group.
temporal_strides: An `int` of temporal strides for the first convolution
in this group.
spatial_strides: An `int` stride to use for the first convolution of the
layer. If greater than 1, this layer will downsample the input.
block_fn: Either `nn_blocks.ResidualBlock` or `nn_blocks.BottleneckBlock`.
block_repeats: An `int` of number of blocks contained in the layer.
stochastic_depth_drop_rate: A `float` of drop rate of the current block
group.
use_self_gating: A `bool` that specifies whether to apply self-gating
module or not.
name: A `str` name for the block.
Returns:
The output `tf.Tensor` of the block layer.
"""
del inputs
if len(temporal_kernel_sizes) != block_repeats:
raise ValueError(
'Number of elements in temporal_kernel_sizes must equal to '
'block_repeats.')
# Only apply self-gating module in the last block.
use_self_gating_list = [False] * (block_repeats - 1) + [use_self_gating]
name = 'cell'
block_layers = {}
block_layers[f'{name}_0'] = block_fn(
filters=filters,
temporal_kernel_size=temporal_kernel_sizes[0],
temporal_strides=temporal_strides,
spatial_strides=spatial_strides,
stochastic_depth_drop_rate=stochastic_depth_drop_rate,
use_self_gating=use_self_gating_list[0],
se_ratio=self._se_ratio,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer,
bias_regularizer=self._bias_regularizer,
activation=self._activation,
use_sync_bn=self._use_sync_bn,
norm_momentum=self._norm_momentum,
norm_epsilon=self._norm_epsilon,
name=f'{name}_0')
for i in range(1, block_repeats):
block_layers[f'{name}_{i}'] = block_fn(
filters=filters,
temporal_kernel_size=temporal_kernel_sizes[i],
temporal_strides=1,
spatial_strides=1,
stochastic_depth_drop_rate=stochastic_depth_drop_rate,
use_self_gating=use_self_gating_list[i],
se_ratio=self._se_ratio,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer,
bias_regularizer=self._bias_regularizer,
activation=self._activation,
use_sync_bn=self._use_sync_bn,
norm_momentum=self._norm_momentum,
norm_epsilon=self._norm_epsilon,
name=f'{name}_{i}')
return block_layers
def call(self, inputs: tf.Tensor, training: bool = False, mask: Any = None):
"""Calls ResNet3DY model."""
del mask
x = self._stem_conv(inputs, training=training)
x = self._stem_bn(x, training=training)
x = self._stem_activation(x)
x = self._max_pool(x)
res4 = None
endpoints = {}
for i, block_layers in enumerate(self._blocks.values()):
for block_fn in block_layers.values():
x = block_fn(x, training=training)
endpoints[f'{i + 2}'] = x
if i + 2 == 4:
res4 = x
for block_fn in self._res_5_1_layers.values():
res4 = block_fn(res4, training=training)
endpoints['5_1'] = res4
return endpoints
def get_config(self):
config_dict = {
'model_id': self._model_id,
'temporal_strides': self._temporal_strides,
'temporal_kernel_sizes': self._temporal_kernel_sizes,
'stem_type': self._stem_type,
'stem_conv_temporal_kernel_size': self._stem_conv_temporal_kernel_size,
'stem_conv_temporal_stride': self._stem_conv_temporal_stride,
'stem_pool_temporal_stride': self._stem_pool_temporal_stride,
'use_self_gating': self._use_self_gating,
'se_ratio': self._se_ratio,
'init_stochastic_depth_rate': self._init_stochastic_depth_rate,
'activation': self._activation,
'use_sync_bn': self._use_sync_bn,
'norm_momentum': self._norm_momentum,
'norm_epsilon': self._norm_epsilon,
'kernel_initializer': self._kernel_initializer,
'kernel_regularizer': self._kernel_regularizer,
'bias_regularizer': self._bias_regularizer,
}
return config_dict
@classmethod
def from_config(cls, config, custom_objects=None):
return cls(**config)
@factory.register_backbone_builder('resnet_3dy')
def build_resnet3dy(
input_specs: tf.keras.layers.InputSpec,
backbone_config: hyperparams.Config,
norm_activation_config: hyperparams.Config,
l2_regularizer: Optional[tf.keras.regularizers.Regularizer] = None
) -> tf.keras.Model:
"""Builds ResNet 3d-Y backbone from a config."""
backbone_cfg = backbone_config.get()
# Flatten configs before passing to the backbone.
temporal_strides = []
temporal_kernel_sizes = []
use_self_gating = []
for block_spec in backbone_cfg.block_specs:
temporal_strides.append(block_spec.temporal_strides)
temporal_kernel_sizes.append(block_spec.temporal_kernel_sizes)
use_self_gating.append(block_spec.use_self_gating)
return ResNet3DY(
model_id=backbone_cfg.model_id,
temporal_strides=temporal_strides,
temporal_kernel_sizes=temporal_kernel_sizes,
use_self_gating=use_self_gating,
input_specs=input_specs,
stem_type=backbone_cfg.stem_type,
stem_conv_temporal_kernel_size=backbone_cfg
.stem_conv_temporal_kernel_size,
stem_conv_temporal_stride=backbone_cfg.stem_conv_temporal_stride,
stem_pool_temporal_stride=backbone_cfg.stem_pool_temporal_stride,
init_stochastic_depth_rate=backbone_cfg.stochastic_depth_drop_rate,
se_ratio=backbone_cfg.se_ratio,
activation=norm_activation_config.activation,
use_sync_bn=norm_activation_config.use_sync_bn,
norm_momentum=norm_activation_config.norm_momentum,
norm_epsilon=norm_activation_config.norm_epsilon,
kernel_regularizer=l2_regularizer)
| 15,599 | 38.795918 | 80 | py |
models | models-master/official/projects/const_cl/modeling/heads/instance_reconstructor_test.py | # Copyright 2023 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.
"""Tests for instance_reconstructor."""
import tensorflow as tf
from official.projects.const_cl.modeling.heads import instance_reconstructor
class InstanceReconstructorTest(tf.test.TestCase):
def test_instance_reconstructor_return_shapes(self):
decoder = instance_reconstructor.InstanceReconstructor()
inputs = {
'features': tf.ones([12, 5, 7, 7, 128]),
'instances_position': tf.random.uniform([12, 5, 16, 4]),
'instances_mask': tf.ones([12, 5, 16], tf.bool)
}
outputs = decoder(inputs, training=True)
self.assertContainsSubset(
list(outputs.keys()),
['inst_a2b', 'inst_b2a', 'inst_a', 'inst_b', 'masks_a', 'masks_b'])
self.assertAllEqual(outputs['inst_a2b'].shape, [6, 16, 1024])
self.assertAllEqual(outputs['inst_a'].shape, [6, 16, 128])
self.assertAllEqual(outputs['inst_b2a'].shape, [6, 16, 1024])
self.assertAllEqual(outputs['inst_b'].shape, [6, 16, 128])
self.assertAllEqual(outputs['masks_b'].shape, [6, 16])
self.assertAllEqual(outputs['masks_a'].shape, [6, 16])
if __name__ == '__main__':
tf.test.main()
| 1,719 | 35.595745 | 76 | py |
models | models-master/official/projects/const_cl/modeling/heads/instance_reconstructor.py | # Copyright 2023 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.
"""The instance feature reconstructor head."""
from typing import Mapping
import tensorflow as tf
from official.projects.const_cl.modeling.heads import transformer_decoder
from official.vision.modeling.layers import roi_aligner
def _get_shape(x):
"""Helper function to return shape of a given tensor."""
static = x.shape.as_list()
dynamic = tf.shape(x)
return [dynamic[i] if s is None else s for i, s in enumerate(static)]
class InstanceReconstructor(tf.keras.layers.Layer):
"""The SSL head for reconstructing contextualized instance representations."""
def __init__(self,
context_level: int = 1,
# parameters for projector
num_output_channels: int = 1024,
# parameters for RoiAligner
crop_size: int = 4,
sample_offset: float = 0.5,
# parameters for TxDecoder
num_tx_channels: int = 128,
num_tx_layers: int = 3,
num_tx_heads: int = 3,
use_bias: bool = True,
activation: str = 'gelu',
dropout_rate: float = 0.0,
layer_norm_epsilon: float = 1e-6,
use_positional_embedding: bool = True,
normalize_inputs: bool = True,
**kwargs):
"""InstanceReconstructor SSL head initializer.
Args:
context_level: the number of context frame to use.
num_output_channels: the number of final output channels.
crop_size: the ROI aligner crop size.
sample_offset: the ROI aligner sample offset.
num_tx_channels: the Transformer decoder head channels.
num_tx_layers: the number of Transformer decoder layers.
num_tx_heads: the number of Transformer decoder heads per layer.
use_bias: whether to use bias.
activation: the activation function to use.
dropout_rate: the dropout rate.
layer_norm_epsilon: the layer norm epsilon.
use_positional_embedding: whether to use positional embedding.
normalize_inputs: whether to normalize input embeddings.
**kwargs: the kwargs.
"""
super().__init__(**kwargs)
self._normalize_inputs = normalize_inputs
self._context_level = context_level
self._num_output_channels = num_output_channels
self._crop_size = crop_size
self._sample_offset = sample_offset
self._num_tx_channels = num_tx_channels
self._num_tx_layers = num_tx_layers
self._num_tx_heads = num_tx_heads
self._use_bias = use_bias
self._activation = activation
self._dropout_rate = dropout_rate
self._layer_norm_epsilon = layer_norm_epsilon
self._use_positional_embedding = use_positional_embedding
self._roi_aligner = roi_aligner.MultilevelROIAligner(
crop_size=crop_size,
sample_offset=sample_offset)
if self._use_positional_embedding:
self._spatial_mlp = [
tf.keras.layers.Dense(
4, use_bias=True, activation='relu', name='spatial_mlp_l1'),
tf.keras.layers.Dense(
8, use_bias=True, name='spatial_mlp_l2')]
self._temporal_mlp = [
tf.keras.layers.Dense(
4, use_bias=True, activation='relu', name='temporal_mlp_l1'),
tf.keras.layers.Dense(
8, use_bias=True, name='temporal_mlp_l2')]
self._attention_decoder = transformer_decoder.TransformerDecoder(
num_channels=num_tx_channels,
num_layers=num_tx_layers,
num_heads=num_tx_heads,
use_bias=use_bias,
activation=activation,
dropout_rate=dropout_rate,
layer_norm_epsilon=layer_norm_epsilon)
self._projection_layer = tf.keras.layers.Dense(num_output_channels)
def _get_memory_embeddings(self, inputs: tf.Tensor) -> tf.Tensor:
"""Uniformly samples frames to construct memory embeddings."""
if self._context_level % 2 == 0:
raise ValueError('context_level should be specified as odd number.')
num_frames = tf.shape(inputs)[1]
keyframe_index = num_frames // 2
stride = num_frames // self._context_level
start = self._context_level // 2 * -1
stop = self._context_level // 2 + 1 # exclusive
memories = []
for idx in range(start, stop):
idx = idx * stride + keyframe_index
memories.append(inputs[:, idx, ...])
memories = tf.stack(memories, axis=1)
return memories
def _add_positional_embedding(self, inputs: tf.Tensor) -> tf.Tensor:
"""Adds positional embeddings to the inputs tensor."""
# Compute the locations using meshgrid.
b, t, h, w = _get_shape(inputs)[:4]
mesh = tf.meshgrid(tf.range(t), tf.range(h), tf.range(w), indexing='ij')
position = tf.cast(
tf.tile(
tf.expand_dims(tf.stack(mesh, axis=-1), axis=0), [b, 1, 1, 1, 1]),
tf.float32)
# Make the positions relative to center point.
# The mean of all position coordinates would be the center point anyway
center_position = tf.reduce_mean(position, axis=[1, 2, 3], keepdims=True)
position -= center_position
# Apply learneable layers.
temporal_position = position[..., :1]
for mlp in self._temporal_mlp:
temporal_position = mlp(temporal_position)
spatial_position = position[..., 1:]
for mlp in self._spatial_mlp:
spatial_position = mlp(spatial_position)
return tf.concat([inputs, temporal_position, spatial_position], axis=-1)
def _keyframe_roi_pooling(self,
features: tf.Tensor,
boxes: tf.Tensor,
training: bool = True) -> tf.Tensor:
"""Pools ROI features on the keyframe.
Args:
features: a 5D tensor in shape [B, T, H, W, C].
boxes: normalized box coordinates, a 4D tensor in shape [B, T', N, 4].
training: whether in training mode.
Returns:
roi_feature: pooled ROI-features in shape [B, N, C].
"""
if features.shape.ndims != 5:
raise ValueError('Expected features is a rank-5 tensor. Got shape %s' %
features.shape)
keyframe_index = tf.shape(boxes)[1] // 2
t, h, w = _get_shape(features)[1:4]
roi_features = {'0': features[:, t // 2, ...]}
keyframe_boxes = boxes[:, keyframe_index, ...]
unnormalized_boxes = keyframe_boxes * tf.convert_to_tensor(
[h, w, h, w], keyframe_boxes.dtype)
# roi_features in shape [B, N, h, w, C]
roi_features = self._roi_aligner(
roi_features, unnormalized_boxes, training=training)
roi_shape = _get_shape(roi_features)
# Perform average_pooling on ROI-pooled features.
roi_features = tf.reshape(roi_features, [-1] + roi_shape[2:])
roi_features = tf.reduce_mean(roi_features, axis=[1, 2])
roi_features = tf.reshape(roi_features, roi_shape[:2] + roi_shape[-1:])
return roi_features
def call(self,
inputs: Mapping[str, tf.Tensor],
training: bool = False) -> Mapping[str, tf.Tensor]:
"""Forward calls.
Args:
inputs: the inputs dictionary contains
'features': the instance embeddings in shape [2*B, T', H, W, C].
'instances_positions': the instance boxes in shape [2*B, T, N, 4].
'instances_mask': the validity mask for each instance position, in
[2*B, T, N].
training: whether in training mode.
Returns:
the context-guided reconstructed instance representations.
"""
dense_embeddings_raw = inputs['features']
instances_position = inputs['instances_position']
instances_mask = inputs['instances_mask']
if self._normalize_inputs:
dense_embeddings_raw = tf.math.l2_normalize(dense_embeddings_raw, axis=-1)
def _keyframe_temporal_pooling(inputs):
t = tf.shape(inputs)[1] // 2
return inputs[:, t:t+1, ...]
dense_embeddings = _keyframe_temporal_pooling(dense_embeddings_raw)
instances_position = _keyframe_temporal_pooling(instances_position)
instances_mask = _keyframe_temporal_pooling(instances_mask)
instances_mask_a, instances_mask_b = tf.split(
tf.squeeze(instances_mask, axis=1), num_or_size_splits=2, axis=0)
inst_embeddings = self._keyframe_roi_pooling(
features=dense_embeddings,
boxes=instances_position,
training=training)
inst_embeddings_a, inst_embeddings_b = tf.split(inst_embeddings, 2, axis=0)
memory = self._get_memory_embeddings(dense_embeddings_raw)
# Add the positional embeddings before roi_pooling and tx_decoder.
if self._use_positional_embedding:
memory = self._add_positional_embedding(memory)
memory_a, memory_b = tf.split(memory, 2, axis=0)
# Reconstruct inst_a2b by querying in memory_b.
inst_embeddings_a2b = self._attention_decoder(
inputs=inst_embeddings_a, memory=memory_b, training=training)
inst_embeddings_a2b = inst_embeddings_a2b['hidden_states'][-1]
inst_embeddings_a2b = self._projection_layer(
inst_embeddings_a2b, training=training)
# Reconstruct inst_b2a by querying in memory_a.
inst_embeddings_b2a = self._attention_decoder(
inputs=inst_embeddings_b, memory=memory_a, training=training)
inst_embeddings_b2a = inst_embeddings_b2a['hidden_states'][-1]
inst_embeddings_b2a = self._projection_layer(
inst_embeddings_b2a, training=training)
outputs = {
'inst_a2b': inst_embeddings_a2b,
'inst_b2a': inst_embeddings_b2a,
'inst_a': inst_embeddings_a,
'inst_b': inst_embeddings_b,
'masks_a': instances_mask_a,
'masks_b': instances_mask_b,
}
return outputs
| 10,168 | 37.812977 | 80 | py |
models | models-master/official/projects/const_cl/modeling/heads/transformer_decoder.py | # Copyright 2023 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.
"""Definition for Transformer heads."""
from typing import Any, Mapping, Optional, Union, List, Sequence
from absl import logging
import tensorflow as tf
def _get_shape(x: tf.Tensor):
"""Helper function to return shape of a given tensor."""
static = x.shape.as_list()
dynamic = tf.shape(x)
return [dynamic[i] if s is None else s for i, s in enumerate(static)]
class DecoderUnit(tf.keras.layers.Layer):
"""Constructs the decoder MHA module used in Transformer layers."""
def __init__(self,
num_channels: int,
use_bias: bool,
dropout_rate: float,
activation: str,
layer_norm_epsilon: float,
**kwargs):
super().__init__(**kwargs)
self._num_channels = num_channels
self._use_bias = use_bias
self._dropout_rate = dropout_rate
self._activation = activation
self._layer_norm_epsilon = layer_norm_epsilon
def build(self, input_shape: Union[tf.TensorShape, List[tf.TensorShape]]):
"""Builds the layer.
Args:
input_shape: the input shape for the keras tensor.
"""
# Query, key, and value mapping.
self.layer_q = tf.keras.layers.Dense(
self._num_channels,
use_bias=self._use_bias,
activation=None,
name='query')
self.layer_k = tf.keras.layers.Dense(
self._num_channels,
use_bias=self._use_bias,
activation=None,
name='key')
self.layer_v = tf.keras.layers.Dense(
self._num_channels,
use_bias=self._use_bias,
activation=None,
name='value')
self.dropout = tf.keras.layers.Dropout(self._dropout_rate)
# Note here is a different behavior for contrib_layers.layer_norm and
# tf.keras.layers.LayerNormalization, where by default, the former
# calculates mean/variance across all axes except the first one
# (batch axis), while the latter one computes statistics only on the last
# axis.
self.layer_norm = tf.keras.layers.LayerNormalization(
epsilon=self._layer_norm_epsilon,
name='layer_norm')
self.ffn1 = tf.keras.layers.Dense(
self._num_channels,
use_bias=self._use_bias,
activation=self._activation,
name='ffn1')
self.ffn2 = tf.keras.layers.Dense(
self._num_channels,
use_bias=self._use_bias,
activation=None,
name='ffn2')
super().build(input_shape)
def call(self,
query: tf.Tensor,
memory: Optional[tf.Tensor],
training: bool = False) -> Mapping[str, tf.Tensor]:
"""Forward pass of the Transformer decoder unit.
Args:
query: the input query tensor.
memory: the input memory tensor for key/value pairs. If None,
self-attention will be performed.
training: whether in training mode.
Returns:
outputs: the output dictionary contains 'hidden_states' and
'attention weights' matrix.
"""
if memory is None:
memory = query
tensor_q = self.layer_q(query) # (bs, qlen, inner_dim)
tensor_k = self.layer_k(memory) # (bs, klen, inner_dim)
tensor_v = self.layer_v(memory) # (bs, klen, inner_dim)
scores = tf.matmul(tensor_q, tensor_k, transpose_b=True)
# Scales attention_scores.
dk = tf.cast(_get_shape(tensor_k)[-1], dtype=scores.dtype)
scores = scores / tf.math.sqrt(dk)
# Shape: (bs, seq_len, seq_len)
attention_weights = tf.nn.softmax(scores, axis=-1)
# Shape: (bs, seq_len, dim_per_head)
attention_features = tf.matmul(attention_weights, tensor_v)
# Shape: (bs, seq_len, seq_len)
attention_features = self.dropout(attention_features, training=training)
hidden_states = attention_features + tensor_q
hidden_states = self.layer_norm(hidden_states)
# Shape: (bs, seq_len, out_dim)
hidden_states = self.ffn1(hidden_states)
hidden_states = self.ffn2(hidden_states)
outputs = {
'hidden_states': hidden_states,
'attention_weights': attention_weights,
}
return outputs
def get_config(self) -> Mapping[str, Any]:
"""Gets class config parameters."""
config_dict = {
'num_channels': self._num_channels,
'use_bias': self._use_bias,
'dropout_rate': self._dropout_rate,
'activation': self._activation,
'layer_norm_epsilon': self._layer_norm_epsilon,
}
return config_dict
@classmethod
def from_config(cls, config: Mapping[str, Any]):
"""Factory constructor from config."""
return cls(**config)
class TransformerDecoderLayer(tf.keras.layers.Layer):
"""Constructs the main Transformer decoder module which includes MHA + FFN."""
def __init__(self,
num_channels: int,
num_heads: int,
use_bias: bool,
activation: str,
dropout_rate: float,
layer_norm_epsilon: float,
name: str = 'decoder_layer',
**kwargs):
super().__init__(name=name)
self._num_channels = num_channels
self._num_heads = num_heads
self._use_bias = use_bias
self._activation = activation
self._dropout_rate = dropout_rate
self._layer_norm_epsilon = layer_norm_epsilon
self._name = name
self._mha_units = []
for i in range(num_heads):
self._mha_units.append(
DecoderUnit(
num_channels=num_channels,
use_bias=use_bias,
dropout_rate=dropout_rate,
activation=activation,
layer_norm_epsilon=layer_norm_epsilon,
name='mha_{}'.format(i)))
def call(
self,
inputs: tf.Tensor,
memory: Optional[tf.Tensor] = None,
training: bool = False
) -> Mapping[str, Union[tf.Tensor, Sequence[tf.Tensor]]]:
"""Forward pass of the Transformer decoder layer.
Args:
inputs: the input query tensor.
memory: the input memory tensor for key/value pairs. If None,
self-attention will be performed.
training: whether in training mode.
Returns:
outputs: the output dictionary contains 'hidden_states' and
'attention weights' matrix.
"""
if memory is None:
logging.info('No memory tokens are provided. Performing self-attention '
'on input tokens in TransfomerDecoder.')
all_head_feats = []
all_head_attentions = []
for i in range(self._num_heads):
outputs = self._mha_units[i](
query=inputs, memory=memory, training=training)
all_head_feats.append(outputs['hidden_states'])
all_head_attentions.append(outputs['attention_weights'])
outputs = {
'hidden_states': tf.concat(all_head_feats, axis=-1),
'attention_weights': all_head_attentions,
}
return outputs
def get_config(self) -> Mapping[str, Any]:
"""Gets class config parameters."""
config_dict = {
'num_channels': self._num_channels,
'num_heads': self._num_heads,
'use_bias': self._use_bias,
'activation': self._activation,
'dropout_rate': self._dropout_rate,
'layer_norm_epsilon': self._layer_norm_epsilon,
'name': self._name,
}
return config_dict
@classmethod
def from_config(cls, config: Mapping[str, Any]):
"""Factory constructor from config."""
return cls(**config)
class TransformerDecoder(tf.keras.layers.Layer):
"""Constructs the final Transformer decoder stack."""
def __init__(self,
num_channels: int,
num_layers: int,
num_heads: int,
use_bias: bool,
activation: str,
dropout_rate: float,
layer_norm_epsilon: float,
name: str = 'transformer_decoder',
**kwargs):
super().__init__(name=name)
self._num_channels = num_channels
self._num_layers = num_layers
self._num_heads = num_heads
self._use_bias = use_bias
self._activation = activation
self._dropout_rate = dropout_rate
self._layer_norm_epsilon = layer_norm_epsilon
self._layers = []
for n in range(self._num_layers):
self._layers.append(
TransformerDecoderLayer(
num_channels=num_channels,
num_heads=num_heads,
use_bias=use_bias,
activation=activation,
dropout_rate=dropout_rate,
layer_norm_epsilon=layer_norm_epsilon,
name='layer_{}'.format(n)))
def call(self,
inputs: tf.Tensor,
memory: Optional[tf.Tensor] = None,
training: bool = False) -> Mapping[str, Sequence[tf.Tensor]]:
"""Forward pass of the Transformer decoder.
Args:
inputs: the input query tensor.
memory: the input memory tensor for key/value pairs. If None,
self-attention will be performed.
training: whether in training mode.
Returns:
outputs: the output dictionary contains 'hidden_states' and
'attention weights' matrix.
"""
all_hidden_states = ()
all_attentions = ()
memory_shape = _get_shape(memory)
memory = tf.reshape(memory, [memory_shape[0], -1, memory_shape[-1]])
hidden_states = inputs
for layer in self._layers:
layer_outputs = layer(inputs=hidden_states,
memory=memory,
training=training)
# layer_outputs is a dictionary with the following keys:
# hidden_states, self_attention_weights
hidden_states = layer_outputs['hidden_states']
all_attentions += (layer_outputs['attention_weights'],)
# Add last layer
all_hidden_states += (hidden_states,)
outputs = {
'hidden_states': all_hidden_states,
'attention_weights': all_attentions,
}
return outputs
def get_config(self) -> Mapping[str, Any]:
"""Gets class config parameters."""
config_dict = {
'num_channels': self._num_channels,
'num_layers': self._num_layers,
'num_heads': self._num_heads,
'use_bias': self._use_bias,
'activation': self._activation,
'dropout_rate': self._dropout_rate,
'layer_norm_epsilon': self._layer_norm_epsilon,
}
return config_dict
@classmethod
def from_config(cls, config: Mapping[str, Any]):
"""Factory constructor from config."""
return cls(**config)
| 10,974 | 30.90407 | 80 | py |
models | models-master/official/projects/const_cl/modeling/heads/simple.py | # Copyright 2023 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.
"""Constructs simple heads."""
from typing import Any, Mapping, Optional
import tensorflow as tf
from official.modeling import tf_utils
class MLP(tf.keras.layers.Layer):
"""Constructs the Multi-Layer Perceptron head."""
def __init__(self,
num_hidden_layers: int,
num_hidden_channels: int,
num_output_channels: int,
use_sync_bn: bool,
norm_momentum: float = 0.99,
norm_epsilon: float = 1e-5,
activation: Optional[str] = None,
normalize_inputs: bool = False,
**kwargs):
"""Multi-Layer Perceptron initialization.
Args:
num_hidden_layers: the number of hidden layers in the MLP.
num_hidden_channels: the number of hidden nodes.
num_output_channels: the number of final output nodes.
use_sync_bn: whether to use sync batch norm.
norm_momentum: the batch norm momentum.
norm_epsilon: the batch norm epsilon.
activation: the activation function.
normalize_inputs: whether to normalize inputs.
**kwargs: keyword arguments to be passed.
"""
super().__init__(**kwargs)
self._num_hidden_layers = num_hidden_layers
self._num_hidden_channels = num_hidden_channels
self._num_output_channels = num_output_channels
self._use_sync_bn = use_sync_bn
self._norm_momentum = norm_momentum
self._norm_epsilon = norm_epsilon
self._activation = activation
self._normalize_inputs = normalize_inputs
self._layers = []
# MLP hidden layers
for _ in range(num_hidden_layers):
self._layers.append(
tf.keras.layers.Dense(num_hidden_channels, use_bias=False))
if use_sync_bn:
self._layers.append(
tf.keras.layers.experimental.SyncBatchNormalization(
momentum=norm_momentum,
epsilon=norm_epsilon))
else:
self._layers.append(
tf.keras.layers.BatchNormalization(
momentum=norm_momentum,
epsilon=norm_epsilon))
if activation is not None:
self._layers.append(tf_utils.get_activation(activation))
# Projection head
self._layers.append(tf.keras.layers.Dense(num_output_channels))
def call(self, inputs: tf.Tensor, training: bool) -> tf.Tensor:
"""Forward calls with N-D inputs tensor."""
if self._normalize_inputs:
inputs = tf.nn.l2_normalize(inputs, axis=-1)
for layer in self._layers:
if isinstance(layer, tf.keras.layers.Layer):
inputs = layer(inputs, training=training)
else: # activation
inputs = layer(inputs)
return inputs
def get_config(self) -> Mapping[str, Any]:
"""Gets class config parameters."""
config_dict = {
'num_hidden_layer': self._num_hidden_layer,
'num_hidden_channels': self._num_hidden_channels,
'num_output_channels': self._num_output_channels,
'use_sync_bn': self._use_sync_bn,
'norm_momentum': self._norm_momentum,
'norm_epsilon': self._norm_epsilon,
'activation': self._activation,
'normalize_inputs': self._normalize_inputs}
return config_dict
@classmethod
def from_config(cls, config: Mapping[str, Any]):
"""Factory constructor from config."""
return cls(**config)
| 3,926 | 34.7 | 74 | py |
models | models-master/official/projects/const_cl/modeling/heads/transformer_decoder_test.py | # Copyright 2023 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.
"""Tests for TransformerDecoder."""
import tensorflow as tf
from official.projects.const_cl.modeling.heads import transformer_decoder
class TransformerTest(tf.test.TestCase):
def test_decoder_unit_return_shape(self):
decoder_unit = transformer_decoder.DecoderUnit(
num_channels=128,
use_bias=True,
dropout_rate=0.5,
activation='relu',
layer_norm_epsilon=1e-7)
batch_size = 16
num_inputs = 128
num_channels = 256
input_tensor = tf.zeros([batch_size, num_inputs, num_channels])
memory_tensor = tf.ones([batch_size, num_inputs * 4, num_channels])
outputs = decoder_unit(input_tensor, memory_tensor, training=False)
self.assertAllEqual(outputs['hidden_states'].shape,
[batch_size, num_inputs, num_inputs])
self.assertAllEqual(outputs['attention_weights'].shape,
[batch_size, num_inputs, 4 * num_inputs])
def test_decoder_unit_serialize_deserialize(self):
decoder_unit = transformer_decoder.DecoderUnit(
num_channels=128,
use_bias=True,
dropout_rate=0.5,
activation='relu',
layer_norm_epsilon=1e-7)
config = decoder_unit.get_config()
new_decoder_unit = (
transformer_decoder.DecoderUnit.from_config(config))
self.assertAllEqual(
decoder_unit.get_config(), new_decoder_unit.get_config())
def test_decoder_layer_return_shape(self):
decoder_layer = transformer_decoder.TransformerDecoderLayer(
num_channels=128,
num_heads=3,
use_bias=True,
dropout_rate=0.5,
activation='relu',
layer_norm_epsilon=1e-7)
batch_size = 16
num_inputs = 128
num_channels = 256
input_tensor = tf.zeros([batch_size, num_inputs, num_channels])
memory_tensor = tf.ones([batch_size, num_inputs * 4, num_channels])
outputs = decoder_layer(input_tensor, memory_tensor, training=False)
self.assertAllEqual(outputs['hidden_states'].shape,
[batch_size, num_inputs, num_inputs * 3])
self.assertAllEqual(outputs['attention_weights'][-1].shape,
[batch_size, num_inputs, 4 * num_inputs])
def test_decoder_layer_serialize_deserialize(self):
decoder_layer = transformer_decoder.TransformerDecoderLayer(
num_channels=128,
num_heads=3,
use_bias=True,
dropout_rate=0.5,
activation='relu',
layer_norm_epsilon=1e-7)
config = decoder_layer.get_config()
new_decoder_layer = (
transformer_decoder.TransformerDecoderLayer.from_config(config))
self.assertAllEqual(
decoder_layer.get_config(), new_decoder_layer.get_config())
def test_decoder_return_shape(self):
decoder = transformer_decoder.TransformerDecoder(
num_channels=128,
num_layers=5,
num_heads=3,
use_bias=True,
dropout_rate=0.5,
activation='relu',
layer_norm_epsilon=1e-7)
batch_size = 16
num_inputs = 128
num_channels = 256
input_tensor = tf.zeros([batch_size, num_inputs, num_channels])
memory_tensor = tf.ones([batch_size, num_inputs * 4, num_channels])
outputs = decoder(input_tensor, memory_tensor, training=False)
self.assertLen(outputs['attention_weights'], 5)
self.assertAllEqual(outputs['hidden_states'][-1].shape,
[batch_size, num_inputs, num_inputs * 3])
self.assertAllEqual(outputs['attention_weights'][-1][-1].shape,
[batch_size, num_inputs, 4 * num_inputs])
def test_decoder_serialize_deserialize(self):
decoder = transformer_decoder.TransformerDecoder(
num_channels=128,
num_layers=5,
num_heads=3,
use_bias=True,
dropout_rate=0.5,
activation='relu',
layer_norm_epsilon=1e-7)
config = decoder.get_config()
new_decoder = transformer_decoder.TransformerDecoder.from_config(config)
self.assertAllEqual(
decoder.get_config(), new_decoder.get_config())
if __name__ == '__main__':
tf.test.main()
| 4,676 | 35.826772 | 76 | py |
models | models-master/official/projects/const_cl/modeling/heads/simple_test.py | # Copyright 2023 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.
"""Tests for simple."""
import numpy as np
import tensorflow as tf
from official.projects.const_cl.modeling.heads import simple
class SimpleTest(tf.test.TestCase):
def test_mlp_construction(self):
mlp_head = simple.MLP(
num_hidden_layers=3,
num_hidden_channels=128,
num_output_channels=56,
use_sync_bn=False,
activation='relu')
inputs = tf.zeros([2, 512])
outputs = mlp_head(inputs, training=False)
num_params = np.sum(
[np.prod(v.get_shape()) for v in mlp_head.trainable_weights])
self.assertEqual(num_params, 106296)
self.assertAllEqual(outputs.shape, [2, 56])
if __name__ == '__main__':
tf.test.main()
| 1,297 | 29.904762 | 74 | py |
models | models-master/official/projects/const_cl/tasks/const_cl_test.py | # Copyright 2023 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.
"""Tests for ConST-CL pretrain task definition."""
import functools
import os
import random
import orbit
import tensorflow as tf
# pylint: disable=unused-import
from official.core import exp_factory
from official.core import task_factory
from official.modeling import optimization
from official.projects.const_cl.modeling import const_cl_model
from official.projects.const_cl.modeling.backbones import resnet_3d
from official.projects.const_cl.tasks import const_cl
from official.vision.dataloaders import tfexample_utils
# pylint: enable=unused-import
class ConstCLPretrainTaskTest(tf.test.TestCase):
def setUp(self):
super(ConstCLPretrainTaskTest, self).setUp()
data_dir = os.path.join(self.get_temp_dir(), 'data')
tf.io.gfile.makedirs(data_dir)
self._data_path = os.path.join(data_dir, 'data.tfrecord')
# pylint: disable=g-complex-comprehension
examples = [
tfexample_utils.make_video_test_example(
image_shape=(36, 36, 3),
audio_shape=(20, 128),
label=random.randint(0, 100)) for _ in range(2)
]
# pylint: enable=g-complex-comprehension
tfexample_utils.dump_to_tfrecord(self._data_path, tf_examples=examples)
def test_task(self):
config = exp_factory.get_exp_config('const_cl_pretrain_kinetics400')
config.task.train_data.global_batch_size = 2
config.task.train_data.input_path = self._data_path
task = const_cl.ConstCLPretrainTask(
config.task)
model = task.build_model()
metrics = task.build_metrics()
strategy = tf.distribute.get_strategy()
dataset = orbit.utils.make_distributed_dataset(
strategy,
functools.partial(task.build_inputs),
config.task.train_data)
iterator = iter(dataset)
opt_factory = optimization.OptimizerFactory(config.trainer.optimizer_config)
optimizer = opt_factory.build_optimizer(opt_factory.build_learning_rate())
logs = task.train_step(next(iterator), model, optimizer, metrics=metrics)
self.assertIn('total_loss', logs)
self.assertIn('regularization_loss', logs)
self.assertIn('global_loss/loss', logs)
self.assertIn('global_loss/contrastive_accuracy', logs)
self.assertIn('global_loss/contrastive_entropy', logs)
self.assertIn('local_loss/loss', logs)
def test_task_factory(self):
config = exp_factory.get_exp_config('const_cl_pretrain_kinetics400')
task = task_factory.get_task(config.task)
self.assertIs(type(task), const_cl.ConstCLPretrainTask)
if __name__ == '__main__':
tf.test.main()
| 3,149 | 35.627907 | 80 | py |
models | models-master/official/projects/const_cl/tasks/const_cl.py | # Copyright 2023 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.
"""Video ssl pretrain task definition."""
from typing import Any, Optional
from absl import logging
import tensorflow as tf
from official.core import input_reader
from official.core import task_factory
from official.projects.const_cl.configs import const_cl as exp_cfg
from official.projects.const_cl.datasets import video_ssl_inputs
from official.projects.const_cl.losses import losses
from official.projects.video_ssl.tasks import pretrain as video_ssl_pretrain
from official.vision.modeling import factory_3d
@task_factory.register_task_cls(exp_cfg.ConstCLPretrainTask)
class ConstCLPretrainTask(video_ssl_pretrain.VideoSSLPretrainTask):
"""A task for video contextualized ssl pretraining."""
def build_model(self):
"""Builds video ssl pretraining model."""
common_input_shape = [
d1 if d1 == d2 else None
for d1, d2 in zip(self.task_config.train_data.feature_shape,
self.task_config.validation_data.feature_shape)
]
num_frames = common_input_shape[0]
num_instances = self.task_config.train_data.num_instances
input_specs_dict = {
'image':
tf.keras.layers.InputSpec(shape=[None] + common_input_shape),
'instances_position':
tf.keras.layers.InputSpec(
shape=[None, num_frames, num_instances, 4]),
'instances_mask':
tf.keras.layers.InputSpec(shape=[None, num_frames, num_instances]),
}
logging.info('Build model input %r', common_input_shape)
model = factory_3d.build_model(
self.task_config.model.model_type,
input_specs=input_specs_dict,
model_config=self.task_config.model,
num_classes=self.task_config.train_data.num_classes)
return model
def build_inputs(self,
params: exp_cfg.DataConfig,
input_context: Optional[Any] = None) -> tf.data.Dataset:
"""Builds ConST-CL SSL input."""
parser = video_ssl_inputs.Parser(input_params=params)
postprocess_fn = video_ssl_inputs.PostBatchProcessor(params)
reader = input_reader.InputReader(
params,
dataset_fn=self._get_dataset_fn(params),
decoder_fn=self._get_decoder_fn(params),
parser_fn=parser.parse_fn(params.is_training),
postprocess_fn=postprocess_fn)
dataset = reader.read(input_context=input_context)
return dataset
def build_losses(self, model_outputs, num_replicas, model):
"""Sparse categorical cross entropy loss.
Args:
model_outputs: Output logits of the model.
num_replicas: distributed replica number.
model: keras model for calculating weight decay.
Returns:
The total loss tensor.
"""
all_losses = {}
logging_metrics = {}
losses_config = self.task_config.losses
total_loss = None
global_loss = losses.ContrastiveLoss(
normalize_inputs=losses_config.normalize_inputs,
temperature=losses_config.global_temperature)
local_loss = losses.InstanceContrastiveLoss(
normalize_inputs=losses_config.normalize_inputs,
temperature=losses_config.local_temperature)
# Compute global loss.
global_inputs = model_outputs['global_embeddings']
global_loss_dict = global_loss(inputs=global_inputs,
num_replicas=num_replicas)
# Compute local loss.
local_inputs = {
'instances_a2b': model_outputs['inst_a2b'],
'instances_b2a': model_outputs['inst_b2a'],
'instances_a': model_outputs['inst_a'],
'instances_b': model_outputs['inst_b'],
'masks_a': model_outputs['masks_a'],
'masks_b': model_outputs['masks_b'],
}
local_loss_dict = local_loss(predictions=local_inputs,
num_replicas=num_replicas)
# Compute regularization loss.
reg_loss = losses_config.l2_weight_decay * tf.add_n([
tf.nn.l2_loss(v) for v in model.trainable_variables
if 'kernel' in v.name])
total_loss = (global_loss_dict['loss'] * losses_config.global_weight +
local_loss_dict['loss'] * losses_config.local_weight +
reg_loss)
all_losses.update({
'total_loss': total_loss
})
all_losses[self.loss] = total_loss
logging_metrics['regularization_loss'] = reg_loss
for k, v in global_loss_dict.items():
logging_metrics['global_loss/' + k] = v
for k, v in local_loss_dict.items():
logging_metrics['local_loss/' + k] = v
return all_losses, logging_metrics
def build_metrics(self, training=True):
"""Gets streaming metrics for training/validation."""
metrics = [
tf.keras.metrics.Mean(name='regularization_loss'),
tf.keras.metrics.Mean(name='global_loss/loss'),
tf.keras.metrics.Mean(name='global_loss/contrastive_accuracy'),
tf.keras.metrics.Mean(name='global_loss/contrastive_entropy'),
tf.keras.metrics.Mean(name='local_loss/loss'),
tf.keras.metrics.Mean(name='local_loss/positive_similarity_mean'),
tf.keras.metrics.Mean(name='local_loss/positive_similarity_max'),
tf.keras.metrics.Mean(name='local_loss/positive_similarity_min'),
tf.keras.metrics.Mean(name='local_loss/negative_similarity_mean'),
tf.keras.metrics.Mean(name='local_loss/negative_similarity_max'),
tf.keras.metrics.Mean(name='local_loss/negative_similarity_min'),
]
return metrics
def process_metrics(self, metrics, contrastive_metrics):
"""Processes and updates metrics."""
for metric in metrics:
v = contrastive_metrics[metric.name]
metric.update_state(v)
def train_step(self, inputs, model, optimizer, metrics=None):
"""Forward and backward pass.
Args:
inputs: a dictionary of input tensors.
model: the model, forward pass definition.
optimizer: the optimizer for this training step.
metrics: a nested structure of metrics objects.
Returns:
A dictionary of logs.
"""
features, _ = inputs
num_replicas = tf.distribute.get_strategy().num_replicas_in_sync
with tf.GradientTape() as tape:
outputs = model(features, training=True)
# Casting output layer as float32 is necessary when mixed_precision is
# mixed_float16 or mixed_bfloat16 to ensure output is casted as float32.
outputs = tf.nest.map_structure(
lambda x: tf.cast(x, tf.float32), outputs)
all_losses, contrastive_metrics = self.build_losses(
model_outputs=outputs, num_replicas=num_replicas,
model=model)
scaled_loss = all_losses[self.loss]
# For mixed_precision policy, when LossScaleOptimizer is used, loss is
# scaled for numerical stability.
if isinstance(
optimizer, tf.keras.mixed_precision.LossScaleOptimizer):
scaled_loss = optimizer.get_scaled_loss(scaled_loss)
tvars = model.trainable_variables
grads = tape.gradient(scaled_loss, tvars)
# Scales back gradient before apply_gradients when LossScaleOptimizer is
# used.
if isinstance(optimizer, tf.keras.mixed_precision.LossScaleOptimizer):
grads = optimizer.get_unscaled_gradients(grads)
optimizer.apply_gradients(list(zip(grads, tvars)))
logs = all_losses
if metrics:
self.process_metrics(metrics, contrastive_metrics)
logs.update({m.name: m.result() for m in metrics})
return logs
def validation_step(self, inputs, model, metrics=None):
"""Validatation step.
Args:
inputs: a dictionary of input tensors.
model: the keras.Model.
metrics: a nested structure of metrics objects.
Returns:
A dictionary of logs.
"""
raise NotImplementedError
def inference_step(self, features, model):
"""Performs the forward step."""
raise NotImplementedError
| 8,419 | 36.422222 | 79 | py |
models | models-master/official/projects/const_cl/losses/losses_test.py | # Copyright 2023 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.
"""Tests for losses."""
import tensorflow as tf
from official.projects.const_cl.losses import losses
class LossesTest(tf.test.TestCase):
def test_constrative_loss(self):
contrastive_loss = losses.ContrastiveLoss(normalize_inputs=True,
temperature=0.1)
inputs1 = tf.constant(
[[1, 2, 3, 4], [5, 6, 7, 8], [4, 3, 2, 1], [8, 7, 6, 5]],
dtype=tf.float32)
inputs2 = tf.constant(
[[1, 2, 3, 4], [4, 3, 2, 1], [5, 6, 7, 8], [8, 7, 6, 5]],
dtype=tf.float32)
inputs = tf.concat([inputs1, inputs2], axis=0)
contrastive_loss_dict = contrastive_loss(inputs)
self.assertAlmostEqual(contrastive_loss_dict['contrastive_accuracy'], 0.5)
self.assertAlmostEqual(contrastive_loss_dict['loss'], 4.136947, places=4)
def test_instance_constrative_loss(self):
instance_contrastive_loss = losses.InstanceContrastiveLoss(
normalize_inputs=True, temperature=0.1)
inst_a = tf.constant(
[[[1, 2, 3, 4], [5, 6, 7, 8], [-1, -1, -1, -1], [-1, -1, -1, -1]],
[[-1, -1, -1, -1], [-1, -1, -1, -1], [4, 3, 2, 1], [8, 7, 6, 5]],
[[1, 2, 3, 4], [5, 6, 7, 8], [4, 3, 2, 1], [8, 7, 6, 5]]],
dtype=tf.float32)
inst_b = tf.constant([[[1.5, 2.5, 3.5, 4.5], [5.5, 6.5, 7.5, 8.5],
[-1, -1, -1, -1], [-1, -1, -1, -1]],
[[-1, -1, -1, -1], [-1, -1, -1, -1],
[5.5, 6.5, 7.5, 8.5], [8.5, 7.5, 6.5, 5.5]],
[[1.5, 2.5, 3.5, 4.5], [4.5, 3.5, 2.5, 1.5],
[5.5, 6.5, 7.5, 8.5], [8.5, 7.5, 6.5, 5.5]]],
dtype=tf.float32)
inst_a2b = inst_b
inst_b2a = inst_a
masks_a = tf.constant(
[[True, True, False, False],
[False, False, True, True],
[True, True, True, True]], dtype=tf.bool)
masks_b = tf.constant(
[[True, True, False, False],
[False, False, True, True],
[True, True, True, True]], dtype=tf.bool)
predictions = {
'instances_a': inst_a,
'instances_b': inst_b,
'instances_a2b': inst_a2b,
'instances_b2a': inst_b2a,
'masks_a': masks_a,
'masks_b': masks_b}
contrastive_loss_dict = instance_contrastive_loss(
predictions=predictions)
self.assertContainsSubset(
list(contrastive_loss_dict.keys()), [
'loss', 'positive_similarity_mean', 'positive_similarity_min',
'positive_similarity_max', 'negative_similarity_mean',
'negative_similarity_min', 'negative_similarity_max'
])
if __name__ == '__main__':
tf.test.main()
| 3,289 | 37.705882 | 78 | py |
models | models-master/official/projects/const_cl/losses/losses.py | # Copyright 2023 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.
"""The losses for ConST-CL."""
from typing import Mapping
import tensorflow as tf
from tensorflow.compiler.tf2xla.python import xla # pylint: disable=g-direct-tensorflow-import
from official.projects.video_ssl.losses import losses as video_ssl_losses
tpu_cross_replica_concat = video_ssl_losses.tpu_cross_replica_concat
_LARGE_NUM = 1e9
class ContrastiveLoss(object):
"""InfoNCE loss.
Reference: Oord et al. "Representation learning with contrastive
predictive coding" NeurIPS 2019.
"""
def __init__(self,
normalize_inputs: bool,
temperature: float):
"""Computes contrastive loss.
Args:
normalize_inputs: whether or not to l2 normalize the inputs vector.
temperature: temperature in the InfoNCE contrastive loss.
"""
self._normalize_inputs = normalize_inputs
self._temperature = temperature
def __call__(self,
inputs: tf.Tensor,
num_replicas: int = 1) -> Mapping[str, tf.Tensor]:
"""Calculates the loss.
Args:
inputs: the embeddings (in shape [2*B, C]) from video clips after the
projection head.
num_replicas: the number of TPU replicas.
Returns:
a dictionary contains calculated loss and statistics.
"""
inputs1, inputs2 = tf.split(inputs, num_or_size_splits=2, axis=0)
if self._normalize_inputs:
inputs1 = tf.math.l2_normalize(inputs1, -1)
inputs2 = tf.math.l2_normalize(inputs2, -1)
batch_size = tf.shape(inputs1)[0]
if num_replicas == 1:
# This is the local version.
inputs1_large = inputs1
inputs2_large = inputs2
labels = tf.one_hot(tf.range(batch_size), batch_size * 2)
masks = tf.one_hot(tf.range(batch_size), batch_size)
else:
# This is the cross-tpu version.
inputs1_large = tpu_cross_replica_concat(inputs1, num_replicas)
inputs2_large = tpu_cross_replica_concat(inputs2, num_replicas)
enlarged_batch_size = tf.shape(inputs1_large)[0]
replica_id = tf.cast(tf.cast(xla.replica_id(), tf.uint32), tf.int32)
labels_idx = tf.range(batch_size) + replica_id * batch_size
labels = tf.one_hot(labels_idx, enlarged_batch_size * 2)
masks = tf.one_hot(labels_idx, enlarged_batch_size)
logits_aa = tf.matmul(
inputs1, inputs1_large, transpose_b=True) / self._temperature
logits_aa = logits_aa - tf.cast(masks, logits_aa.dtype) * _LARGE_NUM
logits_bb = tf.matmul(
inputs2, inputs2_large, transpose_b=True) / self._temperature
logits_bb = logits_bb - tf.cast(masks, logits_bb.dtype) * _LARGE_NUM
logits_ab = tf.matmul(
inputs1, inputs2_large, transpose_b=True) / self._temperature
logits_ba = tf.matmul(
inputs2, inputs1_large, transpose_b=True) / self._temperature
loss_a = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
labels, tf.concat([logits_ab, logits_aa], 1)))
loss_b = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
labels, tf.concat([logits_ba, logits_bb], 1)))
loss = loss_a + loss_b
contrast_prob = tf.nn.softmax(logits_ab)
contrast_entropy = - tf.reduce_mean(
tf.reduce_sum(contrast_prob * tf.math.log(contrast_prob + 1e-8), -1))
contrast_acc = tf.equal(tf.argmax(labels, 1), tf.argmax(logits_ab, axis=1))
contrast_acc = tf.reduce_mean(tf.cast(contrast_acc, tf.float32))
return {
'loss': loss,
'contrastive_accuracy': contrast_acc,
'contrastive_entropy': contrast_entropy,
}
class InstanceContrastiveLoss(object):
"""Instance Contrastive Loss.
Reference: Yuan et al. "Contextualized Spatio-Temporal Contrastive Learning
with Self-Supervision" CVPR 2022.
"""
def __init__(self,
normalize_inputs: bool,
temperature: float):
self._normalize_inputs = normalize_inputs
self._temperature = temperature
def __call__(self,
predictions: Mapping[str, tf.Tensor],
num_replicas: int = 1) -> Mapping[str, tf.Tensor]:
"""Computes contrastive loss for spatio-temporal instance embeddings.
Args:
predictions: a dictionary of the model outputs, contains
'instances_a2b': the reconstructed instance features from view a -> b.
In shape [B, N, C].
'instances_b2a': the reconstructed instance features from view b -> a.
In shape [B, N, C].
'instances_a': the target instance features in view a. In shape
[B, N, C].
'instances_b': the target instance features in view b. In shape
[B, N, C].
'masks_a': the vaidity boolean mask for instances in view a. In shape
[B, N].
'masks_b': the vaidity boolean mask for instances in view b. In shape
[B, N].
num_replicas: the number of TPU replicas.
Returns:
A loss scalar.
The staticstics for positive examples.
The staticstics for negative examples.
"""
inst_a2b = predictions['instances_a2b']
inst_b2a = predictions['instances_b2a']
inst_a = predictions['instances_a']
inst_b = predictions['instances_b']
masks_a = tf.cast(predictions['masks_a'][..., None], dtype=inst_a.dtype)
masks_b = tf.cast(predictions['masks_b'][..., None], dtype=inst_b.dtype)
if self._normalize_inputs:
inst_a2b = tf.math.l2_normalize(inst_a2b, axis=-1)
inst_b2a = tf.math.l2_normalize(inst_b2a, axis=-1)
inst_a = tf.math.l2_normalize(inst_a, axis=-1)
inst_b = tf.math.l2_normalize(inst_b, axis=-1)
b, n = inst_a.shape.as_list()[:2]
batch_index = tf.range(b)
# Computes similarity based on raw features in view a and b.
similarity_ab = tf.einsum('ijc,ikc->ijk', inst_a, inst_b)
# Loss on translated_a2b.
similarity_ab_index = tf.argmax(similarity_ab, axis=2, output_type=tf.int32)
lookup_a2b_index = tf.stack(
[tf.tile(batch_index[:, None], [1, n]), similarity_ab_index], axis=-1)
loss_and_stats_a = self._compute_constrastive_loss(
positive_lookup_index=lookup_a2b_index,
inst_translated=inst_a2b,
inst_target=inst_b,
inst_mask=masks_a,
num_replicas=num_replicas)
# Loss on translated_b2a.
similarity_ba_index = tf.argmax(similarity_ab, axis=1, output_type=tf.int32)
lookup_b2a_index = tf.stack(
[tf.tile(batch_index[:, None], [1, n]), similarity_ba_index], axis=-1)
loss_and_stats_b = self._compute_constrastive_loss(
positive_lookup_index=lookup_b2a_index,
inst_translated=inst_b2a,
inst_target=inst_a,
inst_mask=masks_b,
num_replicas=num_replicas)
loss_and_stats = {}
for key in loss_and_stats_a:
loss_and_stats[key] = 0.5 * (
loss_and_stats_a[key] + loss_and_stats_b[key])
return loss_and_stats
def _get_negative_similarity_statistics(
self,
logits: tf.Tensor,
batch_masks: tf.Tensor,
inst_mask: tf.Tensor) -> Mapping[str, tf.Tensor]:
"""Gets negative examples similarity statistics.
Args:
logits: the logits matrix.
batch_masks: the batch validity mask.
inst_mask: the instance validity mask.
Returns:
logs: a dictionary of logs.
"""
# logits = [b, n, bl, n]
# batch_masks = [b, n, bl, n]
# inst_mask = [b, n, 1]
inst_mask = tf.cast(inst_mask, logits.dtype)
batch_masks = tf.cast(batch_masks, logits.dtype)
batch_masks = tf.ones_like(batch_masks) - batch_masks
masks = batch_masks * inst_mask[..., None]
# Recover the raw similarity and mask self-similarity, which will be
# removed from negative samples.
similarity = logits * masks * self._temperature
similarity_mean = tf.reduce_sum(similarity) / tf.reduce_sum(masks)
similarity_masks = tf.squeeze(inst_mask, axis=-1)
similarity_max = similarity - (1.0 - masks) * _LARGE_NUM
similarity_max = tf.reduce_max(similarity_max, axis=[-1, -2])
similarity_max = tf.reduce_sum(
similarity_max * similarity_masks) / tf.reduce_sum(similarity_masks)
similarity_min = similarity + (1.0 - masks) * _LARGE_NUM
similarity_min = tf.reduce_min(similarity_min, axis=[-1, -2])
similarity_min = tf.reduce_sum(
similarity_min * similarity_masks) / tf.reduce_sum(similarity_masks)
logs = {
'negative_similarity_mean': similarity_mean,
'negative_similarity_min': similarity_min,
'negative_similarity_max': similarity_max,
}
return logs
def _get_positive_similarity_statistics(
self,
logits: tf.Tensor,
inst_mask: tf.Tensor) -> Mapping[str, tf.Tensor]:
"""Gets positive examples similarity statistics.
Args:
logits: the logits matrix.
inst_mask: the instance validity mask.
Returns:
logs: a dictionary of logs.
"""
# logits in shape [b, n]
# inst_mask in shape [b, n, 1]
inst_mask = tf.squeeze(inst_mask, axis=-1)
inst_mask = tf.cast(inst_mask, dtype=logits.dtype)
similarity = logits * inst_mask * self._temperature
num_instances = tf.reduce_sum(inst_mask)
similarity_mean = tf.reduce_sum(similarity) / num_instances
similarity_max = similarity - (1.0 - inst_mask) * _LARGE_NUM
similarity_max = tf.reduce_max(similarity_max)
similarity_min = similarity + (1.0 - inst_mask) * _LARGE_NUM
similarity_min = tf.reduce_min(similarity_min)
logs = {
'positive_similarity_mean': similarity_mean,
'positive_similarity_min': similarity_min,
'positive_similarity_max': similarity_max,
}
return logs
def _compute_constrastive_loss(
self,
positive_lookup_index: tf.Tensor,
inst_translated: tf.Tensor,
inst_target: tf.Tensor,
inst_mask: tf.Tensor,
num_replicas: int = 1) -> Mapping[str, tf.Tensor]:
"""Computes constrastive loss.
Args:
positive_lookup_index: the index tensor to look-up the corresponding
features in inst_target. In shape [B, N].
inst_translated: a float tensor of shape [B, N, C] of translated instance
features by the transformer head.
inst_target: a float tensor of shape [B, N, C] of instance features on the
target domain. Note that the order of inst_target is not necessarily
matched to inst_translated.
inst_mask: a boolean tensor of shape [B, N, 1] suggesting valid instances
in inst_translated.
num_replicas: the number of TPU replicas.
Returns:
loss_and_stats: a dictionary of loss and intermediate statistics.
"""
b, n = inst_translated.shape.as_list()[:2]
if num_replicas == 1:
inst_target_large = inst_target
b_large = tf.shape(inst_target_large)[0]
labels_idx = tf.range(b)
else:
inst_target_large = tpu_cross_replica_concat(
inst_target,
num_replicas)
b_large = tf.shape(inst_target_large)[0]
# NOTE: make sure to use xla.replica_id() here and in
# tpu_cross_replica_concat to consistently align the replica_id.
# replicator.replica_id != xla.replica_id()
replica_id = tf.cast(tf.cast(xla.replica_id(), tf.uint32), tf.int32)
labels_idx = tf.range(b) + replica_id * b
# [B, BL], 1 indicates positive batches.
batch_masks = tf.one_hot(labels_idx, b_large)
# [B, N, BL, N]
batch_masks = tf.tile(batch_masks[:, None, :, None], [1, n, 1, n])
# Construct negative examples.
logits_negative = tf.einsum(
'ijc,pqc->ijpq',
inst_translated, inst_target_large) / self._temperature
# Get negative statistics.
negative_stats = self._get_negative_similarity_statistics(
logits_negative, batch_masks, inst_mask)
logits_negative = logits_negative - tf.cast(
batch_masks, logits_negative.dtype) * _LARGE_NUM
logits_negative = tf.reshape(logits_negative, [b * n, b_large * n])
# Construct positive examples.
inst_matched = tf.gather_nd(
inst_target, positive_lookup_index, name='matched_inst')
logits_positive = tf.einsum(
'ijc,ijc->ij',
inst_translated, inst_matched) / self._temperature
# Get positive statistics.
positive_stats = self._get_positive_similarity_statistics(
logits_positive, inst_mask)
logits_positive = tf.reshape(logits_positive, [b * n, 1])
logits_all = tf.concat([logits_positive, logits_negative], axis=1)
loss_pos = tf.reduce_logsumexp(logits_positive, 1)
loss_all = tf.reduce_logsumexp(logits_all, 1)
loss = (loss_all - loss_pos) * tf.reshape(inst_mask, [b * n])
# Average across instances.
loss = tf.math.divide_no_nan(
tf.reduce_sum(loss), tf.reduce_sum(inst_mask))
loss_and_stats = {'loss': loss}
loss_and_stats.update(negative_stats)
loss_and_stats.update(positive_stats)
return loss_and_stats
| 13,425 | 36.088398 | 95 | py |
models | models-master/official/projects/nhnet/decoder_test.py | # Copyright 2023 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.
"""Tests for projects.nhnet.decoder."""
import numpy as np
import tensorflow as tf
from official.nlp.modeling import layers
from official.projects.nhnet import configs
from official.projects.nhnet import decoder
from official.projects.nhnet import utils
class DecoderTest(tf.test.TestCase):
def setUp(self):
super(DecoderTest, self).setUp()
self._config = utils.get_test_params()
def test_transformer_decoder(self):
decoder_block = decoder.TransformerDecoder(
num_hidden_layers=self._config.num_hidden_layers,
hidden_size=self._config.hidden_size,
num_attention_heads=self._config.num_attention_heads,
intermediate_size=self._config.intermediate_size,
intermediate_activation=self._config.hidden_act,
hidden_dropout_prob=self._config.hidden_dropout_prob,
attention_probs_dropout_prob=self._config.attention_probs_dropout_prob,
initializer_range=self._config.initializer_range)
decoder_block.build(None)
self.assertEqual(len(decoder_block.layers), self._config.num_hidden_layers)
def test_bert_decoder(self):
seq_length = 10
encoder_input_ids = tf.keras.layers.Input(
shape=(seq_length,), name="encoder_input_ids", dtype=tf.int32)
target_ids = tf.keras.layers.Input(
shape=(seq_length,), name="target_ids", dtype=tf.int32)
encoder_outputs = tf.keras.layers.Input(
shape=(seq_length, self._config.hidden_size),
name="all_encoder_outputs",
dtype=tf.float32)
embedding_lookup = layers.OnDeviceEmbedding(
vocab_size=self._config.vocab_size,
embedding_width=self._config.hidden_size,
initializer=tf.keras.initializers.TruncatedNormal(
stddev=self._config.initializer_range),
name="word_embeddings")
cross_attention_bias = decoder.AttentionBias(bias_type="single_cross")(
encoder_input_ids)
self_attention_bias = decoder.AttentionBias(bias_type="decoder_self")(
target_ids)
inputs = dict(
attention_bias=cross_attention_bias,
self_attention_bias=self_attention_bias,
target_ids=target_ids,
all_encoder_outputs=encoder_outputs)
decoder_layer = decoder.Decoder(self._config, embedding_lookup)
outputs = decoder_layer(inputs)
model_inputs = dict(
encoder_input_ids=encoder_input_ids,
target_ids=target_ids,
all_encoder_outputs=encoder_outputs)
model = tf.keras.Model(inputs=model_inputs, outputs=outputs, name="test")
self.assertLen(decoder_layer.trainable_weights, 30)
# Forward path.
fake_inputs = {
"encoder_input_ids": np.zeros((2, 10), dtype=np.int32),
"target_ids": np.zeros((2, 10), dtype=np.int32),
"all_encoder_outputs": np.zeros((2, 10, 16), dtype=np.float32),
}
output_tensor = model(fake_inputs)
self.assertEqual(output_tensor.shape, (2, 10, 16))
def test_multi_doc_decoder(self):
self._config = utils.get_test_params(cls=configs.NHNetConfig)
seq_length = 10
num_docs = 5
encoder_input_ids = tf.keras.layers.Input(
shape=(num_docs, seq_length), name="encoder_input_ids", dtype=tf.int32)
target_ids = tf.keras.layers.Input(
shape=(seq_length,), name="target_ids", dtype=tf.int32)
encoder_outputs = tf.keras.layers.Input(
shape=(num_docs, seq_length, self._config.hidden_size),
name="all_encoder_outputs",
dtype=tf.float32)
embedding_lookup = layers.OnDeviceEmbedding(
vocab_size=self._config.vocab_size,
embedding_width=self._config.hidden_size,
initializer=tf.keras.initializers.TruncatedNormal(
stddev=self._config.initializer_range),
name="word_embeddings")
doc_attention_probs = tf.keras.layers.Input(
shape=(self._config.num_decoder_attn_heads, seq_length, num_docs),
name="doc_attention_probs",
dtype=tf.float32)
cross_attention_bias = decoder.AttentionBias(bias_type="multi_cross")(
encoder_input_ids)
self_attention_bias = decoder.AttentionBias(bias_type="decoder_self")(
target_ids)
inputs = dict(
attention_bias=cross_attention_bias,
self_attention_bias=self_attention_bias,
target_ids=target_ids,
all_encoder_outputs=encoder_outputs,
doc_attention_probs=doc_attention_probs)
decoder_layer = decoder.Decoder(self._config, embedding_lookup)
outputs = decoder_layer(inputs)
model_inputs = dict(
encoder_input_ids=encoder_input_ids,
target_ids=target_ids,
all_encoder_outputs=encoder_outputs,
doc_attention_probs=doc_attention_probs)
model = tf.keras.Model(inputs=model_inputs, outputs=outputs, name="test")
self.assertLen(decoder_layer.trainable_weights, 30)
# Forward path.
fake_inputs = {
"encoder_input_ids":
np.zeros((2, num_docs, seq_length), dtype=np.int32),
"target_ids":
np.zeros((2, seq_length), dtype=np.int32),
"all_encoder_outputs":
np.zeros((2, num_docs, seq_length, 16), dtype=np.float32),
"doc_attention_probs":
np.zeros(
(2, self._config.num_decoder_attn_heads, seq_length, num_docs),
dtype=np.float32)
}
output_tensor = model(fake_inputs)
self.assertEqual(output_tensor.shape, (2, seq_length, 16))
if __name__ == "__main__":
tf.test.main()
| 6,024 | 39.709459 | 79 | py |
models | models-master/official/projects/nhnet/raw_data_processor.py | # Copyright 2023 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.
"""Library for processing crawled content and generating tfrecords."""
import collections
import json
import multiprocessing
import os
import urllib.parse
import tensorflow as tf
from official.nlp.data import classifier_data_lib
from official.nlp.tools import tokenization
class RawDataProcessor(object):
"""Data converter for story examples."""
def __init__(self,
vocab: str,
do_lower_case: bool,
len_title: int = 15,
len_passage: int = 200,
max_num_articles: int = 5,
include_article_title_in_passage: bool = False,
include_text_snippet_in_example: bool = False):
"""Constructs a RawDataProcessor.
Args:
vocab: Filepath of the BERT vocabulary.
do_lower_case: Whether the vocabulary is uncased or not.
len_title: Maximum number of tokens in story headline.
len_passage: Maximum number of tokens in article passage.
max_num_articles: Maximum number of articles in a story.
include_article_title_in_passage: Whether to include article title in
article passage.
include_text_snippet_in_example: Whether to include text snippet (headline
and article content) in generated tensorflow Examples, for debug usage.
If include_article_title_in_passage=True, title and body will be
separated by [SEP].
"""
self.articles = dict()
self.tokenizer = tokenization.FullTokenizer(
vocab, do_lower_case=do_lower_case, split_on_punc=False)
self.len_title = len_title
self.len_passage = len_passage
self.max_num_articles = max_num_articles
self.include_article_title_in_passage = include_article_title_in_passage
self.include_text_snippet_in_example = include_text_snippet_in_example
# ex_index=5 deactivates printing inside convert_single_example.
self.ex_index = 5
# Parameters used in InputExample, not used in NHNet.
self.label = 0
self.guid = 0
self.num_generated_examples = 0
def read_crawled_articles(self, folder_path):
"""Reads crawled articles under folder_path."""
for path, _, files in os.walk(folder_path):
for name in files:
if not name.endswith(".json"):
continue
url, article = self._get_article_content_from_json(
os.path.join(path, name))
if not article.text_a:
continue
self.articles[RawDataProcessor.normalize_url(url)] = article
if len(self.articles) % 5000 == 0:
print("Number of articles loaded: %d\r" % len(self.articles), end="")
print()
return len(self.articles)
def generate_examples(self, input_file, output_files):
"""Loads story from input json file and exports examples in output_files."""
writers = []
story_partition = []
for output_file in output_files:
writers.append(tf.io.TFRecordWriter(output_file))
story_partition.append(list())
with tf.io.gfile.GFile(input_file, "r") as story_json_file:
stories = json.load(story_json_file)
writer_index = 0
for story in stories:
articles = []
for url in story["urls"]:
normalized_url = RawDataProcessor.normalize_url(url)
if normalized_url in self.articles:
articles.append(self.articles[normalized_url])
if not articles:
continue
story_partition[writer_index].append((story["label"], articles))
writer_index = (writer_index + 1) % len(writers)
lock = multiprocessing.Lock()
pool = multiprocessing.pool.ThreadPool(len(writers))
data = [(story_partition[i], writers[i], lock) for i in range(len(writers))]
pool.map(self._write_story_partition, data)
return len(stories), self.num_generated_examples
@classmethod
def normalize_url(cls, url):
"""Normalize url for better matching."""
url = urllib.parse.unquote(
urllib.parse.urlsplit(url)._replace(query=None).geturl())
output, part = [], None
for part in url.split("//"):
if part == "http:" or part == "https:":
continue
else:
output.append(part)
return "//".join(output)
def _get_article_content_from_json(self, file_path):
"""Returns (url, InputExample) keeping content extracted from file_path."""
with tf.io.gfile.GFile(file_path, "r") as article_json_file:
article = json.load(article_json_file)
if self.include_article_title_in_passage:
return article["url"], classifier_data_lib.InputExample(
guid=self.guid,
text_a=article["title"],
text_b=article["maintext"],
label=self.label)
else:
return article["url"], classifier_data_lib.InputExample(
guid=self.guid, text_a=article["maintext"], label=self.label)
def _write_story_partition(self, data):
"""Writes stories in a partition into file."""
for (story_headline, articles) in data[0]:
story_example = tf.train.Example(
features=tf.train.Features(
feature=self._get_single_story_features(story_headline,
articles)))
data[1].write(story_example.SerializeToString())
data[2].acquire()
try:
self.num_generated_examples += 1
if self.num_generated_examples % 1000 == 0:
print(
"Number of stories written: %d\r" % self.num_generated_examples,
end="")
finally:
data[2].release()
def _get_single_story_features(self, story_headline, articles):
"""Converts a list of articles to a tensorflow Example."""
def get_text_snippet(article):
if article.text_b:
return " [SEP] ".join([article.text_a, article.text_b])
else:
return article.text_a
story_features = collections.OrderedDict()
story_headline_feature = classifier_data_lib.convert_single_example(
ex_index=self.ex_index,
example=classifier_data_lib.InputExample(
guid=self.guid, text_a=story_headline, label=self.label),
label_list=[self.label],
max_seq_length=self.len_title,
tokenizer=self.tokenizer)
if self.include_text_snippet_in_example:
story_headline_feature.label_id = story_headline
self._add_feature_with_suffix(
feature=story_headline_feature,
suffix="a",
story_features=story_features)
for (article_index, article) in enumerate(articles):
if article_index == self.max_num_articles:
break
article_feature = classifier_data_lib.convert_single_example(
ex_index=self.ex_index,
example=article,
label_list=[self.label],
max_seq_length=self.len_passage,
tokenizer=self.tokenizer)
if self.include_text_snippet_in_example:
article_feature.label_id = get_text_snippet(article)
suffix = chr(ord("b") + article_index)
self._add_feature_with_suffix(
feature=article_feature, suffix=suffix, story_features=story_features)
# Adds empty features as placeholder.
for article_index in range(len(articles), self.max_num_articles):
suffix = chr(ord("b") + article_index)
empty_article = classifier_data_lib.InputExample(
guid=self.guid, text_a="", label=self.label)
empty_feature = classifier_data_lib.convert_single_example(
ex_index=self.ex_index,
example=empty_article,
label_list=[self.label],
max_seq_length=self.len_passage,
tokenizer=self.tokenizer)
if self.include_text_snippet_in_example:
empty_feature.label_id = ""
self._add_feature_with_suffix(
feature=empty_feature, suffix=suffix, story_features=story_features)
return story_features
def _add_feature_with_suffix(self, feature, suffix, story_features):
"""Appends suffix to feature names and fills in the corresponding values."""
def _create_int_feature(values):
return tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
def _create_string_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
story_features["input_ids_%c" % suffix] = _create_int_feature(
feature.input_ids)
story_features["input_mask_%c" % suffix] = _create_int_feature(
feature.input_mask)
story_features["segment_ids_%c" % suffix] = _create_int_feature(
feature.segment_ids)
if self.include_text_snippet_in_example:
story_features["text_snippet_%c" % suffix] = _create_string_feature(
bytes(feature.label_id.encode()))
| 9,238 | 39.169565 | 80 | py |
models | models-master/official/projects/nhnet/utils.py | # Copyright 2023 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.
"""Utility helpers for Bert2Bert."""
from typing import Optional, Text
from absl import logging
import tensorflow as tf
from official.legacy.bert import configs
from official.modeling.hyperparams import params_dict
from official.projects.nhnet import configs as nhnet_configs
def get_bert_config_from_params(
params: params_dict.ParamsDict) -> configs.BertConfig:
"""Converts a BertConfig to ParamsDict."""
return configs.BertConfig.from_dict(params.as_dict())
def get_test_params(cls=nhnet_configs.BERT2BERTConfig):
return cls.from_args(**nhnet_configs.UNITTEST_CONFIG)
# pylint: disable=protected-access
def encoder_common_layers(transformer_block):
return [
transformer_block._attention_layer,
transformer_block._attention_layer_norm,
transformer_block._intermediate_dense, transformer_block._output_dense,
transformer_block._output_layer_norm
]
# pylint: enable=protected-access
def initialize_bert2bert_from_pretrained_bert(
bert_encoder: tf.keras.layers.Layer,
bert_decoder: tf.keras.layers.Layer,
init_checkpoint: Optional[Text] = None) -> None:
"""Helper function to initialze Bert2Bert from Bert pretrained checkpoint."""
ckpt = tf.train.Checkpoint(model=bert_encoder)
logging.info(
"Checkpoint file %s found and restoring from "
"initial checkpoint for core model.", init_checkpoint)
status = ckpt.restore(init_checkpoint)
# Expects the bert model is a subset of checkpoint as pooling layer is
# not used.
status.assert_existing_objects_matched()
logging.info("Loading from checkpoint file completed.")
# Saves a checkpoint with transformer layers.
encoder_layers = []
for transformer_block in bert_encoder.transformer_layers:
encoder_layers.extend(encoder_common_layers(transformer_block))
# Restores from the checkpoint with encoder layers.
decoder_layers_to_initialize = []
for decoder_block in bert_decoder.decoder.layers:
decoder_layers_to_initialize.extend(
decoder_block.common_layers_with_encoder())
if len(decoder_layers_to_initialize) != len(encoder_layers):
raise ValueError(
"Source encoder layers with %d objects does not match destination "
"decoder layers with %d objects." %
(len(decoder_layers_to_initialize), len(encoder_layers)))
for dest_layer, source_layer in zip(decoder_layers_to_initialize,
encoder_layers):
try:
dest_layer.set_weights(source_layer.get_weights())
except ValueError as e:
logging.error(
"dest_layer: %s failed to set weights from "
"source_layer: %s as %s", dest_layer.name, source_layer.name, str(e))
| 3,294 | 35.611111 | 79 | py |
models | models-master/official/projects/nhnet/models_test.py | # Copyright 2023 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.
"""Tests for projects.nhnet.models."""
import os
from absl import logging
from absl.testing import parameterized
import numpy as np
import tensorflow as tf
# pylint: disable=g-direct-tensorflow-import
from tensorflow.python.distribute import combinations
from tensorflow.python.distribute import strategy_combinations
# pylint: enable=g-direct-tensorflow-import
from official.projects.nhnet import configs
from official.projects.nhnet import models
from official.projects.nhnet import utils
def all_strategy_combinations():
return combinations.combine(
distribution=[
strategy_combinations.default_strategy,
strategy_combinations.cloud_tpu_strategy,
strategy_combinations.one_device_strategy_gpu,
strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
strategy_combinations.mirrored_strategy_with_two_gpus,
],)
def distribution_forward_path(strategy,
model,
inputs,
batch_size,
mode="train"):
dataset = tf.data.Dataset.from_tensor_slices((inputs))
dataset = dataset.batch(batch_size)
dataset = strategy.experimental_distribute_dataset(dataset)
@tf.function
def test_step(inputs):
"""Calculates evaluation metrics on distributed devices."""
def _test_step_fn(inputs):
"""Replicated accuracy calculation."""
return model(inputs, mode=mode, training=False)
outputs = strategy.run(_test_step_fn, args=(inputs,))
return tf.nest.map_structure(strategy.experimental_local_results, outputs)
return [test_step(inputs) for inputs in dataset]
def process_decoded_ids(predictions, end_token_id):
"""Transforms decoded tensors to lists ending with END_TOKEN_ID."""
if isinstance(predictions, tf.Tensor):
predictions = predictions.numpy()
flatten_ids = predictions.reshape((-1, predictions.shape[-1]))
results = []
for ids in flatten_ids:
ids = list(ids)
if end_token_id in ids:
ids = ids[:ids.index(end_token_id)]
results.append(ids)
return results
class Bert2BertTest(tf.test.TestCase, parameterized.TestCase):
def setUp(self):
super(Bert2BertTest, self).setUp()
self._config = utils.get_test_params()
def test_model_creation(self):
model = models.create_bert2bert_model(params=self._config)
fake_ids = np.zeros((2, 10), dtype=np.int32)
fake_inputs = {
"input_ids": fake_ids,
"input_mask": fake_ids,
"segment_ids": fake_ids,
"target_ids": fake_ids,
}
model(fake_inputs)
@combinations.generate(all_strategy_combinations())
def test_bert2bert_train_forward(self, distribution):
seq_length = 10
# Defines the model inside distribution strategy scope.
with distribution.scope():
# Forward path.
batch_size = 2
batches = 4
fake_ids = np.zeros((batch_size * batches, seq_length), dtype=np.int32)
fake_inputs = {
"input_ids": fake_ids,
"input_mask": fake_ids,
"segment_ids": fake_ids,
"target_ids": fake_ids,
}
model = models.create_bert2bert_model(params=self._config)
results = distribution_forward_path(distribution, model, fake_inputs,
batch_size)
logging.info("Forward path results: %s", str(results))
self.assertLen(results, batches)
def test_bert2bert_decoding(self):
seq_length = 10
self._config.override(
{
"beam_size": 3,
"len_title": seq_length,
"alpha": 0.6,
},
is_strict=False)
batch_size = 2
fake_ids = np.zeros((batch_size, seq_length), dtype=np.int32)
fake_inputs = {
"input_ids": fake_ids,
"input_mask": fake_ids,
"segment_ids": fake_ids,
}
self._config.override({
"padded_decode": False,
"use_cache": False,
},
is_strict=False)
model = models.create_bert2bert_model(params=self._config)
ckpt = tf.train.Checkpoint(model=model)
# Initializes variables from checkpoint to keep outputs deterministic.
init_checkpoint = ckpt.save(os.path.join(self.get_temp_dir(), "ckpt"))
ckpt.restore(init_checkpoint).assert_existing_objects_matched()
top_ids, scores = model(fake_inputs, mode="predict")
self._config.override({
"padded_decode": False,
"use_cache": True,
},
is_strict=False)
model = models.create_bert2bert_model(params=self._config)
ckpt = tf.train.Checkpoint(model=model)
ckpt.restore(init_checkpoint).assert_existing_objects_matched()
cached_top_ids, cached_scores = model(fake_inputs, mode="predict")
self.assertEqual(
process_decoded_ids(top_ids, self._config.end_token_id),
process_decoded_ids(cached_top_ids, self._config.end_token_id))
self.assertAllClose(scores, cached_scores)
self._config.override({
"padded_decode": True,
"use_cache": True,
},
is_strict=False)
model = models.create_bert2bert_model(params=self._config)
ckpt = tf.train.Checkpoint(model=model)
ckpt.restore(init_checkpoint).assert_existing_objects_matched()
padded_top_ids, padded_scores = model(fake_inputs, mode="predict")
self.assertEqual(
process_decoded_ids(top_ids, self._config.end_token_id),
process_decoded_ids(padded_top_ids, self._config.end_token_id))
self.assertAllClose(scores, padded_scores)
@combinations.generate(all_strategy_combinations())
def test_bert2bert_eval(self, distribution):
seq_length = 10
padded_decode = isinstance(
distribution,
(tf.distribute.TPUStrategy, tf.distribute.experimental.TPUStrategy))
self._config.override(
{
"beam_size": 3,
"len_title": seq_length,
"alpha": 0.6,
"padded_decode": padded_decode,
},
is_strict=False)
# Defines the model inside distribution strategy scope.
with distribution.scope():
# Forward path.
batch_size = 2
batches = 4
fake_ids = np.zeros((batch_size * batches, seq_length), dtype=np.int32)
fake_inputs = {
"input_ids": fake_ids,
"input_mask": fake_ids,
"segment_ids": fake_ids,
}
model = models.create_bert2bert_model(params=self._config)
results = distribution_forward_path(
distribution, model, fake_inputs, batch_size, mode="predict")
self.assertLen(results, batches)
results = distribution_forward_path(
distribution, model, fake_inputs, batch_size, mode="eval")
self.assertLen(results, batches)
class NHNetTest(tf.test.TestCase, parameterized.TestCase):
def setUp(self):
super(NHNetTest, self).setUp()
self._nhnet_config = configs.NHNetConfig()
self._nhnet_config.override(utils.get_test_params().as_dict())
self._bert2bert_config = configs.BERT2BERTConfig()
self._bert2bert_config.override(utils.get_test_params().as_dict())
def _count_params(self, layer, trainable_only=True):
"""Returns the count of all model parameters, or just trainable ones."""
if not trainable_only:
return layer.count_params()
else:
return int(
np.sum([
tf.keras.backend.count_params(p) for p in layer.trainable_weights
]))
def test_create_nhnet_layers(self):
single_doc_bert, single_doc_decoder = models.get_bert2bert_layers(
self._bert2bert_config)
multi_doc_bert, multi_doc_decoder = models.get_nhnet_layers(
self._nhnet_config)
# Expects multi-doc encoder/decoder have the same number of parameters as
# single-doc encoder/decoder.
self.assertEqual(
self._count_params(multi_doc_bert), self._count_params(single_doc_bert))
self.assertEqual(
self._count_params(multi_doc_decoder),
self._count_params(single_doc_decoder))
def test_checkpoint_restore(self):
bert2bert_model = models.create_bert2bert_model(self._bert2bert_config)
ckpt = tf.train.Checkpoint(model=bert2bert_model)
init_checkpoint = ckpt.save(os.path.join(self.get_temp_dir(), "ckpt"))
nhnet_model = models.create_nhnet_model(
params=self._nhnet_config, init_checkpoint=init_checkpoint)
source_weights = (
bert2bert_model.bert_layer.trainable_weights +
bert2bert_model.decoder_layer.trainable_weights)
dest_weights = (
nhnet_model.bert_layer.trainable_weights +
nhnet_model.decoder_layer.trainable_weights)
for source_weight, dest_weight in zip(source_weights, dest_weights):
self.assertAllClose(source_weight.numpy(), dest_weight.numpy())
@combinations.generate(all_strategy_combinations())
def test_nhnet_train_forward(self, distribution):
seq_length = 10
# Defines the model inside distribution strategy scope.
with distribution.scope():
# Forward path.
batch_size = 2
num_docs = 2
batches = 4
fake_ids = np.zeros((batch_size * batches, num_docs, seq_length),
dtype=np.int32)
fake_inputs = {
"input_ids":
fake_ids,
"input_mask":
fake_ids,
"segment_ids":
fake_ids,
"target_ids":
np.zeros((batch_size * batches, seq_length * 2), dtype=np.int32),
}
model = models.create_nhnet_model(params=self._nhnet_config)
results = distribution_forward_path(distribution, model, fake_inputs,
batch_size)
logging.info("Forward path results: %s", str(results))
self.assertLen(results, batches)
@combinations.generate(all_strategy_combinations())
def test_nhnet_eval(self, distribution):
seq_length = 10
padded_decode = isinstance(
distribution,
(tf.distribute.TPUStrategy, tf.distribute.experimental.TPUStrategy))
self._nhnet_config.override(
{
"beam_size": 4,
"len_title": seq_length,
"alpha": 0.6,
"multi_channel_cross_attention": True,
"padded_decode": padded_decode,
},
is_strict=False)
# Defines the model inside distribution strategy scope.
with distribution.scope():
# Forward path.
batch_size = 2
num_docs = 2
batches = 4
fake_ids = np.zeros((batch_size * batches, num_docs, seq_length),
dtype=np.int32)
fake_inputs = {
"input_ids": fake_ids,
"input_mask": fake_ids,
"segment_ids": fake_ids,
"target_ids": np.zeros((batch_size * batches, 5), dtype=np.int32),
}
model = models.create_nhnet_model(params=self._nhnet_config)
results = distribution_forward_path(
distribution, model, fake_inputs, batch_size, mode="predict")
self.assertLen(results, batches)
results = distribution_forward_path(
distribution, model, fake_inputs, batch_size, mode="eval")
self.assertLen(results, batches)
if __name__ == "__main__":
tf.test.main()
| 11,786 | 35.267692 | 80 | py |
models | models-master/official/projects/nhnet/decoder.py | # Copyright 2023 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.
"""Transformer decoder that mimics a BERT encoder, to load BERT checkpoints."""
import tensorflow as tf
from official.legacy.transformer import model_utils as transformer_utils
from official.modeling import tf_utils
from official.nlp.modeling import layers
class TransformerDecoder(tf.keras.layers.Layer):
"""Transformer decoder stack."""
def __init__(self,
num_hidden_layers=12,
hidden_size=768,
num_attention_heads=12,
intermediate_size=3072,
intermediate_activation="gelu",
hidden_dropout_prob=0.0,
attention_probs_dropout_prob=0.0,
initializer_range=0.02,
attend_to_last_layer=True,
multi_channel_cross_attention=False,
**kwargs):
super(TransformerDecoder, self).__init__(**kwargs)
self.num_hidden_layers = num_hidden_layers
self.hidden_size = hidden_size
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.intermediate_activation = tf_utils.get_activation(
intermediate_activation)
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.initializer_range = initializer_range
self.attend_to_last_layer = attend_to_last_layer
self.multi_channel_cross_attention = multi_channel_cross_attention
def build(self, unused_input_shapes):
"""Implements build() for the layer."""
self.layers = []
for i in range(self.num_hidden_layers):
self.layers.append(
layers.TransformerDecoderBlock(
num_attention_heads=self.num_attention_heads,
intermediate_size=self.intermediate_size,
intermediate_activation=self.intermediate_activation,
dropout_rate=self.hidden_dropout_prob,
attention_dropout_rate=self.attention_probs_dropout_prob,
kernel_initializer=tf.keras.initializers.TruncatedNormal(
stddev=self.initializer_range),
multi_channel_cross_attention=self.multi_channel_cross_attention,
name=("layer_%d" % i)))
super(TransformerDecoder, self).build(unused_input_shapes)
def call(self, inputs, cache=None, decode_loop_step=None):
"""Return the output of the decoder layer stacks.
Args:
inputs: A dictionary of inputs. `decoder_inputs` is a tf.int32 tensor for
input ids. `encoder_outputs` is a list of tensors with shape
[batch_size, input_length, hidden_size]. `self_attention_mask` is the
bias for decoder self-attention layer. [1, 1, target_length,
target_length]. `attention_mask` is the bias for encoder-decoder
attention layer, [batch_size, 1, 1, input_length].
cache: A dictionary of cache tensors, including key & value attentions.
decode_loop_step: an integer to indicate the step inside a decoding loop.
Returns:
Output of decoder layer stack.
float32 tensor with shape [batch_size, target_length, hidden_size]
"""
decoder_inputs = inputs["decoder_inputs"]
encoder_outputs = inputs["encoder_outputs"]
self_attention_mask = inputs["self_attention_mask"]
attention_mask = inputs["attention_mask"]
decoder_shape = tf_utils.get_shape_list(decoder_inputs, expected_rank=3)
batch_size = decoder_shape[0]
decoder_length = decoder_shape[1]
def _to_bert_self_attention_mask(matrix):
"""[1, 1, target_len, target_len] -> [bs, target_len, target_len]."""
matrix = tf.squeeze(matrix, axis=[1])
matrix = tf.tile(matrix, [batch_size, 1, 1])
return matrix
def _to_bert_encdec_attention_mask(matrix):
"""[bs, 1, 1, input_len] -> [bs, target_len, input_len]."""
if self.multi_channel_cross_attention:
matrix = tf.expand_dims(matrix, axis=2)
matrix = tf.tile(matrix, [1, 1, decoder_length, 1])
else:
matrix = tf.squeeze(matrix, axis=[1])
matrix = tf.tile(matrix, [1, decoder_length, 1])
return matrix
attention_mask = _to_bert_encdec_attention_mask(attention_mask)
self_attention_mask = _to_bert_self_attention_mask(self_attention_mask)
output_tensor = decoder_inputs
for layer_idx in range(self.num_hidden_layers):
if self.attend_to_last_layer:
memory = encoder_outputs[-1]
else:
memory = encoder_outputs[layer_idx]
if self.multi_channel_cross_attention:
transformer_inputs = [
output_tensor, memory, attention_mask, self_attention_mask,
inputs["doc_attention_probs"]
]
else:
transformer_inputs = [
output_tensor, memory, attention_mask, self_attention_mask
]
# Gets the cache for decoding.
if cache is None:
output_tensor, _ = self.layers[layer_idx](transformer_inputs)
else:
cache_layer_idx = str(layer_idx)
output_tensor, cache[cache_layer_idx] = self.layers[layer_idx](
transformer_inputs,
cache=cache[cache_layer_idx],
decode_loop_step=decode_loop_step)
return output_tensor, cache
def get_attention_bias(input_tensor,
bias_type,
padding_value=0,
max_length=None):
"""A helper function to get various attention bias tensors."""
if bias_type not in ("single_cross", "multi_cross", "decoder_self"):
raise ValueError("Invalid attention bias type: %s" % bias_type)
if bias_type == "single_cross":
length = tf_utils.get_shape_list(input_tensor, expected_rank=2)[1]
bias = transformer_utils.get_padding_bias(
input_tensor, padding_value=padding_value)
elif bias_type == "multi_cross":
length = tf_utils.get_shape_list(input_tensor, expected_rank=3)[2]
padding = transformer_utils.get_padding(
input_tensor, padding_value=padding_value)
bias = padding * -1e9
else:
if max_length is not None:
length = max_length
else:
length = tf_utils.get_shape_list(input_tensor, expected_rank=2)[1]
bias = transformer_utils.get_decoder_self_attention_bias(length)
return tf.where(bias < 0, tf.zeros_like(bias), tf.ones_like(bias))
class AttentionBias(tf.keras.layers.Layer):
def __init__(self, bias_type, **kwargs):
super(AttentionBias, self).__init__(**kwargs)
self.bias_type = bias_type
def call(self, inputs):
return get_attention_bias(inputs, self.bias_type)
class EmbeddingPostprocessor(tf.keras.layers.Layer):
"""Performs various post-processing on a word embedding tensor."""
def __init__(self,
use_type_embeddings=False,
token_type_vocab_size=None,
use_position_embeddings=True,
max_position_embeddings=512,
dropout_prob=0.0,
initializer_range=0.02,
initializer=None,
**kwargs):
super(EmbeddingPostprocessor, self).__init__(**kwargs)
self.use_type_embeddings = use_type_embeddings
self.token_type_vocab_size = token_type_vocab_size
self.use_position_embeddings = use_position_embeddings
self.max_position_embeddings = max_position_embeddings
self.dropout_prob = dropout_prob
self.initializer_range = initializer_range
if not initializer:
self.initializer = tf.keras.initializers.TruncatedNormal(
stddev=initializer_range)
else:
self.initializer = initializer
if self.use_type_embeddings and not self.token_type_vocab_size:
raise ValueError("If `use_type_embeddings` is True, then "
"`token_type_vocab_size` must be specified.")
def build(self, input_shapes):
"""Implements build() for the layer."""
(word_embeddings_shape, _) = input_shapes
width = word_embeddings_shape.as_list()[-1]
self.type_embeddings = None
if self.use_type_embeddings:
self.type_embeddings = self.add_weight(
"type_embeddings",
shape=[self.token_type_vocab_size, width],
initializer=tf.keras.initializers.TruncatedNormal(
stddev=self.initializer_range),
dtype=self.dtype)
self.position_embeddings = None
if self.use_position_embeddings:
self.position_embeddings = self.add_weight(
"position_embeddings",
shape=[self.max_position_embeddings, width],
initializer=tf.keras.initializers.TruncatedNormal(
stddev=self.initializer_range),
dtype=self.dtype)
self.output_layer_norm = tf.keras.layers.LayerNormalization(
name="layer_norm", axis=-1, epsilon=1e-12, dtype=tf.float32)
self.output_dropout = tf.keras.layers.Dropout(
rate=self.dropout_prob, dtype=tf.float32)
super(EmbeddingPostprocessor, self).build(input_shapes)
def __call__(self, word_embeddings, token_type_ids=None, **kwargs):
inputs = tf_utils.pack_inputs([word_embeddings, token_type_ids])
return super(EmbeddingPostprocessor, self).__call__(inputs, **kwargs) # pytype: disable=attribute-error # typed-keras
def call(self, inputs):
"""Implements call() for the layer."""
unpacked_inputs = tf_utils.unpack_inputs(inputs)
word_embeddings = unpacked_inputs[0]
token_type_ids = unpacked_inputs[1]
input_shape = tf_utils.get_shape_list(word_embeddings, expected_rank=3)
batch_size = input_shape[0]
seq_length = input_shape[1]
width = input_shape[2]
output = word_embeddings
if self.use_type_embeddings:
flat_token_type_ids = tf.reshape(token_type_ids, [-1])
token_type_embeddings = tf.gather(self.type_embeddings,
flat_token_type_ids)
token_type_embeddings = tf.reshape(token_type_embeddings,
[batch_size, seq_length, width])
output += token_type_embeddings
if self.use_position_embeddings:
position_embeddings = tf.expand_dims(
tf.slice(self.position_embeddings, [0, 0], [seq_length, width]),
axis=0)
output += position_embeddings
output = self.output_layer_norm(output)
output = self.output_dropout(output)
return output
class Decoder(tf.keras.layers.Layer):
"""The decoder network which can reuse encoder embeddings for target."""
def __init__(self, config, embedding_lookup=None, **kwargs):
super(Decoder, self).__init__(**kwargs)
self.config = config
# Shares vocabulary embedding.
self.embedding_lookup = None
if embedding_lookup:
self.embedding_lookup = embedding_lookup
def build(self, unused_input_shapes):
"""Implements build() for the layer."""
if self.embedding_lookup is None:
self.embedding_lookup = layers.OnDeviceEmbedding(
vocab_size=self.config.vocab_size,
embedding_width=self.config.hidden_size,
initializer=tf.keras.initializers.TruncatedNormal(
stddev=self.config.initializer_range),
name="target_embeddings")
self.embedding_postprocessor = EmbeddingPostprocessor(
use_type_embeddings=False,
use_position_embeddings=True,
max_position_embeddings=self.config.max_position_embeddings,
dropout_prob=self.config.hidden_dropout_prob,
initializer=tf.keras.initializers.VarianceScaling(
scale=self.config.initializer_gain,
mode="fan_avg",
distribution="uniform"),
name="embedding_postprocessor")
# Decoder can use a different intermediate size.
self.multi_channel_cross_attention = self.config.get(
"multi_channel_cross_attention", False)
self.decoder = TransformerDecoder(
num_hidden_layers=self.config.num_decoder_layers,
hidden_size=self.config.hidden_size,
num_attention_heads=self.config.num_decoder_attn_heads,
intermediate_size=self.config.decoder_intermediate_size,
intermediate_activation=self.config.hidden_act,
hidden_dropout_prob=self.config.hidden_dropout_prob,
attention_probs_dropout_prob=self.config.attention_probs_dropout_prob,
initializer_range=self.config.initializer_range,
multi_channel_cross_attention=self.multi_channel_cross_attention,
name="decoder")
super(Decoder, self).build(unused_input_shapes)
def _decoding_step_time_signal(self, target_embeds, decode_loop_step):
"""Applies time signal (positional embeddings) for decoded embeddings."""
# TODO(hongkuny): migrate to keras bert and design a module to handle this.
output = target_embeds
if self.embedding_postprocessor.use_position_embeddings:
position_embeddings = tf.gather(
self.embedding_postprocessor.position_embeddings, [decode_loop_step])
# Broadcasts to all sequences inside a batch.
output += position_embeddings
output = self.embedding_postprocessor.output_layer_norm(output)
output = self.embedding_postprocessor.output_dropout(output)
return output
def call(self,
inputs,
cache=None,
decode_loop_step=None,
padded_decode=False):
"""Implements call() for the layer.
Args:
inputs: a list of input tensors.
cache: A dictionary of cache tensors, including key & value attentions.
Due to the limit of keras, we uses the side effect to update cache and
states of tensors will be mutated.
decode_loop_step: an integer to indicate the step inside a decoding loop.
padded_decode: a boolean indicates if the pass is for padded decoding.
Returns:
Decoder output tensors.
"""
attention_bias = inputs["attention_bias"]
target_ids = inputs["target_ids"]
all_encoder_outputs = inputs["all_encoder_outputs"]
self_attention_bias = inputs["self_attention_bias"]
if not isinstance(all_encoder_outputs, list):
all_encoder_outputs = [all_encoder_outputs]
target_embeds = self.embedding_lookup(target_ids)
if decode_loop_step is None:
target_embeds = self.embedding_postprocessor(target_embeds)
else:
target_embeds = self._decoding_step_time_signal(target_embeds,
decode_loop_step)
decoder_inputs = dict(
decoder_inputs=target_embeds,
encoder_outputs=all_encoder_outputs,
self_attention_mask=self_attention_bias,
attention_mask=attention_bias)
if self.multi_channel_cross_attention:
decoder_inputs["doc_attention_probs"] = inputs["doc_attention_probs"]
decode_outputs, cache = self.decoder(
decoder_inputs, cache, decode_loop_step if padded_decode else None)
return decode_outputs
| 15,312 | 40.274933 | 123 | py |
models | models-master/official/projects/nhnet/configs_test.py | # Copyright 2023 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.
"""Tests for configs."""
import tensorflow as tf
from official.projects.nhnet import configs
BERT2BERT_CONFIG = {
"vocab_size": 30522,
"hidden_size": 768,
"num_hidden_layers": 12,
"num_attention_heads": 12,
"intermediate_size": 3072,
"hidden_act": "gelu",
"hidden_dropout_prob": 0.1,
"attention_probs_dropout_prob": 0.1,
"max_position_embeddings": 512,
"type_vocab_size": 2,
"initializer_range": 0.02,
# model params
"decoder_intermediate_size": 3072,
"num_decoder_attn_heads": 12,
"num_decoder_layers": 12,
# training params
"label_smoothing": 0.1,
"learning_rate": 0.05,
"learning_rate_warmup_steps": 20000,
"optimizer": "Adam",
"adam_beta1": 0.9,
"adam_beta2": 0.997,
"adam_epsilon": 1e-09,
# predict params
"beam_size": 5,
"alpha": 0.6,
"initializer_gain": 1.0,
"use_cache": True,
# input params
"input_sharding": False,
"input_data_not_padded": False,
"pad_token_id": 0,
"end_token_id": 102,
"start_token_id": 101,
}
NHNET_CONFIG = {
"vocab_size": 30522,
"hidden_size": 768,
"num_hidden_layers": 12,
"num_attention_heads": 12,
"intermediate_size": 3072,
"hidden_act": "gelu",
"hidden_dropout_prob": 0.1,
"attention_probs_dropout_prob": 0.1,
"max_position_embeddings": 512,
"type_vocab_size": 2,
"initializer_range": 0.02,
# model params
"decoder_intermediate_size": 3072,
"num_decoder_attn_heads": 12,
"num_decoder_layers": 12,
"multi_channel_cross_attention": True,
# training params
"label_smoothing": 0.1,
"learning_rate": 0.05,
"learning_rate_warmup_steps": 20000,
"optimizer": "Adam",
"adam_beta1": 0.9,
"adam_beta2": 0.997,
"adam_epsilon": 1e-09,
# predict params
"beam_size": 5,
"alpha": 0.6,
"initializer_gain": 1.0,
"use_cache": True,
# input params
"passage_list": ["b", "c", "d", "e", "f"],
"input_sharding": False,
"input_data_not_padded": False,
"pad_token_id": 0,
"end_token_id": 102,
"start_token_id": 101,
"init_from_bert2bert": True,
}
class ConfigsTest(tf.test.TestCase):
def test_configs(self):
cfg = configs.BERT2BERTConfig()
cfg.validate()
self.assertEqual(cfg.as_dict(), BERT2BERT_CONFIG)
def test_nhnet_config(self):
cfg = configs.NHNetConfig()
cfg.validate()
self.assertEqual(cfg.as_dict(), NHNET_CONFIG)
if __name__ == "__main__":
tf.test.main()
| 3,116 | 24.760331 | 74 | py |
models | models-master/official/projects/nhnet/models.py | # Copyright 2023 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.
"""tf.keras Models for NHNet."""
from typing import Optional, Text
from absl import logging
import gin
import tensorflow as tf
from official.modeling import tf_utils
from official.modeling.hyperparams import params_dict
from official.nlp.modeling import networks
from official.nlp.modeling.layers import multi_channel_attention
from official.nlp.modeling.ops import beam_search
from official.projects.nhnet import configs
from official.projects.nhnet import decoder
from official.projects.nhnet import utils
def embedding_linear(embedding_matrix, x):
"""Uses embeddings as linear transformation weights."""
with tf.name_scope("presoftmax_linear"):
batch_size = tf.shape(x)[0]
length = tf.shape(x)[1]
hidden_size = tf.shape(x)[2]
vocab_size = tf.shape(embedding_matrix)[0]
x = tf.reshape(x, [-1, hidden_size])
logits = tf.matmul(x, embedding_matrix, transpose_b=True)
return tf.reshape(logits, [batch_size, length, vocab_size])
def _add_sos_to_seq(seq, start_token_id):
"""Add a start sequence token while keeping seq length."""
batch_size = tf.shape(seq)[0]
seq_len = tf.shape(seq)[1]
sos_ids = tf.ones([batch_size], tf.int32) * start_token_id
targets = tf.concat([tf.expand_dims(sos_ids, axis=1), seq], axis=1)
targets = targets[:, :-1]
tf.assert_equal(tf.shape(targets), (batch_size, seq_len))
return targets
def remove_sos_from_seq(seq, pad_token_id):
"""Remove the start sequence token while keeping seq length."""
batch_size, seq_len = tf_utils.get_shape_list(seq, expected_rank=2)
# remove <s>
targets = seq[:, 1:]
# pad
pad_ids = tf.ones([batch_size], tf.int32) * pad_token_id
targets = tf.concat([targets, tf.expand_dims(pad_ids, axis=1)], axis=1)
tf.assert_equal(tf.shape(targets), (batch_size, seq_len))
return targets
class Bert2Bert(tf.keras.Model):
"""Bert2Bert encoder decoder model for training."""
def __init__(self, params, bert_layer, decoder_layer, name=None):
super(Bert2Bert, self).__init__(name=name)
self.params = params
if not bert_layer.built:
raise ValueError("bert_layer should be built.")
if not decoder_layer.built:
raise ValueError("decoder_layer should be built.")
self.bert_layer = bert_layer
self.decoder_layer = decoder_layer
def get_config(self):
return {"params": self.params.as_dict()}
def get_decode_logits(self,
decoder_inputs,
ids,
decoder_self_attention_bias,
step,
cache=None):
if cache:
if self.params.get("padded_decode", False):
bias_shape = decoder_self_attention_bias.shape.as_list()
self_attention_bias = tf.slice(
decoder_self_attention_bias, [0, 0, step, 0],
[bias_shape[0], bias_shape[1], 1, bias_shape[3]])
else:
self_attention_bias = decoder_self_attention_bias[:, :, step:step +
1, :step + 1]
# Sets decoder input to the last generated IDs.
decoder_input = ids[:, -1:]
else:
self_attention_bias = decoder_self_attention_bias[:, :, :step + 1, :step +
1]
decoder_input = ids
decoder_inputs["target_ids"] = decoder_input
decoder_inputs["self_attention_bias"] = self_attention_bias
if cache:
decoder_outputs = self.decoder_layer(
decoder_inputs,
cache,
decode_loop_step=step,
padded_decode=self.params.get("padded_decode", False))
else:
decoder_outputs = self.decoder_layer(decoder_inputs)
logits = embedding_linear(self.decoder_layer.embedding_lookup.embeddings,
decoder_outputs[:, -1:, :])
logits = tf.squeeze(logits, axis=[1])
return logits
def _get_symbols_to_logits_fn(self, max_decode_length):
"""Returns a decoding function that calculates logits of the next tokens."""
# Max decode length should be smaller than the positional embedding max
# sequence length.
decoder_self_attention_bias = decoder.get_attention_bias(
input_tensor=None,
bias_type="decoder_self",
max_length=max_decode_length)
def _symbols_to_logits_fn(ids, i, cache):
"""Generate logits for next candidate IDs.
Args:
ids: Current decoded sequences. int tensor with shape [batch_size *
beam_size, i + 1]
i: Loop index
cache: dictionary of values storing the encoder output, encoder-decoder
attention bias, and previous decoder attention values.
Returns:
Tuple of
(logits with shape [batch_size * beam_size, vocab_size],
updated cache values)
"""
decoder_inputs = dict(
all_encoder_outputs=cache["all_encoder_outputs"],
attention_bias=cache["attention_bias"])
logits = self.get_decode_logits(
decoder_inputs,
ids,
decoder_self_attention_bias,
step=i,
cache=cache if self.params.use_cache else None)
return logits, cache
return _symbols_to_logits_fn
def train_decode(self, decode_outputs):
logits = embedding_linear(self.decoder_layer.embedding_lookup.embeddings,
decode_outputs)
decode_output_ids = tf.cast(tf.argmax(logits, axis=-1), tf.int32)
output_log_probs = tf.nn.log_softmax(logits, axis=-1)
return logits, decode_output_ids, output_log_probs
def predict_decode(self, start_token_ids, cache):
symbols_to_logits_fn = self._get_symbols_to_logits_fn(self.params.len_title)
# Use beam search to find the top beam_size sequences and scores.
decoded_ids, scores = beam_search.sequence_beam_search(
symbols_to_logits_fn=symbols_to_logits_fn,
initial_ids=start_token_ids,
initial_cache=cache,
vocab_size=self.params.vocab_size,
beam_size=self.params.beam_size,
alpha=self.params.alpha,
max_decode_length=self.params.len_title,
padded_decode=self.params.get("padded_decode", False),
eos_id=self.params.end_token_id)
return decoded_ids, scores
def _get_logits_for_decode_ids(self, decoder_inputs, top_decoded_ids):
"""Returns the log probabilities for ids."""
target_ids = _add_sos_to_seq(top_decoded_ids, self.params.start_token_id)
decoder_inputs["self_attention_bias"] = decoder.get_attention_bias(
target_ids, bias_type="decoder_self")
decoder_inputs["target_ids"] = target_ids
decoder_outputs = self.decoder_layer(decoder_inputs)
logits = embedding_linear(self.decoder_layer.embedding_lookup.embeddings,
decoder_outputs)
return logits
def _init_cache(self, batch_size):
num_heads = self.params.num_decoder_attn_heads
dim_per_head = self.params.hidden_size // num_heads
init_decode_length = (
self.params.len_title if self.params.get("padded_decode", False) else 0)
cache = {}
for layer in range(self.params.num_decoder_layers):
cache[str(layer)] = {
"key":
tf.zeros(
[batch_size, init_decode_length, num_heads, dim_per_head],
dtype=tf.float32),
"value":
tf.zeros(
[batch_size, init_decode_length, num_heads, dim_per_head],
dtype=tf.float32)
}
return cache
def call(self, inputs, mode="train"):
"""Implements call().
Args:
inputs: a dictionary of tensors.
mode: string, an enum for mode, train/eval.
Returns:
logits, decode_output_ids, output_log_probs for training. top_decoded_ids
for eval.
"""
input_ids = inputs["input_ids"]
input_mask = inputs["input_mask"]
segment_ids = inputs["segment_ids"]
all_encoder_outputs, _ = self.bert_layer(
[input_ids, input_mask, segment_ids])
if mode not in ("train", "eval", "predict"):
raise ValueError("Invalid call mode: %s" % mode)
encoder_decoder_attention_bias = decoder.get_attention_bias(
input_ids,
bias_type="single_cross",
padding_value=self.params.pad_token_id)
if mode == "train":
self_attention_bias = decoder.get_attention_bias(
inputs["target_ids"], bias_type="decoder_self")
decoder_inputs = dict(
attention_bias=encoder_decoder_attention_bias,
all_encoder_outputs=all_encoder_outputs,
target_ids=inputs["target_ids"],
self_attention_bias=self_attention_bias)
decoder_outputs = self.decoder_layer(decoder_inputs)
return self.train_decode(decoder_outputs)
batch_size = tf.shape(input_ids)[0]
start_token_ids = tf.ones([batch_size],
tf.int32) * self.params.start_token_id
# Add encoder output and attention bias to the cache.
if self.params.use_cache:
cache = self._init_cache(batch_size)
else:
cache = {}
cache["all_encoder_outputs"] = all_encoder_outputs
cache["attention_bias"] = encoder_decoder_attention_bias
decoded_ids, scores = self.predict_decode(start_token_ids, cache)
if mode == "predict":
return decoded_ids[:, :self.params.beam_size,
1:], scores[:, :self.params.beam_size]
decoder_inputs = dict(
attention_bias=encoder_decoder_attention_bias,
all_encoder_outputs=all_encoder_outputs)
top_decoded_ids = decoded_ids[:, 0, 1:]
return self._get_logits_for_decode_ids(decoder_inputs, top_decoded_ids)
class NHNet(Bert2Bert):
"""NHNet model which performs multi-doc decoding."""
def __init__(self, params, bert_layer, decoder_layer, name=None):
super(NHNet, self).__init__(params, bert_layer, decoder_layer, name=name)
self.doc_attention = multi_channel_attention.VotingAttention(
num_heads=params.num_decoder_attn_heads,
head_size=params.hidden_size // params.num_decoder_attn_heads)
def _expand_doc_attention_probs(self, doc_attention_probs, target_length):
"""Expands doc attention probs to fit the decoding sequence length."""
doc_attention_probs = tf.expand_dims(
doc_attention_probs, axis=[1]) # [B, 1, A]
doc_attention_probs = tf.expand_dims(
doc_attention_probs, axis=[2]) # [B, 1, 1, A]
return tf.tile(doc_attention_probs,
[1, self.params.num_decoder_attn_heads, target_length, 1])
def _get_symbols_to_logits_fn(self, max_decode_length):
"""Returns a decoding function that calculates logits of the next tokens."""
# Max decode length should be smaller than the positional embedding max
# sequence length.
decoder_self_attention_bias = decoder.get_attention_bias(
input_tensor=None,
bias_type="decoder_self",
max_length=max_decode_length)
def _symbols_to_logits_fn(ids, i, cache):
"""Generate logits for next candidate IDs."""
if self.params.use_cache:
target_length = 1
else:
target_length = i + 1
decoder_inputs = dict(
doc_attention_probs=self._expand_doc_attention_probs(
cache["doc_attention_probs"], target_length),
all_encoder_outputs=cache["all_encoder_outputs"],
attention_bias=cache["attention_bias"])
logits = self.get_decode_logits(
decoder_inputs,
ids,
decoder_self_attention_bias,
step=i,
cache=cache if self.params.use_cache else None)
return logits, cache
return _symbols_to_logits_fn
def call(self, inputs, mode="training"): # pytype: disable=signature-mismatch # overriding-default-value-checks
input_shape = tf_utils.get_shape_list(inputs["input_ids"], expected_rank=3)
batch_size, num_docs, len_passage = (input_shape[0], input_shape[1],
input_shape[2])
input_ids = tf.reshape(inputs["input_ids"], [-1, len_passage])
input_mask = tf.reshape(inputs["input_mask"], [-1, len_passage])
segment_ids = tf.reshape(inputs["segment_ids"], [-1, len_passage])
all_encoder_outputs, _ = self.bert_layer(
[input_ids, input_mask, segment_ids])
encoder_outputs = tf.reshape(
all_encoder_outputs[-1],
[batch_size, num_docs, len_passage, self.params.hidden_size])
doc_attention_mask = tf.reshape(
tf.cast(
tf.math.count_nonzero(input_mask, axis=1, dtype=tf.int32) > 2,
tf.int32), [batch_size, num_docs])
doc_attention_probs = self.doc_attention(encoder_outputs,
doc_attention_mask)
encoder_decoder_attention_bias = decoder.get_attention_bias(
inputs["input_ids"],
bias_type="multi_cross",
padding_value=self.params.pad_token_id)
if mode == "train":
target_length = tf_utils.get_shape_list(
inputs["target_ids"], expected_rank=2)[1]
doc_attention_probs = self._expand_doc_attention_probs(
doc_attention_probs, target_length)
self_attention_bias = decoder.get_attention_bias(
inputs["target_ids"], bias_type="decoder_self")
decoder_inputs = dict(
attention_bias=encoder_decoder_attention_bias,
self_attention_bias=self_attention_bias,
target_ids=inputs["target_ids"],
all_encoder_outputs=encoder_outputs,
doc_attention_probs=doc_attention_probs)
decoder_outputs = self.decoder_layer(decoder_inputs)
return self.train_decode(decoder_outputs)
# Adds encoder output and attention bias to the cache.
if self.params.use_cache:
cache = self._init_cache(batch_size)
else:
cache = {}
cache["all_encoder_outputs"] = [encoder_outputs]
cache["attention_bias"] = encoder_decoder_attention_bias
cache["doc_attention_probs"] = doc_attention_probs
start_token_ids = tf.ones([batch_size],
tf.int32) * self.params.start_token_id
decoded_ids, scores = self.predict_decode(start_token_ids, cache)
if mode == "predict":
return decoded_ids[:, :self.params.beam_size,
1:], scores[:, :self.params.beam_size]
top_decoded_ids = decoded_ids[:, 0, 1:]
target_length = tf_utils.get_shape_list(top_decoded_ids)[-1]
decoder_inputs = dict(
attention_bias=encoder_decoder_attention_bias,
all_encoder_outputs=[encoder_outputs],
doc_attention_probs=self._expand_doc_attention_probs(
doc_attention_probs, target_length))
return self._get_logits_for_decode_ids(decoder_inputs, top_decoded_ids)
def get_bert2bert_layers(params: configs.BERT2BERTConfig):
"""Creates a Bert2Bert stem model and returns Bert encoder/decoder.
We use funtional-style to create stem model because we need to make all layers
built to restore variables in a customized way. The layers are called with
placeholder inputs to make them fully built.
Args:
params: ParamsDict.
Returns:
two keras Layers, bert_model_layer and decoder_layer
"""
input_ids = tf.keras.layers.Input(
shape=(None,), name="input_ids", dtype=tf.int32)
input_mask = tf.keras.layers.Input(
shape=(None,), name="input_mask", dtype=tf.int32)
segment_ids = tf.keras.layers.Input(
shape=(None,), name="segment_ids", dtype=tf.int32)
target_ids = tf.keras.layers.Input(
shape=(None,), name="target_ids", dtype=tf.int32)
bert_config = utils.get_bert_config_from_params(params)
bert_model_layer = networks.BertEncoder(
vocab_size=bert_config.vocab_size,
hidden_size=bert_config.hidden_size,
num_layers=bert_config.num_hidden_layers,
num_attention_heads=bert_config.num_attention_heads,
intermediate_size=bert_config.intermediate_size,
activation=tf_utils.get_activation(bert_config.hidden_act),
dropout_rate=bert_config.hidden_dropout_prob,
attention_dropout_rate=bert_config.attention_probs_dropout_prob,
max_sequence_length=bert_config.max_position_embeddings,
type_vocab_size=bert_config.type_vocab_size,
initializer=tf.keras.initializers.TruncatedNormal(
stddev=bert_config.initializer_range),
return_all_encoder_outputs=True,
name="bert_encoder")
all_encoder_outputs, _ = bert_model_layer(
[input_ids, input_mask, segment_ids])
# pylint: disable=protected-access
decoder_layer = decoder.Decoder(params, bert_model_layer._embedding_layer)
# pylint: enable=protected-access
cross_attention_bias = decoder.AttentionBias(bias_type="single_cross")(
input_ids)
self_attention_bias = decoder.AttentionBias(bias_type="decoder_self")(
target_ids)
decoder_inputs = dict(
attention_bias=cross_attention_bias,
self_attention_bias=self_attention_bias,
target_ids=target_ids,
all_encoder_outputs=all_encoder_outputs)
_ = decoder_layer(decoder_inputs)
return bert_model_layer, decoder_layer
def get_nhnet_layers(params: configs.NHNetConfig):
"""Creates a Mult-doc encoder/decoder.
Args:
params: ParamsDict.
Returns:
two keras Layers, bert_model_layer and decoder_layer
"""
input_ids = tf.keras.layers.Input(
shape=(None,), name="input_ids", dtype=tf.int32)
input_mask = tf.keras.layers.Input(
shape=(None,), name="input_mask", dtype=tf.int32)
segment_ids = tf.keras.layers.Input(
shape=(None,), name="segment_ids", dtype=tf.int32)
bert_config = utils.get_bert_config_from_params(params)
bert_model_layer = networks.BertEncoder(
vocab_size=bert_config.vocab_size,
hidden_size=bert_config.hidden_size,
num_layers=bert_config.num_hidden_layers,
num_attention_heads=bert_config.num_attention_heads,
intermediate_size=bert_config.intermediate_size,
activation=tf_utils.get_activation(bert_config.hidden_act),
dropout_rate=bert_config.hidden_dropout_prob,
attention_dropout_rate=bert_config.attention_probs_dropout_prob,
max_sequence_length=bert_config.max_position_embeddings,
type_vocab_size=bert_config.type_vocab_size,
initializer=tf.keras.initializers.TruncatedNormal(
stddev=bert_config.initializer_range),
return_all_encoder_outputs=True,
name="bert_encoder")
bert_model_layer([input_ids, input_mask, segment_ids])
input_ids = tf.keras.layers.Input(
shape=(None, None), name="input_ids", dtype=tf.int32)
all_encoder_outputs = tf.keras.layers.Input((None, None, params.hidden_size),
dtype=tf.float32)
target_ids = tf.keras.layers.Input(
shape=(None,), name="target_ids", dtype=tf.int32)
doc_attention_probs = tf.keras.layers.Input(
(params.num_decoder_attn_heads, None, None), dtype=tf.float32)
# pylint: disable=protected-access
decoder_layer = decoder.Decoder(params, bert_model_layer._embedding_layer)
# pylint: enable=protected-access
cross_attention_bias = decoder.AttentionBias(bias_type="multi_cross")(
input_ids)
self_attention_bias = decoder.AttentionBias(bias_type="decoder_self")(
target_ids)
decoder_inputs = dict(
attention_bias=cross_attention_bias,
self_attention_bias=self_attention_bias,
target_ids=target_ids,
all_encoder_outputs=all_encoder_outputs,
doc_attention_probs=doc_attention_probs)
_ = decoder_layer(decoder_inputs)
return bert_model_layer, decoder_layer
def create_transformer_model(params,
init_checkpoint: Optional[Text] = None
) -> tf.keras.Model:
"""A helper to create Transformer model."""
bert_layer, decoder_layer = get_bert2bert_layers(params=params)
model = Bert2Bert(
params=params,
bert_layer=bert_layer,
decoder_layer=decoder_layer,
name="transformer")
if init_checkpoint:
logging.info(
"Checkpoint file %s found and restoring from "
"initial checkpoint.", init_checkpoint)
ckpt = tf.train.Checkpoint(model=model)
ckpt.restore(init_checkpoint).expect_partial()
return model
def create_bert2bert_model(
params: configs.BERT2BERTConfig,
cls=Bert2Bert,
init_checkpoint: Optional[Text] = None) -> tf.keras.Model:
"""A helper to create Bert2Bert model."""
bert_layer, decoder_layer = get_bert2bert_layers(params=params)
if init_checkpoint:
utils.initialize_bert2bert_from_pretrained_bert(bert_layer, decoder_layer,
init_checkpoint)
return cls(
params=params,
bert_layer=bert_layer,
decoder_layer=decoder_layer,
name="bert2bert")
def create_nhnet_model(
params: configs.NHNetConfig,
cls=NHNet,
init_checkpoint: Optional[Text] = None) -> tf.keras.Model:
"""A helper to create NHNet model."""
bert_layer, decoder_layer = get_nhnet_layers(params=params)
model = cls(
params=params,
bert_layer=bert_layer,
decoder_layer=decoder_layer,
name="nhnet")
if init_checkpoint:
logging.info(
"Checkpoint file %s found and restoring from "
"initial checkpoint.", init_checkpoint)
if params.init_from_bert2bert:
ckpt = tf.train.Checkpoint(model=model)
ckpt.restore(init_checkpoint).assert_existing_objects_matched()
else:
utils.initialize_bert2bert_from_pretrained_bert(bert_layer, decoder_layer,
init_checkpoint)
return model
@gin.configurable
def get_model_params(model: Optional[Text] = "bert2bert",
config_class=None) -> params_dict.ParamsDict:
"""Helper function to convert config file to ParamsDict."""
if model == "bert2bert":
return configs.BERT2BERTConfig()
elif model == "nhnet":
return configs.NHNetConfig()
elif config_class:
return config_class()
else:
raise KeyError("The model type is not defined: %s" % model)
@gin.configurable
def create_model(model_type: Text,
params,
init_checkpoint: Optional[Text] = None):
"""A factory function to create different types of models."""
if model_type == "bert2bert":
return create_bert2bert_model(params, init_checkpoint=init_checkpoint)
elif model_type == "nhnet":
return create_nhnet_model(params, init_checkpoint=init_checkpoint)
elif "transformer" in model_type:
return create_transformer_model(params, init_checkpoint=init_checkpoint)
else:
raise KeyError("The model type is not defined: %s" % model_type)
| 23,129 | 38.674099 | 115 | py |
models | models-master/official/projects/nhnet/raw_data_process.py | # Copyright 2023 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.
"""Processes crawled content from news URLs by generating tfrecords."""
import os
from absl import app
from absl import flags
from official.projects.nhnet import raw_data_processor
FLAGS = flags.FLAGS
flags.DEFINE_string("crawled_articles", "/tmp/nhnet/",
"Folder path to the crawled articles using news-please.")
flags.DEFINE_string("vocab", None, "Filepath of the BERT vocabulary.")
flags.DEFINE_bool("do_lower_case", True,
"Whether the vocabulary is uncased or not.")
flags.DEFINE_integer("len_title", 15,
"Maximum number of tokens in story headline.")
flags.DEFINE_integer("len_passage", 200,
"Maximum number of tokens in article passage.")
flags.DEFINE_integer("max_num_articles", 5,
"Maximum number of articles in a story.")
flags.DEFINE_bool("include_article_title_in_passage", False,
"Whether to include article title in article passage.")
flags.DEFINE_string("data_folder", None,
"Folder path to the downloaded data folder (output).")
flags.DEFINE_integer("num_tfrecords_shards", 20,
"Number of shards for train/valid/test.")
def transform_as_tfrecords(data_processor, filename):
"""Transforms story from json to tfrecord (sharded).
Args:
data_processor: Instance of RawDataProcessor.
filename: 'train', 'valid', or 'test'.
"""
print("Transforming json to tfrecord for %s..." % filename)
story_filepath = os.path.join(FLAGS.data_folder, filename + ".json")
output_folder = os.path.join(FLAGS.data_folder, "processed")
os.makedirs(output_folder, exist_ok=True)
output_filepaths = []
for i in range(FLAGS.num_tfrecords_shards):
output_filepaths.append(
os.path.join(
output_folder, "%s.tfrecord-%.5d-of-%.5d" %
(filename, i, FLAGS.num_tfrecords_shards)))
(total_num_examples,
generated_num_examples) = data_processor.generate_examples(
story_filepath, output_filepaths)
print("For %s, %d examples have been generated from %d stories in json." %
(filename, generated_num_examples, total_num_examples))
def main(_):
if not FLAGS.data_folder:
raise ValueError("data_folder must be set as the downloaded folder path.")
if not FLAGS.vocab:
raise ValueError("vocab must be set as the filepath of BERT vocabulary.")
data_processor = raw_data_processor.RawDataProcessor(
vocab=FLAGS.vocab,
do_lower_case=FLAGS.do_lower_case,
len_title=FLAGS.len_title,
len_passage=FLAGS.len_passage,
max_num_articles=FLAGS.max_num_articles,
include_article_title_in_passage=FLAGS.include_article_title_in_passage,
include_text_snippet_in_example=True)
print("Loading crawled articles...")
num_articles = data_processor.read_crawled_articles(FLAGS.crawled_articles)
print("Total number of articles loaded: %d" % num_articles)
print()
transform_as_tfrecords(data_processor, "train")
transform_as_tfrecords(data_processor, "valid")
transform_as_tfrecords(data_processor, "test")
if __name__ == "__main__":
app.run(main)
| 3,735 | 39.608696 | 78 | py |
models | models-master/official/projects/nhnet/__init__.py | # Copyright 2023 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.
| 609 | 39.666667 | 74 | py |
models | models-master/official/projects/nhnet/evaluation.py | # Copyright 2023 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.
"""Evaluation for Bert2Bert."""
import os
# Import libraries
from absl import logging
import numpy as np
import tensorflow as tf
from official.legacy.transformer import metrics as metrics_v2
from official.legacy.transformer.utils import metrics
from official.projects.nhnet import input_pipeline
from official.projects.nhnet import models
def rouge_l_fscore(logits, labels):
"""ROUGE scores computation between labels and predictions.
This is an approximate ROUGE scoring method since we do not glue word pieces
or decode the ids and tokenize the output.
Args:
logits: tensor, model predictions
labels: tensor, gold output.
Returns:
rouge_l_fscore: approx rouge-l f1 score.
"""
predictions = np.argmax(logits, axis=-1)
rouge_l_f_score = metrics.rouge_l_sentence_level(predictions, labels)
return rouge_l_f_score
def rouge_2_fscore(logits, labels):
"""ROUGE-2 F1 score computation between labels and predictions.
This is an approximate ROUGE scoring method since we do not glue word pieces
or decode the ids and tokenize the output.
Args:
logits: tensor, model predictions
labels: tensor, gold output.
Returns:
rouge2_fscore: approx rouge-2 f1 score.
"""
predictions = np.argmax(logits, axis=-1)
rouge_2_f_score = metrics.rouge_n(predictions, labels)
return rouge_2_f_score
def bleu_score(logits, labels):
"""Approximate BLEU score computation between labels and predictions.
An approximate BLEU scoring method since we do not glue word pieces or
decode the ids and tokenize the output. By default, we use ngram order of 4
and use brevity penalty. Also, this does not have beam search.
Args:
logits: Tensor of size [batch_size, length_logits, vocab_size]
labels: Tensor of size [batch-size, length_labels]
Returns:
bleu: int, approx bleu score
"""
predictions = np.argmax(logits, axis=-1)
bleu = metrics.compute_bleu(labels, predictions)
return bleu
def continuous_eval(strategy,
params,
model_type,
eval_file_pattern=None,
batch_size=4,
eval_steps=None,
model_dir=None,
timeout=3000):
"""Continuously evaluate checkpoints on testing data."""
test_dataset = input_pipeline.get_input_dataset(
eval_file_pattern,
batch_size=batch_size,
params=params,
is_training=False,
strategy=strategy)
with strategy.scope():
model = models.create_model(model_type, params)
metric_layer = metrics_v2.MetricLayer(params.vocab_size)
eval_summary_writer = tf.summary.create_file_writer(
os.path.join(model_dir, "summaries/eval"))
global_step = tf.Variable(
0,
trainable=False,
dtype=tf.int64,
aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA,
shape=[])
@tf.function
def test_step(inputs):
"""Calculates evaluation metrics on distributed devices."""
def _test_step_fn(inputs):
"""Replicated accuracy calculation."""
targets = models.remove_sos_from_seq(inputs["target_ids"],
params.pad_token_id)
# Using ground truth sequences as targets to calculate logits for accuracy
# and perplexity metrics.
logits, _, _ = model(inputs, training=False, mode="train")
metric_layer([logits, targets])
# Get logits from top beam search results for bleu and rouge metrics.
logits = model(inputs, training=False, mode="eval")
return targets, logits
outputs = strategy.run(_test_step_fn, args=(inputs,))
return tf.nest.map_structure(strategy.experimental_local_results, outputs)
metrics_and_funcs = [
(tf.keras.metrics.Mean("bleu", dtype=tf.float32), bleu_score),
(tf.keras.metrics.Mean("rouge_2_fscore",
dtype=tf.float32), rouge_2_fscore),
(tf.keras.metrics.Mean("rouge_l_fscore",
dtype=tf.float32), rouge_l_fscore),
]
eval_results = {}
for latest_checkpoint in tf.train.checkpoints_iterator(
model_dir, timeout=timeout):
checkpoint = tf.train.Checkpoint(model=model, global_step=global_step)
checkpoint.restore(latest_checkpoint).expect_partial()
logging.info("Loaded checkpoint %s", latest_checkpoint)
for i, inputs in enumerate(test_dataset):
if eval_steps and i >= eval_steps:
break
outputs = test_step(inputs)
for metric, func in metrics_and_funcs:
for targets, logits in zip(outputs[0], outputs[1]):
metric.update_state(func(logits.numpy(), targets.numpy()))
with eval_summary_writer.as_default():
step = global_step.numpy()
for metric, _ in metrics_and_funcs:
eval_results[metric.name] = metric.result().numpy().astype(float)
tf.summary.scalar(
metric.name,
eval_results[metric.name],
step=step)
for metric in metric_layer.metrics:
eval_results[metric.name] = metric.result().numpy().astype(float)
tf.summary.scalar(
metric.name,
eval_results[metric.name],
step=step)
logging.info("Step %d Metrics= %s", step, str(eval_results))
eval_summary_writer.flush()
# Resets metrics.
for metric, _ in metrics_and_funcs:
metric.reset_states()
for metric in metric_layer.metrics:
metric.reset_states()
return eval_results
| 6,091 | 32.472527 | 80 | py |
models | models-master/official/projects/nhnet/trainer_test.py | # Copyright 2023 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.
"""Tests for official.projects.nhnet.trainer."""
import os
from absl import flags
from absl.testing import parameterized
import tensorflow as tf
# pylint: disable=g-direct-tensorflow-import
from tensorflow.python.distribute import combinations
from tensorflow.python.distribute import strategy_combinations
# pylint: enable=g-direct-tensorflow-import
from official.projects.nhnet import trainer
from official.projects.nhnet import utils
FLAGS = flags.FLAGS
trainer.define_flags()
def all_strategy_combinations():
return combinations.combine(
distribution=[
strategy_combinations.one_device_strategy,
strategy_combinations.one_device_strategy_gpu,
strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
strategy_combinations.cloud_tpu_strategy,
],)
def get_trivial_data(config) -> tf.data.Dataset:
"""Gets trivial data in the ImageNet size."""
batch_size, num_docs = 2, len(config.passage_list),
len_passage = config.len_passage
len_title = config.len_title
def generate_data(_) -> tf.data.Dataset:
fake_ids = tf.zeros((num_docs, len_passage), dtype=tf.int32)
title = tf.zeros((len_title), dtype=tf.int32)
return dict(
input_ids=fake_ids,
input_mask=fake_ids,
segment_ids=fake_ids,
target_ids=title)
dataset = tf.data.Dataset.range(1)
dataset = dataset.repeat()
dataset = dataset.map(
generate_data, num_parallel_calls=tf.data.experimental.AUTOTUNE)
dataset = dataset.prefetch(buffer_size=1).batch(batch_size)
return dataset
class TrainerTest(tf.test.TestCase, parameterized.TestCase):
def setUp(self):
super(TrainerTest, self).setUp()
self._config = utils.get_test_params()
self._config.override(
{
"vocab_size": 49911,
"max_position_embeddings": 200,
"len_title": 15,
"len_passage": 20,
"beam_size": 5,
"alpha": 0.6,
"learning_rate": 0.0,
"learning_rate_warmup_steps": 0,
"multi_channel_cross_attention": True,
"passage_list": ["a", "b"],
},
is_strict=False)
@combinations.generate(all_strategy_combinations())
def test_train(self, distribution):
FLAGS.train_steps = 10
FLAGS.checkpoint_interval = 5
FLAGS.model_dir = self.get_temp_dir()
FLAGS.model_type = "nhnet"
stats = trainer.train(self._config, distribution,
get_trivial_data(self._config))
self.assertIn("training_loss", stats)
self.assertLen(
tf.io.gfile.glob(os.path.join(FLAGS.model_dir, "ckpt*.index")), 2)
if __name__ == "__main__":
tf.test.main()
| 3,289 | 31.254902 | 74 | py |
models | models-master/official/projects/nhnet/configs.py | # Copyright 2023 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.
"""Common NHNet/Bert2Bert configuration."""
import dataclasses
from typing import List, Text
from official.modeling.hyperparams import base_config
@dataclasses.dataclass
class BERT2BERTConfig(base_config.Config):
"""High-level configurations for BERT2BERT model.
These include parameters that are not directly related to the experiment,
e.g. encoder, decoder, prediction, training, etc.
"""
vocab_size: int = 30522
hidden_size: int = 768
num_hidden_layers: int = 12
num_attention_heads: int = 12
intermediate_size: int = 3072
hidden_act: str = "gelu"
hidden_dropout_prob: float = 0.1
attention_probs_dropout_prob: float = 0.1
max_position_embeddings: int = 512
type_vocab_size: int = 2
initializer_range: float = 0.02
decoder_intermediate_size: int = 3072
num_decoder_attn_heads: int = 12
num_decoder_layers: int = 12
label_smoothing: float = 0.1
learning_rate: float = 0.05
learning_rate_warmup_steps: int = 20000
optimizer: str = "Adam"
adam_beta1: float = 0.9
adam_beta2: float = 0.997
adam_epsilon: float = 1e-09
# predict params
beam_size: int = 5
alpha: float = 0.6
initializer_gain: float = 1.0
use_cache: bool = True
# input params
input_sharding: bool = False
input_data_not_padded: bool = False
pad_token_id: int = 0
end_token_id: int = 102
start_token_id: int = 101
@dataclasses.dataclass
class NHNetConfig(BERT2BERTConfig):
"""High-level configurations for NHNet model.
These include parameters that are not directly related to the experiment,
e.g. encoder, decoder, prediction, training, etc.
"""
multi_channel_cross_attention: bool = True
passage_list: List[Text] = dataclasses.field(
default_factory=lambda: [chr(ord("b") + i) for i in range(5)])
# Initialization method.
# If init_from_bert2bert is false, we assume the checkpoint is from BERT
# pretraining and only encoder and self-attention variables are initialized.
init_from_bert2bert: bool = True
UNITTEST_CONFIG = {
"attention_probs_dropout_prob": 0.0,
"hidden_act": "gelu",
"hidden_dropout_prob": 0.0,
"hidden_size": 16,
"initializer_range": 0.02,
"intermediate_size": 32,
"max_position_embeddings": 128,
"num_attention_heads": 2,
"num_hidden_layers": 1,
"type_vocab_size": 2,
"vocab_size": 30522,
"initializer_gain": 1.0,
"decoder_intermediate_size": 32,
"num_decoder_attn_heads": 2,
"num_decoder_layers": 1,
"use_cache": True,
"input_data_not_padded": False,
"pad_token_id": 0,
"end_token_id": 102,
"start_token_id": 101,
}
| 3,202 | 29.216981 | 78 | py |
models | models-master/official/projects/nhnet/trainer.py | # Copyright 2023 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.
"""Run NHNet model training and eval."""
import os
# Import libraries
from absl import app
from absl import flags
from absl import logging
from six.moves import zip
import tensorflow as tf
from official.common import distribute_utils
from official.legacy.transformer import metrics as transformer_metrics
from official.modeling.hyperparams import params_dict
from official.projects.nhnet import evaluation
from official.projects.nhnet import input_pipeline
from official.projects.nhnet import models
from official.projects.nhnet import optimizer
from official.utils.misc import keras_utils
FLAGS = flags.FLAGS
def define_flags():
"""Defines command line flags used by NHNet trainer."""
## Required parameters
flags.DEFINE_enum("mode", "train", ["train", "eval", "train_and_eval"],
"Execution mode.")
flags.DEFINE_string("train_file_pattern", "", "Train file pattern.")
flags.DEFINE_string("eval_file_pattern", "", "Eval file pattern.")
flags.DEFINE_string(
"model_dir", None,
"The output directory where the model checkpoints will be written.")
# Model training specific flags.
flags.DEFINE_enum(
"distribution_strategy", "mirrored", ["tpu", "mirrored"],
"Distribution Strategy type to use for training. `tpu` uses TPUStrategy "
"for running on TPUs, `mirrored` uses GPUs with single host.")
flags.DEFINE_string("tpu", "", "TPU address to connect to.")
flags.DEFINE_string(
"init_checkpoint", None,
"Initial checkpoint (usually from a pre-trained BERT model).")
flags.DEFINE_integer("train_steps", 100000, "Max train steps")
flags.DEFINE_integer("eval_steps", 32, "Number of eval steps per run.")
flags.DEFINE_integer("eval_timeout", 3000, "Timeout waiting for checkpoints.")
flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.")
flags.DEFINE_integer("eval_batch_size", 4, "Total batch size for evaluation.")
flags.DEFINE_integer(
"steps_per_loop", 1000,
"Number of steps per graph-mode loop. Only training step "
"happens inside the loop.")
flags.DEFINE_integer("checkpoint_interval", 2000, "Checkpointing interval.")
flags.DEFINE_integer("len_title", 15, "Title length.")
flags.DEFINE_integer("len_passage", 200, "Passage length.")
flags.DEFINE_integer("num_encoder_layers", 12,
"Number of hidden layers of encoder.")
flags.DEFINE_integer("num_decoder_layers", 12,
"Number of hidden layers of decoder.")
flags.DEFINE_string("model_type", "nhnet",
"Model type to choose a model configuration.")
flags.DEFINE_integer(
"num_nhnet_articles", 5,
"Maximum number of articles in NHNet, only used when model_type=nhnet")
flags.DEFINE_string(
"params_override",
default=None,
help=("a YAML/JSON string or a YAML file which specifies additional "
"overrides over the default parameters"))
# Enables MLIR-based TF/XLA bridge. This is part of a soft rollout and will
# eventually be the Google-wide default.
flags.DEFINE_bool("enable_mlir_bridge", True,
"Use MLIR TF/XLA bridge (experimental).")
# pylint: disable=protected-access
class Trainer(tf.keras.Model):
"""A training only model."""
def __init__(self, model, params):
super(Trainer, self).__init__()
self.model = model
self.params = params
self._num_replicas_in_sync = tf.distribute.get_strategy(
).num_replicas_in_sync
def call(self, inputs, mode="train"):
return self.model(inputs, mode)
def train_step(self, inputs):
"""The logic for one training step."""
with tf.GradientTape() as tape:
logits, _, _ = self(inputs, mode="train", training=True)
targets = models.remove_sos_from_seq(inputs["target_ids"],
self.params.pad_token_id)
loss = transformer_metrics.transformer_loss(logits, targets,
self.params.label_smoothing,
self.params.vocab_size)
# Scales the loss, which results in using the average loss across all
# of the replicas for backprop.
scaled_loss = loss / self._num_replicas_in_sync
tvars = self.trainable_variables
grads = tape.gradient(scaled_loss, tvars)
self.optimizer.apply_gradients(list(zip(grads, tvars)))
if isinstance(self.optimizer, tf.keras.optimizers.experimental.Optimizer):
learning_rate = self.optimizer.learning_rate
else:
learning_rate = self.optimizer._decayed_lr(var_dtype=tf.float32)
return {
"training_loss": loss,
"learning_rate": learning_rate,
}
def train(params, strategy, dataset=None):
"""Runs training."""
if not dataset:
dataset = input_pipeline.get_input_dataset(
FLAGS.train_file_pattern,
FLAGS.train_batch_size,
params,
is_training=True,
strategy=strategy)
with strategy.scope():
model = models.create_model(
FLAGS.model_type, params, init_checkpoint=FLAGS.init_checkpoint)
opt = optimizer.create_optimizer(params)
trainer = Trainer(model, params)
trainer.compile(
optimizer=opt,
steps_per_execution=FLAGS.steps_per_loop)
summary_dir = os.path.join(FLAGS.model_dir, "summaries")
summary_callback = tf.keras.callbacks.TensorBoard(
summary_dir, update_freq=max(100, FLAGS.steps_per_loop))
checkpoint = tf.train.Checkpoint(
model=model, optimizer=opt, global_step=opt.iterations)
checkpoint_manager = tf.train.CheckpointManager(
checkpoint,
directory=FLAGS.model_dir,
max_to_keep=10,
step_counter=opt.iterations,
checkpoint_interval=FLAGS.checkpoint_interval)
if checkpoint_manager.restore_or_initialize():
logging.info("Training restored from the checkpoints in: %s",
FLAGS.model_dir)
checkpoint_callback = keras_utils.SimpleCheckpoint(checkpoint_manager)
# Trains the model.
steps_per_epoch = min(FLAGS.train_steps, FLAGS.checkpoint_interval)
epochs = FLAGS.train_steps // steps_per_epoch
history = trainer.fit(
x=dataset,
steps_per_epoch=steps_per_epoch,
epochs=epochs,
callbacks=[summary_callback, checkpoint_callback],
verbose=2)
train_hist = history.history
# Gets final loss from training.
stats = dict(training_loss=float(train_hist["training_loss"][-1]))
return stats
def run():
"""Runs NHNet using Keras APIs."""
if FLAGS.enable_mlir_bridge:
tf.config.experimental.enable_mlir_bridge()
strategy = distribute_utils.get_distribution_strategy(
distribution_strategy=FLAGS.distribution_strategy, tpu_address=FLAGS.tpu)
if strategy:
logging.info("***** Number of cores used : %d",
strategy.num_replicas_in_sync)
params = models.get_model_params(FLAGS.model_type)
params = params_dict.override_params_dict(
params, FLAGS.params_override, is_strict=True)
params.override(
{
"len_title":
FLAGS.len_title,
"len_passage":
FLAGS.len_passage,
"num_hidden_layers":
FLAGS.num_encoder_layers,
"num_decoder_layers":
FLAGS.num_decoder_layers,
"passage_list":
[chr(ord("b") + i) for i in range(FLAGS.num_nhnet_articles)],
},
is_strict=False)
stats = {}
if "train" in FLAGS.mode:
stats = train(params, strategy)
if "eval" in FLAGS.mode:
timeout = 0 if FLAGS.mode == "train_and_eval" else FLAGS.eval_timeout
# Uses padded decoding for TPU. Always uses cache.
padded_decode = isinstance(strategy, tf.distribute.TPUStrategy)
params.override({
"padded_decode": padded_decode,
}, is_strict=False)
stats = evaluation.continuous_eval(
strategy,
params,
model_type=FLAGS.model_type,
eval_file_pattern=FLAGS.eval_file_pattern,
batch_size=FLAGS.eval_batch_size,
eval_steps=FLAGS.eval_steps,
model_dir=FLAGS.model_dir,
timeout=timeout)
return stats
def main(_):
stats = run()
if stats:
logging.info("Stats:\n%s", stats)
if __name__ == "__main__":
define_flags()
app.run(main)
| 8,900 | 35.780992 | 80 | py |
models | models-master/official/projects/nhnet/input_pipeline.py | # Copyright 2023 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.
"""Input pipelines."""
import tensorflow as tf
def decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.io.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.cast(t, tf.int32)
example[name] = t
return example
def process_singledoc_dataset(dataset, batch_size, params):
"""Parses and batches single-doc dataset."""
name_to_features = {
"input_ids_a": tf.io.FixedLenFeature([params.len_title], tf.int64),
"input_ids_b": tf.io.FixedLenFeature([params.len_passage], tf.int64),
"input_mask_b": tf.io.FixedLenFeature([params.len_passage], tf.int64),
"segment_ids_b": tf.io.FixedLenFeature([params.len_passage], tf.int64),
}
decode_fn = lambda record: decode_record(record, name_to_features)
dataset = dataset.map(
decode_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)
def _select_data_from_record(record):
"""Filter out features to use for pretraining."""
return {
"input_ids": record["input_ids_b"],
"input_mask": record["input_mask_b"],
"segment_ids": record["segment_ids_b"],
"target_ids": record["input_ids_a"],
}
dataset = dataset.map(
_select_data_from_record,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
dataset = dataset.batch(batch_size, drop_remainder=True)
return dataset
def decode_sparse_record(record, name_to_features):
"""Decodes a sparse record to a TensorFlow example."""
example = tf.io.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.cast(t, tf.int32)
example[name] = tf.sparse.to_dense(t)
return example
def _filter_max_length(example, max_title_length=256):
"""Indicates whether the example's length is lower than the maximum length."""
return tf.size(example["targets"]) <= max_title_length
def process_singledoc_transformer_dataset(dataset, batch_size, params):
"""Parses, batches and pads single-doc dataset."""
name_to_features = {
"inputs": tf.io.VarLenFeature(tf.int64),
"targets": tf.io.VarLenFeature(tf.int64),
}
decode_fn = lambda record: decode_sparse_record(record, name_to_features)
dataset = dataset.map(
decode_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)
def _select_data_from_record(record):
"""Filter out features to use for pretraining."""
input_ids = record["inputs"][:params.len_passage]
target_ids = record["targets"]
input_mask = tf.ones_like(input_ids)
segment_ids = tf.zeros_like(input_ids)
return {
"input_ids": input_ids,
"input_mask": input_mask,
"segment_ids": segment_ids,
"target_ids": target_ids,
}
dataset = dataset.filter(lambda x: _filter_max_length(x, params.len_title))
dataset = dataset.map(
_select_data_from_record,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
dataset = dataset.padded_batch(
batch_size, {
"input_ids": [params.len_passage],
"input_mask": [params.len_passage],
"segment_ids": [params.len_passage],
"target_ids": [params.len_title],
},
padding_values={
"input_ids": params.pad_token_id,
"input_mask": 0,
"segment_ids": 0,
"target_ids": params.pad_token_id,
},
drop_remainder=True)
return dataset
def multidoc_parse_spec(params, training=True):
"""Gets the mutli-doc tf.Example parsing spec."""
len_p = params.len_passage
name_to_features = {}
feature_list = ["input_ids", "input_mask", "segment_ids"]
for idx in params.passage_list:
for feature in feature_list:
name_to_features["%s_%s" % (feature, idx)] = tf.io.FixedLenFeature(
[len_p], tf.int64)
if training:
# Cluster title.
name_to_features["input_ids_a"] = tf.io.FixedLenFeature([params.len_title],
tf.int64)
return name_to_features, feature_list
def process_multidoc_dataset(dataset, batch_size, params):
"""Parses, organizes and batches multi-doc dataset."""
name_to_features, feature_list = multidoc_parse_spec(params)
decode_fn = lambda record: decode_record(record, name_to_features)
dataset = dataset.map(
decode_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)
def _select_data_from_record(record):
"""Filter out features to use for pretraining."""
features = {"target_ids": record["input_ids_a"]}
for feature in feature_list:
tensors = [record["%s_%s" % (feature, i)] for i in params.passage_list]
features[feature] = tf.stack(tensors)
return features
dataset = dataset.map(
_select_data_from_record,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
dataset = dataset.batch(batch_size, drop_remainder=True)
return dataset
def create_dataset(file_paths,
batch_size,
params,
is_training=True,
input_pipeline_context=None):
"""Creates input dataset from (tf)records files for pretraining."""
dataset = tf.data.Dataset.list_files(file_paths, shuffle=is_training)
if input_pipeline_context and input_pipeline_context.num_input_pipelines > 1:
if not is_training or params.input_sharding:
dataset = dataset.shard(input_pipeline_context.num_input_pipelines,
input_pipeline_context.input_pipeline_id)
if is_training:
dataset = dataset.repeat()
# We set shuffle buffer to exactly match total number of
# training files to ensure that training data is well shuffled.
dataset = dataset.shuffle(len(file_paths))
# In parallel, create tf record dataset for each train files.
# cycle_length = 8 means that up to 8 files will be read and deserialized in
# parallel. You may want to increase this number if you have a large number of
# CPU cores.
dataset = dataset.interleave(
tf.data.TFRecordDataset,
cycle_length=8,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
if is_training:
dataset = dataset.shuffle(100)
if params.get("multi_channel_cross_attention", value=False):
dataset = process_multidoc_dataset(dataset, batch_size, params)
else:
if not params.input_data_not_padded:
dataset = process_singledoc_dataset(dataset, batch_size, params)
else:
dataset = process_singledoc_transformer_dataset(dataset, batch_size,
params)
dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE)
return dataset
def get_input_dataset(input_file_pattern,
batch_size,
params,
is_training,
strategy=None):
"""Returns input dataset from input file string."""
# When using TPU pods, we need to clone dataset across
# workers and need to pass in function that returns the dataset rather
# than passing dataset instance itself.
use_dataset_fn = isinstance(strategy, tf.distribute.TPUStrategy)
if use_dataset_fn:
if batch_size % strategy.num_replicas_in_sync != 0:
raise ValueError(
"Batch size must be divisible by number of replicas : {}".format(
strategy.num_replicas_in_sync))
# As auto rebatching is not supported in
# `distribute_datasets_from_function()` API, which is
# required when cloning dataset to multiple workers in eager mode,
# we use per-replica batch size.
batch_size = int(batch_size / strategy.num_replicas_in_sync)
def _dataset_fn(ctx=None):
"""Returns tf.data.Dataset for distributed BERT pretraining."""
input_files = []
for input_pattern in input_file_pattern.split(","):
input_files.extend(tf.io.gfile.glob(input_pattern))
return create_dataset(
input_files,
batch_size,
params,
is_training=is_training,
input_pipeline_context=ctx)
if use_dataset_fn:
return strategy.distribute_datasets_from_function(_dataset_fn)
else:
return strategy.experimental_distribute_dataset(_dataset_fn())
| 9,053 | 35.071713 | 80 | py |
models | models-master/official/projects/nhnet/optimizer.py | # Copyright 2023 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.
"""Optimizer and learning rate scheduler."""
import tensorflow as tf
from official.modeling.hyperparams import params_dict
class LearningRateSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):
"""Learning rate schedule."""
def __init__(self, initial_learning_rate, hidden_size, warmup_steps):
"""Initialize configuration of the learning rate schedule.
Args:
initial_learning_rate: A float, the initial learning rate.
hidden_size: An integer, the model dimension in the hidden layers.
warmup_steps: An integer, the number of steps required for linear warmup.
"""
super(LearningRateSchedule, self).__init__()
self.initial_learning_rate = initial_learning_rate
self.hidden_size = hidden_size
self.warmup_steps = tf.cast(warmup_steps, tf.float32)
def __call__(self, global_step):
"""Calculate learning rate with linear warmup and rsqrt decay.
Args:
global_step: An integer, the current global step used for learning rate
calculation.
Returns:
A float, the learning rate needs to be used for current global step.
"""
with tf.name_scope('learning_rate_schedule'):
global_step = tf.cast(global_step, tf.float32)
learning_rate = self.initial_learning_rate
learning_rate *= (self.hidden_size**-0.5)
# Apply linear warmup
learning_rate *= tf.minimum(1.0, global_step / self.warmup_steps)
# Apply rsqrt decay
learning_rate /= tf.sqrt(tf.maximum(global_step, self.warmup_steps))
return learning_rate
def get_config(self):
"""Get the configuration of the learning rate schedule."""
return {
'initial_learning_rate': self.initial_learning_rate,
'hidden_size': self.hidden_size,
'warmup_steps': self.warmup_steps,
}
def create_optimizer(params: params_dict.ParamsDict):
"""Creates optimizer."""
lr_schedule = LearningRateSchedule(params.learning_rate, params.hidden_size,
params.learning_rate_warmup_steps)
return tf.keras.optimizers.Adam(
learning_rate=lr_schedule,
beta_1=params.adam_beta1,
beta_2=params.adam_beta2,
epsilon=params.adam_epsilon)
| 2,809 | 35.973684 | 79 | py |
models | models-master/official/projects/fffner/fffner.py | # Copyright 2023 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.
"""The encoder used for FFFNER."""
import tensorflow as tf
from official.modeling import tf_utils
from official.modeling.hyperparams import base_config
from official.nlp.configs import encoders
from official.projects.fffner import fffner_encoder
FFFNerEncoderConfig = encoders.BertEncoderConfig
@base_config.bind(FFFNerEncoderConfig)
def get_encoder(encoder_cfg: FFFNerEncoderConfig):
"""Gets the FFNerEncoder from the configurations."""
encoder = fffner_encoder.FFFNerEncoder(
vocab_size=encoder_cfg.vocab_size,
hidden_size=encoder_cfg.hidden_size,
num_layers=encoder_cfg.num_layers,
num_attention_heads=encoder_cfg.num_attention_heads,
inner_dim=encoder_cfg.intermediate_size,
inner_activation=tf_utils.get_activation(encoder_cfg.hidden_activation),
output_dropout=encoder_cfg.dropout_rate,
attention_dropout=encoder_cfg.attention_dropout_rate,
max_sequence_length=encoder_cfg.max_position_embeddings,
type_vocab_size=encoder_cfg.type_vocab_size,
initializer=tf.keras.initializers.TruncatedNormal(
stddev=encoder_cfg.initializer_range),
output_range=encoder_cfg.output_range,
embedding_width=encoder_cfg.embedding_size,
norm_first=encoder_cfg.norm_first)
return encoder
| 1,885 | 40 | 78 | py |
models | models-master/official/projects/fffner/fffner_experiments.py | # Copyright 2023 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.
"""FFFNER experiment configurations."""
# pylint: disable=g-doc-return-or-yield,line-too-long
from official.core import config_definitions as cfg
from official.core import exp_factory
from official.modeling import optimization
from official.nlp.configs import encoders
from official.projects.fffner import fffner
from official.projects.fffner import fffner_dataloader
from official.projects.fffner import fffner_prediction
AdamWeightDecay = optimization.AdamWeightDecayConfig
PolynomialLr = optimization.PolynomialLrConfig
PolynomialWarmupConfig = optimization.PolynomialWarmupConfig
@exp_factory.register_config_factory('fffner/ner')
def fffner_ner() -> cfg.ExperimentConfig:
"""Defines fffner experiments."""
config = cfg.ExperimentConfig(
task=fffner_prediction.FFFNerPredictionConfig(
model=fffner_prediction.FFFNerModelConfig(
encoder=encoders.EncoderConfig(
type='any', any=fffner.FFFNerEncoderConfig())),
train_data=fffner_dataloader.FFFNerDataConfig(),
validation_data=fffner_dataloader.FFFNerDataConfig(
is_training=False, drop_remainder=False,
include_example_id=True)),
trainer=cfg.TrainerConfig(
optimizer_config=optimization.OptimizationConfig({
'optimizer': {
'type': 'adamw',
'adamw': {
'weight_decay_rate':
0.01,
'exclude_from_weight_decay':
['LayerNorm', 'layer_norm', 'bias'],
}
},
'learning_rate': {
'type': 'polynomial',
'polynomial': {
'initial_learning_rate': 2e-5,
'end_learning_rate': 0.0,
}
},
'warmup': {
'type': 'polynomial'
}
})),
restrictions=[
'task.train_data.is_training != None',
'task.validation_data.is_training != None'
])
return config
| 2,695 | 38.072464 | 74 | py |
models | models-master/official/projects/fffner/fffner_encoder.py | # Copyright 2023 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.
"""Transformer-based encoder network for FFFNER."""
# pylint: disable=g-classes-have-attributes
from typing import Any, Callable, Optional, Union
from absl import logging
import tensorflow as tf
from official.modeling import tf_utils
from official.nlp.modeling import layers
_Initializer = Union[str, tf.keras.initializers.Initializer]
_Activation = Union[str, Callable[..., Any]]
_approx_gelu = lambda x: tf.keras.activations.gelu(x, approximate=True)
class FFFNerEncoder(tf.keras.layers.Layer):
"""Transformer-based encoder network for FFFNER.
The main difference is that it takes in additional positional arguments and
returns last layer representations at those positions.
Args:
vocab_size: The size of the token vocabulary.
hidden_size: The size of the transformer hidden layers.
num_layers: The number of transformer layers.
num_attention_heads: The number of attention heads for each transformer. The
hidden size must be divisible by the number of attention heads.
max_sequence_length: The maximum sequence length that this encoder can
consume. This determines the variable shape for positional embeddings.
type_vocab_size: The number of types that the 'type_ids' input can take.
inner_dim: The output dimension of the first Dense layer in a two-layer
feedforward network for each transformer.
inner_activation: The activation for the first Dense layer in a two-layer
feedforward network for each transformer.
output_dropout: Dropout probability for the post-attention and output
dropout.
attention_dropout: The dropout rate to use for the attention layers within
the transformer layers.
initializer: The initialzer to use for all weights in this encoder.
output_range: The sequence output range, [0, output_range), by slicing the
target sequence of the last transformer layer. `None` means the entire
target sequence will attend to the source sequence, which yields the full
output.
embedding_width: The width of the word embeddings. If the embedding width is
not equal to hidden size, embedding parameters will be factorized into two
matrices in the shape of ['vocab_size', 'embedding_width'] and
['embedding_width', 'hidden_size'] ('embedding_width' is usually much
smaller than 'hidden_size').
embedding_layer: An optional Layer instance which will be called to generate
embeddings for the input word IDs.
norm_first: Whether to normalize inputs to attention and intermediate dense
layers. If set False, output of attention and intermediate dense layers is
normalized.
with_dense_inputs: Whether to accept dense embeddings as the input.
return_attention_scores: Whether to add an additional output containing the
attention scores of all transformer layers. This will be a list of length
`num_layers`, and each element will be in the shape [batch_size,
num_attention_heads, seq_dim, seq_dim].
"""
def __init__(
self,
vocab_size: int,
hidden_size: int = 768,
num_layers: int = 12,
num_attention_heads: int = 12,
max_sequence_length: int = 512,
type_vocab_size: int = 16,
inner_dim: int = 3072,
inner_activation: _Activation = _approx_gelu,
output_dropout: float = 0.1,
attention_dropout: float = 0.1,
initializer: _Initializer = tf.keras.initializers.TruncatedNormal(
stddev=0.02),
output_range: Optional[int] = None,
embedding_width: Optional[int] = None,
embedding_layer: Optional[tf.keras.layers.Layer] = None,
norm_first: bool = False,
with_dense_inputs: bool = False,
return_attention_scores: bool = False,
**kwargs):
if 'dict_outputs' in kwargs:
kwargs.pop('dict_outputs')
if 'return_all_encoder_outputs' in kwargs:
kwargs.pop('return_all_encoder_outputs')
if 'intermediate_size' in kwargs:
inner_dim = kwargs.pop('intermediate_size')
if 'activation' in kwargs:
inner_activation = kwargs.pop('activation')
if 'dropout_rate' in kwargs:
output_dropout = kwargs.pop('dropout_rate')
if 'attention_dropout_rate' in kwargs:
attention_dropout = kwargs.pop('attention_dropout_rate')
super().__init__(**kwargs)
self._output_range = output_range
activation = tf.keras.activations.get(inner_activation)
initializer = tf.keras.initializers.get(initializer)
if embedding_width is None:
embedding_width = hidden_size
if embedding_layer is None:
self._embedding_layer = layers.OnDeviceEmbedding(
vocab_size=vocab_size,
embedding_width=embedding_width,
initializer=tf_utils.clone_initializer(initializer),
name='word_embeddings')
else:
self._embedding_layer = embedding_layer
self._position_embedding_layer = layers.PositionEmbedding(
initializer=tf_utils.clone_initializer(initializer),
max_length=max_sequence_length,
name='position_embedding')
self._type_embedding_layer = layers.OnDeviceEmbedding(
vocab_size=type_vocab_size,
embedding_width=embedding_width,
initializer=tf_utils.clone_initializer(initializer),
use_one_hot=True,
name='type_embeddings')
self._embedding_norm_layer = tf.keras.layers.LayerNormalization(
name='embeddings/layer_norm', axis=-1, epsilon=1e-12, dtype=tf.float32)
self._embedding_dropout = tf.keras.layers.Dropout(
rate=output_dropout, name='embedding_dropout')
# We project the 'embedding' output to 'hidden_size' if it is not already
# 'hidden_size'.
self._embedding_projection = None
if embedding_width != hidden_size:
self._embedding_projection = tf.keras.layers.EinsumDense(
'...x,xy->...y',
output_shape=hidden_size,
bias_axes='y',
kernel_initializer=tf_utils.clone_initializer(initializer),
name='embedding_projection')
self._transformer_layers = []
self._attention_mask_layer = layers.SelfAttentionMask(
name='self_attention_mask')
self._num_layers = num_layers
for i in range(num_layers):
layer = layers.TransformerEncoderBlock(
num_attention_heads=num_attention_heads,
inner_dim=inner_dim,
inner_activation=inner_activation,
output_dropout=output_dropout,
attention_dropout=attention_dropout,
norm_first=norm_first,
return_attention_scores=return_attention_scores,
kernel_initializer=tf_utils.clone_initializer(initializer),
name='transformer/layer_%d' % i)
self._transformer_layers.append(layer)
self._pooler_layer_is_entity = tf.keras.layers.Dense(
units=hidden_size,
activation='tanh',
kernel_initializer=tf_utils.clone_initializer(initializer),
name='pooler_transform_is_entity')
self._pooler_layer_entity_type = tf.keras.layers.Dense(
units=hidden_size,
activation='tanh',
kernel_initializer=tf_utils.clone_initializer(initializer),
name='pooler_transform_entity_type')
self._config = {
'vocab_size': vocab_size,
'hidden_size': hidden_size,
'num_layers': num_layers,
'num_attention_heads': num_attention_heads,
'max_sequence_length': max_sequence_length,
'type_vocab_size': type_vocab_size,
'inner_dim': inner_dim,
'inner_activation': tf.keras.activations.serialize(activation),
'output_dropout': output_dropout,
'attention_dropout': attention_dropout,
'initializer': tf.keras.initializers.serialize(initializer),
'output_range': output_range,
'embedding_width': embedding_width,
'embedding_layer': embedding_layer,
'norm_first': norm_first,
'with_dense_inputs': with_dense_inputs,
'return_attention_scores': return_attention_scores,
}
if with_dense_inputs:
self.inputs = dict(
input_word_ids=tf.keras.Input(shape=(None,), dtype=tf.int32),
input_mask=tf.keras.Input(shape=(None,), dtype=tf.int32),
input_type_ids=tf.keras.Input(shape=(None,), dtype=tf.int32),
dense_inputs=tf.keras.Input(
shape=(None, embedding_width), dtype=tf.float32),
dense_mask=tf.keras.Input(shape=(None,), dtype=tf.int32),
dense_type_ids=tf.keras.Input(shape=(None,), dtype=tf.int32),
is_entity_token_pos=tf.keras.Input(shape=(None,), dtype=tf.int32),
entity_type_token_pos=tf.keras.Input(shape=(None,), dtype=tf.int32))
else:
self.inputs = dict(
input_word_ids=tf.keras.Input(shape=(None,), dtype=tf.int32),
input_mask=tf.keras.Input(shape=(None,), dtype=tf.int32),
input_type_ids=tf.keras.Input(shape=(None,), dtype=tf.int32),
is_entity_token_pos=tf.keras.Input(shape=(None,), dtype=tf.int32),
entity_type_token_pos=tf.keras.Input(shape=(None,), dtype=tf.int32))
def call(self, inputs):
word_embeddings = None
if isinstance(inputs, dict):
word_ids = inputs.get('input_word_ids')
mask = inputs.get('input_mask')
type_ids = inputs.get('input_type_ids')
word_embeddings = inputs.get('input_word_embeddings', None)
dense_inputs = inputs.get('dense_inputs', None)
dense_mask = inputs.get('dense_mask', None)
dense_type_ids = inputs.get('dense_type_ids', None)
is_entity_token_pos = inputs.get('is_entity_token_pos', None)
entity_type_token_pos = inputs.get('entity_type_token_pos', None)
else:
raise ValueError('Unexpected inputs type to %s.' % self.__class__)
if word_embeddings is None:
word_embeddings = self._embedding_layer(word_ids)
if dense_inputs is not None:
mask = tf.concat([mask, dense_mask], axis=1)
embeddings = self._get_embeddings(word_ids, type_ids, word_embeddings,
dense_inputs, dense_type_ids)
embeddings = self._embedding_norm_layer(embeddings)
embeddings = self._embedding_dropout(embeddings)
if self._embedding_projection is not None:
embeddings = self._embedding_projection(embeddings)
attention_mask = self._attention_mask_layer(embeddings, mask)
encoder_outputs = []
attention_outputs = []
x = embeddings
for i, layer in enumerate(self._transformer_layers):
transformer_output_range = None
if i == self._num_layers - 1:
transformer_output_range = self._output_range
x = layer([x, attention_mask], output_range=transformer_output_range)
if self._config['return_attention_scores']:
x, attention_scores = x
attention_outputs.append(attention_scores)
encoder_outputs.append(x)
last_encoder_output = encoder_outputs[-1]
encoder_output_is_entity = tf.gather(
last_encoder_output, indices=is_entity_token_pos, axis=1, batch_dims=1)
encoder_output_entity_type = tf.gather(
last_encoder_output,
indices=entity_type_token_pos,
axis=1,
batch_dims=1)
cls_output_is_entity = self._pooler_layer_is_entity(
encoder_output_is_entity)
cls_output_entity_type = self._pooler_layer_entity_type(
encoder_output_entity_type)
pooled_output = tf.concat([cls_output_is_entity, cls_output_entity_type], 1)
output = dict(
sequence_output=encoder_outputs[-1],
pooled_output=pooled_output,
encoder_outputs=encoder_outputs)
if self._config['return_attention_scores']:
output['attention_scores'] = attention_outputs
return output
def get_embedding_table(self):
return self._embedding_layer.embeddings
def get_embedding_layer(self):
return self._embedding_layer
def get_config(self):
return dict(self._config)
@property
def transformer_layers(self):
"""List of Transformer layers in the encoder."""
return self._transformer_layers
@property
def pooler_layer_is_entity(self):
"""The pooler dense layer for is entity classification after the transformer layers.
"""
return self._pooler_layer_is_entity
@property
def pooler_layer_entity_type(self):
"""The pooler dense layer for entity type classification after the transformer layers.
"""
return self._pooler_layer_entity_type
@classmethod
def from_config(cls, config, custom_objects=None):
if 'embedding_layer' in config and config['embedding_layer'] is not None:
warn_string = (
'You are reloading a model that was saved with a '
'potentially-shared embedding layer object. If you contine to '
'train this model, the embedding layer will no longer be shared. '
'To work around this, load the model outside of the Keras API.')
print('WARNING: ' + warn_string)
logging.warn(warn_string)
return cls(**config)
def _get_embeddings(self, word_ids: tf.Tensor, type_ids: tf.Tensor,
word_embeddings: Optional[tf.Tensor],
dense_inputs: Optional[tf.Tensor],
dense_type_ids: Optional[tf.Tensor]) -> tf.Tensor:
if word_embeddings is None:
word_embeddings = self._embedding_layer(word_ids)
if dense_inputs is not None:
# Concat the dense embeddings at sequence end.
word_embeddings = tf.concat([word_embeddings, dense_inputs], axis=1)
type_ids = tf.concat([type_ids, dense_type_ids], axis=1)
type_embeddings = self._type_embedding_layer(type_ids)
# absolute position embeddings.
position_embeddings = self._position_embedding_layer(word_embeddings)
return word_embeddings + position_embeddings + type_embeddings
| 14,353 | 40.365994 | 90 | py |
models | models-master/official/projects/fffner/fffner_dataloader.py | # Copyright 2023 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.
"""Loads dataset for the FFFNER task."""
import dataclasses
from typing import Mapping, Optional, Tuple
import tensorflow as tf
from official.common import dataset_fn
from official.core import config_definitions as cfg
from official.core import input_reader
from official.nlp.data import data_loader
from official.nlp.data import data_loader_factory
LABEL_TYPES_MAP = {'int': tf.int64, 'float': tf.float32}
@dataclasses.dataclass
class FFFNerDataConfig(cfg.DataConfig):
"""Data config for sentence prediction task (tasks/sentence_prediction)."""
input_path: str = ''
global_batch_size: int = 32
is_training: bool = True
seq_length: int = 128
label_type: str = 'int'
# Whether to include the example id number.
include_example_id: bool = False
label_field_is_entity: str = 'is_entity_label'
label_field_entity_type: str = 'entity_type_label'
# Maps the key in TfExample to feature name.
# E.g 'label_ids' to 'next_sentence_labels'
label_name: Optional[Tuple[str, str]] = None
# Either tfrecord, sstable, or recordio.
file_type: str = 'tfrecord'
@data_loader_factory.register_data_loader_cls(FFFNerDataConfig)
class FFFNerDataLoader(data_loader.DataLoader):
"""A class to load dataset for sentence prediction (classification) task."""
def __init__(self, params):
self._params = params
self._seq_length = params.seq_length
self._include_example_id = params.include_example_id
self._label_field_is_entity = params.label_field_is_entity
self._label_field_entity_type = params.label_field_entity_type
if params.label_name:
self._label_name_mapping = dict(
[params.label_name_is_entity, params.label_name_entity_type])
else:
self._label_name_mapping = dict()
def name_to_features_spec(self):
"""Defines features to decode. Subclass may override to append features."""
label_type = LABEL_TYPES_MAP[self._params.label_type]
name_to_features = {
'input_ids': tf.io.FixedLenFeature([self._seq_length], tf.int64),
'input_mask': tf.io.FixedLenFeature([self._seq_length], tf.int64),
'segment_ids': tf.io.FixedLenFeature([self._seq_length], tf.int64),
'is_entity_token_pos': tf.io.FixedLenFeature([1], tf.int64),
'entity_type_token_pos': tf.io.FixedLenFeature([1], tf.int64),
self._label_field_is_entity: tf.io.FixedLenFeature([], label_type),
self._label_field_entity_type: tf.io.FixedLenFeature([], label_type),
'sentence_id': tf.io.FixedLenFeature([1], tf.int64),
'span_start': tf.io.FixedLenFeature([1], tf.int64),
'span_end': tf.io.FixedLenFeature([1], tf.int64),
}
if self._include_example_id:
name_to_features['example_id'] = tf.io.FixedLenFeature([], tf.int64)
return name_to_features
def _decode(self, record: tf.Tensor):
"""Decodes a serialized tf.Example."""
example = tf.io.parse_single_example(record, self.name_to_features_spec())
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in example:
t = example[name]
if t.dtype == tf.int64:
t = tf.cast(t, tf.int32)
example[name] = t
return example
def _parse(self, record: Mapping[str, tf.Tensor]):
"""Parses raw tensors into a dict of tensors to be consumed by the model."""
key_mapping = {
'input_ids': 'input_word_ids',
'input_mask': 'input_mask',
'segment_ids': 'input_type_ids',
'is_entity_token_pos': 'is_entity_token_pos',
'entity_type_token_pos': 'entity_type_token_pos',
'is_entity_label': 'is_entity_label',
'entity_type_label': 'entity_type_label',
'sentence_id': 'sentence_id',
'span_start': 'span_start',
'span_end': 'span_end',
}
ret = {}
for record_key in record:
if record_key in key_mapping:
ret[key_mapping[record_key]] = record[record_key]
else:
ret[record_key] = record[record_key]
return ret
def load(self, input_context: Optional[tf.distribute.InputContext] = None):
"""Returns a tf.dataset.Dataset."""
reader = input_reader.InputReader(
dataset_fn=dataset_fn.pick_dataset_fn(self._params.file_type),
params=self._params,
decoder_fn=self._decode,
parser_fn=self._parse)
return reader.read(input_context)
| 4,985 | 37.353846 | 80 | py |
models | models-master/official/projects/fffner/fffner_prediction.py | # Copyright 2023 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.
"""FFFNER prediction task."""
import collections
import dataclasses
from absl import logging
import numpy as np
import tensorflow as tf
from official.core import base_task
from official.core import config_definitions as cfg
from official.core import task_factory
from official.modeling import tf_utils
from official.modeling.hyperparams import base_config
from official.nlp.configs import encoders
from official.nlp.data import data_loader_factory
from official.nlp.tasks import utils
from official.projects.fffner import fffner_classifier
METRIC_TYPES = frozenset(
['accuracy', 'matthews_corrcoef', 'pearson_spearman_corr'])
@dataclasses.dataclass
class FFFNerModelConfig(base_config.Config):
"""A classifier/regressor configuration."""
num_classes_is_entity: int = 0
num_classes_entity_type: int = 0
use_encoder_pooler: bool = True
encoder: encoders.EncoderConfig = dataclasses.field(
default_factory=encoders.EncoderConfig
)
@dataclasses.dataclass
class FFFNerPredictionConfig(cfg.TaskConfig):
"""The model config."""
# At most one of `init_checkpoint` and `hub_module_url` can
# be specified.
init_checkpoint: str = ''
init_cls_pooler: bool = False
hub_module_url: str = ''
metric_type: str = 'accuracy'
# Defines the concrete model config at instantiation time.
model: FFFNerModelConfig = dataclasses.field(
default_factory=FFFNerModelConfig
)
train_data: cfg.DataConfig = dataclasses.field(default_factory=cfg.DataConfig)
validation_data: cfg.DataConfig = dataclasses.field(
default_factory=cfg.DataConfig
)
@task_factory.register_task_cls(FFFNerPredictionConfig)
class FFFNerTask(base_task.Task):
"""Task object for FFFNer."""
def __init__(self, params: cfg.TaskConfig, logging_dir=None, name=None):
super().__init__(params, logging_dir, name=name)
if params.metric_type not in METRIC_TYPES:
raise ValueError('Invalid metric_type: {}'.format(params.metric_type))
self.metric_type = params.metric_type
self.label_field_is_entity = 'is_entity_label'
self.label_field_entity_type = 'entity_type_label'
def build_model(self):
if self.task_config.hub_module_url and self.task_config.init_checkpoint:
raise ValueError('At most one of `hub_module_url` and '
'`init_checkpoint` can be specified.')
if self.task_config.hub_module_url:
encoder_network = utils.get_encoder_from_hub(
self.task_config.hub_module_url)
else:
encoder_network = encoders.build_encoder(self.task_config.model.encoder)
encoder_cfg = self.task_config.model.encoder.get()
if self.task_config.model.encoder.type == 'xlnet':
assert False, 'Not supported yet'
else:
return fffner_classifier.FFFNerClassifier(
# encoder_network.inputs
network=encoder_network,
num_classes_is_entity=self.task_config.model.num_classes_is_entity,
num_classes_entity_type=self.task_config.model
.num_classes_entity_type,
initializer=tf.keras.initializers.TruncatedNormal(
stddev=encoder_cfg.initializer_range),
use_encoder_pooler=self.task_config.model.use_encoder_pooler)
def build_losses(self, labels, model_outputs, aux_losses=None) -> tf.Tensor:
label_ids_is_entity = labels[self.label_field_is_entity]
label_ids_entity_type = labels[self.label_field_entity_type]
loss_is_entity = tf.keras.losses.sparse_categorical_crossentropy(
label_ids_is_entity,
tf.cast(model_outputs[0], tf.float32),
from_logits=True)
loss_entity_type = tf.keras.losses.sparse_categorical_crossentropy(
label_ids_entity_type,
tf.cast(model_outputs[1], tf.float32),
from_logits=True)
loss = loss_is_entity + loss_entity_type
if aux_losses:
loss += tf.add_n(aux_losses)
return tf_utils.safe_mean(loss)
def build_inputs(self, params, input_context=None):
"""Returns tf.data.Dataset for sentence_prediction task."""
if params.input_path == 'dummy':
def dummy_data(_):
dummy_ids = tf.zeros((1, params.seq_length), dtype=tf.int32)
x = dict(
input_word_ids=dummy_ids,
input_mask=dummy_ids,
input_type_ids=dummy_ids,
is_entity_token_pos=tf.zeros((1, 1), dtype=tf.int32),
entity_type_token_pos=tf.ones((1, 1), dtype=tf.int32))
x[self.label_field_is_entity] = tf.zeros((1, 1), dtype=tf.int32)
x[self.label_field_entity_type] = tf.zeros((1, 1), dtype=tf.int32)
return x
dataset = tf.data.Dataset.range(1)
dataset = dataset.repeat()
dataset = dataset.map(
dummy_data, num_parallel_calls=tf.data.experimental.AUTOTUNE)
return dataset
return data_loader_factory.get_data_loader(params).load(input_context)
def build_metrics(self, training=None):
del training
metrics = [
tf.keras.metrics.SparseCategoricalAccuracy(
name='cls_accuracy_is_entity'),
tf.keras.metrics.SparseCategoricalAccuracy(
name='cls_accuracy_entity_type'),
]
return metrics
def process_metrics(self, metrics, labels, model_outputs):
for metric in metrics:
if metric.name == 'cls_accuracy_is_entity':
metric.update_state(labels[self.label_field_is_entity],
model_outputs[0])
if metric.name == 'cls_accuracy_entity_type':
metric.update_state(labels[self.label_field_entity_type],
model_outputs[1])
def process_compiled_metrics(self, compiled_metrics, labels, model_outputs):
compiled_metrics.update_state(labels[self.label_field_is_entity],
model_outputs[0])
compiled_metrics.update_state(labels[self.label_field_entity_type],
model_outputs[1])
def validation_step(self, inputs, model: tf.keras.Model, metrics=None):
features, labels = inputs, inputs
outputs = self.inference_step(features, model)
loss = self.build_losses(
labels=labels, model_outputs=outputs, aux_losses=model.losses)
logs = {self.loss: loss}
if metrics:
self.process_metrics(metrics, labels, outputs)
if model.compiled_metrics:
self.process_compiled_metrics(model.compiled_metrics, labels, outputs)
logs.update({m.name: m.result() for m in metrics or []})
logs.update({m.name: m.result() for m in model.metrics})
logs.update({
'sentence_prediction_is_entity': outputs[0],
'sentence_prediction_entity_type': outputs[1],
'labels_is_entity': labels[self.label_field_is_entity],
'labels_entity_type': labels[self.label_field_entity_type],
'id': labels['example_id'],
'sentence_id': labels['sentence_id'],
'span_start': labels['span_start'],
'span_end': labels['span_end']
})
return logs
def aggregate_logs(self, state=None, step_outputs=None):
if state is None:
state = {
'sentence_prediction_is_entity': [],
'sentence_prediction_entity_type': [],
'labels_is_entity': [],
'labels_entity_type': [],
'ids': [],
'sentence_id': [],
'span_start': [],
'span_end': []
}
state['sentence_prediction_is_entity'].append(
np.concatenate(
[v.numpy() for v in step_outputs['sentence_prediction_is_entity']],
axis=0))
state['sentence_prediction_entity_type'].append(
np.concatenate([
v.numpy() for v in step_outputs['sentence_prediction_entity_type']
],
axis=0))
state['labels_is_entity'].append(
np.concatenate([v.numpy() for v in step_outputs['labels_is_entity']],
axis=0))
state['labels_entity_type'].append(
np.concatenate([v.numpy() for v in step_outputs['labels_entity_type']],
axis=0))
state['ids'].append(
np.concatenate([v.numpy() for v in step_outputs['id']], axis=0))
state['sentence_id'].append(
np.concatenate([v.numpy() for v in step_outputs['sentence_id']],
axis=0))
state['span_start'].append(
np.concatenate([v.numpy() for v in step_outputs['span_start']], axis=0))
state['span_end'].append(
np.concatenate([v.numpy() for v in step_outputs['span_end']], axis=0))
return state
def reduce_aggregated_logs(self, aggregated_logs, global_step=None):
sentence_prediction_is_entity = np.concatenate(
aggregated_logs['sentence_prediction_is_entity'], axis=0)
sentence_prediction_is_entity = np.reshape(
sentence_prediction_is_entity,
(-1, self.task_config.model.num_classes_is_entity))
sentence_prediction_entity_type = np.concatenate(
aggregated_logs['sentence_prediction_entity_type'], axis=0)
sentence_prediction_entity_type = np.reshape(
sentence_prediction_entity_type,
(-1, self.task_config.model.num_classes_entity_type))
labels_is_entity = np.concatenate(
aggregated_logs['labels_is_entity'], axis=0)
labels_is_entity = np.reshape(labels_is_entity, -1)
labels_entity_type = np.concatenate(
aggregated_logs['labels_entity_type'], axis=0)
labels_entity_type = np.reshape(labels_entity_type, -1)
ids = np.concatenate(aggregated_logs['ids'], axis=0)
ids = np.reshape(ids, -1)
sentence_id = np.concatenate(aggregated_logs['sentence_id'], axis=0)
sentence_id = np.reshape(sentence_id, -1)
span_start = np.concatenate(aggregated_logs['span_start'], axis=0)
span_start = np.reshape(span_start, -1)
span_end = np.concatenate(aggregated_logs['span_end'], axis=0)
span_end = np.reshape(span_end, -1)
def resolve(length, spans, prediction_confidence):
used = [False] * length
spans = sorted(
spans,
key=lambda x: prediction_confidence[(x[0], x[1])],
reverse=True)
real_spans = []
for span_start, span_end, ent_type in spans:
fill = False
for s in range(span_start, span_end + 1):
if used[s]:
fill = True
break
if not fill:
real_spans.append((span_start, span_end, ent_type))
for s in range(span_start, span_end + 1):
used[s] = True
return real_spans
def get_p_r_f(truth, pred):
n_pred = len(pred)
n_truth = len(truth)
n_correct = len(set(pred) & set(truth))
precision = 1. * n_correct / n_pred if n_pred != 0 else 0.0
recall = 1. * n_correct / n_truth if n_truth != 0 else 0.0
f1 = 2 * precision * recall / (
precision + recall) if precision + recall != 0.0 else 0.0
return {
'n_pred': n_pred,
'n_truth': n_truth,
'n_correct': n_correct,
'precision': precision,
'recall': recall,
'f1': f1,
}
def softmax(x):
x = np.array(x)
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum(axis=0)
per_sid_results = collections.defaultdict(list)
for _, sent_id, sp_start, sp_end, is_entity_label, is_entity_logit, entity_type_label, entity_type_logit in zip(
ids, sentence_id, span_start, span_end, labels_is_entity,
sentence_prediction_is_entity, labels_entity_type,
sentence_prediction_entity_type):
if sent_id > 0:
per_sid_results[sent_id].append(
(sp_start, sp_end, is_entity_label, is_entity_logit,
entity_type_label, entity_type_logit))
ground_truth = []
prediction_is_entity = []
prediction_entity_type = []
for key in sorted(list(per_sid_results.keys())):
results = per_sid_results[key]
gt_entities = []
predictied_entities = []
prediction_confidence = {}
prediction_confidence_type = {}
length = 0
for span_start, span_end, ground_truth_span, prediction_span, ground_truth_type, prediction_type in results:
if ground_truth_span == 1:
gt_entities.append((span_start, span_end, ground_truth_type))
if prediction_span[1] > prediction_span[0]:
predictied_entities.append(
(span_start, span_end, np.argmax(prediction_type).item()))
prediction_confidence[(span_start,
span_end)] = max(softmax(prediction_span))
prediction_confidence_type[(span_start,
span_end)] = max(softmax(prediction_type))
length = max(length, span_end)
length += 1
ground_truth.extend([(key, *x) for x in gt_entities])
prediction_is_entity.extend([(key, *x) for x in predictied_entities])
resolved_predicted = resolve(length, predictied_entities,
prediction_confidence)
prediction_entity_type.extend([(key, *x) for x in resolved_predicted])
raw = get_p_r_f(ground_truth, prediction_is_entity)
resolved = get_p_r_f(ground_truth, prediction_entity_type)
return {
'raw_f1': raw['f1'],
'raw_precision': raw['precision'],
'raw_recall': raw['recall'],
'resolved_f1': resolved['f1'],
'resolved_precision': resolved['precision'],
'resolved_recall': resolved['recall'],
'overall_f1': raw['f1'] + resolved['f1'],
}
def initialize(self, model):
"""Load a pretrained checkpoint (if exists) and then train from iter 0."""
ckpt_dir_or_file = self.task_config.init_checkpoint
logging.info('Trying to load pretrained checkpoint from %s',
ckpt_dir_or_file)
if ckpt_dir_or_file and tf.io.gfile.isdir(ckpt_dir_or_file):
ckpt_dir_or_file = tf.train.latest_checkpoint(ckpt_dir_or_file)
if not ckpt_dir_or_file:
logging.info('No checkpoint file found from %s. Will not load.',
ckpt_dir_or_file)
return
pretrain2finetune_mapping = {
'encoder': model.checkpoint_items['encoder'],
}
if self.task_config.init_cls_pooler:
# This option is valid when use_encoder_pooler is false.
pretrain2finetune_mapping[
'next_sentence.pooler_dense'] = model.checkpoint_items[
'sentence_prediction.pooler_dense']
ckpt = tf.train.Checkpoint(**pretrain2finetune_mapping)
status = ckpt.read(ckpt_dir_or_file)
status.expect_partial().assert_existing_objects_matched()
logging.info('Finished loading pretrained checkpoint from %s',
ckpt_dir_or_file)
| 15,128 | 39.560322 | 116 | py |
models | models-master/official/projects/fffner/fffner_classifier.py | # Copyright 2023 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.
"""FFF-NER special token classifier."""
# pylint: disable=g-classes-have-attributes
import collections
import tensorflow as tf
from official.nlp.modeling import layers
@tf.keras.utils.register_keras_serializable(package='Text')
class FFFNerClassifier(tf.keras.Model):
"""Classifier model based on a BERT-style transformer-based encoder.
This is an implementation of the network structure surrounding a transformer
encoder as described in "BERT: Pre-training of Deep Bidirectional Transformers
for Language Understanding" (https://arxiv.org/abs/1810.04805).
The BertClassifier allows a user to pass in a transformer stack, and
instantiates a classification network based on the passed `num_classes`
argument. If `num_classes` is set to 1, a regression network is instantiated.
*Note* that the model is constructed by
[Keras Functional API](https://keras.io/guides/functional_api/).
Args:
network: A transformer network. This network should output a sequence output
and a classification output. Furthermore, it should expose its embedding
table via a "get_embedding_table" method.
num_classes: Number of classes to predict from the classification network.
initializer: The initializer (if any) to use in the classification networks.
Defaults to a Glorot uniform initializer.
dropout_rate: The dropout probability of the cls head.
use_encoder_pooler: Whether to use the pooler layer pre-defined inside the
encoder.
head_name_is_entity: Name of the classification head.
head_name_entity_type: Name of the classification head.
"""
def __init__(self,
network,
num_classes_is_entity,
num_classes_entity_type,
initializer='glorot_uniform',
dropout_rate=0.1,
use_encoder_pooler=True,
head_name_is_entity='fffner_prediction_is_entity',
head_name_entity_type='fffner_prediction_entity_type',
cls_head=None,
**kwargs):
self.num_classes_is_entity = num_classes_is_entity
self.num_classes_entity_type = num_classes_entity_type
self.head_name_is_entity = head_name_is_entity
self.head_name_entity_type = head_name_entity_type
self.initializer = initializer
self.use_encoder_pooler = use_encoder_pooler
assert use_encoder_pooler, ('Customized pooling & classification function '
'is used')
# We want to use the inputs of the passed network as the inputs to this
# Model. To do this, we need to keep a handle to the network inputs for use
# when we construct the Model object at the end of init.
inputs = network.inputs
outputs = network(inputs)
if isinstance(outputs, list):
cls_inputs = outputs[1]
else:
cls_inputs = outputs['pooled_output']
cls_inputs = tf.keras.layers.Dropout(rate=dropout_rate)(cls_inputs)
classifier_is_entity = layers.ClassificationHead(
inner_dim=0 if use_encoder_pooler else cls_inputs.shape[-1],
num_classes=num_classes_is_entity,
initializer=initializer,
dropout_rate=dropout_rate,
name=head_name_is_entity)
classifier_entity_type = layers.ClassificationHead(
inner_dim=0 if use_encoder_pooler else cls_inputs.shape[-1],
num_classes=num_classes_entity_type,
initializer=initializer,
dropout_rate=dropout_rate,
name=head_name_entity_type)
predictions_is_entity = classifier_is_entity(cls_inputs[:, 0, :])
predictions_entity_type = classifier_entity_type(cls_inputs[:, 1, :])
super().__init__(
inputs=inputs,
outputs=[predictions_is_entity, predictions_entity_type],
**kwargs)
self._network = network
self._cls_head = cls_head
config_dict = self._make_config_dict()
# We are storing the config dict as a namedtuple here to ensure checkpoint
# compatibility with an earlier version of this model which did not track
# the config dict attribute. TF does not track immutable attrs which
# do not contain Trackables, so by creating a config namedtuple instead of
# a dict we avoid tracking it.
config_cls = collections.namedtuple('Config', config_dict.keys())
self._config = config_cls(**config_dict)
self.classifier_is_entity = classifier_is_entity
self.classifier_entity_type = classifier_entity_type
@property
def checkpoint_items(self):
items = dict(encoder=self._network)
if hasattr(self.classifier_is_entity, 'checkpoint_items'):
for key, item in self.classifier_is_entity.checkpoint_items.items():
items['.'.join([self.classifier_is_entity.name, key])] = item
if hasattr(self.classifier_entity_type, 'checkpoint_items'):
for key, item in self.classifier_entity_type.checkpoint_items.items():
items['.'.join([self.classifier_entity_type.name, key])] = item
return items
def get_config(self):
return dict(self._config._asdict())
@classmethod
def from_config(cls, config, custom_objects=None):
return cls(**config)
def _make_config_dict(self):
return {
'network': self._network,
'num_classes_is_entity': self.num_classes_is_entity,
'num_classes_entity_type': self.num_classes_entity_type,
'head_name_is_entity': self.head_name_is_entity,
'head_name_entity_type': self.head_name_entity_type,
'initializer': self.initializer,
'use_encoder_pooler': self.use_encoder_pooler,
}
| 6,139 | 41.054795 | 80 | py |
models | models-master/official/projects/fffner/fffner_encoder_test.py | # Copyright 2023 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.
"""Tests for official.nlp.projects.fffner.fffner_encoder."""
import numpy as np
import tensorflow as tf
from official.projects.fffner import fffner_encoder
class FFFNerEncoderTest(tf.test.TestCase):
def setUp(self):
super().setUp()
np.random.seed(0)
tf.random.set_seed(0)
def test_encoder(self):
sequence_length = 128
batch_size = 2
vocab_size = 1024
hidden_size = 256
network = fffner_encoder.FFFNerEncoder(
vocab_size=vocab_size,
hidden_size=hidden_size,
num_layers=1,
num_attention_heads=4,
max_sequence_length=512,
dict_outputs=True)
word_id_data = np.random.randint(
vocab_size, size=(batch_size, sequence_length), dtype=np.int32)
mask_data = np.random.randint(
2, size=(batch_size, sequence_length), dtype=np.int32)
type_id_data = np.random.randint(
2, size=(batch_size, sequence_length), dtype=np.int32)
is_entity_token_pos = np.random.randint(
sequence_length, size=(batch_size,), dtype=np.int32)
entity_type_token_pos = np.random.randint(
sequence_length, size=(batch_size,), dtype=np.int32)
inputs = {
'input_word_ids': word_id_data,
'input_mask': mask_data,
'input_type_ids': type_id_data,
'is_entity_token_pos': is_entity_token_pos,
'entity_type_token_pos': entity_type_token_pos
}
outputs = network(inputs)
self.assertEqual(outputs['sequence_output'].shape,
(batch_size, sequence_length, hidden_size))
self.assertEqual(outputs['pooled_output'].shape,
(batch_size, 2 * hidden_size))
if __name__ == '__main__':
tf.test.main()
| 2,303 | 32.391304 | 74 | py |
models | models-master/official/projects/fffner/train.py | # Copyright 2023 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.
"""FFFNER trainer."""
from absl import app
from official.common import flags as tfm_flags
# pylint: disable=unused-import
from official.nlp import train
from official.projects.fffner import fffner_experiments
# pylint: enable=unused-import
if __name__ == '__main__':
tfm_flags.define_flags()
app.run(train.main)
| 928 | 32.178571 | 74 | py |
models | models-master/official/projects/fffner/utils/convert_checkpoint_huggingface.py | # Copyright 2023 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.
"""Converts pre-trained pytorch checkpoint into a tf encoder checkpoint."""
import os
from absl import app
import numpy as np
import tensorflow as tf
import transformers
from official.modeling import tf_utils
from official.projects.fffner.fffner import FFFNerEncoderConfig
from official.projects.fffner.fffner_encoder import FFFNerEncoder
def _get_huggingface_bert_model_and_config(huggingface_model_name_or_path):
model = transformers.AutoModel.from_pretrained(huggingface_model_name_or_path)
return {n: p.data.numpy() for n, p in model.named_parameters()}, model.config
def _create_fffner_model(huggingface_bert_config):
"""Creates a Longformer model."""
encoder_cfg = FFFNerEncoderConfig()
encoder = FFFNerEncoder(
vocab_size=huggingface_bert_config.vocab_size,
hidden_size=huggingface_bert_config.hidden_size,
num_layers=huggingface_bert_config.num_hidden_layers,
num_attention_heads=huggingface_bert_config.num_attention_heads,
inner_dim=huggingface_bert_config.intermediate_size,
inner_activation=tf_utils.get_activation(
huggingface_bert_config.hidden_act),
output_dropout=huggingface_bert_config.hidden_dropout_prob,
attention_dropout=huggingface_bert_config.attention_probs_dropout_prob,
max_sequence_length=huggingface_bert_config.max_position_embeddings,
type_vocab_size=huggingface_bert_config.type_vocab_size,
initializer=tf.keras.initializers.TruncatedNormal(
stddev=encoder_cfg.initializer_range),
output_range=encoder_cfg.output_range,
embedding_width=huggingface_bert_config.hidden_size,
norm_first=encoder_cfg.norm_first)
return encoder
# pylint: disable=protected-access
def convert(encoder, bert_model):
"""Convert a Huggingface transformers bert encoder to the one in the codebase.
"""
num_layers = encoder._config["num_layers"]
num_attention_heads = encoder._config["num_attention_heads"]
hidden_size = encoder._config["hidden_size"]
head_size = hidden_size // num_attention_heads
assert head_size * num_attention_heads == hidden_size
encoder._embedding_layer.set_weights(
[bert_model["embeddings.word_embeddings.weight"]])
encoder._embedding_norm_layer.set_weights([
bert_model["embeddings.LayerNorm.weight"],
bert_model["embeddings.LayerNorm.bias"]
])
encoder._type_embedding_layer.set_weights(
[bert_model["embeddings.token_type_embeddings.weight"]])
encoder._position_embedding_layer.set_weights(
[bert_model["embeddings.position_embeddings.weight"]])
for layer_num in range(num_layers):
encoder._transformer_layers[
layer_num]._attention_layer._key_dense.set_weights([
bert_model[f"encoder.layer.{layer_num}.attention.self.key.weight"].T
.reshape((hidden_size, num_attention_heads, head_size)),
bert_model[f"encoder.layer.{layer_num}.attention.self.key.bias"]
.reshape((num_attention_heads, head_size))
])
encoder._transformer_layers[
layer_num]._attention_layer._query_dense.set_weights([
bert_model[f"encoder.layer.{layer_num}.attention.self.query.weight"]
.T.reshape((hidden_size, num_attention_heads, head_size)),
bert_model[f"encoder.layer.{layer_num}.attention.self.query.bias"]
.reshape((num_attention_heads, head_size))
])
encoder._transformer_layers[
layer_num]._attention_layer._value_dense.set_weights([
bert_model[f"encoder.layer.{layer_num}.attention.self.value.weight"]
.T.reshape((hidden_size, num_attention_heads, head_size)),
bert_model[f"encoder.layer.{layer_num}.attention.self.value.bias"]
.reshape((num_attention_heads, head_size))
])
encoder._transformer_layers[
layer_num]._attention_layer._output_dense.set_weights([
bert_model[
f"encoder.layer.{layer_num}.attention.output.dense.weight"].T
.reshape((num_attention_heads, head_size, hidden_size)),
bert_model[f"encoder.layer.{layer_num}.attention.output.dense.bias"]
])
encoder._transformer_layers[layer_num]._attention_layer_norm.set_weights([
bert_model[
f"encoder.layer.{layer_num}.attention.output.LayerNorm.weight"],
bert_model[f"encoder.layer.{layer_num}.attention.output.LayerNorm.bias"]
])
encoder._transformer_layers[layer_num]._intermediate_dense.set_weights([
bert_model[f"encoder.layer.{layer_num}.intermediate.dense.weight"].T,
bert_model[f"encoder.layer.{layer_num}.intermediate.dense.bias"]
])
encoder._transformer_layers[layer_num]._output_dense.set_weights([
bert_model[f"encoder.layer.{layer_num}.output.dense.weight"].T,
bert_model[f"encoder.layer.{layer_num}.output.dense.bias"]
])
encoder._transformer_layers[layer_num]._output_layer_norm.set_weights([
bert_model[f"encoder.layer.{layer_num}.output.LayerNorm.weight"],
bert_model[f"encoder.layer.{layer_num}.output.LayerNorm.bias"]
])
def convert_checkpoint(huggingface_model_name_or_path, output_path):
"""Converts and save the checkpoint."""
output_dir, _ = os.path.split(output_path)
tf.io.gfile.makedirs(output_dir)
huggingface_bert_model, huggingface_bert_config = _get_huggingface_bert_model_and_config(
huggingface_model_name_or_path)
encoder = _create_fffner_model(huggingface_bert_config)
sequence_length = 128
batch_size = 2
word_id_data = np.random.randint(
10, size=(batch_size, sequence_length), dtype=np.int32)
mask_data = np.random.randint(
2, size=(batch_size, sequence_length), dtype=np.int32)
type_id_data = np.random.randint(
2, size=(batch_size, sequence_length), dtype=np.int32)
is_entity_token_pos = np.zeros((batch_size, 1), dtype=np.int32)
entity_type_token_pos = np.ones((batch_size, 1), dtype=np.int32)
inputs = {
"input_word_ids": word_id_data,
"input_mask": mask_data,
"input_type_ids": type_id_data,
"is_entity_token_pos": is_entity_token_pos,
"entity_type_token_pos": entity_type_token_pos,
}
encoder(inputs)
convert(encoder, huggingface_bert_model)
tf.train.Checkpoint(encoder=encoder).write(output_path)
def main(_):
convert_checkpoint("bert-base-uncased", "bert-uncased")
if __name__ == "__main__":
app.run(main)
| 6,992 | 42.434783 | 91 | py |
models | models-master/official/projects/fffner/utils/create_data.py | # Copyright 2023 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.
"""Creates the datasets for FFF-NER model."""
import collections
import json
import math
import os
import sys
import numpy as np
import tensorflow as tf
from tqdm import tqdm
import transformers
class NERDataset:
"""A Named Entity Recognition dataset for FFF-NER model."""
def __init__(self, words_path, labels_path, tokenizer, is_train,
label_to_entity_type_index, ablation_not_mask,
ablation_no_brackets, ablation_span_type_together):
"""Instantiates the class.
Args:
words_path: Path to the .words file that contains the text.
labels_path: Path to the .ner file that contains NER labels for the text.
tokenizer: A huggingface tokenizer.
is_train: If creating a dataset for training, otherwise testing.
label_to_entity_type_index: A mapping of NER labels to indices.
ablation_not_mask: An ablation experiment that does not use mask tokens.
ablation_no_brackets: An ablation experiment that does not use brackets.
ablation_span_type_together: An ablation experiment that does span and
type prediction together at a single token.
"""
self.words_path = words_path
self.labels_path = labels_path
self.tokenizer = tokenizer
self.is_train = is_train
self.label_to_entity_type_index = label_to_entity_type_index
self.ablation_no_brackets = ablation_no_brackets
self.ablation_span_type_together = ablation_span_type_together
self.ablation_not_mask = ablation_not_mask
self.left_bracket = self.tokenize_word(" [")[0]
self.right_bracket = self.tokenize_word(" ]")[0]
self.mask_id = self.tokenizer.mask_token_id
self.cls_token_id = self.tokenizer.cls_token_id
self.sep_token_id = self.tokenizer.sep_token_id
self.data = []
self.id_to_sentence_infos = dict()
self.id_counter = 0
self.all_tokens = []
self.all_labels = []
self.max_seq_len_in_data = 0
self.max_len = 128
def read_file(self):
"""Reads the input files from words_path and labels_paths."""
with open(self.words_path) as f1, open(self.labels_path) as f2:
for _, (l1, l2) in enumerate(zip(f1, f2)):
tokens = l1.strip().split(" ")
labels = l2.strip().split(" ")
# since we are use [ and ], we replace all [, ] in the text with (, )
tokens = ["(" if token == "[" else token for token in tokens]
tokens = [")" if token == "]" else token for token in tokens]
yield tokens, labels
def tokenize_word(self, word):
"""Calls the tokenizer to produce word ids from text."""
result = self.tokenizer(word, add_special_tokens=False)
return result["input_ids"]
def tokenize_word_list(self, word_list):
return [self.tokenize_word(word) for word in word_list]
def process_to_input(self, input_ids, is_entity_token_pos,
entity_type_token_pos, is_entity_label,
entity_type_label, sid, span_start, span_end):
"""Process and store sentence and span id information."""
self.id_counter += 1
self.id_to_sentence_infos[self.id_counter] = {
"sid": sid, # sentence id
"span_start": span_start,
"span_end": span_end,
}
seqlen = len(input_ids)
self.max_seq_len_in_data = max(self.max_seq_len_in_data, seqlen)
return {
"input_ids": input_ids,
"attention_mask": [1] * seqlen,
"is_entity_token_pos": is_entity_token_pos,
"entity_type_token_pos": entity_type_token_pos,
"is_entity_label": 1 if is_entity_label else 0,
"entity_type_label": entity_type_label,
"sentence_id": sid,
"span_start": span_start,
"span_end": span_end,
"id": self.id_counter,
}
def process_word_list_and_spans_to_inputs(self, sid, word_list, spans):
"""Constructs the fffner input with spans and types."""
tokenized_word_list = self.tokenize_word_list(word_list)
final_len = sum(len(x) for x in tokenized_word_list)
final_len = 2 + 3 + 2 + 3 + final_len # account for mask and brackets
if final_len > self.max_len:
print(f"final_len {final_len} too long, skipping")
return
for span_start, span_end, span_type, span_label in spans:
assert span_type == "mask"
input_ids = []
input_ids.append(self.cls_token_id)
for ids in tokenized_word_list[:span_start]:
input_ids.extend(ids)
if not self.ablation_span_type_together:
if not self.ablation_no_brackets:
input_ids.append(self.left_bracket)
is_entity_token_pos = len(input_ids)
input_ids.append(self.mask_id if not self.ablation_not_mask else 8487)
if not self.ablation_no_brackets:
input_ids.append(self.right_bracket)
if not self.ablation_no_brackets:
input_ids.append(self.left_bracket)
for ids in tokenized_word_list[span_start:span_end + 1]:
input_ids.extend(ids)
if not self.ablation_no_brackets:
input_ids.append(self.right_bracket)
if not self.ablation_no_brackets:
input_ids.append(self.left_bracket)
entity_type_token_pos = len(input_ids)
if self.ablation_span_type_together:
is_entity_token_pos = len(input_ids)
input_ids.append(self.mask_id if not self.ablation_not_mask else 2828)
if not self.ablation_no_brackets:
input_ids.append(self.right_bracket)
for ids in tokenized_word_list[span_end + 1:]:
input_ids.extend(ids)
input_ids.append(self.sep_token_id)
is_entity_label = span_label in self.label_to_entity_type_index
entity_type_label = self.label_to_entity_type_index.get(span_label, 0)
yield self.process_to_input(input_ids, is_entity_token_pos,
entity_type_token_pos, is_entity_label,
entity_type_label, sid, span_start, span_end)
def bio_labels_to_spans(self, bio_labels):
"""Gets labels to spans."""
spans = []
for i, label in enumerate(bio_labels):
if label.startswith("B-"):
spans.append([i, i, label[2:]])
elif label.startswith("I-"):
if spans:
print("Error... I-tag should not start a span")
spans.append([i, i, label[2:]])
elif spans[-1][1] != i - 1 or spans[-1][2] != label[2:]:
print("Error... I-tag not consistent with previous tag")
spans.append([i, i, label[2:]])
else:
spans[-1][1] = i
elif label.startswith("O"):
pass
else:
assert False, bio_labels
spans = list(
filter(lambda x: x[2] in self.label_to_entity_type_index.keys(), spans))
return spans
def collate_fn(self, batch):
batch = self.tokenizer.pad(
batch,
padding="max_length",
max_length=self.max_len,
)
return batch
def prepare(self, negative_multiplier=3.):
"""Constructs negative sampling and handling train/test differences."""
desc = ("prepare data for training"
if self.is_train else "prepare data for testing")
total_missed_entities = 0
total_entities = 0
for sid, (tokens, labels) in tqdm(enumerate(self.read_file()), desc=desc):
self.all_tokens.append(tokens)
self.all_labels.append(labels)
entity_spans = self.bio_labels_to_spans(labels)
entity_spans_dict = {
(start, end): ent_type for start, end, ent_type in entity_spans
}
num_entities = len(entity_spans_dict)
num_negatives = int(
(len(tokens) + num_entities * 10) * negative_multiplier)
num_negatives = min(num_negatives, len(tokens) * (len(tokens) + 1) // 2)
min_words = 1
max_words = len(tokens)
total_entities += len(entity_spans)
spans = []
if self.is_train:
is_token_entity_prefix = [0] * (len(tokens) + 1)
for start, end, _ in entity_spans:
for i in range(start, end + 1):
is_token_entity_prefix[i + 1] = 1
for i in range(len(tokens)):
is_token_entity_prefix[i + 1] += is_token_entity_prefix[i]
negative_spans = []
negative_spans_probs = []
for n_words in range(min_words, max_words + 1):
for i in range(len(tokens) - n_words + 1):
j = i + n_words - 1
ent_type = entity_spans_dict.get((i, j), "O")
if not self.is_train or ent_type != "O":
spans.append((i, j, "mask", ent_type))
else:
negative_spans.append((i, j, "mask", ent_type))
intersection_size = (is_token_entity_prefix[j + 1] -
is_token_entity_prefix[i] + 1) / (
j + 1 - i)
negative_spans_probs.append(math.e**intersection_size)
if negative_spans and num_negatives > 0:
negative_spans_probs = np.array(negative_spans_probs) / np.sum(
negative_spans_probs)
negative_span_indices = np.random.choice(
len(negative_spans),
num_negatives,
replace=True,
p=negative_spans_probs)
spans.extend([negative_spans[x] for x in negative_span_indices])
else:
for n_words in range(min_words, max_words + 1):
for i in range(len(tokens) - n_words + 1):
j = i + n_words - 1
ent_type = entity_spans_dict.get((i, j), "O")
spans.append((i, j, "mask", ent_type))
for instance in self.process_word_list_and_spans_to_inputs(
sid, tokens, spans):
self.data.append(instance)
print(f"{total_missed_entities}/{total_entities} are ignored due to length")
print(f"Total {self.__len__()} instances")
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
return self.data[idx]
if __name__ == "__main__":
path_to_data_folder = sys.argv[1]
dataset_name = sys.argv[2]
train_file = sys.argv[3]
dataset = os.path.join(path_to_data_folder, dataset_name)
test_file = "test"
_tokenizer = transformers.AutoTokenizer.from_pretrained("bert-base-uncased")
entity_map = json.load(open(os.path.join(dataset, "entity_map.json")))
_label_to_entity_type_index = {
k: i for i, k in enumerate(list(entity_map.keys()))
}
train_ds = NERDataset(
words_path=os.path.join(dataset, train_file + ".words"),
labels_path=os.path.join(dataset, train_file + ".ner"),
tokenizer=_tokenizer,
is_train=True,
ablation_not_mask=False,
ablation_no_brackets=False,
ablation_span_type_together=False,
label_to_entity_type_index=_label_to_entity_type_index)
eval_ds = NERDataset(
words_path=os.path.join(dataset, test_file + ".words"),
labels_path=os.path.join(dataset, test_file + ".ner"),
tokenizer=_tokenizer,
is_train=False,
ablation_not_mask=False,
ablation_no_brackets=False,
ablation_span_type_together=False,
label_to_entity_type_index=_label_to_entity_type_index)
train_ds.prepare(negative_multiplier=3)
train_data = train_ds.collate_fn(train_ds.data)
eval_ds.prepare(negative_multiplier=3)
eval_data = eval_ds.collate_fn(eval_ds.data)
def file_based_convert_examples_to_features(examples, output_file):
"""Convert a set of `InputExample`s to a TFRecord file."""
tf.io.gfile.makedirs(os.path.dirname(output_file))
writer = tf.io.TFRecordWriter(output_file)
for ex_index in range(len(examples["input_ids"])):
if ex_index % 10000 == 0:
print(f"Writing example {ex_index} of {len(examples['input_ids'])}")
print(examples["input_ids"][ex_index])
def create_int_feature(values):
f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
return f
features = collections.OrderedDict()
features["input_ids"] = create_int_feature(
examples["input_ids"][ex_index])
features["input_mask"] = create_int_feature(
examples["attention_mask"][ex_index])
features["segment_ids"] = create_int_feature(
[0] * len(examples["attention_mask"][ex_index]))
features["is_entity_token_pos"] = create_int_feature(
[examples["is_entity_token_pos"][ex_index]])
features["entity_type_token_pos"] = create_int_feature(
[examples["entity_type_token_pos"][ex_index]])
features["is_entity_label"] = create_int_feature(
[examples["is_entity_label"][ex_index]])
features["entity_type_label"] = create_int_feature(
[examples["entity_type_label"][ex_index]])
features["example_id"] = create_int_feature([examples["id"][ex_index]])
features["sentence_id"] = create_int_feature(
[examples["sentence_id"][ex_index]])
features["span_start"] = create_int_feature(
[examples["span_start"][ex_index]])
features["span_end"] = create_int_feature(
[examples["span_end"][ex_index]])
tf_example = tf.train.Example(
features=tf.train.Features(feature=features))
writer.write(tf_example.SerializeToString())
writer.close()
file_based_convert_examples_to_features(
train_data, f"{dataset_name}_{train_file}.tf_record")
file_based_convert_examples_to_features(
eval_data, f"{dataset_name}_{test_file}.tf_record")
| 13,915 | 38.988506 | 80 | py |
models | models-master/official/projects/fffner/utils/convert_checkpoint_tensorflow.py | # Copyright 2023 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.
"""Converts pre-trained encoder into a fffner encoder checkpoint."""
import os
from absl import app
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
from official.projects.fffner.fffner import FFFNerEncoderConfig
from official.projects.fffner.fffner_encoder import FFFNerEncoder
def _get_tensorflow_bert_model_and_config(tfhub_handle_encoder):
"""Gets the BERT model name-parameters pairs and configurations."""
bert_model = hub.KerasLayer(tfhub_handle_encoder)
bert_model_weights_name = [w.name for w in bert_model.weights]
bert_model_weights = bert_model.get_weights()
named_parameters = {
n: p for n, p in zip(bert_model_weights_name, bert_model_weights)
}
config = {}
config["num_attention_heads"], _, config["hidden_size"] = named_parameters[
"transformer/layer_0/self_attention/attention_output/kernel:0"].shape
_, config["intermediate_size"] = named_parameters[
"transformer/layer_0/intermediate/kernel:0"].shape
num_hidden_layers = 0
while f"transformer/layer_{num_hidden_layers}/self_attention/query/kernel:0" in named_parameters:
num_hidden_layers += 1
config["num_hidden_layers"] = num_hidden_layers
config["vocab_size"], _ = named_parameters[
"word_embeddings/embeddings:0"].shape
config["max_position_embeddings"], _ = named_parameters[
"position_embedding/embeddings:0"].shape
config["type_vocab_size"], _ = named_parameters[
"type_embeddings/embeddings:0"].shape
return named_parameters, config
def _create_fffner_model(bert_config):
"""Creates a Longformer model."""
encoder_cfg = FFFNerEncoderConfig()
encoder = FFFNerEncoder(
vocab_size=bert_config["vocab_size"],
hidden_size=bert_config["hidden_size"],
num_layers=bert_config["num_hidden_layers"],
num_attention_heads=bert_config["num_attention_heads"],
inner_dim=bert_config["intermediate_size"],
max_sequence_length=bert_config["max_position_embeddings"],
type_vocab_size=bert_config["type_vocab_size"],
initializer=tf.keras.initializers.TruncatedNormal(
stddev=encoder_cfg.initializer_range),
output_range=encoder_cfg.output_range,
embedding_width=bert_config["hidden_size"],
norm_first=encoder_cfg.norm_first)
return encoder
# pylint: disable=protected-access
def convert(encoder, bert_model):
"""Convert a Tensorflow transformers bert encoder to the one in the codebase.
"""
num_layers = encoder._config["num_layers"]
num_attention_heads = encoder._config["num_attention_heads"]
hidden_size = encoder._config["hidden_size"]
head_size = hidden_size // num_attention_heads
assert head_size * num_attention_heads == hidden_size
encoder._embedding_layer.set_weights(
[bert_model["word_embeddings/embeddings:0"]])
encoder._embedding_norm_layer.set_weights([
bert_model["embeddings/layer_norm/gamma:0"],
bert_model["embeddings/layer_norm/beta:0"]
])
encoder._type_embedding_layer.set_weights(
[bert_model["type_embeddings/embeddings:0"]])
encoder._position_embedding_layer.set_weights(
[bert_model["position_embedding/embeddings:0"]])
for layer_num in range(num_layers):
encoder._transformer_layers[
layer_num]._attention_layer._key_dense.set_weights([
bert_model[
f"transformer/layer_{layer_num}/self_attention/key/kernel:0"],
bert_model[
f"transformer/layer_{layer_num}/self_attention/key/bias:0"]
])
encoder._transformer_layers[
layer_num]._attention_layer._query_dense.set_weights([
bert_model[
f"transformer/layer_{layer_num}/self_attention/query/kernel:0"],
bert_model[
f"transformer/layer_{layer_num}/self_attention/query/bias:0"]
])
encoder._transformer_layers[
layer_num]._attention_layer._value_dense.set_weights([
bert_model[
f"transformer/layer_{layer_num}/self_attention/value/kernel:0"],
bert_model[
f"transformer/layer_{layer_num}/self_attention/value/bias:0"]
])
encoder._transformer_layers[layer_num]._attention_layer._output_dense.set_weights([
bert_model[
f"transformer/layer_{layer_num}/self_attention/attention_output/kernel:0"],
bert_model[
f"transformer/layer_{layer_num}/self_attention/attention_output/bias:0"]
])
encoder._transformer_layers[layer_num]._attention_layer_norm.set_weights([
bert_model[
f"transformer/layer_{layer_num}/self_attention_layer_norm/gamma:0"],
bert_model[
f"transformer/layer_{layer_num}/self_attention_layer_norm/beta:0"]
])
encoder._transformer_layers[layer_num]._intermediate_dense.set_weights([
bert_model[f"transformer/layer_{layer_num}/intermediate/kernel:0"],
bert_model[f"transformer/layer_{layer_num}/intermediate/bias:0"]
])
encoder._transformer_layers[layer_num]._output_dense.set_weights([
bert_model[f"transformer/layer_{layer_num}/output/kernel:0"],
bert_model[f"transformer/layer_{layer_num}/output/bias:0"]
])
encoder._transformer_layers[layer_num]._output_layer_norm.set_weights([
bert_model[f"transformer/layer_{layer_num}/output_layer_norm/gamma:0"],
bert_model[f"transformer/layer_{layer_num}/output_layer_norm/beta:0"]
])
def convert_checkpoint(output_path, tfhub_handle_encoder):
"""Converts and save the checkpoint."""
output_dir, _ = os.path.split(output_path)
tf.io.gfile.makedirs(output_dir)
bert_model, bert_config = _get_tensorflow_bert_model_and_config(
tfhub_handle_encoder)
encoder = _create_fffner_model(bert_config)
sequence_length = 128
batch_size = 2
word_id_data = np.random.randint(
10, size=(batch_size, sequence_length), dtype=np.int32)
mask_data = np.random.randint(
2, size=(batch_size, sequence_length), dtype=np.int32)
type_id_data = np.random.randint(
2, size=(batch_size, sequence_length), dtype=np.int32)
is_entity_token_pos = np.zeros((batch_size, 1), dtype=np.int32)
entity_type_token_pos = np.ones((batch_size, 1), dtype=np.int32)
inputs = {
"input_word_ids": word_id_data,
"input_mask": mask_data,
"input_type_ids": type_id_data,
"is_entity_token_pos": is_entity_token_pos,
"entity_type_token_pos": entity_type_token_pos,
}
encoder(inputs)
convert(encoder, bert_model)
tf.train.Checkpoint(encoder=encoder).write(output_path)
def main(_):
convert_checkpoint(
output_path="tf-bert-uncased",
tfhub_handle_encoder="https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/3"
)
if __name__ == "__main__":
app.run(main)
| 7,350 | 39.838889 | 99 | py |
models | models-master/official/projects/edgetpu/nlp/run_mobilebert_edgetpu_train.py | # Copyright 2023 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.
"""MobileBERT-EdgeTPU model runner."""
import os
from absl import app
from absl import flags
from absl import logging
import orbit
import tensorflow as tf
from official.common import distribute_utils
from official.common import flags as tfm_flags
from official.projects.edgetpu.nlp import mobilebert_edgetpu_trainer
from official.projects.edgetpu.nlp.configs import params
from official.projects.edgetpu.nlp.modeling import model_builder
from official.projects.edgetpu.nlp.utils import utils
FLAGS = flags.FLAGS
def main(_):
# Set up experiment params and load the configs from file/files.
experiment_params = params.EdgeTPUBERTCustomParams()
experiment_params = utils.config_override(experiment_params, FLAGS)
model_dir = utils.get_model_dir(experiment_params, FLAGS)
distribution_strategy = distribute_utils.get_distribution_strategy(
distribution_strategy=experiment_params.runtime.distribution_strategy,
all_reduce_alg=experiment_params.runtime.all_reduce_alg,
num_gpus=experiment_params.runtime.num_gpus,
tpu_address=experiment_params.runtime.tpu_address)
with distribution_strategy.scope():
teacher_model = model_builder.build_bert_pretrainer(
pretrainer_cfg=experiment_params.teacher_model,
quantization_friendly=False,
name='teacher')
student_model = model_builder.build_bert_pretrainer(
pretrainer_cfg=experiment_params.student_model,
quantization_friendly=True,
name='student')
# Load model weights.
teacher_ckpt_dir_or_file = experiment_params.teacher_model_init_checkpoint
if not teacher_ckpt_dir_or_file:
raise ValueError('`teacher_model_init_checkpoint` is not specified.')
utils.load_checkpoint(teacher_model, teacher_ckpt_dir_or_file)
student_ckpt_dir_or_file = experiment_params.student_model_init_checkpoint
if not student_ckpt_dir_or_file:
# Makes sure the pretrainer variables are created.
_ = student_model(student_model.inputs)
logging.warn('No student checkpoint is provided, training might take '
'much longer before converging.')
else:
utils.load_checkpoint(student_model, student_ckpt_dir_or_file)
runner = mobilebert_edgetpu_trainer.MobileBERTEdgeTPUDistillationTrainer(
teacher_model=teacher_model,
student_model=student_model,
strategy=distribution_strategy,
experiment_params=experiment_params,
export_ckpt_path=model_dir)
# Save checkpoint for preemption handling.
# Checkpoint for downstreaming tasks are saved separately inside the
# runner's train_loop_end() function.
checkpoint = tf.train.Checkpoint(
teacher_model=runner.teacher_model,
student_model=runner.student_model,
layer_wise_optimizer=runner.layer_wise_optimizer,
e2e_optimizer=runner.e2e_optimizer,
current_step=runner.current_step)
checkpoint_manager = tf.train.CheckpointManager(
checkpoint,
directory=model_dir,
max_to_keep=5,
step_counter=runner.current_step,
checkpoint_interval=20000,
init_fn=None)
controller = orbit.Controller(
trainer=runner,
evaluator=runner,
global_step=runner.current_step,
strategy=distribution_strategy,
steps_per_loop=experiment_params.orbit_config.steps_per_loop,
summary_dir=os.path.join(model_dir, 'train'),
eval_summary_dir=os.path.join(model_dir, 'eval'),
checkpoint_manager=checkpoint_manager)
if FLAGS.mode == 'train':
controller.train(steps=experiment_params.orbit_config.total_steps)
else:
raise ValueError('Unsupported mode, only support `train`')
if __name__ == '__main__':
tfm_flags.define_flags()
app.run(main)
| 4,364 | 36.956522 | 78 | py |
models | models-master/official/projects/edgetpu/nlp/mobilebert_edgetpu_trainer_test.py | # Copyright 2023 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.
"""Tests for mobilebert_edgetpu_trainer.py."""
import tensorflow as tf
from official.projects.edgetpu.nlp import mobilebert_edgetpu_trainer
from official.projects.edgetpu.nlp.configs import params
from official.projects.edgetpu.nlp.modeling import model_builder
# Helper function to create dummy dataset
def _dummy_dataset():
def dummy_data(_):
dummy_ids = tf.zeros((1, 64), dtype=tf.int32)
dummy_lm = tf.zeros((1, 64), dtype=tf.int32)
return dict(
input_word_ids=dummy_ids,
input_mask=dummy_ids,
input_type_ids=dummy_ids,
masked_lm_positions=dummy_lm,
masked_lm_ids=dummy_lm,
masked_lm_weights=tf.cast(dummy_lm, dtype=tf.float32),
next_sentence_labels=tf.zeros((1, 1), dtype=tf.int32))
dataset = tf.data.Dataset.range(1)
dataset = dataset.repeat()
dataset = dataset.map(
dummy_data, num_parallel_calls=tf.data.experimental.AUTOTUNE)
return dataset
class EdgetpuBertTrainerTest(tf.test.TestCase):
def setUp(self):
super(EdgetpuBertTrainerTest, self).setUp()
self.experiment_params = params.EdgeTPUBERTCustomParams()
self.strategy = tf.distribute.get_strategy()
self.experiment_params.train_datasest.input_path = 'dummy'
self.experiment_params.eval_dataset.input_path = 'dummy'
def test_train_model_locally(self):
"""Tests training a model locally with one step."""
teacher_model = model_builder.build_bert_pretrainer(
pretrainer_cfg=self.experiment_params.teacher_model,
name='teacher')
_ = teacher_model(teacher_model.inputs)
student_model = model_builder.build_bert_pretrainer(
pretrainer_cfg=self.experiment_params.student_model,
name='student')
_ = student_model(student_model.inputs)
trainer = mobilebert_edgetpu_trainer.MobileBERTEdgeTPUDistillationTrainer(
teacher_model=teacher_model,
student_model=student_model,
strategy=self.strategy,
experiment_params=self.experiment_params)
# Rebuild dummy dataset since loading real dataset will cause timeout error.
trainer.train_dataset = _dummy_dataset()
trainer.eval_dataset = _dummy_dataset()
train_dataset_iter = iter(trainer.train_dataset)
eval_dataset_iter = iter(trainer.eval_dataset)
trainer.train_loop_begin()
trainer.train_step(train_dataset_iter)
trainer.eval_step(eval_dataset_iter)
if __name__ == '__main__':
tf.test.main()
| 3,038 | 36.060976 | 80 | py |
models | models-master/official/projects/edgetpu/nlp/__init__.py | # Copyright 2023 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.
| 609 | 39.666667 | 74 | py |
models | models-master/official/projects/edgetpu/nlp/mobilebert_edgetpu_trainer.py | # Copyright 2023 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.
"""Distillation trainer for EdgeTPU-BERT."""
import enum
import os
from typing import Optional
from absl import logging
import orbit
import tensorflow as tf
from official.modeling import optimization
from official.nlp import modeling
from official.nlp.data import data_loader_factory
from official.projects.edgetpu.nlp.configs import params
class DistillationMode(enum.Enum):
"""enum.Enum class for different distillation mode.
A state machine is used to control the training progress. When the training
job starts from the beginning or resumes from a preemption, the state is INIT.
Then depends on the 'self.current_step', the state switches to either
'LAYER_WISE' or 'END2END'.
Options:
UNKNOWN: Unknown status, always raise errors.
INIT: The trainer is initialized or restarted from the preemption.
LAYER_WISE: Layer-wise distillation for each transformer layers.
END2END: End-to-end distillation after layer-wise distillaiton is done.
"""
UNKNOWN = 0
INIT = 1
LAYER_WISE = 2
END2END = 3
def _get_distribution_losses(teacher, student):
"""Returns the beta and gamma distall losses for feature distribution."""
teacher_mean = tf.math.reduce_mean(teacher, axis=-1, keepdims=True)
student_mean = tf.math.reduce_mean(student, axis=-1, keepdims=True)
teacher_var = tf.math.reduce_variance(teacher, axis=-1, keepdims=True)
student_var = tf.math.reduce_variance(student, axis=-1, keepdims=True)
beta_loss = tf.math.squared_difference(student_mean, teacher_mean)
beta_loss = tf.math.reduce_mean(beta_loss, axis=None, keepdims=False)
gamma_loss = tf.math.abs(student_var - teacher_var)
gamma_loss = tf.math.reduce_mean(gamma_loss, axis=None, keepdims=False)
return beta_loss, gamma_loss
def _get_attention_loss(teacher_score, student_score):
"""Function to calculate attention loss for transformer layers."""
# Note that the definition of KLDivergence here is a little different from
# the original one (tf.keras.losses.KLDivergence). We adopt this approach
# to stay consistent with the TF1 implementation.
teacher_weight = tf.keras.activations.softmax(teacher_score, axis=-1)
student_log_weight = tf.nn.log_softmax(student_score, axis=-1)
kl_divergence = -(teacher_weight * student_log_weight)
kl_divergence = tf.math.reduce_sum(kl_divergence, axis=-1, keepdims=True)
kl_divergence = tf.math.reduce_mean(kl_divergence, axis=None,
keepdims=False)
return kl_divergence
def _build_sub_encoder(encoder, stage_number):
"""Builds a partial model containing the first few transformer layers."""
input_ids = encoder.inputs[0]
input_mask = encoder.inputs[1]
type_ids = encoder.inputs[2]
attention_mask = modeling.layers.SelfAttentionMask()(
inputs=input_ids, to_mask=input_mask)
embedding_output = encoder.embedding_layer(input_ids, type_ids)
layer_output = embedding_output
attention_score = None
for layer_idx in range(stage_number + 1):
layer_output, attention_score = encoder.transformer_layers[layer_idx](
layer_output, attention_mask, return_attention_scores=True)
return tf.keras.Model(
inputs=[input_ids, input_mask, type_ids],
outputs=[layer_output, attention_score])
class MobileBERTEdgeTPUDistillationTrainer(orbit.StandardTrainer,
orbit.StandardEvaluator):
"""Orbit based distillation training pipeline for MobileBERT-EdgeTPU models."""
def __init__(self,
teacher_model: modeling.models.BertPretrainerV2,
student_model: modeling.models.BertPretrainerV2,
strategy: tf.distribute.Strategy,
experiment_params: params.EdgeTPUBERTCustomParams,
export_ckpt_path: Optional[str] = None,
reuse_teacher_embedding: Optional[bool] = True):
self.teacher_model = teacher_model
self.student_model = student_model
self.strategy = strategy
self.layer_wise_distill_config = experiment_params.layer_wise_distillation
self.e2e_distill_config = experiment_params.end_to_end_distillation
self.optimizer_config = experiment_params.optimizer
self.train_dataset_config = experiment_params.train_datasest
self.eval_dataset_config = experiment_params.eval_dataset
self.word_vocab_size = experiment_params.student_model.encoder.mobilebert.word_vocab_size
self.distill_gt_ratio = experiment_params.end_to_end_distillation.distill_ground_truth_ratio
self.teacher_transformer_layers = experiment_params.teacher_model.encoder.mobilebert.num_blocks
self.student_transformer_layers = experiment_params.student_model.encoder.mobilebert.num_blocks
self.exported_ckpt_path = export_ckpt_path
self.current_step = orbit.utils.create_global_step()
self.current_step.assign(0)
# Stage is updated every time when the distillation is done for one
# transformer layer. self.stage is updated at the train_loop_begin()
# function. After the last stage is done, the self.mode is changed to
# 'e2e'.
self.stage = 0
self.mode = DistillationMode.INIT
# Number of transformer layers in teacher should be equal (or divisible)
# by the number of transformer layers in student.
if self.teacher_transformer_layers % self.student_transformer_layers != 0:
raise ValueError(
'Number of transformer layer must be equal or divisible.')
self.ratio = (self.teacher_transformer_layers //
self.student_transformer_layers)
# Create optimizers for different training stage.
self.layer_wise_optimizer = self.build_optimizer(
self.layer_wise_distill_config)
self.e2e_optimizer = self.build_optimizer(self.e2e_distill_config)
self.current_optimizer = self.layer_wise_optimizer
# A non-trainable layer for feature normalization for transfer loss.
self._layer_norm = tf.keras.layers.LayerNormalization(
axis=-1,
beta_initializer='zeros',
gamma_initializer='ones',
trainable=False)
self.build_dataset()
self.build_metrics()
# Create an empty exported checkpoint manager, it will be initialized once
# the training mode enters END2END.
self.exported_ckpt_manager = None
# Reuse the teacher's embedding table in student model.
if reuse_teacher_embedding:
logging.info('Copy word embedding from teacher model to student.')
teacher_encoder = self.teacher_model.encoder_network
student_encoder = self.student_model.encoder_network
embedding_weights = teacher_encoder.embedding_layer.get_weights()
student_encoder.embedding_layer.set_weights(embedding_weights)
orbit.StandardTrainer.__init__(self, self.train_dataset)
orbit.StandardEvaluator.__init__(self, self.eval_dataset)
def build_dataset(self):
"""Creates the training and evaluation dataset."""
# Returns None when the input_path is 'dummy'.
if self.train_dataset_config.input_path == 'dummy':
self.train_dataset = None
self.eval_dataset = None
return
# None distributed dataset.
train_dataset = data_loader_factory.get_data_loader(
self.train_dataset_config).load()
eval_dataset = data_loader_factory.get_data_loader(
self.eval_dataset_config).load()
# Ddistributed dataset.
self.train_dataset = orbit.utils.make_distributed_dataset(
self.strategy, train_dataset)
self.eval_dataset = orbit.utils.make_distributed_dataset(
self.strategy, eval_dataset)
def build_model(self):
"""Creates the fused model from teacher/student model."""
self.teacher_model.trainable = False
if self.mode == DistillationMode.LAYER_WISE:
# Build a model that outputs teacher's and student's transformer outputs.
inputs = self.student_model.encoder_network.inputs
student_sub_encoder = _build_sub_encoder(
encoder=self.student_model.encoder_network,
stage_number=self.stage)
student_output_feature, student_attention_score = student_sub_encoder(
inputs)
teacher_sub_encoder = _build_sub_encoder(
encoder=self.teacher_model.encoder_network,
stage_number=int(self.stage * self.ratio))
teacher_output_feature, teacher_attention_score = teacher_sub_encoder(
inputs)
return tf.keras.Model(
inputs=inputs,
outputs=dict(
student_output_feature=student_output_feature,
student_attention_score=student_attention_score,
teacher_output_feature=teacher_output_feature,
teacher_attention_score=teacher_attention_score))
elif self.mode == DistillationMode.END2END:
# Build a model that outputs teacher's and student's MLM/NSP outputs.
inputs = self.student_model.inputs
student_pretrainer_outputs = self.student_model(inputs)
teacher_pretrainer_outputs = self.teacher_model(inputs)
model = tf.keras.Model(
inputs=inputs,
outputs=dict(
student_pretrainer_outputs=student_pretrainer_outputs,
teacher_pretrainer_outputs=teacher_pretrainer_outputs,
))
# Checkpoint the student encoder which is the goal of distillation.
model.checkpoint_items = self.student_model.checkpoint_items
return model
else:
raise ValueError(f'Unknown distillation mode: {self.mode}.')
def build_optimizer(self, config):
"""Creates optimier for the fused model."""
optimizer_config = self.optimizer_config.replace(
learning_rate={
'polynomial': {
'decay_steps': config.decay_steps,
'initial_learning_rate': config.initial_learning_rate,
'end_learning_rate': config.end_learning_rate,
}
},
warmup={
'type': 'linear',
'linear': {
'warmup_steps': config.warmup_steps,
}
})
logging.info('The optimizer config is: %s', optimizer_config.as_dict())
optimizer_factory = optimization.OptimizerFactory(optimizer_config)
return optimizer_factory.build_optimizer(
optimizer_factory.build_learning_rate())
def build_metrics(self):
"""Creates metrics functions for the training."""
self.train_metrics = {
'feature_transfer_mse': tf.keras.metrics.Mean(),
'beta_transfer_loss': tf.keras.metrics.Mean(),
'gamma_transfer_loss': tf.keras.metrics.Mean(),
'attention_transfer_loss': tf.keras.metrics.Mean(),
'masked_lm_accuracy': tf.keras.metrics.SparseCategoricalAccuracy(),
'lm_example_loss': tf.keras.metrics.Mean(),
'total_loss': tf.keras.metrics.Mean(),
'next_sentence_accuracy': tf.keras.metrics.SparseCategoricalAccuracy(),
'next_sentence_loss': tf.keras.metrics.Mean(),
}
self.eval_metrics = {
'masked_lm_accuracy': tf.keras.metrics.SparseCategoricalAccuracy(),
'next_sentence_accuracy': tf.keras.metrics.SparseCategoricalAccuracy(),
}
def build_exported_ckpt_manager(self):
"""Creates checkpoint manager for exported models."""
if self.exported_ckpt_path is None:
logging.warn('exported_ckpt_path is not specified. The saved model'
'can not be used for downstreaming tasks.')
return
checkpoint = tf.train.Checkpoint(global_step=self.current_step,
model=self.model,
optimizer=self.current_optimizer,
**self.model.checkpoint_items)
self.exported_ckpt_manager = tf.train.CheckpointManager(
checkpoint,
directory=os.path.join(self.exported_ckpt_path, 'exported_ckpt'),
max_to_keep=2,
step_counter=self.current_step,
checkpoint_interval=20000,
init_fn=None)
def calculate_loss_metrics(self, labels, outputs):
"""Calculates loss and metrics.
Args:
labels: Ground truth from dataset.
outputs: fused outputs from teacher model and student model.
Returns:
total loss value.
"""
if self.mode == DistillationMode.LAYER_WISE:
teacher_feature = outputs['teacher_output_feature']
student_feature = outputs['student_output_feature']
feature_transfer_loss = tf.keras.losses.mean_squared_error(
self._layer_norm(teacher_feature), self._layer_norm(student_feature))
# feature_transfer_loss = tf.reduce_mean(feature_transfer_loss)
feature_transfer_loss *= self.layer_wise_distill_config.hidden_distill_factor
beta_loss, gamma_loss = _get_distribution_losses(teacher_feature,
student_feature)
beta_loss *= self.layer_wise_distill_config.beta_distill_factor
gamma_loss *= self.layer_wise_distill_config.gamma_distill_factor
total_loss = feature_transfer_loss + beta_loss + gamma_loss
teacher_attention = outputs['teacher_attention_score']
student_attention = outputs['student_attention_score']
attention_loss = _get_attention_loss(teacher_attention, student_attention)
attention_loss *= self.layer_wise_distill_config.attention_distill_factor
total_loss += attention_loss
total_loss /= tf.cast((self.stage + 1), tf.float32)
elif self.mode == DistillationMode.END2END:
lm_label = labels['masked_lm_ids']
# Shape: [batch, max_predictions_per_seq, word_vocab_size]
lm_label = tf.one_hot(indices=lm_label,
depth=self.word_vocab_size,
on_value=1.0,
off_value=0.0,
axis=-1,
dtype=tf.float32)
lm_label_weights = labels['masked_lm_weights']
teacher_mlm_logits = outputs['teacher_pretrainer_outputs']['mlm_logits']
teacher_labels = tf.nn.softmax(teacher_mlm_logits, axis=-1)
gt_label = self.distill_gt_ratio * lm_label
teacher_label = (1 - self.distill_gt_ratio) * teacher_labels
lm_label = gt_label + teacher_label
student_pretrainer_output = outputs['student_pretrainer_outputs']
# Shape: [batch, max_predictions_per_seq, word_vocab_size]
student_lm_log_probs = tf.nn.log_softmax(
student_pretrainer_output['mlm_logits'], axis=-1)
# Shape: [batch * max_predictions_per_seq]
per_example_loss = tf.reshape(
-tf.reduce_sum(student_lm_log_probs * lm_label, axis=[-1]), [-1])
lm_label_weights = tf.reshape(labels['masked_lm_weights'], [-1])
lm_numerator_loss = tf.reduce_sum(per_example_loss * lm_label_weights)
lm_denominator_loss = tf.reduce_sum(lm_label_weights)
mlm_loss = tf.math.divide_no_nan(lm_numerator_loss, lm_denominator_loss)
total_loss = mlm_loss
sentence_labels = labels['next_sentence_labels']
sentence_outputs = tf.cast(
student_pretrainer_output['next_sentence'], dtype=tf.float32)
sentence_loss = tf.reduce_mean(
tf.keras.losses.sparse_categorical_crossentropy(
sentence_labels, sentence_outputs, from_logits=True))
total_loss += sentence_loss
else:
raise ValueError('Training mode has to be LAYER-WISE or END2END.')
if self.mode == DistillationMode.LAYER_WISE:
self.train_metrics['feature_transfer_mse'].update_state(
feature_transfer_loss)
self.train_metrics['beta_transfer_loss'].update_state(beta_loss)
self.train_metrics['gamma_transfer_loss'].update_state(gamma_loss)
self.train_metrics['attention_transfer_loss'].update_state(attention_loss)
elif self.mode == DistillationMode.END2END:
self.train_metrics['lm_example_loss'].update_state(mlm_loss)
self.train_metrics['next_sentence_loss'].update_state(sentence_loss)
self.train_metrics['total_loss'].update_state(total_loss)
return total_loss
def calculate_accuracy_metrics(self, labels, outputs, metrics):
"""Calculates metrics that are not related to the losses."""
if self.mode == DistillationMode.END2END:
student_pretrainer_output = outputs['student_pretrainer_outputs']
metrics['masked_lm_accuracy'].update_state(
labels['masked_lm_ids'],
student_pretrainer_output['mlm_logits'],
labels['masked_lm_weights'])
metrics['next_sentence_accuracy'].update_state(
labels['next_sentence_labels'],
student_pretrainer_output['next_sentence'])
def _rebuild_training_graph(self):
"""Rebuilds the training graph when one stage/step is done."""
self.stage = (self.current_step.numpy() //
self.layer_wise_distill_config.num_steps)
logging.info('Start distillation training for the %d stage', self.stage)
self.model = self.build_model()
self.layer_wise_optimizer = self.build_optimizer(
self.layer_wise_distill_config)
# Rebuild the dataset which can significantly improve the training
# accuracy.
logging.info('Rebuild the training dataset.')
self.build_dataset()
# Setting `self._train_loop_fn` and `self._eval_loop_fn` to None will
# rebuild the train and eval functions with the updated loss function.
logging.info('Rebuild the training and evaluation graph.')
self._train_loop_fn = None
self._eval_loop_fn = None
def train_loop_begin(self):
"""A train loop is similar with the concept of an epoch."""
self.train_metrics['feature_transfer_mse'].reset_states()
self.train_metrics['beta_transfer_loss'].reset_states()
self.train_metrics['gamma_transfer_loss'].reset_states()
self.train_metrics['attention_transfer_loss'].reset_states()
self.train_metrics['total_loss'].reset_states()
self.train_metrics['lm_example_loss'].reset_states()
self.train_metrics['next_sentence_loss'].reset_states()
self.train_metrics['masked_lm_accuracy'].reset_states()
self.train_metrics['next_sentence_accuracy'].reset_states()
if self.mode == DistillationMode.INIT:
if (self.current_step.numpy() < self.layer_wise_distill_config.num_steps *
self.student_transformer_layers):
logging.info('Start or resume layer-wise training.')
self.mode = DistillationMode.LAYER_WISE
self.stage = (self.current_step.numpy() //
self.layer_wise_distill_config.num_steps)
self.model = self.build_model()
self.build_dataset()
self.current_optimizer = self.layer_wise_optimizer
else:
self.mode = DistillationMode.END2END
logging.info('Start or resume e2e training.')
self.model = self.build_model()
self.current_optimizer = self.e2e_optimizer
elif self.mode == DistillationMode.LAYER_WISE:
if (self.current_step.numpy() < self.layer_wise_distill_config.num_steps *
self.student_transformer_layers):
if (self.current_step.numpy() %
self.layer_wise_distill_config.num_steps) == 0:
self._rebuild_training_graph()
self.current_optimizer = self.layer_wise_optimizer
else:
self.mode = DistillationMode.END2END
self.model = self.build_model()
logging.info('Start e2e distillation training.')
self.current_optimizer = self.e2e_optimizer
logging.info('Rebuild the training dataset.')
self.build_dataset()
logging.info('Rebuild the training and evaluation graph.')
self._train_loop_fn = None
self._eval_loop_fn = None
def train_step(self, iterator):
"""A single step of train."""
def step_fn(inputs):
with tf.GradientTape() as tape:
outputs = self.model(inputs, training=True)
loss = self.calculate_loss_metrics(inputs, outputs)
self.calculate_accuracy_metrics(inputs, outputs, self.train_metrics)
grads = tape.gradient(loss, self.model.trainable_variables)
self.current_optimizer.apply_gradients(
zip(grads, self.model.trainable_variables))
self.current_step.assign_add(1)
self.strategy.run(step_fn, args=(next(iterator),))
def train_loop_end(self):
"""A train loop is similar with the concept of an epoch."""
if self.mode == DistillationMode.END2END:
# Save the exported checkpoint (used for downstreaming tasks) after every
# 'checkpoint_interval' steps. And only export checkpoints after entering
# e2e distillation training stage.
if self.exported_ckpt_manager is None:
self.build_exported_ckpt_manager()
self.exported_ckpt_manager.save(
checkpoint_number=self.current_step.numpy(),
check_interval=True)
return {
'feature_transfer_mse':
self.train_metrics['feature_transfer_mse'].result(),
'beta_transfer_loss':
self.train_metrics['beta_transfer_loss'].result(),
'gamma_transfer_loss':
self.train_metrics['gamma_transfer_loss'].result(),
'attention_transfer_loss':
self.train_metrics['attention_transfer_loss'].result(),
'total_loss':
self.train_metrics['total_loss'].result(),
'lm_example_loss':
self.train_metrics['lm_example_loss'].result(),
'next_sentence_loss':
self.train_metrics['next_sentence_loss'].result(),
'masked_lm_accuracy':
self.train_metrics['masked_lm_accuracy'].result(),
'next_sentence_accuracy':
self.train_metrics['next_sentence_accuracy'].result(),
'learning_rate':
self.current_optimizer.learning_rate(
self.current_optimizer.iterations),
'current_step':
self.current_step,
'optimizer_step':
self.current_optimizer.iterations,
}
# TODO(longy): We only run evaluation on downstream tasks.
def eval_begin(self):
self.eval_metrics['masked_lm_accuracy'].reset_states()
self.eval_metrics['next_sentence_accuracy'].reset_states()
def eval_step(self, iterator):
def step_fn(inputs):
outputs = self.model(inputs, training=False)
self.calculate_accuracy_metrics(inputs, outputs, self.eval_metrics)
self.strategy.run(step_fn, args=(next(iterator),))
def eval_end(self):
return {'masked_lm_accuracy':
self.eval_metrics['masked_lm_accuracy'].result(),
'next_sentence_accuracy':
self.eval_metrics['next_sentence_accuracy'].result()}
| 23,030 | 43.290385 | 99 | py |
models | models-master/official/projects/edgetpu/nlp/serving/export_tflite_squad_test.py | # Copyright 2023 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.
"""Tests for export_tflite_squad."""
import tensorflow as tf
from official.nlp.modeling import models
from official.projects.edgetpu.nlp.configs import params
from official.projects.edgetpu.nlp.modeling import model_builder
from official.projects.edgetpu.nlp.serving import export_tflite_squad
class ExportTfliteSquadTest(tf.test.TestCase):
def setUp(self):
super(ExportTfliteSquadTest, self).setUp()
experiment_params = params.EdgeTPUBERTCustomParams()
pretrainer_model = model_builder.build_bert_pretrainer(
experiment_params.student_model, name='pretrainer')
encoder_network = pretrainer_model.encoder_network
self.span_labeler = models.BertSpanLabeler(
network=encoder_network,
initializer=tf.keras.initializers.TruncatedNormal(stddev=0.01))
def test_model_input_output(self):
test_model = export_tflite_squad.build_model_for_serving(self.span_labeler)
# Test model input order, names, and shape.
self.assertEqual(test_model.input[0].name, 'input_word_ids')
self.assertEqual(test_model.input[1].name, 'input_type_ids')
self.assertEqual(test_model.input[2].name, 'input_mask')
self.assertEqual(test_model.input[0].shape, (1, 384))
self.assertEqual(test_model.input[1].shape, (1, 384))
self.assertEqual(test_model.input[2].shape, (1, 384))
# Test model output order, name, and shape.
self.assertEqual(test_model.output[0].name, 'start_positions/Identity:0')
self.assertEqual(test_model.output[1].name, 'end_positions/Identity:0')
self.assertEqual(test_model.output[0].shape, (1, 384))
self.assertEqual(test_model.output[1].shape, (1, 384))
if __name__ == '__main__':
tf.test.main()
| 2,306 | 38.775862 | 79 | py |
models | models-master/official/projects/edgetpu/nlp/serving/export_tflite_squad.py | # Copyright 2023 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.
# pylint: disable=line-too-long
r"""Export tflite for MobileBERT-EdgeTPU with SQUAD head.
Example usage:
python3 export_tflite_squad.py \
--config_file=official/projects/edgetpu/nlp/experiments/mobilebert_edgetpu_xs.yaml \
--export_path=/tmp/ \
--quantization_method=full-integer
"""
# pylint: enable=line-too-long
import os
import tempfile
from typing import Sequence
from absl import app
from absl import flags
from absl import logging
import orbit
import tensorflow as tf
from official.common import flags as tfm_flags
from official.nlp.data import data_loader_factory
from official.nlp.data import question_answering_dataloader
from official.nlp.modeling import models
from official.projects.edgetpu.nlp.configs import params
from official.projects.edgetpu.nlp.modeling import model_builder
from official.projects.edgetpu.nlp.utils import utils
FLAGS = flags.FLAGS
SQUAD_TRAIN_SPLIT = 'gs://**/tp/bert/squad_v1.1/train.tf_record'
flags.DEFINE_string('export_path', '/tmp/',
'File path to store tflite model.')
flags.DEFINE_enum('quantization_method', 'float',
['full-integer', 'hybrid', 'float'], 'Quantization method.')
flags.DEFINE_integer('batch_size', 1,
'Fixed batch size for exported TFLite model.')
flags.DEFINE_integer('sequence_length', 384,
'Fixed sequence length.')
flags.DEFINE_string('model_checkpoint', None,
'Checkpoint path for the model. Model will be initialized'
'with random weights if path is None.')
def build_model_for_serving(model: tf.keras.Model,
sequence_length: int = 384,
batch_size: int = 1) -> tf.keras.Model:
"""Builds MLPerf evaluation compatible models.
To run the model on device, the model input/output datatype and node names
need to match the MLPerf setup.
Args:
model: Input keras model.
sequence_length: BERT model sequence length.
batch_size: Inference batch size.
Returns:
Keras model with new input/output nodes.
"""
word_ids = tf.keras.Input(shape=(sequence_length,),
batch_size=batch_size,
dtype=tf.int32,
name='input_word_ids')
mask = tf.keras.Input(shape=(sequence_length,),
batch_size=batch_size,
dtype=tf.int32, name='input_mask')
type_ids = tf.keras.Input(shape=(sequence_length,),
batch_size=batch_size,
dtype=tf.int32, name='input_type_ids')
model_output = model([word_ids, type_ids, mask])
# Use identity layers wrapped in lambdas to explicitly name the output
# tensors.
start_logits = tf.keras.layers.Lambda(
tf.identity, name='start_positions')(
model_output[0])
end_logits = tf.keras.layers.Lambda(
tf.identity, name='end_positions')(
model_output[1])
model = tf.keras.Model(
inputs=[word_ids, type_ids, mask],
outputs=[start_logits, end_logits])
return model
def build_inputs(data_params, input_context=None):
"""Returns tf.data.Dataset for sentence_prediction task."""
return data_loader_factory.get_data_loader(data_params).load(input_context)
def main(argv: Sequence[str]) -> None:
if len(argv) > 1:
raise app.UsageError('Too many command-line arguments.')
# Set up experiment params and load the configs from file/files.
experiment_params = params.EdgeTPUBERTCustomParams()
experiment_params = utils.config_override(experiment_params, FLAGS)
# change the input mask type to tf.float32 to avoid additional casting op.
experiment_params.student_model.encoder.mobilebert.input_mask_dtype = 'float32'
# Experiments indicate using -120 as the mask value for Softmax is good enough
# for both int8 and bfloat. So we set quantization_friendly to True for both
# quant and float model.
pretrainer_model = model_builder.build_bert_pretrainer(
experiment_params.student_model,
name='pretrainer',
quantization_friendly=True)
encoder_network = pretrainer_model.encoder_network
model = models.BertSpanLabeler(
network=encoder_network,
initializer=tf.keras.initializers.TruncatedNormal(stddev=0.01))
# Load model weights.
if FLAGS.model_checkpoint is not None:
checkpoint_dict = {'model': model}
checkpoint = tf.train.Checkpoint(**checkpoint_dict)
checkpoint.restore(FLAGS.model_checkpoint).assert_existing_objects_matched()
model_for_serving = build_model_for_serving(model, FLAGS.sequence_length,
FLAGS.batch_size)
model_for_serving.summary()
# TODO(b/194449109): Need to save the model to file and then convert tflite
# with 'tf.lite.TFLiteConverter.from_saved_model()' to get the expected
# accuracy
tmp_dir = tempfile.TemporaryDirectory().name
model_for_serving.save(tmp_dir)
def _representative_dataset():
dataset_params = question_answering_dataloader.QADataConfig()
dataset_params.input_path = SQUAD_TRAIN_SPLIT
dataset_params.drop_remainder = False
dataset_params.global_batch_size = 1
dataset_params.is_training = True
dataset = orbit.utils.make_distributed_dataset(tf.distribute.get_strategy(),
build_inputs, dataset_params)
for example in dataset.take(100):
inputs = example[0]
input_word_ids = inputs['input_word_ids']
input_mask = inputs['input_mask']
input_type_ids = inputs['input_type_ids']
yield [input_word_ids, input_mask, input_type_ids]
converter = tf.lite.TFLiteConverter.from_saved_model(tmp_dir)
if FLAGS.quantization_method in ['full-integer', 'hybrid']:
converter.optimizations = [tf.lite.Optimize.DEFAULT]
if FLAGS.quantization_method in ['full-integer']:
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8
converter.inference_output_type = tf.float32
converter.representative_dataset = _representative_dataset
tflite_quant_model = converter.convert()
export_model_path = os.path.join(FLAGS.export_path, 'model.tflite')
with tf.io.gfile.GFile(export_model_path, 'wb') as f:
f.write(tflite_quant_model)
logging.info('Successfully save the tflite to %s', FLAGS.export_path)
if __name__ == '__main__':
tfm_flags.define_flags()
app.run(main)
| 7,070 | 37.639344 | 84 | py |
models | models-master/official/projects/edgetpu/nlp/serving/__init__.py | # Copyright 2023 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.
| 609 | 39.666667 | 74 | py |
models | models-master/official/projects/edgetpu/nlp/configs/__init__.py | # Copyright 2023 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.
| 609 | 39.666667 | 74 | py |
models | models-master/official/projects/edgetpu/nlp/configs/params.py | # Copyright 2023 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.
"""Datastructures for all the configurations for MobileBERT-EdgeTPU training."""
import dataclasses
from typing import Optional
from official.modeling import optimization
from official.modeling.hyperparams import base_config
from official.nlp.configs import bert
from official.nlp.data import pretrain_dataloader
DatasetParams = pretrain_dataloader.BertPretrainDataConfig
PretrainerModelParams = bert.PretrainerConfig
@dataclasses.dataclass
class OrbitParams(base_config.Config):
"""Parameters that setup Orbit training/evaluation pipeline.
Attributes:
mode: Orbit controller mode, can be 'train', 'train_and_evaluate', or
'evaluate'.
steps_per_loop: The number of steps to run in each inner loop of training.
total_steps: The global step count to train up to.
eval_steps: The number of steps to run during an evaluation. If -1, this
method will evaluate over the entire evaluation dataset.
eval_interval: The number of training steps to run between evaluations. If
set, training will always stop every `eval_interval` steps, even if this
results in a shorter inner loop than specified by `steps_per_loop`
setting. If None, evaluation will only be performed after training is
complete.
"""
mode: str = 'train'
steps_per_loop: int = 1000
total_steps: int = 1000000
eval_steps: int = -1
eval_interval: Optional[int] = None
@dataclasses.dataclass
class OptimizerParams(optimization.OptimizationConfig):
"""Optimizer parameters for MobileBERT-EdgeTPU."""
optimizer: optimization.OptimizerConfig = dataclasses.field(
default_factory=lambda: optimization.OptimizerConfig( # pylint: disable=g-long-lambda
type='adamw',
adamw=optimization.AdamWeightDecayConfig(
weight_decay_rate=0.01,
exclude_from_weight_decay=['LayerNorm', 'layer_norm', 'bias'],
),
)
)
learning_rate: optimization.LrConfig = dataclasses.field(
default_factory=lambda: optimization.LrConfig( # pylint: disable=g-long-lambda
type='polynomial',
polynomial=optimization.PolynomialLrConfig(
initial_learning_rate=1e-4,
decay_steps=1000000,
end_learning_rate=0.0,
),
)
)
warmup: optimization.WarmupConfig = dataclasses.field(
default_factory=lambda: optimization.WarmupConfig( # pylint: disable=g-long-lambda
type='polynomial',
polynomial=optimization.PolynomialWarmupConfig(warmup_steps=10000),
)
)
@dataclasses.dataclass
class RuntimeParams(base_config.Config):
"""Parameters that set up the training runtime.
TODO(longy): Can reuse the Runtime Config in:
official/core/config_definitions.py
Attributes
distribution_strategy: Keras distribution strategy
use_gpu: Whether to use GPU
use_tpu: Whether to use TPU
num_gpus: Number of gpus to use for training
num_workers: Number of parallel workers
tpu_address: The bns address of the TPU to use.
"""
distribution_strategy: str = 'off'
num_gpus: Optional[int] = 0
all_reduce_alg: Optional[str] = None
num_workers: int = 1
tpu_address: str = ''
use_gpu: Optional[bool] = None
use_tpu: Optional[bool] = None
@dataclasses.dataclass
class LayerWiseDistillationParams(base_config.Config):
"""Define the behavior of layer-wise distillation.
Layer-wise distillation is an optional step where the knowledge is transferred
layerwisely for all the transformer layers. The end-to-end distillation is
performed after layer-wise distillation if layer-wise distillation steps is
not zero.
"""
num_steps: int = 10000
warmup_steps: int = 10000
initial_learning_rate: float = 1.5e-3
end_learning_rate: float = 1.5e-3
decay_steps: int = 10000
hidden_distill_factor: float = 100.0
beta_distill_factor: float = 5000.0
gamma_distill_factor: float = 5.0
attention_distill_factor: float = 1.0
@dataclasses.dataclass
class EndToEndDistillationParams(base_config.Config):
"""Define the behavior of end2end pretrainer distillation."""
num_steps: int = 580000
warmup_steps: int = 20000
initial_learning_rate: float = 1.5e-3
end_learning_rate: float = 1.5e-7
decay_steps: int = 580000
distill_ground_truth_ratio: float = 0.5
@dataclasses.dataclass
class EdgeTPUBERTCustomParams(base_config.Config):
"""EdgeTPU-BERT custom params.
Attributes:
train_dataset: An instance of the DatasetParams.
eval_dataset: An instance of the DatasetParams.
teacher_model: An instance of the PretrainerModelParams. If None, then the
student model is trained independently without distillation.
student_model: An instance of the PretrainerModelParams
teacher_model_init_checkpoint: Path for the teacher model init checkpoint.
student_model_init_checkpoint: Path for the student model init checkpoint.
layer_wise_distillation: Distillation config for the layer-wise step.
end_to_end_distillation: Distillation config for the end2end step.
optimizer: An instance of the OptimizerParams.
runtime: An instance of the RuntimeParams.
learning_rate: An instance of the LearningRateParams.
orbit_config: An instance of the OrbitParams.
distill_ground_truth_ratio: A float number representing the ratio between
distillation output and ground truth.
"""
train_datasest: DatasetParams = dataclasses.field(
default_factory=DatasetParams
)
eval_dataset: DatasetParams = dataclasses.field(default_factory=DatasetParams)
teacher_model: Optional[PretrainerModelParams] = dataclasses.field(
default_factory=PretrainerModelParams
)
student_model: PretrainerModelParams = dataclasses.field(
default_factory=PretrainerModelParams
)
teacher_model_init_checkpoint: str = ''
student_model_init_checkpoint: str = ''
layer_wise_distillation: LayerWiseDistillationParams = dataclasses.field(
default_factory=LayerWiseDistillationParams
)
end_to_end_distillation: EndToEndDistillationParams = dataclasses.field(
default_factory=EndToEndDistillationParams
)
optimizer: OptimizerParams = dataclasses.field(
default_factory=OptimizerParams
)
runtime: RuntimeParams = dataclasses.field(default_factory=RuntimeParams)
orbit_config: OrbitParams = dataclasses.field(default_factory=OrbitParams)
| 6,952 | 37.414365 | 92 | py |
models | models-master/official/projects/edgetpu/nlp/utils/utils.py | # Copyright 2023 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.
"""Utility functions."""
import os
import pprint
from absl import logging
import tensorflow as tf
from official.modeling import hyperparams
from official.projects.edgetpu.nlp.configs import params
def serialize_config(experiment_params: params.EdgeTPUBERTCustomParams,
model_dir: str):
"""Serializes and saves the experiment config."""
params_save_path = os.path.join(model_dir, 'params.yaml')
logging.info('Saving experiment configuration to %s', params_save_path)
tf.io.gfile.makedirs(model_dir)
hyperparams.save_params_dict_to_yaml(experiment_params, params_save_path)
# Note: Do not call this utility function unless you load the `flags`
# module in your script.
def config_override(experiment_params, flags_obj):
"""Overrides ExperimentConfig according to flags."""
if not hasattr(flags_obj, 'tpu'):
raise ModuleNotFoundError(
'`tpu` is not found in FLAGS. Need to load flags.py first.')
# Change runtime.tpu to the real tpu.
experiment_params.override({
'runtime': {
'tpu_address': flags_obj.tpu,
}
})
# Get the first level of override from `--config_file`.
# `--config_file` is typically used as a template that specifies the common
# override for a particular experiment.
for config_file in flags_obj.config_file or []:
experiment_params = hyperparams.override_params_dict(
experiment_params, config_file, is_strict=True)
# Get the second level of override from `--params_override`.
# `--params_override` is typically used as a further override over the
# template. For example, one may define a particular template for training
# ResNet50 on ImageNet in a config file and pass it via `--config_file`,
# then define different learning rates and pass it via `--params_override`.
if flags_obj.params_override:
experiment_params = hyperparams.override_params_dict(
experiment_params, flags_obj.params_override, is_strict=True)
experiment_params.validate()
experiment_params.lock()
pp = pprint.PrettyPrinter()
logging.info('Final experiment parameters: %s',
pp.pformat(experiment_params.as_dict()))
model_dir = get_model_dir(experiment_params, flags_obj)
if flags_obj.mode is not None:
if 'train' in flags_obj.mode:
# Pure eval modes do not output yaml files. Otherwise continuous eval job
# may race against the train job for writing the same file.
serialize_config(experiment_params, model_dir)
return experiment_params
def get_model_dir(experiment_params, flags_obj):
"""Gets model dir from Flags."""
del experiment_params
return flags_obj.model_dir
def load_checkpoint(model: tf.keras.Model, ckpt_path: str):
"""Initializes model with the checkpoint."""
ckpt_dir_or_file = ckpt_path
if tf.io.gfile.isdir(ckpt_dir_or_file):
ckpt_dir_or_file = tf.train.latest_checkpoint(ckpt_dir_or_file)
# Makes sure the pretrainer variables are created.
_ = model(model.inputs)
checkpoint = tf.train.Checkpoint(
**model.checkpoint_items)
checkpoint.read(ckpt_dir_or_file).expect_partial()
logging.info('Successfully load parameters for %s model', model.name)
| 3,792 | 36.554455 | 79 | py |
models | models-master/official/projects/edgetpu/nlp/utils/__init__.py | # Copyright 2023 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.
| 609 | 39.666667 | 74 | py |
models | models-master/official/projects/edgetpu/nlp/utils/utils_test.py | # Copyright 2023 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.
"""Tests for utils.py."""
from absl import flags
import tensorflow as tf
from official.projects.edgetpu.nlp.configs import params
from official.projects.edgetpu.nlp.modeling import model_builder
from official.projects.edgetpu.nlp.utils import utils
FLAGS = flags.FLAGS
# Helper function to compare two nested Dicts.
# Note that this function only ensures all the fields in dict_a have definition
# and same value in dict_b. This function does not guarantee that
# dict_a == dict_b.
def nested_dict_compare(dict_a, dict_b):
for k, v in sorted(dict_a.items()):
if k not in dict_b:
return False
if isinstance(v, dict) and isinstance(dict_b[k], dict):
if not nested_dict_compare(dict_a[k], dict_b[k]):
return False
else:
# A caveat: When dict_a[k] = 1, dict_b[k] = True, the return is True.
if dict_a[k] != dict_b[k]:
return False
return True
class UtilsTest(tf.test.TestCase):
def test_config_override(self):
# Define several dummy flags which are call by the utils.config_override
# function.
flags.DEFINE_string('tpu', None, 'tpu_address.')
flags.DEFINE_list('config_file', [],
'A list of config files path.')
flags.DEFINE_string('params_override',
'orbit_config.mode=eval', 'Override params.')
flags.DEFINE_string('model_dir', '/tmp/', 'Model saving directory.')
flags.DEFINE_list('mode', ['train'], 'Job mode.')
flags.DEFINE_bool('use_vizier', False,
'Whether to enable vizier based hyperparameter search.')
experiment_params = params.EdgeTPUBERTCustomParams()
# By default, the orbit is set with train mode.
self.assertEqual(experiment_params.orbit_config.mode, 'train')
# Config override should set the orbit to eval mode.
experiment_params = utils.config_override(experiment_params, FLAGS)
self.assertEqual(experiment_params.orbit_config.mode, 'eval')
def test_load_checkpoint(self):
"""Test the pretrained model can be successfully loaded."""
experiment_params = params.EdgeTPUBERTCustomParams()
student_pretrainer = experiment_params.student_model
student_pretrainer.encoder.type = 'mobilebert'
pretrainer = model_builder.build_bert_pretrainer(
pretrainer_cfg=student_pretrainer,
name='test_model')
# Makes sure the pretrainer variables are created.
checkpoint_path = self.create_tempfile().full_path
_ = pretrainer(pretrainer.inputs)
pretrainer.save_weights(checkpoint_path)
utils.load_checkpoint(pretrainer, checkpoint_path)
if __name__ == '__main__':
tf.test.main()
| 3,238 | 37.559524 | 79 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.