Spaces:
Running
on
Zero
Running
on
Zero
File size: 9,988 Bytes
4450790 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 |
# Copyright 2022 Google LLC
# 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
# https://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.
# ==============================================================================
"""Loss functions used to train the FILM interpolation model.
The losses for training and test loops are configurable via gin. Training can
use more than one loss function. Test loop can also evaluate one ore more loss
functions, each of which can be summarized separately.
"""
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple
from . import vgg19_loss as vgg19
import gin.tf
import numpy as np
import tensorflow as tf
@gin.configurable('vgg', denylist=['example', 'prediction'])
def vgg_loss(example: Mapping[str, tf.Tensor],
prediction: Mapping[str, tf.Tensor],
vgg_model_file: str,
weights: Optional[List[float]] = None) -> tf.Tensor:
"""Perceptual loss for images in [0,1] color range.
Args:
example: A dictionary with the ground truth image as 'y'.
prediction: The prediction dictionary with the image as 'image'.
vgg_model_file: The path containing the vgg19 weights in MATLAB format.
weights: An optional array of weights for different VGG layers. If None, the
default weights are used (see vgg19.vgg_loss documentation).
Returns:
The perceptual loss.
"""
return vgg19.vgg_loss(prediction['image'], example['y'], vgg_model_file,
weights)
@gin.configurable('style', denylist=['example', 'prediction'])
def style_loss(example: Mapping[str, tf.Tensor],
prediction: Mapping[str, tf.Tensor],
vgg_model_file: str,
weights: Optional[List[float]] = None) -> tf.Tensor:
"""Computes style loss from images in [0..1] color range.
Args:
example: A dictionary with the ground truth image as 'y'.
prediction: The prediction dictionary with the image as 'image'.
vgg_model_file: The path containing the vgg19 weights in MATLAB format.
weights: An optional array of weights for different VGG layers. If None, the
default weights are used (see vgg19.vgg_loss documentation).
Returns:
A tf.Tensor of a scalar representing the style loss computed over multiple
vgg layer features.
"""
return vgg19.style_loss(prediction['image'], example['y'], vgg_model_file,
weights)
def l1_loss(example: Mapping[str, tf.Tensor],
prediction: Mapping[str, tf.Tensor]) -> tf.Tensor:
return tf.reduce_mean(tf.abs(prediction['image'] - example['y']))
def l1_warped_loss(example: Mapping[str, tf.Tensor],
prediction: Mapping[str, tf.Tensor]) -> tf.Tensor:
"""Computes an l1 loss using only warped images.
Args:
example: A dictionary with the ground truth image as 'y'.
prediction: The prediction dictionary with the image(s) as 'x0_warped'
and/or 'x1_warped'.
Returns:
A tf.Tensor of a scalar representing the linear combination of l1 losses
between prediction images and y.
"""
loss = tf.constant(0.0, dtype=tf.float32)
if 'x0_warped' in prediction:
loss += tf.reduce_mean(tf.abs(prediction['x0_warped'] - example['y']))
if 'x1_warped' in prediction:
loss += tf.reduce_mean(tf.abs(prediction['x1_warped'] - example['y']))
return loss
def l2_loss(example: Mapping[str, tf.Tensor],
prediction: Mapping[str, tf.Tensor]) -> tf.Tensor:
return tf.reduce_mean(tf.square(prediction['image'] - example['y']))
def ssim_loss(example: Mapping[str, tf.Tensor],
prediction: Mapping[str, tf.Tensor]) -> tf.Tensor:
image = prediction['image']
y = example['y']
return tf.reduce_mean(tf.image.ssim(image, y, max_val=1.0))
def psnr_loss(example: Mapping[str, tf.Tensor],
prediction: Mapping[str, tf.Tensor]) -> tf.Tensor:
return tf.reduce_mean(
tf.image.psnr(prediction['image'], example['y'], max_val=1.0))
def get_loss(loss_name: str) -> Callable[[Any, Any], tf.Tensor]:
"""Returns the loss function corresponding to the given name."""
if loss_name == 'l1':
return l1_loss
elif loss_name == 'l2':
return l2_loss
elif loss_name == 'ssim':
return ssim_loss
elif loss_name == 'vgg':
return vgg_loss
elif loss_name == 'style':
return style_loss
elif loss_name == 'psnr':
return psnr_loss
elif loss_name == 'l1_warped':
return l1_warped_loss
else:
raise ValueError('Invalid loss function %s' % loss_name)
# pylint: disable=unnecessary-lambda
def get_loss_op(loss_name):
"""Returns a function for creating a loss calculation op."""
loss = get_loss(loss_name)
return lambda example, prediction: loss(example, prediction)
def get_weight_op(weight_schedule):
"""Returns a function for creating an iteration dependent loss weight op."""
return lambda iterations: weight_schedule(iterations)
def create_losses(
loss_names: List[str], loss_weight_schedules: List[
tf.keras.optimizers.schedules.LearningRateSchedule]
) -> Dict[str, Tuple[Callable[[Any, Any], tf.Tensor], Callable[[Any],
tf.Tensor]]]:
"""Returns a dictionary of functions for creating loss and loss_weight ops.
As an example, create_losses(['l1', 'l2'], [PiecewiseConstantDecay(),
PiecewiseConstantDecay()]) returns a dictionary with two keys, and each value
being a tuple of ops for loss calculation and loss_weight sampling.
Args:
loss_names: Names of the losses.
loss_weight_schedules: Instances of loss weight schedules.
Returns:
A dictionary that contains the loss and weight schedule ops keyed by the
names.
"""
losses = dict()
for name, weight_schedule in zip(loss_names, loss_weight_schedules):
unique_values = np.unique(weight_schedule.values)
if len(unique_values) == 1 and unique_values[0] == 1.0:
# Special case 'no weight' for prettier TensorBoard summaries.
weighted_name = name
else:
# Weights are variable/scheduled, a constant "k" is used to
# indicate weights are iteration dependent.
weighted_name = 'k*' + name
losses[weighted_name] = (get_loss_op(name), get_weight_op(weight_schedule))
return losses
@gin.configurable
def training_losses(
loss_names: List[str],
loss_weights: Optional[List[float]] = None,
loss_weight_schedules: Optional[List[
tf.keras.optimizers.schedules.LearningRateSchedule]] = None,
loss_weight_parameters: Optional[List[Mapping[str, List[Any]]]] = None
) -> Mapping[str, Tuple[Callable[[Any, Any], tf.Tensor], Callable[[Any],
tf.Tensor]]]:
"""Creates the training loss functions and loss weight schedules."""
weight_schedules = []
if not loss_weights:
for weight_schedule, weight_parameters in zip(loss_weight_schedules,
loss_weight_parameters):
weight_schedules.append(weight_schedule(**weight_parameters))
else:
for loss_weight in loss_weights:
weight_parameters = {
'boundaries': [0],
'values': 2 * [
loss_weight,
]
}
weight_schedules.append(
tf.keras.optimizers.schedules.PiecewiseConstantDecay(
**weight_parameters))
return create_losses(loss_names, weight_schedules)
@gin.configurable
def test_losses(
loss_names: List[str],
loss_weights: Optional[List[float]] = None,
loss_weight_schedules: Optional[List[
tf.keras.optimizers.schedules.LearningRateSchedule]] = None,
loss_weight_parameters: Optional[List[Mapping[str, List[Any]]]] = None
) -> Mapping[str, Tuple[Callable[[Any, Any], tf.Tensor], Callable[[Any],
tf.Tensor]]]:
"""Creates the test loss functions and loss weight schedules."""
weight_schedules = []
if not loss_weights:
for weight_schedule, weight_parameters in zip(loss_weight_schedules,
loss_weight_parameters):
weight_schedules.append(weight_schedule(**weight_parameters))
else:
for loss_weight in loss_weights:
weight_parameters = {
'boundaries': [0],
'values': 2 * [
loss_weight,
]
}
weight_schedules.append(
tf.keras.optimizers.schedules.PiecewiseConstantDecay(
**weight_parameters))
return create_losses(loss_names, weight_schedules)
def aggregate_batch_losses(
batch_losses: List[Mapping[str, float]]) -> Mapping[str, float]:
"""Averages per batch losses into single dictionary for the whole epoch.
As an example, if the batch_losses contained per batch losses:
batch_losses = { {'l1': 0.2, 'ssim': 0.9}, {'l1': 0.3, 'ssim': 0.8}}
The returned dictionary would look like: { 'l1': 0.25, 'ssim': 0.95 }
Args:
batch_losses: A list of dictionary objects, with one entry for each loss.
Returns:
Single dictionary with the losses aggregated.
"""
transp_losses = {}
# Loop through all losses
for batch_loss in batch_losses:
# Loop through per batch losses of a single type:
for loss_name, loss in batch_loss.items():
if loss_name not in transp_losses:
transp_losses[loss_name] = []
transp_losses[loss_name].append(loss)
aggregate_losses = {}
for loss_name in transp_losses:
aggregate_losses[loss_name] = np.mean(transp_losses[loss_name])
return aggregate_losses
|