text
stringlengths 5
261k
| id
stringlengths 16
106
| metadata
dict | __index_level_0__
int64 0
266
|
---|---|---|---|
# node shell/generate_json.js
gh api -H "Accept: application/vnd.github+json" /repos/keras-team/keras-tuner/contributors --paginate > response.json
sed "s/\]\[/,/g" response.json > contributors.json
rm response.json
mkdir avatars
python shell/contributors.py avatars > docs/contributors.svg
rm contributors.json
rm -rf avatars
| keras-tuner/shell/contributors.sh/0 | {
"file_path": "keras-tuner/shell/contributors.sh",
"repo_id": "keras-tuner",
"token_count": 115
} | 143 |
import types
import jax
import jax.experimental.sparse as jax_sparse
import jax.numpy as jnp
import ml_dtypes
import numpy as np
import tree
from jax.tree_util import Partial
from keras.backend.common import KerasVariable
from keras.backend.common import global_state
from keras.backend.common import standardize_dtype
from keras.backend.common.keras_tensor import KerasTensor
from keras.backend.common.stateless_scope import StatelessScope
from keras.backend.jax import distribution_lib
SUPPORTS_SPARSE_TENSORS = True
class Variable(KerasVariable):
def _initialize(self, value):
value = jnp.array(value, dtype=self._dtype)
# Note that variable.shape is needed by distribution_lib
self._shape = tuple(value.shape)
# We can't import the keras/distribution/distribution_lib
# due to circular dependency.
distribution = global_state.get_global_attribute("distribution")
if distribution is not None:
self._layout = distribution_lib._to_jax_layout(
distribution.get_variable_layout(self)
)
else:
self._layout = None
self._direct_assign(value)
def _direct_assign(self, value):
if getattr(self, "_layout", None) is not None:
value = distribution_lib.distribute_variable(value, self._layout)
self._value = value
def _convert_to_tensor(self, value, dtype=None):
return convert_to_tensor(value, dtype=dtype, sparse=False)
# Overload native accessor.
def __jax_array__(self):
return self.value
def convert_to_tensor(x, dtype=None, sparse=True):
if dtype is not None:
dtype = standardize_dtype(dtype)
if isinstance(x, (jnp.ndarray, jax.Array)) and dtype == x.dtype:
# Skip the conversion early if the instance is already a JAX array.
# This is important in the multi-process context since jax.array(x) for
# an existing distributed jax array will raise error.
return x
if isinstance(x, Variable):
if dtype and dtype != x.dtype:
return x.value.astype(dtype)
return x.value
if isinstance(x, jax_sparse.JAXSparse):
if sparse is not None and not sparse:
x = x.todense()
elif dtype and dtype != x.dtype:
return x.astype(dtype)
else:
return x
if not is_tensor(x) and standardize_dtype(dtype) == "bfloat16":
# Can't create bfloat16 arrays on the fly (e.g. from a h5 Dataset).
# Instead we convert "as is" (to stored dtype) and cast.
return jnp.asarray(x).astype(dtype)
return jnp.asarray(x, dtype=dtype)
def convert_to_numpy(x):
if isinstance(x, jax_sparse.JAXSparse):
x = x.todense()
if is_tensor(x) and x.dtype == "bfloat16":
return np.asarray(x, ml_dtypes.bfloat16)
return np.asarray(x)
def is_tensor(x):
if isinstance(x, (jnp.ndarray, jax_sparse.JAXSparse)):
return True
return False
def shape(x):
# This will work as long as we disallow
# dynamic shapes in JAX.
return x.shape
def cast(x, dtype):
return convert_to_tensor(x, dtype=dtype)
# Shape / dtype / sparseness inference util
def compute_output_spec(fn, *args, **kwargs):
with StatelessScope():
built_in_types = (type(None), int, float, str, bool, complex, bytes)
# First, separate symbolic args from other args
static_args_idx = []
static_args = []
maybe_symbolic_args = []
static_kwargs = {}
maybe_symbolic_kwargs = {}
for idx, arg in enumerate(args):
if isinstance(arg, built_in_types):
static_args_idx.append(idx)
static_args.append(arg)
else:
maybe_symbolic_args.append(arg)
maybe_symbolic_args = tuple(maybe_symbolic_args)
for k, v in kwargs.items():
if isinstance(v, built_in_types):
static_kwargs[k] = v
else:
maybe_symbolic_kwargs[k] = v
# Second, find out if there are dynamic shapes
has_none = False
for x in tree.flatten((maybe_symbolic_args, maybe_symbolic_kwargs)):
if isinstance(x, KerasTensor) and any(d is None for d in x.shape):
has_none = True
def convert_keras_tensor_to_jax(x, fill_value=None):
if isinstance(x, KerasTensor):
shape = list(x.shape)
if fill_value:
for i, e in enumerate(shape):
if e is None:
shape[i] = fill_value
jax_tensor = jax.ShapeDtypeStruct(shape, dtype=x.dtype)
return jax_tensor
if isinstance(x, types.FunctionType):
def _fn(*args, **kwargs):
out = x(*args, **kwargs)
out = convert_keras_tensor_to_jax(
out, fill_value=fill_value
)
return out
return Partial(_fn)
if isinstance(x, dict):
return {
k: convert_keras_tensor_to_jax(v, fill_value=fill_value)
for k, v in x.items()
}
if isinstance(x, list):
return [
convert_keras_tensor_to_jax(xi, fill_value=fill_value)
for xi in x
]
return x
def wrapped_fn(*args, **kwargs):
# Turn inputs that are sparse to BCOO tensors
def to_bcoo_if_sparse(x, maybe_symbolic_x):
if (
isinstance(maybe_symbolic_x, KerasTensor)
and maybe_symbolic_x.sparse
):
return jax_sparse.BCOO.fromdense(x, nse=1)
return x
args, kwargs = tree.map_structure(
to_bcoo_if_sparse,
(args, kwargs),
(maybe_symbolic_args, maybe_symbolic_kwargs),
)
rec_args = []
idx_static = 0
idx_sym = 0
i = 0
while idx_static < len(static_args) or idx_sym < len(args):
if i in static_args_idx:
rec_args.append(static_args[idx_static])
idx_static += 1
else:
rec_args.append(args[idx_sym])
idx_sym += 1
i += 1
with StatelessScope():
return fn(*rec_args, **kwargs, **static_kwargs)
output_spec = None
if has_none:
try:
ms_args_1, ms_kwargs_1 = tree.map_structure(
lambda x: convert_keras_tensor_to_jax(x, fill_value=83),
(maybe_symbolic_args, maybe_symbolic_kwargs),
)
_, jax_out_1 = jax.make_jaxpr(wrapped_fn, return_shape=True)(
*ms_args_1, **ms_kwargs_1
)
ms_args_2, ms_kwargs_2 = tree.map_structure(
lambda x: convert_keras_tensor_to_jax(x, fill_value=89),
(maybe_symbolic_args, maybe_symbolic_kwargs),
)
_, jax_out_2 = jax.make_jaxpr(wrapped_fn, return_shape=True)(
*ms_args_2, **ms_kwargs_2
)
def merge_shapes(shape1, shape2):
return tuple(
[
d1 if d1 == d2 else None
for d1, d2 in zip(shape1, shape2)
]
)
def convert_jax_specs_to_keras_tensor(x1, x2):
if isinstance(x1, jax.ShapeDtypeStruct):
if not isinstance(x2, jax.ShapeDtypeStruct):
raise ValueError("Indeterministic output ordering.")
return KerasTensor(
merge_shapes(x1.shape, x2.shape), dtype=x1.dtype
)
elif isinstance(x1, jax_sparse.BCOO):
if not isinstance(x2, jax_sparse.BCOO):
raise ValueError("Indeterministic output ordering.")
return KerasTensor(
merge_shapes(x1.shape, x2.shape),
dtype=x1.dtype,
sparse=True,
)
else:
return x1
output_spec = tree.map_structure(
convert_jax_specs_to_keras_tensor, jax_out_1, jax_out_2
)
except Exception as e:
if "[JAX RNG]" in str(e):
raise e
# Errors can happen when the filled dimensions
# are not compatible with the function
# (or when the function contains a bug).
# In such cases we don't want to confuse users
# with random filled dimensions and the like,
# so we rerun a pass on the dynamic shapes,
# which will likely error out when JAX tries to
# validate shapes as fully static.
# The error message will be much easier to understand.
pass
if output_spec is None:
maybe_symbolic_args, maybe_symbolic_kwargs = tree.map_structure(
convert_keras_tensor_to_jax,
(maybe_symbolic_args, maybe_symbolic_kwargs),
)
_, jax_out = jax.make_jaxpr(wrapped_fn, return_shape=True)(
*maybe_symbolic_args, **maybe_symbolic_kwargs
)
def convert_jax_spec_to_keras_tensor(x):
if isinstance(x, jax.ShapeDtypeStruct):
return KerasTensor(x.shape, x.dtype)
elif isinstance(x, jax_sparse.BCOO):
return KerasTensor(x.shape, x.dtype, sparse=True)
return x
output_spec = tree.map_structure(
convert_jax_spec_to_keras_tensor, jax_out
)
return output_spec
def cond(pred, true_fn, false_fn):
return jax.lax.cond(pred, true_fun=true_fn, false_fun=false_fn)
def vectorized_map(function, elements):
return jax.vmap(function)(elements)
def scatter(indices, values, shape):
zeros = jnp.zeros(shape, values.dtype)
key = tuple(jnp.moveaxis(indices, -1, 0))
return zeros.at[key].add(values)
def scatter_update(inputs, indices, updates):
inputs = convert_to_tensor(inputs)
indices = jnp.array(indices)
indices = jnp.transpose(indices)
inputs = inputs.at[tuple(indices)].set(updates)
return inputs
def slice(inputs, start_indices, shape):
return jax.lax.dynamic_slice(inputs, start_indices, shape)
def slice_update(inputs, start_indices, updates):
return jax.lax.dynamic_update_slice(inputs, updates, start_indices)
def while_loop(
cond,
body,
loop_vars,
maximum_iterations=None,
):
is_tuple = isinstance(loop_vars, (tuple, list))
loop_vars = tuple(loop_vars) if is_tuple else (loop_vars,)
if maximum_iterations is not None:
current_iter = 0
loop_vars = loop_vars + (current_iter,)
# Unpack list/tuple args. The last argument is `current_iter`.
def _cond(args):
return cond(*args[:-1]) & (args[-1] < maximum_iterations)
def _body(args):
outputs = body(*args[:-1])
outputs = tuple(outputs) if is_tuple else (outputs,)
return outputs + (args[-1] + 1,)
else:
def _cond(args):
return cond(*args)
def _body(args):
outputs = body(*args)
return tuple(outputs) if is_tuple else (outputs,)
outputs = jax.lax.while_loop(_cond, _body, loop_vars)
if maximum_iterations is not None:
outputs = outputs[:-1]
return outputs if is_tuple else outputs[0]
def fori_loop(lower, upper, body_fun, init_val):
return jax.lax.fori_loop(lower, upper, body_fun, init_val)
def stop_gradient(variable):
return jax.lax.stop_gradient(variable)
def unstack(x, num=None, axis=0):
return [
jax.lax.index_in_dim(x, i, axis, keepdims=False)
for i in range(x.shape[axis])
]
def device_scope(device_name):
if isinstance(device_name, str):
# We support string value like "cpu:0", "gpu:1", etc.
device_name = device_name.lower()
jax_device = distribution_lib._to_jax_device(device_name)
elif not isinstance(device_name, jax.Device):
raise ValueError(
"Invalid value for argument `device_name`. "
"Expected a string like 'gpu:0' or a `jax.Device` instance. "
f"Received: device_name='{device_name}'"
)
else:
jax_device = device_name
return jax.default_device(jax_device)
| keras/keras/backend/jax/core.py/0 | {
"file_path": "keras/keras/backend/jax/core.py",
"repo_id": "keras",
"token_count": 6684
} | 144 |
import tensorflow as tf
from tensorflow.experimental import numpy as tfnp
from keras.backend import config
from keras.backend import standardize_dtype
from keras.backend.common import dtypes
from keras.backend.tensorflow.core import cast
from keras.backend.tensorflow.core import convert_to_tensor
def segment_sum(data, segment_ids, num_segments=None, sorted=False):
if sorted:
return tf.math.segment_sum(data, segment_ids)
else:
if num_segments is None:
unique_segment_ids, _ = tf.unique(segment_ids)
num_segments = tf.shape(unique_segment_ids)[0]
return tf.math.unsorted_segment_sum(data, segment_ids, num_segments)
def segment_max(data, segment_ids, num_segments=None, sorted=False):
if sorted:
return tf.math.segment_max(data, segment_ids)
else:
if num_segments is None:
unique_segment_ids, _ = tf.unique(segment_ids)
num_segments = tf.shape(unique_segment_ids)[0]
return tf.math.unsorted_segment_max(data, segment_ids, num_segments)
def top_k(x, k, sorted=True):
return tf.math.top_k(x, k, sorted=sorted)
def in_top_k(targets, predictions, k):
return tf.math.in_top_k(targets, predictions, k)
def logsumexp(x, axis=None, keepdims=False):
return tf.math.reduce_logsumexp(x, axis=axis, keepdims=keepdims)
def qr(x, mode="reduced"):
if mode not in {"reduced", "complete"}:
raise ValueError(
"`mode` argument value not supported. "
"Expected one of {'reduced', 'complete'}. "
f"Received: mode={mode}"
)
if mode == "reduced":
return tf.linalg.qr(x)
return tf.linalg.qr(x, full_matrices=True)
def extract_sequences(x, sequence_length, sequence_stride):
return tf.signal.frame(
x,
frame_length=sequence_length,
frame_step=sequence_stride,
axis=-1,
pad_end=False,
)
def _get_complex_tensor_from_tuple(x):
if not isinstance(x, (tuple, list)) or len(x) != 2:
raise ValueError(
"Input `x` should be a tuple of two tensors - real and imaginary."
f"Received: x={x}"
)
# `convert_to_tensor` does not support passing complex tensors. We separate
# the input out into real and imaginary and convert them separately.
real, imag = x
real = convert_to_tensor(real)
imag = convert_to_tensor(imag)
# Check shapes.
if real.shape != imag.shape:
raise ValueError(
"Input `x` should be a tuple of two tensors - real and imaginary."
"Both the real and imaginary parts should have the same shape. "
f"Received: x[0].shape = {real.shape}, x[1].shape = {imag.shape}"
)
# Ensure dtype is float.
if not real.dtype.is_floating or not imag.dtype.is_floating:
raise ValueError(
"At least one tensor in input `x` is not of type float."
f"Received: x={x}."
)
complex_input = tf.dtypes.complex(real, imag)
return complex_input
def fft(x):
complex_input = _get_complex_tensor_from_tuple(x)
complex_output = tf.signal.fft(complex_input)
return tf.math.real(complex_output), tf.math.imag(complex_output)
def fft2(x):
complex_input = _get_complex_tensor_from_tuple(x)
complex_output = tf.signal.fft2d(complex_input)
return tf.math.real(complex_output), tf.math.imag(complex_output)
def rfft(x, fft_length=None):
if fft_length is not None:
fft_length = [fft_length]
complex_output = tf.signal.rfft(x, fft_length=fft_length)
return tf.math.real(complex_output), tf.math.imag(complex_output)
def irfft(x, fft_length=None):
complex_input = _get_complex_tensor_from_tuple(x)
if fft_length is not None:
fft_length = [fft_length]
return tf.signal.irfft(complex_input, fft_length)
def stft(
x, sequence_length, sequence_stride, fft_length, window="hann", center=True
):
if standardize_dtype(x.dtype) not in {"float32", "float64"}:
raise TypeError(
"Invalid input type. Expected `float32` or `float64`. "
f"Received: input type={x.dtype}"
)
if fft_length < sequence_length:
raise ValueError(
"`fft_length` must equal or larger than `sequence_length`. "
f"Received: sequence_length={sequence_length}, "
f"fft_length={fft_length}"
)
if isinstance(window, str):
if window not in {"hann", "hamming"}:
raise ValueError(
"If a string is passed to `window`, it must be one of "
f'`"hann"`, `"hamming"`. Received: window={window}'
)
x = convert_to_tensor(x)
if center:
pad_width = [(0, 0) for _ in range(len(x.shape))]
pad_width[-1] = (fft_length // 2, fft_length // 2)
x = tf.pad(x, pad_width, mode="reflect")
l_pad = (fft_length - sequence_length) // 2
r_pad = fft_length - sequence_length - l_pad
if window is not None:
if isinstance(window, str):
if window == "hann":
win_array = tf.signal.hann_window(
sequence_length, periodic=True, dtype=x.dtype
)
else:
win_array = tf.signal.hamming_window(
sequence_length, periodic=True, dtype=x.dtype
)
else:
win_array = convert_to_tensor(window, dtype=x.dtype)
if len(win_array.shape) != 1 or win_array.shape[-1] != sequence_length:
raise ValueError(
"The shape of `window` must be equal to [sequence_length]."
f"Received: window shape={win_array.shape}"
)
win_array = tf.pad(win_array, [[l_pad, r_pad]])
def win(frame_step, dtype):
return win_array
else:
win = None
result = tf.signal.stft(
x,
frame_length=(sequence_length + l_pad + r_pad),
frame_step=sequence_stride,
fft_length=fft_length,
window_fn=win,
)
return tf.math.real(result), tf.math.imag(result)
def istft(
x,
sequence_length,
sequence_stride,
fft_length,
length=None,
window="hann",
center=True,
):
complex_input = _get_complex_tensor_from_tuple(x)
dtype = tf.math.real(complex_input).dtype
expected_output_len = fft_length + sequence_stride * (
tf.shape(complex_input)[-2] - 1
)
l_pad = (fft_length - sequence_length) // 2
r_pad = fft_length - sequence_length - l_pad
if window is not None:
if isinstance(window, str):
if window == "hann":
win_array = tf.signal.hann_window(
sequence_length, periodic=True, dtype=dtype
)
else:
win_array = tf.signal.hamming_window(
sequence_length, periodic=True, dtype=dtype
)
else:
win_array = convert_to_tensor(window, dtype=dtype)
if len(win_array.shape) != 1 or win_array.shape[-1] != sequence_length:
raise ValueError(
"The shape of `window` must be equal to [sequence_length]."
f"Received: window shape={win_array.shape}"
)
win_array = tf.pad(win_array, [[l_pad, r_pad]])
win = tf.signal.inverse_stft_window_fn(
sequence_stride, lambda frame_step, dtype: win_array
)
else:
win = None
x = tf.signal.inverse_stft(
complex_input,
frame_length=(sequence_length + l_pad + r_pad),
frame_step=sequence_stride,
fft_length=fft_length,
window_fn=win,
)
start = 0 if center is False else fft_length // 2
if length is not None:
end = start + length
elif center is True:
end = -(fft_length // 2)
else:
end = expected_output_len
return x[..., start:end]
def rsqrt(x):
return tf.math.rsqrt(x)
def erf(x):
return tf.math.erf(x)
def erfinv(x):
return tf.math.erfinv(x)
def solve(a, b):
a = convert_to_tensor(a)
b = convert_to_tensor(b)
return tf.linalg.solve(a, b)
def norm(x, ord=None, axis=None, keepdims=False):
x = convert_to_tensor(x)
x_shape = x.shape
ndim = x_shape.rank
if axis is None:
axis = tuple(range(ndim))
elif isinstance(axis, int):
axis = (axis,)
axis = axis[0] if len(axis) == 1 else axis
num_axes = 1 if isinstance(axis, int) else len(axis)
if num_axes == 1 and ord is None:
ord = "euclidean"
elif num_axes == 2 and ord is None:
ord = "fro"
if standardize_dtype(x.dtype) == "int64":
dtype = config.floatx()
else:
dtype = dtypes.result_type(x.dtype, float)
x = cast(x, dtype)
# Fast path to utilze `tf.linalg.norm`
if (num_axes == 1 and ord in ("euclidean", 1, 2, float("inf"))) or (
num_axes == 2 and ord in ("euclidean", "fro", 1, 2, float("inf"))
):
return tf.linalg.norm(x, ord=ord, axis=axis, keepdims=keepdims)
# Ref: jax.numpy.linalg.norm
if num_axes == 1 and ord not in ("fro", "nuc"):
if ord == float("-inf"):
return tf.math.reduce_min(
tf.math.abs(x), axis=axis, keepdims=keepdims
)
elif ord == 0:
return tf.math.reduce_sum(
tf.cast(tf.not_equal(x, 0), dtype=x.dtype),
axis=axis,
keepdims=keepdims,
)
else:
ord = convert_to_tensor(ord, dtype=x.dtype)
out = tf.math.reduce_sum(
tf.pow(tf.math.abs(x), ord), axis=axis, keepdims=keepdims
)
return tf.pow(out, 1.0 / ord)
elif num_axes == 2 and ord in ("nuc", float("-inf"), -2, -1):
row_axis, col_axis = axis[0], axis[1]
row_axis = row_axis + ndim if row_axis < 0 else row_axis
col_axis = col_axis + ndim if col_axis < 0 else col_axis
if ord == float("-inf"):
if not keepdims and row_axis > col_axis:
row_axis -= 1
x = tf.math.reduce_min(
tf.reduce_sum(tf.math.abs(x), axis=col_axis, keepdims=keepdims),
axis=row_axis,
keepdims=keepdims,
)
elif ord == -1:
if not keepdims and col_axis > row_axis:
col_axis -= 1
x = tf.math.reduce_min(
tf.reduce_sum(tf.math.abs(x), axis=row_axis, keepdims=keepdims),
axis=col_axis,
keepdims=keepdims,
)
else:
x = tfnp.moveaxis(x, axis, (-2, -1))
if ord == -2:
x = tf.math.reduce_min(
tf.linalg.svd(x, compute_uv=False), axis=-1
)
else:
x = tf.math.reduce_sum(
tf.linalg.svd(x, compute_uv=False), axis=-1
)
if keepdims:
x = tf.expand_dims(x, axis[0])
x = tf.expand_dims(x, axis[1])
return x
if num_axes == 1:
raise ValueError(
f"Invalid `ord` argument for vector norm. Received: ord={ord}"
)
elif num_axes == 2:
raise ValueError(
f"Invalid `ord` argument for matrix norm. Received: ord={ord}"
)
else:
raise ValueError(f"Invalid axis values. Received: axis={axis}")
| keras/keras/backend/tensorflow/math.py/0 | {
"file_path": "keras/keras/backend/tensorflow/math.py",
"repo_id": "keras",
"token_count": 5614
} | 145 |
import contextlib
import os
import ml_dtypes
import numpy as np
import torch
import tree
from keras.backend.common import KerasVariable
from keras.backend.common import global_state
from keras.backend.common import standardize_dtype
from keras.backend.common.dtypes import result_type
from keras.backend.common.keras_tensor import KerasTensor
from keras.backend.common.stateless_scope import StatelessScope
from keras.backend.config import floatx
from keras.utils.nest import pack_sequence_as
SUPPORTS_SPARSE_TENSORS = False
# Some operators such as 'aten::_foreach_mul_.Scalar'
# are not currently implemented for the MPS device.
# check https://github.com/pytorch/pytorch/issues/77764.
if (
torch.backends.mps.is_available()
and os.getenv("PYTORCH_ENABLE_MPS_FALLBACK") == "1"
):
DEFAULT_DEVICE = "mps"
elif torch.cuda.is_available():
DEFAULT_DEVICE = "cuda"
else:
DEFAULT_DEVICE = "cpu"
TORCH_DTYPES = {
"float16": torch.float16,
"float32": torch.float32,
"float64": torch.float64,
"uint8": torch.uint8,
"uint16": torch.int32, # TODO: Torch doesn't have `uint16` dtype.
"uint32": torch.int64, # TODO: Torch doesn't have `uint32` dtype.
"int8": torch.int8,
"int16": torch.int16,
"int32": torch.int32,
"int64": torch.int64,
"bfloat16": torch.bfloat16,
"bool": torch.bool,
}
@contextlib.contextmanager
def device_scope(device_name):
previous_device = global_state.get_global_attribute("torch_device", None)
current_device = _parse_device_input(device_name)
global_state.set_global_attribute("torch_device", current_device)
try:
yield
finally:
global_state.set_global_attribute("torch_device", previous_device)
def get_device():
device = global_state.get_global_attribute("torch_device", None)
if device is None:
return DEFAULT_DEVICE
return device
def _parse_device_input(device_name):
if isinstance(device_name, str):
# We support string value like "cpu:0", "gpu:1", and need to convert
# "gpu" to "cuda"
device_name = device_name.lower()
if "gpu" in device_name:
device_name = device_name.replace("gpu", "cuda")
else:
raise ValueError(
"Invalid value for argument `device_name`. "
"Expected a string like 'gpu:0' or 'cpu'. "
f"Received: device_name='{device_name}'"
)
# The torch.Device instance can be used directly.
return device_name
def to_torch_dtype(dtype):
standardized_dtype = TORCH_DTYPES.get(standardize_dtype(dtype), None)
if standardized_dtype is None:
raise ValueError(f"Unsupported dtype for PyTorch: {dtype}")
return standardized_dtype
class Variable(KerasVariable):
def _initialize(self, value):
if isinstance(value, torch.nn.Parameter):
# Reuse same parameter
self._value = value
else:
self._value = torch.nn.Parameter(
convert_to_tensor(value, dtype=self._dtype),
requires_grad=self.trainable,
).to(get_device())
def _direct_assign(self, value):
with torch.no_grad():
self.value.copy_(value)
def _convert_to_tensor(self, value, dtype=None):
return convert_to_tensor(value, dtype=dtype)
# Overload native accessor.
@classmethod
def __torch_function__(cls, func, types, args=(), kwargs=None):
args = [
arg.value if isinstance(arg, KerasVariable) else arg for arg in args
]
if kwargs is None:
kwargs = {}
kwargs = {
key: value.value if isinstance(value, KerasVariable) else value
for key, value in kwargs.items()
}
return func(*args, **kwargs)
def __array__(self, dtype=None):
value = convert_to_numpy(self.value)
if dtype:
return value.astype(dtype)
return value
@property
def value(self):
value = super().value
# Create and use a symbolic tensor stub in symbolic calls.
if str(get_device()) == "meta" and str(value.device) != "meta":
return torch.empty(
size=value.shape,
dtype=value.dtype,
device="meta",
)
return value
@property
def trainable(self):
return self._trainable
@trainable.setter
def trainable(self, value):
self._trainable = value
if self._value is not None:
self._value.requires_grad = value
def __eq__(self, other):
try:
return super().__eq__(other)
except Exception:
return False
def convert_to_tensor(x, dtype=None, sparse=None):
if sparse:
raise ValueError("`sparse=True` is not supported with torch backend")
if is_tensor(x):
device = get_device()
if x.device != device:
x = x.to(device)
if dtype is None:
return x
return x.to(to_torch_dtype(dtype))
if isinstance(x, Variable):
# TorchDynamo has bugs supporting nn.Parameter type check.
# Return it directly instead of pass it to the rest of the logic in the
# function.
return x.value
if dtype is None:
if isinstance(x, bool):
return torch.as_tensor(x, dtype=torch.bool, device=get_device())
elif isinstance(x, int):
return torch.as_tensor(x, dtype=torch.int32, device=get_device())
elif isinstance(x, float):
return torch.as_tensor(
x, dtype=to_torch_dtype(floatx()), device=get_device()
)
# Convert to np in case of any array-like that is not list or tuple.
if not isinstance(x, (list, tuple)):
x = np.array(x)
elif len(x) > 0 and any(isinstance(x1, torch.Tensor) for x1 in x):
# Handle list or tuple of torch tensors
return torch.stack([convert_to_tensor(x1) for x1 in x])
if isinstance(x, np.ndarray):
if x.dtype == np.uint32:
# Torch backend does not support uint32.
x = x.astype(np.int64)
if standardize_dtype(x.dtype) == "bfloat16":
# Torch backend does not support converting bfloat16 ndarray.
x = x.astype(np.float32)
dtype = "bfloat16"
dtype = dtype or x.dtype
if dtype is None:
dtype = result_type(
*[getattr(item, "dtype", type(item)) for item in tree.flatten(x)]
)
dtype = to_torch_dtype(dtype)
return torch.as_tensor(x, dtype=dtype, device=get_device())
def convert_to_numpy(x):
def transform(x):
if is_tensor(x):
if x.requires_grad:
x = x.detach()
# Tensor has to be moved to CPU before converting to numpy.
if x.is_cuda or x.is_mps:
x = x.cpu()
if x.dtype == torch.bfloat16:
# Attempting to call .numpy() on a bfloat16 torch tensor leads
# to an immediate error. Instead we upcast to float32 and then
# convert to the numpy friendly bfloat16 type.
# https://github.com/pytorch/pytorch/issues/90574
return np.array(x.to(torch.float32)).astype(ml_dtypes.bfloat16)
return np.array(x)
if isinstance(x, (list, tuple)):
return np.array([transform(e) for e in x])
return transform(x)
def is_tensor(x):
# Using the built-in `isinstance` is recommended by pytorch
# over using torch.is_tensor
# see: https://pytorch.org/docs/stable/generated/torch.is_tensor.html
#
# Also, `torch.is_tensor()` causes issues with dynamo caching when
# a torch.Tensor and numpy.ndarray of the same size, shape, and dtype
# is passed, if called on a Tensor first the second call with ndarray
# will return `True` and vice-versa.
return isinstance(x, torch.Tensor)
def shape(x):
return x.shape
def cast(x, dtype):
dtype = to_torch_dtype(dtype)
if isinstance(x, KerasVariable):
x = x.value
if is_tensor(x):
if x.dtype == dtype:
return x
else:
return x.to(dtype)
return convert_to_tensor(x, dtype)
# Shape / dtype inference util
def compute_output_spec(fn, *args, **kwargs):
def has_none_shape(x):
"""Check for if a `KerasTensor` has dynamic shape."""
if isinstance(x, KerasTensor):
return None in x.shape
return False
def convert_keras_tensor_to_torch(x, fill_value=None):
"""Convert `KerasTensor`s to `torch.Tensor`s."""
if isinstance(x, KerasTensor):
shape = list(x.shape)
if fill_value:
for i, e in enumerate(shape):
if e is None:
shape[i] = fill_value
return torch.ones(
size=shape,
dtype=TORCH_DTYPES[x.dtype],
device=get_device(),
)
return x
def convert_torch_to_keras_tensor(x):
"""Convert `torch.Tensor`s to `KerasTensor`s."""
if is_tensor(x):
return KerasTensor(x.shape, standardize_dtype(x.dtype))
return x
def symbolic_call(fn, args, kwargs, fill_value):
"""Call `fn` to infer output shape and dtype."""
try:
# First try instantiating all tensors on the `"meta"` device,
# which should give a "zero flop" way to trace shape, but does
# not have universal support with torch operations.
with device_scope("meta"):
meta_args, meta_kwargs = tree.map_structure(
lambda x: convert_keras_tensor_to_torch(x, fill_value),
(args, kwargs),
)
return fn(*meta_args, **meta_kwargs)
except:
with device_scope(DEFAULT_DEVICE):
# If the `"meta"` device placement fails, fall back to tracing
# eagerly with tensors on the default device. This will be
# more robust, but more expensive.
eager_args, eager_kwargs = tree.map_structure(
lambda x: convert_keras_tensor_to_torch(x, fill_value),
(args, kwargs),
)
return fn(*eager_args, **eager_kwargs)
with StatelessScope(), torch.no_grad():
outputs = symbolic_call(fn, args, kwargs, fill_value=83)
none_in_shape = any(map(has_none_shape, tree.flatten((args, kwargs))))
if none_in_shape:
outputs_1 = outputs
outputs_2 = symbolic_call(fn, args, kwargs, fill_value=89)
flat_out_1 = tree.flatten(outputs_1)
flat_out_2 = tree.flatten(outputs_2)
flat_out = []
for x1, x2 in zip(flat_out_1, flat_out_2):
shape = list(x1.shape)
for i, e in enumerate(x2.shape):
if e != shape[i]:
shape[i] = None
flat_out.append(KerasTensor(shape, standardize_dtype(x1.dtype)))
outputs = pack_sequence_as(outputs_1, flat_out)
output_spec = tree.map_structure(convert_torch_to_keras_tensor, outputs)
return output_spec
def cond(pred, true_fn, false_fn):
# When symbolic execution, take pred as true.
if get_device() == "meta":
return true_fn()
if pred:
return true_fn()
return false_fn()
def vectorized_map(function, elements):
return torch.vmap(function)(elements)
def scatter(indices, values, shape):
indices = convert_to_tensor(indices)
values = convert_to_tensor(values)
zeros = torch.zeros(shape, dtype=values.dtype, device=get_device())
index_length = indices.shape[-1]
value_shape = shape[index_length:]
indices = torch.reshape(indices, [-1, index_length])
values = torch.reshape(values, [-1] + list(value_shape))
for i in range(indices.shape[0]):
index = indices[i]
zeros[tuple(index)] += values[i]
return zeros
def scatter_update(inputs, indices, updates):
inputs = convert_to_tensor(inputs)
indices = convert_to_tensor(indices, dtype="int64")
updates = convert_to_tensor(updates)
indices = torch.transpose(indices, 0, 1)
inputs[tuple(indices)] = updates
return inputs
def slice(inputs, start_indices, shape):
shape_dtype = to_torch_dtype("int64")
inputs = convert_to_tensor(inputs)
start_indices = convert_to_tensor(start_indices).to(shape_dtype)
shape = convert_to_tensor(shape).to(shape_dtype)
python_slice = __builtins__["slice"]
slices = [
python_slice(start_index, start_index + length)
for start_index, length in zip(start_indices, shape)
]
return inputs[slices]
def slice_update(inputs, start_indices, updates):
shape_dtype = to_torch_dtype("int64")
inputs = convert_to_tensor(inputs)
start_indices = convert_to_tensor(start_indices).to(shape_dtype)
updates = convert_to_tensor(updates)
python_slice = __builtins__["slice"]
slices = [
python_slice(start_index, start_index + update_length)
for start_index, update_length in zip(start_indices, updates.shape)
]
outputs = torch.clone(inputs)
outputs[slices] = updates
return outputs
def while_loop(
cond,
body,
loop_vars,
maximum_iterations=None,
):
current_iter = 0
iteration_check = (
lambda iter: maximum_iterations is None or iter < maximum_iterations
)
is_tuple = isinstance(loop_vars, (tuple, list))
loop_vars = tuple(loop_vars) if is_tuple else (loop_vars,)
loop_vars = tree.map_structure(convert_to_tensor, loop_vars)
while cond(*loop_vars) and iteration_check(current_iter):
loop_vars = body(*loop_vars)
if not isinstance(loop_vars, (list, tuple)):
loop_vars = (loop_vars,)
loop_vars = tuple(loop_vars)
current_iter += 1
return loop_vars if is_tuple else loop_vars[0]
def fori_loop(lower, upper, body_fun, init_val):
val = init_val
for i in range(lower, upper):
val = body_fun(i, val)
return val
def stop_gradient(variable):
# We can't use `.requires_grad_(False)` here since it only
# works when the tensor is a leaf node in the graph.
return variable.detach()
def unstack(x, num=None, axis=0):
return x.unbind(axis)
| keras/keras/backend/torch/core.py/0 | {
"file_path": "keras/keras/backend/torch/core.py",
"repo_id": "keras",
"token_count": 6509
} | 146 |
import torch
from keras.optimizers.base_optimizer import BaseOptimizer
from keras.utils import torch_utils
class TorchParallelOptimizer(BaseOptimizer):
@torch_utils.no_grad
def _backend_update_step(self, grads, trainable_variables, learning_rate):
self._parallel_update_step(
grads,
trainable_variables,
learning_rate,
)
@torch_utils.no_grad
def _backend_reset_gradient_accumulators(self):
acc_list = [v.value for v in self._accumulated_gradients]
torch._foreach_mul_(acc_list, 0.0)
@torch_utils.no_grad
def _backend_increment_gradient_accumulators(self, grads):
acc_list = [v.value for v in self._accumulated_gradients]
torch._foreach_add_(acc_list, grads, alpha=1.0)
| keras/keras/backend/torch/optimizers/torch_parallel_optimizer.py/0 | {
"file_path": "keras/keras/backend/torch/optimizers/torch_parallel_optimizer.py",
"repo_id": "keras",
"token_count": 338
} | 147 |
from keras.api_export import keras_export
from keras.callbacks.callback import Callback
@keras_export("keras.callbacks.History")
class History(Callback):
"""Callback that records events into a `History` object.
This callback is automatically applied to
every Keras model. The `History` object
gets returned by the `fit()` method of models.
Example:
>>> model = Sequential([layers.Dense(10)])
>>> model.compile(SGD(), loss='mse')
>>> history = model.fit(np.arange(100).reshape(5, 20), np.zeros(5),
... epochs=10, verbose=1)
>>> print(history.params)
{'verbose': 1, 'epochs': 10, 'steps': 1}
>>> # check the keys of history object
>>> print(history.history.keys())
dict_keys(['loss'])
"""
def __init__(self):
super().__init__()
self.history = {}
def on_train_begin(self, logs=None):
self.epoch = []
def on_epoch_end(self, epoch, logs=None):
logs = logs or {}
self.epoch.append(epoch)
for k, v in logs.items():
self.history.setdefault(k, []).append(v)
# Set the history attribute on the model after the epoch ends. This will
# make sure that the state which is set is the latest one.
self.model.history = self
| keras/keras/callbacks/history.py/0 | {
"file_path": "keras/keras/callbacks/history.py",
"repo_id": "keras",
"token_count": 513
} | 148 |
import numpy as np
from keras.api_export import keras_export
from keras.callbacks.callback import Callback
from keras.utils import io_utils
@keras_export("keras.callbacks.TerminateOnNaN")
class TerminateOnNaN(Callback):
"""Callback that terminates training when a NaN loss is encountered."""
def on_batch_end(self, batch, logs=None):
logs = logs or {}
loss = logs.get("loss")
if loss is not None:
if np.isnan(loss) or np.isinf(loss):
io_utils.print_msg(
f"Batch {batch}: Invalid loss, terminating training"
)
self.model.stop_training = True
| keras/keras/callbacks/terminate_on_nan.py/0 | {
"file_path": "keras/keras/callbacks/terminate_on_nan.py",
"repo_id": "keras",
"token_count": 280
} | 149 |
"""Unified high level distribution APIs across backends.
!!!DO NOT USE!!! Currently under development and APIs are not final.
Currently only the JAX backend has been implemented. The TensorFlow backend
will be implemented in the future (via tf.dtensor API).
"""
import collections
import contextlib
import os
import re
import warnings
import numpy as np
from keras.api_export import keras_export
from keras.backend import KerasTensor
from keras.backend import distribution_lib
from keras.backend.common import global_state
DEFAULT_BATCH_DIM_NAME = "batch"
GLOBAL_ATTRIBUTE_NAME = "distribution"
@keras_export("keras.distribution.list_devices")
def list_devices(device_type=None):
"""Return all the available devices based on the device type.
Note: in a distributed setting, global devices are returned.
Args:
device_type: string, one of `"cpu"`, `"gpu"` or `"tpu"`.
Defaults to `"gpu"` or `"tpu"` if available when
`device_type` is not provided. Otherwise
will return the `"cpu"` devices.
Return:
List of devices that are available for distribute computation.
"""
return distribution_lib.list_devices(device_type)
@keras_export("keras.distribution.initialize")
def initialize(job_addresses=None, num_processes=None, proceed_id=None):
"""Initialize the distribution system for multi-host/process setting.
Calling `initialize` will prepare the backend for execution on multi-host
GPU or TPUs. It should be called before any computations.
Note that the parameters can also be injected via enviornment variables,
which can be better controlled by the launch script at startup time.
For certain backend that also rely on the enviornment variables to
configure, Keras will properly forward them.
Args:
job_addresses: string. Comma separated IP addresses for all the jobs
that will form the whole computation cluster. Note that for JAX
backend, only the address for job 0 (coodinator) is needed. For
certain runtime like cloud TPU, this value can be `None`, and the
backend will figure it out with the TPU enviornment variables. You
can also config this value via enviornment variable
`KERAS_DISTRIBUTION_JOB_ADDRESSES`.
num_processes: int. The number of worker/processes that will form the
whole computation cluster. For certain runtime like cloud TPU, this
value can be `None`, and the backend will figure it out with the TPU
enviornment variables. You can also configure this value via
enviornment variable `KERAS_DISTRIBUTION_NUM_PROCESSES`.
process_id: int. The ID number of the current worker/process. The value
should be ranged from `0` to `num_processes - 1`. `0` will indicate
the current worker/process is the master/coordinate job. You can
also configure this value via enviornment variable
`KERAS_DISTRIBUTION_PROCESS_ID`.
Example:
Suppose there are two GPU processes, and process 0 is running at
address `10.0.0.1:1234`, and process 1 is running at address
`10.0.0.2:2345`. To configure such cluster, you can run
On process 0:
```python
keras.distribute.initialize(
job_addresses="10.0.0.1:1234,10.0.0.2:2345",
num_processes=2,
process_id=0)
```
On process 1:
```python
keras.distribute.initialize(
job_addresses="10.0.0.1:1234,10.0.0.2:2345",
num_processes=2,
process_id=1)
```
or via the enviornment variables:
On process 0:
```python
os.environ[
"KERAS_DISTRIBUTION_JOB_ADDRESSES"] = "10.0.0.1:1234,10.0.0.2:2345"
os.environ["KERAS_DISTRIBUTION_NUM_PROCESSES"] = "2
os.environ["KERAS_DISTRIBUTION_PROCESS_ID"] = "0"
keras.distribute.initialize()
```
On process 1:
```python
os.environ[
"KERAS_DISTRIBUTION_JOB_ADDRESSES"] = "10.0.0.1:1234,10.0.0.2:2345"
os.environ["KERAS_DISTRIBUTION_NUM_PROCESSES"] = "2
os.environ["KERAS_DISTRIBUTION_PROCESS_ID"] = "1"
keras.distribute.initialize()
```
Also note that for JAX backend, the `job_addresses` can be further
reduced to just the master/coordinator address, which is
`10.0.0.1:1234`.
"""
if (
job_addresses is None
and "KERAS_DISTRIBUTION_JOB_ADDRESSES" in os.environ
):
job_addresses = os.environ["KERAS_DISTRIBUTION_JOB_ADDRESSES"]
if (
num_processes is None
and "KERAS_DISTRIBUTION_NUM_PROCESSES" in os.environ
):
num_processes = int(os.environ["KERAS_DISTRIBUTION_NUM_PROCESSES"])
if proceed_id is None and "KERAS_DISTRIBUTION_PROCESS_ID" in os.environ:
proceed_id = int(os.environ["KERAS_DISTRIBUTION_PROCESS_ID"])
distribution_lib.initialize(job_addresses, num_processes, proceed_id)
@keras_export("keras.distribution.DeviceMesh")
class DeviceMesh:
"""A cluster of computation devices for distributed computation.
This API is aligned with `jax.sharding.Mesh` and `tf.dtensor.Mesh`, which
represents the computation devices in the global context.
See more details in [jax.sharding.Mesh](
https://jax.readthedocs.io/en/latest/jax.sharding.html#jax.sharding.Mesh)
and [tf.dtensor.Mesh](
https://www.tensorflow.org/api_docs/python/tf/experimental/dtensor/Mesh).
Args:
shape: tuple of list of integers. The shape of the overall
`DeviceMesh`, e.g. `(8,)` for a data parallel only distribution,
or `(4, 2)` for a model+data parallel distribution.
axis_names: List of string. The logical name of the each axis for
the `DeviceMesh`. The length of the `axis_names` should match to
the rank of the `shape`. The `axis_names` will be used to
match/create the `TensorLayout` when distribute the data and
variables.
devices: Optional list of devices. Defaults to all the available
devices locally from `keras.distribution.list_devices()`.
"""
def __init__(
self,
shape,
axis_names,
devices=None,
):
if not shape or not axis_names:
raise ValueError(
"Shape and axis_names cannot be empty. Received: "
f"shape={shape}, axis_names={axis_names}"
)
if len(shape) != len(axis_names):
raise ValueError(
"Shape and axis_names should have same size. "
f"Received: shape={shape}, axis_names={axis_names}"
)
if devices is None:
devices = list_devices()
devices = np.array(devices)
if np.prod(shape) != np.prod(devices.shape):
raise ValueError(
"Shape does not match the number of devices. "
f"Received: shape={shape}; devices.shape="
f"{devices.shape}"
)
self._shape = shape
self._axis_names = axis_names
self._devices = np.reshape(devices, shape)
@property
def shape(self):
return self._shape
@property
def axis_names(self):
return self._axis_names
@property
def devices(self):
return self._devices
def __repr__(self):
return (
f"<{self.__class__.__name__} "
f"shape={self.shape}, axis_names={self.axis_names}>"
)
def __str__(self):
return self.__repr__()
@keras_export("keras.distribution.TensorLayout")
class TensorLayout:
"""A layout to apply to a tensor.
This API is aligned with `jax.sharding.NamedSharding`
and `tf.dtensor.Layout`.
See more details in [jax.sharding.NamedSharding](
https://jax.readthedocs.io/en/latest/jax.sharding.html#jax.sharding.NamedSharding)
and [tf.dtensor.Layout](
https://www.tensorflow.org/api_docs/python/tf/experimental/dtensor/Layout).
Args:
axes: tuple of strings that should map to the `axis_names` in
a `DeviceMesh`. For any dimentions that doesn't need any sharding,
A `None` can be used a placeholder.
device_mesh: Optional `DeviceMesh` that will be used to create
the layout. The actual mapping of tensor to physical device
is not known until the mesh is specified.
"""
def __init__(self, axes, device_mesh=None):
self._axes = tuple(axes)
self._device_mesh = device_mesh
self._validate_axes()
@property
def axes(self):
return self._axes
@property
def device_mesh(self):
return self._device_mesh
@device_mesh.setter
def device_mesh(self, device_mesh):
if self._device_mesh is not None:
raise ValueError(
"Cannot override device mesh value. Existing "
f"value is {self._device_mesh}"
)
self._device_mesh = device_mesh
self._validate_axes()
def _validate_axes(self):
if self._device_mesh:
valid_axis_names = set(self._device_mesh.axis_names)
axis_names = set(self._axes) - set([None])
if axis_names - valid_axis_names:
raise ValueError(
"Invalid axis names for Layout. Valid axis "
f"names: {valid_axis_names}, Got {axis_names}"
)
def __repr__(self):
return (
f"<{self.__class__.__name__} "
f"axes={self.axes}, device_mesh={self.device_mesh}>"
)
def __str__(self):
return self.__repr__()
class Distribution:
"""Base class for variable distribution strategies.
A `Distribution` has following key functionalities:
1. Distribute the model variables to a `DeviceMesh`.
2. Distribute the input data to a `DeviceMesh`.
3. Distribute an intermediate state tensor in the model.
It can create a context scope so that the framework to properly detect the
`Distribution` and distribute the variable/data accordingly.
Args:
device_mesh: A `DeviceMesh` instance.
"""
def __init__(self, device_mesh):
self._device_mesh = device_mesh
def get_data_layout(self, data_shape):
"""Retrieve the `TensorLayout` for the input data.
Args:
data_shape: shape for the input data in list or tuple format.
Returns:
The `TensorLayout` for the data, which can be used by
`backend.distribute_value()` to redistribute a input data.
"""
raise NotImplementedError()
def get_variable_layout(self, variable):
"""Retrieve the `TensorLayout` for the variable.
Args:
variable: A `KerasVariable` instance.
return:
The `TensorLayout` for the variable, which can be used by
`backend.distribute_value()` to redistribute a variable.
"""
raise NotImplementedError()
def get_tensor_layout(self, path):
"""Retrieve the `TensorLayout` for the intermediate tensor.
Args:
path: a string path for the correspoding tensor.
return:
The `TensorLayout` for the intermediate tensor, which can be used
by `backend.relayout()` to reshard the tensor. Could also return
None.
"""
raise NotImplementedError()
@contextlib.contextmanager
def scope(self):
"""Context manager to make the `Distribution` current."""
original_scope = distribution()
set_distribution(self)
try:
yield
finally:
set_distribution(original_scope)
@property
def device_mesh(self):
return self._device_mesh
def distribute_dataset(self, dataset):
"""Create a distributed dataset instance from the original user dataset.
Args:
dataset: the original global dataset instance. Only
`tf.data.Dataset` is supported at the moment.
Returns:
a sharded `tf.data.Dataset` instance, which will produce data for
the current local worker/process.
"""
raise NotImplementedError()
def __repr__(self):
return f"<{self.__class__.__name__} device_mesh={self.device_mesh}>"
def __str__(self):
return self.__repr__()
@keras_export("keras.distribution.DataParallel")
class DataParallel(Distribution):
"""Distribution for data parallelism.
You can choose to create this instance by either specifing
the `device_mesh` or `devices` arguments (but not both).
The `device_mesh` argument is expected to be a `DeviceMesh` instance,
and is expected to be 1D only. In case that the mesh has multiple axes,
then the first axis will be treated as the data parallel dimension
(and a warning will be raised).
When a list of `devices` are provided, they will be used to construct a
1D mesh.
When both `mesh` and `devices` are absent, then `list_devices()`
will be used to detect any available devices and create a 1D mesh from
them.
Args:
device_mesh: Optional `DeviceMesh` instance.
devices: Optional list of devices.
"""
def __init__(self, device_mesh=None, devices=None):
if device_mesh:
self._initialize_with_device_mesh(device_mesh)
elif devices:
self._initialize_mesh_from_devices(devices)
else:
self._initialize_mesh_from_list_devices()
self._batch_dim_name = self.device_mesh.axis_names[0]
# Those following attributes might get convert to public methods.
self._num_process = distribution_lib.num_processes()
self._process_id = distribution_lib.process_id()
self._is_multi_process = self._num_process > 1
def _initialize_with_device_mesh(self, device_mesh):
if not isinstance(device_mesh, DeviceMesh):
raise ValueError(
"Expect `mesh` to be an instance of `DeviceMesh`. "
f"Received: mesh={device_mesh} (of type {type(device_mesh)})"
)
super().__init__(device_mesh)
if self.device_mesh.devices.ndim != 1:
warnings.warn(
"Expect the input mesh to be 1D, but received "
"mesh.devices.ndim=%d. "
"The first axis will be used for data-parallel sharding.",
device_mesh.devices.ndim,
)
def _initialize_mesh_from_devices(self, devices):
devices = np.array(devices)
device_mesh = DeviceMesh(
shape=devices.shape,
axis_names=[DEFAULT_BATCH_DIM_NAME],
devices=devices,
)
super().__init__(device_mesh)
def _initialize_mesh_from_list_devices(self):
devices = np.array(list_devices())
device_mesh = DeviceMesh(
shape=devices.shape,
axis_names=[DEFAULT_BATCH_DIM_NAME],
devices=devices,
)
super().__init__(device_mesh)
def get_data_layout(self, data_shape):
data_shard_spec = [None] * len(data_shape)
data_shard_spec[0] = self._batch_dim_name # Shard on the first dim
return TensorLayout(data_shard_spec, self.device_mesh)
def get_variable_layout(self, variable):
variable_shard_spec = [None] * len(variable.shape)
return TensorLayout(variable_shard_spec, self.device_mesh)
def get_tensor_layout(self, path):
# For data parallel training, the intermediate state is not changed.
return None
def distribute_dataset(self, dataset):
from tensorflow.python.data.experimental.ops import (
distribute as tf_data_distribute,
)
from keras.utils.module_utils import tensorflow as tf
if not isinstance(dataset, tf.data.Dataset):
raise ValueError(
"Only `tf.data.Dataset` is supported for "
f"sharding, got {type(dataset)}"
)
if not self._is_multi_process:
return dataset
batch_size = tf_data_distribute.compute_batch_size(dataset)
if batch_size.numpy() < 0:
raise ValueError(
"The batch size of the input dataset is "
"unknown. Please config the batch size for "
"the input dataset, e.g via `dataset.batch(batch_size)`"
)
per_worker_batch_size = tf_data_distribute.batch_sizes_for_worker(
global_batch_size=batch_size,
num_workers=self._num_process,
num_replicas_per_worker=1, # We hard code this for now.
worker_index=self._process_id,
)
distributed_dataset = dataset.rebatch(per_worker_batch_size)
distributed_dataset = tf_data_distribute._AutoShardDataset(
distributed_dataset,
num_workers=self._num_process,
index=self._process_id,
num_replicas=self._num_process,
)
return distributed_dataset.prefetch(tf.data.AUTOTUNE)
@keras_export("keras.distribution.ModelParallel")
class ModelParallel(Distribution):
"""Distribution that shards model variables.
Compare to `DataParallel` which replicates the variables across all devices,
`ModelParallel` allows you to shard variables in addition to the input data.
To construct a `ModelParallel` distribution, you need to provide a
`DeviceMesh` and a `LayoutMap`.
1. `DeviceMesh` contains physcial device information. The axis names in
the mesh will be used to map the variable and data layout.
2. `LayoutMap` contains the mapping between variable paths to their
corresponding `TensorLayout`.
Example:
```python
devices = list_devices() # Assume there are 8 devices.
# Create a mesh with 2 devices for data parallelism and 4 devices for
# model parallelism.
device_mesh = DeviceMesh(shape=(2, 4), axis_names=('batch', 'model'),
devices=devices)
# Create a layout map that shard the `Dense` layer and `Conv2D`
# layer variables on the last dimension.
# Based on the `device_mesh`, this means the variables
# will be split across 4 devices. Any other variable that doesn't
# match any key in the layout map will be fully replicated.
layout_map = LayoutMap(device_mesh)
layout_map['dense.*kernel'] = (None, 'model')
layout_map['dense.*bias'] = ('model',)
layout_map['conv2d.*kernel'] = (None, None, None, 'model')
layout_map['conv2d.*bias'] = ('model',)
distribution = ModelParallel(device_mesh=device_mesh,
layout_map=layout_map,
batch_dim_name='batch')
# Set the global distribution, or via `with distribution.scope():`
set_distribution(distribution)
model = model_creation()
model.compile()
model.fit(data)
```
You can quickly update the device mesh shape to change the sharding factor
of the variables. E.g.
```
# With only the shape change for the device mesh, the variables will be
# sharded across 8 devices instead of 4, which further reduces the memory
# footprint of variables on each of the device.
device_mesh = DeviceMesh(shape=(1, 8), axis_names=('batch', 'model'),
devices=devices)
```
To figure out a proper layout mapping rule for all the model variables, you
can first list out all the model variable paths, which will be used as the
key to map the variables to `TensorLayout`.
e.g.
```
model = create_model()
for v in model.variables:
print(v.path)
```
Args:
device_mesh: `DeviceMesh` instance for physical device and its
logical mapping.
layout_map: `LayoutMap` instance which map the variable path to the
corresponding `TensorLayout`. The axis names of the
`TensorLayout`s should match to the axis names in the
device_mesh, or exception will be raised.
batch_dim_name: optional string, the axis name in the `device_mesh`
that will be used to distribute data. If unspecified, the
first axis from the `device_mesh` will be used.
"""
def __init__(self, device_mesh, layout_map, batch_dim_name=None):
super().__init__(device_mesh)
self._layout_map = layout_map
self._batch_dim_name = batch_dim_name or self.device_mesh.axis_names[0]
# Those following attributes might get convert to public methods.
self._num_process = distribution_lib.num_processes()
self._process_id = distribution_lib.process_id()
self._is_multi_process = self._num_process > 1
def get_data_layout(self, data_shape):
data_shard_spec = [None] * len(data_shape)
data_shard_spec[0] = self._batch_dim_name # Shard on the first dim
return TensorLayout(data_shard_spec, self.device_mesh)
def get_variable_layout(self, variable):
variable_layout = self._layout_map[variable.path]
if variable_layout is not None:
return variable_layout
variable_shard_spec = [None] * len(variable.shape)
return TensorLayout(variable_shard_spec, self.device_mesh)
def get_tensor_layout(self, path):
return self._layout_map[path]
def distribute_dataset(self, dataset):
from tensorflow.python.data.experimental.ops import (
distribute as tf_data_distribute,
)
from keras.utils.module_utils import tensorflow as tf
if not isinstance(dataset, tf.data.Dataset):
raise ValueError(
"Only `tf.data.Dataset` is supported for "
f"sharding, got {type(dataset)}"
)
if not self._is_multi_process:
return dataset
global_batch_size = tf_data_distribute.compute_batch_size(dataset)
if global_batch_size.numpy() < 0:
raise ValueError(
"The batch size of the input dataset is "
"unknown. Please config the batch size for "
"the input dataset, e.g via `dataset.batch(batch_size)`"
)
# We need to compute the the per-worker batch size.
# Imagine we have 4 workers, and each worker has 2 devices. The device
# ID will be w{worker_id}_{device_id} from global perspective, eg
# 'w0_0', 'w0_1', 'w1_0', etc.
# For a mesh with global shape {'batch': 4, 'model': 2}, we would like
# the mesh to be like below:
# batch ->
# --------------------------
# model | w0_0, w0_1, w1_0, w1_1 |
# v | w0_2, w0_3, w1_2, w1_3 |
# --------------------------
# In this case, the batch dim will be split acorss 2 workers.
#
# In the case that global batch dim is smaller than the worker size, eg
# {'batch': 1, 'model': 8}, then the mesh will be like below:
# batch ->
# --------
# model | w0_0 |
# | w0_1 |
# | w1_0 |
# | w1_1 |
# | w2_0 |
# | w2_1 |
# | w3_0 |
# | w3_1 |
# --------
# And the data batch will be fully replicated for each of the worker.
mesh_batch_dim_index = self.device_mesh.axis_names.index(
self._batch_dim_name
)
mesh_batch_dim_size = self.device_mesh.shape[mesh_batch_dim_index]
# TODO(scottzhu): local device count can be a field of the mesh.
local_device_count = (
np.prod(self.device_mesh.shape) // self._num_process
)
if mesh_batch_dim_size < local_device_count:
# No sharding is needed in this case. The worker will have the
# global batch size, and data from the iterator will need to be
# replicated for model dimention.
return dataset.prefetch(tf.data.AUTOTUNE)
else:
if mesh_batch_dim_size % local_device_count != 0:
raise ValueError(
"The Batch dimention of the mesh is not compatible "
"with the local worker device count. Mesh batch "
f"dim = {mesh_batch_dim_size} and local device "
f"count = {local_device_count}"
)
num_shards = mesh_batch_dim_size // local_device_count
per_worker_batch_size = global_batch_size // num_shards
distributed_dataset = dataset.rebatch(per_worker_batch_size)
distributed_dataset = tf_data_distribute._AutoShardDataset(
distributed_dataset,
num_workers=num_shards,
index=self._process_id % num_shards,
num_replicas=num_shards,
)
return distributed_dataset.prefetch(tf.data.AUTOTUNE)
@keras_export("keras.distribution.LayoutMap")
class LayoutMap(collections.abc.MutableMapping):
"""A dict-like object that maps string to `TensorLayout` instances.
`LayoutMap` uses a string as key and a `TensorLayout` as value. There is a
behavior difference between a normal Python dict and this class. The string
key will be treated as a regex when retrieving the value. See the docstring
of `get` for more details.
See below for a usage example. You can define the naming schema
of the `TensorLayout`, and then retrieve the corresponding
`TensorLayout` instance.
In the normal case, the key to query is usually the `variable.path`, which
is the idenifier of the variable.
As shortcut, tuple or list of axis names are also allowed when inserting
as value, and will be converted to `TensorLayout`.
```python
layout_map = LayoutMap(device_mesh=None)
layout_map['dense.*kernel'] = (None, 'model') # layout_2d
layout_map['dense.*bias'] = ('model',) # layout_1d
layout_map['conv2d.*kernel'] = TensorLayout((None, None, None, 'model'))
layout_map['conv2d.*bias'] = TensorLayout(('model',)) # layout_1d
layout_1 = layout_map['dense_1.kernel'] # layout_1 == layout_2d
layout_2 = layout_map['dense_1.bias'] # layout_2 == layout_1d
layout_3 = layout_map['dense_2.kernel'] # layout_3 == layout_2d
layout_4 = layout_map['dense_2.bias'] # layout_4 == layout_1d
layout_5 = layout_map['my_model/conv2d_123/kernel'] # layout_5 == layout_4d
layout_6 = layout_map['my_model/conv2d_123/bias'] # layout_6 == layout_1d
layout_7 = layout_map['my_model/conv3d_1/kernel'] # layout_7 == None
layout_8 = layout_map['my_model/conv3d_1/bias'] # layout_8 == None
```
Args:
device_mesh: An optional `DeviceMesh` that can be used to populate the
`TensorLayout.device_mesh` if `TensorLayout.device_mesh` is not set.
"""
def __init__(self, device_mesh=None):
self._layout_map = collections.OrderedDict()
self._device_mesh = device_mesh
def __getitem__(self, key):
"""Retrieves the corresponding layout by the string key.
When there isn't an exact match, all the existing keys in the layout map
will be treated as a regex and map against the input key again. When
there are multiple matches for the regex, an `ValueError` will be
raised. Returns `None` if there isn't any match found.
Args:
key: String key to query a layout.
Returns:
Corresponding layout based on the query.
"""
if key in self._layout_map:
return self._layout_map[key]
matching_keys = []
for k in self._layout_map:
if re.search(k, key):
matching_keys.append(k)
if len(matching_keys) > 1:
raise ValueError(
f"Path '{key}' matches multiple layout "
f"specification keys: {matching_keys}. Please make "
"sure each tensor/variable path only matches at most "
"one layout specification key in the LayoutMap."
)
elif len(matching_keys) == 1:
return self._layout_map[matching_keys[0]]
return None
def __setitem__(self, key, layout):
"""Insert TensorLayout to the LayoutMap.
Args:
key: String key for the `TensorLayout`.
layout: The `TensorLayout`. As a shortcut, tuple of string and None
are also acceptable, and will be converted to `TensorLayout`.
"""
if key in self._layout_map:
raise ValueError(
f"{key} already exist in the LayoutMap with "
f"value {self._layout_map[key]}. Please make sure to "
"not use duplicated keys."
)
if isinstance(layout, tuple):
layout = TensorLayout(axes=layout, device_mesh=None)
if not isinstance(layout, TensorLayout):
raise ValueError(
f"{layout} should be a TensorLayout type, got {type(layout)}"
)
self._maybe_populate_device_mesh(layout)
self._layout_map[key] = layout
def __delitem__(self, key):
# let the dict to handle the key missing error
return self._layout_map.pop(key)
def __len__(self):
return len(self._layout_map)
def __iter__(self):
return iter(self._layout_map)
@property
def device_mesh(self):
return self._device_mesh
def _maybe_populate_device_mesh(self, layout):
if layout.device_mesh is None and self.device_mesh is not None:
layout.device_mesh = self.device_mesh
LayoutMap.get.__doc__ = LayoutMap.__getitem__.__doc__
@keras_export("keras.distribution.distribute_tensor")
def distribute_tensor(tensor, layout):
"""Change the layout of a Tensor value in the jit function execution.
Args:
tensor: a Tensor to change the layout.
layout: `TensorLayout` to be applied on the value.
Returns:
a new value with the specified tensor layout.
"""
if isinstance(tensor, KerasTensor):
# keras tensor is only used for building functional model, and can't be
# used to alter layout/sharding.
return tensor
return distribution_lib.distribute_tensor(tensor, layout)
@keras_export("keras.distribution.distribution")
def distribution():
"""Retrieve the current distribution from global context."""
return global_state.get_global_attribute(GLOBAL_ATTRIBUTE_NAME)
@keras_export("keras.distribution.set_distribution")
def set_distribution(value):
"""Set the distribution as the global distribution setting.
Args:
value: a `Distribution` instance.
"""
global_state.set_global_attribute(GLOBAL_ATTRIBUTE_NAME, value)
| keras/keras/distribution/distribution_lib.py/0 | {
"file_path": "keras/keras/distribution/distribution_lib.py",
"repo_id": "keras",
"token_count": 13217
} | 150 |
from keras import activations
from keras.api_export import keras_export
from keras.layers.layer import Layer
@keras_export("keras.layers.Activation")
class Activation(Layer):
"""Applies an activation function to an output.
Args:
activation: Activation function. It could be a callable, or the name of
an activation from the `keras.activations` namespace.
**kwargs: Base layer keyword arguments, such as `name` and `dtype`.
Example:
>>> layer = keras.layers.Activation('relu')
>>> layer([-3.0, -1.0, 0.0, 2.0])
[0.0, 0.0, 0.0, 2.0]
>>> layer = keras.layers.Activation(keras.activations.relu)
>>> layer([-3.0, -1.0, 0.0, 2.0])
[0.0, 0.0, 0.0, 2.0]
"""
def __init__(self, activation, **kwargs):
super().__init__(**kwargs)
self.supports_masking = True
self.activation = activations.get(activation)
def call(self, inputs):
return self.activation(inputs)
def compute_output_shape(self, input_shape):
return input_shape
def get_config(self):
config = {"activation": activations.serialize(self.activation)}
base_config = super().get_config()
return {**base_config, **config}
| keras/keras/layers/activations/activation.py/0 | {
"file_path": "keras/keras/layers/activations/activation.py",
"repo_id": "keras",
"token_count": 497
} | 151 |
import numpy as np
from keras import layers
from keras import ops
from keras import testing
class AttentionTest(testing.TestCase):
def test_attention_basics(self):
# No scale, no concat.
self.run_layer_test(
layers.Attention,
init_kwargs={
"score_mode": "dot",
"dropout": 0.5,
},
input_shape=[(2, 3, 4), (2, 4, 4)],
expected_output_shape=(2, 3, 4),
expected_num_trainable_weights=0,
expected_num_non_trainable_weights=0,
expected_num_seed_generators=1,
expected_num_losses=0,
supports_masking=True,
run_training_check=False,
)
# Scale and concat.
self.run_layer_test(
layers.Attention,
init_kwargs={
"use_scale": True,
"score_mode": "concat",
"dropout": 0.5,
},
input_shape=[(2, 3, 4), (2, 4, 4)],
expected_output_shape=(2, 3, 4),
expected_num_trainable_weights=2,
expected_num_non_trainable_weights=0,
expected_num_seed_generators=1,
expected_num_losses=0,
supports_masking=True,
run_training_check=False,
)
def test_attention_correctness(self):
query = np.array([[[1.0, 0.0], [0.0, 1.0]]])
key = np.array([[[0.0, 1.0], [1.0, 0.0]]])
value = np.array([[[1.0, 2.0], [3.0, 4.0]]])
# Dot.
layer = layers.Attention(score_mode="dot")
output, scores = layer(
[query, value, key],
return_attention_scores=True,
)
self.assertAllClose(
output, [[[2.462, 3.462], [1.538, 2.538]]], atol=1e-3
)
self.assertAllClose(
scores, [[[0.269, 0.731], [0.731, 0.269]]], atol=1e-3
)
# Concat.
layer = layers.Attention(score_mode="concat")
output, scores = layer(
[query, value, key],
return_attention_scores=True,
)
self.assertAllClose(
output, [[[1.727, 2.727], [2.272, 3.272]]], atol=1e-3
)
self.assertAllClose(
scores, [[[0.636, 0.363], [0.363, 0.636]]], atol=1e-3
)
def test_attention_with_mask(self):
layer = layers.Attention()
query = np.array([[[1.0, 0.0], [0.0, 1.0]]])
value = np.array([[[1.0, 1.0], [1.0, 1.0]]])
query_mask = np.array([[True, False]])
value_mask = np.array([[True, False]])
output, scores = layer(
[query, value],
mask=[query_mask, value_mask],
return_attention_scores=True,
)
self.assertAllClose(output, [[[1.0, 1.0], [0.0, 0.0]]])
self.assertAllClose(scores, [[[1.0, 0.0], [1.0, 0.0]]])
def test_attention_errors(self):
layer = layers.Attention()
tensor = np.array([[[1.0, 1.0], [1.0, 1.0]]])
with self.assertRaisesRegex(ValueError, "must be called on a list"):
layer(tensor)
with self.assertRaisesRegex(ValueError, "length 2 or 3"):
layer([tensor, tensor, tensor, tensor])
with self.assertRaisesRegex(ValueError, "layer mask must be a list"):
layer([tensor, tensor], mask=tensor)
with self.assertRaisesRegex(ValueError, "length 2 or 3"):
layer([tensor, tensor], mask=[tensor])
def test_attention_with_dropout(self):
query = np.array([[[1.0, 0.0], [0.0, 1.0]]])
value = np.array([[[1.0, 1.0], [1.0, 1.0]]])
layer_with_dropout = layers.Attention(dropout=0.2)
layer_without_dropout = layers.Attention()
output1, scores1 = layer_with_dropout(
[query, value], return_attention_scores=True, training=True
)
output2, scores2 = layer_without_dropout(
[query, value], return_attention_scores=True, training=True
)
self.assertNotAllClose(output1, output2)
self.assertNotAllClose(scores1, scores2)
def test_attention_invalid_score_mode(self):
with self.assertRaisesRegex(
ValueError,
"Invalid value for argument score_mode. "
"Expected one of {'dot', 'concat'}",
):
layers.Attention(score_mode="invalid_mode")
def test_attention_calculate_scores_with_scale(self):
query = np.random.random((2, 3, 4))
key = np.random.random((2, 4, 4))
layer = layers.Attention(use_scale=True, score_mode="dot")
layer.build(input_shape=[(2, 3, 4), (2, 4, 4)])
expected_scores = np.matmul(query, key.transpose((0, 2, 1)))
expected_scores *= layer.scale.numpy()
actual_scores = layer._calculate_scores(query, key)
self.assertAllClose(actual_scores, expected_scores)
def test_attention_calculate_score_mask_no_causal_no_vmask(self):
scores = np.random.random((2, 3, 4))
layer = layers.Attention()
mask = layer._calculate_score_mask(
scores, v_mask=None, use_causal_mask=False
)
self.assertIsNone(
mask,
"Mask should be None when no causal mask and no value mask "
"are used",
)
def test_attention_calculate_score_mask_with_causal_no_vmask(self):
scores = np.random.random((2, 3, 4))
layer = layers.Attention()
causal_mask = layer._calculate_score_mask(
scores, v_mask=None, use_causal_mask=True
)
expected_causal_mask = np.tril(
np.ones((1, scores.shape[1], scores.shape[2])), k=0
)
self.assertAllClose(causal_mask, expected_causal_mask, atol=1e-6)
def test_attention_calculate_score_mask_with_causal_and_vmask(self):
scores = np.random.random((2, 3, 4))
layer = layers.Attention()
v_mask = np.array([[True, False, True, False]])
combined_mask = layer._calculate_score_mask(
scores, v_mask=v_mask, use_causal_mask=True
)
expected_causal_mask = np.tril(
np.ones((1, scores.shape[1], scores.shape[2])), k=0
)
expected_combined_mask = np.logical_and(
expected_causal_mask, v_mask[:, np.newaxis, :]
)
self.assertAllClose(combined_mask, expected_combined_mask, atol=1e-6)
def test_attention_compute_mask_with_no_mask(self):
layer = layers.Attention()
dummy_inputs = [
np.random.random((2, 3, 4)),
np.random.random((2, 4, 4)),
]
self.assertIsNone(
layer.compute_mask(inputs=dummy_inputs, mask=None),
"compute_mask should return None when mask is None",
)
def test_attention_compute_mask_with_first_element_none(self):
layer = layers.Attention()
dummy_inputs = [
np.random.random((2, 3, 4)),
np.random.random((2, 4, 4)),
]
mask = [None, np.array([True, False, True])]
self.assertIsNone(
layer.compute_mask(inputs=dummy_inputs, mask=mask),
"compute_mask should return None when the first element is None",
)
def test_attention_compute_mask_does_not_return_none_with_valid_mask(self):
layer = layers.Attention()
dummy_inputs = [
np.random.random((2, 3, 4)),
np.random.random((2, 4, 4)),
]
valid_mask = np.array([True, False, True])
mask = [valid_mask, np.array([False, True, False])]
computed_mask = layer.compute_mask(inputs=dummy_inputs, mask=mask)
computed_mask = ops.convert_to_numpy(computed_mask)
self.assertIsNotNone(
computed_mask,
"compute_mask should not return None with a valid mask",
)
def test_attention_compute_mask_returns_correct_tensor_with_valid_mask(
self,
):
layer = layers.Attention()
dummy_inputs = [
np.random.random((2, 3, 4)),
np.random.random((2, 4, 4)),
]
valid_mask = np.array([True, False, True])
mask = [valid_mask, np.array([False, True, False])]
computed_mask = layer.compute_mask(inputs=dummy_inputs, mask=mask)
computed_mask = ops.convert_to_numpy(computed_mask)
self.assertTrue(
np.array_equal(computed_mask, valid_mask),
"compute_mask did not return the correct mask tensor",
)
def test_attention_compute_mask_returns_correct_tensor_with_all_true_mask(
self,
):
layer = layers.Attention()
dummy_inputs = [np.ones((2, 3, 4)), np.ones((2, 4, 4))]
valid_mask = np.array([True, True, True])
mask = [valid_mask, np.array([True, True, True])]
computed_mask = layer.compute_mask(inputs=dummy_inputs, mask=mask)
computed_mask = ops.convert_to_numpy(computed_mask)
expected_mask = np.array([True, True, True])
self.assertTrue(
np.array_equal(computed_mask, expected_mask),
"compute_mask did not return the correct mask tensor",
)
def test_attention_compute_mask_returns_correct_tensor_with_all_false_mask(
self,
):
layer = layers.Attention()
dummy_inputs = [np.ones((2, 3, 4)), np.ones((2, 4, 4))]
valid_mask = np.array([False, False, False])
mask = [valid_mask, np.array([False, False, False])]
computed_mask = layer.compute_mask(inputs=dummy_inputs, mask=mask)
computed_mask = ops.convert_to_numpy(computed_mask)
expected_mask = np.array([False, False, False])
self.assertTrue(
np.array_equal(computed_mask, expected_mask),
"compute_mask did not return the correct mask tensor",
)
def test_attention_compute_mask_with_tolerance_1e_3(self):
layer = layers.Attention()
dummy_inputs = [np.ones((2, 3, 4)), np.ones((2, 4, 4))]
valid_mask = np.array([1.0, 0.0, 1.0], dtype=float)
mask = [valid_mask, np.array([0.0, 1.0, 0.0], dtype=float)]
computed_mask = layer.compute_mask(inputs=dummy_inputs, mask=mask)
computed_mask = ops.convert_to_numpy(computed_mask)
expected_mask = valid_mask
self.assertTrue(
np.allclose(computed_mask, expected_mask, atol=1e-3),
"Incorrect mask tensor within tolerance 1e-3",
)
def test_attention_compute_mask_with_tolerance_1e_5(self):
layer = layers.Attention()
dummy_inputs = [np.ones((2, 3, 4)), np.ones((2, 4, 4))]
valid_mask = np.array([1.0, 0.0, 1.0], dtype=float)
mask = [valid_mask, np.array([0.0, 1.0, 0.0], dtype=float)]
computed_mask = layer.compute_mask(inputs=dummy_inputs, mask=mask)
computed_mask = ops.convert_to_numpy(computed_mask)
expected_mask = valid_mask
self.assertTrue(
np.allclose(computed_mask, expected_mask, atol=1e-5),
"Incorrect mask tensor within tolerance 1e-5",
)
def test_attention_compute_mask_with_tolerance_1e_7(self):
layer = layers.Attention()
dummy_inputs = [np.ones((2, 3, 4)), np.ones((2, 4, 4))]
valid_mask = np.array([1.0, 0.0, 1.0], dtype=float)
mask = [valid_mask, np.array([0.0, 1.0, 0.0], dtype=float)]
computed_mask = layer.compute_mask(inputs=dummy_inputs, mask=mask)
computed_mask = ops.convert_to_numpy(computed_mask)
expected_mask = valid_mask
self.assertTrue(
np.allclose(computed_mask, expected_mask, atol=1e-7),
"Incorrect mask tensor within tolerance 1e-7 ",
)
def test_attention_compute_mask_with_single_element_masks(self):
layer = layers.Attention()
dummy_inputs = [np.ones((2, 3, 4)), np.ones((2, 4, 4))]
valid_mask = np.array([True])
mask = [valid_mask, np.array([False])]
computed_mask = layer.compute_mask(inputs=dummy_inputs, mask=mask)
computed_mask = ops.convert_to_numpy(computed_mask)
expected_shape = (1,)
self.assertEqual(computed_mask.shape, expected_shape)
def test_attention_compute_mask_with_non_boolean_masks(self):
layer = layers.Attention()
dummy_inputs = [np.ones((2, 3, 4)), np.ones((2, 4, 4))]
valid_mask = np.array([1, 0, 1])
mask = [valid_mask, np.array([0, 1, 0])]
computed_mask = layer.compute_mask(inputs=dummy_inputs, mask=mask)
computed_mask = ops.convert_to_numpy(computed_mask)
self.assertTrue(np.array_equal(computed_mask, valid_mask))
def test_attention_compute_mask_with_edge_case_masks(self):
layer = layers.Attention()
dummy_inputs = [np.ones((2, 3, 4)), np.ones((2, 4, 4))]
edge_case_masks = [
np.array([True, True, True]),
np.array([False, False, False]),
np.array([True, False, True]),
]
for mask in edge_case_masks:
computed_mask = layer.compute_mask(
inputs=dummy_inputs, mask=[mask, mask]
)
computed_mask = ops.convert_to_numpy(computed_mask)
self.assertTrue(np.array_equal(computed_mask, mask))
def test_attention_compute_mask_with_different_input_shapes(self):
layer = layers.Attention()
input_shapes = [(2, 3, 4), (3, 2, 5), (4, 1, 6)]
valid_mask = np.array([True, False, True])
for shape in input_shapes:
dummy_inputs = [np.ones(shape), np.ones(shape)]
mask = [valid_mask, np.array([False, True, False])]
computed_mask = layer.compute_mask(inputs=dummy_inputs, mask=mask)
computed_mask = ops.convert_to_numpy(computed_mask)
self.assertTrue(np.array_equal(computed_mask, valid_mask))
| keras/keras/layers/attention/attention_test.py/0 | {
"file_path": "keras/keras/layers/attention/attention_test.py",
"repo_id": "keras",
"token_count": 6768
} | 152 |
import pytest
from absl.testing import parameterized
from keras import backend
from keras import layers
from keras import testing
class IdentityTest(testing.TestCase, parameterized.TestCase):
@parameterized.named_parameters(
[
{"testcase_name": "dense", "sparse": False},
{"testcase_name": "sparse", "sparse": True},
]
)
@pytest.mark.requires_trainable_backend
def test_identity_basics(self, sparse):
if sparse and not backend.SUPPORTS_SPARSE_TENSORS:
pytest.skip("Backend does not support sparse tensors.")
self.run_layer_test(
layers.Identity,
init_kwargs={},
input_shape=(2, 3),
input_sparse=sparse,
expected_output_shape=(2, 3),
expected_output_sparse=sparse,
expected_num_trainable_weights=0,
expected_num_non_trainable_weights=0,
expected_num_seed_generators=0,
expected_num_losses=0,
run_training_check=not sparse,
supports_masking=True,
)
| keras/keras/layers/core/identity_test.py/0 | {
"file_path": "keras/keras/layers/core/identity_test.py",
"repo_id": "keras",
"token_count": 504
} | 153 |
from keras import regularizers
from keras.api_export import keras_export
from keras.layers.layer import Layer
@keras_export("keras.layers.ActivityRegularization")
class ActivityRegularization(Layer):
"""Layer that applies an update to the cost function based input activity.
Args:
l1: L1 regularization factor (positive float).
l2: L2 regularization factor (positive float).
Input shape:
Arbitrary. Use the keyword argument `input_shape`
(tuple of integers, does not include the samples axis)
when using this layer as the first layer in a model.
Output shape:
Same shape as input.
"""
def __init__(self, l1=0.0, l2=0.0, **kwargs):
super().__init__(
activity_regularizer=regularizers.L1L2(l1=l1, l2=l2), **kwargs
)
self.supports_masking = True
self.l1 = l1
self.l2 = l2
def call(self, inputs):
return inputs
def compute_output_shape(self, input_shape):
return input_shape
def get_config(self):
base_config = super().get_config()
config = {"l1": self.l1, "l2": self.l2}
return {**base_config, **config}
| keras/keras/layers/regularization/activity_regularization.py/0 | {
"file_path": "keras/keras/layers/regularization/activity_regularization.py",
"repo_id": "keras",
"token_count": 479
} | 154 |
import numpy as np
import pytest
from absl.testing import parameterized
from keras import backend
from keras import layers
from keras import ops
from keras import testing
class Cropping2DTest(testing.TestCase, parameterized.TestCase):
@parameterized.product(
(
# different cropping values
{"cropping": ((1, 2), (3, 4)), "expected_ranges": ((1, 5), (3, 5))},
# same cropping values with 2 tuples
{"cropping": ((2, 2), (2, 2)), "expected_ranges": ((2, 5), (2, 7))},
# same cropping values with 1 tuple
{"cropping": (2, 2), "expected_ranges": ((2, 5), (2, 7))},
# same cropping values with an integer
{"cropping": 2, "expected_ranges": ((2, 5), (2, 7))},
# cropping right only in both dimensions
{"cropping": ((0, 2), (0, 4)), "expected_ranges": ((0, 5), (0, 5))},
# cropping left only in both dimensions
{"cropping": ((1, 0), (3, 0)), "expected_ranges": ((1, 7), (3, 9))},
# cropping left only in rows dimension
{"cropping": ((1, 0), (3, 4)), "expected_ranges": ((1, 7), (3, 5))},
# cropping left only in cols dimension
{"cropping": ((1, 2), (3, 0)), "expected_ranges": ((1, 5), (3, 9))},
),
(
{"data_format": "channels_first"},
{"data_format": "channels_last"},
),
)
@pytest.mark.requires_trainable_backend
def test_cropping_2d(self, cropping, data_format, expected_ranges):
if data_format == "channels_first":
inputs = np.random.rand(3, 5, 7, 9)
expected_output = ops.convert_to_tensor(
inputs[
:,
:,
expected_ranges[0][0] : expected_ranges[0][1],
expected_ranges[1][0] : expected_ranges[1][1],
]
)
else:
inputs = np.random.rand(3, 7, 9, 5)
expected_output = ops.convert_to_tensor(
inputs[
:,
expected_ranges[0][0] : expected_ranges[0][1],
expected_ranges[1][0] : expected_ranges[1][1],
:,
]
)
self.run_layer_test(
layers.Cropping2D,
init_kwargs={"cropping": cropping, "data_format": data_format},
input_data=inputs,
expected_output=expected_output,
)
def test_cropping_2d_with_dynamic_spatial_dim(self):
if backend.config.image_data_format() == "channels_last":
input_layer = layers.Input(batch_shape=(1, 7, None, 5))
else:
input_layer = layers.Input(batch_shape=(1, 5, 7, None))
cropped = layers.Cropping2D(((1, 2), (3, 4)))(input_layer)
if backend.config.image_data_format() == "channels_last":
self.assertEqual(cropped.shape, (1, 4, None, 5))
else:
self.assertEqual(cropped.shape, (1, 5, 4, None))
@parameterized.product(
(
{"cropping": ((3, 6), (0, 0))},
{"cropping": ((0, 0), (5, 4))},
),
(
{"data_format": "channels_first"},
{"data_format": "channels_last"},
),
)
def test_cropping_2d_errors_if_cropping_more_than_available(
self, cropping, data_format
):
input_layer = layers.Input(batch_shape=(3, 7, 9, 5))
with self.assertRaises(ValueError):
layers.Cropping2D(cropping=cropping, data_format=data_format)(
input_layer
)
def test_cropping_2d_errors_if_cropping_argument_invalid(self):
with self.assertRaises(ValueError):
layers.Cropping2D(cropping=(1,))
with self.assertRaises(ValueError):
layers.Cropping2D(cropping=(1, 2, 3))
with self.assertRaises(ValueError):
layers.Cropping2D(cropping="1")
with self.assertRaises(ValueError):
layers.Cropping2D(cropping=((1, 2), (3, 4, 5)))
with self.assertRaises(ValueError):
layers.Cropping2D(cropping=((1, 2), (3, -4)))
with self.assertRaises(ValueError):
layers.Cropping2D(cropping=((1, 2), "3"))
@parameterized.product(
(
{"cropping": ((4, 5), (0, 0)), "input_shape": (3, 8, 9, 5)},
{"cropping": ((0, 0), (5, 5)), "input_shape": (3, 8, 9, 5)},
{"cropping": ((6, 3), (0, 0)), "input_shape": (3, 8, 9, 5)},
{"cropping": ((0, 0), (7, 3)), "input_shape": (3, 8, 9, 5)},
),
(
{"data_format": "channels_first"},
{"data_format": "channels_last"},
),
)
def test_cropping_2d_error_on_excessive_cropping(
self, cropping, input_shape, data_format
):
inputs = np.random.rand(*input_shape)
with self.assertRaisesRegex(
ValueError,
"Values in `cropping` argument should be smaller than the "
"corresponding spatial dimension of the input.",
):
layer = layers.Cropping2D(
cropping=cropping, data_format=data_format
)
_ = layer(inputs)
| keras/keras/layers/reshaping/cropping2d_test.py/0 | {
"file_path": "keras/keras/layers/reshaping/cropping2d_test.py",
"repo_id": "keras",
"token_count": 2666
} | 155 |
import numpy as np
import pytest
from keras import backend
from keras import initializers
from keras import layers
from keras import testing
class ConvLSTM1DTest(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_basics(self):
channels_last = backend.config.image_data_format() == "channels_last"
self.run_layer_test(
layers.ConvLSTM3D,
init_kwargs={"filters": 5, "kernel_size": 3, "padding": "same"},
input_shape=(
(3, 2, 4, 4, 4, 3) if channels_last else (3, 2, 3, 4, 4, 4)
),
expected_output_shape=(
(3, 4, 4, 4, 5) if channels_last else (3, 5, 4, 4, 4)
),
expected_num_trainable_weights=3,
expected_num_non_trainable_weights=0,
supports_masking=True,
)
self.run_layer_test(
layers.ConvLSTM3D,
init_kwargs={
"filters": 5,
"kernel_size": 3,
"padding": "valid",
"recurrent_dropout": 0.5,
},
input_shape=(
(3, 2, 8, 8, 8, 3) if channels_last else (3, 2, 3, 8, 8, 8)
),
call_kwargs={"training": True},
expected_output_shape=(
(3, 6, 6, 6, 5) if channels_last else (3, 5, 6, 6, 6)
),
expected_num_trainable_weights=3,
expected_num_non_trainable_weights=0,
supports_masking=True,
)
self.run_layer_test(
layers.ConvLSTM3D,
init_kwargs={
"filters": 5,
"kernel_size": 3,
"padding": "valid",
"return_sequences": True,
},
input_shape=(
(3, 2, 8, 8, 8, 3) if channels_last else (3, 2, 3, 8, 8, 8)
),
expected_output_shape=(
(3, 2, 6, 6, 6, 5) if channels_last else (3, 2, 5, 6, 6, 6)
),
expected_num_trainable_weights=3,
expected_num_non_trainable_weights=0,
supports_masking=True,
)
def test_correctness(self):
sequence = (
np.arange(1920).reshape((2, 3, 4, 4, 4, 5)).astype("float32") / 100
)
expected_output = np.array(
[
[
[
[[0.99149036, 0.99149036], [0.99180907, 0.99180907]],
[[0.99258363, 0.99258363], [0.9927925, 0.9927925]],
],
[
[[0.99413764, 0.99413764], [0.99420583, 0.99420583]],
[[0.9943788, 0.9943788], [0.9944278, 0.9944278]],
],
],
[
[
[[0.9950547, 0.9950547], [0.9950547, 0.9950547]],
[[0.9950547, 0.9950547], [0.9950547, 0.9950547]],
],
[
[[0.9950547, 0.9950547], [0.9950547, 0.9950547]],
[[0.9950547, 0.9950547], [0.9950547, 0.9950547]],
],
],
]
)
if backend.config.image_data_format() == "channels_first":
sequence = sequence.transpose((0, 1, 5, 2, 3, 4))
expected_output = expected_output.transpose((0, 4, 1, 2, 3))
layer = layers.ConvLSTM3D(
filters=2,
kernel_size=3,
kernel_initializer=initializers.Constant(0.01),
recurrent_initializer=initializers.Constant(0.02),
bias_initializer=initializers.Constant(0.03),
)
output = layer(sequence)
self.assertAllClose(
expected_output,
output,
)
| keras/keras/layers/rnn/conv_lstm3d_test.py/0 | {
"file_path": "keras/keras/layers/rnn/conv_lstm3d_test.py",
"repo_id": "keras",
"token_count": 2283
} | 156 |
import numpy as np
import pytest
from absl.testing import parameterized
from keras import backend
from keras import layers
from keras import losses
from keras import models
from keras import testing
from keras.backend.common import standardize_dtype
from keras.backend.common.keras_tensor import KerasTensor
from keras.backend.common.variables import ALLOWED_DTYPES
from keras.layers.convolutional.conv_test import np_conv1d
from keras.layers.convolutional.conv_test import np_conv2d
from keras.layers.convolutional.conv_test import np_conv3d
from keras.layers.convolutional.conv_transpose_test import np_conv1d_transpose
from keras.layers.convolutional.conv_transpose_test import np_conv2d_transpose
from keras.layers.convolutional.depthwise_conv_test import np_depthwise_conv2d
from keras.layers.pooling.average_pooling_test import np_avgpool1d
from keras.layers.pooling.average_pooling_test import np_avgpool2d
from keras.layers.pooling.max_pooling_test import np_maxpool1d
from keras.layers.pooling.max_pooling_test import np_maxpool2d
from keras.ops import nn as knn
from keras.ops import numpy as knp
from keras.testing.test_utils import named_product
class NNOpsDynamicShapeTest(testing.TestCase, parameterized.TestCase):
def test_relu(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.relu(x).shape, (None, 2, 3))
def test_relu6(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.relu6(x).shape, (None, 2, 3))
def test_sigmoid(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.sigmoid(x).shape, (None, 2, 3))
def test_softplus(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.softplus(x).shape, (None, 2, 3))
def test_softsign(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.softsign(x).shape, (None, 2, 3))
def test_silu(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.silu(x).shape, (None, 2, 3))
def test_log_sigmoid(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.log_sigmoid(x).shape, (None, 2, 3))
def test_leaky_relu(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.leaky_relu(x).shape, (None, 2, 3))
def test_hard_sigmoid(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.hard_sigmoid(x).shape, (None, 2, 3))
def test_hard_silu(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.hard_silu(x).shape, (None, 2, 3))
def test_elu(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.elu(x).shape, (None, 2, 3))
def test_selu(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.selu(x).shape, (None, 2, 3))
def test_gelu(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.gelu(x).shape, (None, 2, 3))
def test_softmax(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.softmax(x).shape, (None, 2, 3))
self.assertEqual(knn.softmax(x, axis=1).shape, (None, 2, 3))
self.assertEqual(knn.softmax(x, axis=-1).shape, (None, 2, 3))
def test_log_softmax(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.log_softmax(x).shape, (None, 2, 3))
self.assertEqual(knn.log_softmax(x, axis=1).shape, (None, 2, 3))
self.assertEqual(knn.log_softmax(x, axis=-1).shape, (None, 2, 3))
def test_max_pool(self):
data_format = backend.config.image_data_format()
if data_format == "channels_last":
input_shape = (None, 8, 3)
else:
input_shape = (None, 3, 8)
x = KerasTensor(input_shape)
self.assertEqual(
knn.max_pool(x, 2, 1).shape,
(None, 7, 3) if data_format == "channels_last" else (None, 3, 7),
)
self.assertEqual(
knn.max_pool(x, 2, 2, padding="same").shape,
(None, 4, 3) if data_format == "channels_last" else (None, 3, 4),
)
if data_format == "channels_last":
input_shape = (None, 8, None, 3)
else:
input_shape = (None, 3, 8, None)
x = KerasTensor(input_shape)
(
self.assertEqual(knn.max_pool(x, 2, 1).shape, (None, 7, None, 3))
if data_format == "channels_last"
else (None, 3, 7, None)
)
self.assertEqual(
knn.max_pool(x, 2, 2, padding="same").shape,
(
(None, 4, None, 3)
if data_format == "channels_last"
else (None, 3, 4, None)
),
)
self.assertEqual(
knn.max_pool(x, (2, 2), (2, 2), padding="same").shape,
(
(None, 4, None, 3)
if data_format == "channels_last"
else (None, 3, 4, None)
),
)
def test_average_pool(self):
data_format = backend.config.image_data_format()
if data_format == "channels_last":
input_shape = (None, 8, 3)
else:
input_shape = (None, 3, 8)
x = KerasTensor(input_shape)
self.assertEqual(
knn.average_pool(x, 2, 1).shape,
(None, 7, 3) if data_format == "channels_last" else (None, 3, 7),
)
self.assertEqual(
knn.average_pool(x, 2, 2, padding="same").shape,
(None, 4, 3) if data_format == "channels_last" else (None, 3, 4),
)
if data_format == "channels_last":
input_shape = (None, 8, None, 3)
else:
input_shape = (None, 3, 8, None)
x = KerasTensor(input_shape)
self.assertEqual(
knn.average_pool(x, 2, 1).shape,
(
(None, 7, None, 3)
if data_format == "channels_last"
else (None, 3, 7, None)
),
)
self.assertEqual(
knn.average_pool(x, 2, 2, padding="same").shape,
(
(None, 4, None, 3)
if data_format == "channels_last"
else (None, 3, 4, None)
),
)
self.assertEqual(
knn.average_pool(x, (2, 2), (2, 2), padding="same").shape,
(
(None, 4, None, 3)
if data_format == "channels_last"
else (None, 3, 4, None)
),
)
def test_multi_hot(self):
x = KerasTensor([None, 3, 1])
self.assertEqual(knn.multi_hot(x, 5).shape, (None, 1, 5))
self.assertEqual(knn.multi_hot(x, 5, 1).shape, (None, 3, 1))
self.assertEqual(knn.multi_hot(x, 5, 2).shape, (None, 5, 1))
@parameterized.product(dtype=["float32", "int32"])
def test_multi_hot_dtype(self, dtype):
# dtype tests
x = np.arange(5)
out = knn.multi_hot(x, 5, axis=0, dtype=dtype)
self.assertEqual(backend.standardize_dtype(out.dtype), dtype)
def test_conv(self):
data_format = backend.config.image_data_format()
# Test 1D conv.
if data_format == "channels_last":
input_shape = (None, 20, 3)
else:
input_shape = (None, 3, 20)
inputs_1d = KerasTensor(input_shape)
kernel = KerasTensor([4, 3, 2])
for padding in ["valid", "VALID"]:
self.assertEqual(
knn.conv(inputs_1d, kernel, 1, padding=padding).shape,
(
(None, 17, 2)
if data_format == "channels_last"
else (None, 2, 17)
),
)
for padding in ["same", "SAME"]:
self.assertEqual(
knn.conv(inputs_1d, kernel, 1, padding=padding).shape,
(
(None, 20, 2)
if data_format == "channels_last"
else (None, 2, 20)
),
)
self.assertEqual(
knn.conv(inputs_1d, kernel, (2,), dilation_rate=2).shape,
(None, 7, 2) if data_format == "channels_last" else (None, 2, 7),
)
# Test 2D conv.
if data_format == "channels_last":
input_shape = (None, 10, None, 3)
else:
input_shape = (None, 3, 10, None)
inputs_2d = KerasTensor(input_shape)
kernel = KerasTensor([2, 2, 3, 2])
for padding in ["valid", "VALID"]:
self.assertEqual(
knn.conv(inputs_2d, kernel, 1, padding=padding).shape,
(
(None, 9, None, 2)
if data_format == "channels_last"
else (None, 2, 9, None)
),
)
for padding in ["same", "SAME"]:
self.assertEqual(
knn.conv(inputs_2d, kernel, 1, padding=padding).shape,
(
(None, 10, None, 2)
if data_format == "channels_last"
else (None, 2, 10, None)
),
)
self.assertEqual(
knn.conv(inputs_2d, kernel, (2, 1), dilation_rate=(2, 1)).shape,
(
(None, 4, None, 2)
if data_format == "channels_last"
else (None, 2, 4, None)
),
)
# Test 2D conv - H, W specified
if data_format == "channels_last":
input_shape = (None, 10, 10, 3)
else:
input_shape = (None, 3, 10, 10)
inputs_2d = KerasTensor(input_shape)
kernel = KerasTensor([2, 2, 3, 2])
for padding in ["valid", "VALID"]:
self.assertEqual(
knn.conv(inputs_2d, kernel, 1, padding=padding).shape,
(
(None, 9, 9, 2)
if data_format == "channels_last"
else (None, 2, 9, 9)
),
)
for padding in ["same", "SAME"]:
self.assertEqual(
knn.conv(inputs_2d, kernel, 1, padding=padding).shape,
(
(None, 10, 10, 2)
if data_format == "channels_last"
else (None, 2, 10, 10)
),
)
self.assertEqual(
knn.conv(inputs_2d, kernel, (2, 1), dilation_rate=(2, 1)).shape,
(
(None, 4, 9, 2)
if data_format == "channels_last"
else (None, 2, 4, 9)
),
)
# Test 3D conv.
if data_format == "channels_last":
input_shape = (None, 8, None, 8, 3)
else:
input_shape = (None, 3, 8, None, 8)
inputs_3d = KerasTensor(input_shape)
kernel = KerasTensor([3, 3, 3, 3, 2])
for padding in ["valid", "VALID"]:
self.assertEqual(
knn.conv(inputs_3d, kernel, 1, padding=padding).shape,
(
(None, 6, None, 6, 2)
if data_format == "channels_last"
else (None, 2, 6, None, 6)
),
)
for padding in ["same", "SAME"]:
self.assertEqual(
knn.conv(inputs_3d, kernel, (2, 1, 2), padding=padding).shape,
(
(None, 4, None, 4, 2)
if data_format == "channels_last"
else (None, 2, 4, None, 4)
),
)
self.assertEqual(
knn.conv(
inputs_3d, kernel, 1, padding="valid", dilation_rate=(1, 2, 2)
).shape,
(
(None, 6, None, 4, 2)
if data_format == "channels_last"
else (None, 2, 6, None, 4)
),
)
def test_depthwise_conv(self):
data_format = backend.config.image_data_format()
# Test 1D depthwise conv.
if data_format == "channels_last":
input_shape = (None, 20, 3)
else:
input_shape = (None, 3, 20)
inputs_1d = KerasTensor(input_shape)
kernel = KerasTensor([4, 3, 1])
for padding in ["valid", "VALID"]:
self.assertEqual(
knn.depthwise_conv(inputs_1d, kernel, 1, padding=padding).shape,
(
(None, 17, 3)
if data_format == "channels_last"
else (None, 3, 17)
),
)
for padding in ["same", "SAME"]:
self.assertEqual(
knn.depthwise_conv(
inputs_1d, kernel, (1,), padding=padding
).shape,
(
(None, 20, 3)
if data_format == "channels_last"
else (None, 3, 20)
),
)
self.assertEqual(
knn.depthwise_conv(inputs_1d, kernel, 2, dilation_rate=2).shape,
(None, 7, 3) if data_format == "channels_last" else (None, 3, 7),
)
# Test 2D depthwise conv.
if data_format == "channels_last":
input_shape = (None, 10, 10, 3)
else:
input_shape = (None, 3, 10, 10)
inputs_2d = KerasTensor(input_shape)
kernel = KerasTensor([2, 2, 3, 1])
for padding in ["valid", "VALID"]:
self.assertEqual(
knn.depthwise_conv(inputs_2d, kernel, 1, padding=padding).shape,
(
(None, 9, 9, 3)
if data_format == "channels_last"
else (None, 3, 9, 9)
),
)
for padding in ["same", "SAME"]:
self.assertEqual(
knn.depthwise_conv(
inputs_2d, kernel, (1, 2), padding=padding
).shape,
(
(None, 10, 5, 3)
if data_format == "channels_last"
else (None, 3, 10, 5)
),
)
self.assertEqual(
knn.depthwise_conv(inputs_2d, kernel, 2, dilation_rate=2).shape,
(
(None, 4, 4, 3)
if data_format == "channels_last"
else (None, 3, 4, 4)
),
)
self.assertEqual(
knn.depthwise_conv(
inputs_2d, kernel, 2, dilation_rate=(2, 1)
).shape,
(
(None, 4, 5, 3)
if data_format == "channels_last"
else (None, 3, 4, 5)
),
)
def test_separable_conv(self):
data_format = backend.config.image_data_format()
# Test 1D separable conv.
if data_format == "channels_last":
input_shape = (None, 20, 3)
else:
input_shape = (None, 3, 20)
inputs_1d = KerasTensor(input_shape)
kernel = KerasTensor([4, 3, 2])
pointwise_kernel = KerasTensor([1, 6, 5])
self.assertEqual(
knn.separable_conv(
inputs_1d, kernel, pointwise_kernel, 1, padding="valid"
).shape,
(None, 17, 5) if data_format == "channels_last" else (None, 5, 17),
)
self.assertEqual(
knn.separable_conv(
inputs_1d, kernel, pointwise_kernel, 1, padding="same"
).shape,
(None, 20, 5) if data_format == "channels_last" else (None, 5, 20),
)
self.assertEqual(
knn.separable_conv(
inputs_1d, kernel, pointwise_kernel, 2, dilation_rate=2
).shape,
(None, 7, 5) if data_format == "channels_last" else (None, 5, 7),
)
# Test 2D separable conv.
if data_format == "channels_last":
input_shape = (None, 10, 10, 3)
else:
input_shape = (None, 3, 10, 10)
inputs_2d = KerasTensor(input_shape)
kernel = KerasTensor([2, 2, 3, 2])
pointwise_kernel = KerasTensor([1, 1, 6, 5])
self.assertEqual(
knn.separable_conv(
inputs_2d, kernel, pointwise_kernel, 1, padding="valid"
).shape,
(
(None, 9, 9, 5)
if data_format == "channels_last"
else (None, 5, 9, 9)
),
)
self.assertEqual(
knn.separable_conv(
inputs_2d, kernel, pointwise_kernel, (1, 2), padding="same"
).shape,
(
(None, 10, 5, 5)
if data_format == "channels_last"
else (None, 5, 10, 5)
),
)
self.assertEqual(
knn.separable_conv(
inputs_2d, kernel, pointwise_kernel, 2, dilation_rate=(2, 1)
).shape,
(
(None, 4, 5, 5)
if data_format == "channels_last"
else (None, 5, 4, 5)
),
)
def test_conv_transpose(self):
data_format = backend.config.image_data_format()
if data_format == "channels_last":
input_shape = (None, 4, 3)
else:
input_shape = (None, 3, 4)
inputs_1d = KerasTensor(input_shape)
kernel = KerasTensor([2, 5, 3])
self.assertEqual(
knn.conv_transpose(inputs_1d, kernel, 2).shape,
(None, 8, 5) if data_format == "channels_last" else (None, 5, 8),
)
self.assertEqual(
knn.conv_transpose(inputs_1d, kernel, 2, padding="same").shape,
(None, 8, 5) if data_format == "channels_last" else (None, 5, 8),
)
self.assertEqual(
knn.conv_transpose(
inputs_1d, kernel, 5, padding="valid", output_padding=4
).shape,
(None, 21, 5) if data_format == "channels_last" else (None, 5, 21),
)
if data_format == "channels_last":
input_shape = (None, 4, 4, 3)
else:
input_shape = (None, 3, 4, 4)
inputs_2d = KerasTensor(input_shape)
kernel = KerasTensor([2, 2, 5, 3])
self.assertEqual(
knn.conv_transpose(inputs_2d, kernel, 2).shape,
(
(None, 8, 8, 5)
if data_format == "channels_last"
else (None, 5, 8, 8)
),
)
self.assertEqual(
knn.conv_transpose(inputs_2d, kernel, (2, 2), padding="same").shape,
(
(None, 8, 8, 5)
if data_format == "channels_last"
else (None, 5, 8, 8)
),
)
self.assertEqual(
knn.conv_transpose(
inputs_2d, kernel, (5, 5), padding="valid", output_padding=4
).shape,
(
(None, 21, 21, 5)
if data_format == "channels_last"
else (None, 5, 21, 21)
),
)
def test_one_hot(self):
x = KerasTensor([None, 3, 1])
self.assertEqual(knn.one_hot(x, 5).shape, (None, 3, 1, 5))
self.assertEqual(knn.one_hot(x, 5, 1).shape, (None, 5, 3, 1))
self.assertEqual(knn.one_hot(x, 5, 2).shape, (None, 3, 5, 1))
@parameterized.product(dtype=["float32", "int32"])
def test_one_hot_dtype(self, dtype):
# dtype tests
x = np.arange(5)
out = knn.one_hot(x, 5, axis=0, dtype=dtype)
self.assertEqual(backend.standardize_dtype(out.dtype), dtype)
def test_moments(self):
x = KerasTensor([None, 3, 4])
self.assertEqual(knn.moments(x, axes=[0])[0].shape, (3, 4))
self.assertEqual(knn.moments(x, axes=[0, 1])[0].shape, (4,))
self.assertEqual(
knn.moments(x, axes=[0, 1], keepdims=True)[0].shape, (1, 1, 4)
)
self.assertEqual(knn.moments(x, axes=[1])[0].shape, (None, 4))
self.assertEqual(knn.moments(x, axes=[1, 2])[0].shape, (None,))
self.assertEqual(
knn.moments(x, axes=[1, 2], keepdims=True)[0].shape, (None, 1, 1)
)
def test_batch_normalization(self):
x = KerasTensor([None, 3, 4])
mean = KerasTensor([4])
variance = KerasTensor([4])
self.assertEqual(
knn.batch_normalization(x, mean, variance, axis=-1).shape,
(None, 3, 4),
)
x = KerasTensor([None, 3, 4, 5])
self.assertEqual(
knn.batch_normalization(x, mean, variance, axis=2).shape,
(None, 3, 4, 5),
)
mean = KerasTensor([3])
variance = KerasTensor([3])
self.assertEqual(
knn.batch_normalization(x, mean, variance, axis=1).shape,
(None, 3, 4, 5),
)
# Test wrong offset shape
self.assertRaisesRegex(
ValueError,
"`offset` must be a vector of length",
knn.batch_normalization,
KerasTensor([None, 3, 4, 5]),
KerasTensor([5]),
KerasTensor([5]),
axis=-1,
offset=KerasTensor([3]),
scale=KerasTensor([5]),
)
# Test wrong scale shape
self.assertRaisesRegex(
ValueError,
"`scale` must be a vector of length",
knn.batch_normalization,
KerasTensor([None, 3, 4, 5]),
KerasTensor([5]),
KerasTensor([5]),
axis=-1,
offset=KerasTensor([5]),
scale=KerasTensor([3]),
)
def test_normalize(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.normalize(x).shape, (None, 2, 3))
class NNOpsStaticShapeTest(testing.TestCase):
def test_relu(self):
x = KerasTensor([1, 2, 3])
self.assertEqual(knn.relu(x).shape, (1, 2, 3))
def test_relu6(self):
x = KerasTensor([1, 2, 3])
self.assertEqual(knn.relu6(x).shape, (1, 2, 3))
def test_sigmoid(self):
x = KerasTensor([1, 2, 3])
self.assertEqual(knn.sigmoid(x).shape, (1, 2, 3))
def test_softplus(self):
x = KerasTensor([1, 2, 3])
self.assertEqual(knn.softplus(x).shape, (1, 2, 3))
def test_softsign(self):
x = KerasTensor([1, 2, 3])
self.assertEqual(knn.softsign(x).shape, (1, 2, 3))
def test_silu(self):
x = KerasTensor([1, 2, 3])
self.assertEqual(knn.silu(x).shape, (1, 2, 3))
def test_log_sigmoid(self):
x = KerasTensor([1, 2, 3])
self.assertEqual(knn.log_sigmoid(x).shape, (1, 2, 3))
def test_leaky_relu(self):
x = KerasTensor([1, 2, 3])
self.assertEqual(knn.leaky_relu(x).shape, (1, 2, 3))
def test_hard_sigmoid(self):
x = KerasTensor([1, 2, 3])
self.assertEqual(knn.hard_sigmoid(x).shape, (1, 2, 3))
def test_hard_silu(self):
x = KerasTensor([1, 2, 3])
self.assertEqual(knn.hard_silu(x).shape, (1, 2, 3))
def test_elu(self):
x = KerasTensor([1, 2, 3])
self.assertEqual(knn.elu(x).shape, (1, 2, 3))
def test_selu(self):
x = KerasTensor([1, 2, 3])
self.assertEqual(knn.selu(x).shape, (1, 2, 3))
def test_gelu(self):
x = KerasTensor([1, 2, 3])
self.assertEqual(knn.gelu(x).shape, (1, 2, 3))
def test_softmax(self):
x = KerasTensor([1, 2, 3])
self.assertEqual(knn.softmax(x).shape, (1, 2, 3))
self.assertEqual(knn.softmax(x, axis=1).shape, (1, 2, 3))
self.assertEqual(knn.softmax(x, axis=-1).shape, (1, 2, 3))
def test_log_softmax(self):
x = KerasTensor([1, 2, 3])
self.assertEqual(knn.log_softmax(x).shape, (1, 2, 3))
self.assertEqual(knn.log_softmax(x, axis=1).shape, (1, 2, 3))
self.assertEqual(knn.log_softmax(x, axis=-1).shape, (1, 2, 3))
def test_max_pool(self):
data_format = backend.config.image_data_format()
if data_format == "channels_last":
input_shape = (1, 8, 3)
else:
input_shape = (1, 3, 8)
x = KerasTensor(input_shape)
self.assertEqual(
knn.max_pool(x, 2, 1).shape,
(1, 7, 3) if data_format == "channels_last" else (1, 3, 7),
)
self.assertEqual(
knn.max_pool(x, 2, 2, padding="same").shape,
(1, 4, 3) if data_format == "channels_last" else (1, 3, 4),
)
if data_format == "channels_last":
input_shape = (1, 8, 8, 3)
else:
input_shape = (1, 3, 8, 8)
x = KerasTensor(input_shape)
self.assertEqual(
knn.max_pool(x, 2, 1).shape,
(1, 7, 7, 3) if data_format == "channels_last" else (1, 3, 7, 7),
)
self.assertEqual(
knn.max_pool(x, 2, 2, padding="same").shape,
(1, 4, 4, 3) if data_format == "channels_last" else (1, 3, 4, 4),
)
self.assertEqual(
knn.max_pool(x, (2, 2), (2, 2), padding="same").shape,
(1, 4, 4, 3) if data_format == "channels_last" else (1, 3, 4, 4),
)
def test_average_pool(self):
data_format = backend.config.image_data_format()
if data_format == "channels_last":
input_shape = (1, 8, 3)
else:
input_shape = (1, 3, 8)
x = KerasTensor(input_shape)
self.assertEqual(
knn.average_pool(x, 2, 1).shape,
(1, 7, 3) if data_format == "channels_last" else (1, 3, 7),
)
self.assertEqual(
knn.average_pool(x, 2, 2, padding="same").shape,
(1, 4, 3) if data_format == "channels_last" else (1, 3, 4),
)
if data_format == "channels_last":
input_shape = (1, 8, 8, 3)
else:
input_shape = (1, 3, 8, 8)
x = KerasTensor(input_shape)
self.assertEqual(
knn.average_pool(x, 2, 1).shape,
(1, 7, 7, 3) if data_format == "channels_last" else (1, 3, 7, 7),
)
self.assertEqual(
knn.average_pool(x, 2, 2, padding="same").shape,
(1, 4, 4, 3) if data_format == "channels_last" else (1, 3, 4, 4),
)
self.assertEqual(
knn.average_pool(x, (2, 2), (2, 2), padding="same").shape,
(1, 4, 4, 3) if data_format == "channels_last" else (1, 3, 4, 4),
)
def test_conv(self):
data_format = backend.config.image_data_format()
# Test 1D conv.
if data_format == "channels_last":
input_shape = (2, 20, 3)
else:
input_shape = (2, 3, 20)
inputs_1d = KerasTensor(input_shape)
kernel = KerasTensor([4, 3, 2])
self.assertEqual(
knn.conv(inputs_1d, kernel, 1, padding="valid").shape,
(2, 17, 2) if data_format == "channels_last" else (2, 2, 17),
)
self.assertEqual(
knn.conv(inputs_1d, kernel, 1, padding="same").shape,
(2, 20, 2) if data_format == "channels_last" else (2, 2, 20),
)
self.assertEqual(
knn.conv(inputs_1d, kernel, (2,), dilation_rate=2).shape,
(2, 7, 2) if data_format == "channels_last" else (2, 2, 7),
)
# Test 2D conv.
if data_format == "channels_last":
input_shape = (2, 10, 10, 3)
else:
input_shape = (2, 3, 10, 10)
inputs_2d = KerasTensor(input_shape)
kernel = KerasTensor([2, 2, 3, 2])
self.assertEqual(
knn.conv(inputs_2d, kernel, 1, padding="valid").shape,
(2, 9, 9, 2) if data_format == "channels_last" else (2, 2, 9, 9),
)
self.assertEqual(
knn.conv(inputs_2d, kernel, 1, padding="same").shape,
(
(2, 10, 10, 2)
if data_format == "channels_last"
else (2, 2, 10, 10)
),
)
self.assertEqual(
knn.conv(inputs_2d, kernel, (2, 1), dilation_rate=(2, 1)).shape,
(2, 4, 9, 2) if data_format == "channels_last" else (2, 2, 4, 9),
)
# Test 3D conv.
if data_format == "channels_last":
input_shape = (2, 8, 8, 8, 3)
else:
input_shape = (2, 3, 8, 8, 8)
inputs_3d = KerasTensor(input_shape)
kernel = KerasTensor([3, 3, 3, 3, 2])
self.assertEqual(
knn.conv(inputs_3d, kernel, 1, padding="valid").shape,
(
(2, 6, 6, 6, 2)
if data_format == "channels_last"
else (2, 2, 6, 6, 6)
),
)
self.assertEqual(
knn.conv(inputs_3d, kernel, (2, 1, 2), padding="same").shape,
(
(2, 4, 8, 4, 2)
if data_format == "channels_last"
else (2, 2, 4, 8, 4)
),
)
self.assertEqual(
knn.conv(
inputs_3d, kernel, 1, padding="valid", dilation_rate=(1, 2, 2)
).shape,
(
(2, 6, 4, 4, 2)
if data_format == "channels_last"
else (2, 2, 6, 4, 4)
),
)
def test_depthwise_conv(self):
data_format = backend.config.image_data_format()
# Test 1D depthwise conv.
if data_format == "channels_last":
input_shape = (2, 20, 3)
else:
input_shape = (2, 3, 20)
inputs_1d = KerasTensor(input_shape)
kernel = KerasTensor([4, 3, 1])
self.assertEqual(
knn.depthwise_conv(inputs_1d, kernel, 1, padding="valid").shape,
(2, 17, 3) if data_format == "channels_last" else (2, 3, 17),
)
self.assertEqual(
knn.depthwise_conv(inputs_1d, kernel, (1,), padding="same").shape,
(2, 20, 3) if data_format == "channels_last" else (2, 3, 20),
)
self.assertEqual(
knn.depthwise_conv(inputs_1d, kernel, 2, dilation_rate=2).shape,
(2, 7, 3) if data_format == "channels_last" else (2, 3, 7),
)
# Test 2D depthwise conv.
if data_format == "channels_last":
input_shape = (2, 10, 10, 3)
else:
input_shape = (2, 3, 10, 10)
inputs_2d = KerasTensor(input_shape)
kernel = KerasTensor([2, 2, 3, 1])
self.assertEqual(
knn.depthwise_conv(inputs_2d, kernel, 1, padding="valid").shape,
(2, 9, 9, 3) if data_format == "channels_last" else (2, 3, 9, 9),
)
self.assertEqual(
knn.depthwise_conv(inputs_2d, kernel, (1, 2), padding="same").shape,
(2, 10, 5, 3) if data_format == "channels_last" else (2, 3, 10, 5),
)
self.assertEqual(
knn.depthwise_conv(inputs_2d, kernel, 2, dilation_rate=2).shape,
(2, 4, 4, 3) if data_format == "channels_last" else (2, 3, 4, 4),
)
self.assertEqual(
knn.depthwise_conv(
inputs_2d, kernel, 2, dilation_rate=(2, 1)
).shape,
(2, 4, 5, 3) if data_format == "channels_last" else (2, 3, 4, 5),
)
def test_separable_conv(self):
data_format = backend.config.image_data_format()
# Test 1D max pooling.
if data_format == "channels_last":
input_shape = (2, 20, 3)
else:
input_shape = (2, 3, 20)
inputs_1d = KerasTensor(input_shape)
kernel = KerasTensor([4, 3, 2])
pointwise_kernel = KerasTensor([1, 6, 5])
self.assertEqual(
knn.separable_conv(
inputs_1d, kernel, pointwise_kernel, 1, padding="valid"
).shape,
(2, 17, 5) if data_format == "channels_last" else (2, 5, 17),
)
self.assertEqual(
knn.separable_conv(
inputs_1d, kernel, pointwise_kernel, 1, padding="same"
).shape,
(2, 20, 5) if data_format == "channels_last" else (2, 5, 20),
)
self.assertEqual(
knn.separable_conv(
inputs_1d, kernel, pointwise_kernel, 2, dilation_rate=2
).shape,
(2, 7, 5) if data_format == "channels_last" else (2, 5, 7),
)
# Test 2D separable conv.
if data_format == "channels_last":
input_shape = (2, 10, 10, 3)
else:
input_shape = (2, 3, 10, 10)
inputs_2d = KerasTensor(input_shape)
kernel = KerasTensor([2, 2, 3, 2])
pointwise_kernel = KerasTensor([1, 1, 6, 5])
self.assertEqual(
knn.separable_conv(
inputs_2d, kernel, pointwise_kernel, 1, padding="valid"
).shape,
(2, 9, 9, 5) if data_format == "channels_last" else (2, 5, 9, 9),
)
self.assertEqual(
knn.separable_conv(
inputs_2d, kernel, pointwise_kernel, (1, 2), padding="same"
).shape,
(2, 10, 5, 5) if data_format == "channels_last" else (2, 5, 10, 5),
)
self.assertEqual(
knn.separable_conv(
inputs_2d, kernel, pointwise_kernel, 2, dilation_rate=(2, 1)
).shape,
(2, 4, 5, 5) if data_format == "channels_last" else (2, 5, 4, 5),
)
def test_conv_transpose(self):
data_format = backend.config.image_data_format()
if data_format == "channels_last":
input_shape = (2, 4, 3)
else:
input_shape = (2, 3, 4)
inputs_1d = KerasTensor(input_shape)
kernel = KerasTensor([2, 5, 3])
self.assertEqual(
knn.conv_transpose(inputs_1d, kernel, 2).shape,
(2, 8, 5) if data_format == "channels_last" else (2, 5, 8),
)
self.assertEqual(
knn.conv_transpose(inputs_1d, kernel, 2, padding="same").shape,
(2, 8, 5) if data_format == "channels_last" else (2, 5, 8),
)
self.assertEqual(
knn.conv_transpose(
inputs_1d, kernel, 5, padding="valid", output_padding=4
).shape,
(2, 21, 5) if data_format == "channels_last" else (2, 5, 21),
)
if data_format == "channels_last":
input_shape = (2, 4, 4, 3)
else:
input_shape = (2, 3, 4, 4)
inputs_2d = KerasTensor(input_shape)
kernel = KerasTensor([2, 2, 5, 3])
self.assertEqual(
knn.conv_transpose(inputs_2d, kernel, 2).shape,
(2, 8, 8, 5) if data_format == "channels_last" else (2, 5, 8, 8),
)
self.assertEqual(
knn.conv_transpose(inputs_2d, kernel, (2, 2), padding="same").shape,
(2, 8, 8, 5) if data_format == "channels_last" else (2, 5, 8, 8),
)
self.assertEqual(
knn.conv_transpose(
inputs_2d, kernel, (5, 5), padding="valid", output_padding=4
).shape,
(
(2, 21, 21, 5)
if data_format == "channels_last"
else (2, 5, 21, 21)
),
)
def test_batched_and_unbatched_inputs_multi_hot(self):
x = KerasTensor([2, 3, 1])
unbatched_input = KerasTensor(
[
5,
]
)
self.assertEqual(knn.multi_hot(unbatched_input, 5, -1).shape, (5,))
self.assertEqual(knn.multi_hot(x, 5).shape, (2, 1, 5))
self.assertEqual(knn.multi_hot(x, 5, 1).shape, (2, 3, 1))
self.assertEqual(knn.multi_hot(x, 5, 2).shape, (2, 5, 1))
def test_one_hot(self):
x = KerasTensor([2, 3, 1])
self.assertEqual(knn.one_hot(x, 5).shape, (2, 3, 1, 5))
self.assertEqual(knn.one_hot(x, 5, 1).shape, (2, 5, 3, 1))
self.assertEqual(knn.one_hot(x, 5, 2).shape, (2, 3, 5, 1))
def test_binary_crossentropy(self):
x1 = KerasTensor([2, 3, 1])
x2 = KerasTensor([2, 3, 1])
self.assertEqual(knn.binary_crossentropy(x1, x2).shape, (2, 3, 1))
def test_categorical_crossentropy(self):
x1 = KerasTensor([2, 3, 4])
x2 = KerasTensor([2, 3, 4])
self.assertEqual(knn.categorical_crossentropy(x1, x2).shape, (2, 3))
def test_sparse_categorical_crossentropy(self):
x1 = KerasTensor([2, 3], dtype="int32")
x2 = KerasTensor([2, 3, 4])
self.assertEqual(
knn.sparse_categorical_crossentropy(x1, x2).shape, (2, 3)
)
def test_moments(self):
x = KerasTensor([2, 3, 4])
self.assertEqual(knn.moments(x, axes=[0])[0].shape, (3, 4))
self.assertEqual(knn.moments(x, axes=[0, 1])[0].shape, (4,))
self.assertEqual(
knn.moments(x, axes=[0, 1], keepdims=True)[0].shape, (1, 1, 4)
)
def test_batch_normalization(self):
x = KerasTensor([10, 3, 4])
mean = KerasTensor([4])
variance = KerasTensor([4])
self.assertEqual(
knn.batch_normalization(x, mean, variance, axis=-1).shape,
(10, 3, 4),
)
x = KerasTensor([10, 3, 4, 5])
self.assertEqual(
knn.batch_normalization(x, mean, variance, axis=2).shape,
(10, 3, 4, 5),
)
mean = KerasTensor([3])
variance = KerasTensor([3])
self.assertEqual(
knn.batch_normalization(x, mean, variance, axis=1).shape,
(10, 3, 4, 5),
)
@pytest.mark.skipif(
backend.backend() == "numpy",
reason="Numpy does not support CTC loss",
)
def test_ctc_loss(self):
x = KerasTensor([10, 3, 4])
y = KerasTensor([10, 3], dtype="int32")
x_lengths = KerasTensor([10], dtype="int32")
y_lengths = KerasTensor([10], dtype="int32")
self.assertEqual(knn.ctc_loss(x, y, x_lengths, y_lengths).shape, (10,))
def test_normalize(self):
x = KerasTensor([1, 2, 3])
self.assertEqual(knn.normalize(x).shape, (1, 2, 3))
class NNOpsCorrectnessTest(testing.TestCase, parameterized.TestCase):
def test_relu(self):
x = np.array([-1, 0, 1, 2, 3], dtype=np.float32)
self.assertAllClose(knn.relu(x), [0, 0, 1, 2, 3])
def test_relu6(self):
x = np.array([-1, 0, 1, 2, 3, 4, 5, 6, 7], dtype=np.float32)
self.assertAllClose(knn.relu6(x), [0, 0, 1, 2, 3, 4, 5, 6, 6])
def test_sigmoid(self):
x = np.array([-1, 0, 1, 2, 3], dtype=np.float32)
self.assertAllClose(
knn.sigmoid(x), [0.26894143, 0.5, 0.7310586, 0.880797, 0.95257413]
)
def test_softplus(self):
x = np.array([-1, 0, 1, 2, 3], dtype=np.float32)
self.assertAllClose(
knn.softplus(x),
[0.31326166, 0.6931472, 1.3132616, 2.126928, 3.0485873],
)
def test_softsign(self):
x = np.array([-1, 0, 1, 2, 3], dtype=np.float32)
self.assertAllClose(knn.softsign(x), [-0.5, 0, 0.5, 0.6666667, 0.75])
def test_silu(self):
x = np.array([-1, 0, 1, 2, 3], dtype=np.float32)
self.assertAllClose(
knn.silu(x),
[-0.26894143, 0, 0.7310586, 1.7615942, 2.8577223],
)
def test_log_sigmoid(self):
x = np.array([-1, 0, 1, 2, 3], dtype=np.float32)
self.assertAllClose(
knn.log_sigmoid(x),
[-1.3132616, -0.6931472, -0.31326166, -0.126928, -0.04858732],
)
def test_leaky_relu(self):
x = np.array([-1, 0, 1, 2, 3], dtype=np.float32)
self.assertAllClose(
knn.leaky_relu(x),
[-0.2, 0, 1, 2, 3],
)
def test_hard_sigmoid(self):
x = np.array([-1, 0, 1, 2, 3], dtype=np.float32)
self.assertAllClose(
knn.hard_sigmoid(x),
[0.33333334, 0.5, 0.6666667, 0.8333334, 1.0],
)
def test_hard_silu(self):
x = np.array([-3, -2, -1, 0, 1, 2, 3], dtype=np.float32)
self.assertAllClose(
knn.hard_silu(x),
[-0.0, -0.333333, -0.333333, 0.0, 0.6666667, 1.6666667, 3.0],
)
def test_elu(self):
x = np.array([-1, 0, 1, 2, 3], dtype=np.float32)
self.assertAllClose(
knn.elu(x),
[-0.63212055, 0, 1, 2, 3],
)
self.assertAllClose(
knn.elu(x, alpha=0.5),
[-0.31606027, 0, 1, 2, 3],
)
def test_selu(self):
x = np.array([-1, 0, 1, 2, 3], dtype=np.float32)
self.assertAllClose(
knn.selu(x),
[-1.1113307, 0.0, 1.050701, 2.101402, 3.152103],
)
def test_gelu(self):
x = np.array([-1, 0, 1, 2, 3], dtype=np.float32)
self.assertAllClose(
knn.gelu(x),
[-0.15880796, 0.0, 0.841192, 1.9545977, 2.9963627],
)
def test_softmax(self):
x = np.array([[1, 2, 3], [1, 2, 3]], dtype=np.float32)
self.assertAllClose(
knn.softmax(x, axis=None), # Reduce on all axes.
[[0.045015, 0.122364, 0.33262], [0.045015, 0.122364, 0.33262]],
)
self.assertAllClose(
knn.softmax(x, axis=0),
[[0.5, 0.5, 0.5], [0.5, 0.5, 0.5]],
)
self.assertAllClose(
knn.softmax(x, axis=-1),
[
[0.09003057, 0.24472848, 0.66524094],
[0.09003057, 0.24472848, 0.66524094],
],
)
self.assertAllClose(
knn.softmax(x), # Default axis should be -1.
[
[0.09003057, 0.24472848, 0.66524094],
[0.09003057, 0.24472848, 0.66524094],
],
)
def test_log_softmax(self):
x = np.array([[1, 2, 3], [1, 2, 3]], dtype=np.float32)
self.assertAllClose(
knn.log_softmax(x, axis=None), # Reduce on all axes.
[
[-3.100753, -2.100753, -1.100753],
[-3.100753, -2.100753, -1.100753],
],
)
self.assertAllClose(
knn.log_softmax(x, axis=0),
[
[-0.693147, -0.693147, -0.693147],
[-0.693147, -0.693147, -0.693147],
],
)
self.assertAllClose(
knn.log_softmax(x, axis=-1),
[
[-2.407606, -1.407606, -0.407606],
[-2.407606, -1.407606, -0.407606],
],
)
self.assertAllClose(
knn.log_softmax(x), # Default axis should be -1.
[
[-2.407606, -1.407606, -0.407606],
[-2.407606, -1.407606, -0.407606],
],
)
def test_max_pool(self):
data_format = backend.config.image_data_format()
# Test 1D max pooling.
if data_format == "channels_last":
input_shape = (2, 20, 3)
else:
input_shape = (2, 3, 20)
x = np.arange(120, dtype=float).reshape(input_shape)
self.assertAllClose(
knn.max_pool(x, 2, 1, padding="valid"),
np_maxpool1d(x, 2, 1, padding="valid", data_format=data_format),
)
self.assertAllClose(
knn.max_pool(x, 2, 2, padding="same"),
np_maxpool1d(x, 2, 2, padding="same", data_format=data_format),
)
# Test 2D max pooling.
if data_format == "channels_last":
input_shape = (2, 10, 9, 3)
else:
input_shape = (2, 3, 10, 9)
x = np.arange(540, dtype=float).reshape(input_shape)
self.assertAllClose(
knn.max_pool(x, 2, 1, padding="valid"),
np_maxpool2d(x, 2, 1, padding="valid", data_format=data_format),
)
self.assertAllClose(
knn.max_pool(x, 2, (2, 1), padding="same"),
np_maxpool2d(x, 2, (2, 1), padding="same", data_format=data_format),
)
def test_average_pool_valid_padding(self):
data_format = backend.config.image_data_format()
# Test 1D max pooling.
if data_format == "channels_last":
input_shape = (2, 20, 3)
else:
input_shape = (2, 3, 20)
x = np.arange(120, dtype=float).reshape(input_shape)
self.assertAllClose(
knn.average_pool(x, 2, 1, padding="valid"),
np_avgpool1d(x, 2, 1, padding="valid", data_format=data_format),
)
# Test 2D max pooling.
if data_format == "channels_last":
input_shape = (2, 10, 9, 3)
else:
input_shape = (2, 3, 10, 9)
x = np.arange(540, dtype=float).reshape(input_shape)
self.assertAllClose(
knn.average_pool(x, 2, 1, padding="valid"),
np_avgpool2d(x, 2, 1, padding="valid", data_format=data_format),
)
@pytest.mark.skipif(
backend.backend() == "torch",
reason="Torch outputs differently from TF when using `same` padding.",
)
def test_average_pool_same_padding(self):
data_format = backend.config.image_data_format()
# Test 1D max pooling.
if data_format == "channels_last":
input_shape = (2, 20, 3)
else:
input_shape = (2, 3, 20)
x = np.arange(120, dtype=float).reshape(input_shape)
self.assertAllClose(
knn.average_pool(x, 2, 2, padding="same"),
np_avgpool1d(x, 2, 2, padding="same", data_format=data_format),
)
# Test 2D max pooling.
if data_format == "channels_last":
input_shape = (2, 10, 9, 3)
else:
input_shape = (2, 3, 10, 9)
x = np.arange(540, dtype=float).reshape(input_shape)
self.assertAllClose(
knn.average_pool(x, 2, (2, 1), padding="same"),
np_avgpool2d(x, 2, (2, 1), padding="same", data_format=data_format),
)
@parameterized.product(
strides=(1, 2, 3),
padding=("valid", "same"),
dilation_rate=(1, 2),
)
def test_conv_1d(self, strides, padding, dilation_rate):
if strides > 1 and dilation_rate > 1:
pytest.skip("Unsupported configuration")
if backend.config.image_data_format() == "channels_last":
input_shape = (2, 20, 3)
else:
input_shape = (2, 3, 20)
inputs_1d = np.arange(120, dtype=float).reshape(input_shape)
kernel = np.arange(24, dtype=float).reshape([4, 3, 2])
outputs = knn.conv(
inputs_1d,
kernel,
strides=strides,
padding=padding,
dilation_rate=dilation_rate,
)
expected = np_conv1d(
inputs_1d,
kernel,
bias_weights=np.zeros((2,)),
strides=strides,
padding=padding.lower(),
data_format=backend.config.image_data_format(),
dilation_rate=dilation_rate,
groups=1,
)
self.assertAllClose(outputs, expected)
@parameterized.product(strides=(1, 2, (1, 2)), padding=("valid", "same"))
def test_conv_2d(self, strides, padding):
if backend.config.image_data_format() == "channels_last":
input_shape = (2, 10, 10, 3)
else:
input_shape = (2, 3, 10, 10)
inputs_2d = np.arange(600, dtype=float).reshape(input_shape)
kernel = np.arange(24, dtype=float).reshape([2, 2, 3, 2])
outputs = knn.conv(inputs_2d, kernel, strides, padding=padding)
expected = np_conv2d(
inputs_2d,
kernel,
bias_weights=np.zeros((2,)),
strides=strides,
padding=padding,
data_format=backend.config.image_data_format(),
dilation_rate=1,
groups=1,
)
self.assertAllClose(outputs, expected)
@parameterized.product(strides=(1, 2), dilation_rate=(1, (2, 1)))
def test_conv_2d_group_2(self, strides, dilation_rate):
if (
backend.backend() == "tensorflow"
and strides == 2
and dilation_rate == (2, 1)
):
# This case is not supported by the TF backend.
return
if backend.config.image_data_format() == "channels_last":
input_shape = (2, 10, 10, 4)
else:
input_shape = (2, 4, 10, 10)
inputs_2d = np.ones(input_shape)
kernel = np.ones([2, 2, 2, 6])
outputs = knn.conv(
inputs_2d,
kernel,
strides,
padding="same",
dilation_rate=dilation_rate,
)
expected = np_conv2d(
inputs_2d,
kernel,
bias_weights=np.zeros((6,)),
strides=strides,
padding="same",
data_format=backend.config.image_data_format(),
dilation_rate=dilation_rate,
groups=1,
)
self.assertAllClose(outputs, expected)
@parameterized.product(strides=(1, (1, 1, 1), 2), padding=("valid", "same"))
def test_conv_3d(self, strides, padding):
if backend.config.image_data_format() == "channels_last":
input_shape = (2, 8, 8, 8, 3)
else:
input_shape = (2, 3, 8, 8, 8)
inputs_3d = np.arange(3072, dtype=float).reshape(input_shape)
kernel = np.arange(162, dtype=float).reshape([3, 3, 3, 3, 2])
outputs = knn.conv(inputs_3d, kernel, strides, padding=padding)
expected = np_conv3d(
inputs_3d,
kernel,
bias_weights=np.zeros((2,)),
strides=strides,
padding=padding,
data_format=backend.config.image_data_format(),
dilation_rate=1,
groups=1,
)
self.assertAllClose(outputs, expected, rtol=1e-5, atol=1e-5)
@parameterized.product(
strides=(1, (1, 1), (2, 2)),
padding=("valid", "same"),
dilation_rate=(1, (2, 2)),
)
def test_depthwise_conv_2d(self, strides, padding, dilation_rate):
if (
backend.backend() == "tensorflow"
and strides == (2, 2)
and dilation_rate == (2, 2)
):
# This case is not supported by the TF backend.
return
print(strides, padding, dilation_rate)
if backend.config.image_data_format() == "channels_last":
input_shape = (2, 10, 10, 3)
else:
input_shape = (2, 3, 10, 10)
inputs_2d = np.arange(600, dtype=float).reshape(input_shape)
kernel = np.arange(24, dtype=float).reshape([2, 2, 3, 2])
outputs = knn.depthwise_conv(
inputs_2d,
kernel,
strides,
padding=padding,
dilation_rate=dilation_rate,
)
expected = np_depthwise_conv2d(
inputs_2d,
kernel,
bias_weights=np.zeros((6,)),
strides=strides,
padding=padding,
data_format=backend.config.image_data_format(),
dilation_rate=dilation_rate,
)
self.assertAllClose(outputs, expected)
@parameterized.product(
strides=(1, 2),
padding=("valid", "same"),
dilation_rate=(1, (2, 2)),
)
def test_separable_conv_2d(self, strides, padding, dilation_rate):
if (
backend.backend() == "tensorflow"
and strides == 2
and dilation_rate == (2, 2)
):
# This case is not supported by the TF backend.
return
# Test 2D conv.
if backend.config.image_data_format() == "channels_last":
input_shape = (2, 10, 10, 3)
else:
input_shape = (2, 3, 10, 10)
inputs_2d = np.arange(600, dtype=float).reshape(input_shape)
depthwise_kernel = np.arange(24, dtype=float).reshape([2, 2, 3, 2])
pointwise_kernel = np.arange(72, dtype=float).reshape([1, 1, 6, 12])
outputs = knn.separable_conv(
inputs_2d,
depthwise_kernel,
pointwise_kernel,
strides,
padding=padding,
dilation_rate=dilation_rate,
)
# Depthwise followed by pointwise conv
expected_depthwise = np_depthwise_conv2d(
inputs_2d,
depthwise_kernel,
np.zeros(6),
strides=strides,
padding=padding,
data_format=backend.config.image_data_format(),
dilation_rate=dilation_rate,
)
expected = np_conv2d(
expected_depthwise,
pointwise_kernel,
np.zeros(6 * 12),
strides=1,
padding=padding,
data_format=backend.config.image_data_format(),
dilation_rate=dilation_rate,
groups=1,
)
self.assertAllClose(outputs, expected)
@parameterized.product(padding=("valid", "same"))
def test_conv_transpose_1d(self, padding):
if backend.config.image_data_format() == "channels_last":
input_shape = (2, 4, 3)
else:
input_shape = (2, 3, 4)
inputs_1d = np.arange(24, dtype=float).reshape(input_shape)
kernel = np.arange(30, dtype=float).reshape([2, 5, 3])
outputs = knn.conv_transpose(inputs_1d, kernel, 2, padding=padding)
expected = np_conv1d_transpose(
inputs_1d,
kernel,
bias_weights=np.zeros(5),
strides=2,
output_padding=None,
padding=padding,
data_format=backend.config.image_data_format(),
dilation_rate=1,
)
self.assertAllClose(outputs, expected)
@parameterized.product(strides=(2, (2, 2)), padding=("valid", "same"))
def test_conv_transpose_2d(self, strides, padding):
if backend.config.image_data_format() == "channels_last":
input_shape = (2, 4, 4, 3)
else:
input_shape = (2, 3, 4, 4)
inputs_2d = np.arange(96, dtype=float).reshape(input_shape)
kernel = np.arange(60, dtype=float).reshape([2, 2, 5, 3])
outputs = knn.conv_transpose(
inputs_2d, kernel, strides, padding=padding
)
expected = np_conv2d_transpose(
inputs_2d,
kernel,
bias_weights=np.zeros(5),
strides=strides,
output_padding=None,
padding=padding,
data_format=backend.config.image_data_format(),
dilation_rate=1,
)
self.assertAllClose(outputs, expected)
def test_one_hot(self):
# Test 1D one-hot.
indices_1d = np.array([0, 1, 2, 3])
self.assertAllClose(knn.one_hot(indices_1d, 4), np.eye(4)[indices_1d])
self.assertAllClose(
knn.one_hot(indices_1d, 4, axis=0),
np.eye(4)[indices_1d],
)
# Test 1D list one-hot.
indices_1d = [0, 1, 2, 3]
self.assertAllClose(knn.one_hot(indices_1d, 4), np.eye(4)[indices_1d])
self.assertAllClose(
knn.one_hot(indices_1d, 4, axis=0),
np.eye(4)[indices_1d],
)
# Test 2D one-hot.
indices_2d = np.array([[0, 1], [2, 3]])
self.assertAllClose(knn.one_hot(indices_2d, 4), np.eye(4)[indices_2d])
self.assertAllClose(
knn.one_hot(indices_2d, 4, axis=2),
np.eye(4)[indices_2d],
)
self.assertAllClose(
knn.one_hot(indices_2d, 4, axis=1),
np.transpose(np.eye(4)[indices_2d], (0, 2, 1)),
)
# Test 1D one-hot with negative inputs
indices_1d = np.array([0, -1, -1, 3])
self.assertAllClose(
knn.one_hot(indices_1d, 4),
np.array(
[
[1, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[
0,
0,
0,
1,
],
],
dtype=np.float32,
),
)
def test_binary_crossentropy(self):
# Test with from_logits=False
target = np.array([[0.1], [0.9], [0.2], [1.0]])
output = np.array([[0.1], [0.2], [0.3], [0.4]])
result = knn.binary_crossentropy(target, output, from_logits=False)
self.assertAllClose(
result,
np.array([[0.32508277], [1.47080801], [0.52613434], [0.91629048]]),
)
# Test with from_logits=True
target = np.array([[0.1], [0.9], [0.2], [1.0]])
output = np.array([[0.1], [0.2], [0.3], [0.4]])
result = knn.binary_crossentropy(target, output, from_logits=True)
self.assertAllClose(
result,
np.array([[0.73439666], [0.61813887], [0.79435524], [0.51301525]]),
)
# Test with output clipping
target = np.array([[0.1], [0.9], [0.2], [1.0]])
output = np.array([[0.99], [-0.2], [0.9], [-0.4]])
result = knn.binary_crossentropy(target, output, from_logits=True)
self.assertAllClose(
result,
np.array([[1.206961], [0.778139], [1.061154], [0.913015]]),
)
def test_categorical_crossentropy(self):
target = np.array(
[
[0.33008796, 0.0391289, 0.9503603],
[0.80376694, 0.92363342, 0.19147756],
]
)
output = np.array(
[
[0.23446431, 0.35822914, 0.06683268],
[0.3413979, 0.05420256, 0.81619654],
]
)
# Test from_logits=False
result = knn.categorical_crossentropy(
target, output, from_logits=False, axis=-1
)
self.assertAllClose(result, np.array([2.54095299, 3.96374412]))
# Test axis
result = knn.categorical_crossentropy(
target, output, from_logits=False, axis=0
)
self.assertAllClose(
result, np.array([0.71683073, 1.87988172, 2.46810762])
)
# Test from_logits=True
result = knn.categorical_crossentropy(
target, output, from_logits=True, axis=-1
)
self.assertAllClose(result, np.array([1.59419954, 2.49880593]))
# Test with output clipping
output = np.array(
[
[1.23446431, -0.35822914, 1.06683268],
[0.3413979, -0.05420256, 0.81619654],
]
)
result = knn.categorical_crossentropy(
target, output, from_logits=True, axis=-1
)
self.assertAllClose(result, np.array([1.16825923, 2.55436813]))
def test_sparse_categorical_crossentropy(self):
target = np.array([0, 1, 2])
output = np.array(
[[0.9, 0.05, 0.05], [0.05, 0.89, 0.06], [0.05, 0.01, 0.94]]
)
result = knn.sparse_categorical_crossentropy(target, output)
self.assertAllClose(result, [0.105361, 0.116534, 0.061875])
output = np.array([[8.0, 1.0, 1.0], [0.0, 9.0, 1.0], [2.0, 3.0, 5.0]])
result = knn.sparse_categorical_crossentropy(
target, output, from_logits=True
)
self.assertAllClose(result, [0.001822, 0.000459, 0.169846])
def test_multi_hot(self):
# Test 1D multi-hot.
indices_1d = np.array([0, 1, 2, 3])
expected_output_1d = np.array([1, 1, 1, 1])
self.assertAllClose(knn.multi_hot(indices_1d, 4), expected_output_1d)
# Test 2D multi-hot.
indices_2d = np.array([[0, 1], [2, 3]])
expected_output_2d = np.array([[1, 1, 0, 0], [0, 0, 1, 1]])
self.assertAllClose(knn.multi_hot(indices_2d, 4), expected_output_2d)
# Test 1D multi-hot with negative inputs
indices_1d = np.array([0, -1, -1, 3])
expected_output_1d = np.array([1, 0, 0, 1])
self.assertAllClose(knn.multi_hot(indices_1d, 4), expected_output_1d)
def test_moments(self):
# Test 1D moments
x = np.array([0, 1, 2, 3, 4, 100, -200]).astype(np.float32)
mean, variance = knn.moments(x, axes=[0])
self.assertAllClose(mean, np.mean(x), atol=1e-5, rtol=1e-5)
self.assertAllClose(variance, np.var(x), atol=1e-5, rtol=1e-5)
# Test batch statistics for 4D moments (batch, height, width, channels)
x = np.random.uniform(size=(2, 28, 28, 3)).astype(np.float32)
mean, variance = knn.moments(x, axes=[0])
self.assertAllClose(mean, np.mean(x, axis=0), atol=1e-5, rtol=1e-5)
self.assertAllClose(variance, np.var(x, axis=0), atol=1e-5, rtol=1e-5)
# Test global statistics for 4D moments (batch, height, width, channels)
x = np.random.uniform(size=(2, 28, 28, 3)).astype(np.float32)
mean, variance = knn.moments(x, axes=[0, 1, 2])
expected_mean = np.mean(x, axis=(0, 1, 2))
expected_variance = np.var(x, axis=(0, 1, 2))
self.assertAllClose(mean, expected_mean, atol=1e-5, rtol=1e-5)
self.assertAllClose(variance, expected_variance, atol=1e-5, rtol=1e-5)
# Test keepdims
x = np.random.uniform(size=(2, 28, 28, 3)).astype(np.float32)
mean, variance = knn.moments(x, axes=[0, 1, 2], keepdims=True)
expected_mean = np.mean(x, axis=(0, 1, 2), keepdims=True)
expected_variance = np.var(x, axis=(0, 1, 2), keepdims=True)
self.assertAllClose(mean, expected_mean, atol=1e-5, rtol=1e-5)
self.assertAllClose(variance, expected_variance, atol=1e-5, rtol=1e-5)
# Test float16 which causes overflow
x = np.array(
[-741.0, 353.2, 1099.0, -1807.0, 502.8, -83.4, 333.5, -130.9],
dtype=np.float16,
)
mean, variance = knn.moments(x, axes=[0])
expected_mean = np.mean(x.astype(np.float32)).astype(np.float16)
# the output variance is clipped to the max value of np.float16 because
# it is overflowed
expected_variance = np.finfo(np.float16).max
self.assertAllClose(mean, expected_mean, atol=1e-5, rtol=1e-5)
self.assertAllClose(variance, expected_variance, atol=1e-5, rtol=1e-5)
@pytest.mark.skipif(
backend.backend() != "tensorflow",
reason="synchronized=True only implemented for TF backend",
)
def test_moments_sync(self):
# Test batch statistics for 4D moments (batch, height, width, channels)
x = np.random.uniform(size=(2, 28, 28, 3)).astype(np.float32)
mean, variance = knn.moments(x, axes=[0], synchronized=True)
self.assertAllClose(mean, np.mean(x, axis=0), atol=1e-5, rtol=1e-5)
self.assertAllClose(variance, np.var(x, axis=0), atol=1e-5, rtol=1e-5)
# Test global statistics for 4D moments (batch, height, width, channels)
x = np.random.uniform(size=(2, 28, 28, 3)).astype(np.float32)
mean, variance = knn.moments(x, axes=[0, 1, 2], synchronized=True)
expected_mean = np.mean(x, axis=(0, 1, 2))
expected_variance = np.var(x, axis=(0, 1, 2))
self.assertAllClose(mean, expected_mean, atol=1e-5, rtol=1e-5)
self.assertAllClose(variance, expected_variance, atol=1e-5, rtol=1e-5)
# Test keepdims
x = np.random.uniform(size=(2, 28, 28, 3)).astype(np.float32)
mean, variance = knn.moments(
x, axes=[0, 1, 2], keepdims=True, synchronized=True
)
expected_mean = np.mean(x, axis=(0, 1, 2), keepdims=True)
expected_variance = np.var(x, axis=(0, 1, 2), keepdims=True)
self.assertAllClose(mean, expected_mean, atol=1e-5, rtol=1e-5)
self.assertAllClose(variance, expected_variance, atol=1e-5, rtol=1e-5)
@parameterized.product(dtype=["float16", "float32"])
@pytest.mark.skipif(
backend.backend() != "tensorflow",
reason="synchronized=True only implemented for TF backend",
)
def test_moments_sync_with_distribution_strategy(self, dtype):
from keras.utils.module_utils import tensorflow as tf
# Config 2 CPUs for testing.
logical_cpus = tf.config.list_logical_devices("CPU")
if len(logical_cpus) == 1:
from tensorflow.python.eager import context
context._reset_context()
tf.config.set_logical_device_configuration(
tf.config.list_physical_devices("CPU")[0],
[
tf.config.LogicalDeviceConfiguration(),
tf.config.LogicalDeviceConfiguration(),
],
)
@tf.function()
def test_on_moments(inputs):
return knn.moments(
inputs, axes=-1, keepdims=True, synchronized=True
)
# Test output of moments.
inputs = tf.constant([5.0, 9.0, 1.0, 3.0], dtype=dtype)
strategy = tf.distribute.MirroredStrategy(["CPU:0", "CPU:1"])
with strategy.scope():
mean, variance = strategy.run(test_on_moments, args=(inputs,))
self.assertEqual(mean.values[0], 4.5)
self.assertEqual(variance.values[0], 8.75)
self.assertEqual(variance.values[0], 8.75)
def test_batch_normalization(self):
x = np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]])
mean = np.array([0.2, 0.3, 0.4])
variance = np.array([4.0, 16.0, 64.0])
output = knn.batch_normalization(
x,
mean,
variance,
axis=-1,
offset=np.array([5.0, 10.0, 15.0]),
scale=np.array([10.0, 20.0, 30.0]),
epsilon=1e-7,
)
expected_output = np.array([[4.5, 9.5, 14.625], [6.0, 11.0, 15.75]])
self.assertAllClose(output, expected_output)
output = knn.batch_normalization(
x,
mean,
variance,
axis=1,
epsilon=1e-7,
)
expected_output = np.array(
[[-0.05, -0.025, -0.0125], [0.1, 0.05, 0.025]]
)
self.assertAllClose(output, expected_output)
output = knn.batch_normalization(
np.random.uniform(size=[2, 3, 3, 5]),
np.random.uniform(size=[5]),
np.random.uniform(size=[5]),
axis=3,
offset=np.random.uniform(size=[5]),
scale=np.random.uniform(size=[5]),
)
self.assertEqual(tuple(output.shape), (2, 3, 3, 5))
@pytest.mark.skipif(
backend.backend() == "numpy",
reason="Numpy does not support CTC loss",
)
def test_ctc_loss(self):
labels = np.array([[1, 2, 1], [1, 2, 2]])
outputs = np.array(
[
[[0.4, 0.8, 0.4], [0.2, 0.8, 0.3], [0.9, 0.4, 0.5]],
[[0.4, 0.8, 0.4], [0.2, 0.3, 0.3], [0.4, 0.3, 0.2]],
]
)
label_length = np.array([3, 2])
output_length = np.array([3, 2])
result = knn.ctc_loss(labels, outputs, label_length, output_length)
self.assertAllClose(result, np.array([3.4411672, 1.91680186]))
def test_normalize(self):
x = np.array([[1, 2, 3], [1, 2, 3]], dtype=np.float32)
self.assertAllClose(
knn.normalize(x, axis=None),
[
[0.18898225, 0.3779645, 0.56694674],
[0.18898225, 0.3779645, 0.56694674],
],
)
self.assertAllClose(
knn.normalize(x, axis=0),
[
[0.70710677, 0.70710677, 0.70710677],
[0.70710677, 0.70710677, 0.70710677],
],
)
self.assertAllClose(
knn.normalize(x, axis=-1),
[
[0.26726124, 0.53452247, 0.8017837],
[0.26726124, 0.53452247, 0.8017837],
],
)
self.assertAllClose(
knn.normalize(x, order=3),
[
[0.30285344, 0.6057069, 0.9085603],
[0.30285344, 0.6057069, 0.9085603],
],
)
class TestLogitRecovery(testing.TestCase):
def test_logit_recovery_binary_crossentropy(self):
layer = layers.Dense(
4, activation="sigmoid", use_bias=False, kernel_initializer="ones"
)
loss = losses.BinaryCrossentropy()
x = np.array([[1.4, 1.6, 0.8]])
y = np.array([[0.2, 0.6, 0.1, 0.3]])
loss_value = loss(y, layer(x))
self.assertAllClose(loss_value, 2.682124)
model = models.Sequential([layer])
model.compile(loss="binary_crossentropy", optimizer="sgd")
out = model.evaluate(x, y)
self.assertAllClose(out, 2.682124)
class NNOpsDtypeTest(testing.TestCase, parameterized.TestCase):
"""Test the dtype to verify that the behavior matches JAX."""
FLOAT_DTYPES = [x for x in ALLOWED_DTYPES if "float" in x]
def setUp(self):
from jax.experimental import enable_x64
self.jax_enable_x64 = enable_x64()
self.jax_enable_x64.__enter__()
return super().setUp()
def tearDown(self) -> None:
self.jax_enable_x64.__exit__(None, None, None)
return super().tearDown()
@parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES))
def test_elu(self, dtype):
import jax.nn as jnn
import jax.numpy as jnp
x = knp.ones((), dtype=dtype)
x_jax = jnp.ones((), dtype=dtype)
expected_dtype = standardize_dtype(jnn.elu(x_jax).dtype)
self.assertEqual(
standardize_dtype(knn.elu(x).dtype),
expected_dtype,
)
self.assertEqual(
standardize_dtype(knn.Elu().symbolic_call(x).dtype),
expected_dtype,
)
@parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES))
def test_gelu(self, dtype):
import jax.nn as jnn
import jax.numpy as jnp
x = knp.ones((), dtype=dtype)
x_jax = jnp.ones((), dtype=dtype)
# approximate = True
expected_dtype = standardize_dtype(jnn.gelu(x_jax).dtype)
self.assertEqual(
standardize_dtype(knn.gelu(x).dtype),
expected_dtype,
)
self.assertEqual(
standardize_dtype(knn.Gelu().symbolic_call(x).dtype),
expected_dtype,
)
# approximate = False
expected_dtype = standardize_dtype(jnn.gelu(x_jax, False).dtype)
self.assertEqual(
standardize_dtype(knn.gelu(x, False).dtype),
expected_dtype,
)
self.assertEqual(
standardize_dtype(knn.Gelu(False).symbolic_call(x).dtype),
expected_dtype,
)
@parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES))
def test_hard_sigmoid(self, dtype):
import jax.nn as jnn
import jax.numpy as jnp
x = knp.ones((), dtype=dtype)
x_jax = jnp.ones((), dtype=dtype)
expected_dtype = standardize_dtype(jnn.hard_sigmoid(x_jax).dtype)
self.assertEqual(
standardize_dtype(knn.hard_sigmoid(x).dtype),
expected_dtype,
)
self.assertEqual(
standardize_dtype(knn.HardSigmoid().symbolic_call(x).dtype),
expected_dtype,
)
@parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES))
def test_hard_silu(self, dtype):
import jax.nn as jnn
import jax.numpy as jnp
x = knp.ones((), dtype=dtype)
x_jax = jnp.ones((), dtype=dtype)
expected_dtype = standardize_dtype(jnn.hard_silu(x_jax).dtype)
self.assertEqual(
standardize_dtype(knn.hard_silu(x).dtype),
expected_dtype,
)
self.assertEqual(
standardize_dtype(knn.HardSilu().symbolic_call(x).dtype),
expected_dtype,
)
@parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES))
def test_leaky_relu(self, dtype):
import jax.nn as jnn
import jax.numpy as jnp
x = knp.ones((), dtype=dtype)
x_jax = jnp.ones((), dtype=dtype)
expected_dtype = standardize_dtype(jnn.leaky_relu(x_jax).dtype)
self.assertEqual(
standardize_dtype(knn.leaky_relu(x).dtype),
expected_dtype,
)
self.assertEqual(
standardize_dtype(knn.LeakyRelu().symbolic_call(x).dtype),
expected_dtype,
)
@parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES))
def test_log_sigmoid(self, dtype):
import jax.nn as jnn
import jax.numpy as jnp
x = knp.ones((), dtype=dtype)
x_jax = jnp.ones((), dtype=dtype)
expected_dtype = standardize_dtype(jnn.log_sigmoid(x_jax).dtype)
self.assertEqual(
standardize_dtype(knn.log_sigmoid(x).dtype),
expected_dtype,
)
self.assertEqual(
standardize_dtype(knn.LogSigmoid().symbolic_call(x).dtype),
expected_dtype,
)
@parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES))
def test_log_softmax(self, dtype):
import jax.nn as jnn
import jax.numpy as jnp
x = knp.ones((10,), dtype=dtype)
x_jax = jnp.ones((10,), dtype=dtype)
expected_dtype = standardize_dtype(jnn.log_softmax(x_jax).dtype)
self.assertEqual(
standardize_dtype(knn.log_softmax(x).dtype),
expected_dtype,
)
self.assertEqual(
standardize_dtype(knn.LogSoftmax().symbolic_call(x).dtype),
expected_dtype,
)
@parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES))
def test_relu(self, dtype):
import jax.nn as jnn
import jax.numpy as jnp
x = knp.ones((), dtype=dtype)
x_jax = jnp.ones((), dtype=dtype)
expected_dtype = standardize_dtype(jnn.relu(x_jax).dtype)
self.assertEqual(
standardize_dtype(knn.relu(x).dtype),
expected_dtype,
)
self.assertEqual(
standardize_dtype(knn.Relu().symbolic_call(x).dtype),
expected_dtype,
)
@parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES))
def test_relu6(self, dtype):
import jax.nn as jnn
import jax.numpy as jnp
x = knp.ones((), dtype=dtype)
x_jax = jnp.ones((), dtype=dtype)
expected_dtype = standardize_dtype(jnn.relu6(x_jax).dtype)
self.assertEqual(
standardize_dtype(knn.relu6(x).dtype),
expected_dtype,
)
self.assertEqual(
standardize_dtype(knn.Relu6().symbolic_call(x).dtype),
expected_dtype,
)
@parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES))
def test_selu(self, dtype):
import jax.nn as jnn
import jax.numpy as jnp
x = knp.ones((), dtype=dtype)
x_jax = jnp.ones((), dtype=dtype)
expected_dtype = standardize_dtype(jnn.selu(x_jax).dtype)
self.assertEqual(
standardize_dtype(knn.selu(x).dtype),
expected_dtype,
)
self.assertEqual(
standardize_dtype(knn.Selu().symbolic_call(x).dtype),
expected_dtype,
)
@parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES))
def test_sigmoid(self, dtype):
import jax.nn as jnn
import jax.numpy as jnp
x = knp.ones((), dtype=dtype)
x_jax = jnp.ones((), dtype=dtype)
expected_dtype = standardize_dtype(jnn.sigmoid(x_jax).dtype)
self.assertEqual(
standardize_dtype(knn.sigmoid(x).dtype),
expected_dtype,
)
self.assertEqual(
standardize_dtype(knn.Sigmoid().symbolic_call(x).dtype),
expected_dtype,
)
@parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES))
def test_silu(self, dtype):
import jax.nn as jnn
import jax.numpy as jnp
x = knp.ones((), dtype=dtype)
x_jax = jnp.ones((), dtype=dtype)
expected_dtype = standardize_dtype(jnn.silu(x_jax).dtype)
self.assertEqual(
standardize_dtype(knn.silu(x).dtype),
expected_dtype,
)
self.assertEqual(
standardize_dtype(knn.Silu().symbolic_call(x).dtype),
expected_dtype,
)
@parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES))
def test_softplus(self, dtype):
import jax.nn as jnn
import jax.numpy as jnp
x = knp.ones((), dtype=dtype)
x_jax = jnp.ones((), dtype=dtype)
expected_dtype = standardize_dtype(jnn.softplus(x_jax).dtype)
self.assertEqual(
standardize_dtype(knn.softplus(x).dtype),
expected_dtype,
)
self.assertEqual(
standardize_dtype(knn.Softplus().symbolic_call(x).dtype),
expected_dtype,
)
@parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES))
def test_softmax(self, dtype):
import jax.nn as jnn
import jax.numpy as jnp
x = knp.ones((10,), dtype=dtype)
x_jax = jnp.ones((10,), dtype=dtype)
expected_dtype = standardize_dtype(jnn.softmax(x_jax).dtype)
self.assertEqual(
standardize_dtype(knn.softmax(x).dtype),
expected_dtype,
)
self.assertEqual(
standardize_dtype(knn.Softmax().symbolic_call(x).dtype),
expected_dtype,
)
@parameterized.named_parameters(named_product(dtype=FLOAT_DTYPES))
def test_softsign(self, dtype):
import jax.nn as jnn
import jax.numpy as jnp
x = knp.ones((), dtype=dtype)
x_jax = jnp.ones((), dtype=dtype)
expected_dtype = standardize_dtype(jnn.soft_sign(x_jax).dtype)
self.assertEqual(
standardize_dtype(knn.softsign(x).dtype),
expected_dtype,
)
self.assertEqual(
standardize_dtype(knn.Softsign().symbolic_call(x).dtype),
expected_dtype,
)
| keras/keras/ops/nn_test.py/0 | {
"file_path": "keras/keras/ops/nn_test.py",
"repo_id": "keras",
"token_count": 42580
} | 157 |
import numpy as np
import pytest
from keras import backend
from keras import ops
from keras import testing
from keras.random import seed_generator
class SeedGeneratorTest(testing.TestCase):
def test_seed_generator_initialization(self):
gen = seed_generator.SeedGenerator()
self.assertIsNotNone(gen.state)
seed = 12345
gen = seed_generator.SeedGenerator(seed=seed)
self.assertEqual(ops.convert_to_numpy(gen.state)[0], seed)
with self.assertRaisesRegex(
ValueError, "Argument `seed` must be an integer"
):
seed_generator.SeedGenerator(seed="invalid_seed")
def test_seed_generator_next(self):
gen = seed_generator.SeedGenerator(seed=42)
seed1 = ops.convert_to_numpy(gen.next())
seed2 = ops.convert_to_numpy(gen.next())
self.assertFalse(np.array_equal(seed1, seed2))
def test_global_seed_generator(self):
gen1 = seed_generator.global_seed_generator()
gen2 = seed_generator.global_seed_generator()
self.assertEqual(gen1, gen2)
def test_make_default_seed(self):
seed1 = seed_generator.make_default_seed()
seed2 = seed_generator.make_default_seed()
self.assertNotEqual(seed1, seed2)
def test_draw_seed_from_seed_generator(self):
gen = seed_generator.SeedGenerator(seed=42)
seed1 = seed_generator.draw_seed(gen)
self.assertTrue(backend.is_tensor(seed1))
def test_draw_seed_from_integer(self):
seed2 = seed_generator.draw_seed(12345)
self.assertTrue(backend.is_tensor(seed2))
def test_draw_seed_from_none(self):
seed3 = seed_generator.draw_seed(None)
self.assertTrue(backend.is_tensor(seed3))
def test_draw_seed_invalid(self):
with self.assertRaisesRegex(
ValueError, "Argument `seed` must be either an integer"
):
seed_generator.draw_seed("invalid_seed")
def test_seed_generator_unexpected_kwargs(self):
with self.assertRaisesRegex(
ValueError, "Unrecognized keyword arguments"
):
seed_generator.SeedGenerator(invalid_arg="unexpected_value")
@pytest.mark.skipif(
backend.backend() != "jax", reason="This test requires the JAX backend"
)
def test_jax_tracing_with_global_seed_generator(self):
import jax
@jax.jit
def traced_function():
return seed_generator.global_seed_generator().next()
with self.assertRaisesRegex(
ValueError,
"When tracing a JAX function, you should only use seeded random",
):
traced_function()
def test_seed_generator_serialization(self):
random_generator = seed_generator.SeedGenerator(seed=42)
self.run_class_serialization_test(random_generator)
| keras/keras/random/seed_generator_test.py/0 | {
"file_path": "keras/keras/random/seed_generator_test.py",
"repo_id": "keras",
"token_count": 1233
} | 158 |
import numpy as np
from absl.testing import parameterized
from keras.testing import test_case
from keras.testing import test_utils
class GetTestDataTest(test_case.TestCase):
def setUp(self):
self.train_samples = 100
self.test_samples = 50
self.input_shape = (28, 28)
self.num_classes = 10
def test_labels_within_range(self):
"""Check if labels are within valid range."""
(_, y_train), (_, y_test) = test_utils.get_test_data(
self.train_samples,
self.test_samples,
self.input_shape,
self.num_classes,
)
self.assertTrue(np.all(y_train < self.num_classes))
self.assertTrue(np.all(y_train >= 0))
self.assertTrue(np.all(y_test < self.num_classes))
self.assertTrue(np.all(y_test >= 0))
def test_edge_cases_for_zero_samples(self):
"""Test when train or test samples are zero."""
(x_train, _), (x_test, _) = test_utils.get_test_data(
0, self.test_samples, self.input_shape, self.num_classes
)
self.assertEqual(len(x_train), 0)
(x_train, _), (x_test, _) = test_utils.get_test_data(
self.train_samples, 0, self.input_shape, self.num_classes
)
self.assertEqual(len(x_test), 0)
def test_get_test_data_returns_correct_number_of_samples(self):
"""Check if returned samples count is correct."""
(x_train, y_train), (x_test, y_test) = test_utils.get_test_data(
self.train_samples,
self.test_samples,
self.input_shape,
self.num_classes,
)
self.assertEqual(len(x_train), self.train_samples)
self.assertEqual(len(y_train), self.train_samples)
self.assertEqual(len(x_test), self.test_samples)
self.assertEqual(len(y_test), self.test_samples)
def test_get_test_data_returns_correct_shape_of_data(self):
"""Check if returned data shape is correct."""
(x_train, y_train), (x_test, y_test) = test_utils.get_test_data(
self.train_samples,
self.test_samples,
self.input_shape,
self.num_classes,
)
self.assertEqual(
x_train.shape, (self.train_samples,) + self.input_shape
)
self.assertEqual(y_train.shape, (self.train_samples,))
self.assertEqual(x_test.shape, (self.test_samples,) + self.input_shape)
self.assertEqual(y_test.shape, (self.test_samples,))
def test_get_test_data_returns_different_data_for_different_seeds(self):
"""Test variability with different seeds."""
(x_train_1, y_train_1), (x_test_1, y_test_1) = test_utils.get_test_data(
self.train_samples,
self.test_samples,
self.input_shape,
self.num_classes,
random_seed=1,
)
(x_train_2, y_train_2), (x_test_2, y_test_2) = test_utils.get_test_data(
self.train_samples,
self.test_samples,
self.input_shape,
self.num_classes,
random_seed=2,
)
self.assertFalse(np.array_equal(x_train_1, x_train_2))
self.assertFalse(np.array_equal(y_train_1, y_train_2))
self.assertFalse(np.array_equal(x_test_1, x_test_2))
self.assertFalse(np.array_equal(y_test_1, y_test_2))
def test_get_test_data_returns_consistent_data_for_same_seed(self):
"""Test consistency with the same seed."""
(x_train_1, y_train_1), (x_test_1, y_test_1) = test_utils.get_test_data(
self.train_samples,
self.test_samples,
self.input_shape,
self.num_classes,
random_seed=1,
)
(x_train_2, y_train_2), (x_test_2, y_test_2) = test_utils.get_test_data(
self.train_samples,
self.test_samples,
self.input_shape,
self.num_classes,
random_seed=1,
)
self.assertTrue(np.array_equal(x_train_1, x_train_2))
self.assertTrue(np.array_equal(y_train_1, y_train_2))
self.assertTrue(np.array_equal(x_test_1, x_test_2))
self.assertTrue(np.array_equal(y_test_1, y_test_2))
def test_input_shape_variations(self):
"""Check function for different input shapes."""
input_shape_3d = (28, 28, 3)
(x_train_3d, _), (_, _) = test_utils.get_test_data(
self.train_samples,
self.test_samples,
input_shape_3d,
self.num_classes,
)
self.assertEqual(
x_train_3d.shape, (self.train_samples,) + input_shape_3d
)
def test_all_classes_represented(self):
"""Ensure all classes are represented in the data."""
(_, y_train), (_, y_test) = test_utils.get_test_data(
self.train_samples,
self.test_samples,
self.input_shape,
self.num_classes,
)
self.assertEqual(len(np.unique(y_train)), self.num_classes)
self.assertEqual(len(np.unique(y_test)), self.num_classes)
def test_data_type(self):
"""Validate the type of the generated data."""
(x_train, _), (x_test, _) = test_utils.get_test_data(
self.train_samples,
self.test_samples,
self.input_shape,
self.num_classes,
)
self.assertEqual(x_train.dtype, np.float32)
self.assertEqual(x_test.dtype, np.float32)
def test_label_type(self):
"""Validate label type of the generated labels."""
(_, y_train), (_, y_test) = test_utils.get_test_data(
self.train_samples,
self.test_samples,
self.input_shape,
self.num_classes,
)
self.assertEqual(y_train.dtype, np.int64)
self.assertEqual(y_test.dtype, np.int64)
class ClassDistributionTests(test_case.TestCase):
def setUp(self):
self.train_samples = 100
self.test_samples = 50
self.input_shape = (28, 28)
self.num_classes = 10
def test_equal_class_distribution(self):
"""Verify equal class distribution in train and test sets."""
(_, y_train), (_, y_test) = test_utils.get_test_data(
self.train_samples,
self.test_samples,
self.input_shape,
self.num_classes,
)
_, counts_train = np.unique(y_train, return_counts=True)
_, counts_test = np.unique(y_test, return_counts=True)
self.assertTrue(
np.all(counts_train == self.train_samples // self.num_classes)
)
self.assertTrue(
np.all(counts_test == self.test_samples // self.num_classes)
)
def test_uneven_samples_class_distribution(self):
"""Check class distribution with uneven samples."""
train_samples = 103
test_samples = 52
(_, y_train), (_, y_test) = test_utils.get_test_data(
train_samples,
test_samples,
self.input_shape,
self.num_classes,
)
_, counts_train = np.unique(y_train, return_counts=True)
_, counts_test = np.unique(y_test, return_counts=True)
self.assertTrue(np.max(counts_train) - np.min(counts_train) <= 1)
self.assertTrue(np.max(counts_test) - np.min(counts_test) <= 1)
def test_randomness_in_class_distribution(self):
"""Ensure class distribution isn't too deterministic."""
(_, y_train_1), (_, y_test_1) = test_utils.get_test_data(
self.train_samples,
self.test_samples,
self.input_shape,
self.num_classes,
)
(_, y_train_2), (_, y_test_2) = test_utils.get_test_data(
self.train_samples,
self.test_samples,
self.input_shape,
self.num_classes,
)
self.assertFalse(np.array_equal(y_train_1, y_train_2))
self.assertFalse(np.array_equal(y_test_1, y_test_2))
def test_large_number_of_classes(self):
"""Validate function with a large number of classes."""
num_classes = 150
train_samples = (
num_classes * 10
) # 10 samples for each class in training
test_samples = num_classes * 5 # 5 samples for each class in testing
(_, y_train), (_, y_test) = test_utils.get_test_data(
train_samples,
test_samples,
self.input_shape,
num_classes,
)
self.assertEqual(len(np.unique(y_train)), num_classes)
self.assertEqual(len(np.unique(y_test)), num_classes)
def test_single_class(self):
"""Test with a single class."""
num_classes = 1
(_, y_train), (_, y_test) = test_utils.get_test_data(
self.train_samples,
self.test_samples,
self.input_shape,
num_classes,
)
self.assertTrue(np.all(y_train == 0))
self.assertTrue(np.all(y_test == 0))
class NamedProductTest(parameterized.TestCase):
def test_test_cases(self):
all_tests = test_utils.named_product(
[
{"testcase_name": "negative", "x": -1},
{"testcase_name": "positive", "x": 1},
{"testcase_name": "zero", "x": 0},
],
numeral_type=[float, int],
)
names = [test["testcase_name"] for test in all_tests]
self.assertListEqual(
names,
[
"negative_float",
"positive_float",
"zero_float",
"negative_int",
"positive_int",
"zero_int",
],
)
def test_test_cases_no_product(self):
all_tests = test_utils.named_product(numeral_type=[float, int])
names = [test["testcase_name"] for test in all_tests]
self.assertListEqual(names, ["float", "int"])
@parameterized.named_parameters(
test_utils.named_product(
[
{"testcase_name": "negative", "x": -1},
{"testcase_name": "positive", "x": 1},
{"testcase_name": "zero", "x": 0},
],
numeral_type=[float, int],
)
)
def test_via_decorator(self, x, numeral_type):
self.assertIn(x, (-1, 1, 0))
self.assertIn(numeral_type, (float, int))
@parameterized.named_parameters(
test_utils.named_product(numeral_type=[float, int])
)
def test_via_decorator_no_product(self, numeral_type):
self.assertIn(numeral_type, (float, int))
| keras/keras/testing/test_utils_test.py/0 | {
"file_path": "keras/keras/testing/test_utils_test.py",
"repo_id": "keras",
"token_count": 5339
} | 159 |
import math
import jax
import numpy as np
import tensorflow as tf
import torch
from absl.testing import parameterized
from keras import testing
from keras.testing.test_utils import named_product
from keras.trainers.data_adapters.torch_data_loader_adapter import (
TorchDataLoaderAdapter,
)
class TestTorchDataLoaderAdapter(testing.TestCase, parameterized.TestCase):
@parameterized.named_parameters(
named_product(iterator_type=["np", "tf", "jax", "torch"])
)
def test_basic_dataloader(self, iterator_type):
x = torch.normal(2, 3, size=(34, 4))
y = torch.normal(1, 3, size=(34, 2))
ds = torch.utils.data.TensorDataset(x, y)
dataloader = torch.utils.data.DataLoader(ds, batch_size=16)
adapter = TorchDataLoaderAdapter(dataloader)
self.assertEqual(adapter.num_batches, 3)
self.assertEqual(adapter.batch_size, 16)
self.assertEqual(adapter.has_partial_batch, True)
self.assertEqual(adapter.partial_batch_size, 2)
if iterator_type == "np":
it = adapter.get_numpy_iterator()
expected_class = np.ndarray
elif iterator_type == "tf":
it = adapter.get_tf_dataset()
expected_class = tf.Tensor
elif iterator_type == "jax":
it = adapter.get_jax_iterator()
expected_class = jax.Array
elif iterator_type == "torch":
it = adapter.get_torch_dataloader()
expected_class = torch.Tensor
for i, batch in enumerate(it):
self.assertEqual(len(batch), 2)
bx, by = batch
self.assertIsInstance(bx, expected_class)
self.assertIsInstance(by, expected_class)
self.assertEqual(bx.dtype, by.dtype)
self.assertContainsExactSubsequence(str(bx.dtype), "float32")
if i < 2:
self.assertEqual(bx.shape, (16, 4))
self.assertEqual(by.shape, (16, 2))
else:
self.assertEqual(bx.shape, (2, 4))
self.assertEqual(by.shape, (2, 2))
@parameterized.named_parameters(
named_product(
batch_size=[None, 3],
implements_len=[True, False],
iterator_type=["np", "tf", "jax", "torch"],
)
)
def test_dataloader_iterable_dataset(
self, batch_size, implements_len, iterator_type
):
class TestIterableDataset(torch.utils.data.IterableDataset):
def __init__(self):
self.x = torch.normal(2, 3, size=(16, 4))
self.y = torch.normal(1, 3, size=(16, 2))
def __iter__(self):
for _ in range(10):
yield (self.x, self.y)
class TestIterableDatasetWithLen(TestIterableDataset):
def __len__(self):
return 10
ds = (
TestIterableDatasetWithLen()
if implements_len
else TestIterableDataset()
)
dataloader = torch.utils.data.DataLoader(ds, batch_size=batch_size)
adapter = TorchDataLoaderAdapter(dataloader)
if implements_len and batch_size:
self.assertEqual(adapter.num_batches, math.ceil(10 / batch_size))
self.assertEqual(adapter.batch_size, batch_size)
self.assertEqual(adapter.has_partial_batch, True)
self.assertEqual(adapter.partial_batch_size, 10 % batch_size)
elif implements_len:
self.assertEqual(adapter.num_batches, 10)
self.assertEqual(adapter.batch_size, None)
self.assertEqual(adapter.has_partial_batch, None)
self.assertEqual(adapter.partial_batch_size, None)
else:
self.assertIsNone(adapter.num_batches)
self.assertEqual(adapter.batch_size, batch_size)
self.assertIsNone(adapter.has_partial_batch)
self.assertIsNone(adapter.partial_batch_size)
if iterator_type == "np":
it = adapter.get_numpy_iterator()
expected_class = np.ndarray
elif iterator_type == "tf":
it = adapter.get_tf_dataset()
expected_class = tf.Tensor
elif iterator_type == "jax":
it = adapter.get_jax_iterator()
expected_class = jax.Array
elif iterator_type == "torch":
it = adapter.get_torch_dataloader()
expected_class = torch.Tensor
batch_count = 0
for i, batch in enumerate(it):
batch_count += 1
self.assertEqual(len(batch), 2)
bx, by = batch
self.assertIsInstance(bx, expected_class)
self.assertIsInstance(by, expected_class)
self.assertEqual(bx.dtype, by.dtype)
self.assertContainsExactSubsequence(str(bx.dtype), "float32")
if batch_size:
if i < 3:
self.assertEqual(bx.shape, (batch_size, 16, 4))
self.assertEqual(by.shape, (batch_size, 16, 2))
else:
self.assertEqual(bx.shape, (10 % batch_size, 16, 4))
self.assertEqual(by.shape, (10 % batch_size, 16, 2))
else:
self.assertEqual(bx.shape, (16, 4))
self.assertEqual(by.shape, (16, 2))
if batch_size:
self.assertEqual(batch_count, math.ceil(10 / batch_size))
else:
self.assertEqual(batch_count, 10)
| keras/keras/trainers/data_adapters/torch_data_loader_adapter_test.py/0 | {
"file_path": "keras/keras/trainers/data_adapters/torch_data_loader_adapter_test.py",
"repo_id": "keras",
"token_count": 2724
} | 160 |
5.4.0 | tf-keras/.bazelversion/0 | {
"file_path": "tf-keras/.bazelversion",
"repo_id": "tf-keras",
"token_count": 5
} | 161 |
# TF-Keras: the pure-TensorFlow implementation of Keras
This repository hosts the development of the TF-Keras library. It is a pure
TensorFlow implementation of Keras, based on the legacy `tf.keras` codebase.
Note that the "main" version of Keras is now Keras 3 (formerly Keras Core),
which is a multi-backend implementation of Keras, supporting JAX,
PyTorch, and TensorFlow. Keras 3 is being developed at
[keras-team/keras](https://github.com/keras-team/keras).
---
## Support
You can ask questions and join the development discussion:
- In the [TensorFlow forum](https://discuss.tensorflow.org/).
- On the [Keras mailing list](https://groups.google.com/forum/#!forum/keras-users).
---
## Opening an issue
You can also post **bug reports and feature requests** (only)
in [GitHub issues](https://github.com/keras-team/tf-keras/issues).
---
## Opening a PR
We welcome contributions! Before opening a PR, please read
[our contributor guide](https://github.com/keras-team/tf-keras/blob/master/CONTRIBUTING.md),
and the [API design guideline](https://github.com/keras-team/governance/blob/master/keras_api_design_guidelines.md).
| tf-keras/README.md/0 | {
"file_path": "tf-keras/README.md",
"repo_id": "tf-keras",
"token_count": 358
} | 162 |
# Copyright 2015 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.
# ==============================================================================
"""Inception V3 model for TF-Keras.
Reference:
- [Rethinking the Inception Architecture for Computer Vision](
http://arxiv.org/abs/1512.00567) (CVPR 2016)
"""
import tensorflow.compat.v2 as tf
from tf_keras import backend
from tf_keras.applications import imagenet_utils
from tf_keras.engine import training
from tf_keras.layers import VersionAwareLayers
from tf_keras.utils import data_utils
from tf_keras.utils import layer_utils
# isort: off
from tensorflow.python.util.tf_export import keras_export
WEIGHTS_PATH = (
"https://storage.googleapis.com/tensorflow/keras-applications/"
"inception_v3/inception_v3_weights_tf_dim_ordering_tf_kernels.h5"
)
WEIGHTS_PATH_NO_TOP = (
"https://storage.googleapis.com/tensorflow/keras-applications/"
"inception_v3/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5"
)
layers = VersionAwareLayers()
@keras_export(
"keras.applications.inception_v3.InceptionV3",
"keras.applications.InceptionV3",
)
def InceptionV3(
include_top=True,
weights="imagenet",
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
classifier_activation="softmax",
):
"""Instantiates the Inception v3 architecture.
Reference:
- [Rethinking the Inception Architecture for Computer Vision](
http://arxiv.org/abs/1512.00567) (CVPR 2016)
This function returns a TF-Keras image classification model,
optionally loaded with weights pre-trained on ImageNet.
For image classification use cases, see
[this page for detailed examples](
https://keras.io/api/applications/#usage-examples-for-image-classification-models).
For transfer learning use cases, make sure to read the
[guide to transfer learning & fine-tuning](
https://keras.io/guides/transfer_learning/).
Note: each TF-Keras Application expects a specific kind of input
preprocessing. For `InceptionV3`, call
`tf.keras.applications.inception_v3.preprocess_input` on your inputs before
passing them to the model. `inception_v3.preprocess_input` will scale input
pixels between -1 and 1.
Args:
include_top: Boolean, whether to include the fully-connected
layer at the top, as the last layer of the network. Defaults to `True`.
weights: One of `None` (random initialization),
`imagenet` (pre-training on ImageNet),
or the path to the weights file to be loaded. Defaults to `imagenet`.
input_tensor: Optional TF-Keras tensor (i.e. output of `layers.Input()`)
to use as image input for the model. `input_tensor` is useful for
sharing inputs between multiple different networks. Defaults to `None`.
input_shape: Optional shape tuple, only to be specified
if `include_top` is False (otherwise the input shape
has to be `(299, 299, 3)` (with `channels_last` data format)
or `(3, 299, 299)` (with `channels_first` data format).
It should have exactly 3 inputs channels,
and width and height should be no smaller than 75.
E.g. `(150, 150, 3)` would be one valid value.
`input_shape` will be ignored if the `input_tensor` is provided.
pooling: Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` (default) means that the output of the model will be
the 4D tensor output of the last convolutional block.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional block, and thus
the output of the model will be a 2D tensor.
- `max` means that global max pooling will be applied.
classes: optional number of classes to classify images
into, only to be specified if `include_top` is True, and
if no `weights` argument is specified. Defaults to 1000.
classifier_activation: A `str` or callable. The activation function to use
on the "top" layer. Ignored unless `include_top=True`. Set
`classifier_activation=None` to return the logits of the "top" layer.
When loading pretrained weights, `classifier_activation` can only
be `None` or `"softmax"`.
Returns:
A `keras.Model` instance.
"""
if not (weights in {"imagenet", None} or tf.io.gfile.exists(weights)):
raise ValueError(
"The `weights` argument should be either "
"`None` (random initialization), `imagenet` "
"(pre-training on ImageNet), "
"or the path to the weights file to be loaded; "
f"Received: weights={weights}"
)
if weights == "imagenet" and include_top and classes != 1000:
raise ValueError(
'If using `weights` as `"imagenet"` with `include_top` '
"as true, `classes` should be 1000; "
f"Received classes={classes}"
)
# Determine proper input shape
input_shape = imagenet_utils.obtain_input_shape(
input_shape,
default_size=299,
min_size=75,
data_format=backend.image_data_format(),
require_flatten=include_top,
weights=weights,
)
if input_tensor is None:
img_input = layers.Input(shape=input_shape)
else:
if not backend.is_keras_tensor(input_tensor):
img_input = layers.Input(tensor=input_tensor, shape=input_shape)
else:
img_input = input_tensor
if backend.image_data_format() == "channels_first":
channel_axis = 1
else:
channel_axis = 3
x = conv2d_bn(img_input, 32, 3, 3, strides=(2, 2), padding="valid")
x = conv2d_bn(x, 32, 3, 3, padding="valid")
x = conv2d_bn(x, 64, 3, 3)
x = layers.MaxPooling2D((3, 3), strides=(2, 2))(x)
x = conv2d_bn(x, 80, 1, 1, padding="valid")
x = conv2d_bn(x, 192, 3, 3, padding="valid")
x = layers.MaxPooling2D((3, 3), strides=(2, 2))(x)
# mixed 0: 35 x 35 x 256
branch1x1 = conv2d_bn(x, 64, 1, 1)
branch5x5 = conv2d_bn(x, 48, 1, 1)
branch5x5 = conv2d_bn(branch5x5, 64, 5, 5)
branch3x3dbl = conv2d_bn(x, 64, 1, 1)
branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)
branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)
branch_pool = layers.AveragePooling2D(
(3, 3), strides=(1, 1), padding="same"
)(x)
branch_pool = conv2d_bn(branch_pool, 32, 1, 1)
x = layers.concatenate(
[branch1x1, branch5x5, branch3x3dbl, branch_pool],
axis=channel_axis,
name="mixed0",
)
# mixed 1: 35 x 35 x 288
branch1x1 = conv2d_bn(x, 64, 1, 1)
branch5x5 = conv2d_bn(x, 48, 1, 1)
branch5x5 = conv2d_bn(branch5x5, 64, 5, 5)
branch3x3dbl = conv2d_bn(x, 64, 1, 1)
branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)
branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)
branch_pool = layers.AveragePooling2D(
(3, 3), strides=(1, 1), padding="same"
)(x)
branch_pool = conv2d_bn(branch_pool, 64, 1, 1)
x = layers.concatenate(
[branch1x1, branch5x5, branch3x3dbl, branch_pool],
axis=channel_axis,
name="mixed1",
)
# mixed 2: 35 x 35 x 288
branch1x1 = conv2d_bn(x, 64, 1, 1)
branch5x5 = conv2d_bn(x, 48, 1, 1)
branch5x5 = conv2d_bn(branch5x5, 64, 5, 5)
branch3x3dbl = conv2d_bn(x, 64, 1, 1)
branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)
branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)
branch_pool = layers.AveragePooling2D(
(3, 3), strides=(1, 1), padding="same"
)(x)
branch_pool = conv2d_bn(branch_pool, 64, 1, 1)
x = layers.concatenate(
[branch1x1, branch5x5, branch3x3dbl, branch_pool],
axis=channel_axis,
name="mixed2",
)
# mixed 3: 17 x 17 x 768
branch3x3 = conv2d_bn(x, 384, 3, 3, strides=(2, 2), padding="valid")
branch3x3dbl = conv2d_bn(x, 64, 1, 1)
branch3x3dbl = conv2d_bn(branch3x3dbl, 96, 3, 3)
branch3x3dbl = conv2d_bn(
branch3x3dbl, 96, 3, 3, strides=(2, 2), padding="valid"
)
branch_pool = layers.MaxPooling2D((3, 3), strides=(2, 2))(x)
x = layers.concatenate(
[branch3x3, branch3x3dbl, branch_pool], axis=channel_axis, name="mixed3"
)
# mixed 4: 17 x 17 x 768
branch1x1 = conv2d_bn(x, 192, 1, 1)
branch7x7 = conv2d_bn(x, 128, 1, 1)
branch7x7 = conv2d_bn(branch7x7, 128, 1, 7)
branch7x7 = conv2d_bn(branch7x7, 192, 7, 1)
branch7x7dbl = conv2d_bn(x, 128, 1, 1)
branch7x7dbl = conv2d_bn(branch7x7dbl, 128, 7, 1)
branch7x7dbl = conv2d_bn(branch7x7dbl, 128, 1, 7)
branch7x7dbl = conv2d_bn(branch7x7dbl, 128, 7, 1)
branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 1, 7)
branch_pool = layers.AveragePooling2D(
(3, 3), strides=(1, 1), padding="same"
)(x)
branch_pool = conv2d_bn(branch_pool, 192, 1, 1)
x = layers.concatenate(
[branch1x1, branch7x7, branch7x7dbl, branch_pool],
axis=channel_axis,
name="mixed4",
)
# mixed 5, 6: 17 x 17 x 768
for i in range(2):
branch1x1 = conv2d_bn(x, 192, 1, 1)
branch7x7 = conv2d_bn(x, 160, 1, 1)
branch7x7 = conv2d_bn(branch7x7, 160, 1, 7)
branch7x7 = conv2d_bn(branch7x7, 192, 7, 1)
branch7x7dbl = conv2d_bn(x, 160, 1, 1)
branch7x7dbl = conv2d_bn(branch7x7dbl, 160, 7, 1)
branch7x7dbl = conv2d_bn(branch7x7dbl, 160, 1, 7)
branch7x7dbl = conv2d_bn(branch7x7dbl, 160, 7, 1)
branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 1, 7)
branch_pool = layers.AveragePooling2D(
(3, 3), strides=(1, 1), padding="same"
)(x)
branch_pool = conv2d_bn(branch_pool, 192, 1, 1)
x = layers.concatenate(
[branch1x1, branch7x7, branch7x7dbl, branch_pool],
axis=channel_axis,
name="mixed" + str(5 + i),
)
# mixed 7: 17 x 17 x 768
branch1x1 = conv2d_bn(x, 192, 1, 1)
branch7x7 = conv2d_bn(x, 192, 1, 1)
branch7x7 = conv2d_bn(branch7x7, 192, 1, 7)
branch7x7 = conv2d_bn(branch7x7, 192, 7, 1)
branch7x7dbl = conv2d_bn(x, 192, 1, 1)
branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 7, 1)
branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 1, 7)
branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 7, 1)
branch7x7dbl = conv2d_bn(branch7x7dbl, 192, 1, 7)
branch_pool = layers.AveragePooling2D(
(3, 3), strides=(1, 1), padding="same"
)(x)
branch_pool = conv2d_bn(branch_pool, 192, 1, 1)
x = layers.concatenate(
[branch1x1, branch7x7, branch7x7dbl, branch_pool],
axis=channel_axis,
name="mixed7",
)
# mixed 8: 8 x 8 x 1280
branch3x3 = conv2d_bn(x, 192, 1, 1)
branch3x3 = conv2d_bn(branch3x3, 320, 3, 3, strides=(2, 2), padding="valid")
branch7x7x3 = conv2d_bn(x, 192, 1, 1)
branch7x7x3 = conv2d_bn(branch7x7x3, 192, 1, 7)
branch7x7x3 = conv2d_bn(branch7x7x3, 192, 7, 1)
branch7x7x3 = conv2d_bn(
branch7x7x3, 192, 3, 3, strides=(2, 2), padding="valid"
)
branch_pool = layers.MaxPooling2D((3, 3), strides=(2, 2))(x)
x = layers.concatenate(
[branch3x3, branch7x7x3, branch_pool], axis=channel_axis, name="mixed8"
)
# mixed 9: 8 x 8 x 2048
for i in range(2):
branch1x1 = conv2d_bn(x, 320, 1, 1)
branch3x3 = conv2d_bn(x, 384, 1, 1)
branch3x3_1 = conv2d_bn(branch3x3, 384, 1, 3)
branch3x3_2 = conv2d_bn(branch3x3, 384, 3, 1)
branch3x3 = layers.concatenate(
[branch3x3_1, branch3x3_2],
axis=channel_axis,
name="mixed9_" + str(i),
)
branch3x3dbl = conv2d_bn(x, 448, 1, 1)
branch3x3dbl = conv2d_bn(branch3x3dbl, 384, 3, 3)
branch3x3dbl_1 = conv2d_bn(branch3x3dbl, 384, 1, 3)
branch3x3dbl_2 = conv2d_bn(branch3x3dbl, 384, 3, 1)
branch3x3dbl = layers.concatenate(
[branch3x3dbl_1, branch3x3dbl_2], axis=channel_axis
)
branch_pool = layers.AveragePooling2D(
(3, 3), strides=(1, 1), padding="same"
)(x)
branch_pool = conv2d_bn(branch_pool, 192, 1, 1)
x = layers.concatenate(
[branch1x1, branch3x3, branch3x3dbl, branch_pool],
axis=channel_axis,
name="mixed" + str(9 + i),
)
if include_top:
# Classification block
x = layers.GlobalAveragePooling2D(name="avg_pool")(x)
imagenet_utils.validate_activation(classifier_activation, weights)
x = layers.Dense(
classes, activation=classifier_activation, name="predictions"
)(x)
else:
if pooling == "avg":
x = layers.GlobalAveragePooling2D()(x)
elif pooling == "max":
x = layers.GlobalMaxPooling2D()(x)
# Ensure that the model takes into account
# any potential predecessors of `input_tensor`.
if input_tensor is not None:
inputs = layer_utils.get_source_inputs(input_tensor)
else:
inputs = img_input
# Create model.
model = training.Model(inputs, x, name="inception_v3")
# Load weights.
if weights == "imagenet":
if include_top:
weights_path = data_utils.get_file(
"inception_v3_weights_tf_dim_ordering_tf_kernels.h5",
WEIGHTS_PATH,
cache_subdir="models",
file_hash="9a0d58056eeedaa3f26cb7ebd46da564",
)
else:
weights_path = data_utils.get_file(
"inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5",
WEIGHTS_PATH_NO_TOP,
cache_subdir="models",
file_hash="bcbd6486424b2319ff4ef7d526e38f63",
)
model.load_weights(weights_path)
elif weights is not None:
model.load_weights(weights)
return model
def conv2d_bn(
x, filters, num_row, num_col, padding="same", strides=(1, 1), name=None
):
"""Utility function to apply conv + BN.
Args:
x: input tensor.
filters: filters in `Conv2D`.
num_row: height of the convolution kernel.
num_col: width of the convolution kernel.
padding: padding mode in `Conv2D`.
strides: strides in `Conv2D`.
name: name of the ops; will become `name + '_conv'`
for the convolution and `name + '_bn'` for the
batch norm layer.
Returns:
Output tensor after applying `Conv2D` and `BatchNormalization`.
"""
if name is not None:
bn_name = name + "_bn"
conv_name = name + "_conv"
else:
bn_name = None
conv_name = None
if backend.image_data_format() == "channels_first":
bn_axis = 1
else:
bn_axis = 3
x = layers.Conv2D(
filters,
(num_row, num_col),
strides=strides,
padding=padding,
use_bias=False,
name=conv_name,
)(x)
x = layers.BatchNormalization(axis=bn_axis, scale=False, name=bn_name)(x)
x = layers.Activation("relu", name=name)(x)
return x
@keras_export("keras.applications.inception_v3.preprocess_input")
def preprocess_input(x, data_format=None):
return imagenet_utils.preprocess_input(
x, data_format=data_format, mode="tf"
)
@keras_export("keras.applications.inception_v3.decode_predictions")
def decode_predictions(preds, top=5):
return imagenet_utils.decode_predictions(preds, top=top)
preprocess_input.__doc__ = imagenet_utils.PREPROCESS_INPUT_DOC.format(
mode="",
ret=imagenet_utils.PREPROCESS_INPUT_RET_DOC_TF,
error=imagenet_utils.PREPROCESS_INPUT_ERROR_DOC,
)
decode_predictions.__doc__ = imagenet_utils.decode_predictions.__doc__
| tf-keras/tf_keras/applications/inception_v3.py/0 | {
"file_path": "tf-keras/tf_keras/applications/inception_v3.py",
"repo_id": "tf-keras",
"token_count": 7506
} | 163 |
# Description:
# Implementation of TF-Keras benchmarks.
# Placeholder: load unaliased py_binary
# Placeholder: load unaliased py_library
# Placeholder: load unaliased py_test
load("@org_keras//tf_keras:tf_keras.bzl", "cuda_py_test")
package(
# copybara:uncomment default_applicable_licenses = ["//tf_keras:license"],
default_visibility = ["//visibility:public"],
licenses = ["notice"],
)
# To run CPU benchmarks:
# bazel run -c opt benchmarks_test -- --benchmarks=.
# To run GPU benchmarks:
# bazel run --config=cuda -c opt --copt="-mavx" benchmarks_test -- \
# --benchmarks=.
# To run a subset of benchmarks using --benchmarks flag.
# --benchmarks: the list of benchmarks to run. The specified value is interpreted
# as a regular expression and any benchmark whose name contains a partial match
# to the regular expression is executed.
# e.g. --benchmarks=".*lstm*." will run all lstm layer related benchmarks.
# Add all benchmarks related utils here for pip testing dependencies.
py_library(
name = "keras_benchmark_lib_pip",
srcs_version = "PY3",
deps = [
":benchmark_util",
":distribution_util",
"//tf_keras/benchmarks/saved_model_benchmarks:saved_model_benchmark_util",
],
)
# This lib is mainly for running benchmarks on mlcompass infra.
py_library(
name = "profiler_lib",
srcs_version = "PY3",
visibility = [
"//learning/brain/contrib/keras_benchmark:__subpackages__",
"//tf_keras:friends",
],
)
COMMON_TAGS = [
"no_pip", # b/161253163
"no_windows", # b/160628318
]
py_test(
name = "keras_cpu_benchmark_test",
size = "large",
srcs = ["keras_cpu_benchmark_test.py"],
python_version = "PY3",
tags = COMMON_TAGS,
deps = [
":benchmark_util",
":profiler_lib",
"//:expect_numpy_installed",
"//:expect_tensorflow_installed",
"//tf_keras/api:tf_keras_api",
],
)
cuda_py_test(
name = "eager_microbenchmarks_test",
size = "medium",
srcs = ["eager_microbenchmarks_test.py"],
python_version = "PY3",
tags = COMMON_TAGS + [
"no_oss_py38", # TODO(b/162044699)
],
deps = [
":profiler_lib",
"//:expect_tensorflow_installed",
"//tf_keras/api:tf_keras_api",
"//tf_keras/utils:tf_inspect",
],
)
cuda_py_test(
name = "model_components_benchmarks_test",
srcs = ["model_components_benchmarks_test.py"],
python_version = "PY3",
deps = [
":profiler_lib",
"//:expect_tensorflow_installed",
"//tf_keras/api:tf_keras_api",
],
)
py_library(
name = "benchmark_util",
srcs = ["benchmark_util.py"],
srcs_version = "PY3",
deps = [
":distribution_util",
"//:expect_numpy_installed",
"//:expect_tensorflow_installed",
"//tf_keras/api:tf_keras_api",
],
)
py_test(
name = "benchmark_util_test",
srcs = ["benchmark_util_test.py"],
python_version = "PY3",
tags = COMMON_TAGS,
deps = [
":benchmark_util",
"//:expect_tensorflow_installed",
"//tf_keras/api:tf_keras_api",
],
)
py_library(
name = "distribution_util",
srcs = ["distribution_util.py"],
srcs_version = "PY3",
deps = [
"//:expect_tensorflow_installed",
],
)
py_test(
name = "optimizer_benchmarks_test",
srcs = ["optimizer_benchmarks_test.py"],
python_version = "PY3",
tags = COMMON_TAGS + [
"no_oss_py38", # TODO(b/162044699)
],
deps = [
":benchmark_util",
":profiler_lib",
"//:expect_tensorflow_installed",
"//tf_keras/api:tf_keras_api",
"//tf_keras/optimizers/legacy:optimizers",
],
)
# Run memory profiler on TF-Keras model.
# Please make sure `memory_profiler` is installed.
# To run the memory profiler:
# With CPU:
# bazel run -c opt model_memory_profile -- --model=YOUR_MODEL_NAME
# With GPU:
# bazel run -c opt --config=cuda model_memory_profile -- --model=YOUR_MODEL_NAME
py_binary(
name = "model_memory_profile",
srcs = ["model_memory_profile.py"],
python_version = "PY3",
tags = ["no_oss"],
deps = ["//:expect_tensorflow_installed"],
)
py_test(
name = "metrics_memory_benchmark_test",
srcs = ["metrics_memory_benchmark_test.py"],
python_version = "PY3",
tags = COMMON_TAGS,
deps = [
"//:expect_numpy_installed",
"//:expect_tensorflow_installed",
"//tf_keras/api:tf_keras_api",
],
)
| tf-keras/tf_keras/benchmarks/BUILD/0 | {
"file_path": "tf-keras/tf_keras/benchmarks/BUILD",
"repo_id": "tf-keras",
"token_count": 2013
} | 164 |
# Copyright 2020 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.
# ==============================================================================
"""Benchmarks on IRNN on MNIST digits."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v2 as tf
import tf_keras as keras
from tf_keras.benchmarks import benchmark_util
class IRNNMnistBenchmark(tf.test.Benchmark):
"""Benchmarks for IRNN using `tf.test.Benchmark`."""
def __init__(self):
super().__init__()
self.num_classes = 10
self.hidden_units = 100
self.learning_rate = 1e-6
(self.x_train, self.y_train), _ = keras.datasets.mnist.load_data()
self.x_train = self.x_train.reshape(self.x_train.shape[0], -1, 1)
self.x_train = self.x_train.astype("float32") / 255
self.y_train = keras.utils.to_categorical(
self.y_train, self.num_classes
)
def _build_model(self):
"""Model from https://github.com/keras-team/tf-keras/
blob/master/examples/mnist_irnn.py.
"""
model = keras.Sequential()
model.add(
keras.layers.SimpleRNN(
self.hidden_units,
kernel_initializer=keras.initializers.RandomNormal(
stddev=0.001
),
recurrent_initializer=keras.initializers.Identity(gain=1.0),
activation="relu",
input_shape=self.x_train.shape[1:],
)
)
model.add(keras.layers.Dense(self.num_classes))
model.add(keras.layers.Activation("softmax"))
return model
# In each benchmark test, the required arguments for the
# method `measure_performance` include:
# x: Input data, it could be Numpy or loaded from tfds.
# y: Target data. If `x` is a dataset or generator instance,
# `y` should not be specified.
# loss: Loss function for model.
# optimizer: Optimizer for model.
# Check more details in `measure_performance()` method of
# benchmark_util.
def benchmark_irnn_mnist_bs_256(self):
"""Measure performance with batch_size=256."""
batch_size = 256
metrics, wall_time, extras = benchmark_util.measure_performance(
self._build_model,
x=self.x_train,
y=self.y_train,
batch_size=batch_size,
optimizer=keras.optimizers.RMSprop(
learning_rate=self.learning_rate
),
loss="categorical_crossentropy",
metrics=["accuracy"],
)
metadata = benchmark_util.get_keras_examples_metadata(
"irnn", batch_size
)
extras.update(metadata)
self.report_benchmark(
wall_time=wall_time, metrics=metrics, extras=extras
)
def benchmark_irnn_mnist_bs_512(self):
"""Measure performance with batch_size=512."""
batch_size = 512
metrics, wall_time, extras = benchmark_util.measure_performance(
self._build_model,
x=self.x_train,
y=self.y_train,
batch_size=batch_size,
optimizer=keras.optimizers.RMSprop(
learning_rate=self.learning_rate
),
loss="categorical_crossentropy",
metrics=["accuracy"],
)
metadata = benchmark_util.get_keras_examples_metadata(
"irnn", batch_size
)
extras.update(metadata)
self.report_benchmark(
wall_time=wall_time, metrics=metrics, extras=extras
)
def benchmark_irnn_mnist_bs_1024(self):
"""Measure performance with batch_size=1024."""
batch_size = 1024
metrics, wall_time, extras = benchmark_util.measure_performance(
self._build_model,
x=self.x_train,
y=self.y_train,
batch_size=batch_size,
optimizer=keras.optimizers.RMSprop(
learning_rate=self.learning_rate
),
loss="categorical_crossentropy",
metrics=["accuracy"],
)
metadata = benchmark_util.get_keras_examples_metadata(
"irnn", batch_size
)
extras.update(metadata)
self.report_benchmark(
wall_time=wall_time, metrics=metrics, extras=extras
)
def benchmark_irnn_mnist_bs_1024_gpu_2(self):
"""Measure performance with batch_size=1024, gpu=2 and
distribution_strategy='mirrored'
"""
batch_size = 1024
metrics, wall_time, extras = benchmark_util.measure_performance(
self._build_model,
x=self.x_train,
y=self.y_train,
batch_size=batch_size,
num_gpus=2,
distribution_strategy="mirrored",
optimizer=keras.optimizers.RMSprop(
learning_rate=self.learning_rate
),
loss="categorical_crossentropy",
metrics=["accuracy"],
)
metadata = benchmark_util.get_keras_examples_metadata(
"irnn", batch_size
)
extras.update(metadata)
self.report_benchmark(
wall_time=wall_time, metrics=metrics, extras=extras
)
if __name__ == "__main__":
tf.test.main()
| tf-keras/tf_keras/benchmarks/keras_examples_benchmarks/mnist_irnn_benchmark_test.py/0 | {
"file_path": "tf-keras/tf_keras/benchmarks/keras_examples_benchmarks/mnist_irnn_benchmark_test.py",
"repo_id": "tf-keras",
"token_count": 2683
} | 165 |
# Copyright 2015 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.
# ==============================================================================
"""CIFAR100 small images classification dataset."""
import os
import numpy as np
from tf_keras import backend
from tf_keras.datasets.cifar import load_batch
from tf_keras.utils.data_utils import get_file
# isort: off
from tensorflow.python.util.tf_export import keras_export
@keras_export("keras.datasets.cifar100.load_data")
def load_data(label_mode="fine"):
"""Loads the CIFAR100 dataset.
This is a dataset of 50,000 32x32 color training images and
10,000 test images, labeled over 100 fine-grained classes that are
grouped into 20 coarse-grained classes. See more info at the
[CIFAR homepage](https://www.cs.toronto.edu/~kriz/cifar.html).
Args:
label_mode: one of "fine", "coarse". If it is "fine" the category labels
are the fine-grained labels, if it is "coarse" the output labels are the
coarse-grained superclasses.
Returns:
Tuple of NumPy arrays: `(x_train, y_train), (x_test, y_test)`.
**x_train**: uint8 NumPy array of image data with shapes
`(50000, 32, 32, 3)`, containing the training data. Pixel values range
from 0 to 255.
**y_train**: uint8 NumPy array of labels (integers in range 0-99)
with shape `(50000, 1)` for the training data.
**x_test**: uint8 NumPy array of image data with shapes
`(10000, 32, 32, 3)`, containing the test data. Pixel values range
from 0 to 255.
**y_test**: uint8 NumPy array of labels (integers in range 0-99)
with shape `(10000, 1)` for the test data.
Example:
```python
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar100.load_data()
assert x_train.shape == (50000, 32, 32, 3)
assert x_test.shape == (10000, 32, 32, 3)
assert y_train.shape == (50000, 1)
assert y_test.shape == (10000, 1)
```
"""
if label_mode not in ["fine", "coarse"]:
raise ValueError(
'`label_mode` must be one of `"fine"`, `"coarse"`. '
f"Received: label_mode={label_mode}."
)
dirname = "cifar-100-python"
origin = "https://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz"
path = get_file(
dirname,
origin=origin,
untar=True,
file_hash=( # noqa: E501
"85cd44d02ba6437773c5bbd22e183051d648de2e7d6b014e1ef29b855ba677a7"
),
)
fpath = os.path.join(path, "train")
x_train, y_train = load_batch(fpath, label_key=label_mode + "_labels")
fpath = os.path.join(path, "test")
x_test, y_test = load_batch(fpath, label_key=label_mode + "_labels")
y_train = np.reshape(y_train, (len(y_train), 1))
y_test = np.reshape(y_test, (len(y_test), 1))
if backend.image_data_format() == "channels_last":
x_train = x_train.transpose(0, 2, 3, 1)
x_test = x_test.transpose(0, 2, 3, 1)
return (x_train, y_train), (x_test, y_test)
| tf-keras/tf_keras/datasets/cifar100.py/0 | {
"file_path": "tf-keras/tf_keras/datasets/cifar100.py",
"repo_id": "tf-keras",
"token_count": 1378
} | 166 |
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for `DatasetCreator` with `Model.fit` across usages and strategies."""
import os
import numpy as np
import tensorflow.compat.v2 as tf
from absl.testing import parameterized
import tf_keras as keras
from tf_keras import callbacks as callbacks_lib
from tf_keras.engine import sequential
from tf_keras.layers import core as core_layers
from tf_keras.layers.preprocessing import string_lookup
from tf_keras.optimizers.legacy import gradient_descent
from tf_keras.utils import dataset_creator
# isort: off
from tensorflow.python.platform import tf_logging as logging
class DatasetCreatorModelFitTestBase(tf.test.TestCase, parameterized.TestCase):
"""The base class for DatasetCreator with Model.fit tests."""
def _get_dataset_fn(self, use_lookup_layer):
if use_lookup_layer:
filepath = os.path.join(self.get_temp_dir(), "vocab")
with open(filepath, "w") as f:
f.write("\n".join(["earth", "wind", "and", "fire"]))
def dataset_fn(input_context):
del input_context
lookup_layer = string_lookup.StringLookup(
num_oov_indices=1, vocabulary=filepath
)
x = np.array(
[
["earth", "wind", "and", "fire"],
["fire", "and", "earth", "michigan"],
]
)
y = np.array([0, 1])
map_fn = lambda x, y: (lookup_layer(x), y)
return (
tf.data.Dataset.from_tensor_slices((x, y))
.shuffle(10)
.repeat()
.batch(2)
.map(map_fn)
)
else:
def dataset_fn(input_context):
del input_context
x = tf.random.uniform((10, 10))
y = tf.random.uniform((10,))
return (
tf.data.Dataset.from_tensor_slices((x, y))
.shuffle(10)
.repeat()
.batch(2)
)
return dataset_fn
def _model_compile(
self,
strategy,
steps_per_execution=1,
run_eagerly=False,
with_normalization_layer=False,
jit_compile=None,
):
class ResultAssertingCallback(callbacks_lib.Callback):
"""A callback that asserts the result of the tests."""
def __init__(self):
self._prev_epoch = -1
def on_epoch_end(self, epoch, logs=None):
logging.info("testModelFit: epoch=%r, logs=%r", epoch, logs)
if epoch <= self._prev_epoch:
raise RuntimeError(
"Epoch is supposed to be larger than previous."
)
self._prev_epoch = epoch
is_loss_float = logs.get(
"loss", None
) is not None and isinstance(logs["loss"], (float, np.floating))
if not is_loss_float:
raise RuntimeError(
"loss is supposed to be in the logs and float."
)
with strategy.scope():
model = sequential.Sequential([core_layers.Dense(10)])
if with_normalization_layer:
norm = keras.layers.BatchNormalization(
axis=-1, input_shape=(4, 4, 3), momentum=0.8
)
model.add(norm)
model.add(core_layers.Dense(1, activation="sigmoid"))
self._accuracy_metric = keras.metrics.Accuracy()
model.compile(
gradient_descent.SGD(),
loss="binary_crossentropy",
metrics=[self._accuracy_metric],
steps_per_execution=steps_per_execution,
run_eagerly=run_eagerly,
jit_compile=jit_compile,
)
return model, [ResultAssertingCallback()]
def _model_fit(
self,
strategy,
steps_per_execution=1,
validation_data=None,
x=None,
y=None,
shuffle=True,
batch_size=None,
steps_per_epoch=10,
run_eagerly=False,
with_normalization_layer=False,
callbacks=None,
use_lookup_layer=False,
use_dataset_creator=True,
verbose="auto",
jit_compile=None,
):
if callbacks is None:
callbacks = []
model, default_callbacks = self._model_compile(
strategy,
steps_per_execution,
run_eagerly,
with_normalization_layer,
jit_compile,
)
callbacks += default_callbacks
if x is None:
if use_dataset_creator:
x = dataset_creator.DatasetCreator(
self._get_dataset_fn(use_lookup_layer)
)
else:
x = self._get_dataset_fn(use_lookup_layer)(None)
if validation_data is None:
if use_dataset_creator:
validation_data = dataset_creator.DatasetCreator(
self._get_dataset_fn(use_lookup_layer)
)
else:
validation_data = self._get_dataset_fn(use_lookup_layer)(None)
model.fit(
x,
y,
shuffle=shuffle,
batch_size=batch_size,
epochs=10,
steps_per_epoch=steps_per_epoch,
callbacks=callbacks,
validation_data=validation_data,
validation_steps=steps_per_epoch,
verbose=verbose,
)
return model
def _model_evaluate(
self,
strategy,
steps_per_execution=1,
x=None,
y=None,
batch_size=None,
steps=10,
run_eagerly=False,
with_normalization_layer=False,
callbacks=None,
use_dataset_creator=True,
):
if callbacks is None:
callbacks = []
model, default_callbacks = self._model_compile(
strategy,
steps_per_execution,
run_eagerly,
with_normalization_layer,
)
callbacks += default_callbacks
def dataset_fn(input_context):
del input_context
x = tf.random.uniform((10, 10))
y = tf.random.uniform((10, 1))
return (
tf.data.Dataset.from_tensor_slices((x, y))
.shuffle(10)
.repeat()
.batch(8)
)
if x is None:
if use_dataset_creator:
x = dataset_creator.DatasetCreator(dataset_fn)
else:
x = dataset_fn(None)
model.evaluate(
x=x, y=y, steps=steps, callbacks=callbacks, batch_size=batch_size
)
return model
def _model_predict(
self,
strategy,
model=None,
steps_per_execution=1,
test_data=None,
steps=10,
with_normalization_layer=False,
):
callbacks = []
if model is None:
model, default_callbacks = self._model_compile(
strategy,
steps_per_execution,
with_normalization_layer=with_normalization_layer,
)
callbacks += default_callbacks
def create_test_data():
x = tf.constant([[1.0], [2.0], [3.0], [1.0], [5.0], [1.0]])
return tf.data.Dataset.from_tensor_slices(x).repeat().batch(2)
if test_data is None:
test_data = create_test_data()
predictions = model.predict(
x=test_data, steps=steps, callbacks=callbacks
)
predictions = np.around(predictions, 4)
return model, predictions
| tf-keras/tf_keras/distribute/dataset_creator_model_fit_test_base.py/0 | {
"file_path": "tf-keras/tf_keras/distribute/dataset_creator_model_fit_test_base.py",
"repo_id": "tf-keras",
"token_count": 4431
} | 167 |
# Copyright 2019 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.
# ==============================================================================
"""Correctness tests for tf.keras RNN models using DistributionStrategy."""
import numpy as np
import tensorflow.compat.v2 as tf
import tf_keras as keras
from tf_keras.distribute import keras_correctness_test_base
from tf_keras.layers.rnn import gru
from tf_keras.layers.rnn import gru_v1
from tf_keras.layers.rnn import lstm
from tf_keras.layers.rnn import lstm_v1
from tf_keras.mixed_precision import policy
from tf_keras.optimizers.legacy import (
gradient_descent as gradient_descent_keras,
)
from tf_keras.testing_infra import test_utils
class _DistributionStrategyRnnModelCorrectnessTest(
keras_correctness_test_base.TestDistributionStrategyEmbeddingModelCorrectnessBase # noqa: E501
):
def _get_layer_class(self):
raise NotImplementedError
def get_model(
self,
max_words=10,
initial_weights=None,
distribution=None,
input_shapes=None,
):
del input_shapes
rnn_cls = self._get_layer_class()
with keras_correctness_test_base.MaybeDistributionScope(distribution):
word_ids = keras.layers.Input(
shape=(max_words,), dtype=np.int32, name="words"
)
word_embed = keras.layers.Embedding(input_dim=20, output_dim=10)(
word_ids
)
rnn_embed = rnn_cls(units=4, return_sequences=False)(word_embed)
dense_output = keras.layers.Dense(2)(rnn_embed)
preds = keras.layers.Softmax(dtype="float32")(dense_output)
model = keras.Model(inputs=[word_ids], outputs=[preds])
if initial_weights:
model.set_weights(initial_weights)
optimizer_fn = gradient_descent_keras.SGD
model.compile(
optimizer=optimizer_fn(learning_rate=0.1),
loss="sparse_categorical_crossentropy",
metrics=["sparse_categorical_accuracy"],
)
return model
@test_utils.run_all_without_tensor_float_32(
"Uses Dense layers, which call matmul"
)
class DistributionStrategyGruModelCorrectnessTest(
_DistributionStrategyRnnModelCorrectnessTest
):
def _get_layer_class(self):
if tf.__internal__.tf2.enabled():
if not tf.executing_eagerly():
self.skipTest(
"GRU v2 and legacy graph mode don't work together."
)
return gru.GRU
else:
return gru_v1.GRU
@tf.__internal__.distribute.combinations.generate(
keras_correctness_test_base.test_combinations_for_embedding_model()
+ keras_correctness_test_base.multi_worker_mirrored_eager()
)
def test_gru_model_correctness(
self, distribution, use_numpy, use_validation_data
):
self.run_correctness_test(distribution, use_numpy, use_validation_data)
@test_utils.run_all_without_tensor_float_32(
"Uses Dense layers, which call matmul"
)
class DistributionStrategyLstmModelCorrectnessTest(
_DistributionStrategyRnnModelCorrectnessTest
):
def _get_layer_class(self):
if tf.__internal__.tf2.enabled():
if not tf.executing_eagerly():
self.skipTest(
"LSTM v2 and legacy graph mode don't work together."
)
return lstm.LSTM
else:
return lstm_v1.LSTM
@tf.__internal__.distribute.combinations.generate(
keras_correctness_test_base.test_combinations_for_embedding_model()
+ keras_correctness_test_base.multi_worker_mirrored_eager()
)
def test_lstm_model_correctness(
self, distribution, use_numpy, use_validation_data
):
self.run_correctness_test(distribution, use_numpy, use_validation_data)
@tf.__internal__.distribute.combinations.generate(
keras_correctness_test_base.test_combinations_for_embedding_model()
+ keras_correctness_test_base.multi_worker_mirrored_eager()
)
@test_utils.enable_v2_dtype_behavior
def test_lstm_model_correctness_mixed_precision(
self, distribution, use_numpy, use_validation_data
):
if isinstance(
distribution,
(
tf.distribute.experimental.CentralStorageStrategy,
tf.compat.v1.distribute.experimental.CentralStorageStrategy,
),
):
self.skipTest(
"CentralStorageStrategy is not supported by mixed precision."
)
if isinstance(
distribution,
(
tf.distribute.experimental.TPUStrategy,
tf.compat.v1.distribute.experimental.TPUStrategy,
),
):
policy_name = "mixed_bfloat16"
else:
policy_name = "mixed_float16"
with policy.policy_scope(policy_name):
self.run_correctness_test(
distribution, use_numpy, use_validation_data
)
if __name__ == "__main__":
tf.__internal__.distribute.multi_process_runner.test_main()
| tf-keras/tf_keras/distribute/keras_rnn_model_correctness_test.py/0 | {
"file_path": "tf-keras/tf_keras/distribute/keras_rnn_model_correctness_test.py",
"repo_id": "tf-keras",
"token_count": 2503
} | 168 |
# Copyright 2019 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 saving and loading with mixed APIs with distribution strategies.
For saving, Keras's export_saved_model() API is used; and for loading,
saved_model's load() API is used. Keras's export_save_model() when used with
`serving_only` parameter equals to True should be the same as using
tf.saved_model.save().
"""
import tensorflow.compat.v2 as tf
from tf_keras.distribute import saved_model_test_base as test_base
from tf_keras.saving.legacy import save
from tf_keras.testing_infra import test_utils
_DEFAULT_FUNCTION_KEY = "serving_default"
@test_utils.run_all_without_tensor_float_32(
"Uses Dense layers, which call matmul"
)
class SavedModelSaveAndLoadTest(test_base.TestSavedModelBase):
def setUp(self):
self._root_dir = "saved_model_save_load"
super().setUp()
def _save_model(self, model, saved_dir):
save.save_model(model, saved_dir, save_format="tf")
def _load_and_run_model(
self, distribution, saved_dir, predict_dataset, output_name="output_1"
):
return test_base.load_and_run_with_saved_model_api(
distribution, saved_dir, predict_dataset, output_name
)
@tf.__internal__.distribute.combinations.generate(
test_base.simple_models_with_strategies()
)
def test_save_no_strategy_restore_strategy(
self, model_and_input, distribution
):
self.run_test_save_no_strategy_restore_strategy(
model_and_input, distribution
)
@tf.__internal__.distribute.combinations.generate(
tf.__internal__.test.combinations.times(
test_base.simple_models_with_strategies(),
tf.__internal__.test.combinations.combine(
save_in_scope=[True, False]
),
)
)
def test_save_strategy_restore_no_strategy(
self, model_and_input, distribution, save_in_scope
):
self.run_test_save_strategy_restore_no_strategy(
model_and_input, distribution, save_in_scope
)
@tf.__internal__.distribute.combinations.generate(
tf.__internal__.test.combinations.times(
test_base.simple_models_with_strategy_pairs(),
tf.__internal__.test.combinations.combine(
save_in_scope=[True, False]
),
)
)
def test_save_strategy_restore_strategy(
self,
model_and_input,
distribution_for_saving,
distribution_for_restoring,
save_in_scope,
):
self.run_test_save_strategy_restore_strategy(
model_and_input,
distribution_for_saving,
distribution_for_restoring,
save_in_scope,
)
if __name__ == "__main__":
tf.compat.v1.enable_eager_execution()
tf.test.main()
| tf-keras/tf_keras/distribute/saved_model_mixed_api_test.py/0 | {
"file_path": "tf-keras/tf_keras/distribute/saved_model_mixed_api_test.py",
"repo_id": "tf-keras",
"token_count": 1381
} | 169 |
# Copyright 2022 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 layout_map."""
import os
import shutil
import numpy as np
import tensorflow.compat.v2 as tf
from tf_keras import backend
from tf_keras import layers
from tf_keras import models
from tf_keras.dtensor import dtensor_api as dtensor
from tf_keras.dtensor import layout_map as layout_map_lib
from tf_keras.dtensor import test_util
from tf_keras.utils import tf_utils
class LayoutMapTest(test_util.DTensorBaseTest):
def setUp(self):
super().setUp()
backend.enable_tf_random_generator()
tf_utils.set_random_seed(1337)
global_ids = test_util.create_device_ids_array((2, 2))
local_device_ids = np.ravel(global_ids).tolist()
mesh_dict = {
"CPU": dtensor.Mesh(
["X", "Y"],
global_ids,
local_device_ids,
test_util.create_device_list((2, 2), "CPU"),
)
}
self.mesh = self.configTestMesh(mesh_dict)
self.layout_2d = dtensor.Layout.replicated(self.mesh, rank=2)
self.layout_1d = dtensor.Layout.replicated(self.mesh, rank=1)
self.sharded_2d = dtensor.Layout.batch_sharded(self.mesh, "X", rank=2)
self.sharded_1d = dtensor.Layout.batch_sharded(self.mesh, "X", rank=1)
def test_add(self):
layout_map = layout_map_lib.LayoutMap()
layout_map["dense/kernel"] = self.layout_2d
layout_map["dense/bias"] = self.layout_1d
# Make there are two items in the map, and we access them via the
# underlying container at layout_map._layout_map
self.assertLen(layout_map._layout_map, 2)
self.assertEqual(layout_map._layout_map["dense/kernel"], self.layout_2d)
self.assertEqual(layout_map._layout_map["dense/bias"], self.layout_1d)
with self.assertRaisesRegex(ValueError, "dense/kernel already exist"):
layout_map["dense/kernel"] = self.layout_1d
with self.assertRaisesRegex(ValueError, "should be a dtensor.Layout"):
layout_map["conv.kernel"] = [1, 2, 3]
def test_get(self):
layout_map = layout_map_lib.LayoutMap()
layout_map["dense/kernel"] = self.sharded_2d
layout_map["dense/bias"] = self.sharded_1d
layout_map["dense.*kernel"] = self.layout_2d
layout_map["dense.*bias"] = self.layout_1d
layout_map[".*bias"] = self.sharded_1d
self.assertEqual(layout_map["dense/kernel"], self.sharded_2d)
self.assertEqual(layout_map["dense/bias"], self.sharded_1d)
# Map against the wildcard bias rule for dense, and based on the order
# of insertion, it will not use .*bias.
self.assertEqual(layout_map["dense_2/kernel"], self.layout_2d)
self.assertEqual(layout_map["dense_2/bias"], self.layout_1d)
self.assertIsNone(layout_map["conv2d/kernel"])
self.assertEqual(layout_map["conv2d/bias"], self.sharded_1d)
def test_delete(self):
layout_map = layout_map_lib.LayoutMap()
layout_map["dense/kernel"] = self.layout_2d
layout_map["dense/bias"] = self.layout_1d
self.assertEqual(layout_map.pop("dense/kernel"), self.layout_2d)
# Make sure to match against the exact string, not the regex
with self.assertRaises(KeyError):
layout_map.pop(".*bias")
# Make sure del also works
del layout_map["dense/bias"]
self.assertEmpty(layout_map._layout_map)
def test_len(self):
layout_map = layout_map_lib.LayoutMap()
self.assertEmpty(layout_map)
layout_map["dense/kernel"] = self.layout_2d
layout_map["dense/bias"] = self.layout_1d
self.assertLen(layout_map, 2)
def test_iter(self):
layout_map = layout_map_lib.LayoutMap()
layout_map["dense/kernel"] = self.layout_2d
layout_map["dense/bias"] = self.layout_1d
# Make sure the items are ordered based on the insertion order.
self.assertEqual(
list(layout_map.keys()), ["dense/kernel", "dense/bias"]
)
keys = []
values = []
for k, v in layout_map.items():
keys.append(k)
values.append(v)
self.assertEqual(keys, ["dense/kernel", "dense/bias"])
self.assertEqual(values, [self.layout_2d, self.layout_1d])
# Class used for testing.
class SubclassModel(models.Model):
def __init__(self, name=None):
super().__init__(name=name)
self.d1 = layers.Dense(1000)
self.d2 = layers.Dense(1000)
self.dropout = layers.Dropout(0.1)
def call(self, inputs, training=None):
x = self.d1(inputs)
x = self.dropout(x, training=training)
return self.d2(x)
class SubclassLayer(layers.Layer):
def __init__(self, unit):
super().__init__()
self.unit = unit
def build(self, input_shape):
weight_shape = (input_shape[-1], self.unit)
# Note that the variable name is "kernel", but assigned to "_weight"
# This will cause the checkpoint to record 2 dependencies.
self._weight = self.add_weight(shape=weight_shape, name="kernel")
def call(self, inputs):
return tf.matmul(inputs, self._weight)
class ObjectPathMappingTest(test_util.DTensorBaseTest):
def setUp(self):
super().setUp()
backend.enable_tf_random_generator()
tf_utils.set_random_seed(1337)
global_ids = test_util.create_device_ids_array((2, 2))
local_device_ids = np.ravel(global_ids).tolist()
mesh_dict = {
"CPU": dtensor.Mesh(
["X", "Y"],
global_ids,
local_device_ids,
test_util.create_device_list((2, 2), "CPU"),
)
}
self.mesh = self.configTestMesh(mesh_dict)
self.layout_2d = dtensor.Layout.replicated(self.mesh, rank=2)
self.layout_1d = dtensor.Layout.replicated(self.mesh, rank=1)
self.sharded_2d = dtensor.Layout.batch_sharded(self.mesh, "X", rank=2)
self.sharded_1d = dtensor.Layout.batch_sharded(self.mesh, "X", rank=1)
def test_init_subclass_model_variable_with_layout(self):
layout_map = layout_map_lib.LayoutMap(mesh=self.mesh)
layout_map["d1.kernel"] = self.layout_2d
layout_map["d1.bias"] = self.layout_1d
layout_map["d2.kernel"] = self.layout_2d
layout_map["d2.bias"] = self.layout_1d
with layout_map.scope():
model = SubclassModel(name="model")
# Init the model with eager tensor, make sure the model weights have
# correct layout, as well as produce correct result.
inputs = tf.zeros((10, 10))
inputs = dtensor.copy_to_mesh(inputs, layout=self.layout_2d)
result = model(inputs)
self.assertAllClose(result, tf.zeros((10, 1000)))
d1 = model.d1
d2 = model.d2
self.assertEqual(d1.kernel.layout, self.layout_2d)
self.assertEqual(d1.bias.layout, self.layout_1d)
self.assertEqual(d2.kernel.layout, self.layout_2d)
self.assertEqual(d2.bias.layout, self.layout_1d)
# Also make sure we repopulate the cached attributes like
# layer._trainable_weights
self.assertIs(d1.kernel, d1._trainable_weights[0])
self.assertIs(d1.bias, d1._trainable_weights[1])
self.assertIs(d2.kernel, d2._trainable_weights[0])
self.assertIs(d2.bias, d2._trainable_weights[1])
result = model(inputs, training=True)
self.assertAllClose(
result,
tf.experimental.dtensor.copy_to_mesh(
tf.zeros((10, 1000)), self.layout_2d
),
)
def test_init_functional_model_variable_with_layout(self):
# Note that the functional model is using layers name + attribute name
# the layer name are unique among the functional model, and when the
# layer doesn't have a name, keras will give it a unique name based on
# the layer class.
layout_map = layout_map_lib.LayoutMap(mesh=self.mesh)
layout_map["d1.kernel"] = self.layout_2d
layout_map["d1.bias"] = self.layout_1d
layout_map["d2.kernel"] = self.layout_2d
layout_map["d2.bias"] = self.layout_1d
with layout_map.scope():
inputs = layers.Input((10,), batch_size=10)
x = layers.Dense(20, name="d1")(inputs)
x = layers.Dropout(0.1)(x)
output = layers.Dense(30, name="d2")(x)
model = models.Model(inputs, output)
# It includes input layer as well.
self.assertLen(model.layers, 4)
d1 = model.layers[1]
d2 = model.layers[3]
self.assertEqual(d1.kernel.layout, self.layout_2d)
self.assertEqual(d1.bias.layout, self.layout_1d)
self.assertEqual(d2.kernel.layout, self.layout_2d)
self.assertEqual(d2.bias.layout, self.layout_1d)
# Also make sure we repopulate the cached attributes like
# layer._trainable_weights
self.assertIs(d1.kernel, d1._trainable_weights[0])
self.assertIs(d1.bias, d1._trainable_weights[1])
self.assertIs(d2.kernel, d2._trainable_weights[0])
self.assertIs(d2.bias, d2._trainable_weights[1])
inputs = tf.zeros((10, 10))
inputs = dtensor.copy_to_mesh(inputs, layout=self.layout_2d)
result = model(inputs, training=True)
expected_result = tf.zeros((10, 30))
expected_result = dtensor.copy_to_mesh(
expected_result, layout=self.layout_2d
)
self.assertAllClose(result, expected_result)
def test_init_sequential_model_variable_with_layout(self):
# Note that the sequential model is using layers name + attribute name
# the layer name are unique among the functional model, and when the
# layer doesn't have a name, keras will give it a unique name based on
# the layer class.
layout_map = layout_map_lib.LayoutMap(mesh=self.mesh)
layout_map["d1.kernel"] = self.layout_2d
layout_map["d1.bias"] = self.layout_1d
layout_map["d2.kernel"] = self.layout_2d
layout_map["d2.bias"] = self.layout_1d
with layout_map.scope():
model = models.Sequential(
[
layers.Dense(20, name="d1", input_shape=(10,)),
layers.Dropout(0.1),
layers.Dense(30, name="d2"),
]
)
self.assertLen(model.layers, 3)
d1 = model.layers[0]
d2 = model.layers[2]
self.assertEqual(d1.kernel.layout, self.layout_2d)
self.assertEqual(d1.bias.layout, self.layout_1d)
self.assertEqual(d2.kernel.layout, self.layout_2d)
self.assertEqual(d2.bias.layout, self.layout_1d)
# Also make sure we repopulate the cached attributes like
# layer._trainable_weights
self.assertIs(d1.kernel, d1._trainable_weights[0])
self.assertIs(d1.bias, d1._trainable_weights[1])
self.assertIs(d2.kernel, d2._trainable_weights[0])
self.assertIs(d2.bias, d2._trainable_weights[1])
inputs = tf.zeros((10, 10))
inputs = dtensor.copy_to_mesh(inputs, layout=self.layout_2d)
result = model(inputs, training=True)
expected_result = tf.zeros((10, 30))
expected_result = dtensor.copy_to_mesh(
expected_result, layout=self.layout_2d
)
self.assertAllClose(result, expected_result)
def test_init_model_with_empty_layout_map(self):
# Create empty layout map, which means all the weights just default to
# all replicated.
layout_map = layout_map_lib.LayoutMap(mesh=self.mesh)
with layout_map.scope():
model = models.Sequential(
[
layers.Dense(20, name="d1", input_shape=(10,)),
layers.Dropout(0.1),
layers.Dense(30, name="d2"),
]
)
self.assertLen(model.layers, 3)
d1 = model.layers[0]
d2 = model.layers[2]
self.assertEqual(d1.kernel.layout, self.layout_2d)
self.assertEqual(d1.bias.layout, self.layout_1d)
self.assertEqual(d2.kernel.layout, self.layout_2d)
self.assertEqual(d2.bias.layout, self.layout_1d)
def test_weight_regularization(self):
layout_map = layout_map_lib.LayoutMap(mesh=self.mesh)
with layout_map.scope():
model = models.Sequential(
[
layers.Dense(
20,
name="d1",
input_shape=(10,),
kernel_initializer="ones",
kernel_regularizer="l2",
),
layers.Dropout(0.1),
layers.Dense(
30,
name="d2",
kernel_initializer="ones",
kernel_regularizer="l2",
),
]
)
self.assertLen(model.losses, 2)
# kernel shape [10, 20] with all "1", timed by 0.01 from l2
self.assertAllClose(model.losses[0], 2.0)
# kernel shape [20, 30] with all "1", timed by 0.01 from l2
self.assertAllClose(model.losses[1], 6.0)
def test_dvariable_name(self):
layout_map = layout_map_lib.LayoutMap(mesh=self.mesh)
with layout_map.scope():
model = models.Sequential(
[
layers.Dense(20, name="d1", input_shape=(10,)),
layers.Dropout(0.1),
layers.Dense(30, name="d2"),
]
)
self.assertLen(model.layers, 3)
self.assertEqual(model.layers[0].kernel.name, "d1/kernel:0")
self.assertEqual(model.layers[0].bias.name, "d1/bias:0")
@tf.compat.v1.test.mock.patch.dict(
"os.environ", {"DTENSOR_ENABLE_CHECKPOINT_V2": "True"}
)
def test_checkpoint(self):
layout_map = layout_map_lib.LayoutMap(mesh=self.mesh)
with layout_map.scope():
model = models.Sequential(
[
layers.Dense(20, name="d1", input_shape=(10,)),
SubclassLayer(10),
]
)
cpt = tf.train.Checkpoint(root=model)
options = tf.train.CheckpointOptions(
experimental_io_device=dtensor.device_name()
)
tmpdir = self.get_temp_dir()
self.addCleanup(shutil.rmtree, tmpdir, ignore_errors=True)
saved_path = cpt.save(
os.path.join(tmpdir, "checkpoint"),
options=options,
)
cpt.restore(saved_path, options=options)
if __name__ == "__main__":
tf.test.main()
| tf-keras/tf_keras/dtensor/layout_map_test.py/0 | {
"file_path": "tf-keras/tf_keras/dtensor/layout_map_test.py",
"repo_id": "tf-keras",
"token_count": 7325
} | 170 |
# Copyright 2015 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 base Layer class, from which all layers inherit."""
import functools
import itertools
import threading
import numpy as np
import tensorflow.compat.v2 as tf
from tf_keras import backend
from tf_keras import constraints
from tf_keras import initializers
from tf_keras import regularizers
from tf_keras.engine import base_layer
from tf_keras.engine import base_layer_utils
from tf_keras.engine import input_spec
from tf_keras.mixed_precision import autocast_variable
from tf_keras.mixed_precision import loss_scale_optimizer
from tf_keras.mixed_precision import policy
from tf_keras.saving.legacy.saved_model import layer_serialization
from tf_keras.utils import generic_utils
from tf_keras.utils import layer_utils
from tf_keras.utils import object_identity
from tf_keras.utils import tf_inspect
from tf_keras.utils import tf_utils
# A module that only depends on `keras.layers` import these from here.
from tf_keras.utils.generic_utils import to_snake_case # noqa: F401
from tf_keras.utils.tf_utils import is_tensor_or_tensor_list # noqa: F401
# isort: off
from tensorflow.python.platform import tf_logging
from tensorflow.tools.docs import doc_controls
class Layer(base_layer.Layer):
"""Base layer class.
This is the class from which all layers inherit.
A layer is a class implementing common neural networks operations, such
as convolution, batch norm, etc. These operations require managing weights,
losses, updates, and inter-layer connectivity.
Users will just instantiate a layer and then treat it as a callable.
We recommend that descendants of `Layer` implement the following methods:
* `__init__()`: Save configuration in member variables
* `build()`: Called once from `__call__`, when we know the shapes of inputs
and `dtype`. Should have the calls to `add_weight()`, and then
call the super's `build()` (which sets `self.built = True`, which is
nice in case the user wants to call `build()` manually before the
first `__call__`).
* `call()`: Called in `__call__` after making sure `build()` has been called
once. Should actually perform the logic of applying the layer to the
input tensors (which should be passed in as the first argument).
Args:
trainable: Boolean, whether the layer's variables should be trainable.
name: String name of the layer.
dtype: The dtype of the layer's computations and weights (default of
`None` means use `tf.keras.backend.floatx` in TensorFlow 2, or the type
of the first input in TensorFlow 1).
dynamic: Set this to `True` if your layer should only be run eagerly, and
should not be used to generate a static computation graph.
This would be the case for a Tree-RNN or a recursive network,
for example, or generally for any layer that manipulates tensors
using Python control flow. If `False`, we assume that the layer can
safely be used to generate a static computation graph.
Attributes:
name: The name of the layer (string).
dtype: The dtype of the layer's computations and weights. If mixed
precision is used with a `tf.keras.mixed_precision.Policy`, this is
instead just the dtype of the layer's weights, as the computations are
done in a different dtype.
updates: List of update ops of this layer.
losses: List of losses added by this layer.
trainable_weights: List of variables to be included in backprop.
non_trainable_weights: List of variables that should not be
included in backprop.
weights: The concatenation of the lists trainable_weights and
non_trainable_weights (in this order).
trainable: Whether the layer should be trained (boolean).
input_spec: Optional (list of) `InputSpec` object(s) specifying the
constraints on inputs that can be accepted by the layer.
Each layer has a dtype, which is typically the dtype of the layer's
computations and variables. A layer's dtype can be queried via the
`Layer.dtype` property. The dtype is specified with the `dtype` constructor
argument. In TensorFlow 2, the dtype defaults to `tf.keras.backend.floatx()`
if no dtype is passed. `floatx()` itself defaults to "float32".
Additionally, layers will cast their inputs to the layer's dtype in
TensorFlow 2. When mixed precision is used, layers may have different
computation and variable dtypes. See `tf.keras.mixed_precision.Policy` for
details on layer dtypes.
"""
# See tf.Module for the usage of this property. The key for
# _obj_reference_counts_dict is a Trackable, which could be a variable or
# layer etc. tf.Module._flatten will fail to flatten the key since it is
# trying to convert Trackable to a string. This attribute can be ignored
# even after the fix of nest lib, since the trackable object should already
# been available as individual attributes. _obj_reference_counts_dict just
# contains a copy of them.
_TF_MODULE_IGNORED_PROPERTIES = frozenset(
itertools.chain(
("_obj_reference_counts_dict",),
tf.Module._TF_MODULE_IGNORED_PROPERTIES,
)
)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def __init__(
self, trainable=True, name=None, dtype=None, dynamic=False, **kwargs
):
self._instrument_layer_creation()
# These properties should be set by the user via keyword arguments.
# note that 'dtype', 'input_shape' and 'batch_input_shape'
# are only applicable to input layers: do not pass these keywords
# to non-input layers.
allowed_kwargs = {
"input_dim",
"input_shape",
"batch_input_shape",
"batch_size",
"weights",
"activity_regularizer",
"autocast",
"implementation",
}
# Validate optional keyword arguments.
generic_utils.validate_kwargs(kwargs, allowed_kwargs)
# Mutable properties
# Indicates whether the layer's weights are updated during training
# and whether the layer's updates are run during training.
self._trainable = trainable
# A stateful layer is a layer whose updates are run during inference
# too, for instance stateful RNNs.
self._stateful = False
# Indicates whether `build` needs to be called upon layer call, to
# create the layer's weights.
self.built = False
self._build_input_shape = None
# Provides information about which inputs are compatible with the layer.
self._input_spec = None
self.supports_masking = False
self._init_set_name(name)
self._activity_regularizer = regularizers.get(
kwargs.pop("activity_regularizer", None)
)
self._maybe_create_attribute("_trainable_weights", [])
self._maybe_create_attribute("_non_trainable_weights", [])
self._updates = []
# Object to store all thread local layer properties.
self._thread_local = threading.local()
# A list of zero-argument lambdas which return Tensors, used for
# variable regularizers.
self._callable_losses = []
# A list of symbolic Tensors containing activity regularizers and losses
# manually added through `add_loss` in graph-building mode.
self._losses = []
# A list of metric instances corresponding to the symbolic metric
# tensors added using the `add_metric` API.
self._metrics = []
# Note that models also have a dtype policy, as they are layers. For
# functional models, the policy is only used in Model.compile, which
# wraps the optimizer with a LossScaleOptimizer if the policy name is
# "mixed_float16". Subclassed models additionally use the policy's
# compute and variable dtypes, as like any ordinary layer.
self._set_dtype_policy(dtype)
# Boolean indicating whether the layer automatically casts its inputs to
# the layer's compute_dtype.
self._autocast = kwargs.get(
"autocast", base_layer_utils.v2_dtype_behavior_enabled()
)
# Dependencies tracked via attribute assignment.
# All layers in order of horizontal graph traversal.
# Entries are unique. For models includes input and output layers.
self._maybe_create_attribute("_self_tracked_trackables", [])
# These lists will be filled via successive calls
# to self._add_inbound_node().
# Used in symbolic mode only, only in conjunction with graph-networks
self._inbound_nodes_value = []
self._outbound_nodes_value = []
self._init_call_fn_args()
# Whether the `call` method can be used to build a TF graph without
# issues. This attribute has no effect if the model is created using
# the Functional API. Instead, `model.dynamic` is determined based on
# the internal layers.
self._dynamic = dynamic
# Manage input shape information if passed.
if "input_dim" in kwargs and "input_shape" not in kwargs:
# Backwards compatibility: alias 'input_dim' to 'input_shape'.
kwargs["input_shape"] = (kwargs["input_dim"],)
if "input_shape" in kwargs or "batch_input_shape" in kwargs:
# In this case we will later create an input layer
# to insert before the current layer
if "batch_input_shape" in kwargs:
batch_input_shape = tuple(kwargs["batch_input_shape"])
elif "input_shape" in kwargs:
if "batch_size" in kwargs:
batch_size = kwargs["batch_size"]
else:
batch_size = None
batch_input_shape = (batch_size,) + tuple(kwargs["input_shape"])
self._batch_input_shape = batch_input_shape
# Manage initial weight values if passed.
self._initial_weights = kwargs.get("weights", None)
# Whether the layer will track any layers that are set as attribute on
# itself as sub-layers, the weights from the sub-layers will be included
# in the parent layer's variables() as well. Defaults to `True`, which
# means auto tracking is turned on. Certain subclass might want to turn
# it off, like the Sequential model.
self._auto_track_sub_layers = True
# Mark this layer as having been originally built as a tf1 layer/model
self._originally_built_as_v1 = True
# For backward compat reasons, most built-in layers do not guarantee
# That they will 100% preserve the structure of input args when saving
# / loading configs. E.g. they may un-nest an arg that is
# a list with one element.
self._preserve_input_structure_in_config = False
@tf.__internal__.tracking.no_automatic_dependency_tracking
@generic_utils.default
def build(self, input_shape):
"""Creates the variables of the layer (for subclass implementers).
This is a method that implementers of subclasses of `Layer` or `Model`
can override if they need a state-creation step in-between
layer instantiation and layer call.
This is typically used to create the weights of `Layer` subclasses.
Args:
input_shape: Instance of `TensorShape`, or list of instances of
`TensorShape` if the layer expects a list of inputs
(one instance per input).
"""
if not hasattr(self.build, "_is_default"):
self._build_input_shape = input_shape
self.built = True
@doc_controls.for_subclass_implementers
def call(self, inputs, **kwargs):
"""This is where the layer's logic lives.
Args:
inputs: Input tensor, or list/tuple of input tensors.
**kwargs: Additional keyword arguments.
Returns:
A tensor or list/tuple of tensors.
"""
return inputs
@doc_controls.for_subclass_implementers
def _add_trackable(self, trackable_object, trainable):
"""Adds a Trackable object to this layer's state.
Args:
trackable_object: The tf.tracking.Trackable object to add.
trainable: Boolean, whether the variable should be part of the layer's
"trainable_variables" (e.g. variables, biases) or
"non_trainable_variables" (e.g. BatchNorm mean and variance).
Returns:
The TrackableWeightHandler used to track this object.
"""
if isinstance(
trackable_object, base_layer_utils.TrackableWeightHandler
):
handler = trackable_object
else:
handler = base_layer_utils.TrackableWeightHandler(trackable_object)
if trainable:
self._trainable_weights.append(handler)
else:
self._non_trainable_weights.append(handler)
return handler
@doc_controls.for_subclass_implementers
def add_weight(
self,
name=None,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
trainable=None,
constraint=None,
partitioner=None,
use_resource=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.compat.v1.VariableAggregation.NONE,
**kwargs,
):
"""Adds a new variable to the layer.
Args:
name: Variable name.
shape: Variable shape. Defaults to scalar if unspecified.
dtype: The type of the variable. Defaults to `self.dtype` or
`float32`.
initializer: Initializer instance (callable).
regularizer: Regularizer instance (callable).
trainable: Boolean, whether the variable should be part of the layer's
"trainable_variables" (e.g. variables, biases)
or "non_trainable_variables" (e.g. BatchNorm mean and variance).
Note that `trainable` cannot be `True` if `synchronization`
is set to `ON_READ`.
constraint: Constraint instance (callable).
partitioner: Partitioner to be passed to the `Trackable` API.
use_resource: Whether to use `ResourceVariable`.
synchronization: Indicates when a distributed variable will be
aggregated. Accepted values are constants defined in the class
`tf.VariableSynchronization`. By default the synchronization is set
to `AUTO` and the current `DistributionStrategy` chooses when to
synchronize. If `synchronization` is set to `ON_READ`, `trainable`
must not be set to `True`.
aggregation: Indicates how a distributed variable will be aggregated.
Accepted values are constants defined in the class
`tf.VariableAggregation`.
**kwargs: Additional keyword arguments. Accepted values are `getter`,
`collections`, `experimental_autocast` and `caching_device`.
Returns:
The created variable. Usually either a `Variable` or
`ResourceVariable` instance. If `partitioner` is not `None`, a
`PartitionedVariable` instance is returned.
Raises:
RuntimeError: If called with partitioned variable regularization and
eager execution is enabled.
ValueError: When giving unsupported dtype and no initializer or when
trainable has been set to True with synchronization set as
`ON_READ`.
"""
if shape is None:
shape = ()
# Validate optional keyword arguments.
for kwarg in kwargs:
if kwarg not in [
"getter",
"collections",
"experimental_autocast",
"caching_device",
]:
raise TypeError("Unknown keyword argument:", kwarg)
has_custom_getter = "getter" in kwargs
getter = kwargs.pop("getter", base_layer_utils.make_variable)
collections_arg = kwargs.pop("collections", None)
# 'experimental_autocast' can be set to False by the caller to indicate
# an AutoCastVariable should never be created.
autocast = kwargs.pop("experimental_autocast", True)
# See the docstring for tf.Variable about the details for
# caching_device.
caching_device = kwargs.pop("caching_device", None)
if dtype is None:
dtype = self.dtype or backend.floatx()
dtype = tf.as_dtype(dtype)
if self._dtype_policy.variable_dtype is None:
# The policy is "_infer", so we infer the policy from the variable
# dtype.
self._set_dtype_policy(policy.Policy(dtype.base_dtype.name))
initializer = initializers.get(initializer)
regularizer = regularizers.get(regularizer)
constraint = constraints.get(constraint)
if synchronization == tf.VariableSynchronization.ON_READ:
if trainable:
raise ValueError(
"Synchronization value can be set to "
"VariableSynchronization.ON_READ only for non-trainable "
"variables. You have specified trainable=True and "
"synchronization=VariableSynchronization.ON_READ."
)
else:
# Set trainable to be false when the variable is to be synced on
# read.
trainable = False
elif trainable is None:
trainable = True
# Initialize variable when no initializer provided
if initializer is None:
# If dtype is DT_FLOAT, provide a uniform unit scaling initializer
if dtype.is_floating:
initializer = initializers.get("glorot_uniform")
# If dtype is DT_INT/DT_UINT, provide a default value `zero`
# If dtype is DT_BOOL, provide a default value `FALSE`
elif dtype.is_integer or dtype.is_unsigned or dtype.is_bool:
initializer = tf.compat.v1.zeros_initializer()
# NOTES:Do we need to support for handling DT_STRING and DT_COMPLEX
# here?
elif not has_custom_getter:
# When `getter` is specified, it's possibly fine for
# `initializer` to be None since it's up to the custom `getter`
# to raise error in case it indeed needs `initializer`.
raise ValueError(
"An initializer for variable %s of type %s is required"
" for layer %s" % (name, dtype.base_dtype, self.name)
)
if (
autocast
and self._dtype_policy.compute_dtype
!= self._dtype_policy.variable_dtype
and dtype.is_floating
):
# Wrap 'getter' with a version that returns an AutoCastVariable.
old_getter = getter
def getter(*args, **kwargs):
variable = old_getter(*args, **kwargs)
return autocast_variable.create_autocast_variable(variable)
# Also the caching_device does not work with the mixed precision
# API, disable it if it is specified.
# TODO(b/142020079): Re-enable it once the bug is fixed.
if caching_device is not None:
tf_logging.warning(
"`caching_device` does not work with mixed precision API. "
"Ignoring user specified `caching_device`."
)
caching_device = None
variable = self._add_variable_with_custom_getter(
name=name,
shape=shape,
# TODO(allenl): a `make_variable` equivalent should be added as a
# `Trackable` method.
getter=getter,
# Manage errors in Layer rather than Trackable.
overwrite=True,
initializer=initializer,
dtype=dtype,
constraint=constraint,
trainable=trainable,
partitioner=partitioner,
use_resource=use_resource,
collections=collections_arg,
synchronization=synchronization,
aggregation=aggregation,
caching_device=caching_device,
)
if regularizer is not None:
# TODO(fchollet): in the future, this should be handled at the
# level of variable creation, and weight regularization losses
# should be variable attributes.
name_in_scope = variable.name[: variable.name.find(":")]
self._handle_weight_regularization(
name_in_scope, variable, regularizer
)
if base_layer_utils.is_split_variable(variable):
for v in variable:
backend.track_variable(v)
if trainable:
self._trainable_weights.append(v)
else:
self._non_trainable_weights.append(v)
else:
backend.track_variable(variable)
if trainable:
self._trainable_weights.append(variable)
else:
self._non_trainable_weights.append(variable)
return variable
@generic_utils.default
def get_config(self):
"""Returns the config of the layer.
A layer config is a Python dictionary (serializable)
containing the configuration of a layer.
The same layer can be reinstantiated later
(without its trained weights) from this configuration.
The config of a layer does not include connectivity
information, nor the layer class name. These are handled
by `Network` (one layer of abstraction above).
Returns:
Python dictionary.
"""
all_args = tf_inspect.getfullargspec(self.__init__).args
config = {"name": self.name, "trainable": self.trainable}
if hasattr(self, "_batch_input_shape"):
config["batch_input_shape"] = self._batch_input_shape
config["dtype"] = policy.serialize(self._dtype_policy)
if hasattr(self, "dynamic"):
# Only include `dynamic` in the `config` if it is `True`
if self.dynamic:
config["dynamic"] = self.dynamic
elif "dynamic" in all_args:
all_args.remove("dynamic")
expected_args = config.keys()
# Finds all arguments in the `__init__` that are not in the config:
extra_args = [arg for arg in all_args if arg not in expected_args]
# Check that either the only argument in the `__init__` is `self`,
# or that `get_config` has been overridden:
if len(extra_args) > 1 and hasattr(self.get_config, "_is_default"):
raise NotImplementedError(
"Layers with arguments in `__init__` must "
"override `get_config`."
)
return config
@classmethod
def from_config(cls, config):
"""Creates a layer from its config.
This method is the reverse of `get_config`,
capable of instantiating the same layer from the config
dictionary. It does not handle layer connectivity
(handled by Network), nor weights (handled by `set_weights`).
Args:
config: A Python dictionary, typically the
output of get_config.
Returns:
A layer instance.
"""
return cls(**config)
def compute_output_shape(self, input_shape):
"""Computes the output shape of the layer.
If the layer has not been built, this method will call `build` on the
layer. This assumes that the layer will later be used with inputs that
match the input shape provided here.
Args:
input_shape: Shape tuple (tuple of integers)
or list of shape tuples (one per output tensor of the layer).
Shape tuples can include None for free dimensions,
instead of an integer.
Returns:
An input shape tuple.
"""
if tf.executing_eagerly():
# In this case we build the model first in order to do shape
# inference. This is acceptable because the framework only calls
# `compute_output_shape` on shape values that the layer would later
# be built for. It would however cause issues in case a user
# attempts to use `compute_output_shape` manually with shapes that
# are incompatible with the shape the Layer will be called on (these
# users will have to implement `compute_output_shape` themselves).
self._maybe_build(input_shape)
with tf.compat.v1.get_default_graph().as_default():
graph = tf.__internal__.FuncGraph("graph")
with graph.as_default():
input_shape = tf_utils.convert_shapes(
input_shape, to_tuples=False
)
inputs = tf.nest.map_structure(
base_layer_utils.generate_placeholders_from_shape,
input_shape,
)
try:
outputs = self(inputs, training=False)
except TypeError as e:
raise NotImplementedError(
"We could not automatically infer the static "
"shape of the layer's output. Please implement the "
"`compute_output_shape` method on your layer (%s)."
% self.__class__.__name__
) from e
return tf.nest.map_structure(lambda t: t.shape, outputs)
raise NotImplementedError
@doc_controls.for_subclass_implementers
def compute_output_signature(self, input_signature):
"""Compute the output tensor signature of the layer based on the inputs.
Unlike a TensorShape object, a TensorSpec object contains both shape
and dtype information for a tensor. This method allows layers to provide
output dtype information if it is different from the input dtype.
For any layer that doesn't implement this function,
the framework will fall back to use `compute_output_shape`, and will
assume that the output dtype matches the input dtype.
Args:
input_signature: Single TensorSpec or nested structure of TensorSpec
objects, describing a candidate input for the layer.
Returns:
Single TensorSpec or nested structure of TensorSpec objects,
describing how the layer would transform the provided input.
Raises:
TypeError: If input_signature contains a non-TensorSpec object.
"""
def check_type_return_shape(s):
if not isinstance(s, tf.TensorSpec):
raise TypeError(
"Only TensorSpec signature types are supported, "
"but saw signature entry: {}.".format(s)
)
return s.shape
input_shape = tf.nest.map_structure(
check_type_return_shape, input_signature
)
output_shape = self.compute_output_shape(input_shape)
dtype = self._compute_dtype
if dtype is None:
input_dtypes = [s.dtype for s in tf.nest.flatten(input_signature)]
# Default behavior when self.dtype is None, is to use the first
# input's dtype.
dtype = input_dtypes[0]
return tf.nest.map_structure(
lambda s: tf.TensorSpec(dtype=dtype, shape=s), output_shape
)
@generic_utils.default
def compute_mask(self, inputs, mask=None):
"""Computes an output mask tensor.
Args:
inputs: Tensor or list of tensors.
mask: Tensor or list of tensors.
Returns:
None or a tensor (or list of tensors,
one per output tensor of the layer).
"""
if not self.supports_masking:
if any(m is not None for m in tf.nest.flatten(mask)):
raise TypeError(
"Layer " + self.name + " does not support masking, "
"but was passed an input_mask: " + str(mask)
)
# masking not explicitly supported: return None as mask.
return None
# if masking is explicitly supported, by default
# carry over the input mask
return mask
def __call__(self, *args, **kwargs):
"""Wraps `call`, applying pre- and post-processing steps.
Args:
*args: Positional arguments to be passed to `self.call`.
**kwargs: Keyword arguments to be passed to `self.call`.
Returns:
Output tensor(s).
Note:
- The following optional keyword arguments are reserved for specific
uses:
* `training`: Boolean scalar tensor of Python boolean indicating
whether the `call` is meant for training or inference.
* `mask`: Boolean input mask.
- If the layer's `call` method takes a `mask` argument (as some Keras
layers do), its default value will be set to the mask generated
for `inputs` by the previous layer (if `input` did come from
a layer that generated a corresponding mask, i.e. if it came from
a TF-Keras layer with masking support.
Raises:
ValueError: if the layer's `call` method returns None (an invalid
value).
RuntimeError: if `super().__init__()` was not called in the
constructor.
"""
self._assert_built_as_v1()
if not hasattr(self, "_thread_local"):
raise RuntimeError(
"You must call `super().__init__()` in the layer constructor."
)
# Grab the first positional or keyword argument.
if args:
inputs = args[0]
args = args[1:]
elif self._call_spec.arg_names[0] in kwargs:
inputs = kwargs.pop(self._call_spec.arg_names[0])
else:
raise ValueError(
"The first argument to `Layer.call` must always be passed."
)
call_context = base_layer_utils.call_context()
input_list = tf.nest.flatten(inputs)
# We will attempt to build a TF graph if & only if all inputs are
# symbolic. This is always the case in graph mode. It can also be the
# case in eager mode when all inputs can be traced back to
# `keras.Input()` (when building models using the functional API).
build_graph = tf_utils.are_all_symbolic_tensors(input_list)
# Accept NumPy and scalar inputs by converting to Tensors.
if any(isinstance(x, (np.ndarray, float, int)) for x in input_list):
def _convert_non_tensor(x):
# Don't call `ops.convert_to_tensor` on all `inputs` because
# `SparseTensors` can't be converted to `Tensor`.
if isinstance(x, (np.ndarray, float, int)):
return tf.convert_to_tensor(x)
return x
inputs = tf.nest.map_structure(_convert_non_tensor, inputs)
input_list = tf.nest.flatten(inputs)
# Handle `mask` propagation from previous layer to current layer. Masks
# can be propagated explicitly via the `mask` argument, or implicitly
# via setting the `_keras_mask` attribute on the inputs to a Layer.
# Masks passed explicitly take priority.
mask_arg_passed_by_framework = False
input_masks = self._collect_input_masks(inputs, args, kwargs)
if (
self._expects_mask_arg
and input_masks is not None
and not self._call_spec.arg_was_passed("mask", args, kwargs)
):
mask_arg_passed_by_framework = True
kwargs["mask"] = input_masks
# If `training` argument is None or not explicitly passed,
# propagate `training` value from this layer's calling layer.
training_value = None
training_arg_passed_by_framework = False
# Priority 1: `training` was explicitly passed.
if self._call_spec.arg_was_passed("training", args, kwargs):
training_value = self._call_spec.get_arg_value(
"training", args, kwargs
)
if not self._expects_training_arg:
kwargs.pop("training")
if training_value is None:
# Priority 2: `training` was passed to a parent layer.
if call_context.training is not None:
training_value = call_context.training
# Priority 3a: `learning_phase()` has been set.
elif backend.global_learning_phase_is_set():
training_value = backend.learning_phase()
# Priority 3b: Pass the `learning_phase()` if in the Keras
# FuncGraph.
elif build_graph:
with backend.get_graph().as_default():
if base_layer_utils.is_in_keras_graph():
training_value = backend.learning_phase()
if self._expects_training_arg and training_value is not None:
# Force the training_value to be bool type which matches to the
# contract for layer/model call args.
if tf.is_tensor(training_value):
training_value = tf.cast(training_value, tf.bool)
else:
training_value = bool(training_value)
args, kwargs = self._call_spec.set_arg_value(
"training", training_value, args, kwargs
)
training_arg_passed_by_framework = True
# Only create TF-Keras history if at least one tensor originates from a
# `keras.Input`. Otherwise this Layer may be being used outside the
# TF-Keras framework.
if build_graph and base_layer_utils.needs_keras_history(inputs):
base_layer_utils.create_keras_history(inputs)
with call_context.enter(self, inputs, build_graph, training_value):
# Check input assumptions set after layer building, e.g. input
# shape.
if build_graph:
# Symbolic execution on symbolic tensors. We will attempt to
# build the corresponding TF subgraph inside
# `backend.get_graph()`
input_spec.assert_input_compatibility(
self.input_spec, inputs, self.name
)
graph = backend.get_graph()
with graph.as_default(), backend.name_scope(self._name_scope()):
# Build layer if applicable (if the `build` method has been
# overridden).
self._maybe_build(inputs)
cast_inputs = self._maybe_cast_inputs(inputs)
# Wrapping `call` function in autograph to allow for dynamic
# control flow and control dependencies in call. We are
# limiting this to subclassed layers as autograph is
# strictly needed only for subclassed layers and models.
# tf_convert will respect the value of autograph setting in
# the enclosing tf.function, if any.
if base_layer_utils.is_subclassed(
self
) and not base_layer_utils.from_saved_model(self):
call_fn = tf.__internal__.autograph.tf_convert(
self.call,
tf.__internal__.autograph.control_status_ctx(),
)
else:
call_fn = self.call
if not self.dynamic:
try:
with autocast_variable.enable_auto_cast_variables(
self._compute_dtype_object
):
outputs = call_fn(cast_inputs, *args, **kwargs)
except tf.errors.OperatorNotAllowedInGraphError as e:
raise TypeError(
"You are attempting to use Python control "
"flow in a layer that was not declared to be "
"dynamic. Pass `dynamic=True` to the class "
'constructor.\nEncountered error:\n"""\n'
+ str(e)
+ '\n"""'
)
else:
# We will use static shape inference to return symbolic
# tensors matching the specifications of the layer
# outputs. Since `self.dynamic` is True, we will never
# attempt to run the underlying TF graph (which is
# disconnected).
# TODO(fchollet): consider py_func as an alternative,
# which would enable us to run the underlying graph if
# needed.
outputs = self._symbolic_call(inputs)
if outputs is None:
raise ValueError(
"A layer's `call` method should return a "
"Tensor or a list of Tensors, not None "
"(layer: " + self.name + ")."
)
if base_layer_utils.have_all_keras_metadata(inputs):
if training_arg_passed_by_framework:
args, kwargs = self._call_spec.set_arg_value(
"training",
None,
args,
kwargs,
pop_kwarg_if_none=True,
)
if mask_arg_passed_by_framework:
kwargs.pop("mask")
outputs = self._set_connectivity_metadata(
(inputs,) + args, kwargs, outputs
)
self._handle_activity_regularization(inputs, outputs)
self._set_mask_metadata(inputs, outputs, input_masks)
if hasattr(self, "_set_inputs") and not self.inputs:
# Subclassed network: explicitly set metadata normally
# set by a call to self._set_inputs().
# TODO(b/120997007): This should be done in Eager as
# well, but causes garbage collection issues because of
# the placeholders created on the default TF-Keras
# graph.
self._set_save_spec(inputs, args, kwargs)
self._set_inputs(inputs, outputs)
else:
# Eager execution on data tensors.
with backend.name_scope(self._name_scope()):
self._maybe_build(inputs)
cast_inputs = self._maybe_cast_inputs(inputs)
with autocast_variable.enable_auto_cast_variables(
self._compute_dtype_object
):
outputs = self.call(cast_inputs, *args, **kwargs)
self._handle_activity_regularization(inputs, outputs)
self._set_mask_metadata(inputs, outputs, input_masks)
return outputs
def _assert_built_as_v1(self):
if not hasattr(self, "_originally_built_as_v1"):
raise ValueError(
"Your Layer or Model is in an invalid state. "
"This can happen for the following cases:\n "
"1. You might be interleaving estimator/non-estimator models "
"or interleaving models/layers made in "
"tf.compat.v1.Graph.as_default() with models/layers created "
"outside of it. "
"Converting a model to an estimator (via model_to_estimator) "
"invalidates all models/layers made before the conversion "
"(even if they were not the model converted to an estimator). "
"Similarly, making a layer or a model inside a "
"a tf.compat.v1.Graph invalidates all layers/models you "
"previously made outside of the graph.\n"
"2. You might be using a custom keras layer implementation "
"with custom __init__ which didn't call super().__init__. "
" Please check the implementation of %s and its bases."
% (type(self),)
)
@property
def dtype(self):
return self._dtype_policy.variable_dtype
@property
def name(self):
return self._name
@property
def dynamic(self):
return any(layer._dynamic for layer in self._flatten_layers())
@property
@doc_controls.do_not_generate_docs
def stateful(self):
return any(layer._stateful for layer in self._flatten_layers())
@stateful.setter
def stateful(self, value):
self._stateful = value
@property
def trainable(self):
return self._trainable
@trainable.setter
def trainable(self, value):
self._trainable = value
for layer in getattr(self, "_self_tracked_trackables", []):
layer.trainable = value
@property
def activity_regularizer(self):
"""Optional regularizer function for the output of this layer."""
return self._activity_regularizer
@activity_regularizer.setter
def activity_regularizer(self, regularizer):
"""Optional regularizer function for the output of this layer."""
self._activity_regularizer = regularizer
@property
def input_spec(self):
return self._input_spec
@input_spec.setter
# Must be decorated to prevent tracking, since the input_spec can be nested
# InputSpec objects.
@tf.__internal__.tracking.no_automatic_dependency_tracking
def input_spec(self, value):
for v in tf.nest.flatten(value):
if v is not None and "InputSpec" not in v.__class__.__name__:
raise TypeError(
"Layer input_spec must be an instance of InputSpec. "
"Got: {}".format(v)
)
self._input_spec = value
@property
def updates(self):
collected_updates = []
all_layers = self._flatten_layers()
with backend.get_graph().as_default():
for layer in all_layers:
if not layer.trainable and not layer.stateful:
continue
for u in layer._updates:
if callable(u):
try:
u = u()
except ValueError as e:
if "InaccessibleTensorError" in type(e).__name__:
# For one specific case of error we try to raise
# a more meaningful error message about the
# graph if we can. This error is an internal TF
# symbol that is not publicly exposed, so we
# check the name directly rather than using a
# direct import.
base_layer_utils.check_graph_consistency(
method="add_update", force_raise=True
)
# check_graph_consistency may not always raise.
raise
base_layer_utils.check_graph_consistency(
u, method="add_update"
)
collected_updates.append(u)
return collected_updates
@property
def losses(self):
"""Losses which are associated with this `Layer`.
Variable regularization tensors are created when this property is
accessed, so it is eager safe: accessing `losses` under a
`tf.GradientTape` will propagate gradients back to the corresponding
variables.
Returns:
A list of tensors.
"""
collected_losses = []
all_layers = self._flatten_layers()
for layer in all_layers:
# If any eager losses are present, we assume the model to be part of
# an eager training loop (either a custom one or the one used when
# `run_eagerly=True`) and so we always return just the eager losses.
collected_losses.extend(layer._losses)
for regularizer in layer._callable_losses:
loss_tensor = regularizer()
if loss_tensor is not None:
collected_losses.append(loss_tensor)
return collected_losses
@doc_controls.for_subclass_implementers
def add_loss(self, losses, inputs=None):
"""Add loss tensor(s), potentially dependent on layer inputs.
Some losses (for instance, activity regularization losses) may be
dependent on the inputs passed when calling a layer. Hence, when reusing
the same layer on different inputs `a` and `b`, some entries in
`layer.losses` may be dependent on `a` and some on `b`. This method
automatically keeps track of dependencies.
This method can be used inside a subclassed layer or model's `call`
function, in which case `losses` should be a Tensor or list of Tensors.
Example:
```python
class MyLayer(tf.keras.layers.Layer):
def call(inputs, self):
self.add_loss(tf.abs(tf.reduce_mean(inputs)), inputs=True)
return inputs
```
This method can also be called directly on a Functional Model during
construction. In this case, any loss Tensors passed to this Model must
be symbolic and be able to be traced back to the model's `Input`s. These
losses become part of the model's topology and are tracked in
`get_config`.
Example:
```python
inputs = tf.keras.Input(shape=(10,))
x = tf.keras.layers.Dense(10)(inputs)
outputs = tf.keras.layers.Dense(1)(x)
model = tf.keras.Model(inputs, outputs)
# Activity regularization.
model.add_loss(tf.abs(tf.reduce_mean(x)))
```
If this is not the case for your loss (if, for example, your loss
references a `Variable` of one of the model's layers), you can wrap your
loss in a zero-argument lambda. These losses are not tracked as part of
the model's topology since they can't be serialized.
Example:
```python
inputs = tf.keras.Input(shape=(10,))
x = tf.keras.layers.Dense(10)(inputs)
outputs = tf.keras.layers.Dense(1)(x)
model = tf.keras.Model(inputs, outputs)
# Weight regularization.
model.add_loss(lambda: tf.reduce_mean(x.kernel))
```
Args:
losses: Loss tensor, or list/tuple of tensors. Rather than tensors,
losses may also be zero-argument callables which create a loss
tensor.
inputs: Ignored when executing eagerly. If anything other than None is
passed, it signals the losses are conditional on some of the layer's
inputs, and thus they should only be run where these inputs are
available. This is the case for activity regularization losses, for
instance. If `None` is passed, the losses are assumed
to be unconditional, and will apply across all dataflows of the
layer (e.g. weight regularization losses).
"""
def _tag_unconditional(loss):
"""Process the loss and tag it by setting ._unconditional_loss."""
if callable(loss):
# We run the loss without autocasting, as regularizers are often
# numerically unstable in float16.
with autocast_variable.enable_auto_cast_variables(None):
loss = loss()
if loss is None:
# Will be filtered out when computing the .losses property
return None
if not tf.is_tensor(loss):
loss = tf.convert_to_tensor(loss, dtype=backend.floatx())
loss._unconditional_loss = inputs is None
return loss
losses = tf.nest.flatten(losses)
callable_losses = []
symbolic_losses = []
for loss in losses:
if callable(loss):
callable_losses.append(
functools.partial(_tag_unconditional, loss)
)
continue
if loss is None:
continue
if not tf.is_tensor(loss):
loss = tf.convert_to_tensor(loss, dtype=backend.floatx())
# TF Functions should take the eager path.
if (
tf_utils.is_symbolic_tensor(loss)
and not base_layer_utils.is_in_tf_function()
):
symbolic_losses.append(_tag_unconditional(loss))
base_layer_utils.check_graph_consistency(
loss, method="add_loss"
)
self._callable_losses.extend(callable_losses)
in_call_context = base_layer_utils.call_context().in_call
if in_call_context:
for symbolic_loss in symbolic_losses:
self._losses.append(symbolic_loss)
else:
for symbolic_loss in symbolic_losses:
if getattr(self, "_is_graph_network", False):
self._graph_network_add_loss(symbolic_loss)
else:
# Possible a loss was added in a Layer's `build`.
self._losses.append(symbolic_loss)
@property
def metrics(self):
collected_metrics = []
for layer in self._flatten_layers():
collected_metrics.extend(layer._metrics)
return collected_metrics
@doc_controls.for_subclass_implementers
def add_metric(self, value, aggregation=None, name=None):
"""Adds metric tensor to the layer.
Args:
value: Metric tensor.
aggregation: Sample-wise metric reduction function. If
`aggregation=None`, it indicates that the metric tensor provided has
been aggregated already. eg, `bin_acc = BinaryAccuracy(name='acc')`
followed by `model.add_metric(bin_acc(y_true, y_pred))`. If
aggregation='mean', the given metric tensor will be sample-wise
reduced using `mean` function. eg,
`model.add_metric(tf.reduce_sum(outputs), name='output_mean',
aggregation='mean')`.
name: String metric name.
Raises:
ValueError: If `aggregation` is anything other than None or `mean`.
"""
if aggregation is not None and aggregation != "mean":
raise ValueError(
"We currently support only `mean` sample-wise metric "
"aggregation. You provided aggregation=`%s`" % aggregation
)
from_metric_obj = hasattr(value, "_metric_obj")
is_symbolic = tf_utils.is_symbolic_tensor(value)
in_call_context = base_layer_utils.call_context().in_call
if name is None and not from_metric_obj:
# Eg. `self.add_metric(math_ops.reduce_sum(x), aggregation='mean')`
# In eager mode, we use metric name to lookup a metric. Without a
# name, a new Mean metric wrapper will be created on every
# model/layer call. So, we raise an error when no name is provided.
# We will do the same for symbolic mode for consistency although a
# name will be generated if no name is provided.
# We will not raise this error in the foll use case for the sake of
# consistency as name in provided in the metric constructor.
# mean = metrics.Mean(name='my_metric')
# model.add_metric(mean(outputs))
raise ValueError(
"Please provide a name for your metric like "
"`self.add_metric(tf.reduce_sum(inputs), "
"name='mean_activation', aggregation='mean')`"
)
elif from_metric_obj:
name = value._metric_obj.name
if in_call_context:
# TF Function path should take the eager path.
self._symbolic_add_metric(value, aggregation, name)
else:
if not is_symbolic:
raise ValueError(
"Expected a symbolic Tensor for the metric value, "
"received: " + str(value)
)
# Possible a metric was added in a Layer's `build`.
if not getattr(self, "_is_graph_network", False):
with backend.get_graph().as_default():
self._symbolic_add_metric(value, aggregation, name)
return
if from_metric_obj:
raise ValueError(
"Using the result of calling a `Metric` object "
"when calling `add_metric` on a Functional "
"Model is not supported. Please pass the "
"Tensor to monitor directly."
)
# Insert layers into the TF-Keras Graph Network.
self._graph_network_add_metric(value, aggregation, name)
@doc_controls.for_subclass_implementers
def add_update(self, updates):
"""Add update op(s), potentially dependent on layer inputs.
Weight updates (for instance, the updates of the moving mean and
variance in a BatchNormalization layer) may be dependent on the inputs
passed when calling a layer. Hence, when reusing the same layer on
different inputs `a` and `b`, some entries in `layer.updates` may be
dependent on `a` and some on `b`. This method automatically keeps track
of dependencies.
The `get_updates_for` method allows to retrieve the updates relevant to
a specific set of inputs.
This call is ignored when eager execution is enabled (in that case,
variable updates are run on the fly and thus do not need to be tracked
for later execution).
Args:
updates: Update op, or list/tuple of update ops, or zero-arg callable
that returns an update op. A zero-arg callable should be passed in
order to disable running the updates by setting `trainable=False`
on this Layer, when executing in Eager mode.
"""
call_context = base_layer_utils.call_context()
if (
tf.distribute.has_strategy()
and tf.distribute.in_cross_replica_context()
# When saving the model, the distribution strategy context should be
# ignored, following the default path for adding updates.
and not call_context.saving
):
# Updates don't need to be run in a cross-replica context.
return
updates = generic_utils.to_list(updates)
if call_context.in_call:
relevant_inputs = call_context.inputs
else:
inbound_nodes = getattr(self, "_inbound_nodes", [])
relevant_inputs = [node.input_tensors for node in inbound_nodes]
def process_update(x):
"""Standardize update ops.
Args:
x: Tensor, op, or callable.
Returns:
An update op.
"""
if callable(x):
update = lambda: process_update(x())
return update()
elif isinstance(x, tf.Operation):
update = x
elif hasattr(x, "op"):
update = x.op
else:
update = tf.convert_to_tensor(x)
reachable = tf_utils.get_reachable_from_inputs(
relevant_inputs, [update]
)
update._unconditional_update = update not in reachable
return update
updates = [process_update(x) for x in updates]
self._updates.extend(updates)
def set_weights(self, weights):
"""Sets the weights of the layer, from Numpy arrays.
The weights of a layer represent the state of the layer. This function
sets the weight values from numpy arrays. The weight values should be
passed in the order they are created by the layer. Note that the layer's
weights must be instantiated before calling this function by calling
the layer.
For example, a Dense layer returns a list of two values-- per-output
weights and the bias value. These can be used to set the weights of
another Dense layer:
>>> a = tf.keras.layers.Dense(1,
... kernel_initializer=tf.constant_initializer(1.))
>>> a_out = a(tf.convert_to_tensor([[1., 2., 3.]]))
>>> a.get_weights()
[array([[1.],
[1.],
[1.]], dtype=float32), array([0.], dtype=float32)]
>>> b = tf.keras.layers.Dense(1,
... kernel_initializer=tf.constant_initializer(2.))
>>> b_out = b(tf.convert_to_tensor([[10., 20., 30.]]))
>>> b.get_weights()
[array([[2.],
[2.],
[2.]], dtype=float32), array([0.], dtype=float32)]
>>> b.set_weights(a.get_weights())
>>> b.get_weights()
[array([[1.],
[1.],
[1.]], dtype=float32), array([0.], dtype=float32)]
Args:
weights: a list of Numpy arrays. The number
of arrays and their shape must match
number of the dimensions of the weights
of the layer (i.e. it should match the
output of `get_weights`).
Raises:
ValueError: If the provided weights list does not match the
layer's specifications.
"""
params = self.weights
expected_num_weights = 0
for param in params:
if isinstance(param, base_layer_utils.TrackableWeightHandler):
expected_num_weights += param.num_tensors
else:
expected_num_weights += 1
if expected_num_weights != len(weights):
raise ValueError(
'You called `set_weights(weights)` on layer "%s" '
"with a weight list of length %s, but the layer was "
"expecting %s weights. Provided weights: %s..."
% (
self.name,
len(weights),
expected_num_weights,
str(weights)[:50],
)
)
weight_index = 0
weight_value_tuples = []
for param in params:
if isinstance(param, base_layer_utils.TrackableWeightHandler):
num_tensors = param.num_tensors
tensors = weights[weight_index : weight_index + num_tensors]
param.set_weights(tensors)
weight_index += num_tensors
else:
weight = weights[weight_index]
weight_shape = weight.shape if hasattr(weight, "shape") else ()
ref_shape = param.shape
if not ref_shape.is_compatible_with(weight_shape):
raise ValueError(
"Layer weight shape %s not compatible with provided "
"weight shape %s" % (ref_shape, weight_shape)
)
weight_value_tuples.append((param, weight))
weight_index += 1
backend.batch_set_value(weight_value_tuples)
def get_weights(self):
"""Returns the current weights of the layer.
The weights of a layer represent the state of the layer. This function
returns both trainable and non-trainable weight values associated with
this layer as a list of Numpy arrays, which can in turn be used to load
state into similarly parameterized layers.
For example, a Dense layer returns a list of two values-- per-output
weights and the bias value. These can be used to set the weights of
another Dense layer:
>>> a = tf.keras.layers.Dense(1,
... kernel_initializer=tf.constant_initializer(1.))
>>> a_out = a(tf.convert_to_tensor([[1., 2., 3.]]))
>>> a.get_weights()
[array([[1.],
[1.],
[1.]], dtype=float32), array([0.], dtype=float32)]
>>> b = tf.keras.layers.Dense(1,
... kernel_initializer=tf.constant_initializer(2.))
>>> b_out = b(tf.convert_to_tensor([[10., 20., 30.]]))
>>> b.get_weights()
[array([[2.],
[2.],
[2.]], dtype=float32), array([0.], dtype=float32)]
>>> b.set_weights(a.get_weights())
>>> b.get_weights()
[array([[1.],
[1.],
[1.]], dtype=float32), array([0.], dtype=float32)]
Returns:
Weights values as a list of numpy arrays.
"""
weights = self.weights
output_weights = []
for weight in weights:
if isinstance(weight, base_layer_utils.TrackableWeightHandler):
output_weights.extend(weight.get_tensors())
else:
output_weights.append(weight)
return backend.batch_get_value(output_weights)
def get_updates_for(self, inputs):
"""Retrieves updates relevant to a specific set of inputs.
Args:
inputs: Input tensor or list/tuple of input tensors.
Returns:
List of update ops of the layer that depend on `inputs`.
"""
if inputs is None:
# Requesting unconditional updates.
return [u for u in self.updates if u._unconditional_update]
# Requesting input-conditional updates.
updates = [u for u in self.updates if not u._unconditional_update]
inputs = tf.nest.flatten(inputs)
reachable = tf_utils.get_reachable_from_inputs(inputs, updates)
return [u for u in updates if u in reachable]
def get_losses_for(self, inputs):
"""Retrieves losses relevant to a specific set of inputs.
Args:
inputs: Input tensor or list/tuple of input tensors.
Returns:
List of loss tensors of the layer that depend on `inputs`.
"""
if inputs is None:
# Requesting unconditional losses.
return [l for l in self.losses if l._unconditional_loss]
# Requesting input-conditional losses.
losses = [l for l in self.losses if not l._unconditional_loss]
inputs = tf.nest.flatten(inputs)
reachable = tf_utils.get_reachable_from_inputs(inputs, losses)
return [l for l in losses if l in reachable]
def get_input_mask_at(self, node_index):
"""Retrieves the input mask tensor(s) of a layer at a given node.
Args:
node_index: Integer, index of the node
from which to retrieve the attribute.
E.g. `node_index=0` will correspond to the
first time the layer was called.
Returns:
A mask tensor
(or list of tensors if the layer has multiple inputs).
"""
inputs = self.get_input_at(node_index)
if isinstance(inputs, list):
return [getattr(x, "_keras_mask", None) for x in inputs]
else:
return getattr(inputs, "_keras_mask", None)
def get_output_mask_at(self, node_index):
"""Retrieves the output mask tensor(s) of a layer at a given node.
Args:
node_index: Integer, index of the node
from which to retrieve the attribute.
E.g. `node_index=0` will correspond to the
first time the layer was called.
Returns:
A mask tensor
(or list of tensors if the layer has multiple outputs).
"""
output = self.get_output_at(node_index)
if isinstance(output, list):
return [getattr(x, "_keras_mask", None) for x in output]
else:
return getattr(output, "_keras_mask", None)
@property
def input_mask(self):
"""Retrieves the input mask tensor(s) of a layer.
Only applicable if the layer has exactly one inbound node,
i.e. if it is connected to one incoming layer.
Returns:
Input mask tensor (potentially None) or list of input
mask tensors.
Raises:
AttributeError: if the layer is connected to
more than one incoming layers.
"""
inputs = self.input
if isinstance(inputs, list):
return [getattr(x, "_keras_mask", None) for x in inputs]
else:
return getattr(inputs, "_keras_mask", None)
@property
def output_mask(self):
"""Retrieves the output mask tensor(s) of a layer.
Only applicable if the layer has exactly one inbound node,
i.e. if it is connected to one incoming layer.
Returns:
Output mask tensor (potentially None) or list of output
mask tensors.
Raises:
AttributeError: if the layer is connected to
more than one incoming layers.
"""
output = self.output
if isinstance(output, list):
return [getattr(x, "_keras_mask", None) for x in output]
else:
return getattr(output, "_keras_mask", None)
def get_input_shape_at(self, node_index):
"""Retrieves the input shape(s) of a layer at a given node.
Args:
node_index: Integer, index of the node
from which to retrieve the attribute.
E.g. `node_index=0` will correspond to the
first time the layer was called.
Returns:
A shape tuple
(or list of shape tuples if the layer has multiple inputs).
Raises:
RuntimeError: If called in Eager mode.
"""
return self._get_node_attribute_at_index(
node_index, "input_shapes", "input shape"
)
def get_output_shape_at(self, node_index):
"""Retrieves the output shape(s) of a layer at a given node.
Args:
node_index: Integer, index of the node
from which to retrieve the attribute.
E.g. `node_index=0` will correspond to the
first time the layer was called.
Returns:
A shape tuple
(or list of shape tuples if the layer has multiple outputs).
Raises:
RuntimeError: If called in Eager mode.
"""
return self._get_node_attribute_at_index(
node_index, "output_shapes", "output shape"
)
def get_input_at(self, node_index):
"""Retrieves the input tensor(s) of a layer at a given node.
Args:
node_index: Integer, index of the node
from which to retrieve the attribute.
E.g. `node_index=0` will correspond to the
first input node of the layer.
Returns:
A tensor (or list of tensors if the layer has multiple inputs).
Raises:
RuntimeError: If called in Eager mode.
"""
return self._get_node_attribute_at_index(
node_index, "input_tensors", "input"
)
def get_output_at(self, node_index):
"""Retrieves the output tensor(s) of a layer at a given node.
Args:
node_index: Integer, index of the node
from which to retrieve the attribute.
E.g. `node_index=0` will correspond to the
first output node of the layer.
Returns:
A tensor (or list of tensors if the layer has multiple outputs).
Raises:
RuntimeError: If called in Eager mode.
"""
return self._get_node_attribute_at_index(
node_index, "output_tensors", "output"
)
@property
def input(self):
"""Retrieves the input tensor(s) of a layer.
Only applicable if the layer has exactly one input,
i.e. if it is connected to one incoming layer.
Returns:
Input tensor or list of input tensors.
Raises:
RuntimeError: If called in Eager mode.
AttributeError: If no inbound nodes are found.
"""
if not self._inbound_nodes:
raise AttributeError(
"Layer " + self.name + " is not connected, no input to return."
)
return self._get_node_attribute_at_index(0, "input_tensors", "input")
@property
def output(self):
"""Retrieves the output tensor(s) of a layer.
Only applicable if the layer has exactly one output,
i.e. if it is connected to one incoming layer.
Returns:
Output tensor or list of output tensors.
Raises:
AttributeError: if the layer is connected to more than one incoming
layers.
RuntimeError: if called in Eager mode.
"""
if not self._inbound_nodes:
raise AttributeError(
"Layer " + self.name + " has no inbound nodes."
)
return self._get_node_attribute_at_index(0, "output_tensors", "output")
@property
def input_shape(self):
"""Retrieves the input shape(s) of a layer.
Only applicable if the layer has exactly one input,
i.e. if it is connected to one incoming layer, or if all inputs
have the same shape.
Returns:
Input shape, as an integer shape tuple
(or list of shape tuples, one tuple per input tensor).
Raises:
AttributeError: if the layer has no defined input_shape.
RuntimeError: if called in Eager mode.
"""
if not self._inbound_nodes:
raise AttributeError(
f'The layer "{self.name}" has never been called '
"and thus has no defined input shape. Note that the "
"`input_shape` property is only available for "
"Functional and Sequential models."
)
all_input_shapes = set(
[str(node.input_shapes) for node in self._inbound_nodes]
)
if len(all_input_shapes) == 1:
return self._inbound_nodes[0].input_shapes
else:
raise AttributeError(
'The layer "' + str(self.name) + " has multiple inbound nodes, "
"with different input shapes. Hence "
'the notion of "input shape" is '
"ill-defined for the layer. "
"Use `get_input_shape_at(node_index)` "
"instead."
)
def count_params(self):
"""Count the total number of scalars composing the weights.
Returns:
An integer count.
Raises:
ValueError: if the layer isn't yet built
(in which case its weights aren't yet defined).
"""
if not self.built:
if getattr(self, "_is_graph_network", False):
with tf_utils.maybe_init_scope(self):
self._maybe_build(self.inputs)
else:
raise ValueError(
"You tried to call `count_params` on "
+ self.name
+ ", but the layer isn't built. "
"You can build it manually via: `"
+ self.name
+ ".build(batch_input_shape)`."
)
return layer_utils.count_params(self.weights)
@property
def output_shape(self):
"""Retrieves the output shape(s) of a layer.
Only applicable if the layer has one output,
or if all outputs have the same shape.
Returns:
Output shape, as an integer shape tuple
(or list of shape tuples, one tuple per output tensor).
Raises:
AttributeError: if the layer has no defined output shape.
RuntimeError: if called in Eager mode.
"""
if not self._inbound_nodes:
raise AttributeError(
"The layer has never been called "
"and thus has no defined output shape."
)
all_output_shapes = set(
[str(node.output_shapes) for node in self._inbound_nodes]
)
if len(all_output_shapes) == 1:
return self._inbound_nodes[0].output_shapes
else:
raise AttributeError(
'The layer "%s"'
" has multiple inbound nodes, "
"with different output shapes. Hence "
'the notion of "output shape" is '
"ill-defined for the layer. "
"Use `get_output_shape_at(node_index)` "
"instead." % self.name
)
@property
@doc_controls.do_not_doc_inheritable
def inbound_nodes(self):
"""Deprecated, do NOT use! Only for external TF-Keras compatibility ."""
return self._inbound_nodes
@property
@doc_controls.do_not_doc_inheritable
def outbound_nodes(self):
"""Deprecated, do NOT use! Only for external TF-Keras compatibility ."""
return self._outbound_nodes
###########################################################################
# Methods & attributes below are public aliases of other methods. #
###########################################################################
@property
def variables(self):
"""Returns the list of all layer variables/weights.
Alias of `self.weights`.
Returns:
A list of variables.
"""
return self.weights
@property
def trainable_variables(self):
return self.trainable_weights
@property
def non_trainable_variables(self):
return self.non_trainable_weights
############################################################################
# Methods & attributes below are all private and only used by the framework.
############################################################################
@property
def _inbound_nodes(self):
return self._inbound_nodes_value
@_inbound_nodes.setter
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _inbound_nodes(self, value):
self._inbound_nodes_value = value
@property
def _outbound_nodes(self):
return self._outbound_nodes_value
@_outbound_nodes.setter
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _outbound_nodes(self, value):
self._outbound_nodes_value = value
def _set_dtype_policy(self, dtype):
"""Sets self._dtype_policy."""
if isinstance(dtype, policy.Policy):
self._dtype_policy = dtype
elif isinstance(dtype, dict):
self._dtype_policy = policy.deserialize(dtype)
elif isinstance(dtype, str) and dtype in (
"mixed_float16",
"mixed_bfloat16",
):
# The isinstance check is required since np.dtype raises an error if
# compared to a non-dtype string.
self._dtype_policy = policy.Policy(dtype)
elif dtype:
self._dtype_policy = policy.Policy(tf.as_dtype(dtype).name)
else:
self._dtype_policy = policy.global_policy()
if (
self._dtype_policy.name == "mixed_float16"
and not loss_scale_optimizer.strategy_supports_loss_scaling()
):
# Although only loss scaling doesn't support certain strategies, to
# avoid confusion, we disallow the 'mixed_float16' policy with
# unsupported strategies. This is because 'mixed_float16' requires
# loss scaling for numeric stability.
strategy = tf.distribute.get_strategy()
raise ValueError(
"Mixed precision is not supported with the "
"tf.distribute.Strategy: %s. Either stop using mixed "
'precision by removing the use of the "%s" policy or '
"use a different Strategy, e.g. a MirroredStrategy."
% (strategy.__class__.__name__, self._dtype_policy.name)
)
# Performance optimization: cache the compute dtype as a Dtype object or
# None, so that str to Dtype conversion doesn't happen in
# Layer.__call__.
if self._dtype_policy.compute_dtype:
self._compute_dtype_object = tf.as_dtype(
self._dtype_policy.compute_dtype
)
else:
self._compute_dtype_object = None
# TODO(reedwm): Expose this property?
@property
def _compute_dtype(self):
"""The layer's compute dtype.
Unless mixed-precision is used, this is the same as `Layer.dtype`.
If self._autocast is True, layer's will cast floating-point inputs to
this.
Returns:
The layer's compute dtype.
"""
return self._dtype_policy.compute_dtype
def _maybe_cast_inputs(self, inputs):
"""Maybe casts the inputs to the compute dtype.
If self._compute_dtype is floating-point, and self_autocast is True,
floating-point inputs are casted to self._compute_dtype.
Args:
inputs: Input tensor, or structure of input tensors.
Returns:
`inputs`, but tensors may have been casted to self._compute_dtype
"""
compute_dtype = self._compute_dtype
if (
self._autocast
and compute_dtype
and tf.as_dtype(compute_dtype).is_floating
):
def f(x):
"""Cast a single Tensor or TensorSpec to the compute dtype."""
cast_types = (tf.Tensor, tf.SparseTensor, tf.RaggedTensor)
if (
isinstance(x, cast_types)
and x.dtype.is_floating
and x.dtype.base_dtype.name != compute_dtype
):
return tf.cast(x, compute_dtype)
elif isinstance(x, tf.TensorSpec) and x.dtype.is_floating:
# Inputs may be TensorSpecs when this function is called
# from model._set_inputs.
return tf.TensorSpec(x.shape, compute_dtype, x.name)
else:
return x
return tf.nest.map_structure(f, inputs)
else:
return inputs
# _dtype used to be an attribute set in the constructor. We still expose it
# because some clients still use it.
# TODO(reedwm): Deprecate, then remove the _dtype property.
@property
def _dtype(self):
# This is equivalent to returning self.dtype . We do not return
# self.dtype as it would cause infinite recursion in a few subclasses,
# which override "dtype" to return self._dtype.
return self._dtype_policy.variable_dtype
@_dtype.setter
def _dtype(self, value):
value = tf.as_dtype(value).name
self._set_dtype_policy(policy.Policy(value))
def _name_scope(self):
return self.name
def _init_set_name(self, name, zero_based=True):
if not name:
self._name = backend.unique_object_name(
generic_utils.to_snake_case(self.__class__.__name__),
zero_based=zero_based,
)
else:
self._name = name
def _get_existing_metric(self, name=None):
match = [m for m in self._metrics if m.name == name]
if not match:
return
if len(match) > 1:
raise ValueError(
"Please provide different names for the metrics you have "
'added. We found {} metrics with the name: "{}"'.format(
len(match), name
)
)
return match[0]
def _symbolic_add_metric(self, value, aggregation=None, name=None):
base_layer_utils.check_graph_consistency(value, method="add_metric")
match = self._get_existing_metric(name)
if aggregation is None:
# Iterate over the metrics and check if the given metric exists
# already. This can happen when a metric instance is created in
# subclassed model layer `__init__` and we have tracked that
# instance already in model.__setattr__.
if match:
result_tensor = value
metric_obj = match
elif hasattr(value, "_metric_obj"):
# We track the instance using the metadata on the result tensor.
result_tensor = value
metric_obj = result_tensor._metric_obj
self._metrics.append(metric_obj)
else:
raise ValueError(
"We do not support adding an aggregated metric result "
"tensor that is not the output of a "
"`tf.keras.metrics.Metric` metric instance. Without "
"having access to the metric instance we cannot reset the "
"state of a metric after every epoch during training. You "
"can create a `tf.keras.metrics.Metric` instance and pass "
"the result here or pass an un-aggregated result with "
"`aggregation` parameter set as `mean`. For example: "
"`self.add_metric(tf.reduce_sum(inputs), "
"name='mean_activation', aggregation='mean')` "
)
else:
# If a non-aggregated tensor is given as input (ie. `aggregation` is
# explicitly set to `mean`), we wrap the tensor in `Mean` metric.
if match:
result_tensor = match(value)
metric_obj = match
else:
metric_obj, result_tensor = base_layer_utils.create_mean_metric(
value, name
)
self._metrics.append(metric_obj)
def _handle_weight_regularization(self, name, variable, regularizer):
"""Create lambdas which compute regularization losses."""
def _loss_for_variable(v):
"""Creates a regularization loss `Tensor` for variable `v`."""
with backend.name_scope(name + "/Regularizer"):
regularization = regularizer(v)
return regularization
if base_layer_utils.is_split_variable(variable):
for v in variable:
self.add_loss(functools.partial(_loss_for_variable, v))
else:
self.add_loss(functools.partial(_loss_for_variable, variable))
def _handle_activity_regularization(self, inputs, outputs):
# Apply activity regularization.
# Note that it should be applied every time the layer creates a new
# output, since it is output-specific.
if self._activity_regularizer:
output_list = tf.nest.flatten(outputs)
with backend.name_scope("ActivityRegularizer"):
for output in output_list:
activity_loss = tf.convert_to_tensor(
self._activity_regularizer(output)
)
batch_size = tf.cast(
tf.compat.v1.shape(output)[0], activity_loss.dtype
)
# Make activity regularization strength batch-agnostic.
mean_activity_loss = activity_loss / batch_size
base_layer_utils.check_graph_consistency(
mean_activity_loss, method="activity_regularizer"
)
self.add_loss(mean_activity_loss, inputs=inputs)
def _set_mask_metadata(self, inputs, outputs, previous_mask):
flat_outputs = tf.nest.flatten(outputs)
mask_already_computed = getattr(
self, "_compute_output_and_mask_jointly", False
) or all(
getattr(x, "_keras_mask", None) is not None for x in flat_outputs
)
# Only compute the mask if the Layer explicitly supports masking or has
# overridden `compute_mask`.
should_compute_mask = hasattr(self, "compute_mask") and (
self.supports_masking
or not getattr(self.compute_mask, "_is_default", False)
)
if mask_already_computed:
flat_masks = [getattr(x, "_keras_mask", None) for x in flat_outputs]
elif not should_compute_mask:
flat_masks = [None for _ in flat_outputs]
else:
output_masks = self.compute_mask(inputs, previous_mask)
# `compute_mask` can return a single `None` even when a Layer
# has multiple outputs.
if output_masks is None:
flat_masks = [None for _ in flat_outputs]
else:
flat_masks = tf.nest.flatten(output_masks)
for output, mask in zip(flat_outputs, flat_masks):
try:
output._keras_mask = mask
except AttributeError:
# C Type such as np.ndarray.
pass
if tf_utils.are_all_symbolic_tensors(flat_outputs):
for output in flat_outputs:
if getattr(output, "_keras_mask", None) is not None:
# Do not track masks for `TensorFlowOpLayer` construction.
output._keras_mask._keras_history_checked = True
def _collect_input_masks(self, inputs, args, kwargs):
"""Checks if mask argument was passed, else gathers mask from inputs."""
if self._call_spec.arg_was_passed("mask", args, kwargs):
return self._call_spec.get_arg_value("mask", args, kwargs)
if not self._should_compute_mask:
return None
input_masks = tf.nest.map_structure(
lambda t: getattr(t, "_keras_mask", None), inputs
)
if generic_utils.is_all_none(input_masks):
return None
return input_masks
def _get_node_attribute_at_index(self, node_index, attr, attr_name):
"""Private utility to retrieves an attribute (e.g. inputs) from a node.
This is used to implement the methods:
- get_input_shape_at
- get_output_shape_at
- get_input_at
etc...
Args:
node_index: Integer index of the node from which
to retrieve the attribute.
attr: Exact node attribute name.
attr_name: Human-readable attribute name, for error messages.
Returns:
The layer's attribute `attr` at the node of index `node_index`.
Raises:
RuntimeError: If the layer has no inbound nodes, or if called in
Eager mode.
ValueError: If the index provided does not match any node.
"""
if not self._inbound_nodes:
raise RuntimeError(
"The layer has never been called and thus has no defined "
+ attr_name
+ "."
)
if not len(self._inbound_nodes) > node_index:
raise ValueError(
"Asked to get "
+ attr_name
+ " at node "
+ str(node_index)
+ ", but the layer has only "
+ str(len(self._inbound_nodes))
+ " inbound nodes."
)
values = getattr(self._inbound_nodes[node_index], attr)
if isinstance(values, list) and len(values) == 1:
return values[0]
else:
return values
def _maybe_build(self, inputs):
# Check input assumptions set before layer building, e.g. input rank.
if not self.built:
input_spec.assert_input_compatibility(
self.input_spec, inputs, self.name
)
input_list = tf.nest.flatten(inputs)
if input_list and self._dtype_policy.compute_dtype is None:
try:
dtype = input_list[0].dtype.base_dtype.name
except AttributeError:
pass
else:
self._set_dtype_policy(policy.Policy(dtype))
input_shapes = None
if all(hasattr(x, "shape") for x in input_list):
input_shapes = tf.nest.map_structure(lambda x: x.shape, inputs)
# Only call `build` if the user has manually overridden the build
# method.
if not hasattr(self.build, "_is_default"):
# Any setup work performed only once should happen in an
# `init_scope` to avoid creating symbolic Tensors that will
# later pollute any eager operations.
with tf_utils.maybe_init_scope(self):
self.build(input_shapes)
# We must set also ensure that the layer is marked as built, and the
# build shape is stored since user defined build functions may not
# be calling `super.build()`
Layer.build(self, input_shapes)
# Optionally load weight values specified at layer instantiation.
if self._initial_weights is not None:
self.set_weights(self._initial_weights)
self._initial_weights = None
def _symbolic_call(self, inputs):
input_shapes = tf.nest.map_structure(lambda x: x.shape, inputs)
output_shapes = self.compute_output_shape(input_shapes)
def _make_placeholder_like(shape):
ph = backend.placeholder(shape=shape, dtype=self.dtype)
ph._keras_mask = None
return ph
return tf.nest.map_structure(_make_placeholder_like, output_shapes)
def _get_trainable_state(self):
"""Get the `trainable` state of each sublayer.
Returns:
A dict mapping all sublayers to their `trainable` value.
"""
layers = self._flatten_layers(include_self=False, recursive=False)
trainable_state = {self: self.trainable}
for l in layers:
trainable_state.update(l._get_trainable_state())
return trainable_state
def _set_trainable_state(self, trainable_state):
"""Set `trainable` state for each sublayer."""
if self in trainable_state:
self.trainable = trainable_state[self]
layers = self._flatten_layers(include_self=False, recursive=False)
for l in layers:
if l in trainable_state:
l._set_trainable_state(trainable_state)
@property
def _obj_reference_counts(self):
"""A dict counting the number of attributes referencing an object."""
self._maybe_create_attribute(
"_obj_reference_counts_dict",
object_identity.ObjectIdentityDictionary(),
)
return self._obj_reference_counts_dict
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _maybe_create_attribute(self, name, default_value):
"""Create attribute (with the default value) if it hasn't been created.
This is useful for fields that is used for tracking purpose,
_trainable_weights, or _layers. Note that user could create a layer
subclass and assign an internal field before invoking the
Layer.__init__(), the __setattr__() need to create the tracking fields
and __init__() need to not override them.
Args:
name: String, the name of the attribute.
default_value: Object, the default value of the attribute.
"""
if not hasattr(self, name):
self.__setattr__(name, default_value)
def __delattr__(self, name):
# For any super.__delattr__() call, we will directly use the
# implementation in Trackable and skip the behavior in AutoTrackable.
# The Layer was originally use Trackable as base class, the change of
# using Module as base class forced us to have AutoTrackable in the
# class hierarchy.
#
# TODO(b/180760306) Keeping the status quo of skipping _delattr__ and
# __setattr__ in AutoTrackable may be unsustainable.
existing_value = getattr(self, name, None)
# If this value is replacing an existing object assigned to an
# attribute, we should clean it out to avoid leaking memory. First we
# check if there are other attributes referencing it.
reference_counts = self._obj_reference_counts
if existing_value not in reference_counts:
super(tf.__internal__.tracking.AutoTrackable, self).__delattr__(
name
)
return
reference_count = reference_counts[existing_value]
if reference_count > 1:
# There are other remaining references. We can't remove this object
# from _layers etc.
reference_counts[existing_value] = reference_count - 1
super(tf.__internal__.tracking.AutoTrackable, self).__delattr__(
name
)
return
else:
# This is the last remaining reference.
del reference_counts[existing_value]
super(tf.__internal__.tracking.AutoTrackable, self).__delattr__(name)
if isinstance(existing_value, Layer) or base_layer_utils.has_weights(
existing_value
):
super(tf.__internal__.tracking.AutoTrackable, self).__setattr__(
"_self_tracked_trackables",
[
l
for l in self._self_tracked_trackables
if l is not existing_value
],
)
if isinstance(existing_value, tf.Variable):
super(tf.__internal__.tracking.AutoTrackable, self).__setattr__(
"_trainable_weights",
[w for w in self._trainable_weights if w is not existing_value],
)
super(tf.__internal__.tracking.AutoTrackable, self).__setattr__(
"_non_trainable_weights",
[
w
for w in self._non_trainable_weights
if w is not existing_value
],
)
def __setattr__(self, name, value):
if (
name == "_self_setattr_tracking"
or not getattr(self, "_self_setattr_tracking", True)
# Exclude @property.setters from tracking
or hasattr(self.__class__, name)
):
try:
super(tf.__internal__.tracking.AutoTrackable, self).__setattr__(
name, value
)
except AttributeError:
raise AttributeError(
(
'Can\'t set the attribute "{}", likely because it '
"conflicts with an existing read-only @property of the "
"object. Please choose a different name."
).format(name)
)
return
# Keep track of trackable objects, for the needs of
# `Network.save_weights`.
value = tf.__internal__.tracking.sticky_attribute_assignment(
trackable=self, value=value, name=name
)
reference_counts = self._obj_reference_counts
reference_counts[value] = reference_counts.get(value, 0) + 1
# Clean out the old attribute, which clears _layers and
# _trainable_weights if necessary.
try:
self.__delattr__(name)
except AttributeError:
pass
# Keep track of metric instance created in subclassed layer.
from tf_keras import metrics as metrics_module
for val in tf.nest.flatten(value):
if isinstance(val, metrics_module.Metric) and hasattr(
self, "_metrics"
):
self._metrics.append(val)
# TODO(scottzhu): Need to track Module object as well for weight
# tracking. Be careful about metric if it becomes a Module in future.
# Append value to self._layers if relevant
if getattr(self, "_auto_track_sub_layers", True) and (
isinstance(value, Layer) or base_layer_utils.has_weights(value)
):
self._maybe_create_attribute("_self_tracked_trackables", [])
# We need to check object identity to avoid de-duplicating empty
# container types which compare equal.
if not any(
(layer is value for layer in self._self_tracked_trackables)
):
self._self_tracked_trackables.append(value)
if hasattr(value, "_use_resource_variables"):
# Legacy layers (V1 tf.layers) must always use
# resource variables.
value._use_resource_variables = True
# Append value to list of trainable / non-trainable weights if relevant
# TODO(b/125122625): This won't pick up on any variables added to a
# list/dict after creation.
for val in tf.nest.flatten(value):
if not isinstance(val, tf.Variable):
continue
# Users may add extra weights/variables simply by assigning them to
# attributes (invalid for graph networks)
self._maybe_create_attribute("_trainable_weights", [])
self._maybe_create_attribute("_non_trainable_weights", [])
if val.trainable:
if any(val is w for w in self._trainable_weights):
continue
self._trainable_weights.append(val)
else:
if any(val is w for w in self._non_trainable_weights):
continue
self._non_trainable_weights.append(val)
backend.track_variable(val)
# TODO(b/180760306) Skip the auto trackable from tf.Module to keep
# status quo. See the comment at __delattr__.
super(tf.__internal__.tracking.AutoTrackable, self).__setattr__(
name, value
)
# This is a hack so that the is_layer (within
# training/trackable/layer_utils.py) check doesn't get the weights attr.
# TODO(b/110718070): Remove when fixed.
def _is_layer(self):
return True
@property
@layer_utils.cached_per_instance
def _should_compute_mask(self):
return (
"mask" in self._call_spec.arg_names
or getattr(self, "compute_mask", None) is not None
)
def _dedup_weights(self, weights):
"""Dedupe weights while maintaining order as much as possible."""
output, seen_ids = [], set()
for w in weights:
if id(w) not in seen_ids:
output.append(w)
# Track the Variable's identity to avoid __eq__ issues.
seen_ids.add(id(w))
return output
# SavedModel properties. Please see keras/saving/saved_model for details.
@property
def _trackable_saved_model_saver(self):
return layer_serialization.LayerSavedModelSaver(self)
@property
def _object_identifier(self):
return self._trackable_saved_model_saver.object_identifier
@property
def _tracking_metadata(self):
return self._trackable_saved_model_saver.tracking_metadata
def _trackable_children(self, save_type="checkpoint", **kwargs):
if save_type == "savedmodel":
cache = kwargs["cache"]
# TODO(b/213628533): This must be called before super() to ensure
# that any input shape changes are applied before getting the config
# of the model.
children = self._trackable_saved_model_saver.trackable_children(
cache
)
else:
children = {}
children.update(super()._trackable_children(save_type, **kwargs))
return children
def __getstate__(self):
# Override to support `copy.deepcopy` and pickling.
# Thread-local objects cannot be copied in Python 3, so pop these.
# Thread-local objects are used to cache losses in MirroredStrategy, and
# so shouldn't be copied.
state = self.__dict__.copy()
state.pop("_thread_local", None)
return state
def __setstate__(self, state):
state["_thread_local"] = threading.local()
# Bypass Trackable logic as `__dict__` already contains this info.
object.__setattr__(self, "__dict__", state)
| tf-keras/tf_keras/engine/base_layer_v1.py/0 | {
"file_path": "tf-keras/tf_keras/engine/base_layer_v1.py",
"repo_id": "tf-keras",
"token_count": 46089
} | 171 |
# Copyright 2020 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 InputLayer construction."""
import tensorflow.compat.v2 as tf
from tf_keras import Sequential
from tf_keras import backend
from tf_keras import models
from tf_keras.engine import functional
from tf_keras.engine import input_layer as input_layer_lib
from tf_keras.layers import Dense
from tf_keras.layers import core
from tf_keras.saving.legacy import model_config
from tf_keras.saving.serialization_lib import SafeModeScope
from tf_keras.testing_infra import test_combinations
from tf_keras.testing_infra import test_utils
# isort: off
from tensorflow.python.framework import type_spec
from tensorflow.python.framework import type_spec_registry
class TwoTensors(tf.__internal__.CompositeTensor):
"""A simple value type to test TypeSpec.
Contains two tensors (x, y) and a string (color). The color value is a
stand-in for any extra type metadata we might need to store.
This value type contains no single dtype.
"""
def __init__(self, x, y, color="red", assign_variant_dtype=False):
assert isinstance(color, str)
self.x = tf.convert_to_tensor(x)
self.y = tf.convert_to_tensor(y)
self.color = color
self.shape = tf.TensorShape(None)
self._shape = tf.TensorShape(None)
if assign_variant_dtype:
self.dtype = tf.variant
self._assign_variant_dtype = assign_variant_dtype
def _type_spec(self):
return TwoTensorsSpecNoOneDtype(
self.x.shape,
self.x.dtype,
self.y.shape,
self.y.dtype,
color=self.color,
assign_variant_dtype=self._assign_variant_dtype,
)
def as_shape(shape):
"""Converts the given object to a TensorShape."""
if isinstance(shape, tf.TensorShape):
return shape
else:
return tf.TensorShape(shape)
@type_spec_registry.register("tf.TwoTensorsSpec")
class TwoTensorsSpecNoOneDtype(tf.TypeSpec):
"""A TypeSpec for the TwoTensors value type."""
def __init__(
self,
x_shape,
x_dtype,
y_shape,
y_dtype,
color="red",
assign_variant_dtype=False,
):
self.x_shape = as_shape(x_shape)
self.x_dtype = tf.as_dtype(x_dtype)
self.y_shape = as_shape(y_shape)
self.y_dtype = tf.as_dtype(y_dtype)
self.color = color
self.shape = tf.TensorShape(None)
self._shape = tf.TensorShape(None)
if assign_variant_dtype:
self.dtype = tf.variant
self._assign_variant_dtype = assign_variant_dtype
value_type = property(lambda self: TwoTensors)
@property
def _component_specs(self):
return (
tf.TensorSpec(self.x_shape, self.x_dtype),
tf.TensorSpec(self.y_shape, self.y_dtype),
)
def _to_components(self, value):
return (value.x, value.y)
def _from_components(self, components):
x, y = components
return TwoTensors(x, y, self.color)
def _serialize(self):
return (
self.x_shape,
self.x_dtype,
self.y_shape,
self.y_dtype,
self.color,
)
@classmethod
def from_value(cls, value):
return cls(
value.x.shape,
value.x.dtype,
value.y.shape,
value.y.dtype,
value.color,
)
type_spec.register_type_spec_from_value_converter(
TwoTensors, TwoTensorsSpecNoOneDtype.from_value
)
class InputLayerTest(test_combinations.TestCase):
@test_combinations.generate(
test_combinations.combine(mode=["graph", "eager"])
)
def testBasicOutputShapeNoBatchSize(self):
# Create a TF-Keras Input
x = input_layer_lib.Input(shape=(32,), name="input_a")
self.assertAllEqual(x.shape.as_list(), [None, 32])
# Verify you can construct and use a model w/ this input
model = functional.Functional(x, x * 2.0)
self.assertAllEqual(model(tf.ones((3, 32))), tf.ones((3, 32)) * 2.0)
@test_combinations.generate(
test_combinations.combine(mode=["graph", "eager"])
)
def testBasicOutputShapeWithBatchSize(self):
# Create a TF-Keras Input
x = input_layer_lib.Input(batch_size=6, shape=(32,), name="input_b")
self.assertAllEqual(x.shape.as_list(), [6, 32])
# Verify you can construct and use a model w/ this input
model = functional.Functional(x, x * 2.0)
self.assertAllEqual(model(tf.ones(x.shape)), tf.ones(x.shape) * 2.0)
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
def testBasicOutputShapeNoBatchSizeInTFFunction(self):
model = None
@tf.function
def run_model(inp):
nonlocal model
if not model:
# Create a TF-Keras Input
x = input_layer_lib.Input(shape=(8,), name="input_a")
self.assertAllEqual(x.shape.as_list(), [None, 8])
# Verify you can construct and use a model w/ this input
model = functional.Functional(x, x * 2.0)
return model(inp)
self.assertAllEqual(run_model(tf.ones((10, 8))), tf.ones((10, 8)) * 2.0)
@test_combinations.run_all_keras_modes
def testBasicOutputShapeWithBatchSizeAndNoneDimensionsPlaceholder(self):
x = input_layer_lib.Input((2, 3), batch_size=4, dtype=tf.float32)
model = functional.Functional(x, x * 2.0)
output = model(backend.placeholder(shape=[None, None, 3]))
# batch size and dimension defined in Input should not be applied
self.assertAllEqual(output.shape.as_list(), [None, None, 3])
@test_combinations.generate(
test_combinations.combine(mode=["graph", "eager"])
)
def testInputTensorArg(self):
# Create a TF-Keras Input
x = input_layer_lib.Input(tensor=tf.zeros((7, 32)))
self.assertAllEqual(x.shape.as_list(), [7, 32])
# Verify you can construct and use a model w/ this input
model = functional.Functional(x, x * 2.0)
self.assertAllEqual(model(tf.ones(x.shape)), tf.ones(x.shape) * 2.0)
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
def testInputTensorArgInTFFunction(self):
# We use a mutable model container instead of a model python variable,
# because python 2.7 does not have `nonlocal`
model_container = {}
@tf.function
def run_model(inp):
if not model_container:
# Create a TF-Keras Input
x = input_layer_lib.Input(tensor=tf.zeros((10, 16)))
self.assertAllEqual(x.shape.as_list(), [10, 16])
# Verify you can construct and use a model w/ this input
model_container["model"] = functional.Functional(x, x * 3.0)
return model_container["model"](inp)
self.assertAllEqual(
run_model(tf.ones((10, 16))), tf.ones((10, 16)) * 3.0
)
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
def testCompositeInputTensorArg(self):
# Create a TF-Keras Input
rt = tf.RaggedTensor.from_row_splits(
values=[3, 1, 4, 1, 5, 9, 2, 6], row_splits=[0, 4, 4, 7, 8, 8]
)
x = input_layer_lib.Input(tensor=rt)
# Verify you can construct and use a model w/ this input
model = functional.Functional(x, x * 2)
# And that the model works
rt = tf.RaggedTensor.from_row_splits(
values=[3, 21, 4, 1, 53, 9, 2, 6], row_splits=[0, 4, 4, 7, 8, 8]
)
self.assertAllEqual(model(rt), rt * 2)
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
def testCompositeInputTensorArgInTFFunction(self):
# We use a mutable model container instead of a model python variable,
# because python 2.7 does not have `nonlocal`
model_container = {}
@tf.function
def run_model(inp):
if not model_container:
# Create a TF-Keras Input
rt = tf.RaggedTensor.from_row_splits(
values=[3, 1, 4, 1, 5, 9, 2, 6],
row_splits=[0, 4, 4, 7, 8, 8],
)
x = input_layer_lib.Input(tensor=rt)
# Verify you can construct and use a model w/ this input
model_container["model"] = functional.Functional(x, x * 3)
return model_container["model"](inp)
# And verify the model works
rt = tf.RaggedTensor.from_row_splits(
values=[3, 21, 4, 1, 53, 9, 2, 6], row_splits=[0, 4, 4, 7, 8, 8]
)
self.assertAllEqual(run_model(rt), rt * 3)
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
def testNoMixingArgsWithTypeSpecArg(self):
with self.assertRaisesRegexp(
ValueError, "all other args except `name` must be None"
):
input_layer_lib.Input(
shape=(4, 7), type_spec=tf.TensorSpec((2, 7, 32), tf.float32)
)
with self.assertRaisesRegexp(
ValueError, "all other args except `name` must be None"
):
input_layer_lib.Input(
batch_size=4, type_spec=tf.TensorSpec((7, 32), tf.float32)
)
with self.assertRaisesRegexp(
ValueError, "all other args except `name` must be None"
):
input_layer_lib.Input(
dtype=tf.int64, type_spec=tf.TensorSpec((7, 32), tf.float32)
)
with self.assertRaisesRegexp(
ValueError, "all other args except `name` must be None"
):
input_layer_lib.Input(
sparse=True, type_spec=tf.TensorSpec((7, 32), tf.float32)
)
with self.assertRaisesRegexp(
ValueError, "all other args except `name` must be None"
):
input_layer_lib.Input(
ragged=True, type_spec=tf.TensorSpec((7, 32), tf.float32)
)
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
def testTypeSpecArg(self):
# Create a TF-Keras Input
x = input_layer_lib.Input(type_spec=tf.TensorSpec((7, 32), tf.float32))
self.assertAllEqual(x.shape.as_list(), [7, 32])
# Verify you can construct and use a model w/ this input
model = functional.Functional(x, x * 2.0)
self.assertAllEqual(model(tf.ones(x.shape)), tf.ones(x.shape) * 2.0)
# Test serialization / deserialization
model = functional.Functional.from_config(model.get_config())
self.assertAllEqual(model(tf.ones(x.shape)), tf.ones(x.shape) * 2.0)
model = model_config.model_from_json(model.to_json())
self.assertAllEqual(model(tf.ones(x.shape)), tf.ones(x.shape) * 2.0)
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
def testTypeSpecArgInTFFunction(self):
# We use a mutable model container instead of a model python variable,
# because python 2.7 does not have `nonlocal`
model_container = {}
@tf.function
def run_model(inp):
if not model_container:
# Create a TF-Keras Input
x = input_layer_lib.Input(
type_spec=tf.TensorSpec((10, 16), tf.float32)
)
self.assertAllEqual(x.shape.as_list(), [10, 16])
# Verify you can construct and use a model w/ this input
model_container["model"] = functional.Functional(x, x * 3.0)
return model_container["model"](inp)
self.assertAllEqual(
run_model(tf.ones((10, 16))), tf.ones((10, 16)) * 3.0
)
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
def testCompositeTypeSpecArg(self):
# Create a TF-Keras Input
rt = tf.RaggedTensor.from_row_splits(
values=[3, 1, 4, 1, 5, 9, 2, 6], row_splits=[0, 4, 4, 7, 8, 8]
)
x = input_layer_lib.Input(type_spec=rt._type_spec)
# Verify you can construct and use a model w/ this input
model = functional.Functional(x, x * 2)
# And that the model works
rt = tf.RaggedTensor.from_row_splits(
values=[3, 21, 4, 1, 53, 9, 2, 6], row_splits=[0, 4, 4, 7, 8, 8]
)
self.assertAllEqual(model(rt), rt * 2)
# Test serialization / deserialization
model = functional.Functional.from_config(model.get_config())
self.assertAllEqual(model(rt), rt * 2)
model = model_config.model_from_json(model.to_json())
self.assertAllEqual(model(rt), rt * 2)
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
def testCompositeTypeSpecArgInTFFunction(self):
# We use a mutable model container instead of a model pysthon variable,
# because python 2.7 does not have `nonlocal`
model_container = {}
@tf.function
def run_model(inp):
if not model_container:
# Create a TF-Keras Input
rt = tf.RaggedTensor.from_row_splits(
values=[3, 1, 4, 1, 5, 9, 2, 6],
row_splits=[0, 4, 4, 7, 8, 8],
)
x = input_layer_lib.Input(type_spec=rt._type_spec)
# Verify you can construct and use a model w/ this input
model_container["model"] = functional.Functional(x, x * 3)
return model_container["model"](inp)
# And verify the model works
rt = tf.RaggedTensor.from_row_splits(
values=[3, 21, 4, 1, 53, 9, 2, 6], row_splits=[0, 4, 4, 7, 8, 8]
)
self.assertAllEqual(run_model(rt), rt * 3)
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
def testCompositeTypeSpecArgWithoutDtype(self):
for assign_variant_dtype in [False, True]:
# Create a TF-Keras Input
spec = TwoTensorsSpecNoOneDtype(
(1, 2, 3),
tf.float32,
(1, 2, 3),
tf.int64,
assign_variant_dtype=assign_variant_dtype,
)
x = input_layer_lib.Input(type_spec=spec)
def lambda_fn(tensors):
return tf.cast(tensors.x, tf.float64) + tf.cast(
tensors.y, tf.float64
)
# Verify you can construct and use a model w/ this input
model = functional.Functional(x, core.Lambda(lambda_fn)(x))
# And that the model works
two_tensors = TwoTensors(tf.ones((1, 2, 3)) * 2.0, tf.ones(1, 2, 3))
self.assertAllEqual(model(two_tensors), lambda_fn(two_tensors))
# Test serialization / deserialization
with SafeModeScope(safe_mode=False):
model = functional.Functional.from_config(model.get_config())
self.assertAllEqual(model(two_tensors), lambda_fn(two_tensors))
model = model_config.model_from_json(model.to_json())
self.assertAllEqual(model(two_tensors), lambda_fn(two_tensors))
def test_serialize_with_unknown_rank(self):
inp = backend.placeholder(shape=None, dtype=tf.string)
x = input_layer_lib.InputLayer(input_tensor=inp, dtype=tf.string)
loaded = input_layer_lib.InputLayer.from_config(x.get_config())
self.assertIsNone(loaded._batch_input_shape)
@test_utils.run_v2_only
def test_typespec_naming_propagation(self):
type_spec = tf.TensorSpec(name="test", shape=(None, None, 2))
input1 = input_layer_lib.Input(type_spec=type_spec)
self.assertEqual(input1.name, "test")
@test_utils.run_v2_only
def test_save_input_naming(self):
x = input_layer_lib.Input(shape=(10,), name="features")
y = Dense(1)(x)
model = functional.Functional(x, y)
self.assertEqual(model.layers[0].name, "features")
save_path = self.get_temp_dir() + "/basic_model.keras"
model.save(save_path)
reloaded_model = models.load_model(save_path)
self.assertEqual(reloaded_model.layers[0].name, "features")
@test_utils.run_v2_only
def test_export_input_naming(self):
model = Sequential(
layers=[
input_layer_lib.Input(shape=(8,), name="features"),
Dense(1),
]
)
x = tf.random.normal((8, 8))
model(x)
export_path = self.get_temp_dir() + "test_model"
model.export(export_path)
reloaded_artifact = tf.saved_model.load(export_path)
self.assertEqual(
reloaded_artifact.signatures._signatures["serve"]._arg_keywords[-1],
"features",
)
if __name__ == "__main__":
tf.test.main()
| tf-keras/tf_keras/engine/input_layer_test.py/0 | {
"file_path": "tf-keras/tf_keras/engine/input_layer_test.py",
"repo_id": "tf-keras",
"token_count": 8202
} | 172 |
# Copyright 2018 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.
# ==============================================================================
"""Part of the TF-Keras training engine related to distributed training."""
import numpy as np
import tensorflow.compat.v2 as tf
from tf_keras import backend
from tf_keras import callbacks as cbks
from tf_keras.distribute import distribute_coordinator_utils as dc
from tf_keras.distribute import distributed_training_utils_v1 as dist_utils
from tf_keras.engine import partial_batch_padding_handler as padding_util
from tf_keras.engine import training_arrays_v1
from tf_keras.engine import training_utils_v1
from tf_keras.utils.generic_utils import Progbar
from tf_keras.utils.mode_keys import ModeKeys
# isort: off
from tensorflow.python.distribute import input_lib
from tensorflow.python.platform import tf_logging as logging
def _per_replica_execution_function(model, mode):
exec_func = model._make_execution_function(mode)
return (
exec_func.inputs,
exec_func.outputs,
exec_func.updates_op,
exec_func.session_kwargs,
)
def _build_model(strategy, model, mode, inputs, targets=None):
if model._compile_distribution:
dist_utils.clone_model_on_replicas(
model, strategy, mode, inputs=inputs, targets=targets
)
else:
dist_utils._build_distributed_network(
model, strategy, mode, inputs, targets
)
def _make_train_step_fn(model, mode, strategy, output_labels):
"""Create step fn.
Args:
model: a TF-Keras Model instance.
mode: One of ModeKeys.TRAIN/ModeKeys.TEST/ModeKeys.PREDICT.
strategy: a `tf.distribute.Strategy` instance.
output_labels: the output labels for the step function.
Returns:
A step function to run by `tf.distribute.Strategy`.
"""
def _step_fn(ctx, inputs):
"""A step fn that returns update ops."""
if isinstance(inputs, (tuple, list)) and len(inputs) == 2:
inputs, targets = inputs
else:
targets = None
# When input feature is a dictionary of tensors, dictionary is
# flattended to an array and passed as a model input. This results in
# input mismatch when model input layer names are not sorted in
# alphabetical order as `nest.flatten()`sorts dictionary elements by
# keys. As so, transform input tensors into an array and order it along
# `model._feed_input_names`.
if isinstance(inputs, dict):
inputs = [
inputs[input_name] for input_name in model._feed_input_names
]
_build_model(strategy, model, mode, inputs, targets)
(
grouped_inputs,
grouped_outputs,
grouped_updates,
grouped_session_args,
) = strategy.extended.call_for_each_replica(
_per_replica_execution_function,
args=(dist_utils.get_distributed_model(model, mode), mode),
)
(
all_inputs,
all_outputs,
all_updates,
all_session_args,
) = dist_utils.unwrap_values(
strategy,
grouped_inputs,
grouped_outputs,
grouped_updates,
grouped_session_args,
)
combined_fn = backend.function(
all_inputs,
all_outputs,
updates=all_updates,
name="distributed_" + str(mode) + "_function",
**all_session_args
)
for label, output in zip(output_labels, combined_fn.outputs):
if label == "loss":
reduce_op = tf.distribute.ReduceOp.SUM
else:
# We reduce all other metrics using mean for now. This is
# temporary workaround until new metrics are in place.
reduce_op = tf.distribute.ReduceOp.MEAN
ctx.set_last_step_output(label, output, reduce_op)
# TODO(priyag, sourabhbajaj): Ignoring these things from the
# combined_fn: feed_dict, session kwargs, run options, run_metadata for
# now. These should be handled appropriately
return combined_fn.updates_op
return _step_fn
def experimental_tpu_fit_loop(
model,
dataset,
epochs=100,
verbose=1,
callbacks=None,
initial_epoch=0,
steps_per_epoch=None,
val_dataset=None,
validation_steps=None,
validation_freq=1,
):
"""Fit loop for training with TPU tf.distribute.Strategy.
Args:
model: TF-Keras Model instance.
dataset: Dataset that returns inputs and targets
epochs: Number of times to iterate over the data
verbose: Integer, Verbosity mode, 0, 1 or 2
callbacks: List of callbacks to be called during training
initial_epoch: Epoch at which to start training
(useful for resuming a previous training run)
steps_per_epoch: Total number of steps (batches of samples)
before declaring one epoch finished and starting the
next epoch. Ignored with the default value of `None`.
val_dataset: Dataset for validation data.
validation_steps: Number of steps to run validation for
(only if doing validation from data tensors).
Ignored with the default value of `None`.
validation_freq: Only relevant if validation data is provided. Integer
or `collections.abc.Container` instance (e.g. list, tuple, etc.). If
an integer, specifies how many training epochs to run before a new
validation run is performed, e.g. `validation_freq=2` runs
validation every 2 epochs. If a Container, specifies the epochs on
which to run validation, e.g. `validation_freq=[1, 2, 10]` runs
validation at the end of the 1st, 2nd, and 10th epochs.
Returns:
Returns `None`.
Raises:
ValueError: in case of invalid arguments.
"""
mode = ModeKeys.TRAIN
current_strategy = model._distribution_strategy
iteration_value = min(
steps_per_epoch, current_strategy.extended.steps_per_run
)
steps_per_run = backend.variable(
value=iteration_value, dtype="int32", name="steps_per_run"
)
# TODO(fchollet): add support for `steps_per_epoch=None` in TPU loops.
iterator = dist_utils.get_iterator(dataset, current_strategy)
scope = dist_utils.distributed_scope(
strategy=current_strategy, learning_phase=1
)
scope.__enter__()
out_labels = model.metrics_names or []
step_fn = _make_train_step_fn(
model, ModeKeys.TRAIN, current_strategy, out_labels
)
# Add initial dummy values for loss and other metric tensors.
initial_loop_values = {}
initial_loop_values["loss"] = tf.constant(1e7)
for m in model._get_training_eval_metrics():
tensor = m.result()
initial_loop_values[m.name] = tf.zeros(tensor.shape, tensor.dtype)
ctx = current_strategy.extended.experimental_run_steps_on_iterator(
step_fn,
iterator,
iterations=steps_per_run,
initial_loop_values=initial_loop_values,
)
train_op = ctx.run_op
output_tensors = ctx.last_step_outputs
do_validation = bool(validation_steps)
if model._compile_distribution:
dist_utils._copy_weights_to_distributed_model(model, mode)
callbacks = cbks.configure_callbacks(
callbacks,
model,
do_validation=do_validation,
epochs=epochs,
steps_per_epoch=steps_per_epoch,
verbose=verbose,
count_mode="steps",
mode=mode,
)
# Calculate the steps each time on the device.
steps_to_run = [current_strategy.extended.steps_per_run] * (
steps_per_epoch // current_strategy.extended.steps_per_run
)
if steps_per_epoch % current_strategy.extended.steps_per_run:
steps_to_run.append(
steps_per_epoch % current_strategy.extended.steps_per_run
)
target_steps = len(steps_to_run)
callbacks._call_begin_hook(mode)
initial_epoch = model._maybe_load_initial_epoch_from_ckpt(
initial_epoch, mode
)
for epoch in range(initial_epoch, epochs):
dist_utils._reset_metrics(model)
callbacks.on_epoch_begin(epoch)
epoch_logs = {}
step_index = 0
prev_step_count = None
current_step = 0
while current_step < target_steps:
step_count = steps_to_run[current_step]
batch_logs = {
"batch": step_index,
"size": 1,
"num_steps": step_count,
}
callbacks._call_batch_hook(mode, "begin", step_index, batch_logs)
if prev_step_count is None or step_count != prev_step_count:
backend.get_session().run(steps_per_run.assign(step_count))
prev_step_count = step_count
try:
_, outputs = backend.batch_get_value([train_op, output_tensors])
except tf.errors.OutOfRangeError:
logging.warning(
"Your dataset iterator ran out of data; "
"interrupting training. Make sure that your dataset "
"can generate at least `steps_per_epoch * epochs` "
"batches (in this case, %d batches)."
% steps_per_epoch
* epochs
)
break
batch_logs.update(outputs)
callbacks._call_batch_hook(mode, "end", step_index, batch_logs)
step_index = step_index + step_count
current_step += 1
if callbacks.model.stop_training:
break
if do_validation and training_utils_v1.should_run_validation(
validation_freq, epoch
):
logging.info("Running validation at fit epoch: %s", epoch)
if model._compile_distribution:
# Since we create a new clone from the original model we need to
# copy the weights back to the original model before we can run
# validation.
dist_utils._copy_weights_to_original_model(
model, ModeKeys.TRAIN
)
val_outs = experimental_tpu_test_loop(
model,
val_dataset,
steps=validation_steps,
verbose=verbose,
callbacks=callbacks,
)
if not isinstance(val_outs, list):
val_outs = [val_outs]
# Same labels assumed.
for label, val_out in zip(out_labels, val_outs):
epoch_logs["val_" + label] = val_out
callbacks.on_epoch_end(epoch, epoch_logs)
if callbacks.model.stop_training:
break
model._successful_loop_finish = True
callbacks._call_end_hook(mode)
if model._compile_distribution:
# Copy the weights back from the replicated model to the original model.
dist_utils._copy_weights_to_original_model(model, ModeKeys.TRAIN)
scope.__exit__(None, None, None)
return model.history
def experimental_tpu_test_loop(
model, dataset, verbose=0, steps=None, callbacks=None
):
"""Test loop for evaluating with TPU tf.distribute.Strategy.
Args:
model: TF-Keras Model instance.
dataset: Dataset for input data.
verbose: Integer, Verbosity mode 0 or 1.
steps: Total number of steps (batches of samples)
before declaring predictions finished.
Ignored with the default value of `None`.
callbacks: List of callbacks to be called during training
Returns:
Scalar loss (if the model has a single output and no metrics)
or list of scalars (if the model has multiple outputs
and/or metrics). The attribute `model.metrics_names` will give you
the display labels for the outputs.
"""
mode = ModeKeys.TEST
current_strategy = model._distribution_strategy
iterator = dist_utils.get_iterator(dataset, current_strategy)
scope = dist_utils.distributed_scope(
strategy=current_strategy, learning_phase=0
)
scope.__enter__()
out_labels = model.metrics_names
def _test_step_fn(inputs):
"""A fn that returns output of single test step."""
if isinstance(inputs, (tuple, list)) and len(inputs) == 2:
inputs, targets = inputs
else:
targets = None
(
tf.distribute.get_replica_context().merge_call(
_build_model, args=(model, mode, inputs, targets)
)
)
(_, outputs, updates, _) = _per_replica_execution_function(
dist_utils.get_distributed_model(model, mode), mode
)
with tf.control_dependencies([updates]):
return [tf.identity(out) for out in outputs]
test_input_data = iterator.get_next()
per_replica_outputs = current_strategy.run(
_test_step_fn, args=(test_input_data,)
)
output_tensors = {}
for label, output in zip(out_labels, per_replica_outputs):
if label == "loss":
reduce_op = tf.distribute.ReduceOp.SUM
else:
# We reduce all other metrics using mean for now. This is temporary
# workaround until new metrics are in place.
reduce_op = tf.distribute.ReduceOp.MEAN
output_tensors[label] = current_strategy.reduce(
reduce_op, output, axis=None
)
test_op = tf.group(list(output_tensors.values()))
if verbose >= 1:
progbar = Progbar(target=steps)
if model._compile_distribution:
dist_utils._copy_weights_to_distributed_model(model, mode)
dist_utils._reset_metrics(model)
callbacks = cbks.configure_callbacks(
callbacks,
model,
do_validation=False,
epochs=1,
steps_per_epoch=steps,
verbose=verbose,
count_mode="steps",
mode=ModeKeys.TEST,
)
callbacks._call_begin_hook(mode)
outs = [0.0] * len(model.metrics_names)
if steps is not None:
target_steps = steps
else:
raise ValueError(
"Number of steps could not be inferred from the data, "
"please pass the steps argument."
)
current_step = 0
while current_step < target_steps:
batch_logs = {"batch": current_step, "size": 1}
callbacks._call_batch_hook(mode, "begin", current_step, batch_logs)
try:
_, batch_outs = backend.batch_get_value([test_op, output_tensors])
except tf.errors.OutOfRangeError:
warning_msg = (
"Make sure that your dataset can generate at least "
"`steps` batches (in this case, {} batches).".format(steps)
)
logging.warning(
"Your dataset iterator ran out of data; "
"interrupting evaluation. " + warning_msg
)
target_steps = current_step
break
for i, label in enumerate(model.metrics_names):
if i == 0:
# Loss is stateless metrics.
outs[i] += batch_outs[label]
else:
# For all stateful metrics, the aggregation is handled by
# mirrored vars.
outs[i] = batch_outs[label]
batch_logs = callbacks.make_logs(model, batch_logs, outs, mode)
callbacks._call_batch_hook(mode, "end", current_step, batch_logs)
if verbose == 1:
progbar.update(current_step + 1)
current_step += 1
if verbose >= 1:
# Progress bar finishes at the end.
progbar.update(target_steps)
callbacks._call_end_hook(mode)
scope.__exit__(None, None, None)
if len(outs) > 0:
outs[0] /= target_steps
if len(outs) == 1:
return outs[0]
return outs
def experimental_tpu_predict_loop(
model, dataset, verbose=0, steps=None, callbacks=None
):
"""Predict loop for predicting with TPU tf.distribute.Strategy.
Args:
model: TF-Keras Model instance.
dataset: Dataset for input data.
verbose: Integer, Verbosity mode 0 or 1.
steps: Total number of steps (batches of samples)
before declaring `_predict_loop` finished.
Ignored with the default value of `None`.
callbacks: List of callbacks to be called during training
Returns:
Array of predictions (if the model has a single output)
or list of arrays of predictions
(if the model has multiple outputs).
"""
mode = ModeKeys.PREDICT
dataset_fully_shaped = dist_utils.is_dataset_shape_fully_defined(dataset)
padding_handler = None
if not dataset_fully_shaped:
# TODO(hongjunchoi): Investigate whether operations from
# PartialBatchPaddingHandler are unnecessarily pruned out
# during graph optimization.
padding_handler = padding_util.PartialBatchPaddingHandler(
model._feed_output_shapes
)
batch_size, _, prefetch_buffer = input_lib._get_dataset_attributes(
dataset
)
padding_handler.padded_batch_size = batch_size
padding_handler.padding_mask = dataset.reduce(
padding_handler.padding_mask, padding_handler.update_mask
)
dataset = dataset.map(padding_handler.pad_batch)
dataset = dataset.unbatch()
# Upon this point, it is guaranteed that the dataset does not
# have partial batches. Thus, we set `drop_remainder=True` to
# get static shape information about the elements in the dataset.
dataset = dataset.batch(batch_size, drop_remainder=True)
if prefetch_buffer is not None:
dataset = dataset.prefetch(prefetch_buffer)
current_strategy = model._distribution_strategy
iterator = dist_utils.get_iterator(dataset, current_strategy)
scope = dist_utils.distributed_scope(
strategy=current_strategy, learning_phase=0
)
scope.__enter__()
def _predict_step_fn(inputs):
"""A fn that returns output of single prediction step."""
(
tf.distribute.get_replica_context().merge_call(
_build_model, args=(model, mode, inputs)
)
)
(_, outputs, updates, _) = _per_replica_execution_function(
dist_utils.get_distributed_model(model, mode), mode
)
with tf.control_dependencies([updates]):
return [tf.identity(out) for out in outputs]
# TODO(hongjunchoi): When numpy array is passed as an input to `predict()`
# use numpy arrays directly to avoid cumulating unnecessary input pipeline
# ops.
predict_input_data = iterator.get_next()
per_replica_outputs = current_strategy.run(
_predict_step_fn, args=(predict_input_data,)
)
output_tensors = dist_utils.flatten_per_replica_values(
current_strategy, per_replica_outputs
)
if verbose >= 1:
progbar = Progbar(target=steps)
if model._compile_distribution:
dist_utils._copy_weights_to_distributed_model(model, mode)
dist_utils._reset_metrics(model)
callbacks = cbks.configure_callbacks(
callbacks,
model,
do_validation=False,
epochs=1,
steps_per_epoch=steps,
verbose=verbose,
count_mode="steps",
mode=mode,
)
callbacks._call_begin_hook(mode)
# Since we do not know how many samples we will see, we cannot pre-allocate
# the returned Numpy arrays. Instead, we store one array per batch seen
# and concatenate them upon returning.
num_model_outputs = len(model.output_names)
unconcatenated_outs = [[] for _ in range(num_model_outputs)]
if steps is not None:
target_steps = steps
else:
raise ValueError(
"Number of steps could not be inferred from the data, "
"please pass the steps argument."
)
current_step = 0
while current_step < target_steps:
batch_logs = {"batch": current_step, "size": 1}
callbacks._call_batch_hook(mode, "begin", current_step, batch_logs)
try:
predict_ops = tf.group(output_tensors)
_, batch_outs = backend.batch_get_value(
[predict_ops, output_tensors]
)
except tf.errors.OutOfRangeError:
warning_msg = (
"Make sure that your dataset can generate at least "
"`steps` batches (in this case, {} batches).".format(steps)
)
logging.warning(
"Your dataset iterator ran out of data; "
"interrupting evaluation. " + warning_msg
)
break
# TODO(priyag): maybe need to unwrap the outputs first for
# MirroredStrategy.
for i in range(num_model_outputs):
output_start_index = i * current_strategy.num_replicas_in_sync
output_end_index = (
output_start_index + current_strategy.num_replicas_in_sync
)
single_model_output = batch_outs[
output_start_index:output_end_index
]
unconcatenated_outs[i].extend(single_model_output)
batch_logs = callbacks.make_logs(model, batch_logs, batch_outs, mode)
callbacks._call_batch_hook(mode, "end", current_step, batch_logs)
if verbose == 1:
progbar.update(current_step + 1)
current_step += 1
if verbose >= 1:
# Progress bar finishes at the end.
progbar.update(current_step)
callbacks._call_end_hook(mode)
scope.__exit__(None, None, None)
if len(unconcatenated_outs) == 1:
prediction_result = np.concatenate(unconcatenated_outs[0], axis=0)
else:
prediction_result = [
np.concatenate(out, axis=0) for out in unconcatenated_outs
]
if padding_handler:
prediction_result = padding_handler.apply_mask(prediction_result)
return prediction_result
class DistributionSingleWorkerTrainingLoop(training_utils_v1.TrainingLoop):
"""Training loop for distribution strategy with single worker."""
def fit(
self,
model,
x=None,
y=None,
batch_size=None,
epochs=1,
verbose=1,
callbacks=None,
validation_split=0.0,
validation_data=None,
shuffle=True,
class_weight=None,
sample_weight=None,
initial_epoch=0,
steps_per_epoch=None,
validation_steps=None,
validation_freq=1,
**kwargs
):
"""Fit loop for Distribution Strategies."""
dist_utils.validate_callbacks(
input_callbacks=callbacks, optimizer=model.optimizer
)
dist_utils.validate_inputs(x, y)
batch_size, steps_per_epoch = dist_utils.process_batch_and_step_size(
model._distribution_strategy,
x,
batch_size,
steps_per_epoch,
ModeKeys.TRAIN,
validation_split=validation_split,
)
batch_size = model._validate_or_infer_batch_size(
batch_size, steps_per_epoch, x
)
dataset = model._distribution_standardize_user_data(
x,
y,
sample_weight=sample_weight,
class_weight=class_weight,
batch_size=batch_size,
validation_split=validation_split,
shuffle=shuffle,
epochs=epochs,
)
if not dist_utils.is_distributing_by_cloning(model):
with model._distribution_strategy.scope():
(dataset, _, _) = model._standardize_user_data(
dataset,
sample_weight=sample_weight,
class_weight=class_weight,
batch_size=batch_size,
validation_split=validation_split,
shuffle=shuffle,
)
val_dataset = None
if validation_data:
(
val_x,
val_y,
val_sample_weights,
) = training_utils_v1.unpack_validation_data(validation_data)
dist_utils.validate_inputs(val_x, val_y)
_, validation_steps = dist_utils.process_batch_and_step_size(
model._distribution_strategy,
val_x,
batch_size,
validation_steps,
ModeKeys.TEST,
)
val_dataset = model._distribution_standardize_user_data(
val_x,
val_y,
sample_weight=val_sample_weights,
class_weight=None,
batch_size=batch_size,
validation_split=validation_split,
shuffle=shuffle,
allow_partial_batch=True,
)
elif validation_split:
raise ValueError(
"validation_split argument is not supported with "
"distribution strategies."
)
if backend.is_tpu_strategy(model._distribution_strategy):
steps_per_epoch = training_utils_v1.infer_steps_for_dataset(
model,
dataset,
steps_per_epoch,
epochs,
steps_name="steps_per_epoch",
)
if steps_per_epoch is None:
raise ValueError(
"Number of steps could not be inferred from the data, "
"please pass the steps_per_epoch argument."
)
if not tf.executing_eagerly():
# Run TPU training in a custom loop in graph mode.
return experimental_tpu_fit_loop(
model,
dataset,
epochs=epochs,
verbose=verbose,
callbacks=callbacks,
val_dataset=val_dataset,
initial_epoch=initial_epoch,
steps_per_epoch=steps_per_epoch,
validation_steps=validation_steps,
validation_freq=validation_freq,
)
return training_arrays_v1.fit_loop(
model,
dataset,
batch_size=batch_size,
epochs=epochs,
verbose=verbose,
callbacks=callbacks,
val_inputs=val_dataset,
shuffle=shuffle,
initial_epoch=initial_epoch,
steps_per_epoch=steps_per_epoch,
validation_steps=validation_steps,
validation_freq=validation_freq,
steps_name="steps_per_epoch",
)
def evaluate(
self,
model,
x=None,
y=None,
batch_size=None,
verbose=1,
sample_weight=None,
steps=None,
callbacks=None,
**kwargs
):
"""Evaluate loop for Distribution Strategies."""
dist_utils.validate_inputs(x, y)
batch_size, steps = dist_utils.process_batch_and_step_size(
model._distribution_strategy, x, batch_size, steps, ModeKeys.TEST
)
batch_size = model._validate_or_infer_batch_size(batch_size, steps, x)
dataset = model._distribution_standardize_user_data(
x,
y,
sample_weight=sample_weight,
batch_size=batch_size,
allow_partial_batch=True,
)
if backend.is_tpu_strategy(model._distribution_strategy):
steps = training_utils_v1.infer_steps_for_dataset(
model, dataset, steps, steps_name="steps"
)
if steps is None:
raise ValueError(
"Number of steps could not be inferred from the data, "
"please pass the steps argument."
)
if not tf.executing_eagerly():
# Run TPU evaluation in a custom loop in graph mode.
return experimental_tpu_test_loop(
model,
dataset,
verbose=verbose,
steps=steps,
callbacks=callbacks,
)
return training_arrays_v1.test_loop(
model,
inputs=dataset,
batch_size=batch_size,
verbose=verbose,
steps=steps,
callbacks=callbacks,
)
def predict(
self,
model,
x,
batch_size=None,
verbose=0,
steps=None,
callbacks=None,
**kwargs
):
"""Predict loop for Distribution Strategies."""
dist_utils.validate_inputs(x=x, y=None)
batch_size, steps = dist_utils.process_batch_and_step_size(
model._distribution_strategy, x, batch_size, steps, ModeKeys.PREDICT
)
batch_size = model._validate_or_infer_batch_size(batch_size, steps, x)
dataset = model._distribution_standardize_user_data(
x, batch_size=batch_size, allow_partial_batch=True
)
if backend.is_tpu_strategy(model._distribution_strategy):
steps = training_utils_v1.infer_steps_for_dataset(
model, dataset, steps, steps_name="steps"
)
if steps is None:
raise ValueError(
"Number of steps could not be inferred from the data, "
"please pass the steps argument."
)
if not tf.executing_eagerly():
return experimental_tpu_predict_loop(
model,
dataset,
verbose=verbose,
steps=steps,
callbacks=callbacks,
)
return training_arrays_v1.predict_loop(
model,
dataset,
batch_size=batch_size,
verbose=verbose,
steps=steps,
callbacks=callbacks,
)
def _train_with_multi_worker(method):
"""Decorator handles multi worker training with distribution strategy."""
def wrapper(model, **kwargs):
def _worker_fn(_):
callbacks = kwargs.pop("callbacks", None)
filtered_callbacks = dist_utils.filter_distributed_callbacks(
callbacks, model
)
kwargs["callbacks"] = filtered_callbacks
return method(model, **kwargs)
return dc.run_distribute_coordinator(
_worker_fn, model._distribution_strategy
)
return wrapper
class DistributionMultiWorkerTrainingLoop(training_utils_v1.TrainingLoop):
"""Training loop for distribution strategy with multiple worker."""
def __init__(self, single_worker_loop):
self._single_worker_loop = single_worker_loop
def fit(self, *args, **kwargs):
return _train_with_multi_worker(self._single_worker_loop.fit)(
*args, **kwargs
)
def evaluate(self, *args, **kwargs):
return _train_with_multi_worker(self._single_worker_loop.evaluate)(
*args, **kwargs
)
def predict(self, *args, **kwargs):
# Currently predict is still using the single worker implementation.
return self._single_worker_loop.predict(*args, **kwargs)
| tf-keras/tf_keras/engine/training_distributed_v1.py/0 | {
"file_path": "tf-keras/tf_keras/engine/training_distributed_v1.py",
"repo_id": "tf-keras",
"token_count": 14823
} | 173 |
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Keras initializers for TF 1."""
import tensorflow.compat.v2 as tf
# isort: off
from tensorflow.python.util.tf_export import keras_export
_v1_zeros_initializer = tf.compat.v1.zeros_initializer
_v1_ones_initializer = tf.compat.v1.ones_initializer
_v1_constant_initializer = tf.compat.v1.constant_initializer
_v1_variance_scaling_initializer = tf.compat.v1.variance_scaling_initializer
_v1_orthogonal_initializer = tf.compat.v1.orthogonal_initializer
_v1_identity = tf.compat.v1.initializers.identity
_v1_glorot_uniform_initializer = tf.compat.v1.glorot_uniform_initializer
_v1_glorot_normal_initializer = tf.compat.v1.glorot_normal_initializer
# `allow_multiple_exports` is a no-op kept for TF 2.13 backward compatibility
keras_export(
v1=["keras.initializers.Zeros", "keras.initializers.zeros"],
allow_multiple_exports=True,
)(_v1_zeros_initializer)
keras_export(
v1=["keras.initializers.Ones", "keras.initializers.ones"],
allow_multiple_exports=True,
)(_v1_ones_initializer)
keras_export(
v1=["keras.initializers.Constant", "keras.initializers.constant"],
allow_multiple_exports=True,
)(_v1_constant_initializer)
keras_export(
v1=["keras.initializers.VarianceScaling"], allow_multiple_exports=True
)(_v1_variance_scaling_initializer)
keras_export(
v1=["keras.initializers.Orthogonal", "keras.initializers.orthogonal"],
allow_multiple_exports=True,
)(_v1_orthogonal_initializer)
keras_export(
v1=["keras.initializers.Identity", "keras.initializers.identity"],
allow_multiple_exports=True,
)(_v1_identity)
keras_export(
v1=["keras.initializers.glorot_uniform"], allow_multiple_exports=True
)(_v1_glorot_uniform_initializer)
keras_export(
v1=["keras.initializers.glorot_normal"], allow_multiple_exports=True
)(_v1_glorot_normal_initializer)
@keras_export(
v1=[
"keras.initializers.RandomNormal",
"keras.initializers.random_normal",
"keras.initializers.normal",
]
)
class RandomNormal(tf.compat.v1.random_normal_initializer):
"""Initializer that generates a normal distribution.
Args:
mean: a python scalar or a scalar tensor. Mean of the random values to
generate.
stddev: a python scalar or a scalar tensor. Standard deviation of the
random values to generate.
seed: A Python integer. Used to create random seeds. See
`tf.compat.v1.set_random_seed` for behavior.
dtype: Default data type, used if no `dtype` argument is provided when
calling the initializer. Only floating point types are supported.
@compatibility(TF2)
Although it is a legacy compat.v1 api,
`tf.compat.v1.keras.initializers.RandomNormal` is compatible with eager
execution and `tf.function`.
To switch to native TF2, switch to using
`tf.keras.initializers.RandomNormal` (not from `compat.v1`) and
if you need to change the default dtype use
`tf.keras.backend.set_floatx(float_dtype)`
or pass the dtype when calling the initializer, rather than passing it
when constructing the initializer.
Random seed behavior:
Also be aware that if you pass a seed to the TF2 initializer
API it will reuse that same seed for every single initialization
(unlike the TF1 initializer)
#### Structural Mapping to Native TF2
Before:
```python
initializer = tf.compat.v1.keras.initializers.RandomNormal(
mean=mean,
stddev=stddev,
seed=seed,
dtype=dtype)
weight_one = tf.Variable(initializer(shape_one))
weight_two = tf.Variable(initializer(shape_two))
```
After:
```python
initializer = tf.keras.initializers.RandomNormal(
mean=mean,
# seed=seed, # Setting a seed in the native TF2 API
# causes it to produce the same initializations
# across multiple calls of the same initializer.
stddev=stddev)
weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| :---------------- | :-------------- | :------------------------- |
| `mean` | `mean` | No change to defaults |
| `stddev` | `stddev` | No change to defaults |
| `seed` | `seed` | Different random number generation |
: : : semantics (to change in a :
: : : future version). If set, the TF2 version :
: : : will use stateless random number :
: : : generation which will produce the exact :
: : : same initialization even across multiple :
: : : calls of the initializer instance. the :
: : : `compat.v1` version will generate new :
: : : initializations each time. Do not set :
: : : a seed if you need different :
: : : initializations each time. Instead :
: : : either set a global tf seed with :
: : : `tf.random.set_seed` if you need :
: : : determinism, or initialize each weight:
: : : with a separate initializer instance :
: : : and a different seed. :
| `dtype` | `dtype` | The TF2 native api only takes it |
: : : as a `__call__` arg, not a constructor arg. :
| `partition_info` | - | (`__call__` arg in TF1) Not supported |
#### Example of fixed-seed behavior differences
`compat.v1` Fixed seed behavior:
>>> initializer = tf.compat.v1.keras.initializers.RandomNormal(seed=10)
>>> a = initializer(shape=(2, 2))
>>> b = initializer(shape=(2, 2))
>>> tf.reduce_sum(a - b) == 0
<tf.Tensor: shape=(), dtype=bool, numpy=False>
After:
>>> initializer = tf.keras.initializers.RandomNormal(seed=10)
>>> a = initializer(shape=(2, 2))
>>> b = initializer(shape=(2, 2))
>>> tf.reduce_sum(a - b) == 0
<tf.Tensor: shape=(), dtype=bool, numpy=True>
@end_compatibility
"""
def __init__(self, mean=0.0, stddev=0.05, seed=None, dtype=tf.float32):
super().__init__(mean=mean, stddev=stddev, seed=seed, dtype=dtype)
@keras_export(
v1=[
"keras.initializers.RandomUniform",
"keras.initializers.random_uniform",
"keras.initializers.uniform",
]
)
class RandomUniform(tf.compat.v1.random_uniform_initializer):
"""Initializer that generates tensors with a uniform distribution.
Args:
minval: A python scalar or a scalar tensor. Lower bound of the range of
random values to generate. Defaults to `-0.05`.
maxval: A python scalar or a scalar tensor. Upper bound of the range of
random values to generate. Defaults to `0.05`.
seed: A Python integer. Used to create random seeds. See
`tf.compat.v1.set_random_seed` for behavior.
dtype: Default data type, used if no `dtype` argument is provided when
calling the initializer.
@compatibility(TF2)
Although it is a legacy `compat.v1` api,
`tf.compat.v1.keras.initializers.RandomUniform` is compatible with eager
execution and `tf.function`.
To switch to native TF2, switch to using
`tf.keras.initializers.RandomUniform` (not from `compat.v1`) and
if you need to change the default dtype use
`tf.keras.backend.set_floatx(float_dtype)`
or pass the dtype when calling the initializer, rather than passing it
when constructing the initializer.
Random seed behavior:
Also be aware that if you pass a seed to the TF2 initializer
API it will reuse that same seed for every single initialization
(unlike the TF1 initializer)
#### Structural Mapping to Native TF2
Before:
```python
initializer = tf.compat.v1.keras.initializers.RandomUniform(
minval=minval,
maxval=maxval,
seed=seed,
dtype=dtype)
weight_one = tf.Variable(initializer(shape_one))
weight_two = tf.Variable(initializer(shape_two))
```
After:
```python
initializer = tf.keras.initializers.RandomUniform(
minval=minval,
maxval=maxval,
# seed=seed, # Setting a seed in the native TF2 API
# causes it to produce the same initializations
# across multiple calls of the same initializer.
)
weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| :---------------- | :-------------- | :------------------------- |
| `minval` | `minval` | No change to defaults |
| `maxval` | `maxval` | No change to defaults |
| `seed` | `seed` | Different random number generation |
: : : semantics (to change in a :
: : : future version). If set, the TF2 version :
: : : will use stateless random number :
: : : generation which will produce the exact :
: : : same initialization even across multiple :
: : : calls of the initializer instance. the :
: : : `compat.v1` version will generate new :
: : : initializations each time. Do not set :
: : : a seed if you need different :
: : : initializations each time. Instead :
: : : either set a global tf seed with
: : : `tf.random.set_seed` if you need :
: : : determinism, or initialize each weight :
: : : with a separate initializer instance :
: : : and a different seed. :
| `dtype` | `dtype` | The TF2 native api only takes it |
: : : as a `__call__` arg, not a constructor arg. :
| `partition_info` | - | (`__call__` arg in TF1) Not supported |
#### Example of fixed-seed behavior differences
`compat.v1` Fixed seed behavior:
>>> initializer = tf.compat.v1.keras.initializers.RandomUniform(seed=10)
>>> a = initializer(shape=(2, 2))
>>> b = initializer(shape=(2, 2))
>>> tf.reduce_sum(a - b) == 0
<tf.Tensor: shape=(), dtype=bool, numpy=False>
After:
>>> initializer = tf.keras.initializers.RandomUniform(seed=10)
>>> a = initializer(shape=(2, 2))
>>> b = initializer(shape=(2, 2))
>>> tf.reduce_sum(a - b) == 0
<tf.Tensor: shape=(), dtype=bool, numpy=True>
@end_compatibility
"""
def __init__(self, minval=-0.05, maxval=0.05, seed=None, dtype=tf.float32):
super().__init__(minval=minval, maxval=maxval, seed=seed, dtype=dtype)
@keras_export(
v1=[
"keras.initializers.TruncatedNormal",
"keras.initializers.truncated_normal",
]
)
class TruncatedNormal(tf.compat.v1.truncated_normal_initializer):
"""Initializer that generates a truncated normal distribution.
These values are similar to values from a `random_normal_initializer`
except that values more than two standard deviations from the mean
are discarded and re-drawn. This is the recommended initializer for
neural network weights and filters.
Args:
mean: a python scalar or a scalar tensor. Mean of the random values to
generate.
stddev: a python scalar or a scalar tensor. Standard deviation of the
random values to generate.
seed: A Python integer. Used to create random seeds. See
`tf.compat.v1.set_random_seed` for behavior.
dtype: Default data type, used if no `dtype` argument is provided when
calling the initializer. Only floating point types are supported.
@compatibility(TF2)
Although it is a legacy compat.v1 api,
`tf.compat.v1.keras.initializers.TruncatedNormal` is compatible with eager
execution and `tf.function`.
To switch to native TF2, switch to using
`tf.keras.initializers.TruncatedNormal` (not from `compat.v1`) and
if you need to change the default dtype use
`tf.keras.backend.set_floatx(float_dtype)`
or pass the dtype when calling the initializer, rather than passing it
when constructing the initializer.
Random seed behavior:
Also be aware that if you pass a seed to the TF2 initializer
API it will reuse that same seed for every single initialization
(unlike the TF1 initializer)
#### Structural Mapping to Native TF2
Before:
```python
initializer = tf.compat.v1.keras.initializers.TruncatedNormal(
mean=mean,
stddev=stddev,
seed=seed,
dtype=dtype)
weight_one = tf.Variable(initializer(shape_one))
weight_two = tf.Variable(initializer(shape_two))
```
After:
```python
initializer = tf.keras.initializers.TruncatedNormal(
mean=mean,
# seed=seed, # Setting a seed in the native TF2 API
# causes it to produce the same initializations
# across multiple calls of the same initializer.
stddev=stddev)
weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| :---------------- | :-------------- | :------------------------- |
| `mean` | `mean` | No change to defaults |
| `stddev` | `stddev` | No change to defaults |
| `seed` | `seed` | Different random number generation |
: : : semantics (to change in a :
: : : future version). If set, the TF2 version :
: : : will use stateless random number :
: : : generation which will produce the exact :
: : : same initialization even across multiple :
: : : calls of the initializer instance. the :
: : : `compat.v1` version will generate new :
: : : initializations each time. Do not set :
: : : a seed if you need different :
: : : initializations each time. Instead :
: : : either set a global tf seed with
: : : `tf.random.set_seed` if you need :
: : : determinism, or initialize each weight :
: : : with a separate initializer instance :
: : : and a different seed. :
| `dtype` | `dtype` | The TF2 native api only takes it |
: : : as a `__call__` arg, not a constructor arg. :
| `partition_info` | - | (`__call__` arg in TF1) Not supported |
#### Example of fixed-seed behavior differences
`compat.v1` Fixed seed behavior:
>>> initializer = tf.compat.v1.keras.initializers.TruncatedNormal(seed=10)
>>> a = initializer(shape=(2, 2))
>>> b = initializer(shape=(2, 2))
>>> tf.reduce_sum(a - b) == 0
<tf.Tensor: shape=(), dtype=bool, numpy=False>
After:
>>> initializer = tf.keras.initializers.TruncatedNormal(seed=10)
>>> a = initializer(shape=(2, 2))
>>> b = initializer(shape=(2, 2))
>>> tf.reduce_sum(a - b) == 0
<tf.Tensor: shape=(), dtype=bool, numpy=True>
@end_compatibility
"""
def __init__(self, mean=0.0, stddev=0.05, seed=None, dtype=tf.float32):
"""Initializer that generates a truncated normal distribution.
Args:
mean: a python scalar or a scalar tensor. Mean of the random values to
generate.
stddev: a python scalar or a scalar tensor. Standard deviation of the
random values to generate.
seed: A Python integer. Used to create random seeds. See
`tf.compat.v1.set_random_seed` for behavior.
dtype: Default data type, used if no `dtype` argument is provided when
calling the initializer. Only floating point types are supported.
"""
super().__init__(mean=mean, stddev=stddev, seed=seed, dtype=dtype)
@keras_export(v1=["keras.initializers.lecun_normal"])
class LecunNormal(tf.compat.v1.variance_scaling_initializer):
def __init__(self, seed=None):
super().__init__(
scale=1.0, mode="fan_in", distribution="truncated_normal", seed=seed
)
def get_config(self):
return {"seed": self.seed}
@keras_export(v1=["keras.initializers.lecun_uniform"])
class LecunUniform(tf.compat.v1.variance_scaling_initializer):
def __init__(self, seed=None):
super().__init__(
scale=1.0, mode="fan_in", distribution="uniform", seed=seed
)
def get_config(self):
return {"seed": self.seed}
@keras_export(v1=["keras.initializers.he_normal"])
class HeNormal(tf.compat.v1.variance_scaling_initializer):
def __init__(self, seed=None):
super().__init__(
scale=2.0, mode="fan_in", distribution="truncated_normal", seed=seed
)
def get_config(self):
return {"seed": self.seed}
@keras_export(v1=["keras.initializers.he_uniform"])
class HeUniform(tf.compat.v1.variance_scaling_initializer):
def __init__(self, seed=None):
super().__init__(
scale=2.0, mode="fan_in", distribution="uniform", seed=seed
)
def get_config(self):
return {"seed": self.seed}
| tf-keras/tf_keras/initializers/initializers_v1.py/0 | {
"file_path": "tf-keras/tf_keras/initializers/initializers_v1.py",
"repo_id": "tf-keras",
"token_count": 8138
} | 174 |
# Copyright 2020 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.
# ==============================================================================
import tensorflow.compat.v2 as tf
import tf_keras as keras
class ModuleTest(tf.test.TestCase):
def test_module_discover_layer_variable(self):
m = tf.Module()
m.a = keras.layers.Dense(1)
m.b = keras.layers.Dense(2)
# The weights of the layer has not been created yet.
self.assertEmpty(m.variables)
self.assertLen(m.submodules, 2)
inputs = keras.layers.Input((1,))
m.a(inputs)
m.b(inputs)
variable_list = m.variables
self.assertLen(variable_list, 4)
self.assertIs(variable_list[0], m.a.kernel)
self.assertIs(variable_list[1], m.a.bias)
self.assertIs(variable_list[2], m.b.kernel)
self.assertIs(variable_list[3], m.b.bias)
def test_model_discover_submodule(self):
m = keras.models.Sequential(
layers=[keras.layers.Dense(1), keras.layers.Dense(2)]
)
self.assertEqual(m.submodules, (m.layers[0], m.layers[1]))
m(keras.layers.Input((1,)))
self.assertLen(m.variables, 4)
def test_model_wrapped_in_module_discovers_submodules(self):
linear = keras.models.Sequential(
[keras.layers.Dense(units=1, input_shape=[1])]
)
linear.compile(optimizer="sgd", loss="mean_squared_error")
m = tf.Module()
m.l = linear
self.assertNotEmpty(m.submodules)
self.assertLen(m.variables, 2)
def test_subclass_model(self):
class Model(keras.Model):
def __init__(self):
super().__init__()
self.dense = keras.layers.Dense(units=1)
def call(self, inputs, training=None, mask=None):
return self.dense(inputs)
model = Model()
self.assertLen(model.submodules, 1) # For the dense layer
model.compile(loss="mse", optimizer="sgd")
# Make sure the compiled metric doesn't break tf.module
self.assertLen(model.submodules, 1)
if __name__ == "__main__":
tf.test.main()
| tf-keras/tf_keras/integration_test/module_test.py/0 | {
"file_path": "tf-keras/tf_keras/integration_test/module_test.py",
"repo_id": "tf-keras",
"token_count": 1138
} | 175 |
#!/bin/bash
# Copyright 2020 Google Inc. 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.
set -e
set -x
cd "${KOKORO_ROOT}/"
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.9 1
PYTHON_BINARY="/usr/bin/python3.9"
"${PYTHON_BINARY}" -m venv venv
source venv/bin/activate
# Check the python version
python --version
python3 --version
cd "src/github/tf-keras"
# Keep pip version at 20.1.1 to avoid the slow resolver issue.
pip install -U pip==20.1.1 setuptools
pip install -r requirements.txt
# Uninstall the keras-nightly package so that we will only test the version of
# keras code from local workspace.
# TODO(keras-team): `tf-nightly` currently installs `keras-nightly`.
# Update this once we switch to `tf_keras-nightly` in TensorFlow.
pip uninstall -y keras-nightly
# TODO(scottzhu): Using --define=use_fast_cpp_protos=false to suppress the
# protobuf build issue for now. We should have a proper solution for this.
bazel test --test_timeout 300,450,1200,3600 --test_output=errors --keep_going \
--define=use_fast_cpp_protos=false \
--build_tests_only \
--build_tag_filters="-no_oss,-oss_excluded" \
--test_tag_filters="-no_oss,-oss_excluded" \
-- //tf_keras/...
| tf-keras/tf_keras/kokoro/github/ubuntu/cpu/build.sh/0 | {
"file_path": "tf-keras/tf_keras/kokoro/github/ubuntu/cpu/build.sh",
"repo_id": "tf-keras",
"token_count": 574
} | 176 |
# Copyright 2015 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.
# ==============================================================================
"""Rectified Linear Unit activation layer."""
from tf_keras import backend
from tf_keras.engine.base_layer import Layer
from tf_keras.utils import tf_utils
# isort: off
from tensorflow.python.util.tf_export import keras_export
@keras_export("keras.layers.ReLU")
class ReLU(Layer):
"""Rectified Linear Unit activation function.
With default values, it returns element-wise `max(x, 0)`.
Otherwise, it follows:
```
f(x) = max_value if x >= max_value
f(x) = x if threshold <= x < max_value
f(x) = negative_slope * (x - threshold) otherwise
```
Usage:
>>> layer = tf.keras.layers.ReLU()
>>> output = layer([-3.0, -1.0, 0.0, 2.0])
>>> list(output.numpy())
[0.0, 0.0, 0.0, 2.0]
>>> layer = tf.keras.layers.ReLU(max_value=1.0)
>>> output = layer([-3.0, -1.0, 0.0, 2.0])
>>> list(output.numpy())
[0.0, 0.0, 0.0, 1.0]
>>> layer = tf.keras.layers.ReLU(negative_slope=1.0)
>>> output = layer([-3.0, -1.0, 0.0, 2.0])
>>> list(output.numpy())
[-3.0, -1.0, 0.0, 2.0]
>>> layer = tf.keras.layers.ReLU(threshold=1.5)
>>> output = layer([-3.0, -1.0, 1.0, 2.0])
>>> list(output.numpy())
[0.0, 0.0, 0.0, 2.0]
Input shape:
Arbitrary. Use the keyword argument `input_shape`
(tuple of integers, does not include the batch axis)
when using this layer as the first layer in a model.
Output shape:
Same shape as the input.
Args:
max_value: Float >= 0. Maximum activation value. None means unlimited.
Defaults to `None`.
negative_slope: Float >= 0. Negative slope coefficient.
Defaults to `0.`.
threshold: Float >= 0. Threshold value for thresholded activation.
Defaults to `0.`.
"""
def __init__(
self, max_value=None, negative_slope=0.0, threshold=0.0, **kwargs
):
super().__init__(**kwargs)
if max_value is not None and max_value < 0.0:
raise ValueError(
"max_value of a ReLU layer cannot be a negative "
f"value. Received: {max_value}"
)
if negative_slope is None or negative_slope < 0.0:
raise ValueError(
"negative_slope of a ReLU layer cannot be a negative "
f"value. Received: {negative_slope}"
)
if threshold is None or threshold < 0.0:
raise ValueError(
"threshold of a ReLU layer cannot be a negative "
f"value. Received: {threshold}"
)
self.supports_masking = True
if max_value is not None:
max_value = backend.cast_to_floatx(max_value)
self.max_value = max_value
self.negative_slope = backend.cast_to_floatx(negative_slope)
self.threshold = backend.cast_to_floatx(threshold)
def call(self, inputs):
# alpha is used for leaky relu slope in activations instead of
# negative_slope.
return backend.relu(
inputs,
alpha=self.negative_slope,
max_value=self.max_value,
threshold=self.threshold,
)
def get_config(self):
config = {
"max_value": self.max_value,
"negative_slope": self.negative_slope,
"threshold": self.threshold,
}
base_config = super().get_config()
return dict(list(base_config.items()) + list(config.items()))
@tf_utils.shape_type_conversion
def compute_output_shape(self, input_shape):
return input_shape
| tf-keras/tf_keras/layers/activation/relu.py/0 | {
"file_path": "tf-keras/tf_keras/layers/activation/relu.py",
"repo_id": "tf-keras",
"token_count": 1805
} | 177 |
# Description:
# Contains the TF-Keras convolution layers.
# Placeholder: load unaliased py_library
load("@org_keras//tf_keras:tf_keras.bzl", "cuda_py_test")
package(
# copybara:uncomment default_applicable_licenses = ["//tf_keras:license"],
default_visibility = ["//tf_keras:__subpackages__"],
licenses = ["notice"],
)
py_library(
name = "convolutional",
srcs = [
"__init__.py",
],
srcs_version = "PY3",
deps = [
":conv1d",
":conv1d_transpose",
":conv2d",
":conv2d_transpose",
":conv3d",
":conv3d_transpose",
":depthwise_conv1d",
":depthwise_conv2d",
":separable_conv1d",
":separable_conv2d",
"//tf_keras/layers/pooling:average_pooling1d",
"//tf_keras/layers/pooling:average_pooling2d",
"//tf_keras/layers/pooling:average_pooling3d",
"//tf_keras/layers/pooling:max_pooling1d",
"//tf_keras/layers/pooling:max_pooling2d",
"//tf_keras/layers/pooling:max_pooling3d",
"//tf_keras/layers/reshaping:cropping1d",
"//tf_keras/layers/reshaping:cropping2d",
"//tf_keras/layers/reshaping:cropping3d",
"//tf_keras/layers/reshaping:up_sampling1d",
"//tf_keras/layers/reshaping:up_sampling2d",
"//tf_keras/layers/reshaping:up_sampling3d",
"//tf_keras/layers/reshaping:zero_padding1d",
"//tf_keras/layers/reshaping:zero_padding2d",
"//tf_keras/layers/reshaping:zero_padding3d",
],
)
py_library(
name = "base_conv",
srcs = ["base_conv.py"],
srcs_version = "PY3",
deps = [
"//:expect_tensorflow_installed",
"//tf_keras:activations",
"//tf_keras:constraints",
"//tf_keras:regularizers",
"//tf_keras/engine:base_layer",
"//tf_keras/engine:input_spec",
"//tf_keras/initializers",
"//tf_keras/utils:engine_utils",
],
)
py_library(
name = "conv1d",
srcs = ["conv1d.py"],
srcs_version = "PY3",
deps = [
":base_conv",
"//tf_keras:activations",
"//tf_keras:constraints",
"//tf_keras:regularizers",
"//tf_keras/dtensor:utils",
"//tf_keras/initializers",
],
)
py_library(
name = "conv2d",
srcs = ["conv2d.py"],
srcs_version = "PY3",
deps = [
":base_conv",
"//tf_keras:activations",
"//tf_keras:constraints",
"//tf_keras:regularizers",
"//tf_keras/dtensor:utils",
"//tf_keras/initializers",
],
)
py_library(
name = "conv3d",
srcs = ["conv3d.py"],
srcs_version = "PY3",
deps = [
":base_conv",
"//tf_keras:activations",
"//tf_keras:constraints",
"//tf_keras:regularizers",
"//tf_keras/dtensor:utils",
"//tf_keras/initializers",
],
)
py_library(
name = "conv1d_transpose",
srcs = ["conv1d_transpose.py"],
srcs_version = "PY3",
deps = [
":conv1d",
"//:expect_tensorflow_installed",
"//tf_keras:activations",
"//tf_keras:constraints",
"//tf_keras:regularizers",
"//tf_keras/dtensor:utils",
"//tf_keras/engine:input_spec",
"//tf_keras/initializers",
"//tf_keras/utils:engine_utils",
],
)
py_library(
name = "conv2d_transpose",
srcs = ["conv2d_transpose.py"],
srcs_version = "PY3",
deps = [
":conv2d",
"//:expect_tensorflow_installed",
"//tf_keras:activations",
"//tf_keras:backend",
"//tf_keras:constraints",
"//tf_keras:regularizers",
"//tf_keras/dtensor:utils",
"//tf_keras/engine:input_spec",
"//tf_keras/initializers",
"//tf_keras/utils:engine_utils",
],
)
py_library(
name = "conv3d_transpose",
srcs = ["conv3d_transpose.py"],
srcs_version = "PY3",
deps = [
":conv3d",
"//:expect_tensorflow_installed",
"//tf_keras:activations",
"//tf_keras:constraints",
"//tf_keras:regularizers",
"//tf_keras/dtensor:utils",
"//tf_keras/engine:input_spec",
"//tf_keras/initializers",
"//tf_keras/utils:engine_utils",
],
)
py_library(
name = "base_separable_conv",
srcs = ["base_separable_conv.py"],
srcs_version = "PY3",
deps = [
":base_conv",
"//:expect_tensorflow_installed",
"//tf_keras:activations",
"//tf_keras:constraints",
"//tf_keras:regularizers",
"//tf_keras/engine:input_spec",
"//tf_keras/initializers",
],
)
py_library(
name = "separable_conv1d",
srcs = ["separable_conv1d.py"],
srcs_version = "PY3",
deps = [
":base_separable_conv",
"//:expect_tensorflow_installed",
"//tf_keras:activations",
"//tf_keras:constraints",
"//tf_keras:regularizers",
"//tf_keras/initializers",
"//tf_keras/utils:engine_utils",
],
)
py_library(
name = "separable_conv2d",
srcs = ["separable_conv2d.py"],
srcs_version = "PY3",
deps = [
":base_separable_conv",
"//:expect_tensorflow_installed",
"//tf_keras:activations",
"//tf_keras:constraints",
"//tf_keras:regularizers",
"//tf_keras/initializers",
"//tf_keras/utils:engine_utils",
],
)
py_library(
name = "base_depthwise_conv",
srcs = ["base_depthwise_conv.py"],
srcs_version = "PY3",
deps = [
":base_conv",
"//:expect_tensorflow_installed",
"//tf_keras:constraints",
"//tf_keras:regularizers",
"//tf_keras/engine:input_spec",
"//tf_keras/initializers",
],
)
py_library(
name = "depthwise_conv1d",
srcs = ["depthwise_conv1d.py"],
srcs_version = "PY3",
deps = [
":base_depthwise_conv",
"//:expect_tensorflow_installed",
"//tf_keras/utils:engine_utils",
"//tf_keras/utils:tf_utils",
],
)
py_library(
name = "depthwise_conv2d",
srcs = ["depthwise_conv2d.py"],
srcs_version = "PY3",
deps = [
":base_depthwise_conv",
"//tf_keras:backend",
"//tf_keras/utils:engine_utils",
"//tf_keras/utils:tf_utils",
],
)
cuda_py_test(
name = "conv_test",
size = "medium",
srcs = ["conv_test.py"],
python_version = "PY3",
shard_count = 8,
deps = [
"//:expect_absl_installed", # absl/testing:parameterized
"//:expect_numpy_installed",
"//:expect_tensorflow_installed",
"//tf_keras",
"//tf_keras/testing_infra:test_combinations",
"//tf_keras/testing_infra:test_utils",
],
)
cuda_py_test(
name = "conv_transpose_test",
size = "medium",
srcs = ["conv_transpose_test.py"],
python_version = "PY3",
deps = [
"//:expect_absl_installed", # absl/testing:parameterized
"//:expect_numpy_installed",
"//:expect_tensorflow_installed",
"//tf_keras",
"//tf_keras/testing_infra:test_combinations",
"//tf_keras/testing_infra:test_utils",
],
)
cuda_py_test(
name = "depthwise_conv_test",
size = "medium",
srcs = ["depthwise_conv_test.py"],
python_version = "PY3",
shard_count = 8,
deps = [
"//:expect_absl_installed", # absl/testing:parameterized
"//:expect_tensorflow_installed",
"//tf_keras",
"//tf_keras/testing_infra:test_combinations",
"//tf_keras/testing_infra:test_utils",
],
)
cuda_py_test(
name = "separable_conv_test",
size = "medium",
srcs = ["separable_conv_test.py"],
python_version = "PY3",
deps = [
"//:expect_absl_installed", # absl/testing:parameterized
"//:expect_numpy_installed",
"//:expect_tensorflow_installed",
"//tf_keras",
"//tf_keras/testing_infra:test_combinations",
"//tf_keras/testing_infra:test_utils",
],
)
| tf-keras/tf_keras/layers/convolutional/BUILD/0 | {
"file_path": "tf-keras/tf_keras/layers/convolutional/BUILD",
"repo_id": "tf-keras",
"token_count": 4096
} | 178 |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Keras depthwise separable 1D convolution."""
import tensorflow.compat.v2 as tf
from tf_keras import activations
from tf_keras import constraints
from tf_keras import initializers
from tf_keras import regularizers
from tf_keras.layers.convolutional.base_separable_conv import SeparableConv
from tf_keras.utils import conv_utils
# isort: off
from tensorflow.python.util.tf_export import keras_export
@keras_export(
"keras.layers.SeparableConv1D", "keras.layers.SeparableConvolution1D"
)
class SeparableConv1D(SeparableConv):
"""Depthwise separable 1D convolution.
This layer performs a depthwise convolution that acts separately on
channels, followed by a pointwise convolution that mixes channels.
If `use_bias` is True and a bias initializer is provided,
it adds a bias vector to the output.
It then optionally applies an activation function to produce the final
output.
Args:
filters: Integer, the dimensionality of the output space (i.e. the number
of filters in the convolution).
kernel_size: A single integer specifying the spatial
dimensions of the filters.
strides: A single integer specifying the strides
of the convolution.
Specifying any `stride` value != 1 is incompatible with specifying
any `dilation_rate` value != 1.
padding: One of `"valid"`, `"same"`, or `"causal"` (case-insensitive).
`"valid"` means no padding. `"same"` results in padding with zeros
evenly to the left/right or up/down of the input such that output has
the same height/width dimension as the input. `"causal"` results in
causal (dilated) convolutions, e.g. `output[t]` does not depend on
`input[t+1:]`.
data_format: A string, one of `channels_last` (default) or
`channels_first`. The ordering of the dimensions in the inputs.
`channels_last` corresponds to inputs with shape
`(batch_size, length, channels)` while `channels_first` corresponds to
inputs with shape `(batch_size, channels, length)`.
dilation_rate: A single integer, specifying
the dilation rate to use for dilated convolution.
depth_multiplier: The number of depthwise convolution output channels for
each input channel. The total number of depthwise convolution output
channels will be equal to `num_filters_in * depth_multiplier`.
activation: Activation function to use.
If you don't specify anything, no activation is applied
(see `keras.activations`).
use_bias: Boolean, whether the layer uses a bias.
depthwise_initializer: An initializer for the depthwise convolution kernel
(see `keras.initializers`). If None, then the default initializer
('glorot_uniform') will be used.
pointwise_initializer: An initializer for the pointwise convolution kernel
(see `keras.initializers`). If None, then the default initializer
('glorot_uniform') will be used.
bias_initializer: An initializer for the bias vector. If None, the default
initializer ('zeros') will be used (see `keras.initializers`).
depthwise_regularizer: Optional regularizer for the depthwise
convolution kernel (see `keras.regularizers`).
pointwise_regularizer: Optional regularizer for the pointwise
convolution kernel (see `keras.regularizers`).
bias_regularizer: Optional regularizer for the bias vector
(see `keras.regularizers`).
activity_regularizer: Optional regularizer function for the output
(see `keras.regularizers`).
depthwise_constraint: Optional projection function to be applied to the
depthwise kernel after being updated by an `Optimizer` (e.g. used for
norm constraints or value constraints for layer weights). The function
must take as input the unprojected variable and must return the
projected variable (which must have the same shape). Constraints are
not safe to use when doing asynchronous distributed training
(see `keras.constraints`).
pointwise_constraint: Optional projection function to be applied to the
pointwise kernel after being updated by an `Optimizer`
(see `keras.constraints`).
bias_constraint: Optional projection function to be applied to the
bias after being updated by an `Optimizer`
(see `keras.constraints`).
trainable: Boolean, if `True` the weights of this layer will be marked as
trainable (and listed in `layer.trainable_weights`).
Input shape:
3D tensor with shape:
`(batch_size, channels, steps)` if data_format='channels_first'
or 3D tensor with shape:
`(batch_size, steps, channels)` if data_format='channels_last'.
Output shape:
3D tensor with shape:
`(batch_size, filters, new_steps)` if data_format='channels_first'
or 3D tensor with shape:
`(batch_size, new_steps, filters)` if data_format='channels_last'.
`new_steps` value might have changed due to padding or strides.
Returns:
A tensor of rank 3 representing
`activation(separableconv1d(inputs, kernel) + bias)`.
"""
def __init__(
self,
filters,
kernel_size,
strides=1,
padding="valid",
data_format=None,
dilation_rate=1,
depth_multiplier=1,
activation=None,
use_bias=True,
depthwise_initializer="glorot_uniform",
pointwise_initializer="glorot_uniform",
bias_initializer="zeros",
depthwise_regularizer=None,
pointwise_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
depthwise_constraint=None,
pointwise_constraint=None,
bias_constraint=None,
**kwargs
):
super().__init__(
rank=1,
filters=filters,
kernel_size=kernel_size,
strides=strides,
padding=padding,
data_format=data_format,
dilation_rate=dilation_rate,
depth_multiplier=depth_multiplier,
activation=activations.get(activation),
use_bias=use_bias,
depthwise_initializer=initializers.get(depthwise_initializer),
pointwise_initializer=initializers.get(pointwise_initializer),
bias_initializer=initializers.get(bias_initializer),
depthwise_regularizer=regularizers.get(depthwise_regularizer),
pointwise_regularizer=regularizers.get(pointwise_regularizer),
bias_regularizer=regularizers.get(bias_regularizer),
activity_regularizer=regularizers.get(activity_regularizer),
depthwise_constraint=constraints.get(depthwise_constraint),
pointwise_constraint=constraints.get(pointwise_constraint),
bias_constraint=constraints.get(bias_constraint),
**kwargs
)
def call(self, inputs):
if self.padding == "causal":
inputs = tf.pad(inputs, self._compute_causal_padding(inputs))
if self.data_format == "channels_last":
strides = (1,) + self.strides * 2 + (1,)
spatial_start_dim = 1
else:
strides = (1, 1) + self.strides * 2
spatial_start_dim = 2
# Explicitly broadcast inputs and kernels to 4D.
# TODO(fchollet): refactor when a native separable_conv1d op is
# available.
inputs = tf.expand_dims(inputs, spatial_start_dim)
depthwise_kernel = tf.expand_dims(self.depthwise_kernel, 0)
pointwise_kernel = tf.expand_dims(self.pointwise_kernel, 0)
dilation_rate = (1,) + self.dilation_rate
if self.padding == "causal":
op_padding = "valid"
else:
op_padding = self.padding
outputs = tf.compat.v1.nn.separable_conv2d(
inputs,
depthwise_kernel,
pointwise_kernel,
strides=strides,
padding=op_padding.upper(),
rate=dilation_rate,
data_format=conv_utils.convert_data_format(
self.data_format, ndim=4
),
)
if self.use_bias:
outputs = tf.nn.bias_add(
outputs,
self.bias,
data_format=conv_utils.convert_data_format(
self.data_format, ndim=4
),
)
outputs = tf.squeeze(outputs, [spatial_start_dim])
if self.activation is not None:
return self.activation(outputs)
return outputs
# Alias
SeparableConvolution1D = SeparableConv1D
| tf-keras/tf_keras/layers/convolutional/separable_conv1d.py/0 | {
"file_path": "tf-keras/tf_keras/layers/convolutional/separable_conv1d.py",
"repo_id": "tf-keras",
"token_count": 3686
} | 179 |
# Description:
# DynamicEmbeddingLayer allows for the continuous updating of the vocabulary and embeddings during
# the training process.
# Placeholder: load unaliased py_library
load("@org_keras//tf_keras:tf_keras.bzl", "tf_py_test")
load("@org_keras//tf_keras:tf_keras.bzl", "distribute_py_test")
package(
# copybara:uncomment default_applicable_licenses = ["//third_party/py/keras:license"],
default_visibility = [
"//tf_keras:friends",
],
licenses = ["notice"],
)
py_library(
name = "dynamic_lookup",
srcs = ["dynamic_lookup.py"],
srcs_version = "PY3",
deps = [
"//:expect_tensorflow_installed",
"//tf_keras/layers",
],
)
tf_py_test(
name = "dynamic_lookup_test",
size = "small",
srcs = ["dynamic_lookup_test.py"],
python_version = "PY3",
shard_count = 6,
tags = ["notpu"],
deps = [
":dynamic_lookup",
"//:expect_numpy_installed",
"//:expect_tensorflow_installed",
"//tf_keras",
"//tf_keras/testing_infra:test_combinations",
"//tf_keras/testing_infra:test_utils",
],
)
py_library(
name = "dynamic_embedding",
srcs = ["dynamic_embedding.py"],
deps = [
":dynamic_lookup",
"//:expect_tensorflow_installed",
"//tf_keras",
"//tf_keras/layers",
"//tf_keras/utils",
],
)
tf_py_test(
name = "dynamic_embedding_test",
srcs = ["dynamic_embedding_test.py"],
tags = ["notpu"],
deps = [
":dynamic_embedding",
"//:expect_tensorflow_installed",
"//tf_keras:callbacks",
"//tf_keras/layers",
"//tf_keras/models",
"//tf_keras/testing_infra:test_combinations",
"//tf_keras/testing_infra:test_utils",
],
)
distribute_py_test(
name = "dynamic_embedding_distributed_test",
srcs = ["dynamic_embedding_distributed_test.py"],
tags = [
"no_oss",
"no_windows",
"nomultivm",
"notpu",
],
deps = [
":dynamic_embedding",
"//:expect_absl_installed", # absl/testing:parameterized
"//:expect_numpy_installed",
"//:expect_tensorflow_installed",
"//tf_keras",
"//tf_keras:callbacks",
"//tf_keras/testing_infra:test_utils",
],
)
distribute_py_test(
name = "dynamic_lookup_distributed_test",
srcs = ["dynamic_lookup_distributed_test.py"],
tags = [
"nomultivm",
"notpu",
],
deps = [
":dynamic_lookup",
"//:expect_absl_installed", # absl/testing:parameterized
"//:expect_numpy_installed",
"//:expect_tensorflow_installed",
"//tf_keras",
"//tf_keras/testing_infra:test_utils",
],
)
| tf-keras/tf_keras/layers/experimental/BUILD/0 | {
"file_path": "tf-keras/tf_keras/layers/experimental/BUILD",
"repo_id": "tf-keras",
"token_count": 1333
} | 180 |
# Copyright 2015 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.
# ==============================================================================
"""Private utilities for locally-connected layers."""
import numpy as np
import tensorflow.compat.v2 as tf
from tf_keras import backend
from tf_keras.utils import conv_utils
def get_locallyconnected_mask(
input_shape, kernel_shape, strides, padding, data_format
):
"""Return a mask representing connectivity of a locally-connected operation.
This method returns a masking numpy array of 0s and 1s (of type
`np.float32`) that, when element-wise multiplied with a fully-connected
weight tensor, masks out the weights between disconnected input-output pairs
and thus implements local connectivity through a sparse fully-connected
weight tensor.
Assume an unshared convolution with given parameters is applied to an input
having N spatial dimensions with `input_shape = (d_in1, ..., d_inN)`
to produce an output with spatial shape `(d_out1, ..., d_outN)` (determined
by layer parameters such as `strides`).
This method returns a mask which can be broadcast-multiplied (element-wise)
with a 2*(N+1)-D weight matrix (equivalent to a fully-connected layer
between (N+1)-D activations (N spatial + 1 channel dimensions for input and
output) to make it perform an unshared convolution with given
`kernel_shape`, `strides`, `padding` and `data_format`.
Args:
input_shape: tuple of size N: `(d_in1, ..., d_inN)` spatial shape of the
input.
kernel_shape: tuple of size N, spatial shape of the convolutional kernel /
receptive field.
strides: tuple of size N, strides along each spatial dimension.
padding: type of padding, string `"same"` or `"valid"`.
data_format: a string, `"channels_first"` or `"channels_last"`.
Returns:
a `np.float32`-type `np.ndarray` of shape
`(1, d_in1, ..., d_inN, 1, d_out1, ..., d_outN)`
if `data_format == `"channels_first"`, or
`(d_in1, ..., d_inN, 1, d_out1, ..., d_outN, 1)`
if `data_format == "channels_last"`.
Raises:
ValueError: if `data_format` is neither `"channels_first"` nor
`"channels_last"`.
"""
mask = conv_utils.conv_kernel_mask(
input_shape=input_shape,
kernel_shape=kernel_shape,
strides=strides,
padding=padding,
)
ndims = int(mask.ndim / 2)
if data_format == "channels_first":
mask = np.expand_dims(mask, 0)
mask = np.expand_dims(mask, -ndims - 1)
elif data_format == "channels_last":
mask = np.expand_dims(mask, ndims)
mask = np.expand_dims(mask, -1)
else:
raise ValueError("Unrecognized data_format: " + str(data_format))
return mask
def local_conv_matmul(inputs, kernel, kernel_mask, output_shape):
"""Apply N-D convolution with un-shared weights using a single matmul call.
This method outputs `inputs . (kernel * kernel_mask)`
(with `.` standing for matrix-multiply and `*` for element-wise multiply)
and requires a precomputed `kernel_mask` to zero-out weights in `kernel` and
hence perform the same operation as a convolution with un-shared
(the remaining entries in `kernel`) weights. It also does the necessary
reshapes to make `inputs` and `kernel` 2-D and `output` (N+2)-D.
Args:
inputs: (N+2)-D tensor with shape `(batch_size, channels_in, d_in1, ...,
d_inN)` or `(batch_size, d_in1, ..., d_inN, channels_in)`.
kernel: the unshared weights for N-D convolution,
an (N+2)-D tensor of shape: `(d_in1, ..., d_inN, channels_in,
d_out2, ..., d_outN, channels_out)` or `(channels_in, d_in1, ...,
d_inN, channels_out, d_out2, ..., d_outN)`, with the ordering of
channels and spatial dimensions matching that of the input. Each
entry is the weight between a particular input and output location,
similarly to a fully-connected weight matrix.
kernel_mask: a float 0/1 mask tensor of shape: `(d_in1, ..., d_inN, 1,
d_out2, ..., d_outN, 1)` or `(1, d_in1, ..., d_inN, 1, d_out2, ...,
d_outN)`, with the ordering of singleton and spatial dimensions
matching that of the input. Mask represents the connectivity pattern
of the layer and is precomputed elsewhere based on layer parameters:
stride, padding, and the receptive field shape.
output_shape: a tuple of (N+2) elements representing the output shape:
`(batch_size, channels_out, d_out1, ..., d_outN)` or `(batch_size,
d_out1, ..., d_outN, channels_out)`, with the ordering of channels and
spatial dimensions matching that of the input.
Returns:
Output (N+2)-D tensor with shape `output_shape`.
"""
inputs_flat = backend.reshape(inputs, (backend.shape(inputs)[0], -1))
kernel = kernel_mask * kernel
kernel = make_2d(kernel, split_dim=backend.ndim(kernel) // 2)
output_flat = tf.matmul(inputs_flat, kernel, b_is_sparse=True)
output = backend.reshape(
output_flat,
[
backend.shape(output_flat)[0],
]
+ output_shape.as_list()[1:],
)
return output
def local_conv_sparse_matmul(
inputs, kernel, kernel_idxs, kernel_shape, output_shape
):
"""Apply N-D convolution with unshared weights using a single sparse matmul.
This method outputs `inputs . tf.sparse.SparseTensor(indices=kernel_idxs,
values=kernel, dense_shape=kernel_shape)`, with `.` standing for
matrix-multiply. It also reshapes `inputs` to 2-D and `output` to (N+2)-D.
Args:
inputs: (N+2)-D tensor with shape `(batch_size, channels_in, d_in1, ...,
d_inN)` or `(batch_size, d_in1, ..., d_inN, channels_in)`.
kernel: a 1-D tensor with shape `(len(kernel_idxs),)` containing all the
weights of the layer.
kernel_idxs: a list of integer tuples representing indices in a sparse
matrix performing the un-shared convolution as a matrix-multiply.
kernel_shape: a tuple `(input_size, output_size)`, where `input_size =
channels_in * d_in1 * ... * d_inN` and `output_size = channels_out *
d_out1 * ... * d_outN`.
output_shape: a tuple of (N+2) elements representing the output shape:
`(batch_size, channels_out, d_out1, ..., d_outN)` or `(batch_size,
d_out1, ..., d_outN, channels_out)`, with the ordering of channels and
spatial dimensions matching that of the input.
Returns:
Output (N+2)-D dense tensor with shape `output_shape`.
"""
inputs_flat = backend.reshape(inputs, (backend.shape(inputs)[0], -1))
output_flat = tf.sparse.sparse_dense_matmul(
sp_a=tf.SparseTensor(kernel_idxs, kernel, kernel_shape),
b=inputs_flat,
adjoint_b=True,
)
output_flat_transpose = backend.transpose(output_flat)
output_reshaped = backend.reshape(
output_flat_transpose,
[
backend.shape(output_flat_transpose)[0],
]
+ output_shape.as_list()[1:],
)
return output_reshaped
def make_2d(tensor, split_dim):
"""Reshapes an N-dimensional tensor into a 2D tensor.
Dimensions before (excluding) and after (including) `split_dim` are grouped
together.
Args:
tensor: a tensor of shape `(d0, ..., d(N-1))`.
split_dim: an integer from 1 to N-1, index of the dimension to group
dimensions before (excluding) and after (including).
Returns:
Tensor of shape
`(d0 * ... * d(split_dim-1), d(split_dim) * ... * d(N-1))`.
"""
shape = tf.shape(tensor)
in_dims = shape[:split_dim]
out_dims = shape[split_dim:]
in_size = tf.reduce_prod(in_dims)
out_size = tf.reduce_prod(out_dims)
return tf.reshape(tensor, (in_size, out_size))
| tf-keras/tf_keras/layers/locally_connected/locally_connected_utils.py/0 | {
"file_path": "tf-keras/tf_keras/layers/locally_connected/locally_connected_utils.py",
"repo_id": "tf-keras",
"token_count": 3301
} | 181 |
# Copyright 2019 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 V2 implementation of Normalization layers."""
import warnings
import tensorflow.compat.v2 as tf
from tf_keras import backend
from tf_keras import constraints
from tf_keras import initializers
from tf_keras import regularizers
from tf_keras.dtensor import utils
from tf_keras.engine.base_layer import Layer
from tf_keras.engine.input_spec import InputSpec
from tf_keras.utils import control_flow_util
from tf_keras.utils import tf_utils
# isort: off
from tensorflow.python.ops.control_flow_ops import (
get_enclosing_xla_context,
)
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import deprecation
from tensorflow.python.util.tf_export import keras_export
class BatchNormalizationBase(Layer):
r"""Layer that normalizes its inputs.
Batch normalization applies a transformation that maintains the mean output
close to 0 and the output standard deviation close to 1.
Importantly, batch normalization works differently during training and
during inference.
**During training** (i.e. when using `fit()` or when calling the layer/model
with the argument `training=True`), the layer normalizes its output using
the mean and standard deviation of the current batch of inputs. That is to
say, for each channel being normalized, the layer returns
`gamma * (batch - mean(batch)) / sqrt(var(batch) + epsilon) + beta`, where:
- `epsilon` is small constant (configurable as part of the constructor
arguments)
- `gamma` is a learned scaling factor (initialized as 1), which
can be disabled by passing `scale=False` to the constructor.
- `beta` is a learned offset factor (initialized as 0), which
can be disabled by passing `center=False` to the constructor.
**During inference** (i.e. when using `evaluate()` or `predict()`) or when
calling the layer/model with the argument `training=False` (which is the
default), the layer normalizes its output using a moving average of the
mean and standard deviation of the batches it has seen during training. That
is to say, it returns
`gamma * (batch - self.moving_mean) / sqrt(self.moving_var+epsilon) + beta`.
`self.moving_mean` and `self.moving_var` are non-trainable variables that
are updated each time the layer in called in training mode, as such:
- `moving_mean = moving_mean * momentum + mean(batch) * (1 - momentum)`
- `moving_var = moving_var * momentum + var(batch) * (1 - momentum)`
As such, the layer will only normalize its inputs during inference
*after having been trained on data that has similar statistics as the
inference data*.
Args:
axis: Integer or a list of integers, the axis that should be normalized
(typically the features axis). For instance, after a `Conv2D` layer with
`data_format="channels_first"`, set `axis=1` in `BatchNormalization`.
momentum: Momentum for the moving average.
epsilon: Small float added to variance to avoid dividing by zero.
center: If True, add offset of `beta` to normalized tensor. If False,
`beta` is ignored.
scale: If True, multiply by `gamma`. If False, `gamma` is not used. When
the next layer is linear (also e.g. `nn.relu`), this can be disabled
since the scaling will be done by the next layer.
beta_initializer: Initializer for the beta weight.
gamma_initializer: Initializer for the gamma weight.
moving_mean_initializer: Initializer for the moving mean.
moving_variance_initializer: Initializer for the moving variance.
beta_regularizer: Optional regularizer for the beta weight.
gamma_regularizer: Optional regularizer for the gamma weight.
beta_constraint: Optional constraint for the beta weight.
gamma_constraint: Optional constraint for the gamma weight.
renorm: Whether to use [Batch Renormalization](
https://arxiv.org/abs/1702.03275). This adds extra variables during
training. The inference is the same for either value of this
parameter.
renorm_clipping: A dictionary that may map keys 'rmax', 'rmin', 'dmax' to
scalar `Tensors` used to clip the renorm correction. The correction `(r,
d)` is used as `corrected_value = normalized_value * r + d`, with `r`
clipped to [rmin, rmax], and `d` to [-dmax, dmax]. Missing rmax, rmin,
dmax are set to inf, 0, inf, respectively.
renorm_momentum: Momentum used to update the moving means and standard
deviations with renorm. Unlike `momentum`, this affects training and
should be neither too small (which would add noise) nor too large (which
would give stale estimates). Note that `momentum` is still applied to
get the means and variances for inference.
fused: if `True`, use a faster, fused implementation, or raise a
ValueError if the fused implementation cannot be used. If `None`, use
the faster implementation if possible. If False, do not used the fused
implementation. Note that in TensorFlow 1.x, the meaning of
`fused=True` is different: if `False`, the layer uses the
system-recommended implementation. You cannot use `fused=True` if a
mask is passed in the `call()` method.
trainable: Boolean, if `True` the variables will be marked as trainable.
virtual_batch_size: An `int`. By default, `virtual_batch_size` is `None`,
which means batch normalization is performed across the whole batch.
When `virtual_batch_size` is not `None`, instead perform "Ghost Batch
Normalization", which creates virtual sub-batches which are each
normalized separately (with shared gamma, beta, and moving statistics).
Must divide the actual batch size during execution.
adjustment: A function taking the `Tensor` containing the (dynamic) shape
of the input tensor and returning a pair (scale, bias) to apply to the
normalized values (before gamma and beta), only during training. For
example, if `axis=-1`,
`adjustment = lambda shape: (
tf.random.uniform(shape[-1:], 0.93, 1.07),
tf.random.uniform(shape[-1:], -0.1, 0.1))` will scale the normalized
value by up to 7% up or down, then shift the result by up to 0.1
(with independent scaling and bias for each feature but shared
across all examples), and finally apply gamma and/or beta. If
`None`, no adjustment is applied. Cannot be specified if
virtual_batch_size is specified.
synchronized: If True, synchronizes the global batch statistics (mean and
variance) for the layer across all devices at each training step in a
distributed training strategy. If False, each replica uses its own
local batch statistics. Only relevant when used inside a
`tf.distribute` strategy.
Call arguments:
inputs: Input tensor (of any rank).
training: Python boolean indicating whether the layer should behave in
training mode or in inference mode.
- `training=True`: The layer will normalize its inputs using the mean
and variance of the current batch of inputs.
- `training=False`: The layer will normalize its inputs using the mean
and variance of its moving statistics, learned during training.
mask: Binary tensor of shape broadcastable to `inputs` tensor, indicating
the positions for which the mean and variance should be computed.
Input shape: Arbitrary. Use the keyword argument `input_shape` (tuple of
integers, does not include the samples axis) when using this layer as the
first layer in a model.
Output shape: Same shape as input.
Reference:
- [Ioffe and Szegedy, 2015](https://arxiv.org/abs/1502.03167).
"""
# By default, the base class uses V2 behavior. The BatchNormalization V1
# subclass sets this to False to use the V1 behavior.
_USE_V2_BEHAVIOR = True
def __init__(
self,
axis=-1,
momentum=0.99,
epsilon=1e-3,
center=True,
scale=True,
beta_initializer="zeros",
gamma_initializer="ones",
moving_mean_initializer="zeros",
moving_variance_initializer="ones",
beta_regularizer=None,
gamma_regularizer=None,
beta_constraint=None,
gamma_constraint=None,
renorm=False,
renorm_clipping=None,
renorm_momentum=0.99,
fused=None,
trainable=True,
virtual_batch_size=None,
adjustment=None,
name=None,
synchronized=False,
**kwargs,
):
super().__init__(name=name, **kwargs)
if isinstance(axis, (list, tuple)):
self.axis = axis[:]
elif isinstance(axis, int):
self.axis = axis
else:
raise TypeError(
"Expected an int or a list/tuple of ints for the "
"argument 'axis', but received: %r" % axis
)
if synchronized and fused:
raise ValueError(
"`fused=True` is not supported when `synchronized=True`."
)
self.synchronized = synchronized
if self.synchronized:
fused = False
self.momentum = momentum
self.epsilon = epsilon
self.center = center
self.scale = scale
self.beta_initializer = initializers.get(beta_initializer)
self.gamma_initializer = initializers.get(gamma_initializer)
self.moving_mean_initializer = initializers.get(moving_mean_initializer)
self.moving_variance_initializer = initializers.get(
moving_variance_initializer
)
self.beta_regularizer = regularizers.get(beta_regularizer)
self.gamma_regularizer = regularizers.get(gamma_regularizer)
self.beta_constraint = constraints.get(beta_constraint)
self.gamma_constraint = constraints.get(gamma_constraint)
self.renorm = renorm
self.virtual_batch_size = virtual_batch_size
self.adjustment = adjustment
if self._USE_V2_BEHAVIOR:
if fused:
self._raise_if_fused_cannot_be_used()
# We leave fused as None if self._fused_can_be_used()==True, since
# we still may set it to False in self.build() if the input rank is
# not 4.
elif fused is None and not self._fused_can_be_used():
fused = False
elif fused is None:
fused = True
self.supports_masking = True
self.fused = fused
self._bessels_correction_test_only = True
self.trainable = trainable
if renorm:
renorm_clipping = renorm_clipping or {}
keys = ["rmax", "rmin", "dmax"]
if set(renorm_clipping) - set(keys):
raise ValueError(
"Received invalid keys for `renorm_clipping` argument: "
f"{renorm_clipping}. Supported values: {keys}."
)
self.renorm_clipping = renorm_clipping
self.renorm_momentum = renorm_momentum
def _raise_if_fused_cannot_be_used(self):
"""Raises a ValueError if fused implementation cannot be used.
In addition to the checks done in this function, the input tensors rank
must be 4 or 5. The input rank check can only be done once the input
shape is known.
"""
# Note the ValueErrors in this function are caught and not reraised in
# _fused_can_be_used(). No other exception besides ValueError should be
# raised here.
# Currently fused batch norm doesn't support renorm. It also only
# supports a channel dimension on axis 1 or 3 (rank=4) / 1 or 4 (rank5),
# when no virtual batch size or adjustment is used.
if self.renorm:
raise ValueError(
"Passing both `fused=True` and `renorm=True` is not supported"
)
axis = [self.axis] if isinstance(self.axis, int) else self.axis
# Axis -3 is equivalent to 1, and axis -1 is equivalent to 3, when the
# input rank is 4. Similarly, the valid axis is -4, -1, 1, 4 when the
# rank is 5. The combination of ranks and axes will be checked later.
if len(axis) > 1 or axis[0] not in (-4, -3, -1, 1, 3, 4):
raise ValueError(
"Passing `fused=True` is only supported when axis is 1 "
"or 3 for input rank = 4 or 1 or 4 for input rank = 5. "
"Got axis %s" % (axis,)
)
if self.virtual_batch_size is not None:
raise ValueError(
"Passing `fused=True` is not supported when "
"`virtual_batch_size` is specified."
)
if self.adjustment is not None:
raise ValueError(
"Passing `fused=True` is not supported when "
"`adjustment` is specified."
)
# TODO(reedwm): Support fp64 in FusedBatchNorm then remove this check.
if self._compute_dtype not in ("float16", "bfloat16", "float32", None):
raise ValueError(
"Passing `fused=True` is only supported when the compute "
"dtype is float16, bfloat16, or float32. Got dtype: %s"
% (self._compute_dtype,)
)
def _fused_can_be_used(self):
try:
self._raise_if_fused_cannot_be_used()
return True
except ValueError:
return False
@property
def trainable(self):
return self._trainable
@trainable.setter
def trainable(self, value):
self._trainable = value
@property
def _param_dtype(self):
# Raise parameters of fp16 batch norm to fp32
if self.dtype == tf.float16 or self.dtype == tf.bfloat16:
return tf.float32
else:
return self.dtype or tf.float32
def build(self, input_shape):
self.axis = tf_utils.validate_axis(self.axis, input_shape)
input_shape = tf.TensorShape(input_shape)
rank = input_shape.rank
if self.virtual_batch_size is not None:
if self.virtual_batch_size <= 0:
raise ValueError(
"`virtual_batch_size` must be a positive integer that "
"divides the true batch size of the input tensor. "
f"Received: virtual_batch_size={self.virtual_batch_size}"
)
# If using virtual batches, the first dimension must be the batch
# dimension and cannot be the batch norm axis
if 0 in self.axis:
raise ValueError(
"When using `virtual_batch_size`, the batch dimension "
"must be 0 and thus axis cannot include 0. "
f"Received axis={self.axis}"
)
if self.adjustment is not None:
raise ValueError(
"When using `virtual_batch_size`, adjustment cannot "
"be specified"
)
if self.fused in (None, True):
# TODO(yaozhang): if input is not 4D, reshape it to 4D and reshape
# the output back to its original shape accordingly.
if self._USE_V2_BEHAVIOR:
if self.fused is None:
self.fused = rank in (4, 5)
elif self.fused and rank not in (4, 5):
raise ValueError(
"Batch normalization layers with `fused=True` only "
"support 4D or 5D input tensors. "
f"Received tensor with shape: {tuple(input_shape)}"
)
else:
assert self.fused is not None
self.fused = rank in (4, 5) and self._fused_can_be_used()
# TODO(chrisying): fused batch norm is currently not supported for
# multi-axis batch norm and by extension virtual batches. In some
# cases, it might be possible to use fused batch norm but would
# require reshaping the Tensor to 4D with the axis in 1 or 3
# (preferred 1) which is particularly tricky. A compromise might be
# to just support the most common use case (turning 5D w/ virtual
# batch to NCHW)
if self.fused:
if self.axis == [1] and rank == 4:
self._data_format = "NCHW"
elif self.axis == [1] and rank == 5:
self._data_format = "NCDHW"
elif self.axis == [3] and rank == 4:
self._data_format = "NHWC"
elif self.axis == [4] and rank == 5:
self._data_format = "NDHWC"
elif rank == 5:
# 5D tensors that can be passed in but should not use fused
# batch norm due to unsupported axis.
self.fused = False
else:
if rank == 4:
raise ValueError(
"Unsupported axis. The use of `fused=True` is only "
"possible with `axis=1` or `axis=3` for 4D input "
f"tensors. Received: axis={tuple(self.axis)}"
)
else:
raise ValueError(
"Unsupported axis. The use of `fused=True` is only "
"possible with `axis=1` or `axis=4` for 5D input "
f"tensors. Received: axis={tuple(self.axis)}"
)
axis_to_dim = {x: input_shape.dims[x].value for x in self.axis}
for x in axis_to_dim:
if axis_to_dim[x] is None:
raise ValueError(
"Input has undefined `axis` dimension. Received input "
f"with shape {tuple(input_shape)} "
f"and axis={tuple(self.axis)}"
)
self.input_spec = InputSpec(ndim=rank, axes=axis_to_dim)
if len(axis_to_dim) == 1 and self.virtual_batch_size is None:
# Single axis batch norm (most common/default use-case)
param_shape = (list(axis_to_dim.values())[0],)
else:
# Parameter shape is the original shape but with 1 in all non-axis
# dims
param_shape = [
axis_to_dim[i] if i in axis_to_dim else 1 for i in range(rank)
]
if self.virtual_batch_size is not None:
# When using virtual batches, add an extra dim at index 1
param_shape.insert(1, 1)
for idx, x in enumerate(self.axis):
self.axis[idx] = x + 1 # Account for added dimension
self._param_shape = param_shape
if self.scale:
self.gamma = self.add_weight(
name="gamma",
shape=param_shape,
dtype=self._param_dtype,
initializer=self.gamma_initializer,
regularizer=self.gamma_regularizer,
constraint=self.gamma_constraint,
trainable=True,
experimental_autocast=False,
)
else:
self.gamma = None
if self.center:
self.beta = self.add_weight(
name="beta",
shape=param_shape,
dtype=self._param_dtype,
initializer=self.beta_initializer,
regularizer=self.beta_regularizer,
constraint=self.beta_constraint,
trainable=True,
experimental_autocast=False,
)
else:
self.beta = None
try:
# Disable variable partitioning when creating the moving mean and
# variance
if hasattr(self, "_scope") and self._scope:
partitioner = self._scope.partitioner
self._scope.set_partitioner(None)
else:
partitioner = None
self.moving_mean = self.add_weight(
name="moving_mean",
shape=param_shape,
dtype=self._param_dtype,
initializer=self.moving_mean_initializer,
synchronization=tf.VariableSynchronization.ON_READ,
trainable=False,
aggregation=tf.VariableAggregation.MEAN,
experimental_autocast=False,
)
self.moving_variance = self.add_weight(
name="moving_variance",
shape=param_shape,
dtype=self._param_dtype,
initializer=self.moving_variance_initializer,
synchronization=tf.VariableSynchronization.ON_READ,
trainable=False,
aggregation=tf.VariableAggregation.MEAN,
experimental_autocast=False,
)
if self.renorm:
# In batch renormalization we track the inference moving stddev
# instead of the moving variance to more closely align with the
# paper.
def moving_stddev_initializer(*args, **kwargs):
return tf.sqrt(
self.moving_variance_initializer(*args, **kwargs)
)
with tf.distribute.get_strategy().extended.colocate_vars_with(
self.moving_variance
):
self.moving_stddev = self.add_weight(
name="moving_stddev",
shape=param_shape,
dtype=self._param_dtype,
initializer=moving_stddev_initializer,
synchronization=tf.VariableSynchronization.ON_READ,
trainable=False,
aggregation=tf.VariableAggregation.MEAN,
experimental_autocast=False,
)
# Create variables to maintain the moving mean and standard
# deviation. These are used in training and thus are different
# from the moving averages above. The renorm variables are
# colocated with moving_mean and moving_stddev.
# NOTE: below, the outer `with device` block causes the current
# device stack to be cleared. The nested ones use a `lambda` to
# set the desired device and ignore any devices that may be set
# by the custom getter.
def _renorm_variable(name, shape, initializer="zeros"):
"""Create a renorm variable."""
var = self.add_weight(
name=name,
shape=shape,
dtype=self._param_dtype,
initializer=initializer,
synchronization=tf.VariableSynchronization.ON_READ,
trainable=False,
aggregation=tf.VariableAggregation.MEAN,
experimental_autocast=False,
)
return var
with tf.distribute.get_strategy().extended.colocate_vars_with(
self.moving_mean
):
self.renorm_mean = _renorm_variable(
"renorm_mean", param_shape, self.moving_mean_initializer
)
with tf.distribute.get_strategy().extended.colocate_vars_with(
self.moving_stddev
):
self.renorm_stddev = _renorm_variable(
"renorm_stddev", param_shape, moving_stddev_initializer
)
finally:
if partitioner:
self._scope.set_partitioner(partitioner)
self.built = True
def call(self, inputs, training=None, mask=None):
inputs = tf.cast(inputs, self.compute_dtype)
training = self._get_training_value(training)
# Determine a boolean value for `training`: could be True, False, or
# None.
training_value = control_flow_util.constant_value(training)
_raise_for_non_sync_bn_with_renorm_and_dtensor_strategy(
synchronized=self.synchronized,
training=training,
renorm=self.renorm,
)
if self.virtual_batch_size is not None:
# Virtual batches (aka ghost batches) can be simulated by reshaping
# the Tensor and reusing the existing batch norm implementation
original_shape = tf.shape(inputs)
original_shape = tf.concat(
[tf.constant([-1]), original_shape[1:]], axis=0
)
if tf.__internal__.tf2.enabled():
expanded_shape = (
[self.virtual_batch_size, -1] if training_value else [-1, 1]
)
expanded_shape = tf.concat(
[
tf.constant(expanded_shape),
original_shape[1:],
],
axis=0,
)
else:
# Preserve incorrect legacy behavior for backwards compatibility
expanded_shape = tf.concat(
[
tf.constant([self.virtual_batch_size, -1]),
original_shape[1:],
],
axis=0,
)
# Will cause errors if virtual_batch_size does not divide the batch
# size
inputs = tf.reshape(inputs, expanded_shape)
def undo_virtual_batching(outputs):
outputs = tf.reshape(outputs, original_shape)
return outputs
if self.fused:
outputs = self._fused_batch_norm(
inputs, mask=mask, training=training
)
if self.virtual_batch_size is not None:
# Currently never reaches here since fused_batch_norm does not
# support virtual batching
outputs = undo_virtual_batching(outputs)
return outputs
inputs_dtype = inputs.dtype.base_dtype
if inputs_dtype in (tf.float16, tf.bfloat16):
# Do all math in float32 if given 16-bit inputs for numeric
# stability. In particular, it's very easy for variance to overflow
# in float16 and for safety we also choose to cast bfloat16 to
# float32.
inputs = tf.cast(inputs, tf.float32)
# Compute the axes along which to reduce the mean / variance
input_shape = inputs.shape
ndims = len(input_shape)
reduction_axes = [i for i in range(ndims) if i not in self.axis]
if self.virtual_batch_size is not None:
del reduction_axes[1] # Do not reduce along virtual batch dim
# Broadcasting only necessary for single-axis batch norm where the axis
# is not the last dimension
broadcast_shape = [1] * ndims
broadcast_shape[self.axis[0]] = input_shape.dims[self.axis[0]].value
def _broadcast(v):
if (
v is not None
and len(v.shape) != ndims
and reduction_axes != list(range(ndims - 1))
):
return tf.reshape(v, broadcast_shape)
return v
scale, offset = _broadcast(self.gamma), _broadcast(self.beta)
def _compose_transforms(scale, offset, then_scale, then_offset):
if then_scale is not None:
scale *= then_scale
offset *= then_scale
if then_offset is not None:
offset += then_offset
return (scale, offset)
if training_value == False: # noqa: E712
mean, variance = self.moving_mean, self.moving_variance
else:
# The following long block are handling mean/variance update during
# the training stage in various of different settings.
if self.adjustment:
adj_scale, adj_bias = self.adjustment(tf.shape(inputs))
# Adjust only during training.
adj_scale = control_flow_util.smart_cond(
training, lambda: adj_scale, lambda: tf.ones_like(adj_scale)
)
adj_bias = control_flow_util.smart_cond(
training, lambda: adj_bias, lambda: tf.zeros_like(adj_bias)
)
scale, offset = _compose_transforms(
adj_scale, adj_bias, scale, offset
)
# Some of the computations here are not necessary when
# training==False but not a constant. However, this makes the code
# simpler.
keep_dims = (
self.virtual_batch_size is not None or len(self.axis) > 1
)
mean, variance = self._moments(
tf.cast(inputs, self._param_dtype),
reduction_axes,
keep_dims=keep_dims,
mask=mask,
)
moving_mean = self.moving_mean
moving_variance = self.moving_variance
mean = control_flow_util.smart_cond(
training,
lambda: mean,
lambda: tf.convert_to_tensor(moving_mean),
)
variance = control_flow_util.smart_cond(
training,
lambda: variance,
lambda: tf.convert_to_tensor(moving_variance),
)
if self.virtual_batch_size is not None:
# This isn't strictly correct since in ghost batch norm, you are
# supposed to sequentially update the moving_mean and
# moving_variance with each sub-batch. However, since the moving
# statistics are only used during evaluation, it is more
# efficient to just update in one step and should not make a
# significant difference in the result.
new_mean = tf.reduce_mean(mean, axis=1, keepdims=True)
new_variance = tf.reduce_mean(variance, axis=1, keepdims=True)
else:
if (
utils.running_with_dtensor_strategy()
and not self.synchronized
):
new_mean = tf.math.reduce_mean(mean, axis=reduction_axes)
new_variance = tf.math.reduce_mean(
variance, axis=reduction_axes
)
else:
new_mean, new_variance = mean, variance
if self._support_zero_size_input():
# TF-Keras assumes that batch dimension is the first dimension
# for Batch Normalization.
input_batch_size = tf.shape(inputs)[0]
else:
input_batch_size = None
if self.renorm:
(
r,
d,
new_mean,
new_variance,
) = self._renorm_correction_and_moments(
new_mean, new_variance, training, input_batch_size
)
# When training, the normalized values (say, x) will be
# transformed as x * gamma + beta without renorm, and (x * r +
# d) * gamma + beta = x * (r * gamma) + (d * gamma + beta) with
# renorm.
r = _broadcast(tf.stop_gradient(r, name="renorm_r"))
d = _broadcast(tf.stop_gradient(d, name="renorm_d"))
scale, offset = _compose_transforms(r, d, scale, offset)
def _do_update(var, value):
"""Compute the updates for mean and variance."""
return self._assign_moving_average(
var, value, self.momentum, input_batch_size
)
def mean_update():
true_branch = lambda: _do_update(self.moving_mean, new_mean)
false_branch = lambda: self.moving_mean
return control_flow_util.smart_cond(
training, true_branch, false_branch
)
def variance_update():
"""Update the moving variance."""
def true_branch_renorm():
# We apply epsilon as part of the moving_stddev to mirror
# the training code path.
moving_stddev = _do_update(
self.moving_stddev, tf.sqrt(new_variance + self.epsilon)
)
return self._assign_new_value(
self.moving_variance,
# Apply relu in case floating point rounding causes it
# to go negative.
backend.relu(
moving_stddev * moving_stddev - self.epsilon
),
)
if self.renorm:
true_branch = true_branch_renorm
else:
true_branch = lambda: _do_update(
self.moving_variance, new_variance
)
false_branch = lambda: self.moving_variance
return control_flow_util.smart_cond(
training, true_branch, false_branch
)
self.add_update(mean_update)
self.add_update(variance_update)
# End of handling mean/variance calculation and update.
mean = tf.cast(mean, inputs.dtype)
variance = tf.cast(variance, inputs.dtype)
if offset is not None:
offset = tf.cast(offset, inputs.dtype)
if scale is not None:
scale = tf.cast(scale, inputs.dtype)
outputs = tf.nn.batch_normalization(
inputs,
_broadcast(mean),
_broadcast(variance),
offset,
scale,
self.epsilon,
)
if inputs_dtype in (tf.float16, tf.bfloat16):
outputs = tf.cast(outputs, inputs_dtype)
# If some components of the shape got lost due to adjustments, fix that.
outputs.set_shape(input_shape)
if self.virtual_batch_size is not None:
outputs = undo_virtual_batching(outputs)
return outputs
def compute_output_shape(self, input_shape):
return input_shape
def get_config(self):
config = {
"axis": self.axis,
"momentum": self.momentum,
"epsilon": self.epsilon,
"center": self.center,
"scale": self.scale,
"beta_initializer": initializers.serialize(self.beta_initializer),
"gamma_initializer": initializers.serialize(self.gamma_initializer),
"moving_mean_initializer": initializers.serialize(
self.moving_mean_initializer
),
"moving_variance_initializer": initializers.serialize(
self.moving_variance_initializer
),
"beta_regularizer": regularizers.serialize(self.beta_regularizer),
"gamma_regularizer": regularizers.serialize(self.gamma_regularizer),
"beta_constraint": constraints.serialize(self.beta_constraint),
"gamma_constraint": constraints.serialize(self.gamma_constraint),
}
# Only add TensorFlow-specific parameters if they are set, so as to
# preserve model compatibility with external TF-Keras.
if self.renorm:
config["renorm"] = True
config["renorm_clipping"] = self.renorm_clipping
config["renorm_momentum"] = self.renorm_momentum
if self.virtual_batch_size is not None:
config["virtual_batch_size"] = self.virtual_batch_size
# Note: adjustment is not serializable.
if self.adjustment is not None:
logging.warning(
"The `adjustment` function of this `BatchNormalization` "
"layer cannot be serialized and has been omitted from "
"the layer config. It will not be included when "
"re-creating the layer from the saved config."
)
base_config = super().get_config()
return dict(list(base_config.items()) + list(config.items()))
######################## Start of private methods ##########################
def _support_zero_size_input(self):
if not tf.distribute.has_strategy():
return False
strategy = tf.distribute.get_strategy()
# TODO(b/195085185): remove experimental_enable_get_next_as_optional
# after migrating all users.
return getattr(
strategy.extended,
"enable_partial_batch_handling",
getattr(
strategy.extended,
"experimental_enable_get_next_as_optional",
False,
),
)
def _assign_moving_average(self, variable, value, momentum, inputs_size):
def calculate_update_delta():
decay = tf.convert_to_tensor(1.0 - momentum, name="decay")
if decay.dtype != variable.dtype.base_dtype:
decay = tf.cast(decay, variable.dtype.base_dtype)
update_delta = (variable - tf.cast(value, variable.dtype)) * decay
if inputs_size is not None:
update_delta = tf.where(
inputs_size > 0,
update_delta,
backend.zeros_like(update_delta),
)
return update_delta
with backend.name_scope("AssignMovingAvg") as scope:
if tf.compat.v1.executing_eagerly_outside_functions():
return variable.assign_sub(calculate_update_delta(), name=scope)
else:
with tf.compat.v1.colocate_with(variable):
return tf.compat.v1.assign_sub(
variable, calculate_update_delta(), name=scope
)
def _assign_new_value(self, variable, value):
with backend.name_scope("AssignNewValue") as scope:
if tf.compat.v1.executing_eagerly_outside_functions():
return variable.assign(value, name=scope)
else:
with tf.compat.v1.colocate_with(variable):
return tf.compat.v1.assign(variable, value, name=scope)
def _fused_batch_norm(self, inputs, mask, training):
"""Returns the output of fused batch norm."""
if mask is not None:
warnings.warn(
"Masking is not supported with `fused=True`. "
"You should either turn off fusing "
"(`fused=False`) or you should not pass a `mask` "
"argument when calling the layer. "
"For the moment `mask` will be ignored for the "
"normalization."
)
if self.center:
beta = self.beta
else:
beta = backend.constant(
0.0, dtype=self._param_dtype, shape=self._param_shape
)
if self.scale:
gamma = self.gamma
else:
gamma = backend.constant(
1.0, dtype=self._param_dtype, shape=self._param_shape
)
# TODO(b/129279393): Support zero batch input in non
# DistributionStrategy code as well.
if self._support_zero_size_input():
# TF-Keras assumes that batch dimension is the first dimension for
# Batch Normalization.
input_batch_size = tf.shape(inputs)[0]
else:
input_batch_size = None
# TODO(rmlarsen): Support using fused avg updates for non-eager
# execution after fixing graph pattern matching and enabling
# fused_batch_norm to take exponential_avg_factor as a tensor input.
use_fused_avg_updates = (
tf.compat.v1.executing_eagerly_outside_functions()
and isinstance(self.momentum, (float, int))
and get_enclosing_xla_context() is None
)
if use_fused_avg_updates:
exponential_avg_factor = 1.0 - self.momentum
else:
exponential_avg_factor = None
def _maybe_add_or_remove_bessels_correction(variance, remove=True):
r"""Add or remove Bessel's correction."""
# Removes Bessel's correction if remove == True, adds it otherwise.
# This is to be consistent with non-fused batch norm. Note that the
# variance computed by fused batch norm is with Bessel's correction.
# This is only used in legacy V1 batch norm tests.
if self._bessels_correction_test_only:
return variance
sample_size = tf.cast(
tf.size(inputs) / tf.size(variance), variance.dtype
)
if remove:
factor = (
sample_size - tf.cast(1.0, variance.dtype)
) / sample_size
else:
factor = sample_size / (
sample_size - tf.cast(1.0, variance.dtype)
)
return variance * factor
def _fused_batch_norm_training():
return tf.compat.v1.nn.fused_batch_norm(
inputs,
gamma,
beta,
mean=self.moving_mean,
variance=_maybe_add_or_remove_bessels_correction(
self.moving_variance, remove=False
),
epsilon=self.epsilon,
is_training=True,
data_format=self._data_format,
exponential_avg_factor=exponential_avg_factor,
)
def _fused_batch_norm_inference():
return tf.compat.v1.nn.fused_batch_norm(
inputs,
gamma,
beta,
mean=self.moving_mean,
variance=self.moving_variance,
epsilon=self.epsilon,
is_training=False,
data_format=self._data_format,
)
output, mean, variance = control_flow_util.smart_cond(
training, _fused_batch_norm_training, _fused_batch_norm_inference
)
variance = _maybe_add_or_remove_bessels_correction(
variance, remove=True
)
training_value = control_flow_util.constant_value(training)
if training_value or training_value is None:
if not use_fused_avg_updates:
if training_value is None:
momentum = control_flow_util.smart_cond(
training, lambda: self.momentum, lambda: 1.0
)
else:
momentum = tf.convert_to_tensor(self.momentum)
def mean_update():
"""Update self.moving_mean with the most recent data point."""
if use_fused_avg_updates:
if input_batch_size is not None:
new_mean = control_flow_util.smart_cond(
input_batch_size > 0,
lambda: mean,
lambda: self.moving_mean,
)
else:
new_mean = mean
return self._assign_new_value(self.moving_mean, new_mean)
else:
return self._assign_moving_average(
self.moving_mean, mean, momentum, input_batch_size
)
def variance_update():
"""Update self.moving_variance with the most recent data
point."""
if use_fused_avg_updates:
if input_batch_size is not None:
new_variance = control_flow_util.smart_cond(
input_batch_size > 0,
lambda: variance,
lambda: self.moving_variance,
)
else:
new_variance = variance
return self._assign_new_value(
self.moving_variance, new_variance
)
else:
return self._assign_moving_average(
self.moving_variance,
variance,
momentum,
input_batch_size,
)
self.add_update(mean_update)
self.add_update(variance_update)
return output
def _renorm_correction_and_moments(
self, mean, variance, training, inputs_size
):
"""Returns the correction and update values for renorm."""
stddev = tf.sqrt(variance + self.epsilon)
# Compute the average mean and standard deviation, as if they were
# initialized with this batch's moments.
renorm_mean = self.renorm_mean
# Avoid divide by zero early on in training.
renorm_stddev = tf.maximum(self.renorm_stddev, tf.sqrt(self.epsilon))
# Compute the corrections for batch renorm.
r = stddev / renorm_stddev
d = (mean - renorm_mean) / renorm_stddev
# Ensure the corrections use pre-update moving averages.
with tf.control_dependencies([r, d]):
mean = tf.identity(mean)
stddev = tf.identity(stddev)
rmin, rmax, dmax = [
self.renorm_clipping.get(key) for key in ["rmin", "rmax", "dmax"]
]
if rmin is not None:
r = tf.maximum(r, rmin)
if rmax is not None:
r = tf.minimum(r, rmax)
if dmax is not None:
d = tf.maximum(d, -dmax)
d = tf.minimum(d, dmax)
# When not training, use r=1, d=0.
r = control_flow_util.smart_cond(
training, lambda: r, lambda: tf.ones_like(r)
)
d = control_flow_util.smart_cond(
training, lambda: d, lambda: tf.zeros_like(d)
)
def _update_renorm_variable(var, value, inputs_size):
"""Updates a moving average and weight, returns the unbiased
value."""
value = tf.identity(value)
def _do_update():
"""Updates the var, returns the updated value."""
new_var = self._assign_moving_average(
var, value, self.renorm_momentum, inputs_size
)
return new_var
def _fake_update():
return tf.identity(var)
return control_flow_util.smart_cond(
training, _do_update, _fake_update
)
# TODO(yuefengz): colocate the operations
update_new_mean = _update_renorm_variable(
self.renorm_mean, mean, inputs_size
)
update_new_stddev = _update_renorm_variable(
self.renorm_stddev, stddev, inputs_size
)
# Update the inference mode moving averages with the batch value.
with tf.control_dependencies([update_new_mean, update_new_stddev]):
out_mean = tf.identity(mean)
out_variance = tf.identity(variance)
return (r, d, out_mean, out_variance)
def _calculate_mean_and_var(
self, inputs, reduction_axes, keep_dims, mask=None
):
if self.synchronized:
return self._sync_calculate_mean_and_var(
inputs, reduction_axes, keep_dims, mask=mask
)
return self._no_sync_calculate_mean_and_var(
inputs, reduction_axes, keep_dims, mask=mask
)
def _no_sync_calculate_mean_and_var(
self, inputs, reduction_axes, keep_dims, mask=None
):
if mask is None:
return tf.nn.moments(inputs, reduction_axes, keepdims=keep_dims)
else:
mask_weights = tf.cast(
mask, self.compute_dtype, name="mask_weights"
)
mask_weights = tf.expand_dims(
mask_weights, axis=-1, name="mask_weights_broadcasted"
)
return tf.nn.weighted_moments(
inputs,
axes=reduction_axes,
frequency_weights=mask_weights,
keepdims=keep_dims,
)
def _sync_calculate_mean_and_var(
self, x, reduction_axes, keep_dims, mask=None
):
with backend.name_scope("moments"):
# The dynamic range of fp16 is too limited to support the collection
# of sufficient statistics. As a workaround we simply perform the
# operations on 32-bit floats before converting the mean and
# variance back to fp16
y = tf.cast(x, tf.float32) if x.dtype == tf.float16 else x
replica_ctx = tf.distribute.get_replica_context()
if not replica_ctx:
return self._no_sync_calculate_mean_and_var(
x, reduction_axes, keep_dims, mask=mask
)
if mask is not None:
mask_weights = tf.cast(mask, y.dtype, name="mask_weights")
mask_weights = tf.expand_dims(
mask_weights, axis=-1, name="mask_weights_broadcasted"
)
y *= mask_weights
local_count = tf.broadcast_to(
mask_weights, tf.shape(y), name="count"
)
else:
local_count = tf.ones_like(y, name="count")
local_sum = tf.reduce_sum(y, axis=reduction_axes, keepdims=True)
local_squared_sum = tf.reduce_sum(
tf.square(y), axis=reduction_axes, keepdims=True
)
local_count = tf.reduce_sum(
local_count, axis=reduction_axes, keepdims=True
)
# TODO(b/163099951): batch the all-reduces once we sort out the
# ordering issue for NCCL. We don't have a mechanism to launch
# NCCL in the same order in each replica nowadays, so we limit
# NCCL to batch all-reduces.
y_sum = replica_ctx.all_reduce(
tf.distribute.ReduceOp.SUM, local_sum
)
y_squared_sum = replica_ctx.all_reduce(
tf.distribute.ReduceOp.SUM, local_squared_sum
)
count_sum = replica_ctx.all_reduce(
tf.distribute.ReduceOp.SUM, local_count
)
mean = tf.math.divide_no_nan(y_sum, count_sum)
y_squared_mean = tf.math.divide_no_nan(y_squared_sum, count_sum)
# var = E(x^2) - E(x)^2
# The substraction operation does not guarantee a non-negative
# result given float precision operations.
variance = tf.maximum(y_squared_mean - tf.square(mean), 0.0)
if not keep_dims:
mean = tf.squeeze(mean, reduction_axes)
variance = tf.squeeze(variance, reduction_axes)
if x.dtype == tf.float16:
return (
tf.cast(mean, tf.float16),
tf.cast(variance, tf.float16),
)
else:
return (mean, variance)
def _dtensor_calculate_mean_and_var(
self, inputs, reduction_axes, keep_dims, mask=None
):
if self.synchronized:
return self._dtensor_sync_calculate_mean_and_var(
inputs, reduction_axes, keep_dims, mask=mask
)
return self._dtensor_no_sync_calculate_mean_and_var(
inputs, reduction_axes, keep_dims, mask=mask
)
def _dtensor_no_sync_calculate_mean_and_var(
self, inputs, reduction_axes, keep_dims, mask=None
):
replica_tensor = _expand_tensor_with_local_replica_group(inputs)
local_batch_size = tf.shape(replica_tensor)[1]
# Since we added a new axis in the beginning, all the value in
# reduction_axes need to be incremented by 1.
updated_reduction_axes = [n + 1 for n in reduction_axes]
if mask is None:
mean, var = tf.nn.moments(
replica_tensor, updated_reduction_axes, keepdims=keep_dims
)
else:
mask_weights = tf.cast(
mask, self.compute_dtype, name="mask_weights"
)
mask_weights = tf.expand_dims(
mask_weights, axis=-1, name="mask_weights_broadcasted"
)
mask_weights = _expand_tensor_with_local_replica_group(mask_weights)
mean, var = tf.nn.weighted_moments(
replica_tensor,
axes=updated_reduction_axes,
frequency_weights=mask_weights,
keepdims=keep_dims,
)
# Also note that the mean/var we have here will have an extra dim in
# axis 0, which is represented for num local replica. Down the
# stream, the mean/var will be used to update the moving_mean/var
# and also normalize the inputs. To make the shape match, we will
# expand the tensor shape from [num_replica, x, y] to
# [batch_size, x, y] so that it can be properly used for
# normalization. When it reaches the mean/var update, a separate
# logic will be there to reduce_mean the value based on the batch
# dim.
mean = tf.repeat(mean, local_batch_size, axis=0)
var = tf.repeat(var, local_batch_size, axis=0)
if not keep_dims:
# We need to fill the reduced dims so that the mean/var can be
# properly broadcast to the input shapes. In the example above,
# the original reduction_axes is [0, 1]. We ignore the first 0
# (batch dim) here since we already expand and use it as num_replica
for dim in reduction_axes[1:]:
mean = tf.expand_dims(mean, axis=dim)
var = tf.expand_dims(var, axis=dim)
return mean, var
def _dtensor_sync_calculate_mean_and_var(
self, inputs, reduction_axes, keep_dims, mask=None
):
# In the DTensor sync BN, since the input tensor is already in global
# context, we just need to use the normal moments/weighted_moments
# to calculate mean/var, which is same as the non-sync BN in the normal
# mode.
return self._no_sync_calculate_mean_and_var(
inputs, reduction_axes, keep_dims, mask
)
def _moments(self, inputs, reduction_axes, keep_dims, mask=None):
if utils.running_with_dtensor_strategy():
mean, variance = self._dtensor_calculate_mean_and_var(
inputs, reduction_axes, keep_dims, mask=mask
)
else:
mean, variance = self._calculate_mean_and_var(
inputs, reduction_axes, keep_dims, mask=mask
)
# TODO(b/129279393): Support zero batch input in non
# DistributionStrategy code as well.
if self._support_zero_size_input():
input_batch_size = tf.shape(inputs)[0]
mean = tf.where(
input_batch_size > 0, mean, backend.zeros_like(mean)
)
variance = tf.where(
input_batch_size > 0, variance, backend.zeros_like(variance)
)
return mean, variance
def _get_training_value(self, training=None):
if training is None:
training = backend.learning_phase()
if self._USE_V2_BEHAVIOR:
if isinstance(training, int):
training = bool(training)
if not self.trainable:
# When the layer is not trainable, it overrides the value passed
# from model.
training = False
return training
@keras_export("keras.layers.BatchNormalization", v1=[])
class BatchNormalization(BatchNormalizationBase):
"""Layer that normalizes its inputs.
Batch normalization applies a transformation that maintains the mean output
close to 0 and the output standard deviation close to 1.
Importantly, batch normalization works differently during training and
during inference.
**During training** (i.e. when using `fit()` or when calling the layer/model
with the argument `training=True`), the layer normalizes its output using
the mean and standard deviation of the current batch of inputs. That is to
say, for each channel being normalized, the layer returns
`gamma * (batch - mean(batch)) / sqrt(var(batch) + epsilon) + beta`, where:
- `epsilon` is small constant (configurable as part of the constructor
arguments)
- `gamma` is a learned scaling factor (initialized as 1), which
can be disabled by passing `scale=False` to the constructor.
- `beta` is a learned offset factor (initialized as 0), which
can be disabled by passing `center=False` to the constructor.
**During inference** (i.e. when using `evaluate()` or `predict()` or when
calling the layer/model with the argument `training=False` (which is the
default), the layer normalizes its output using a moving average of the
mean and standard deviation of the batches it has seen during training. That
is to say, it returns
`gamma * (batch - self.moving_mean) / sqrt(self.moving_var+epsilon) + beta`.
`self.moving_mean` and `self.moving_var` are non-trainable variables that
are updated each time the layer in called in training mode, as such:
- `moving_mean = moving_mean * momentum + mean(batch) * (1 - momentum)`
- `moving_var = moving_var * momentum + var(batch) * (1 - momentum)`
As such, the layer will only normalize its inputs during inference
*after having been trained on data that has similar statistics as the
inference data*.
When `synchronized=True` is set and if this layer is used within a
`tf.distribute` strategy, there will be an `allreduce` call
to aggregate batch statistics across all replicas at every
training step. Setting `synchronized` has no impact when the model is
trained without specifying any distribution strategy.
Example usage:
```python
strategy = tf.distribute.MirroredStrategy()
with strategy.scope():
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(16))
model.add(tf.keras.layers.BatchNormalization(synchronized=True))
```
Args:
axis: Integer, the axis that should be normalized (typically the features
axis). For instance, after a `Conv2D` layer with
`data_format="channels_first"`, set `axis=1` in `BatchNormalization`.
momentum: Momentum for the moving average.
epsilon: Small float added to variance to avoid dividing by zero.
center: If True, add offset of `beta` to normalized tensor. If False,
`beta` is ignored.
scale: If True, multiply by `gamma`. If False, `gamma` is not used. When
the next layer is linear (also e.g. `nn.relu`), this can be disabled
since the scaling will be done by the next layer.
beta_initializer: Initializer for the beta weight.
gamma_initializer: Initializer for the gamma weight.
moving_mean_initializer: Initializer for the moving mean.
moving_variance_initializer: Initializer for the moving variance.
beta_regularizer: Optional regularizer for the beta weight.
gamma_regularizer: Optional regularizer for the gamma weight.
beta_constraint: Optional constraint for the beta weight.
gamma_constraint: Optional constraint for the gamma weight.
synchronized: If True, synchronizes the global batch statistics (mean and
variance) for the layer across all devices at each training step in a
distributed training strategy. If False, each replica uses its own
local batch statistics. Only relevant when used inside a
`tf.distribute` strategy.
Call arguments:
inputs: Input tensor (of any rank).
training: Python boolean indicating whether the layer should behave in
training mode or in inference mode.
- `training=True`: The layer will normalize its inputs using the mean
and variance of the current batch of inputs.
- `training=False`: The layer will normalize its inputs using the mean
and variance of its moving statistics, learned during training.
Input shape:
Arbitrary. Use the keyword argument `input_shape` (tuple of
integers, does not include the samples axis) when using this layer as the
first layer in a model.
Output shape:
Same shape as input.
Reference:
- [Ioffe and Szegedy, 2015](https://arxiv.org/abs/1502.03167).
**About setting `layer.trainable = False` on a `BatchNormalization` layer:**
The meaning of setting `layer.trainable = False` is to freeze the layer,
i.e. its internal state will not change during training:
its trainable weights will not be updated
during `fit()` or `train_on_batch()`, and its state updates will not be run.
Usually, this does not necessarily mean that the layer is run in inference
mode (which is normally controlled by the `training` argument that can
be passed when calling a layer). "Frozen state" and "inference mode"
are two separate concepts.
However, in the case of the `BatchNormalization` layer, **setting
`trainable = False` on the layer means that the layer will be
subsequently run in inference mode** (meaning that it will use
the moving mean and the moving variance to normalize the current batch,
rather than using the mean and variance of the current batch).
This behavior has been introduced in TensorFlow 2.0, in order
to enable `layer.trainable = False` to produce the most commonly
expected behavior in the convnet fine-tuning use case.
Note that:
- Setting `trainable` on an model containing other layers will
recursively set the `trainable` value of all inner layers.
- If the value of the `trainable`
attribute is changed after calling `compile()` on a model,
the new value doesn't take effect for this model
until `compile()` is called again.
"""
_USE_V2_BEHAVIOR = True
@utils.allow_initializer_layout
def __init__(
self,
axis=-1,
momentum=0.99,
epsilon=1e-3,
center=True,
scale=True,
beta_initializer="zeros",
gamma_initializer="ones",
moving_mean_initializer="zeros",
moving_variance_initializer="ones",
beta_regularizer=None,
gamma_regularizer=None,
beta_constraint=None,
gamma_constraint=None,
synchronized=False,
**kwargs,
):
# Currently we only support aggregating over the global batch size.
super().__init__(
axis=axis,
momentum=momentum,
epsilon=epsilon,
center=center,
scale=scale,
beta_initializer=beta_initializer,
gamma_initializer=gamma_initializer,
moving_mean_initializer=moving_mean_initializer,
moving_variance_initializer=moving_variance_initializer,
beta_regularizer=beta_regularizer,
gamma_regularizer=gamma_regularizer,
beta_constraint=beta_constraint,
gamma_constraint=gamma_constraint,
synchronized=synchronized,
**kwargs,
)
@keras_export("keras.layers.experimental.SyncBatchNormalization", v1=[])
@deprecation.deprecated_endpoints(
"keras.layers.experimental.SyncBatchNormalization"
)
class SyncBatchNormalization(BatchNormalizationBase):
"""Deprecated. Please use `tf.keras.layers.BatchNormalization` instead.
Caution: `tf.keras.layers.experimental.SyncBatchNormalization` endpoint is
deprecated and will be removed in a future release. Please use
`tf.keras.layers.BatchNormalization` with parameter `synchronized`
set to True
"""
def __init__(
self,
axis=-1,
momentum=0.99,
epsilon=1e-3,
center=True,
scale=True,
beta_initializer="zeros",
gamma_initializer="ones",
moving_mean_initializer="zeros",
moving_variance_initializer="ones",
beta_regularizer=None,
gamma_regularizer=None,
beta_constraint=None,
gamma_constraint=None,
**kwargs,
):
warning = (
"`tf.keras.layers.experimental.SyncBatchNormalization` endpoint is "
"deprecated and will be removed in a future release. Please use "
"`tf.keras.layers.BatchNormalization` with parameter "
"`synchronized` set to True."
)
logging.log_first_n(logging.WARN, warning, 1)
super().__init__(
axis=axis,
momentum=momentum,
epsilon=epsilon,
center=center,
scale=scale,
beta_initializer=beta_initializer,
gamma_initializer=gamma_initializer,
moving_mean_initializer=moving_mean_initializer,
moving_variance_initializer=moving_variance_initializer,
beta_regularizer=beta_regularizer,
gamma_regularizer=gamma_regularizer,
beta_constraint=beta_constraint,
gamma_constraint=gamma_constraint,
synchronized=True,
**kwargs,
)
def _expand_tensor_with_local_replica_group(inputs):
"""Reshape the input tensor to have an extra dimension of replica group.
Under the DTensor usage, the normal batch norm still need to perform on
a local batch size, which mean we can't directly do mean/var on a global
tensor. In order to do a local mean/var, we have to add a new dimention to
the tensor, so that the ops will not cross the replica boundary. E.g,
a global tensor with shape [8, x, y] and has 2 local replica, the output of
this will be [2, 4, x, y], where the first dim is for num of replica, and
the second dim is for the local batch size. The follow ops can do reduces
among the local batch dimension.
Note that this function should only be used under DTensor based strategy,
and it will use the current strategy in the context to get the number of
replica.
Args:
inputs: Tensor with shape [global_batch_size, ...]
Returns:
Tensor with shape [num_replica, local_batch_size, ...]
"""
# TODO(b/272382109): Implement this an an Op.
input_shape = tf.shape(inputs)
global_batch_size = input_shape[0]
num_replica = tf.distribute.get_strategy().num_replicas_in_sync
local_batch_size = global_batch_size // num_replica
replica_shape = tf.stack([num_replica, local_batch_size])
replica_shape = tf.concat([replica_shape, input_shape[1:]], axis=0)
return tf.reshape(inputs, replica_shape)
def _raise_for_non_sync_bn_with_renorm_and_dtensor_strategy(
synchronized, training, renorm
):
if (
utils.running_with_dtensor_strategy()
and not synchronized
and training == True
and renorm
):
raise NotImplementedError(
"Renorm for BatchNormalization under DTensor based distribution "
"strategy is not supported at the moment. Please file a feature "
"request if this is blocking your adoption."
)
| tf-keras/tf_keras/layers/normalization/batch_normalization.py/0 | {
"file_path": "tf-keras/tf_keras/layers/normalization/batch_normalization.py",
"repo_id": "tf-keras",
"token_count": 31586
} | 182 |
# Copyright 2015 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.
# ==============================================================================
"""Average pooling 3D layer."""
import tensorflow.compat.v2 as tf
from tf_keras.layers.pooling.base_pooling3d import Pooling3D
# isort: off
from tensorflow.python.util.tf_export import keras_export
@keras_export("keras.layers.AveragePooling3D", "keras.layers.AvgPool3D")
class AveragePooling3D(Pooling3D):
"""Average pooling operation for 3D data (spatial or spatio-temporal).
Downsamples the input along its spatial dimensions (depth, height, and
width) by taking the average value over an input window
(of size defined by `pool_size`) for each channel of the input.
The window is shifted by `strides` along each dimension.
Args:
pool_size: tuple of 3 integers,
factors by which to downscale (dim1, dim2, dim3).
`(2, 2, 2)` will halve the size of the 3D input in each dimension.
strides: tuple of 3 integers, or None. Strides values.
padding: One of `"valid"` or `"same"` (case-insensitive).
`"valid"` means no padding. `"same"` results in padding evenly to
the left/right or up/down of the input such that output has the same
height/width dimension as the input.
data_format: A string,
one of `channels_last` (default) or `channels_first`.
The ordering of the dimensions in the inputs.
`channels_last` corresponds to inputs with shape
`(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)`
while `channels_first` corresponds to inputs with shape
`(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.
When unspecified, uses
`image_data_format` value found in your TF-Keras config file at
`~/.keras/keras.json` (if exists) else 'channels_last'.
Defaults to 'channels_last'.
Input shape:
- If `data_format='channels_last'`:
5D tensor with shape:
`(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`
- If `data_format='channels_first'`:
5D tensor with shape:
`(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`
Output shape:
- If `data_format='channels_last'`:
5D tensor with shape:
`(batch_size, pooled_dim1, pooled_dim2, pooled_dim3, channels)`
- If `data_format='channels_first'`:
5D tensor with shape:
`(batch_size, channels, pooled_dim1, pooled_dim2, pooled_dim3)`
Example:
```python
depth = 30
height = 30
width = 30
input_channels = 3
inputs = tf.keras.Input(shape=(depth, height, width, input_channels))
layer = tf.keras.layers.AveragePooling3D(pool_size=3)
outputs = layer(inputs) # Shape: (batch_size, 10, 10, 10, 3)
```
"""
def __init__(
self,
pool_size=(2, 2, 2),
strides=None,
padding="valid",
data_format=None,
**kwargs
):
super().__init__(
tf.nn.avg_pool3d,
pool_size=pool_size,
strides=strides,
padding=padding,
data_format=data_format,
**kwargs
)
# Alias
AvgPool3D = AveragePooling3D
| tf-keras/tf_keras/layers/pooling/average_pooling3d.py/0 | {
"file_path": "tf-keras/tf_keras/layers/pooling/average_pooling3d.py",
"repo_id": "tf-keras",
"token_count": 1468
} | 183 |
# Copyright 2015 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.
# ==============================================================================
"""Max pooling 1D layer."""
import functools
from tf_keras import backend
from tf_keras.layers.pooling.base_pooling1d import Pooling1D
# isort: off
from tensorflow.python.util.tf_export import keras_export
@keras_export("keras.layers.MaxPooling1D", "keras.layers.MaxPool1D")
class MaxPooling1D(Pooling1D):
"""Max pooling operation for 1D temporal data.
Downsamples the input representation by taking the maximum value over a
spatial window of size `pool_size`. The window is shifted by `strides`. The
resulting output, when using the `"valid"` padding option, has a shape of:
`output_shape = (input_shape - pool_size + 1) / strides)`
The resulting output shape when using the `"same"` padding option is:
`output_shape = input_shape / strides`
For example, for `strides=1` and `padding="valid"`:
>>> x = tf.constant([1., 2., 3., 4., 5.])
>>> x = tf.reshape(x, [1, 5, 1])
>>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2,
... strides=1, padding='valid')
>>> max_pool_1d(x)
<tf.Tensor: shape=(1, 4, 1), dtype=float32, numpy=
array([[[2.],
[3.],
[4.],
[5.]]], dtype=float32)>
For example, for `strides=2` and `padding="valid"`:
>>> x = tf.constant([1., 2., 3., 4., 5.])
>>> x = tf.reshape(x, [1, 5, 1])
>>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2,
... strides=2, padding='valid')
>>> max_pool_1d(x)
<tf.Tensor: shape=(1, 2, 1), dtype=float32, numpy=
array([[[2.],
[4.]]], dtype=float32)>
For example, for `strides=1` and `padding="same"`:
>>> x = tf.constant([1., 2., 3., 4., 5.])
>>> x = tf.reshape(x, [1, 5, 1])
>>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2,
... strides=1, padding='same')
>>> max_pool_1d(x)
<tf.Tensor: shape=(1, 5, 1), dtype=float32, numpy=
array([[[2.],
[3.],
[4.],
[5.],
[5.]]], dtype=float32)>
Args:
pool_size: Integer, size of the max pooling window.
strides: Integer, or None. Specifies how much the pooling window moves
for each pooling step.
If None, it will default to `pool_size`.
padding: One of `"valid"` or `"same"` (case-insensitive).
`"valid"` means no padding. `"same"` results in padding evenly to
the left/right or up/down of the input such that output has the same
height/width dimension as the input.
data_format: A string,
one of `channels_last` (default) or `channels_first`.
The ordering of the dimensions in the inputs.
`channels_last` corresponds to inputs with shape
`(batch, steps, features)` while `channels_first`
corresponds to inputs with shape
`(batch, features, steps)`.
Input shape:
- If `data_format='channels_last'`:
3D tensor with shape `(batch_size, steps, features)`.
- If `data_format='channels_first'`:
3D tensor with shape `(batch_size, features, steps)`.
Output shape:
- If `data_format='channels_last'`:
3D tensor with shape `(batch_size, downsampled_steps, features)`.
- If `data_format='channels_first'`:
3D tensor with shape `(batch_size, features, downsampled_steps)`.
"""
def __init__(
self,
pool_size=2,
strides=None,
padding="valid",
data_format="channels_last",
**kwargs
):
super().__init__(
functools.partial(backend.pool2d, pool_mode="max"),
pool_size=pool_size,
strides=strides,
padding=padding,
data_format=data_format,
**kwargs
)
# Alias
MaxPool1D = MaxPooling1D
| tf-keras/tf_keras/layers/pooling/max_pooling1d.py/0 | {
"file_path": "tf-keras/tf_keras/layers/pooling/max_pooling1d.py",
"repo_id": "tf-keras",
"token_count": 1827
} | 184 |
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Keras discretization preprocessing layer."""
import numpy as np
import tensorflow.compat.v2 as tf
from tf_keras import backend
from tf_keras.engine import base_preprocessing_layer
from tf_keras.layers.preprocessing import preprocessing_utils as utils
from tf_keras.utils import layer_utils
from tf_keras.utils import tf_utils
# isort: off
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util.tf_export import keras_export
INT = utils.INT
MULTI_HOT = utils.MULTI_HOT
ONE_HOT = utils.ONE_HOT
COUNT = utils.COUNT
def summarize(values, epsilon):
"""Reduce a 1D sequence of values to a summary.
This algorithm is based on numpy.quantiles but modified to allow for
intermediate steps between multiple data sets. It first finds the target
number of bins as the reciprocal of epsilon and then takes the individual
values spaced at appropriate intervals to arrive at that target.
The final step is to return the corresponding counts between those values
If the target num_bins is larger than the size of values, the whole array is
returned (with weights of 1).
Args:
values: 1D `np.ndarray` to be summarized.
epsilon: A `'float32'` that determines the approximate desired
precision.
Returns:
A 2D `np.ndarray` that is a summary of the inputs. First column is the
interpolated partition values, the second is the weights (counts).
"""
values = tf.reshape(values, [-1])
values = tf.sort(values)
elements = tf.cast(tf.size(values), tf.float32)
num_buckets = 1.0 / epsilon
increment = tf.cast(elements / num_buckets, tf.int32)
start = increment
step = tf.maximum(increment, 1)
boundaries = values[start::step]
weights = tf.ones_like(boundaries)
weights = weights * tf.cast(step, tf.float32)
return tf.stack([boundaries, weights])
def compress(summary, epsilon):
"""Compress a summary to within `epsilon` accuracy.
The compression step is needed to keep the summary sizes small after
merging, and also used to return the final target boundaries. It finds the
new bins based on interpolating cumulative weight percentages from the large
summary. Taking the difference of the cumulative weights from the previous
bin's cumulative weight will give the new weight for that bin.
Args:
summary: 2D `np.ndarray` summary to be compressed.
epsilon: A `'float32'` that determines the approxmiate desired
precision.
Returns:
A 2D `np.ndarray` that is a compressed summary. First column is the
interpolated partition values, the second is the weights (counts).
"""
# TODO(b/184863356): remove the numpy escape hatch here.
return tf.numpy_function(
lambda s: _compress_summary_numpy(s, epsilon), [summary], tf.float32
)
def _compress_summary_numpy(summary, epsilon):
"""Compress a summary with numpy."""
if summary.shape[1] * epsilon < 1:
return summary
percents = epsilon + np.arange(0.0, 1.0, epsilon)
cum_weights = summary[1].cumsum()
cum_weight_percents = cum_weights / cum_weights[-1]
new_bins = np.interp(percents, cum_weight_percents, summary[0])
cum_weights = np.interp(percents, cum_weight_percents, cum_weights)
new_weights = cum_weights - np.concatenate(
(np.array([0]), cum_weights[:-1])
)
summary = np.stack((new_bins, new_weights))
return summary.astype(np.float32)
def merge_summaries(prev_summary, next_summary, epsilon):
"""Weighted merge sort of summaries.
Given two summaries of distinct data, this function merges (and compresses)
them to stay within `epsilon` error tolerance.
Args:
prev_summary: 2D `np.ndarray` summary to be merged with `next_summary`.
next_summary: 2D `np.ndarray` summary to be merged with `prev_summary`.
epsilon: A float that determines the approxmiate desired precision.
Returns:
A 2-D `np.ndarray` that is a merged summary. First column is the
interpolated partition values, the second is the weights (counts).
"""
merged = tf.concat((prev_summary, next_summary), axis=1)
merged = tf.gather(merged, tf.argsort(merged[0]), axis=1)
return compress(merged, epsilon)
def get_bin_boundaries(summary, num_bins):
return compress(summary, 1.0 / num_bins)[0, :-1]
@keras_export(
"keras.layers.Discretization",
"keras.layers.experimental.preprocessing.Discretization",
)
class Discretization(base_preprocessing_layer.PreprocessingLayer):
"""A preprocessing layer which buckets continuous features by ranges.
This layer will place each element of its input data into one of several
contiguous ranges and output an integer index indicating which range each
element was placed in.
For an overview and full list of preprocessing layers, see the preprocessing
[guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).
Input shape:
Any `tf.Tensor` or `tf.RaggedTensor` of dimension 2 or higher.
Output shape:
Same as input shape.
Arguments:
bin_boundaries: A list of bin boundaries. The leftmost and rightmost bins
will always extend to `-inf` and `inf`, so `bin_boundaries=[0., 1., 2.]`
generates bins `(-inf, 0.)`, `[0., 1.)`, `[1., 2.)`, and `[2., +inf)`.
If this option is set, `adapt()` should not be called.
num_bins: The integer number of bins to compute. If this option is set,
`adapt()` should be called to learn the bin boundaries.
epsilon: Error tolerance, typically a small fraction close to zero (e.g.
0.01). Higher values of epsilon increase the quantile approximation, and
hence result in more unequal buckets, but could improve performance
and resource consumption.
output_mode: Specification for the output of the layer. Values can be
`"int"`, `"one_hot"`, `"multi_hot"`, or
`"count"` configuring the layer as follows:
- `"int"`: Return the discretized bin indices directly.
- `"one_hot"`: Encodes each individual element in the input into an
array the same size as `num_bins`, containing a 1 at the input's bin
index. If the last dimension is size 1, will encode on that
dimension. If the last dimension is not size 1, will append a new
dimension for the encoded output.
- `"multi_hot"`: Encodes each sample in the input into a single array
the same size as `num_bins`, containing a 1 for each bin index
index present in the sample. Treats the last dimension as the sample
dimension, if input shape is `(..., sample_length)`, output shape
will be `(..., num_tokens)`.
- `"count"`: As `"multi_hot"`, but the int array contains a count of
the number of times the bin index appeared in the sample.
Defaults to `"int"`.
sparse: Boolean. Only applicable to `"one_hot"`, `"multi_hot"`,
and `"count"` output modes. If True, returns a `SparseTensor` instead of
a dense `Tensor`. Defaults to `False`.
Examples:
Bucketize float values based on provided buckets.
>>> input = np.array([[-1.5, 1.0, 3.4, .5], [0.0, 3.0, 1.3, 0.0]])
>>> layer = tf.keras.layers.Discretization(bin_boundaries=[0., 1., 2.])
>>> layer(input)
<tf.Tensor: shape=(2, 4), dtype=int64, numpy=
array([[0, 2, 3, 1],
[1, 3, 2, 1]])>
Bucketize float values based on a number of buckets to compute.
>>> input = np.array([[-1.5, 1.0, 3.4, .5], [0.0, 3.0, 1.3, 0.0]])
>>> layer = tf.keras.layers.Discretization(num_bins=4, epsilon=0.01)
>>> layer.adapt(input)
>>> layer(input)
<tf.Tensor: shape=(2, 4), dtype=int64, numpy=
array([[0, 2, 3, 2],
[1, 3, 3, 1]])>
"""
def __init__(
self,
bin_boundaries=None,
num_bins=None,
epsilon=0.01,
output_mode="int",
sparse=False,
**kwargs,
):
# bins is a deprecated arg for setting bin_boundaries or num_bins that
# still has some usage.
if "bins" in kwargs:
logging.warning(
"bins is deprecated, "
"please use bin_boundaries or num_bins instead."
)
if isinstance(kwargs["bins"], int) and num_bins is None:
num_bins = kwargs["bins"]
elif bin_boundaries is None:
bin_boundaries = kwargs["bins"]
del kwargs["bins"]
# By default, output int64 when output_mode='int' and floats otherwise.
if "dtype" not in kwargs or kwargs["dtype"] is None:
kwargs["dtype"] = (
tf.int64 if output_mode == INT else backend.floatx()
)
elif (
output_mode == "int" and not tf.as_dtype(kwargs["dtype"]).is_integer
):
# Compat for when dtype was always floating and ignored by the
# layer.
kwargs["dtype"] = tf.int64
super().__init__(**kwargs)
# Check dtype only after base layer parses it; dtype parsing is complex.
if (
output_mode == INT
and not tf.as_dtype(self.compute_dtype).is_integer
):
input_dtype = kwargs["dtype"]
raise ValueError(
"When `output_mode='int'`, `dtype` should be an integer "
f"type. Received: dtype={input_dtype}"
)
# 'output_mode' must be one of (INT, ONE_HOT, MULTI_HOT, COUNT)
layer_utils.validate_string_arg(
output_mode,
allowable_strings=(INT, ONE_HOT, MULTI_HOT, COUNT),
layer_name=self.__class__.__name__,
arg_name="output_mode",
)
if sparse and output_mode == INT:
raise ValueError(
"`sparse` may only be true if `output_mode` is "
"`'one_hot'`, `'multi_hot'`, or `'count'`. "
f"Received: sparse={sparse} and "
f"output_mode={output_mode}"
)
if num_bins is not None and num_bins < 0:
raise ValueError(
"`num_bins` must be greater than or equal to 0. "
"You passed `num_bins={}`".format(num_bins)
)
if num_bins is not None and bin_boundaries is not None:
raise ValueError(
"Both `num_bins` and `bin_boundaries` should not be "
"set. You passed `num_bins={}` and "
"`bin_boundaries={}`".format(num_bins, bin_boundaries)
)
bin_boundaries = utils.listify_tensors(bin_boundaries)
self.input_bin_boundaries = bin_boundaries
self.bin_boundaries = (
bin_boundaries if bin_boundaries is not None else []
)
self.num_bins = num_bins
self.epsilon = epsilon
self.output_mode = output_mode
self.sparse = sparse
def build(self, input_shape):
super().build(input_shape)
if self.input_bin_boundaries is not None:
return
# Summary contains two equal length vectors of bins at index 0 and
# weights at index 1.
self.summary = self.add_weight(
name="summary",
shape=(2, None),
dtype=tf.float32,
initializer=lambda shape, dtype: [
[],
[],
],
trainable=False,
)
# We override this method solely to generate a docstring.
def adapt(self, data, batch_size=None, steps=None):
"""Computes bin boundaries from quantiles in a input dataset.
Calling `adapt()` on a `Discretization` layer is an alternative to
passing in a `bin_boundaries` argument during construction. A
`Discretization` layer should always be either adapted over a dataset or
passed `bin_boundaries`.
During `adapt()`, the layer will estimate the quantile boundaries of the
input dataset. The number of quantiles can be controlled via the
`num_bins` argument, and the error tolerance for quantile boundaries can
be controlled via the `epsilon` argument.
In order to make `Discretization` efficient in any distribution context,
the computed boundaries are kept static with respect to any compiled
`tf.Graph`s that call the layer. As a consequence, if the layer is
adapted a second time, any models using the layer should be re-compiled.
For more information see
`tf.keras.layers.experimental.preprocessing.PreprocessingLayer.adapt`.
`adapt()` is meant only as a single machine utility to compute layer
state. To analyze a dataset that cannot fit on a single machine, see
[Tensorflow Transform](
https://www.tensorflow.org/tfx/transform/get_started) for a
multi-machine, map-reduce solution.
Arguments:
data: The data to train on. It can be passed either as a
`tf.data.Dataset`, or as a numpy array.
batch_size: Integer or `None`.
Number of samples per state update.
If unspecified, `batch_size` will default to 32.
Do not specify the `batch_size` if your data is in the
form of datasets, generators, or `keras.utils.Sequence` instances
(since they generate batches).
steps: Integer or `None`.
Total number of steps (batches of samples)
When training with input tensors such as
TensorFlow data tensors, the default `None` is equal to
the number of samples in your dataset divided by
the batch size, or 1 if that cannot be determined. If x is a
`tf.data` dataset, and 'steps' is None, the epoch will run until
the input dataset is exhausted. When passing an infinitely
repeating dataset, you must specify the `steps` argument. This
argument is not supported with array inputs.
"""
super().adapt(data, batch_size=batch_size, steps=steps)
def update_state(self, data):
if self.input_bin_boundaries is not None:
raise ValueError(
"Cannot adapt a Discretization layer that has been initialized "
"with `bin_boundaries`, use `num_bins` instead. You passed "
"`bin_boundaries={}`.".format(self.input_bin_boundaries)
)
if not self.built:
raise RuntimeError("`build` must be called before `update_state`.")
data = tf.convert_to_tensor(data)
if data.dtype != tf.float32:
data = tf.cast(data, tf.float32)
summary = summarize(data, self.epsilon)
self.summary.assign(
merge_summaries(summary, self.summary, self.epsilon)
)
def finalize_state(self):
if self.input_bin_boundaries is not None or not self.built:
return
# The bucketize op only support list boundaries.
self.bin_boundaries = utils.listify_tensors(
get_bin_boundaries(self.summary, self.num_bins)
)
def reset_state(self):
if self.input_bin_boundaries is not None or not self.built:
return
self.summary.assign([[], []])
def get_config(self):
config = super().get_config()
config.update(
{
"bin_boundaries": self.input_bin_boundaries,
"num_bins": self.num_bins,
"epsilon": self.epsilon,
"output_mode": self.output_mode,
"sparse": self.sparse,
}
)
return config
def compute_output_shape(self, input_shape):
return input_shape
def compute_output_signature(self, input_spec):
output_shape = self.compute_output_shape(input_spec.shape.as_list())
if isinstance(input_spec, tf.SparseTensorSpec):
return tf.SparseTensorSpec(
shape=output_shape, dtype=self.compute_dtype
)
return tf.TensorSpec(shape=output_shape, dtype=self.compute_dtype)
def call(self, inputs):
def bucketize(inputs):
return tf.raw_ops.Bucketize(
input=inputs, boundaries=self.bin_boundaries
)
if tf_utils.is_ragged(inputs):
indices = tf.ragged.map_flat_values(bucketize, inputs)
elif tf_utils.is_sparse(inputs):
indices = tf.SparseTensor(
indices=tf.identity(inputs.indices),
values=bucketize(inputs.values),
dense_shape=tf.identity(inputs.dense_shape),
)
else:
indices = bucketize(inputs)
return utils.encode_categorical_inputs(
indices,
output_mode=self.output_mode,
depth=len(self.bin_boundaries) + 1,
sparse=self.sparse,
dtype=self.compute_dtype,
)
| tf-keras/tf_keras/layers/preprocessing/discretization.py/0 | {
"file_path": "tf-keras/tf_keras/layers/preprocessing/discretization.py",
"repo_id": "tf-keras",
"token_count": 7343
} | 185 |
# Copyright 2019 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.
# ==============================================================================
"""Normalization preprocessing layer."""
import numpy as np
import tensorflow.compat.v2 as tf
from tf_keras import backend
from tf_keras.engine import base_preprocessing_layer
from tf_keras.layers.preprocessing import preprocessing_utils as utils
# isort: off
from tensorflow.python.util.tf_export import keras_export
@keras_export(
"keras.layers.Normalization",
"keras.layers.experimental.preprocessing.Normalization",
)
class Normalization(base_preprocessing_layer.PreprocessingLayer):
"""A preprocessing layer which normalizes continuous features.
This layer will shift and scale inputs into a distribution centered around
0 with standard deviation 1. It accomplishes this by precomputing the mean
and variance of the data, and calling `(input - mean) / sqrt(var)` at
runtime.
The mean and variance values for the layer must be either supplied on
construction or learned via `adapt()`. `adapt()` will compute the mean and
variance of the data and store them as the layer's weights. `adapt()` should
be called before `fit()`, `evaluate()`, or `predict()`.
For an overview and full list of preprocessing layers, see the preprocessing
[guide](https://www.tensorflow.org/guide/keras/preprocessing_layers).
Args:
axis: Integer, tuple of integers, or None. The axis or axes that should
have a separate mean and variance for each index in the shape. For
example, if shape is `(None, 5)` and `axis=1`, the layer will track 5
separate mean and variance values for the last axis. If `axis` is set
to `None`, the layer will normalize all elements in the input by a
scalar mean and variance. When `-1` the last axis of the
input is assumed to be a feature dimension and is normalized per
index. Note that in the specific case of batched scalar inputs where
the only axis is the batch axis, the default will normalize each index
in the batch separately. In this case, consider passing `axis=None`.
Defaults to `-1`.
mean: The mean value(s) to use during normalization. The passed value(s)
will be broadcast to the shape of the kept axes above; if the value(s)
cannot be broadcast, an error will be raised when this layer's
`build()` method is called.
variance: The variance value(s) to use during normalization. The passed
value(s) will be broadcast to the shape of the kept axes above; if the
value(s) cannot be broadcast, an error will be raised when this
layer's `build()` method is called.
invert: If True, this layer will apply the inverse transformation
to its inputs: it would turn a normalized input back into its
original form.
Examples:
Calculate a global mean and variance by analyzing the dataset in `adapt()`.
>>> adapt_data = np.array([1., 2., 3., 4., 5.], dtype='float32')
>>> input_data = np.array([1., 2., 3.], dtype='float32')
>>> layer = tf.keras.layers.Normalization(axis=None)
>>> layer.adapt(adapt_data)
>>> layer(input_data)
<tf.Tensor: shape=(3,), dtype=float32, numpy=
array([-1.4142135, -0.70710677, 0.], dtype=float32)>
Calculate a mean and variance for each index on the last axis.
>>> adapt_data = np.array([[0., 7., 4.],
... [2., 9., 6.],
... [0., 7., 4.],
... [2., 9., 6.]], dtype='float32')
>>> input_data = np.array([[0., 7., 4.]], dtype='float32')
>>> layer = tf.keras.layers.Normalization(axis=-1)
>>> layer.adapt(adapt_data)
>>> layer(input_data)
<tf.Tensor: shape=(1, 3), dtype=float32, numpy=
array([-1., -1., -1.], dtype=float32)>
Pass the mean and variance directly.
>>> input_data = np.array([[1.], [2.], [3.]], dtype='float32')
>>> layer = tf.keras.layers.Normalization(mean=3., variance=2.)
>>> layer(input_data)
<tf.Tensor: shape=(3, 1), dtype=float32, numpy=
array([[-1.4142135 ],
[-0.70710677],
[ 0. ]], dtype=float32)>
Use the layer to de-normalize inputs (after adapting the layer).
>>> adapt_data = np.array([[0., 7., 4.],
... [2., 9., 6.],
... [0., 7., 4.],
... [2., 9., 6.]], dtype='float32')
>>> input_data = np.array([[1., 2., 3.]], dtype='float32')
>>> layer = tf.keras.layers.Normalization(axis=-1, invert=True)
>>> layer.adapt(adapt_data)
>>> layer(input_data)
<tf.Tensor: shape=(1, 3), dtype=float32, numpy=
array([2., 10., 8.], dtype=float32)>
"""
def __init__(
self, axis=-1, mean=None, variance=None, invert=False, **kwargs
):
super().__init__(**kwargs)
# Standardize `axis` to a tuple.
if axis is None:
axis = ()
elif isinstance(axis, int):
axis = (axis,)
else:
axis = tuple(axis)
self.axis = axis
# Set `mean` and `variance` if passed.
if isinstance(mean, tf.Variable):
raise ValueError(
"Normalization does not support passing a Variable "
"for the `mean` init arg."
)
if isinstance(variance, tf.Variable):
raise ValueError(
"Normalization does not support passing a Variable "
"for the `variance` init arg."
)
if (mean is not None) != (variance is not None):
raise ValueError(
"When setting values directly, both `mean` and `variance` "
"must be set. Got mean: {} and variance: {}".format(
mean, variance
)
)
self.input_mean = mean
self.input_variance = variance
self.invert = invert
def build(self, input_shape):
super().build(input_shape)
if isinstance(input_shape, (list, tuple)) and all(
isinstance(shape, tf.TensorShape) for shape in input_shape
):
raise ValueError(
"Normalization only accepts a single input. If you are "
"passing a python list or tuple as a single input, "
"please convert to a numpy array or `tf.Tensor`."
)
input_shape = tf.TensorShape(input_shape).as_list()
ndim = len(input_shape)
if any(a < -ndim or a >= ndim for a in self.axis):
raise ValueError(
"All `axis` values must be in the range [-ndim, ndim). "
"Found ndim: `{}`, axis: {}".format(ndim, self.axis)
)
# Axes to be kept, replacing negative values with positive equivalents.
# Sorted to avoid transposing axes.
self._keep_axis = sorted([d if d >= 0 else d + ndim for d in self.axis])
# All axes to be kept should have known shape.
for d in self._keep_axis:
if input_shape[d] is None:
raise ValueError(
"All `axis` values to be kept must have known shape. "
"Got axis: {}, "
"input shape: {}, with unknown axis at index: {}".format(
self.axis, input_shape, d
)
)
# Axes to be reduced.
self._reduce_axis = [d for d in range(ndim) if d not in self._keep_axis]
# 1 if an axis should be reduced, 0 otherwise.
self._reduce_axis_mask = [
0 if d in self._keep_axis else 1 for d in range(ndim)
]
# Broadcast any reduced axes.
self._broadcast_shape = [
input_shape[d] if d in self._keep_axis else 1 for d in range(ndim)
]
mean_and_var_shape = tuple(input_shape[d] for d in self._keep_axis)
if self.input_mean is None:
self.adapt_mean = self.add_weight(
name="mean",
shape=mean_and_var_shape,
dtype=self.compute_dtype,
initializer="zeros",
trainable=False,
)
self.adapt_variance = self.add_weight(
name="variance",
shape=mean_and_var_shape,
dtype=self.compute_dtype,
initializer="ones",
trainable=False,
)
self.count = self.add_weight(
name="count",
shape=(),
dtype=tf.int64,
initializer="zeros",
trainable=False,
)
self.finalize_state()
else:
# In the no adapt case, make constant tensors for mean and variance
# with proper broadcast shape for use during call.
mean = self.input_mean * np.ones(mean_and_var_shape)
variance = self.input_variance * np.ones(mean_and_var_shape)
mean = tf.reshape(mean, self._broadcast_shape)
variance = tf.reshape(variance, self._broadcast_shape)
self.mean = tf.cast(mean, self.compute_dtype)
self.variance = tf.cast(variance, self.compute_dtype)
# We override this method solely to generate a docstring.
def adapt(self, data, batch_size=None, steps=None):
"""Computes the mean and variance of values in a dataset.
Calling `adapt()` on a `Normalization` layer is an alternative to
passing in `mean` and `variance` arguments during layer construction. A
`Normalization` layer should always either be adapted over a dataset or
passed `mean` and `variance`.
During `adapt()`, the layer will compute a `mean` and `variance`
separately for each position in each axis specified by the `axis`
argument. To calculate a single `mean` and `variance` over the input
data, simply pass `axis=None`.
In order to make `Normalization` efficient in any distribution context,
the computed mean and variance are kept static with respect to any
compiled `tf.Graph`s that call the layer. As a consequence, if the layer
is adapted a second time, any models using the layer should be
re-compiled. For more information see
`tf.keras.layers.experimental.preprocessing.PreprocessingLayer.adapt`.
`adapt()` is meant only as a single machine utility to compute layer
state. To analyze a dataset that cannot fit on a single machine, see
[Tensorflow Transform](
https://www.tensorflow.org/tfx/transform/get_started)
for a multi-machine, map-reduce solution.
Arguments:
data: The data to train on. It can be passed either as a
`tf.data.Dataset`, or as a numpy array.
batch_size: Integer or `None`.
Number of samples per state update.
If unspecified, `batch_size` will default to 32.
Do not specify the `batch_size` if your data is in the
form of datasets, generators, or `keras.utils.Sequence` instances
(since they generate batches).
steps: Integer or `None`.
Total number of steps (batches of samples)
When training with input tensors such as
TensorFlow data tensors, the default `None` is equal to
the number of samples in your dataset divided by
the batch size, or 1 if that cannot be determined. If x is a
`tf.data` dataset, and 'steps' is None, the epoch will run until
the input dataset is exhausted. When passing an infinitely
repeating dataset, you must specify the `steps` argument. This
argument is not supported with array inputs.
"""
super().adapt(data, batch_size=batch_size, steps=steps)
def update_state(self, data):
if self.input_mean is not None:
raise ValueError(
"Cannot `adapt` a Normalization layer that is initialized with "
"static `mean` and `variance`, "
"you passed mean {} and variance {}.".format(
self.input_mean, self.input_variance
)
)
if not self.built:
raise RuntimeError("`build` must be called before `update_state`.")
data = self._standardize_inputs(data)
data = tf.cast(data, self.adapt_mean.dtype)
batch_mean, batch_variance = tf.nn.moments(data, axes=self._reduce_axis)
batch_shape = tf.shape(data, out_type=self.count.dtype)
if self._reduce_axis:
batch_reduce_shape = tf.gather(batch_shape, self._reduce_axis)
batch_count = tf.reduce_prod(batch_reduce_shape)
else:
batch_count = 1
total_count = batch_count + self.count
batch_weight = tf.cast(batch_count, dtype=self.compute_dtype) / tf.cast(
total_count, dtype=self.compute_dtype
)
existing_weight = 1.0 - batch_weight
total_mean = (
self.adapt_mean * existing_weight + batch_mean * batch_weight
)
# The variance is computed using the lack-of-fit sum of squares
# formula (see
# https://en.wikipedia.org/wiki/Lack-of-fit_sum_of_squares).
total_variance = (
self.adapt_variance + (self.adapt_mean - total_mean) ** 2
) * existing_weight + (
batch_variance + (batch_mean - total_mean) ** 2
) * batch_weight
self.adapt_mean.assign(total_mean)
self.adapt_variance.assign(total_variance)
self.count.assign(total_count)
def reset_state(self):
if self.input_mean is not None or not self.built:
return
self.adapt_mean.assign(tf.zeros_like(self.adapt_mean))
self.adapt_variance.assign(tf.ones_like(self.adapt_variance))
self.count.assign(tf.zeros_like(self.count))
def finalize_state(self):
if self.input_mean is not None or not self.built:
return
# In the adapt case, we make constant tensors for mean and variance with
# proper broadcast shape and dtype each time `finalize_state` is called.
self.mean = tf.reshape(self.adapt_mean, self._broadcast_shape)
self.mean = tf.cast(self.mean, self.compute_dtype)
self.variance = tf.reshape(self.adapt_variance, self._broadcast_shape)
self.variance = tf.cast(self.variance, self.compute_dtype)
def call(self, inputs):
inputs = self._standardize_inputs(inputs)
# The base layer automatically casts floating-point inputs, but we
# explicitly cast here to also allow integer inputs to be passed
inputs = tf.cast(inputs, self.compute_dtype)
if self.invert:
return self.mean + (
inputs * tf.maximum(tf.sqrt(self.variance), backend.epsilon())
)
else:
return (inputs - self.mean) / tf.maximum(
tf.sqrt(self.variance), backend.epsilon()
)
def compute_output_shape(self, input_shape):
return input_shape
def compute_output_signature(self, input_spec):
return input_spec
def get_config(self):
config = super().get_config()
config.update(
{
"axis": self.axis,
"invert": self.invert,
"mean": utils.listify_tensors(self.input_mean),
"variance": utils.listify_tensors(self.input_variance),
}
)
return config
def _standardize_inputs(self, inputs):
inputs = tf.convert_to_tensor(inputs)
if inputs.dtype != self.compute_dtype:
inputs = tf.cast(inputs, self.compute_dtype)
return inputs
def load_own_variables(self, store):
# Ensure that we call finalize_state after variable loading.
super().load_own_variables(store)
self.finalize_state()
| tf-keras/tf_keras/layers/preprocessing/normalization.py/0 | {
"file_path": "tf-keras/tf_keras/layers/preprocessing/normalization.py",
"repo_id": "tf-keras",
"token_count": 7109
} | 186 |
# Copyright 2015 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 ActivityRegularization layer."""
from tf_keras import regularizers
from tf_keras.engine.base_layer import Layer
# isort: off
from tensorflow.python.util.tf_export import keras_export
@keras_export("keras.layers.ActivityRegularization")
class ActivityRegularization(Layer):
"""Layer that applies an update to the cost function based input activity.
Args:
l1: L1 regularization factor (positive float).
l2: L2 regularization factor (positive float).
Input shape:
Arbitrary. Use the keyword argument `input_shape`
(tuple of integers, does not include the samples axis)
when using this layer as the first layer in a model.
Output shape:
Same shape as input.
"""
def __init__(self, l1=0.0, l2=0.0, **kwargs):
super().__init__(
activity_regularizer=regularizers.L1L2(l1=l1, l2=l2), **kwargs
)
self.supports_masking = True
self.l1 = l1
self.l2 = l2
def compute_output_shape(self, input_shape):
return input_shape
def get_config(self):
config = {"l1": self.l1, "l2": self.l2}
base_config = super().get_config()
return dict(list(base_config.items()) + list(config.items()))
| tf-keras/tf_keras/layers/regularization/activity_regularization.py/0 | {
"file_path": "tf-keras/tf_keras/layers/regularization/activity_regularization.py",
"repo_id": "tf-keras",
"token_count": 645
} | 187 |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Keras cropping layer for 1D input."""
import tensorflow.compat.v2 as tf
from tf_keras.engine.base_layer import Layer
from tf_keras.engine.input_spec import InputSpec
from tf_keras.utils import conv_utils
# isort: off
from tensorflow.python.util.tf_export import keras_export
@keras_export("keras.layers.Cropping1D")
class Cropping1D(Layer):
"""Cropping layer for 1D input (e.g. temporal sequence).
It crops along the time dimension (axis 1).
Examples:
>>> input_shape = (2, 3, 2)
>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)
>>> print(x)
[[[ 0 1]
[ 2 3]
[ 4 5]]
[[ 6 7]
[ 8 9]
[10 11]]]
>>> y = tf.keras.layers.Cropping1D(cropping=1)(x)
>>> print(y)
tf.Tensor(
[[[2 3]]
[[8 9]]], shape=(2, 1, 2), dtype=int64)
Args:
cropping: Int or tuple of int (length 2)
How many units should be trimmed off at the beginning and end of
the cropping dimension (axis 1).
If a single int is provided, the same value will be used for both.
Input shape:
3D tensor with shape `(batch_size, axis_to_crop, features)`
Output shape:
3D tensor with shape `(batch_size, cropped_axis, features)`
"""
def __init__(self, cropping=(1, 1), **kwargs):
super().__init__(**kwargs)
self.cropping = conv_utils.normalize_tuple(
cropping, 2, "cropping", allow_zero=True
)
self.input_spec = InputSpec(ndim=3)
def compute_output_shape(self, input_shape):
input_shape = tf.TensorShape(input_shape).as_list()
if input_shape[1] is not None:
length = input_shape[1] - self.cropping[0] - self.cropping[1]
else:
length = None
return tf.TensorShape([input_shape[0], length, input_shape[2]])
def call(self, inputs):
if (
inputs.shape[1] is not None
and sum(self.cropping) >= inputs.shape[1]
):
raise ValueError(
"cropping parameter of Cropping layer must be "
"greater than the input shape. Received: inputs.shape="
f"{inputs.shape}, and cropping={self.cropping}"
)
if self.cropping[1] == 0:
return inputs[:, self.cropping[0] :, :]
else:
return inputs[:, self.cropping[0] : -self.cropping[1], :]
def get_config(self):
config = {"cropping": self.cropping}
base_config = super().get_config()
return dict(list(base_config.items()) + list(config.items()))
| tf-keras/tf_keras/layers/reshaping/cropping1d.py/0 | {
"file_path": "tf-keras/tf_keras/layers/reshaping/cropping1d.py",
"repo_id": "tf-keras",
"token_count": 1315
} | 188 |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Keras zero-padding layer for 1D input."""
import tensorflow.compat.v2 as tf
from tf_keras import backend
from tf_keras.engine.base_layer import Layer
from tf_keras.engine.input_spec import InputSpec
from tf_keras.utils import conv_utils
# isort: off
from tensorflow.python.util.tf_export import keras_export
@keras_export("keras.layers.ZeroPadding1D")
class ZeroPadding1D(Layer):
"""Zero-padding layer for 1D input (e.g. temporal sequence).
Examples:
>>> input_shape = (2, 2, 3)
>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)
>>> print(x)
[[[ 0 1 2]
[ 3 4 5]]
[[ 6 7 8]
[ 9 10 11]]]
>>> y = tf.keras.layers.ZeroPadding1D(padding=2)(x)
>>> print(y)
tf.Tensor(
[[[ 0 0 0]
[ 0 0 0]
[ 0 1 2]
[ 3 4 5]
[ 0 0 0]
[ 0 0 0]]
[[ 0 0 0]
[ 0 0 0]
[ 6 7 8]
[ 9 10 11]
[ 0 0 0]
[ 0 0 0]]], shape=(2, 6, 3), dtype=int64)
Args:
padding: Int, or tuple of int (length 2).
- If int:
How many zeros to add at the beginning and end of
the padding dimension (axis 1).
- If tuple of int (length 2):
How many zeros to add at the beginning and the end of
the padding dimension (`(left_pad, right_pad)`).
Input shape:
3D tensor with shape `(batch_size, axis_to_pad, features)`
Output shape:
3D tensor with shape `(batch_size, padded_axis, features)`
"""
def __init__(self, padding=1, **kwargs):
super().__init__(**kwargs)
self.padding = conv_utils.normalize_tuple(
padding, 2, "padding", allow_zero=True
)
self.input_spec = InputSpec(ndim=3)
def compute_output_shape(self, input_shape):
if input_shape[1] is not None:
length = input_shape[1] + self.padding[0] + self.padding[1]
else:
length = None
return tf.TensorShape([input_shape[0], length, input_shape[2]])
def call(self, inputs):
return backend.temporal_padding(inputs, padding=self.padding)
def get_config(self):
config = {"padding": self.padding}
base_config = super().get_config()
return dict(list(base_config.items()) + list(config.items()))
| tf-keras/tf_keras/layers/reshaping/zero_padding1d.py/0 | {
"file_path": "tf-keras/tf_keras/layers/reshaping/zero_padding1d.py",
"repo_id": "tf-keras",
"token_count": 1243
} | 189 |
# Copyright 2019 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.
# ==============================================================================
"""Module implementing RNN wrappers."""
# Note that all the APIs under this module are exported as tf.nn.*. This is due
# to the fact that those APIs were from tf.nn.rnn_cell_impl. They are ported
# here to avoid the cyclic dependency issue for serialization. These APIs will
# probably be deprecated and removed in future since similar API is available in
# existing TF-Keras RNN API.
import hashlib
import numbers
import sys
import types as python_types
import warnings
import tensorflow.compat.v2 as tf
from tf_keras.layers.rnn import lstm
from tf_keras.layers.rnn.abstract_rnn_cell import AbstractRNNCell
from tf_keras.saving import serialization_lib
from tf_keras.utils import generic_utils
from tf_keras.utils import tf_inspect
# isort: off
from tensorflow.python.util.tf_export import tf_export
from tensorflow.python.util.deprecation import deprecated
class _RNNCellWrapper(AbstractRNNCell):
"""Base class for cells wrappers V2 compatibility.
This class along with `rnn_cell_impl._RNNCellWrapperV1` allows to define
wrappers that are compatible with V1 and V2, and defines helper methods for
this purpose.
"""
def __init__(self, cell, *args, **kwargs):
super().__init__(*args, **kwargs)
self.cell = cell
cell_call_spec = tf_inspect.getfullargspec(cell.call)
self._call_spec.expects_training_arg = (
"training" in cell_call_spec.args
) or (cell_call_spec.varkw is not None)
def _call_wrapped_cell(self, inputs, state, cell_call_fn, **kwargs):
"""Calls the wrapped cell and performs the wrapping logic.
This method is called from the wrapper's `call` or `__call__` methods.
Args:
inputs: A tensor with wrapped cell's input.
state: A tensor or tuple of tensors with wrapped cell's state.
cell_call_fn: Wrapped cell's method to use for step computation
(cell's `__call__` or 'call' method).
**kwargs: Additional arguments.
Returns:
A pair containing:
- Output: A tensor with cell's output.
- New state: A tensor or tuple of tensors with new wrapped cell's
state.
"""
raise NotImplementedError
def call(self, inputs, state, **kwargs):
"""Runs the RNN cell step computation.
When `call` is being used, we assume that the wrapper object has been
built, and therefore the wrapped cells has been built via its `build`
method and its `call` method can be used directly.
This allows to use the wrapped cell and the non-wrapped cell
equivalently when using `call` and `build`.
Args:
inputs: A tensor with wrapped cell's input.
state: A tensor or tuple of tensors with wrapped cell's state.
**kwargs: Additional arguments passed to the wrapped cell's `call`.
Returns:
A pair containing:
- Output: A tensor with cell's output.
- New state: A tensor or tuple of tensors with new wrapped cell's
state.
"""
return self._call_wrapped_cell(
inputs, state, cell_call_fn=self.cell.call, **kwargs
)
def build(self, inputs_shape):
"""Builds the wrapped cell."""
self.cell.build(inputs_shape)
self.built = True
@property
def wrapped_cell(self):
return self.cell
@property
def state_size(self):
return self.cell.state_size
@property
def output_size(self):
return self.cell.output_size
def zero_state(self, batch_size, dtype):
with tf.name_scope(type(self).__name__ + "ZeroState"):
return self.cell.zero_state(batch_size, dtype)
def get_config(self):
config = {
"cell": {
"class_name": self.cell.__class__.__name__,
"config": self.cell.get_config(),
},
}
base_config = super().get_config()
return dict(list(base_config.items()) + list(config.items()))
@classmethod
def from_config(cls, config, custom_objects=None):
config = config.copy()
from tf_keras.layers.serialization import (
deserialize as deserialize_layer,
)
cell = deserialize_layer(
config.pop("cell"), custom_objects=custom_objects
)
return cls(cell, **config)
@deprecated(None, "Please use tf.keras.layers.RNN instead.")
@tf_export("nn.RNNCellDropoutWrapper", v1=[])
class DropoutWrapper(_RNNCellWrapper):
"""Operator adding dropout to inputs and outputs of the given cell."""
def __init__(
self,
cell,
input_keep_prob=1.0,
output_keep_prob=1.0,
state_keep_prob=1.0,
variational_recurrent=False,
input_size=None,
dtype=None,
seed=None,
dropout_state_filter_visitor=None,
**kwargs,
):
"""Create a cell with added input, state, and/or output dropout.
If `variational_recurrent` is set to `True` (**NOT** the default
behavior), then the same dropout mask is applied at every step, as
described in: [A Theoretically Grounded Application of Dropout in
Recurrent Neural Networks. Y. Gal, Z.
Ghahramani](https://arxiv.org/abs/1512.05287).
Otherwise a different dropout mask is applied at every time step.
Note, by default (unless a custom `dropout_state_filter` is provided),
the memory state (`c` component of any `LSTMStateTuple`) passing through
a `DropoutWrapper` is never modified. This behavior is described in the
above article.
Args:
cell: an RNNCell, a projection to output_size is added to it.
input_keep_prob: unit Tensor or float between 0 and 1, input keep
probability; if it is constant and 1, no input dropout will be
added.
output_keep_prob: unit Tensor or float between 0 and 1, output keep
probability; if it is constant and 1, no output dropout will be
added.
state_keep_prob: unit Tensor or float between 0 and 1, output keep
probability; if it is constant and 1, no output dropout will be
added. State dropout is performed on the outgoing states of the
cell. **Note** the state components to which dropout is applied when
`state_keep_prob` is in `(0, 1)` are also determined by the argument
`dropout_state_filter_visitor` (e.g. by default dropout is never
applied to the `c` component of an `LSTMStateTuple`).
variational_recurrent: Python bool. If `True`, then the same dropout
pattern is applied across all time steps per run call. If this
parameter is set, `input_size` **must** be provided.
input_size: (optional) (possibly nested tuple of) `TensorShape`
objects containing the depth(s) of the input tensors expected to be
passed in to the `DropoutWrapper`. Required and used **iff**
`variational_recurrent = True` and `input_keep_prob < 1`.
dtype: (optional) The `dtype` of the input, state, and output tensors.
Required and used **iff** `variational_recurrent = True`.
seed: (optional) integer, the randomness seed.
dropout_state_filter_visitor: (optional), default: (see below).
Function that takes any hierarchical level of the state and returns
a scalar or depth=1 structure of Python booleans describing which
terms in the state should be dropped out. In addition, if the
function returns `True`, dropout is applied across this sublevel.
If the function returns `False`, dropout is not applied across this
entire sublevel. Default behavior: perform dropout on all terms
except the memory (`c`) state of `LSTMCellState` objects, and don't
try to apply dropout to
`TensorArray` objects:
```
def dropout_state_filter_visitor(s):
# Never perform dropout on the c state.
if isinstance(s, LSTMCellState):
return LSTMCellState(c=False, h=True)
elif isinstance(s, TensorArray):
return False
return True
```
**kwargs: dict of keyword arguments for base layer.
Raises:
TypeError: if `cell` is not an `RNNCell`, or `keep_state_fn` is
provided but not `callable`.
ValueError: if any of the keep_probs are not between 0 and 1.
"""
if isinstance(cell, lstm.LSTMCell):
raise ValueError(
"keras LSTM cell does not work with DropoutWrapper. "
"Please use LSTMCell(dropout=x, recurrent_dropout=y) "
"instead."
)
super().__init__(cell, dtype=dtype, **kwargs)
if dropout_state_filter_visitor is not None and not callable(
dropout_state_filter_visitor
):
raise TypeError(
"dropout_state_filter_visitor must be callable. "
f"Received: {dropout_state_filter_visitor}"
)
self._dropout_state_filter = (
dropout_state_filter_visitor
or _default_dropout_state_filter_visitor
)
with tf.name_scope("DropoutWrapperInit"):
def tensor_and_const_value(v):
tensor_value = tf.convert_to_tensor(v)
const_value = tf.get_static_value(tensor_value)
return (tensor_value, const_value)
for prob, attr in [
(input_keep_prob, "input_keep_prob"),
(state_keep_prob, "state_keep_prob"),
(output_keep_prob, "output_keep_prob"),
]:
tensor_prob, const_prob = tensor_and_const_value(prob)
if const_prob is not None:
if const_prob < 0 or const_prob > 1:
raise ValueError(
f"Parameter {attr} must be between 0 and 1. "
f"Received {const_prob}"
)
setattr(self, f"_{attr}", float(const_prob))
else:
setattr(self, f"_{attr}", tensor_prob)
# Set variational_recurrent, seed before running the code below
self._variational_recurrent = variational_recurrent
self._input_size = input_size
self._seed = seed
self._recurrent_input_noise = None
self._recurrent_state_noise = None
self._recurrent_output_noise = None
if variational_recurrent:
if dtype is None:
raise ValueError(
"When variational_recurrent=True, dtype must be provided"
)
def convert_to_batch_shape(s):
# Prepend a 1 for the batch dimension; for recurrent
# variational dropout we use the same dropout mask for all
# batch elements.
return tf.concat(([1], tf.TensorShape(s).as_list()), 0)
def batch_noise(s, inner_seed):
shape = convert_to_batch_shape(s)
return tf.random.uniform(shape, seed=inner_seed, dtype=dtype)
if (
not isinstance(self._input_keep_prob, numbers.Real)
or self._input_keep_prob < 1.0
):
if input_size is None:
raise ValueError(
"When variational_recurrent=True and input_keep_prob < "
"1.0 or is unknown, input_size must be provided"
)
self._recurrent_input_noise = _enumerated_map_structure_up_to(
input_size,
lambda i, s: batch_noise(
s, inner_seed=self._gen_seed("input", i)
),
input_size,
)
self._recurrent_state_noise = _enumerated_map_structure_up_to(
cell.state_size,
lambda i, s: batch_noise(
s, inner_seed=self._gen_seed("state", i)
),
cell.state_size,
)
self._recurrent_output_noise = _enumerated_map_structure_up_to(
cell.output_size,
lambda i, s: batch_noise(
s, inner_seed=self._gen_seed("output", i)
),
cell.output_size,
)
def _gen_seed(self, salt_prefix, index):
if self._seed is None:
return None
salt = "%s_%d" % (salt_prefix, index)
string = (str(self._seed) + salt).encode("utf-8")
return int(hashlib.md5(string).hexdigest()[:8], 16) & 0x7FFFFFFF
def _variational_recurrent_dropout_value(
self, unused_index, value, noise, keep_prob
):
"""Performs dropout given the pre-calculated noise tensor."""
# uniform [keep_prob, 1.0 + keep_prob)
random_tensor = keep_prob + noise
# 0. if [keep_prob, 1.0) and 1. if [1.0, 1.0 + keep_prob)
binary_tensor = tf.floor(random_tensor)
ret = tf.divide(value, keep_prob) * binary_tensor
ret.set_shape(value.get_shape())
return ret
def _dropout(
self,
values,
salt_prefix,
recurrent_noise,
keep_prob,
shallow_filtered_substructure=None,
):
"""Decides whether to perform standard dropout or recurrent dropout."""
if shallow_filtered_substructure is None:
# Put something so we traverse the entire structure; inside the
# dropout function we check to see if leafs of this are bool or not.
shallow_filtered_substructure = values
if not self._variational_recurrent:
def dropout(i, do_dropout, v):
if not isinstance(do_dropout, bool) or do_dropout:
return tf.nn.dropout(
v,
rate=1.0 - keep_prob,
seed=self._gen_seed(salt_prefix, i),
)
else:
return v
return _enumerated_map_structure_up_to(
shallow_filtered_substructure,
dropout,
*[shallow_filtered_substructure, values],
)
else:
def dropout(i, do_dropout, v, n):
if not isinstance(do_dropout, bool) or do_dropout:
return self._variational_recurrent_dropout_value(
i, v, n, keep_prob
)
else:
return v
return _enumerated_map_structure_up_to(
shallow_filtered_substructure,
dropout,
*[shallow_filtered_substructure, values, recurrent_noise],
)
def _call_wrapped_cell(self, inputs, state, cell_call_fn, **kwargs):
"""Runs the wrapped cell and applies dropout.
Args:
inputs: A tensor with wrapped cell's input.
state: A tensor or tuple of tensors with wrapped cell's state.
cell_call_fn: Wrapped cell's method to use for step computation
(cell's `__call__` or 'call' method).
**kwargs: Additional arguments.
Returns:
A pair containing:
- Output: A tensor with cell's output.
- New state: A tensor or tuple of tensors with new wrapped cell's
state.
"""
def _should_dropout(p):
return (not isinstance(p, float)) or p < 1
if _should_dropout(self._input_keep_prob):
inputs = self._dropout(
inputs,
"input",
self._recurrent_input_noise,
self._input_keep_prob,
)
output, new_state = cell_call_fn(inputs, state, **kwargs)
if _should_dropout(self._state_keep_prob):
# Identify which subsets of the state to perform dropout on and
# which ones to keep.
shallow_filtered_substructure = (
tf.__internal__.nest.get_traverse_shallow_structure(
self._dropout_state_filter, new_state
)
)
new_state = self._dropout(
new_state,
"state",
self._recurrent_state_noise,
self._state_keep_prob,
shallow_filtered_substructure,
)
if _should_dropout(self._output_keep_prob):
output = self._dropout(
output,
"output",
self._recurrent_output_noise,
self._output_keep_prob,
)
return output, new_state
def get_config(self):
"""Returns the config of the dropout wrapper."""
config = {
"input_keep_prob": self._input_keep_prob,
"output_keep_prob": self._output_keep_prob,
"state_keep_prob": self._state_keep_prob,
"variational_recurrent": self._variational_recurrent,
"input_size": self._input_size,
"seed": self._seed,
}
if self._dropout_state_filter != _default_dropout_state_filter_visitor:
(
function,
function_type,
function_module,
) = _serialize_function_to_config(self._dropout_state_filter)
config.update(
{
"dropout_fn": function,
"dropout_fn_type": function_type,
"dropout_fn_module": function_module,
}
)
base_config = super().get_config()
return dict(list(base_config.items()) + list(config.items()))
@classmethod
def from_config(cls, config, custom_objects=None):
if "dropout_fn" in config:
config = config.copy()
dropout_state_filter = _parse_config_to_function(
config,
custom_objects,
"dropout_fn",
"dropout_fn_type",
"dropout_fn_module",
)
config.pop("dropout_fn")
config["dropout_state_filter_visitor"] = dropout_state_filter
return super(DropoutWrapper, cls).from_config(
config, custom_objects=custom_objects
)
@deprecated(None, "Please use tf.keras.layers.RNN instead.")
@tf_export("nn.RNNCellResidualWrapper", v1=[])
class ResidualWrapper(_RNNCellWrapper):
"""RNNCell wrapper that ensures cell inputs are added to the outputs."""
def __init__(self, cell, residual_fn=None, **kwargs):
"""Constructs a `ResidualWrapper` for `cell`.
Args:
cell: An instance of `RNNCell`.
residual_fn: (Optional) The function to map raw cell inputs and raw
cell outputs to the actual cell outputs of the residual network.
Defaults to calling nest.map_structure on (lambda i, o: i + o),
inputs and outputs.
**kwargs: dict of keyword arguments for base layer.
"""
super().__init__(cell, **kwargs)
self._residual_fn = residual_fn
def _call_wrapped_cell(self, inputs, state, cell_call_fn, **kwargs):
"""Run the cell and apply the residual_fn.
Args:
inputs: cell inputs.
state: cell state.
cell_call_fn: Wrapped cell's method to use for step computation
(cell's `__call__` or 'call' method).
**kwargs: Additional arguments passed to the wrapped cell's `call`.
Returns:
Tuple of cell outputs and new state.
Raises:
TypeError: If cell inputs and outputs have different structure (type).
ValueError: If cell inputs and outputs have different structure
(value).
"""
outputs, new_state = cell_call_fn(inputs, state, **kwargs)
# Ensure shapes match
def assert_shape_match(inp, out):
inp.get_shape().assert_is_compatible_with(out.get_shape())
def default_residual_fn(inputs, outputs):
tf.nest.assert_same_structure(inputs, outputs)
tf.nest.map_structure(assert_shape_match, inputs, outputs)
return tf.nest.map_structure(
lambda inp, out: inp + out, inputs, outputs
)
res_outputs = (self._residual_fn or default_residual_fn)(
inputs, outputs
)
return (res_outputs, new_state)
def get_config(self):
"""Returns the config of the residual wrapper."""
if self._residual_fn is not None:
(
function,
function_type,
function_module,
) = _serialize_function_to_config(self._residual_fn)
config = {
"residual_fn": function,
"residual_fn_type": function_type,
"residual_fn_module": function_module,
}
else:
config = {}
base_config = super().get_config()
return dict(list(base_config.items()) + list(config.items()))
@classmethod
def from_config(cls, config, custom_objects=None):
if "residual_fn" in config:
config = config.copy()
residual_function = _parse_config_to_function(
config,
custom_objects,
"residual_fn",
"residual_fn_type",
"residual_fn_module",
)
config["residual_fn"] = residual_function
return super(ResidualWrapper, cls).from_config(
config, custom_objects=custom_objects
)
@deprecated(None, "Please use tf.keras.layers.RNN instead.")
@tf_export("nn.RNNCellDeviceWrapper", v1=[])
class DeviceWrapper(_RNNCellWrapper):
"""Operator that ensures an RNNCell runs on a particular device."""
def __init__(self, cell, device, **kwargs):
"""Construct a `DeviceWrapper` for `cell` with device `device`.
Ensures the wrapped `cell` is called with `tf.device(device)`.
Args:
cell: An instance of `RNNCell`.
device: A device string or function, for passing to `tf.device`.
**kwargs: dict of keyword arguments for base layer.
"""
super().__init__(cell, **kwargs)
self._device = device
def zero_state(self, batch_size, dtype):
with tf.name_scope(type(self).__name__ + "ZeroState"):
with tf.compat.v1.device(self._device):
return self.cell.zero_state(batch_size, dtype)
def _call_wrapped_cell(self, inputs, state, cell_call_fn, **kwargs):
"""Run the cell on specified device."""
with tf.compat.v1.device(self._device):
return cell_call_fn(inputs, state, **kwargs)
def get_config(self):
config = {"device": self._device}
base_config = super().get_config()
return dict(list(base_config.items()) + list(config.items()))
def _serialize_function_to_config(function):
"""Serialize the function for get_config()."""
if isinstance(function, python_types.LambdaType):
output = generic_utils.func_dump(function)
output_type = "lambda"
module = function.__module__
elif callable(function):
output = function.__name__
output_type = "function"
module = function.__module__
else:
raise ValueError(
f"Unrecognized function type for input: {type(function)}"
)
return output, output_type, module
def _parse_config_to_function(
config,
custom_objects,
func_attr_name,
func_type_attr_name,
module_attr_name,
):
"""Reconstruct the function from the config."""
globs = globals()
module = config.pop(module_attr_name, None)
if module in sys.modules:
globs.update(sys.modules[module].__dict__)
elif module is not None:
# Note: we don't know the name of the function if it's a lambda.
warnings.warn(
"{} is not loaded, but a layer uses it. "
"It may cause errors.".format(module),
UserWarning,
stacklevel=2,
)
if custom_objects:
globs.update(custom_objects)
function_type = config.pop(func_type_attr_name)
if function_type == "function":
# Simple lookup in custom objects
function = serialization_lib.deserialize_keras_object(
config[func_attr_name],
custom_objects=custom_objects,
printable_module_name="function in wrapper",
)
elif function_type == "lambda":
if serialization_lib.in_safe_mode():
raise ValueError(
"Requested the deserialization of a layer with a "
"Python `lambda` inside it. "
"This carries a potential risk of arbitrary code execution "
"and thus it is disallowed by default. If you trust the "
"source of the saved model, you can pass `safe_mode=False` to "
"the loading function in order to allow "
"`lambda` loading."
)
# Unsafe deserialization from bytecode
function = generic_utils.func_load(config[func_attr_name], globs=globs)
else:
raise TypeError(
f"Unknown function type received: {function_type}. "
"Expected types are ['function', 'lambda']"
)
return function
def _default_dropout_state_filter_visitor(substate):
return not isinstance(substate, tf.TensorArray)
def _enumerated_map_structure_up_to(shallow_structure, map_fn, *args, **kwargs):
ix = [0]
def enumerated_fn(*inner_args, **inner_kwargs):
r = map_fn(ix[0], *inner_args, **inner_kwargs)
ix[0] += 1
return r
return tf.__internal__.nest.map_structure_up_to(
shallow_structure, enumerated_fn, *args, **kwargs
)
| tf-keras/tf_keras/layers/rnn/cell_wrappers.py/0 | {
"file_path": "tf-keras/tf_keras/layers/rnn/cell_wrappers.py",
"repo_id": "tf-keras",
"token_count": 12333
} | 190 |
# Copyright 2018 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 allowing TF ops to work with TF-Keras Functional API."""
import time
import numpy as np
import tensorflow.compat.v2 as tf
from absl.testing import parameterized
import tf_keras as keras
from tf_keras.engine import keras_tensor
from tf_keras.optimizers.legacy import adam
from tf_keras.saving.legacy import model_config
from tf_keras.testing_infra import test_combinations
from tf_keras.testing_infra import test_utils
def _single_op_at_end():
inputs = keras.Input(shape=(10,))
x = keras.layers.Dense(10)(inputs)
outputs = tf.nn.relu(x)
return keras.Model(inputs, outputs)
def _single_identity_op_at_end():
inputs = keras.Input(shape=(10,))
x = keras.layers.Dense(10)(inputs)
outputs = tf.identity(x)
return keras.Model(inputs, outputs)
def _multiple_ops_at_end():
inputs = keras.Input(shape=(10,))
x = keras.layers.Dense(10)(inputs)
x = tf.nn.relu(x)
outputs = tf.nn.relu(x)
return keras.Model(inputs, outputs)
def _single_op_in_middle():
inputs = keras.Input(shape=(10,))
x = keras.layers.Dense(10)(inputs)
x = tf.nn.relu(x)
outputs = keras.layers.Dense(10)(x)
return keras.Model(inputs, outputs)
def _multiple_ops_in_middle():
inputs = keras.Input(shape=(10,))
x = keras.layers.Dense(10)(inputs)
x = tf.nn.relu(x)
x = tf.nn.relu(x)
outputs = keras.layers.Dense(10)(x)
return keras.Model(inputs, outputs)
def _shape_op_inference():
inputs = keras.Input(shape=(10,))
x = tf.shape(inputs)
x = tf.ones(x)
assert x.shape.as_list() == [None, 10]
outputs = keras.layers.Dense(10)(x)
return keras.Model(inputs, outputs)
def _shape_op_known_batch_size():
inputs = keras.Input(batch_size=2, shape=(10,))
x = tf.shape(inputs)
x = tf.ones(x)
assert x.shape.as_list() == [2, 10]
outputs = keras.layers.Dense(10)(x)
if tf.executing_eagerly():
return keras.Model(inputs, outputs)
else:
# In V1 the op layer fails for some reason,
# but we don't have access to the test case to call
# self.skip_test in this util method
return keras.Model(inputs, inputs)
def _shape_op_slice_and_range():
inputs = keras.Input(shape=(10,))
batch_size = tf.shape(inputs)[0]
x = tf.range(batch_size * 2)
assert x.shape.as_list() == [None]
x = tf.reshape(x, (batch_size, 2))
x = tf.cast(x, dtype="float32")
outputs = keras.layers.Dense(10)(x)
return keras.Model(inputs, outputs)
def _shape_op_slice_and_range_known_dim():
inputs = keras.Input(batch_size=2, shape=(10,))
batch_size = tf.shape(inputs)[0]
x = tf.range(batch_size * 3)
assert x.shape.as_list() == [6]
x = tf.reshape(x, (batch_size, 3))
x = tf.cast(x, dtype="float32")
outputs = keras.layers.Dense(10)(x)
if tf.executing_eagerly():
return keras.Model(inputs, outputs)
else:
# In V1 the op layer fails for some reason,
# but we don't have access to the test case to call
# self.skip_test in this util method
return keras.Model(inputs, inputs)
def _int32_manipulation_too_big_for_shape():
# This test verifies that the TF-Keras Functional API
# won't crash when manipulating int32 tensors that are too large
# to represent shapes.
inputs = keras.Input(batch_size=2, shape=(10,))
batch_size = tf.shape(inputs)[0]
num_features = 3 * 1024 * 16
x = tf.range(batch_size * num_features, dtype="int32")
assert x.shape.as_list() == [inputs.shape[0] * num_features]
x = tf.reshape(x, (batch_size, num_features))
x = tf.cast(x, dtype="float32")
outputs = keras.layers.Dense(10)(x)
if tf.executing_eagerly():
return keras.Model(inputs, outputs)
else:
# In V1 the op layer fails for some reason,
# but we don't have access to the test case to call
# self.skip_test in this util method
return keras.Model(inputs, inputs)
def _int32_manipulation_at_max_shape_dims_limit():
# This test verifies that the TF-Keras Functional API
# won't crash when manipulating int32 tensors that are at the limit
# of the max tensor size TF-Keras can try inferring values for.
inputs = keras.Input(batch_size=2, shape=(10,))
batch_size = tf.shape(inputs)[0]
num_features = int(keras_tensor._MAX_TENSOR_RANK / int(inputs.shape[0]))
x = tf.range(batch_size * num_features, dtype="int32")
assert x.shape.as_list() == [keras_tensor._MAX_TENSOR_RANK]
# Verify that a value was actually inferred for a tensor that *might*
# represent the shape, bying checking that a value in
# the range appears in the printed inferred value
if tf.compat.v1.executing_eagerly_outside_functions():
assert str(keras_tensor._MAX_TENSOR_RANK - 1) in str(x)
x = tf.reshape(x, (batch_size, num_features))
x = tf.cast(x, dtype="float32")
outputs = keras.layers.Dense(10)(x)
if tf.executing_eagerly():
return keras.Model(inputs, outputs)
else:
# In V1 the op layer fails for some reason,
# but we don't have access to the test case to call
# self.skip_test in this util method
return keras.Model(inputs, inputs)
def _single_standalone_branch():
inputs = keras.Input(shape=(10,))
x = keras.layers.Dense(10)(inputs)
outputs = x * 2
return keras.Model(inputs, outputs)
def _single_op_with_attrs():
inputs = keras.Input(shape=(10,))
x = tf.reduce_mean(inputs, axis=1, keepdims=True)
outputs = keras.layers.Dense(10)(x)
return keras.Model(inputs, outputs)
def _multiple_uses():
inputs = keras.Input(shape=(10,))
x = tf.reduce_mean(inputs, axis=1, keepdims=True)
x1 = keras.layers.Dense(10)(x)
x2 = keras.layers.Dense(10)(x)
outputs = x1 + x2
return keras.Model(inputs, outputs)
def _op_with_tensor_list():
inputs = keras.Input(shape=(10,))
x = tf.concat([inputs, inputs], axis=1)
outputs = keras.layers.Dense(10)(x)
return keras.Model(inputs, outputs)
def _add_n():
inputs = keras.Input(shape=(10,))
outputs = tf.add_n([inputs, inputs, inputs])
return keras.Model(inputs, outputs)
def _reuse_op():
inputs = keras.Input(shape=(10,))
# This op needs to be checked multiple times.
x = tf.nn.relu(inputs)
y = keras.layers.Dense(10)(x)
x2 = x * 2
y2 = keras.layers.Dense(10)(x2)
outputs = y + y2
return keras.Model(inputs, outputs)
def _float64_op():
inputs = keras.Input(shape=(10,))
x = keras.layers.Dense(10, dtype="float64")(inputs)
x = tf.nn.relu(x)
assert x.dtype == "float64", f"x has dtype: {x.dtype}"
outputs = keras.layers.Dense(10)(x)
return keras.Model(inputs, outputs)
class MyAdd(keras.layers.Layer):
def call(self, x, y):
return x + y
def _layer_with_tensor_arg():
inputs = keras.Input(shape=(10,))
x = inputs * 2
outputs = MyAdd()(inputs, x)
return keras.Model(inputs, outputs)
class LayerWithLayer(keras.layers.Layer):
def build(self, input_shape):
self.bias = self.add_weight(name="bias", dtype="float32")
self.layer = keras.layers.Dense(10)
def call(self, inputs):
inputs = inputs * self.bias
# Would throw an error if TF-Keras History was created here.
return self.layer(inputs)
def _inner_layer():
inputs = keras.Input(shape=(10,))
outputs = LayerWithLayer()(inputs)
return keras.Model(inputs, outputs)
def _reuse_ancillary_layer():
inputs = (keras.Input(shape=(5,)), keras.Input(shape=(5,)))
base_model = keras.Sequential(
[
keras.layers.Dense(3, input_shape=(5,)),
]
)
outputs = base_model(inputs[0])
model = keras.Model(inputs, outputs)
# The second input is only involved in ancillary layers.
outputs_delta = outputs - base_model(0.5 * inputs[1])
l2_loss = tf.reduce_mean(tf.reduce_sum(tf.square(outputs_delta), -1))
model.add_loss(l2_loss)
model.add_metric(l2_loss, aggregation="mean", name="l2_loss")
l1_loss = 0.01 * tf.reduce_mean(tf.reduce_sum(tf.abs(outputs_delta), -1))
model.add_loss(l1_loss)
model.add_metric(l1_loss, aggregation="mean", name="l1_loss")
return model
@test_combinations.run_all_keras_modes()
class AutoLambdaTest(test_combinations.TestCase):
@parameterized.named_parameters(
("single_op_at_end", _single_op_at_end),
("single_identity_op_at_end", _single_identity_op_at_end),
("multiple_ops_at_end", _multiple_ops_at_end),
("single_op_in_middle", _single_op_in_middle),
("multiple_ops_in_middle", _multiple_ops_in_middle),
("shape_op_inference", _shape_op_inference),
("shape_op_known_batch_size", _shape_op_known_batch_size),
("shape_op_slice_and_range", _shape_op_slice_and_range),
(
"shape_op_slice_and_range_known_dim",
_shape_op_slice_and_range_known_dim,
),
(
"int32_manipulation_too_big_for_shape",
_int32_manipulation_too_big_for_shape,
),
(
"int32_manipulation_at_max_shape_dims_limit",
_int32_manipulation_at_max_shape_dims_limit,
),
("single_standalone_branch", _single_standalone_branch),
("single_op_with_attrs", _single_op_with_attrs),
("multiple_uses", _multiple_uses),
("op_with_tensor_list", _op_with_tensor_list),
("add_n", _add_n),
("_reuse_op", _reuse_op),
("_float64_op", _float64_op),
("_inner_layer", _inner_layer),
("_reuse_ancillary_layer", _reuse_ancillary_layer),
("_layer_with_tensor_arg", _layer_with_tensor_arg),
)
def test_autolambda(self, model_fn):
model = model_fn()
model.compile(
adam.Adam(0.001), "mse", run_eagerly=test_utils.should_run_eagerly()
)
np_inputs = tf.nest.map_structure(
lambda x: np.ones((2,) + tuple(x.shape[1:]), "float32"),
model.inputs,
)
np_outputs = tf.nest.map_structure(
lambda x: np.ones((2,) + tuple(x.shape[1:]), "float32"),
model.outputs,
)
model.fit(np_inputs, np_outputs, batch_size=2)
model(np_inputs) # Test calling the model directly on inputs.
new_model = keras.Model.from_config(
model.get_config(),
custom_objects={"LayerWithLayer": LayerWithLayer, "MyAdd": MyAdd},
)
new_model.compile(
adam.Adam(0.001), "mse", run_eagerly=test_utils.should_run_eagerly()
)
new_model.fit(np_inputs, np_outputs, batch_size=2)
new_model(np_inputs) # Test calling the new model directly on inputs.
# Assert that metrics are preserved and in the right order.
self.assertAllEqual(model.metrics_names, new_model.metrics_names)
# Assert that layer names don't change.
self.assertAllEqual(
[layer.name for layer in model.layers],
[layer.name for layer in new_model.layers],
)
def test_stack_preserves_correct_shape(self):
## Test stack([x])
inp = keras.Input(shape=(), dtype="float32")
out = tf.stack([inp])
model = keras.Model(inputs=inp, outputs=out)
model.compile(
adam.Adam(0.001), "mse", run_eagerly=test_utils.should_run_eagerly()
)
x = tf.ones(shape=(4, 4))
expected = tf.stack([x])
self.assertAllEqual(expected.shape, (1, 4, 4))
self.assertAllEqual(model(x).shape, (1, 4, 4))
self.assertAllEqual(model(x), expected)
config = model.get_config()
model = keras.Model.from_config(config)
self.assertAllEqual(model(x).shape, (1, 4, 4))
self.assertAllEqual(model(x), expected)
## Test stack(x)
inp = keras.Input(shape=(), dtype="float32")
out = tf.stack(inp)
model = keras.Model(inputs=inp, outputs=out)
model.compile(
adam.Adam(0.001), "mse", run_eagerly=test_utils.should_run_eagerly()
)
x = tf.ones(shape=(4, 4))
expected = tf.stack(x)
self.assertAllEqual(expected.shape, (4, 4))
self.assertAllEqual(model(x).shape, (4, 4))
self.assertAllEqual(model(x), expected)
config = model.get_config()
model = keras.Model.from_config(config)
self.assertAllEqual(model(x).shape, (4, 4))
self.assertAllEqual(model(x), expected)
def test_getitem_slice_with_step_only(self):
if not tf.executing_eagerly():
self.skipTest("Complex slicing like this fails in v1")
inp = keras.Input(shape=(8,))
slice_step = keras.Input(shape=(), dtype="int32")
out = inp[..., :: slice_step[0]]
model = keras.Model(inputs=[inp, slice_step], outputs=out)
model.compile(
adam.Adam(0.001), "mse", run_eagerly=test_utils.should_run_eagerly()
)
batch_size = 7
step = 3
x = tf.stack([tf.range(8) for _ in range(batch_size)])
args = [x, tf.constant(step, shape=(batch_size,))]
expected = tf.stack([tf.range(8)[::step] for _ in range(batch_size)])
if tf.compat.v1.executing_eagerly_outside_functions():
self.assertIn(
"tf.__operators__.getitem", (x.name for x in model.layers)
)
self.assertNotIn("tf.strided_slice", (x.name for x in model.layers))
self.assertAllEqual(model(args), expected)
self.assertAllEqual(
model.predict(args, batch_size=batch_size), expected
)
# Make sure it can be successfully saved and loaded
config = model.get_config()
model = keras.Model.from_config(config)
self.assertAllEqual(model(args), expected)
self.assertAllEqual(
model.predict(args, batch_size=batch_size), expected
)
def test_getitem_slice_real_tensor(self):
if not tf.executing_eagerly():
self.skipTest("Complex slicing like this fails in v1")
x = tf.range(10.0)
slice_stop = keras.Input(shape=(), dtype="int32")
out = x[: slice_stop[0]]
model = keras.Model(inputs=slice_stop, outputs=out)
model.compile(
adam.Adam(0.001), "mse", run_eagerly=test_utils.should_run_eagerly()
)
batch_size = 7
stop = 6
args = tf.constant(stop, shape=(batch_size,))
expected = x[:stop]
if tf.compat.v1.executing_eagerly_outside_functions():
self.assertIn(
"tf.__operators__.getitem", (x.name for x in model.layers)
)
# TODO(b/161925288): Fix the dispatch triggering then uncomment:
# self.assertNotIn('tf.strided_slice', (
# x.name for x in model.layers))
self.assertAllEqual(model(args), expected)
self.assertAllEqual(
model.predict(args, batch_size=batch_size), expected
)
config = model.get_config()
model = keras.Model.from_config(config)
self.assertAllEqual(model(args), expected)
self.assertAllEqual(
model.predict(args, batch_size=batch_size), expected
)
def test_getitem_index_real_tensor(self):
if not tf.executing_eagerly():
self.skipTest("Complex slicing like this fails in v1")
x = tf.range(10.0)
slice_stop = keras.Input(shape=(), dtype="int32")
out = x[slice_stop[0]]
model = keras.Model(inputs=slice_stop, outputs=out)
model.compile(
adam.Adam(0.001), "mse", run_eagerly=test_utils.should_run_eagerly()
)
batch_size = 7
index = 6
args = tf.constant(index, shape=(batch_size,))
expected = x[index]
if tf.compat.v1.executing_eagerly_outside_functions():
self.assertIn(
"tf.__operators__.getitem", (x.name for x in model.layers)
)
# TODO(b/161925288): Fix the bug then uncomment:
# self.assertNotIn('tf.strided_slice', (
# x.name for x in model.layers))
self.assertAllEqual(model(args), expected)
self.assertAllEqual(
model.predict(args, batch_size=batch_size), expected
)
# Make sure it can be successfully saved and loaded
config = model.get_config()
model = keras.Model.from_config(config)
self.assertAllEqual(model(args), expected)
self.assertAllEqual(
model.predict(args, batch_size=batch_size), expected
)
def test_getitem_slice_with_stop_only(self):
if not tf.executing_eagerly():
self.skipTest("Complex slicing like this fails in v1")
inp = keras.Input(shape=(8,))
slice_stop = keras.Input(shape=(), dtype="int32")
out = inp[: slice_stop[0]]
model = keras.Model(inputs=[inp, slice_stop], outputs=out)
model.compile(
adam.Adam(0.001), "mse", run_eagerly=test_utils.should_run_eagerly()
)
batch_size = 7
stop = 6
x = tf.stack([tf.range(8) for _ in range(batch_size)])
args = [x, tf.constant(stop, shape=(batch_size,))]
expected = x[:stop]
if tf.compat.v1.executing_eagerly_outside_functions():
self.assertIn(
"tf.__operators__.getitem", (x.name for x in model.layers)
)
self.assertNotIn("tf.strided_slice", (x.name for x in model.layers))
self.assertAllEqual(model(args), expected)
self.assertAllEqual(
model.predict(args, batch_size=batch_size), expected
)
# Make sure it can be successfully saved and loaded
config = model.get_config()
model = keras.Model.from_config(config)
self.assertAllEqual(model(args), expected)
self.assertAllEqual(
model.predict(args, batch_size=batch_size), expected
)
def test_getitem_slice_with_stop_and_ellipsis_only(self):
if not tf.executing_eagerly():
self.skipTest("Complex slicing like this fails in v1")
inp = keras.Input(shape=(8,))
slice_stop = keras.Input(shape=(), dtype="int32")
out = inp[..., : slice_stop[0]]
model = keras.Model(inputs=[inp, slice_stop], outputs=out)
model.compile(
adam.Adam(0.001), "mse", run_eagerly=test_utils.should_run_eagerly()
)
batch_size = 7
stop = 6
x = tf.stack([tf.range(8) for _ in range(batch_size)])
args = [x, tf.constant(stop, shape=(batch_size,))]
expected = tf.stack([tf.range(8)[:stop] for _ in range(batch_size)])
if tf.compat.v1.executing_eagerly_outside_functions():
self.assertIn(
"tf.__operators__.getitem", (x.name for x in model.layers)
)
self.assertNotIn("tf.strided_slice", (x.name for x in model.layers))
self.assertAllEqual(model(args), expected)
self.assertAllEqual(
model.predict(args, batch_size=batch_size), expected
)
# Make sure it can be successfully saved and loaded
config = model.get_config()
model = keras.Model.from_config(config)
self.assertAllEqual(model(args), expected)
self.assertAllEqual(
model.predict(args, batch_size=batch_size), expected
)
def test_getitem_complex_slicing(self):
if not tf.executing_eagerly():
self.skipTest("Complex slicing like this fails in v1")
inp = keras.Input(shape=(4, 3, 8))
first_dim = keras.Input(shape=(), dtype="int32")
slice_start = keras.Input(shape=(), dtype="int32")
slice_stop = keras.Input(shape=(), dtype="int32")
slice_stride = keras.Input(shape=(), dtype="int32")
out = inp[
..., first_dim[0], slice_start[0] : slice_stop[0] : slice_stride[0]
]
model = keras.Model(
inputs=[inp, first_dim, slice_start, slice_stop, slice_stride],
outputs=out,
)
model.compile(
adam.Adam(0.001), "mse", run_eagerly=test_utils.should_run_eagerly()
)
batch_size = 7
start = 1
stop = 6
step = 2
x = tf.stack(
[
tf.stack(
[
tf.stack([tf.range(8) for _ in range(3)])
for _ in range(4)
]
)
for _ in range(batch_size)
]
)
args = [
x,
tf.constant(0, shape=(batch_size,)),
tf.constant(start, shape=(batch_size,)),
tf.constant(stop, shape=(batch_size,)),
tf.constant(step, shape=(batch_size,)),
]
# Slice the innermost dim. only grab one index from the
# second-to-innermost dim, removing that dim from the shape.
expected = tf.stack(
[
tf.stack([tf.range(8)[start:stop:step] for _ in range(4)])
for _ in range(batch_size)
]
)
if tf.compat.v1.executing_eagerly_outside_functions():
self.assertIn(
"tf.__operators__.getitem", (x.name for x in model.layers)
)
self.assertNotIn("tf.strided_slice", (x.name for x in model.layers))
self.assertAllEqual(model(args), expected)
self.assertAllEqual(
model.predict(args, batch_size=batch_size), expected
)
# Make sure it can be successfully saved and loaded
config = model.get_config()
model = keras.Model.from_config(config)
self.assertAllEqual(model(args), expected)
self.assertAllEqual(
model.predict(args, batch_size=batch_size), expected
)
def test_left_hand_numpy_multiplication(self):
x = np.asarray([3.0])
inputs = keras.Input(shape=(4,))
outputs = x * inputs
model = keras.Model(inputs, outputs)
ones = tf.ones((5, 4), dtype="float32")
self.assertAllEqual(model(ones), 3.0 * ones)
def test_numerical_correctness_simple(self):
x = tf.convert_to_tensor([[-1.0, 0.0, -2.0, 1.0]])
inputs = keras.Input(shape=(4,))
outputs = tf.nn.relu(inputs)
model = keras.Model(inputs, outputs)
y = self.evaluate(model(x))
self.assertAllClose(y, [[0.0, 0.0, 0.0, 1.0]])
def test_numerical_correctness_with_attrs(self):
x = tf.convert_to_tensor([[1.5, 1.5], [2.5, 3.5]])
inputs = keras.Input(shape=(2,))
outputs = tf.reduce_mean(inputs, axis=1)
model = keras.Model(inputs, outputs)
y = self.evaluate(model(x))
self.assertAllClose(y, [1.5, 3.0])
def test_numerical_correctness_serialization(self):
x = tf.convert_to_tensor([[-1.0, 0.0, -2.0, 1.0]])
inputs = keras.Input(shape=(4,))
outputs = tf.nn.relu(inputs)
model1 = keras.Model(inputs, outputs)
y1 = self.evaluate(model1(x))
model2 = keras.Model.from_config(model1.get_config())
y2 = self.evaluate(model2(x))
self.assertAllClose(y1, y2)
def test_gradient_tape_in_function(self):
z = keras.Input((1,))
x = tf.matmul(z, tf.constant(2.0, shape=(1, 1)))
x = tf.reduce_mean(x, axis=0, keepdims=True)
h = tf.nn.relu(x)
m = keras.Model(z, h)
@tf.function()
def f(x):
with tf.GradientTape() as t:
t.watch(x)
z = m(x**2)
grads = t.gradient(z, x)
return grads
self.assertAllEqual(
f(tf.constant(10.0, shape=(1, 1))), tf.constant(40.0, shape=(1, 1))
)
f = tf.function(f)
self.assertAllEqual(
f(tf.constant(10.0, shape=(1, 1))), tf.constant(40.0, shape=(1, 1))
)
def test_no_tracking(self):
if not tf.executing_eagerly():
x = tf.constant(1.0, shape=(10, 10))
keras.layers.Dense(1)(x)
self.assertTrue(x._keras_history_checked)
def test_timing_scales_linearly(self):
def _construct_graph_of_size(size):
start = time.time()
x = keras.backend.placeholder(shape=(10, 4))
for _ in range(size):
x = keras.layers.Dense(4)(x)
x = tf.nn.relu(x)
end = time.time()
return end - start
size_50 = _construct_graph_of_size(50)
size_500 = _construct_graph_of_size(500)
# Check construction time grows approx. linearly with size.
e = 3 # Fudge factor to prevent flakiness.
self.assertLess(size_500, (10 * e) * size_50)
def test_built(self):
inputs = keras.Input(shape=(10,))
outputs = tf.nn.relu(inputs)
model = keras.Model(inputs, outputs)
model.compile("sgd", "mse")
for layer in model.layers:
self.assertTrue(layer.built)
# Test something that requires Layers to be built.
model.summary()
def test_json_serialization(self):
inputs = keras.Input(shape=(4,), dtype="uint8")
outputs = tf.cast(inputs, "float32") / 4.0
model = model_config.model_from_json(
keras.Model(inputs, outputs).to_json()
)
self.assertAllEqual(
self.evaluate(model(np.array([0, 64, 128, 192], np.uint8))),
[0.0, 16.0, 32.0, 48.0],
)
model.summary()
@test_combinations.run_all_keras_modes(always_skip_v1=True)
class InputInEagerTest(test_combinations.TestCase):
"""Tests ops on keras inputs in Eager runtime.
Input returns graph/symbolic tensors in the Eager runtime (this
happens, for example, with tensors returned from TF-Keras layers). These
should be routed to the graph-style branch of these ops (b/134715641)
"""
def test_identity(self):
x = keras.Input(shape=(1,))
ident = tf.identity(x)
# This is now a graph tensor, and should be able to continue in
# graphland
self.assertIn("Identity", ident.name)
def test_size(self):
x = keras.Input(shape=(3,))
self.assertAllEqual(x.get_shape().as_list(), [None, 3])
sz = tf.size(x)
# This is now a graph tensor, and should be able to continue in
# graphland
self.assertIn("Size", sz.name)
if __name__ == "__main__":
tf.test.main()
| tf-keras/tf_keras/layers/tensorflow_op_layer_test.py/0 | {
"file_path": "tf-keras/tf_keras/layers/tensorflow_op_layer_test.py",
"repo_id": "tf-keras",
"token_count": 12685
} | 191 |
# Copyright 2015 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 variable store."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gc
import threading
import numpy
import tensorflow as tf
from absl.testing import parameterized
from tf_keras import models
from tf_keras import regularizers
from tf_keras.engine import base_layer
from tf_keras.engine import input_layer as input_layer_module
from tf_keras.engine import training as training_module
from tf_keras.layers import core
from tf_keras.legacy_tf_layers import core as core_layers
from tf_keras.legacy_tf_layers import variable_scope_shim
from tf_keras.testing_infra import test_combinations
# isort: off
from tensorflow.python.framework import (
test_util as tf_test_utils,
)
from tensorflow.python.ops import variable_scope
def run_inside_wrap_function_in_eager_mode(graph_function):
"""Decorator to execute the same graph code in eager and graph modes.
In graph mode, we just execute the graph_function passed as argument. In
eager mode, we wrap the function using wrap_function and then execute the
wrapped result.
Args:
graph_function: python function containing graph code to be wrapped
Returns:
decorated function
"""
def wrap_and_execute(self):
store = variable_scope_shim._EagerVariableStore()
with variable_scope.with_variable_store(store):
# use the original function
graph_function(self)
return wrap_and_execute
class VariableScopeTest(tf.test.TestCase):
def tearDown(self):
gc.collect()
# This will only contain uncollectable garbage, i.e. reference cycles
# involving objects with __del__ defined.
self.assertEqual(0, len(gc.garbage))
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testGetVar(self):
vs = variable_scope._get_default_variable_store()
v = vs.get_variable("v", [1])
v1 = vs.get_variable("v", [1])
self.assertIs(v, v1)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testNameExists(self):
vs = variable_scope._get_default_variable_store()
# No check by default, so we can both create and get existing names.
v = vs.get_variable("v", [1])
v1 = vs.get_variable("v", [1])
self.assertIs(v, v1)
self.assertIsNot(v, vs.get_variable("u", [1], reuse=False))
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testNamelessStore(self):
vs = variable_scope._get_default_variable_store()
vs.get_variable("v1", [2])
vs.get_variable("v2", [2])
expected_names = [f"{name}:0" for name in ["v1", "v2"]]
self.assertEqual(
set(expected_names), set(v.name for v in vs._vars.values())
)
# TODO(mihaimaruseac): Not converted to use wrap_function because of
# TypeError: Expected tf.group() expected Tensor arguments not 'None' with
# type '<type 'NoneType'>'
@tf_test_utils.run_in_graph_and_eager_modes
def testVarScopeInitializer(self):
init = tf.compat.v1.constant_initializer(0.3)
with tf.compat.v1.variable_scope("tower0") as tower:
with tf.compat.v1.variable_scope("foo", initializer=init):
v = tf.compat.v1.get_variable("v", [])
self.evaluate(tf.compat.v1.variables_initializer([v]))
self.assertAllClose(self.evaluate(v.value()), 0.3)
with tf.compat.v1.variable_scope(tower, initializer=init):
w = tf.compat.v1.get_variable("w", [])
self.evaluate(tf.compat.v1.variables_initializer([w]))
self.assertAllClose(self.evaluate(w.value()), 0.3)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarScopeConstraint(self):
constraint = lambda x: 0.0 * x
with tf.compat.v1.variable_scope("tower1") as tower:
with tf.compat.v1.variable_scope("foo", constraint=constraint):
v = tf.compat.v1.get_variable("v", [])
self.assertIsNotNone(v.constraint)
with tf.compat.v1.variable_scope(tower, constraint=constraint):
w = tf.compat.v1.get_variable("w", [])
self.assertIsNotNone(w.constraint)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarScopeDType(self):
with tf.compat.v1.variable_scope("tower2") as tower:
with tf.compat.v1.variable_scope("foo", dtype=tf.float16):
v = tf.compat.v1.get_variable("v", [])
self.assertEqual(v.dtype.base_dtype, tf.float16)
with tf.compat.v1.variable_scope(tower, dtype=tf.float16):
w = tf.compat.v1.get_variable("w", [])
self.assertEqual(w.dtype.base_dtype, tf.float16)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testInitFromNonTensorValue(self):
v = tf.compat.v1.get_variable("v4", initializer=4, dtype=tf.int32)
self.evaluate(tf.compat.v1.variables_initializer([v]))
self.assertAllClose(self.evaluate(v.value()), 4)
w = tf.compat.v1.get_variable(
"w4", initializer=numpy.array([1, 2, 3]), dtype=tf.int64
)
self.evaluate(tf.compat.v1.variables_initializer([w]))
self.assertAllClose(self.evaluate(w.value()), [1, 2, 3])
# A quirk to be revisited?
error = ValueError if tf.executing_eagerly() else TypeError
with self.assertRaises(error):
tf.compat.v1.get_variable("x4", initializer={})
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testInitFromNonInitializer(self):
# Test various dtypes with zeros initializer as following:
types = [
tf.int8,
tf.uint8,
tf.int16,
tf.uint16,
tf.int32,
tf.int64,
tf.bool,
]
# Use different variable_name to distinguish various dtypes
for i, dtype in enumerate(types):
x = tf.compat.v1.get_variable(
name="xx%d" % i, shape=(3, 4), dtype=dtype
)
y = tf.compat.v1.get_variable(
name="yy%d" % i,
shape=(3, 4),
dtype=dtype,
initializer=tf.compat.v1.zeros_initializer(dtype=dtype),
)
self.evaluate(tf.compat.v1.global_variables_initializer())
self.assertAllEqual(
self.evaluate(x.value()), self.evaluate(y.value())
)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarScopeRegularizer(self):
init = tf.compat.v1.constant_initializer(0.3)
def regularizer1(v):
return tf.reduce_mean(v) + 0.1
def regularizer2(v):
return tf.reduce_mean(v) + 0.2
with tf.compat.v1.variable_scope(
"tower3", regularizer=regularizer1
) as tower:
with tf.compat.v1.variable_scope("foo", initializer=init):
v = tf.compat.v1.get_variable("v", [])
self.evaluate(tf.compat.v1.variables_initializer([v]))
with tf.compat.v1.variable_scope(tower, initializer=init) as vs:
tf.compat.v1.get_variable("u", [])
vs.set_regularizer(regularizer2)
tf.compat.v1.get_variable("w", [])
# Next 3 variable not regularized to test disabling
# regularization.
tf.compat.v1.get_variable(
"x", [], regularizer=tf.compat.v1.no_regularizer
)
with tf.compat.v1.variable_scope(
"baz", regularizer=tf.compat.v1.no_regularizer
):
tf.compat.v1.get_variable("y", [])
vs.set_regularizer(tf.compat.v1.no_regularizer)
tf.compat.v1.get_variable("z", [])
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testInitializeFromValue(self):
init = tf.constant(0.1)
w = tf.compat.v1.get_variable("v", initializer=init)
self.evaluate(tf.compat.v1.variables_initializer([w]))
self.assertAllClose(self.evaluate(w.value()), 0.1)
with self.assertRaisesRegex(ValueError, "shape"):
# We disallow explicit shape specification when initializer is
# constant.
tf.compat.v1.get_variable("u", [1], initializer=init)
with tf.compat.v1.variable_scope("foo", initializer=init):
# Constant initializer can be passed through scopes if needed.
v = tf.compat.v1.get_variable("v")
self.evaluate(tf.compat.v1.variables_initializer([v]))
self.assertAllClose(self.evaluate(v.value()), 0.1)
# Check that non-float32 initializer creates a non-float32 variable.
init = tf.constant(1, dtype=tf.int32)
t = tf.compat.v1.get_variable("t", initializer=init)
self.assertEqual(t.dtype.base_dtype, tf.int32)
# Raise error if `initializer` dtype and `dtype` are not identical.
with self.assertRaisesRegex(ValueError, "don't match"):
tf.compat.v1.get_variable("s", initializer=init, dtype=tf.float64)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarScopeGetOrCreateReuse(self):
with self.cached_session():
def test_value(value):
x = tf.constant(value)
with tf.compat.v1.variable_scope(
"testVarScopeGetOrCreateReuse_bar",
reuse=tf.compat.v1.AUTO_REUSE,
):
_ = tf.compat.v1.assign(
tf.compat.v1.get_variable("var", []), x
)
with tf.compat.v1.variable_scope(
"testVarScopeGetOrCreateReuse_bar",
reuse=tf.compat.v1.AUTO_REUSE,
):
_ = tf.compat.v1.get_variable("var", [])
self.assertEqual(value, self.evaluate(x))
test_value(42.0) # Variable is created.
test_value(13.0) # Variable is reused hereafter.
test_value(17.0)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarScopeGetOrCreateReuseIgnoreFalse(self):
with self.cached_session():
def test_value(value):
x = tf.constant(value)
with tf.compat.v1.variable_scope(
"testVarScopeGetOrCreateReuse_bar", reuse=False
):
_ = tf.compat.v1.assign(
tf.compat.v1.get_variable("var", []), x
)
# We need to ignore reuse=False in the shim, because the code is
# expected to get rerun each time the user calls the shim.
with tf.compat.v1.variable_scope(
"testVarScopeGetOrCreateReuse_bar", reuse=False
):
_ = tf.compat.v1.get_variable("var", [])
self.assertEqual(value, self.evaluate(x))
test_value(42.0) # Variable is created.
test_value(13.0) # Variable is reused hereafter.
test_value(17.0)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarOpScope(self):
with self.cached_session():
with tf.name_scope("testVarOpScope1"):
with tf.compat.v1.variable_scope("tower", "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "tower/w:0"
)
with tf.name_scope("testVarOpScope2"):
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "default/w:0"
)
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "default_1/w:0"
)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarOpScopeUniqueNamesInterleavedSubstringScopes(self):
with self.cached_session():
with tf.compat.v1.variable_scope(None, "defaultScope1"):
with tf.compat.v1.variable_scope(None, "layer"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"defaultScope1/layer/w:0",
)
with tf.compat.v1.variable_scope(None, "defaultScope1"):
with tf.compat.v1.variable_scope(None, "layer"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"defaultScope1_1/layer/w:0",
)
with tf.compat.v1.variable_scope(None, "defaultScope"):
with tf.compat.v1.variable_scope(None, "layer"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"defaultScope/layer/w:0",
)
with tf.compat.v1.variable_scope(None, "defaultScope1"):
with tf.compat.v1.variable_scope(None, "layer"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"defaultScope1_2/layer/w:0",
)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarOpScopeUniqueNamesWithJump(self):
with self.cached_session():
with tf.compat.v1.variable_scope("default") as default:
with tf.compat.v1.variable_scope(None, "layer"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"default/layer/w:0",
)
with tf.compat.v1.variable_scope(None, "layer"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"default/layer_1/w:0",
)
with tf.compat.v1.variable_scope(default):
pass
# No matter the jump in the middle, unique numbering continues.
with tf.compat.v1.variable_scope(None, "layer"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"default/layer_2/w:0",
)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarOpScopeReuse(self):
with self.cached_session():
with tf.compat.v1.variable_scope("outer") as outer:
with tf.compat.v1.variable_scope("tower", "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/tower/w:0",
)
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/default/w:0",
)
with tf.compat.v1.variable_scope(outer, reuse=True) as outer:
with tf.compat.v1.variable_scope("tower", "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/tower/w:0",
)
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/default/w:0",
)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarScopeGetVar(self):
with self.cached_session():
with tf.compat.v1.variable_scope("root"):
with tf.compat.v1.variable_scope("towerA") as tower_a:
va = tf.compat.v1.get_variable("v", [1])
self.assertEqual(va.name, "root/towerA/v:0")
with tf.compat.v1.variable_scope(tower_a, reuse=True):
va2 = tf.compat.v1.get_variable("v", [1])
self.assertIs(va2, va)
with tf.compat.v1.variable_scope("towerB"):
vb = tf.compat.v1.get_variable("v", [1])
self.assertEqual(vb.name, "root/towerB/v:0")
with tf.compat.v1.variable_scope("towerA", reuse=True):
va2 = tf.compat.v1.get_variable("v", [1])
self.assertIs(va2, va)
with tf.compat.v1.variable_scope("foo"):
with tf.compat.v1.variable_scope("bar"):
v = tf.compat.v1.get_variable("v", [1])
self.assertEqual(v.name, "root/foo/bar/v:0")
with tf.compat.v1.variable_scope(tower_a, reuse=True):
va3 = tf.compat.v1.get_variable("v", [1])
self.assertIs(va, va3)
with self.assertRaises(ValueError) as exc:
with tf.compat.v1.variable_scope(tower_a, reuse=True):
tf.compat.v1.get_variable("v", [2]) # Different shape.
self.assertEqual("shape" in str(exc.exception), True)
with self.assertRaises(ValueError) as exc:
with tf.compat.v1.variable_scope(tower_a, reuse=True):
tf.compat.v1.get_variable("v", [1], dtype=tf.int32)
self.assertEqual("dtype" in str(exc.exception), True)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarScopeOuterScope(self):
with self.cached_session():
with tf.compat.v1.variable_scope("outer") as outer:
pass
with tf.compat.v1.variable_scope(outer):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/w:0"
)
with tf.compat.v1.variable_scope("default"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/default/w:0",
)
with tf.compat.v1.variable_scope(outer, reuse=True):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/w:0"
)
with tf.compat.v1.variable_scope("default", reuse=True):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/default/w:0",
)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarScopeNestedOuterScope(self):
with self.cached_session():
with tf.compat.v1.variable_scope("outer") as outer:
with tf.compat.v1.variable_scope(outer):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/w:0"
)
with tf.compat.v1.variable_scope("default"):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/default/w:0",
)
with tf.compat.v1.variable_scope(outer, reuse=True):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/w:0"
)
with tf.compat.v1.variable_scope("default", reuse=True):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/default/w:0",
)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarOpScopeReuseParam(self):
with self.cached_session():
with tf.compat.v1.variable_scope("outer") as outer:
with tf.compat.v1.variable_scope("tower", "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/tower/w:0",
)
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/default/w:0",
)
with tf.compat.v1.variable_scope(outer) as outer:
with tf.compat.v1.variable_scope(
"tower", "default", reuse=True
):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/tower/w:0",
)
outer.reuse_variables()
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/default/w:0",
)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarOpScopeReuseError(self):
with self.cached_session():
with self.assertRaises(ValueError):
with tf.compat.v1.variable_scope(None, "default", reuse=True):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/tower/w:0",
)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarOpScopeOuterScope(self):
with self.cached_session():
with tf.compat.v1.variable_scope("outer") as outer:
pass
with tf.compat.v1.variable_scope(outer, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/w:0"
)
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/default/w:0",
)
with tf.compat.v1.variable_scope(outer, "default", reuse=True):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/w:0"
)
outer.reuse_variables()
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/default/w:0",
)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVarOpScopeNestedOuterScope(self):
with self.cached_session():
with tf.compat.v1.variable_scope("outer") as outer:
with tf.compat.v1.variable_scope(outer, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/w:0"
)
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/default/w:0",
)
with tf.compat.v1.variable_scope(outer, "default", reuse=True):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "outer/w:0"
)
with tf.compat.v1.variable_scope(None, "default", []):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/default/w:0",
)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testBasicWhenAuxiliaryNameScopeIsFalse(self):
with self.cached_session():
with tf.compat.v1.variable_scope(
"scope", auxiliary_name_scope=False
) as scope:
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "scope/w:0"
)
with tf.compat.v1.variable_scope(scope, auxiliary_name_scope=False):
self.assertEqual(
tf.compat.v1.get_variable("w1", []).name, "scope/w1:0"
)
with tf.compat.v1.variable_scope("outer"):
with tf.compat.v1.variable_scope(
"inner", auxiliary_name_scope=False
) as inner:
self.assertEqual(inner.original_name_scope, "outer/")
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/inner/w:0",
)
with tf.compat.v1.variable_scope(
inner, auxiliary_name_scope=False
) as inner1:
self.assertEqual(inner1.original_name_scope, "outer/")
self.assertEqual(
tf.compat.v1.get_variable("w1", []).name,
"outer/inner/w1:0",
)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testCreatedByDefaultNameWhenAuxiliaryNameScopeIsFalse(self):
with self.cached_session():
with tf.compat.v1.variable_scope(
None, default_name="default", auxiliary_name_scope=False
):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name, "default/w:0"
)
with tf.compat.v1.variable_scope("outer"):
with tf.compat.v1.variable_scope(
None, default_name="default", auxiliary_name_scope=False
) as inner:
self.assertEqual(inner.original_name_scope, "outer/")
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/default/w:0",
)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testReenterRootScopeWhenAuxiliaryNameScopeIsFalse(self):
with self.cached_session():
root_scope = tf.compat.v1.get_variable_scope()
with tf.compat.v1.variable_scope(
root_scope, auxiliary_name_scope=False
):
self.assertEqual(tf.compat.v1.get_variable("w", []).name, "w:0")
with tf.compat.v1.variable_scope("outer"):
with tf.compat.v1.variable_scope(
root_scope, auxiliary_name_scope=False
) as inner:
self.assertEqual(inner.original_name_scope, "")
self.assertEqual(
tf.compat.v1.get_variable("w1", []).name, "w1:0"
)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testAuxiliaryNameScopeIsInvalid(self):
with self.cached_session():
with self.assertRaisesRegex(TypeError, "auxiliary_name_scope"):
with tf.compat.v1.variable_scope(
None, default_name="scope", auxiliary_name_scope="invalid"
):
pass
with self.assertRaisesRegex(TypeError, "auxiliary_name_scope"):
with tf.compat.v1.variable_scope(
"scope", auxiliary_name_scope="invalid"
):
pass
with tf.compat.v1.variable_scope("scope") as scope:
pass
with self.assertRaisesRegex(TypeError, "auxiliary_name_scope"):
with tf.compat.v1.variable_scope(
scope, auxiliary_name_scope="invalid"
):
pass
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testReuseScopeWithoutNameScopeCollision(self):
# GitHub issue: #13429
with self.cached_session():
with tf.compat.v1.variable_scope("outer"):
with tf.compat.v1.variable_scope("inner") as inner:
pass
with tf.compat.v1.variable_scope(
inner, auxiliary_name_scope=False
) as scope:
with tf.name_scope(scope.original_name_scope):
self.assertEqual(
tf.compat.v1.get_variable("w", []).name,
"outer/inner/w:0",
)
with tf.compat.v1.variable_scope("another"):
with tf.compat.v1.variable_scope(
inner, auxiliary_name_scope=False
) as scope1:
with tf.name_scope(scope1.original_name_scope):
self.assertEqual(
tf.compat.v1.get_variable("w1", []).name,
"outer/inner/w1:0",
)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testGetVarWithDevice(self):
g = tf.Graph()
varname_type = []
def device_func(op):
if op.type in ["Variable", "VariableV2", "VarHandleOp"]:
varname_type.append((op.name, op.get_attr("dtype")))
return "/device:GPU:0"
with g.as_default():
with tf.compat.v1.device(device_func):
_ = tf.compat.v1.get_variable("x", (100, 200))
_ = tf.compat.v1.get_variable(
"y", dtype=tf.int64, initializer=numpy.arange(73)
)
self.assertEqual(varname_type[0], ("x", tf.float32))
self.assertEqual(varname_type[1], ("y", tf.int64))
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testGetVariableWithRefDtype(self):
v = tf.compat.v1.get_variable("v", shape=[3, 4], dtype=tf.float32)
# Ensure it is possible to do get_variable with a _ref dtype passed in.
_ = tf.compat.v1.get_variable("w", shape=[5, 6], dtype=v.dtype)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testGetVariableWithInitializerWhichTakesNoArgs(self):
v = tf.compat.v1.get_variable("foo", initializer=lambda: [2])
self.assertEqual(v.name, "foo:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testGetVariableWithInitializerWhichTakesOptionalArgs(self):
v = tf.compat.v1.get_variable("foo", initializer=lambda x=True: [2])
self.assertEqual(v.name, "foo:0")
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testTwoGraphs(self):
def f():
g1 = tf.Graph()
g2 = tf.Graph()
with g1.as_default():
with g2.as_default():
with tf.compat.v1.variable_scope("_"):
pass
self.assertRaisesRegex(
ValueError, "'_' is not a valid (?:root )?scope name", f
)
class VariableScopeWithCustomGetterTest(tf.test.TestCase):
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testNonCallableGetterFails(self):
with self.assertRaisesRegex(
ValueError, r"custom_getter .* not callable:"
):
with tf.compat.v1.variable_scope("scope0", custom_getter=3):
tf.compat.v1.get_variable("name0")
with self.assertRaisesRegex(
ValueError, r"custom_getter .* not callable:"
):
tf.compat.v1.get_variable("name0", custom_getter=3)
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testNoSideEffectsWithIdentityCustomGetter(self):
called = [0]
def custom_getter(getter, *args, **kwargs):
called[0] += 1
return getter(*args, **kwargs)
with tf.compat.v1.variable_scope(
"scope", custom_getter=custom_getter
) as scope:
v = tf.compat.v1.get_variable("v", [1])
with tf.compat.v1.variable_scope(scope, reuse=True):
v2 = tf.compat.v1.get_variable("v", [1])
with tf.compat.v1.variable_scope("new_scope") as new_scope:
v3 = tf.compat.v1.get_variable("v3", [1])
with tf.compat.v1.variable_scope(
new_scope, reuse=True, custom_getter=custom_getter
):
v4 = tf.compat.v1.get_variable("v3", [1])
self.assertIs(v, v2)
self.assertIs(v3, v4)
self.assertEqual(3, called[0]) # skipped one in the first new_scope
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testSynchronizationAndAggregationWithCustomGetter(self):
called = [0]
synchronization = tf.VariableSynchronization.AUTO
aggregation = tf.compat.v1.VariableAggregation.NONE
def custom_getter(getter, *args, **kwargs):
called[0] += 1
# Verify synchronization and aggregation kwargs are as expected.
self.assertEqual(kwargs["synchronization"], synchronization)
self.assertEqual(kwargs["aggregation"], aggregation)
return getter(*args, **kwargs)
with tf.compat.v1.variable_scope("scope", custom_getter=custom_getter):
tf.compat.v1.get_variable("v", [1])
self.assertEqual(1, called[0])
with tf.compat.v1.variable_scope("scope", custom_getter=custom_getter):
synchronization = tf.VariableSynchronization.ON_READ
aggregation = tf.compat.v1.VariableAggregation.MEAN
tf.compat.v1.get_variable(
"v1",
[1],
synchronization=synchronization,
aggregation=aggregation,
)
self.assertEqual(2, called[0])
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVariableCreator(self):
variable_names = []
def creator_a(next_creator, **kwargs):
variable_names.append(kwargs.get("name", ""))
return next_creator(**kwargs)
def creator_b(next_creator, **kwargs):
kwargs["name"] = "forced_name"
return next_creator(**kwargs)
with tf.variable_creator_scope(creator_a):
with tf.variable_creator_scope(creator_b):
tf.compat.v1.Variable(1.0, name="one_name")
self.assertEqual(variable_names[0], "forced_name")
called = [False]
def creater_c(next_creator, **kwargs):
called[0] = True
self.assertEqual(
kwargs["synchronization"], tf.VariableSynchronization.ON_WRITE
)
self.assertEqual(
kwargs["aggregation"], tf.compat.v1.VariableAggregation.MEAN
)
return next_creator(**kwargs)
with tf.variable_creator_scope(creater_c):
tf.compat.v1.get_variable(
"v",
[],
synchronization=tf.VariableSynchronization.ON_WRITE,
aggregation=tf.compat.v1.VariableAggregation.MEAN,
)
self.assertTrue(called[0])
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testVariableCreatorNestingError(self):
def creator(next_creator, **kwargs):
return next_creator(**kwargs)
# Save the state so we can clean up at the end.
graph = tf.compat.v1.get_default_graph()
old_creator_stack = graph._variable_creator_stack
try:
scope = tf.variable_creator_scope(creator)
scope.__enter__()
with tf.variable_creator_scope(creator):
with self.assertRaises(RuntimeError):
scope.__exit__(None, None, None)
finally:
graph._variable_creator_stack = old_creator_stack
class VariableScopeMultithreadedTest(tf.test.TestCase):
@tf_test_utils.run_in_graph_and_eager_modes
@run_inside_wrap_function_in_eager_mode
def testReenterMainScope(self):
def thread_fn(graph, main_thread_scope):
with graph.as_default():
# Variable created with main scope will have prefix "main".
with tf.compat.v1.variable_scope(main_thread_scope):
with tf.compat.v1.variable_scope("foo"):
v = tf.compat.v1.get_variable("v", [])
self.assertEqual("main/foo/v:0", v.name)
# Variable created outside main scope will not have prefix
# "main".
with tf.compat.v1.variable_scope("bar"):
v = tf.compat.v1.get_variable("v", [])
self.assertEqual("bar/v:0", v.name)
graph = tf.compat.v1.get_default_graph()
with tf.compat.v1.variable_scope("main") as main_thread_scope:
thread = threading.Thread(
target=thread_fn, args=(graph, main_thread_scope)
)
thread.start()
thread.join()
class CompatV1TemplateScaleByY(base_layer.Layer):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def my_op(x, scalar_name):
var1 = tf.compat.v1.get_variable(
scalar_name,
shape=[],
regularizer=regularizers.L2(),
initializer=tf.compat.v1.constant_initializer(1.5),
)
return x * var1
self.scale_by_y = tf.compat.v1.make_template(
"scale_by_y", my_op, scalar_name="y"
)
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs):
with tf.compat.v1.variable_scope("foo"):
return self.scale_by_y(inputs)
class VariableScopeModule(tf.Module):
"""Module that uses the shim."""
@variable_scope_shim.track_tf1_style_variables
def __call__(self, *args, **kwargs):
with self.name_scope:
return self.forward_pass(*args, **kwargs)
def get_compat_v1_regularization_losses(self):
"""Dict w/ regularization losses from
`get_variable`&`compat.v1.layers`."""
return {
name: regularizer()
for name, regularizer in self._tf1_style_var_store._regularizers.items() # noqa: E501
}
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
class TF1VariableScopeLayerTest(tf.test.TestCase, parameterized.TestCase):
def test_get_variable(self):
# Test the shim when using `get_variable` (and regularizers) directly
class WrappedDenseLayer(base_layer.Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs, training=None):
out = inputs
with tf.compat.v1.variable_scope("dense_one"):
# The weights are created with a `regularizer`,
# so the layer should track their regularization losses
kernel = tf.compat.v1.get_variable(
shape=[out.shape[-1], self.units],
regularizer=regularizers.L2(),
initializer=tf.compat.v1.ones_initializer(),
name="kernel",
)
bias = tf.compat.v1.get_variable(
shape=[
self.units,
],
initializer=tf.compat.v1.zeros_initializer(),
name="bias",
)
out = tf.matmul(out, kernel)
out = tf.nn.bias_add(out, bias)
with tf.compat.v1.variable_scope("nested_scope"):
with tf.compat.v1.variable_scope("dense_two"):
kernel = tf.compat.v1.get_variable(
shape=[out.shape[-1], self.units],
regularizer=regularizers.L2(),
initializer=tf.compat.v1.ones_initializer(),
name="kernel",
)
bias = tf.compat.v1.get_variable(
shape=[
self.units,
],
initializer=tf.compat.v1.zeros_initializer(),
name="bias",
)
out = tf.matmul(out, kernel)
out = tf.nn.bias_add(out, bias)
return out
layer = WrappedDenseLayer(10)
out = layer(tf.ones(shape=(5, 5)))
weights = {x.name: x for x in layer.variables}
# Verify the correct output, regularization losses, + variables were
# made
self.assertEqual(
weights.keys(),
{
"dense_one/bias:0",
"dense_one/kernel:0",
"nested_scope/dense_two/bias:0",
"nested_scope/dense_two/kernel:0",
},
)
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 50)
self.assertAllEqual(tf.add_n(layer.losses), 1.5)
# Verify reuse by updating the variables then re-running
weights["dense_one/kernel:0"].assign(tf.ones(shape=(5, 10)) * 2)
weights["nested_scope/dense_two/kernel:0"].assign(
tf.ones(shape=(10, 10)) * 2
)
out = layer(tf.ones(shape=(5, 5)))
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 200)
self.assertAllEqual(tf.add_n(layer.losses), 6)
def test_compat_v1_layer(self):
# Test the shim when using `compat.v1` layers
class WrappedDenseLayer(base_layer.Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs, training=None):
out = core_layers.dense(
inputs,
self.units,
name="dense_one",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2",
)
with tf.compat.v1.variable_scope("nested_scope"):
out = core_layers.dense(
out,
self.units,
name="dense_two",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2",
)
return out
layer = WrappedDenseLayer(10)
out = layer(tf.ones(shape=(5, 5)))
weights = {x.name: x for x in layer.variables}
# Verify the correct output, losses, + variables were made
self.assertEqual(
weights.keys(),
{
"dense_one/bias:0",
"dense_one/kernel:0",
"nested_scope/dense_two/bias:0",
"nested_scope/dense_two/kernel:0",
},
)
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 50)
self.assertAllEqual(tf.add_n(layer.losses), 1.5)
# Verify reuse by updating the variables then re-running
weights["dense_one/kernel:0"].assign(tf.ones(shape=(5, 10)) * 2)
weights["nested_scope/dense_two/kernel:0"].assign(
tf.ones(shape=(10, 10)) * 2
)
out = layer(tf.ones(shape=(5, 5)))
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 200)
self.assertAllEqual(tf.add_n(layer.losses), 6)
def test_shim_exporting(self):
class WrappedDenseLayer(base_layer.Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs, training=None):
out = core_layers.dense(
inputs,
self.units,
name="dense_one",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2",
)
with tf.compat.v1.variable_scope("nested_scope"):
out = core_layers.dense(
out,
self.units,
name="dense_two",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2",
)
return out
layer = WrappedDenseLayer(10)
layer(tf.ones(shape=(5, 5)))
tmp_dir = self.get_temp_dir()
# Try exporting the layer directly
tf.saved_model.save(layer, tmp_dir)
# Try exporting the layer nested in a functional model
# This is where saving reflection gets tricky due to
# trying to replace the passed training arg in training=True
# and training=False modes
inp = input_layer_module.Input(shape=(5, 5))
outs = layer(inp)
model = models.Model(inp, outs)
tf.saved_model.save(model, tmp_dir)
def test_variable_store_scope_get_variable(self):
# Test the module shim when using `get_variable` (and regularizers)
# directly
class WrappedDenseLayer(tf.Module):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
self._variable_store = variable_scope_shim._EagerVariableStore()
def get_compat_v1_regularization_losses(self):
"""Dict w/ regularization losses from `get_variable`."""
return {
name: regularizer()
for name, regularizer in self._variable_store._regularizers.items() # noqa: E501
}
def __call__(self, inputs, training=None):
with self._variable_store.scope():
out = inputs
with tf.compat.v1.variable_scope("dense_one"):
# The weights are created with a `regularizer`,
# so the layer should track their regularization losses
kernel = tf.compat.v1.get_variable(
shape=[out.shape[-1], self.units],
regularizer=regularizers.L2(),
initializer=tf.compat.v1.ones_initializer(),
name="kernel",
)
bias = tf.compat.v1.get_variable(
shape=[
self.units,
],
initializer=tf.compat.v1.zeros_initializer(),
name="bias",
)
out = tf.matmul(out, kernel)
out = tf.nn.bias_add(out, bias)
with tf.compat.v1.variable_scope("nested_scope"):
with tf.compat.v1.variable_scope("dense_two"):
kernel = tf.compat.v1.get_variable(
shape=[out.shape[-1], self.units],
regularizer=regularizers.L2(),
initializer=tf.compat.v1.ones_initializer(),
name="kernel",
)
bias = tf.compat.v1.get_variable(
shape=[
self.units,
],
initializer=tf.compat.v1.zeros_initializer(),
name="bias",
)
out = tf.matmul(out, kernel)
out = tf.nn.bias_add(out, bias)
return out
layer = WrappedDenseLayer(10)
out = layer(tf.ones(shape=(5, 5)))
weights = {x.name: x for x in layer.variables}
# Verify the correct output, regularization losses, + variables were
# made
self.assertEqual(
weights.keys(),
{
"dense_one/bias:0",
"dense_one/kernel:0",
"nested_scope/dense_two/bias:0",
"nested_scope/dense_two/kernel:0",
},
)
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 50)
self.assertAllEqual(
tf.add_n(layer.get_compat_v1_regularization_losses().values()), 1.5
)
# Verify reuse by updating the variables then re-running
weights["dense_one/kernel:0"].assign(tf.ones(shape=(5, 10)) * 2)
weights["nested_scope/dense_two/kernel:0"].assign(
tf.ones(shape=(10, 10)) * 2
)
out = layer(tf.ones(shape=(5, 5)))
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 200)
self.assertAllEqual(
tf.add_n(layer.get_compat_v1_regularization_losses().values()), 6
)
def test_module_get_variable(self):
# Test the module shim when using `get_variable` (and regularizers)
# directly
class WrappedDenseLayer(VariableScopeModule):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
def forward_pass(self, inputs, training=None):
out = inputs
with tf.compat.v1.variable_scope("dense_one"):
# The weights are created with a `regularizer`,
# so the layer should track their regularization losses
kernel = tf.compat.v1.get_variable(
shape=[out.shape[-1], self.units],
regularizer=regularizers.L2(),
initializer=tf.compat.v1.ones_initializer(),
name="kernel",
)
bias = tf.compat.v1.get_variable(
shape=[
self.units,
],
initializer=tf.compat.v1.zeros_initializer(),
name="bias",
)
out = tf.matmul(out, kernel)
out = tf.nn.bias_add(out, bias)
with tf.compat.v1.variable_scope("nested_scope"):
with tf.compat.v1.variable_scope("dense_two"):
kernel = tf.compat.v1.get_variable(
shape=[out.shape[-1], self.units],
regularizer=regularizers.L2(),
initializer=tf.compat.v1.ones_initializer(),
name="kernel",
)
bias = tf.compat.v1.get_variable(
shape=[
self.units,
],
initializer=tf.compat.v1.zeros_initializer(),
name="bias",
)
out = tf.matmul(out, kernel)
out = tf.nn.bias_add(out, bias)
return out
layer = WrappedDenseLayer(10)
out = layer(tf.ones(shape=(5, 5)))
weights = {x.name: x for x in layer.variables}
# Verify the correct output, regularization losses, + variables were
# made
self.assertEqual(
weights.keys(),
{
"dense_one/bias:0",
"dense_one/kernel:0",
"nested_scope/dense_two/bias:0",
"nested_scope/dense_two/kernel:0",
},
)
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 50)
self.assertAllEqual(
tf.add_n(layer.get_compat_v1_regularization_losses().values()), 1.5
)
# Verify reuse by updating the variables then re-running
weights["dense_one/kernel:0"].assign(tf.ones(shape=(5, 10)) * 2)
weights["nested_scope/dense_two/kernel:0"].assign(
tf.ones(shape=(10, 10)) * 2
)
out = layer(tf.ones(shape=(5, 5)))
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 200)
self.assertAllEqual(
tf.add_n(layer.get_compat_v1_regularization_losses().values()), 6
)
def test_module_compat_v1_layer(self):
# Test the module shim when using `compat.v1` layers
class WrappedDenseLayer(VariableScopeModule):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
def forward_pass(self, inputs, training=None):
out = core_layers.dense(
inputs,
self.units,
name="dense_one",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2",
)
with tf.compat.v1.variable_scope("nested_scope"):
out = core_layers.dense(
out,
self.units,
name="dense_two",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2",
)
return out
layer = WrappedDenseLayer(10)
out = layer(tf.ones(shape=(5, 5)))
weights = {x.name: x for x in layer.variables}
# Verify the correct output, losses, + variables were made
self.assertEqual(
weights.keys(),
{
"dense_one/bias:0",
"dense_one/kernel:0",
"nested_scope/dense_two/bias:0",
"nested_scope/dense_two/kernel:0",
},
)
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 50)
self.assertAllEqual(
tf.add_n(layer.get_compat_v1_regularization_losses().values()), 1.5
)
# Verify reuse by updating the variables then re-running
weights["dense_one/kernel:0"].assign(tf.ones(shape=(5, 10)) * 2)
weights["nested_scope/dense_two/kernel:0"].assign(
tf.ones(shape=(10, 10)) * 2
)
out = layer(tf.ones(shape=(5, 5)))
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 200)
self.assertAllEqual(
tf.add_n(layer.get_compat_v1_regularization_losses().values()), 6
)
def test_shim_nesting(self):
# Test that nesting the shim in itself works
class NestedLayer(base_layer.Layer):
def __init__(self, units, name, *args, **kwargs):
super().__init__(*args, name=name, **kwargs)
self.units = units
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs):
out = inputs
with tf.compat.v1.variable_scope(self.name):
# The weights are created with a `regularizer`,
# so the layer should track their regularization losses
kernel = tf.compat.v1.get_variable(
shape=[out.shape[-1], self.units],
regularizer=regularizers.L2(1.0),
initializer=tf.compat.v1.ones_initializer(),
name="kernel",
)
bias = tf.compat.v1.get_variable(
shape=[
self.units,
],
initializer=tf.compat.v1.initializers.zeros,
name="bias",
)
out = tf.linalg.matmul(out, kernel)
out = tf.compat.v1.nn.bias_add(out, bias)
return out
class WrappedDenseLayer(base_layer.Layer):
def __init__(self, units, **kwargs):
super().__init__(**kwargs)
self.units = units
self.dense_layer_a = None
self.dense_layer_b = None
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs):
# Only create the nested tf.variable/module/layer/model if it
# has not already been created!
if not self.dense_layer_a:
self.dense_layer_a = NestedLayer(
self.units * 2, "dense_one"
)
out = self.dense_layer_a(inputs)
if not self.dense_layer_b:
self.dense_layer_b = NestedLayer(self.units, "dense_two")
out = self.dense_layer_b(out)
return out
layer = WrappedDenseLayer(5)
out = layer(tf.ones(shape=(1, 3)))
weights = {x.name: x for x in layer.variables}
# Verify the correct output, losses, + variables were made
# (Specifically: no double-counting of any weights or reg. losses
# between nested components!)
self.assertEqual(
{var.name for var in layer.trainable_weights},
{
"dense_one/bias:0",
"dense_one/kernel:0",
"dense_two/bias:0",
"dense_two/kernel:0",
},
)
self.assertEqual(
{var.name for var in layer.dense_layer_a.weights},
{"dense_one/bias:0", "dense_one/kernel:0"},
)
self.assertEqual(
{var.name for var in layer.dense_layer_b.weights},
{"dense_two/bias:0", "dense_two/kernel:0"},
)
self.assertAllEqual(out, tf.ones(shape=(1, 5)) * 30)
self.assertAllEqual(tf.add_n(layer.dense_layer_a.losses), 30)
self.assertAllEqual(tf.add_n(layer.dense_layer_b.losses), 50)
self.assertAllEqual(tf.add_n(layer.losses), 80)
# Verify reuse by updating the variables then re-running
weights["dense_one/kernel:0"].assign(tf.ones(shape=(3, 10)) * 2)
weights["dense_two/kernel:0"].assign(tf.ones(shape=(10, 5)) * 2)
out = layer(tf.ones(shape=(1, 3)))
self.assertAllEqual(out, tf.ones(shape=(1, 5)) * 120)
self.assertAllEqual(tf.add_n(layer.losses), 320)
def test_compat_v1_make_template_in_shim_eager(self):
# Test the shim when using `compat.v1.make_template`
# Verify it works correctly in eager
layer = CompatV1TemplateScaleByY()
for _ in range(3):
# Use multiple calls to verify that no new weights get created
self.assertAllEqual(
layer(tf.ones(shape=(2, 3))), tf.constant(1.5, shape=(2, 3))
)
self.assertAllEqual(
{var.name: var.numpy() for var in layer.weights},
{"foo/scale_by_y/y:0": 1.5},
)
self.assertAllEqual(
tf.add_n(layer.losses), regularizers.L2()(layer.weights[0])
)
def test_compat_v1_make_template_in_shim_tf_function(self):
# Test the shim when using `compat.v1.make_template`
# Verify it works correctly in a tf.function
# when made outside the function
layer = CompatV1TemplateScaleByY()
@tf.function
def foo(x):
return layer(x), tf.add_n(layer.losses)
for _ in range(3):
# Use multiple calls to verify that no new weights get created
out, loss = foo(tf.ones(shape=(2, 3)))
self.assertAllEqual(out, tf.constant(1.5, shape=(2, 3)))
self.assertAllEqual(loss, regularizers.L2()(layer.weights[0]))
self.assertAllEqual(
{var.name: var.numpy() for var in layer.weights},
{"foo/scale_by_y/y:0": 1.5},
)
def test_compat_v1_make_template_in_trace_in_shim(self):
# Test the shim when using `compat.v1.make_template`
# Verify it works correctly when the make_template/layer/shim
# is created on the first tf.function trace!
layers = {}
@tf.function
def bar(x):
if "layer" not in layers:
layers["layer"] = CompatV1TemplateScaleByY()
layer = layers["layer"]
return layer(x), tf.add_n(layer.losses)
for _ in range(3):
# Use multiple calls to verify that no new weights get created
out, loss = bar(tf.ones(shape=(2, 3)))
self.assertAllEqual(out, tf.constant(1.5, shape=(2, 3)))
self.assertAllEqual(
loss, regularizers.L2()(layers["layer"].weights[0])
)
self.assertAllEqual(
{var.name: var.numpy() for var in layers["layer"].weights},
{"foo/scale_by_y/y:0": 1.5},
)
def test_only_track_get_variable(self):
# Test the shim does not try tracking or reusing variables
# that were not created by get_variable. These variables/modules/layers
# need to be tracked separately
class WrappedDenseLayer(base_layer.Layer):
def __init__(self, units, **kwargs):
super().__init__(**kwargs)
self.units = units
self._dense_model = None
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs):
dense_layer = core.Dense(
self.units,
name="dense",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2",
)
return dense_layer(inputs)
layer = WrappedDenseLayer(10)
out = layer(tf.ones(shape=(5, 5)))
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 5)
self.assertEmpty(layer.weights)
def test_embedded_keras_model(self):
# Test the shim when embedding a TF-Keras model inside of it
# And assigning the model to an attribute
class WrappedDenseLayer(base_layer.Layer):
def __init__(self, units, **kwargs):
super().__init__(**kwargs)
self.units = units
self._dense_model = None
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs):
if not self._dense_model:
inp = input_layer_module.Input(shape=inputs.shape)
dense_layer = core.Dense(
self.units,
name="dense",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2",
)
self._dense_model = training_module.Model(
inputs=inp, outputs=dense_layer(inp)
)
return self._dense_model(inputs)
layer = WrappedDenseLayer(10)
out = layer(tf.ones(shape=(5, 5)))
weights = {x.name: x for x in layer.variables}
# Verify the correct output, losses, + variables were made
self.assertEqual(weights.keys(), {"dense/bias:0", "dense/kernel:0"})
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 5)
self.assertAllEqual(tf.add_n(layer.losses), 0.5)
# Verify reuse by updating the variables then re-running
weights["dense/kernel:0"].assign(tf.ones(shape=(5, 10)) * 2)
out = layer(tf.ones(shape=(5, 5)))
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 10)
self.assertAllEqual(tf.add_n(layer.losses), 2)
def test_embedded_keras_model_in_module(self):
# Test the module shim when embedding a TF-Keras model inside of it
# And assigning the model to an attribute
class WrappedDenseLayer(VariableScopeModule):
def __init__(self, units, **kwargs):
super().__init__(**kwargs)
self.units = units
self._dense_model = None
def forward_pass(self, inputs):
if not self._dense_model:
inp = input_layer_module.Input(shape=inputs.shape)
dense_layer = core.Dense(
self.units,
name="dense",
kernel_initializer=tf.compat.v1.ones_initializer(),
kernel_regularizer="l2",
)
self._dense_model = training_module.Model(
inputs=inp, outputs=dense_layer(inp)
)
return self._dense_model(inputs)
layer = WrappedDenseLayer(10)
out = layer(tf.ones(shape=(5, 5)))
weights = {x.name: x for x in layer.variables}
# Verify the correct output, losses, + variables were made
self.assertEqual(weights.keys(), {"dense/bias:0", "dense/kernel:0"})
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 5)
# The module shim will only track regularization losses made by
# compat.v1.layers and compat.v1.get_variable. Other regularization
# losses must be tracked by separate user-created mechanisms.
self.assertEmpty(layer.get_compat_v1_regularization_losses())
# Verify reuse by updating the variables then re-running
weights["dense/kernel:0"].assign(tf.ones(shape=(5, 10)) * 2)
out = layer(tf.ones(shape=(5, 5)))
self.assertAllEqual(out, tf.ones(shape=(5, 10)) * 10)
# The module shim will only track regularization losses made by
# compat.v1.layers and compat.v1.get_variable. Other regularization
# losses must be tracked by separate user-created mechanisms.
self.assertEmpty(layer.get_compat_v1_regularization_losses())
def test_training_arg(self):
# Test the shim when passing in a TF-Keras `training` arg
class TrainingCheckLayer(base_layer.Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs, training=None):
if training:
out = core_layers.dense(
inputs, self.units, name="dense_training"
)
else:
out = core_layers.dense(
inputs, self.units, name="dense_no_training"
)
return out
layer = TrainingCheckLayer(10)
layer(tf.ones(shape=(5, 5)), training=True)
weights = {x.name: x for x in layer.variables}
# Verify the correct variables were made
self.assertEqual(
weights.keys(), {"dense_training/bias:0", "dense_training/kernel:0"}
)
layer = TrainingCheckLayer(10)
layer(tf.ones(shape=(5, 5)))
weights = {x.name: x for x in layer.variables}
# Verify the correct variables were made
self.assertEqual(
weights.keys(),
{"dense_no_training/bias:0", "dense_no_training/kernel:0"},
)
def test_incorrect_decoration(self):
# Raise an error if you incorrectly decorate a method
# that is not a method of a Module, layer, or model:
@variable_scope_shim.track_tf1_style_variables
def foo(x):
return x * 2
with self.assertRaisesRegex(ValueError, "does not extend"):
foo(tf.ones(shape=(4, 4)))
class GetOrCreateLayerTest(tf.test.TestCase, parameterized.TestCase):
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
def test_get_or_create_layer_with_regularizer_eager(self):
class NestedLayer(base_layer.Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
def build_model(self):
inp = input_layer_module.Input(shape=(5, 5))
dense_layer = core.Dense(
10,
name="dense",
kernel_regularizer="l2",
kernel_initializer=tf.compat.v1.ones_initializer(),
)
model = training_module.Model(
inputs=inp, outputs=dense_layer(inp)
)
return model
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs):
# enter a variable scope to check module key naming
with tf.compat.v1.variable_scope("test_scope"):
model = variable_scope_shim.get_or_create_layer(
"dense_model", self.build_model
)
return model(inputs)
layer = NestedLayer(10)
x = tf.ones(shape=(5, 5))
out1 = layer(tf.expand_dims(x, 0))
model1 = layer.submodules[0]._layers["test_scope/dense_model"]
out2 = layer(tf.expand_dims(x, 0))
# Verify model produces same output on successive calls with same input
self.assertAllEqual(out1, out2)
# Verify the model used on subsequent calls is the same
model2 = layer.submodules[0]._layers["test_scope/dense_model"]
self.assertIs(model1, model2)
# Verify that stored layer computes outputs and losses correctly
weights = {x.name: x for x in layer.variables}
self.assertEqual(weights.keys(), {"dense/bias:0", "dense/kernel:0"})
self.assertAllEqual(out2, tf.ones(shape=(1, 5, 10)) * 5)
self.assertAllEqual(layer.losses, [0.5])
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
def test_get_or_create_layer_no_regularizer_eager(self):
class NestedLayer(base_layer.Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
def build_model(self):
inp = input_layer_module.Input(shape=(5, 5))
dense_layer = core.Dense(
10,
name="dense",
kernel_initializer=tf.compat.v1.ones_initializer(),
)
model = training_module.Model(
inputs=inp, outputs=dense_layer(inp)
)
return model
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs):
# enter a variable scope to check module key naming
with tf.compat.v1.variable_scope("test_scope"):
model = variable_scope_shim.get_or_create_layer(
"dense_model", self.build_model
)
return model(inputs)
layer = NestedLayer(10)
x = tf.ones(shape=(5, 5))
out1 = layer(tf.expand_dims(x, 0))
model1 = layer.submodules[0]._layers["test_scope/dense_model"]
out2 = layer(tf.expand_dims(x, 0))
# Verify model produces same output on successive calls with same input
self.assertAllEqual(out1, out2)
# Verify the model used on subsequent calls is the same
model2 = layer.submodules[0]._layers["test_scope/dense_model"]
self.assertIs(model1, model2)
# Verify that stored layer computes outputs and losses correctly
weights = {x.name: x for x in layer.variables}
self.assertEqual(weights.keys(), {"dense/bias:0", "dense/kernel:0"})
self.assertAllEqual(out2, tf.ones(shape=(1, 5, 10)) * 5)
self.assertAllEqual(layer.losses, [0.0])
@test_combinations.generate(test_combinations.combine(mode=["eager"]))
def test_get_or_create_layer_tf_function(self):
class NestedLayer(base_layer.Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
def build_model(self):
inp = input_layer_module.Input(shape=(5, 5))
dense_layer = core.Dense(
10,
name="dense",
kernel_regularizer="l2",
)
model = training_module.Model(
inputs=inp, outputs=dense_layer(inp)
)
return model
@variable_scope_shim.track_tf1_style_variables
def call(self, inputs):
model = variable_scope_shim.get_or_create_layer(
"dense_model", self.build_model
)
return model(inputs)
layer = NestedLayer(10)
@tf.function
def foo(x):
return layer(x), tf.add_n(layer.losses)
# Verify inner model is reused
out1, loss1 = foo(tf.ones(shape=(5, 5)))
out2, loss2 = foo(tf.ones(shape=(5, 5)))
self.assertAllEqual(out1, out2)
self.assertAllEqual(loss1, loss2)
@tf_test_utils.run_deprecated_v1
def test_get_or_create_layer_graph(self):
class NestedLayer(object):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
def build_model(self):
inp = input_layer_module.Input(shape=(5, 5))
dense_layer = core.Dense(
10,
name="dense",
kernel_regularizer="l2",
kernel_initializer=tf.compat.v1.ones_initializer(),
)
model = training_module.Model(
inputs=inp, outputs=dense_layer(inp)
)
return model
def __call__(self, inputs):
model = variable_scope_shim.get_or_create_layer(
"dense_model", self.build_model
)
return model(inputs)
with self.cached_session():
layer = NestedLayer(10)
x = tf.ones(shape=(5, 5))
out1 = layer(tf.expand_dims(x, 0))
self.evaluate(tf.compat.v1.global_variables_initializer())
# verify output
self.assertEqual(out1.shape, tf.TensorShape([1, 5, 10]))
self.assertAllEqual(out1, tf.ones(shape=(1, 5, 10)) * 5)
# verify variables are tracked
weights = {var.name for var in tf.compat.v1.trainable_variables()}
self.assertEqual(weights, {"dense/bias:0", "dense/kernel:0"})
if __name__ == "__main__":
tf.test.main()
| tf-keras/tf_keras/legacy_tf_layers/variable_scope_shim_test.py/0 | {
"file_path": "tf-keras/tf_keras/legacy_tf_layers/variable_scope_shim_test.py",
"repo_id": "tf-keras",
"token_count": 40969
} | 192 |
# Copyright 2016 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 TF-Keras metrics."""
import tensorflow.compat.v2 as tf
from tf_keras import metrics
from tf_keras.testing_infra import test_combinations
@test_combinations.generate(test_combinations.combine(mode=["graph", "eager"]))
class IoUTest(tf.test.TestCase):
def test_config(self):
obj = metrics.IoU(
num_classes=2, target_class_ids=[1, 0], name="iou_class_1_0"
)
self.assertEqual(obj.name, "iou_class_1_0")
self.assertEqual(obj.num_classes, 2)
self.assertEqual(obj.target_class_ids, [1, 0])
obj2 = metrics.IoU.from_config(obj.get_config())
self.assertEqual(obj2.name, "iou_class_1_0")
self.assertEqual(obj2.num_classes, 2)
self.assertEqual(obj2.target_class_ids, [1, 0])
def test_unweighted(self):
y_pred = [0, 1, 0, 1]
y_true = [0, 0, 1, 1]
obj = metrics.IoU(num_classes=2, target_class_ids=[0, 1])
self.evaluate(tf.compat.v1.variables_initializer(obj.variables))
result = obj(y_true, y_pred)
# cm = [[1, 1],
# [1, 1]]
# sum_row = [2, 2], sum_col = [2, 2], true_positives = [1, 1]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (1 / (2 + 2 - 1) + 1 / (2 + 2 - 1)) / 2
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
def test_weighted(self):
y_pred = tf.constant([0, 1, 0, 1], dtype=tf.float32)
y_true = tf.constant([0, 0, 1, 1])
sample_weight = tf.constant([0.2, 0.3, 0.4, 0.1])
obj = metrics.IoU(num_classes=2, target_class_ids=[1, 0])
self.evaluate(tf.compat.v1.variables_initializer(obj.variables))
result = obj(y_true, y_pred, sample_weight=sample_weight)
# cm = [[0.2, 0.3],
# [0.4, 0.1]]
# sum_row = [0.6, 0.4], sum_col = [0.5, 0.5], true_positives = [0.2,
# 0.1]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (
0.1 / (0.4 + 0.5 - 0.1) + 0.2 / (0.6 + 0.5 - 0.2)
) / 2
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
def test_multi_dim_input(self):
y_pred = tf.constant([[0, 1], [0, 1]], dtype=tf.float32)
y_true = tf.constant([[0, 0], [1, 1]])
sample_weight = tf.constant([[0.2, 0.3], [0.4, 0.1]])
obj = metrics.IoU(num_classes=2, target_class_ids=[0, 1])
self.evaluate(tf.compat.v1.variables_initializer(obj.variables))
result = obj(y_true, y_pred, sample_weight=sample_weight)
# cm = [[0.2, 0.3],
# [0.4, 0.1]]
# sum_row = [0.6, 0.4], sum_col = [0.5, 0.5], true_positives = [0.2,
# 0.1]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (
0.2 / (0.6 + 0.5 - 0.2) + 0.1 / (0.4 + 0.5 - 0.1)
) / 2
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
def test_zero_valid_entries(self):
obj = metrics.IoU(num_classes=2, target_class_ids=[0, 1])
self.evaluate(tf.compat.v1.variables_initializer(obj.variables))
self.assertAllClose(self.evaluate(obj.result()), 0, atol=1e-3)
def test_zero_and_non_zero_entries(self):
y_pred = tf.constant([1], dtype=tf.float32)
y_true = tf.constant([1])
obj = metrics.IoU(num_classes=2, target_class_ids=[0, 1])
self.evaluate(tf.compat.v1.variables_initializer(obj.variables))
result = obj(y_true, y_pred)
# cm = [[0, 0],
# [0, 1]]
# sum_row = [0, 1], sum_col = [0, 1], true_positives = [0, 1]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (1 / (1 + 1 - 1)) / 1
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
@test_combinations.generate(test_combinations.combine(mode=["graph", "eager"]))
class BinaryIoUTest(tf.test.TestCase):
def test_config(self):
obj = metrics.BinaryIoU(
target_class_ids=[1, 0], threshold=0.1, name="iou_class_1_0"
)
self.assertEqual(obj.name, "iou_class_1_0")
self.assertAlmostEqual(obj.threshold, 0.1)
self.assertEqual(obj.target_class_ids, [1, 0])
obj2 = metrics.BinaryIoU.from_config(obj.get_config())
self.assertEqual(obj.name, "iou_class_1_0")
self.assertAlmostEqual(obj2.threshold, 0.1)
self.assertEqual(obj.target_class_ids, [1, 0])
def test_different_thresholds_weighted(self):
y_true = [0, 1, 0, 1]
y_pred = [0.1, 0.2, 0.4, 0.7]
sample_weight = tf.constant([0.2, 0.3, 0.4, 0.1])
# with threshold = 0.3, y_pred will be converted to [0, 0, 1, 1]
# cm = [[0.2, 0.4],
# [0.3, 0.1]]
# sum_row = [0.6, 0.4], sum_col = [0.5, 0.5], true_positives = [0.2,
# 0.1]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (
0.2 / (0.6 + 0.5 - 0.2) + 0.1 / (0.4 + 0.5 - 0.1)
) / 2
obj = metrics.BinaryIoU(target_class_ids=[0, 1], threshold=0.3)
self.evaluate(tf.compat.v1.variables_initializer(obj.variables))
result = obj(y_true, y_pred, sample_weight=sample_weight)
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
sample_weight = tf.constant([0.1, 0.2, 0.4, 0.3])
# with threshold = 0.5, y_pred will be converted to [0, 0, 0, 1]
# cm = [[0.1+0.4, 0],
# [0.2, 0.3]]
# sum_row = [0.5, 0.5], sum_col = [0.7, 0.3], true_positives = [0.5,
# 0.3]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (
0.5 / (0.5 + 0.7 - 0.5) + 0.3 / (0.5 + 0.3 - 0.3)
) / 2
obj = metrics.BinaryIoU(target_class_ids=[0, 1], threshold=0.5)
self.evaluate(tf.compat.v1.variables_initializer(obj.variables))
result = obj(y_true, y_pred, sample_weight=sample_weight)
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
def test_different_thresholds_unweighted(self):
y_true = [0, 1, 0, 1]
y_pred = [0.1, 0.2, 0.4, 0.7]
# with threshold = 0.3, y_pred will be converted to [0, 0, 1, 1]
# cm = [[1, 1],
# [1, 1]]
# sum_row = [2, 2], sum_col = [2, 2], true_positives = [1, 1]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (1 / (2 + 2 - 1) + 1 / (2 + 2 - 1)) / 2
obj = metrics.BinaryIoU(target_class_ids=[0, 1], threshold=0.3)
self.evaluate(tf.compat.v1.variables_initializer(obj.variables))
result = obj(y_true, y_pred)
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
# with threshold = 0.5, y_pred will be converted to [0, 0, 0, 1]
# cm = [[2, 0],
# [1, 1]]
# sum_row = [2, 2], sum_col = [3, 1], true_positives = [2, 1]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (2 / (2 + 3 - 2) + 1 / (2 + 1 - 1)) / 2
obj = metrics.BinaryIoU(target_class_ids=[0, 1], threshold=0.5)
self.evaluate(tf.compat.v1.variables_initializer(obj.variables))
result = obj(y_true, y_pred)
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
def test_multi_dim_input(self):
y_true = tf.constant([[0, 1], [0, 1]], dtype=tf.float32)
y_pred = tf.constant([[0.1, 0.7], [0.9, 0.3]])
threshold = 0.4 # y_pred will become [[0, 1], [1, 0]]
sample_weight = tf.constant([[0.2, 0.3], [0.4, 0.1]])
# cm = [[0.2, 0.4],
# [0.1, 0.3]]
# sum_row = [0.6, 0.4], sum_col = [0.3, 0.7], true_positives = [0.2,
# 0.3]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (
0.2 / (0.6 + 0.3 - 0.2) + 0.3 / (0.4 + 0.7 - 0.3)
) / 2
obj = metrics.BinaryIoU(target_class_ids=[0, 1], threshold=threshold)
self.evaluate(tf.compat.v1.variables_initializer(obj.variables))
result = obj(y_true, y_pred, sample_weight=sample_weight)
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
def test_zero_valid_entries(self):
obj = metrics.BinaryIoU(target_class_ids=[0, 1])
self.evaluate(tf.compat.v1.variables_initializer(obj.variables))
self.assertAllClose(self.evaluate(obj.result()), 0, atol=1e-3)
def test_zero_and_non_zero_entries(self):
y_pred = tf.constant([0.6], dtype=tf.float32)
threshold = 0.5
y_true = tf.constant([1])
obj = metrics.BinaryIoU(target_class_ids=[0, 1], threshold=threshold)
self.evaluate(tf.compat.v1.variables_initializer(obj.variables))
result = obj(y_true, y_pred)
# cm = [[0, 0],
# [0, 1]]
# sum_row = [0, 1], sum_col = [0, 1], true_positives = [0, 1]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = 1 / (1 + 1 - 1)
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
@test_combinations.generate(test_combinations.combine(mode=["graph", "eager"]))
class MeanIoUTest(tf.test.TestCase):
def test_config(self):
m_obj = metrics.MeanIoU(num_classes=2, name="mean_iou")
self.assertEqual(m_obj.name, "mean_iou")
self.assertEqual(m_obj.num_classes, 2)
m_obj2 = metrics.MeanIoU.from_config(m_obj.get_config())
self.assertEqual(m_obj2.name, "mean_iou")
self.assertEqual(m_obj2.num_classes, 2)
def test_unweighted(self):
y_pred = [0, 1, 0, 1]
y_true = [0, 0, 1, 1]
m_obj = metrics.MeanIoU(num_classes=2)
self.evaluate(tf.compat.v1.variables_initializer(m_obj.variables))
result = m_obj(y_true, y_pred)
# cm = [[1, 1],
# [1, 1]]
# sum_row = [2, 2], sum_col = [2, 2], true_positives = [1, 1]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (1 / (2 + 2 - 1) + 1 / (2 + 2 - 1)) / 2
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
def test_unweighted_ignore_class_255(self):
y_pred = [0, 1, 1, 1]
y_true = [0, 1, 2, 255]
m_obj = metrics.MeanIoU(num_classes=3, ignore_class=255)
self.evaluate(tf.compat.v1.variables_initializer(m_obj.variables))
result = m_obj(y_true, y_pred)
# cm = [[1, 0, 0],
# [0, 1, 0],
# [0, 1, 0]]
# sum_row = [1, 1, 1], sum_col = [1, 2, 0], true_positives = [1, 1, 0]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (
1 / (1 + 1 - 1) + 1 / (2 + 1 - 1) + 0 / (0 + 1 - 0)
) / 3
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
def test_unweighted_ignore_class_1(self):
y_pred = [0, 1, 1, 1]
y_true = [0, 1, 2, -1]
m_obj = metrics.MeanIoU(num_classes=3, ignore_class=-1)
self.evaluate(tf.compat.v1.variables_initializer(m_obj.variables))
result = m_obj(y_true, y_pred)
# cm = [[1, 0, 0],
# [0, 1, 0],
# [0, 1, 0]]
# sum_row = [1, 1, 1], sum_col = [1, 2, 0], true_positives = [1, 1, 0]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (
1 / (1 + 1 - 1) + 1 / (2 + 1 - 1) + 0 / (0 + 1 - 0)
) / 3
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
def test_weighted(self):
y_pred = tf.constant([0, 1, 0, 1], dtype=tf.float32)
y_true = tf.constant([0, 0, 1, 1])
sample_weight = tf.constant([0.2, 0.3, 0.4, 0.1])
m_obj = metrics.MeanIoU(num_classes=2)
self.evaluate(tf.compat.v1.variables_initializer(m_obj.variables))
result = m_obj(y_true, y_pred, sample_weight=sample_weight)
# cm = [[0.2, 0.3],
# [0.4, 0.1]]
# sum_row = [0.6, 0.4], sum_col = [0.5, 0.5], true_positives = [0.2,
# 0.1]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (
0.2 / (0.6 + 0.5 - 0.2) + 0.1 / (0.4 + 0.5 - 0.1)
) / 2
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
def test_weighted_ignore_class_1(self):
y_pred = tf.constant([0, 1, 0, 1], dtype=tf.float32)
y_true = tf.constant([0, 0, 1, -1])
sample_weight = tf.constant([0.2, 0.3, 0.4, 0.1])
m_obj = metrics.MeanIoU(num_classes=2, ignore_class=-1)
self.evaluate(tf.compat.v1.variables_initializer(m_obj.variables))
result = m_obj(y_true, y_pred, sample_weight=sample_weight)
# cm = [[0.2, 0.3],
# [0.4, 0.0]]
# sum_row = [0.6, 0.3], sum_col = [0.5, 0.4], true_positives = [0.2,
# 0.0]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (
0.2 / (0.6 + 0.5 - 0.2) + 0.0 / (0.3 + 0.4 - 0.0)
) / 2
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
def test_multi_dim_input(self):
y_pred = tf.constant([[0, 1], [0, 1]], dtype=tf.float32)
y_true = tf.constant([[0, 0], [1, 1]])
sample_weight = tf.constant([[0.2, 0.3], [0.4, 0.1]])
m_obj = metrics.MeanIoU(num_classes=2)
self.evaluate(tf.compat.v1.variables_initializer(m_obj.variables))
result = m_obj(y_true, y_pred, sample_weight=sample_weight)
# cm = [[0.2, 0.3],
# [0.4, 0.1]]
# sum_row = [0.6, 0.4], sum_col = [0.5, 0.5], true_positives = [0.2,
# 0.1]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (
0.2 / (0.6 + 0.5 - 0.2) + 0.1 / (0.4 + 0.5 - 0.1)
) / 2
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
def test_zero_valid_entries(self):
m_obj = metrics.MeanIoU(num_classes=2)
self.evaluate(tf.compat.v1.variables_initializer(m_obj.variables))
self.assertAllClose(self.evaluate(m_obj.result()), 0, atol=1e-3)
def test_zero_and_non_zero_entries(self):
y_pred = tf.constant([1], dtype=tf.float32)
y_true = tf.constant([1])
m_obj = metrics.MeanIoU(num_classes=2)
self.evaluate(tf.compat.v1.variables_initializer(m_obj.variables))
result = m_obj(y_true, y_pred)
# cm = [[0, 0],
# [0, 1]]
# sum_row = [0, 1], sum_col = [0, 1], true_positives = [0, 1]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (0 + 1 / (1 + 1 - 1)) / 1
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
@test_combinations.generate(test_combinations.combine(mode=["graph", "eager"]))
class OneHotIoUTest(tf.test.TestCase):
def test_unweighted(self):
y_true = tf.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0], [1, 0, 0]])
# y_true will be converted to [2, 0, 1, 0]
y_pred = tf.constant(
[[0.2, 0.3, 0.5], [0.1, 0.2, 0.7], [0.5, 0.3, 0.1], [0.1, 0.4, 0.5]]
)
# y_pred will be converted to [2, 2, 0, 2]
# cm = [[0, 0, 2],
# [1, 0, 0],
# [0, 0, 1]
# sum_row = [1, 0, 3], sum_col = [2, 1, 1], true_positives = [0, 0, 1]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (0 / (1 + 2 - 0) + 1 / (3 + 1 - 1)) / 2
obj = metrics.OneHotIoU(num_classes=3, target_class_ids=[0, 2])
self.evaluate(tf.compat.v1.variables_initializer(obj.variables))
result = obj(y_true, y_pred)
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
def test_weighted(self):
y_true = tf.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0], [1, 0, 0]])
# y_true will be converted to [2, 0, 1, 0]
y_pred = tf.constant(
[[0.2, 0.3, 0.5], [0.1, 0.2, 0.7], [0.5, 0.3, 0.1], [0.1, 0.4, 0.5]]
)
# y_pred will be converted to [2, 2, 0, 2]
sample_weight = [0.1, 0.2, 0.3, 0.4]
# cm = [[0, 0, 0.2+0.4],
# [0.3, 0, 0],
# [0, 0, 0.1]]
# sum_row = [0.3, 0, 0.7], sum_col = [0.6, 0.3, 0.1]
# true_positives = [0, 0, 0.1]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (0 / (0.3 + 0.6 - 0) + 0.1 / (0.7 + 0.1 - 0.1)) / 2
obj = metrics.OneHotIoU(num_classes=3, target_class_ids=[0, 2])
self.evaluate(tf.compat.v1.variables_initializer(obj.variables))
result = obj(y_true, y_pred, sample_weight=sample_weight)
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
@test_combinations.generate(test_combinations.combine(mode=["graph", "eager"]))
class OneHotMeanIoUTest(tf.test.TestCase):
def test_unweighted(self):
y_true = tf.constant([[0, 0, 1], [1, 0, 0], [0, 1, 0], [1, 0, 0]])
# y_true will be converted to [2, 0, 1, 0]
y_pred = tf.constant(
[[0.2, 0.3, 0.5], [0.1, 0.2, 0.7], [0.5, 0.3, 0.1], [0.1, 0.4, 0.5]]
)
# y_pred will be converted to [2, 2, 0, 2]
# cm = [[0, 0, 2],
# [1, 0, 0],
# [0, 0, 1]
# sum_row = [1, 0, 3], sum_col = [2, 1, 1], true_positives = [0, 0, 1]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (0 + 0 + 1 / (3 + 1 - 1)) / 3
obj = metrics.OneHotMeanIoU(num_classes=3)
self.evaluate(tf.compat.v1.variables_initializer(obj.variables))
result = obj(y_true, y_pred)
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
def test_weighted(self):
y_true = tf.constant(
[
[0, 0, 1],
[1, 0, 0],
[0, 1, 0],
[1, 0, 0],
[1, 0, 0],
]
)
# y_true will be converted to [2, 0, 1, 0, 0]
y_pred = tf.constant(
[
[0.2, 0.3, 0.5],
[0.1, 0.2, 0.7],
[0.5, 0.3, 0.1],
[0.1, 0.4, 0.5],
[0.6, 0.2, 0.2],
]
)
# y_pred will be converted to [2, 2, 0, 2, 0]
sample_weight = [0.1, 0.2, 0.3, 0.3, 0.1]
# cm = [[0.1, 0, 0.2+0.3],
# [0.3, 0, 0],
# [0, 0, 0.1]]
# sum_row = [0.4, 0, 0.6], sum_col = [0.6, 0.3, 0.1]
# true_positives = [0.1, 0, 0.1]
# iou = true_positives / (sum_row + sum_col - true_positives))
expected_result = (
0.1 / (0.4 + 0.6 - 0.1) + 0 + 0.1 / (0.6 + 0.1 - 0.1)
) / 3
obj = metrics.OneHotMeanIoU(num_classes=3)
self.evaluate(tf.compat.v1.variables_initializer(obj.variables))
result = obj(y_true, y_pred, sample_weight=sample_weight)
self.assertAllClose(self.evaluate(result), expected_result, atol=1e-3)
if __name__ == "__main__":
tf.test.main()
| tf-keras/tf_keras/metrics/iou_metrics_test.py/0 | {
"file_path": "tf-keras/tf_keras/metrics/iou_metrics_test.py",
"repo_id": "tf-keras",
"token_count": 10317
} | 193 |
# Copyright 2019 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 keras.layers.Layer works properly with mixed precision."""
import os
import numpy as np
import tensorflow.compat.v2 as tf
from absl.testing import parameterized
from tf_keras import layers
from tf_keras import models
from tf_keras.engine import base_layer
from tf_keras.engine import base_layer_utils
from tf_keras.engine import input_spec
from tf_keras.mixed_precision import policy
from tf_keras.mixed_precision import test_util as mp_test_util
from tf_keras.optimizers.legacy import gradient_descent
from tf_keras.testing_infra import test_combinations
class MultiplyLayerWithFunction(mp_test_util.MultiplyLayer):
"""Same as MultiplyLayer, but _multiply is decorated with a tf.function."""
@tf.function
def _multiply(self, x, y):
return super()._multiply(x, y)
# If called outside any strategy.scope() calls, this will return the default
# strategy.
default_strategy_fn = tf.distribute.get_strategy
def create_mirrored_strategy():
"""Create a MirroredStrategy, using a GPU if it is available."""
if tf.config.list_logical_devices("GPU"):
return tf.distribute.MirroredStrategy(["cpu:0", "gpu:0"])
else:
return tf.distribute.MirroredStrategy(["cpu:0"])
def create_central_storage_strategy():
"""Create a CentralStorageStrategy, using a GPU if it is available."""
compute_devices = (
["cpu:0", "gpu:0"]
if (tf.config.list_logical_devices("GPU"))
else ["cpu:0"]
)
return tf.distribute.experimental.CentralStorageStrategy(
compute_devices, parameter_device="cpu:0"
)
TESTCASES = (
{"testcase_name": "base", "strategy_fn": default_strategy_fn},
{"testcase_name": "distribute", "strategy_fn": create_mirrored_strategy},
)
@test_combinations.generate(test_combinations.combine(mode=["graph", "eager"]))
class LayerTest(test_combinations.TestCase):
"""Test mixed precision with TF-Keras layers."""
@parameterized.named_parameters(*TESTCASES)
def test_mixed_policies_(self, strategy_fn):
strategy = strategy_fn()
for dtype in "float16", "bfloat16":
x = tf.constant([1.0])
policy_name = "mixed_" + dtype
with strategy.scope(), policy.policy_scope(policy_name):
layer = mp_test_util.MultiplyLayer(assert_type=dtype)
self.assertEqual(layer.dtype, tf.float32)
self.assertEqual(layer.dtype_policy.name, policy_name)
y = layer(x)
self.assertEqual(layer.v.dtype, tf.float32)
self.assertEqual(y.dtype, dtype)
self.assertEqual(layer.dtype_policy.name, policy_name)
self.assertIsInstance(layer.dtype_policy, policy.Policy)
self.assertEqual(layer.compute_dtype, dtype)
self.assertEqual(layer.dtype, tf.float32)
self.assertEqual(layer.variable_dtype, tf.float32)
self.assertEqual(layer.dtype_policy.name, policy_name)
self.evaluate(tf.compat.v1.global_variables_initializer())
self.assertEqual(self.evaluate(y), 1.0)
def test_layer_with_int_variable(self):
class LayerWithIntVar(base_layer.Layer):
def build(self, _):
self.v = self.add_weight("v", dtype="int32", trainable=False)
def call(self, inputs):
# Only float variables should be autocasted. This will fail if
# self.v is autocasted to float32
return tf.cast(inputs, "int32") + self.v
x = tf.constant([1.0])
layer = LayerWithIntVar(dtype="mixed_float16")
self.assertEqual(layer(x).dtype, "int32")
@parameterized.named_parameters(*TESTCASES)
def test_layer_with_non_autocast_variable(self, strategy_fn):
x = tf.constant([1.0])
with strategy_fn().scope():
with policy.policy_scope("mixed_float16"):
layer = mp_test_util.MultiplyLayerWithoutAutoCast(
assert_type=tf.float16
)
y = layer(x)
self.assertEqual(layer.v.dtype, tf.float32)
self.assertEqual(y.dtype, tf.float16)
self.evaluate(tf.compat.v1.global_variables_initializer())
self.assertEqual(self.evaluate(y), 1.0)
@parameterized.named_parameters(*TESTCASES)
def test_layer_calling_tf_function(self, strategy_fn):
x = tf.constant([1.0])
with strategy_fn().scope():
with policy.policy_scope("mixed_float16"):
layer = MultiplyLayerWithFunction(assert_type=tf.float16)
y = layer(x)
self.assertEqual(layer.v.dtype, tf.float32)
self.assertEqual(y.dtype, tf.float16)
self.evaluate(tf.compat.v1.global_variables_initializer())
self.assertEqual(self.evaluate(y), 1.0)
@parameterized.named_parameters(*TESTCASES)
def test_layer_regularizer_runs_in_var_dtype(self, strategy_fn):
x = tf.constant([1.0])
with strategy_fn().scope():
with policy.policy_scope("mixed_float16"):
# Test on MultiplyLayer
layer = mp_test_util.MultiplyLayer(
assert_type=tf.float16,
regularizer=mp_test_util.IdentityRegularizer(),
)
layer(x)
(regularizer_loss,) = layer.losses
self.assertEqual(regularizer_loss.dtype, tf.float32)
self.evaluate(tf.compat.v1.global_variables_initializer())
self.assertEqual(self.evaluate(regularizer_loss), 1.0)
# Test on MultiplyLayerWithoutAutoCast
layer = mp_test_util.MultiplyLayerWithoutAutoCast(
assert_type=tf.float16,
regularizer=mp_test_util.IdentityRegularizer(),
)
layer(x)
(regularizer_loss,) = layer.losses
self.assertEqual(regularizer_loss.dtype, tf.float32)
self.evaluate(tf.compat.v1.global_variables_initializer())
self.assertEqual(self.evaluate(regularizer_loss), 1.0)
@parameterized.named_parameters(*TESTCASES)
def test_passing_policy_to_layer(self, strategy_fn):
x = tf.constant([1.0], dtype=tf.float16)
with strategy_fn().scope():
# Passing a Policy to 'dtype' sets the policy for that layer.
layer = mp_test_util.MultiplyLayer(
assert_type=tf.float16, dtype=policy.Policy("mixed_float16")
)
# layer.dtype refers to the variable dtype
self.assertEqual(layer.dtype, tf.float32)
layer(x)
self.assertEqual(layer.v.dtype, tf.float32)
with policy.policy_scope("mixed_float16"):
# Passing a Policy to dtype overrides the global Policy
layer = mp_test_util.MultiplyLayer(
assert_type=tf.float64, dtype=policy.Policy("float64")
)
self.assertEqual(layer.dtype_policy.name, "float64")
self.assertIsInstance(layer.dtype_policy, policy.Policy)
self.assertEqual(layer.compute_dtype, tf.float64)
self.assertEqual(layer.dtype, tf.float64)
self.assertEqual(layer.variable_dtype, tf.float64)
self.assertEqual(layer(x).dtype, tf.float64)
self.assertEqual(layer.v.dtype, tf.float64)
@parameterized.named_parameters(*TESTCASES)
def test_gradient(self, strategy_fn):
x = tf.constant([1.0])
with strategy_fn().scope() as strategy:
with policy.policy_scope("mixed_float16"):
layer = mp_test_util.MultiplyLayer(assert_type=tf.float16)
# Learning rate is small enough that if applied to a float16
# variable, the variable will not change. So this tests the
# learning rate is not applied to a float16 value, but instead
# the float32 variable.
opt = gradient_descent.SGD(2**-14)
def run_fn():
with tf.GradientTape() as tape:
y = layer(x)
# Divide by num_replicas_in_sync, as the effective total
# loss is the sum of each of the replica's losses.
y /= strategy.num_replicas_in_sync
grad = tape.gradient(y, layer.v)
return opt.apply_gradients([(grad, layer.v)])
op = strategy.experimental_run(run_fn)
if not tf.executing_eagerly():
self.evaluate(tf.compat.v1.global_variables_initializer())
self.evaluate(op)
# The gradient with respective to the variable is 1. Since the
# variable is initialized with 1 and the learning rate is
# 2**-14, the new variable value should be: init_val - gradient
# * learning_rate, which is 1 - 1 * 2**-14
self.assertEqual(self.evaluate(layer.v), 1 - 2**-14)
def _test_checkpointing_layer_weights(
self, strategy_fn, mixed_prec_when_saving, mixed_prec_when_loading
):
# In this test, we potentially save with mixed precision enabled and
# load with mixed precision disabled, or vice versa. This is possible
# because variables are float32 regardless of whether mixed precision is
# enabled.
save_policy = "mixed_float16" if mixed_prec_when_saving else "float32"
load_policy = "mixed_float16" if mixed_prec_when_loading else "float32"
save_input_dtype = "float16" if mixed_prec_when_saving else "float32"
load_input_dtype = "float16" if mixed_prec_when_loading else "float32"
# Create a layer and save a checkpoint.
x = tf.constant([1.0])
with strategy_fn().scope():
with policy.policy_scope(save_policy):
layer = mp_test_util.MultiplyLayer(assert_type=save_input_dtype)
layer(x) # Build layer
layer.set_weights([np.array(100.0)])
self.assertEqual(self.evaluate(layer(x)), 100.0)
checkpoint = tf.train.Checkpoint(layer=layer)
prefix = os.path.join(self.get_temp_dir(), "ckpt")
save_path = checkpoint.save(prefix)
# Create a new layer and restore the checkpoint.
x = tf.constant([1.0])
with strategy_fn().scope():
with policy.policy_scope(load_policy):
layer = mp_test_util.MultiplyLayer(assert_type=load_input_dtype)
layer(x) # Build layer
layer.set_weights([np.array(200.0)])
self.assertEqual(self.evaluate(layer(x)), 200.0)
checkpoint = tf.train.Checkpoint(layer=layer)
checkpoint.restore(save_path).assert_consumed().run_restore_ops()
self.assertEqual(layer.get_weights(), [100.0])
self.assertEqual(self.evaluate(layer(x)), 100.0)
@parameterized.named_parameters(*TESTCASES)
def test_checkpointing_layer_weights(self, strategy_fn):
with self.test_session():
self._test_checkpointing_layer_weights(
strategy_fn,
mixed_prec_when_saving=True,
mixed_prec_when_loading=True,
)
self._test_checkpointing_layer_weights(
strategy_fn,
mixed_prec_when_saving=True,
mixed_prec_when_loading=False,
)
self._test_checkpointing_layer_weights(
strategy_fn,
mixed_prec_when_saving=False,
mixed_prec_when_loading=True,
)
@parameterized.named_parameters(*TESTCASES)
def test_config(self, strategy_fn):
x = tf.constant([1.0], dtype=tf.float16)
with strategy_fn().scope():
for layer, dtype in (
(mp_test_util.MultiplyLayer(), "float32"),
(mp_test_util.MultiplyLayer(dtype="float64"), "float64"),
(
mp_test_util.MultiplyLayer(dtype=policy.Policy("float64")),
"float64",
),
):
config = layer.get_config()
self.assertEqual(config["dtype"], dtype)
self.assertIsInstance(config["dtype"], str)
layer = mp_test_util.MultiplyLayer.from_config(config)
self.assertEqual(layer.dtype, dtype)
self.assertEqual(layer(x).dtype, dtype)
self.assertEqual(layer.v.dtype, dtype)
layer = mp_test_util.MultiplyLayer(dtype="mixed_float16")
config = layer.get_config()
if tf.__internal__.tf2.enabled():
self.assertEqual(
config["dtype"],
{
"module": "keras.mixed_precision",
"class_name": "Policy",
"config": {"name": "mixed_float16"},
"registered_name": None,
},
)
else:
self.assertEqual(
config["dtype"],
{
"class_name": "Policy",
"config": {"name": "mixed_float16"},
},
)
layer = mp_test_util.MultiplyLayer.from_config(config)
self.assertEqual(layer.dtype, "float32")
self.assertEqual(layer(x).dtype, "float16")
self.assertEqual(layer.v.dtype, "float32")
config = layer.get_config()
if tf.__internal__.tf2.enabled():
self.assertEqual(
config["dtype"],
{
"module": "keras.mixed_precision",
"class_name": "Policy",
"config": {"name": "mixed_float16"},
"registered_name": None,
},
)
else:
self.assertEqual(
config["dtype"],
{
"class_name": "Policy",
"config": {"name": "mixed_float16"},
},
)
layer = mp_test_util.MultiplyLayer(dtype=policy.Policy("_infer"))
config = layer.get_config()
self.assertIsNone(config["dtype"])
layer = mp_test_util.MultiplyLayer.from_config(config)
# If a layer is serialized with the "_infer" policy, when
# deserialized into TF 2 it will have the global policy instead of
# "_infer". This is because "_infer" is serialized into None, and
# passing dtype=None in TensorFlow 2 indicates to use the global
# policy.
self.assertEqual(layer.dtype, "float32")
self.assertEqual(layer(x).dtype, "float32")
self.assertEqual(layer.v.dtype, "float32")
@parameterized.named_parameters(*TESTCASES)
def test_from_config_policy_v1(self, strategy_fn):
# Test that layers serialized in previous TF-Keras versions with the
# now-deleted PolicyV1 can be deserialized. In such cases, the PolicyV1
# will be converted to a Policy, since PolicyV1 no longer exists. Unlike
# Policy, PolicyV1 had a "loss_scale" field, which is silently dropped
# when deserialized.
x = tf.constant([1.0], dtype=tf.float16)
with strategy_fn().scope():
layer = mp_test_util.MultiplyLayer(dtype="mixed_float16")
config = layer.get_config()
# Change the serialized dtype policy to a PolicyV1
if tf.__internal__.tf2.enabled():
config["dtype"] = {
"module": "keras.mixed_precision",
"class_name": "PolicyV1",
"config": {"name": "mixed_float16", "loss_scale": None},
"registered_name": None,
}
else:
config["dtype"] = {
"class_name": "PolicyV1",
"config": {"name": "mixed_float16", "loss_scale": None},
}
layer = mp_test_util.MultiplyLayer.from_config(config)
self.assertEqual(layer.dtype, "float32")
self.assertEqual(layer(x).dtype, "float16")
self.assertEqual(layer.v.dtype, "float32")
config = layer.get_config()
# The loss_scale is silently dropped
if tf.__internal__.tf2.enabled():
self.assertEqual(
config["dtype"],
{
"module": "keras.mixed_precision",
"class_name": "Policy",
"config": {"name": "mixed_float16"},
"registered_name": None,
},
)
else:
self.assertEqual(
config["dtype"],
{
"class_name": "Policy",
"config": {"name": "mixed_float16"},
},
)
layer = mp_test_util.MultiplyLayer(dtype="float64")
config = layer.get_config()
config["dtype"] = {
"class_name": "PolicyV1",
"config": {
"name": "float64",
"loss_scale": {
"class_name": "FixedLossScale",
"config": {"loss_scale_value": 2.0},
},
},
}
layer = mp_test_util.MultiplyLayer.from_config(config)
self.assertEqual(layer.dtype, "float64")
self.assertEqual(layer(x).dtype, "float64")
self.assertEqual(layer.v.dtype, "float64")
config = layer.get_config()
self.assertEqual(config["dtype"], "float64")
layer = mp_test_util.MultiplyLayer(dtype=policy.Policy("_infer"))
config = layer.get_config()
config["dtype"] = {
"class_name": "PolicyV1",
"config": {
"name": "_infer",
"loss_scale": {
"class_name": "FixedLossScale",
"config": {"loss_scale_value": 2.0},
},
},
}
layer = mp_test_util.MultiplyLayer.from_config(config)
self.assertEqual(layer.dtype, None)
self.assertEqual(layer(x).dtype, "float16")
self.assertEqual(layer.v.dtype, "float16")
self.assertEqual(type(layer.dtype_policy), policy.Policy)
config = layer.get_config()
self.assertEqual(config["dtype"], "float16")
def test_delete_variable(self):
layer = base_layer.Layer(dtype="mixed_float16")
layer.x = layer.add_weight("x")
self.assertEqual(layer.trainable_weights, [layer.x])
del layer.x
self.assertEqual(layer.trainable_weights, [])
def test_build_and_call_layer_in_function(self):
layer = mp_test_util.MultiplyLayer(dtype=policy.Policy("mixed_float16"))
@tf.function
def f():
return layer(1.0)
y = f()
self.evaluate(tf.compat.v1.global_variables_initializer())
self.assertEqual(y.dtype, "float16")
self.assertEqual(layer.v.dtype, "float32")
self.assertEqual(self.evaluate(y), 1.0)
def test_unsupported_strategy(self):
strategy = create_central_storage_strategy()
with strategy.scope(), self.assertRaisesRegex(
ValueError,
"Mixed precision is not supported with the "
"tf.distribute.Strategy: CentralStorageStrategy.",
):
mp_test_util.MultiplyLayer(dtype="mixed_float16")
# Non-mixed policies are fine
mp_test_util.MultiplyLayer(dtype=policy.Policy("float64"))
def test_input_spec_dtype(self):
# Test the InputSpec's dtype is compared against the inputs before the
# layer casts them, not after.
layer = mp_test_util.MultiplyLayer(dtype="float64")
layer.input_spec = input_spec.InputSpec(dtype="float16")
# Test passing Eager tensors
x = tf.ones((2, 2), dtype="float16")
layer(x)
x = tf.ones((2, 2), dtype="float64")
with self.assertRaisesRegex(
ValueError, "expected dtype=float16, found dtype=.*float64"
):
layer(x)
# Test passing symbolic tensors
x = layers.Input((2,), dtype="float16")
y = layer(x)
model = models.Model(x, y)
model(tf.ones((2, 2)))
x = layers.Input((2,), dtype="float64")
with self.assertRaisesRegex(
ValueError, "expected dtype=float16, found dtype=.*float64"
):
# In TF2, the error is only raised when the model is run
y = layer(x)
model = models.Model(x, y)
model(tf.ones((2, 2)))
if __name__ == "__main__":
base_layer_utils.enable_v2_dtype_behavior()
tf.test.main()
| tf-keras/tf_keras/mixed_precision/layer_test.py/0 | {
"file_path": "tf-keras/tf_keras/mixed_precision/layer_test.py",
"repo_id": "tf-keras",
"token_count": 10876
} | 194 |
# Copyright 2022 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.
# ==============================================================================
"""FTRL optimizer implementation."""
import tensorflow.compat.v2 as tf
from tf_keras.optimizers import optimizer
from tf_keras.saving.object_registration import register_keras_serializable
# isort: off
from tensorflow.python.util.tf_export import keras_export
@register_keras_serializable()
@keras_export(
"keras.optimizers.Ftrl", "keras.optimizers.experimental.Ftrl", v1=[]
)
class Ftrl(optimizer.Optimizer):
r"""Optimizer that implements the FTRL algorithm.
"Follow The Regularized Leader" (FTRL) is an optimization algorithm
developed at Google for click-through rate prediction in the early 2010s. It
is most suitable for shallow models with large and sparse feature spaces.
The algorithm is described by
[McMahan et al., 2013](https://research.google.com/pubs/archive/41159.pdf).
The TF-Keras version has support for both online L2 regularization
(the L2 regularization described in the paper
above) and shrinkage-type L2 regularization
(which is the addition of an L2 penalty to the loss function).
Initialization:
```python
n = 0
sigma = 0
z = 0
```
Update rule for one variable `w`:
```python
prev_n = n
n = n + g ** 2
sigma = (n ** -lr_power - prev_n ** -lr_power) / lr
z = z + g - sigma * w
if abs(z) < lambda_1:
w = 0
else:
w = (sgn(z) * lambda_1 - z) / ((beta + sqrt(n)) / alpha + lambda_2)
```
Notation:
- `lr` is the learning rate
- `g` is the gradient for the variable
- `lambda_1` is the L1 regularization strength
- `lambda_2` is the L2 regularization strength
- `lr_power` is the power to scale n.
Check the documentation for the `l2_shrinkage_regularization_strength`
parameter for more details when shrinkage is enabled, in which case gradient
is replaced with a gradient with shrinkage.
Args:
learning_rate: A `Tensor`, floating point value, a schedule that is a
`tf.keras.optimizers.schedules.LearningRateSchedule`, or a callable
that takes no arguments and returns the actual value to use. The
learning rate. Defaults to `0.001`.
learning_rate_power: A float value, must be less or equal to zero.
Controls how the learning rate decreases during training. Use zero
for a fixed learning rate.
initial_accumulator_value: The starting value for accumulators. Only
zero or positive values are allowed.
l1_regularization_strength: A float value, must be greater than or equal
to zero. Defaults to `0.0`.
l2_regularization_strength: A float value, must be greater than or equal
to zero. Defaults to `0.0`.
l2_shrinkage_regularization_strength: A float value, must be greater
than or equal to zero. This differs from L2 above in that the L2
above is a stabilization penalty, whereas this L2 shrinkage is a
magnitude penalty. When input is sparse shrinkage will only happen
on the active weights.
beta: A float value, representing the beta value from the paper.
Defaults to 0.0.
{{base_optimizer_keyword_args}}
"""
def __init__(
self,
learning_rate=0.001,
learning_rate_power=-0.5,
initial_accumulator_value=0.1,
l1_regularization_strength=0.0,
l2_regularization_strength=0.0,
l2_shrinkage_regularization_strength=0.0,
beta=0.0,
weight_decay=None,
clipnorm=None,
clipvalue=None,
global_clipnorm=None,
use_ema=False,
ema_momentum=0.99,
ema_overwrite_frequency=None,
jit_compile=True,
name="Ftrl",
**kwargs,
):
super().__init__(
name=name,
weight_decay=weight_decay,
clipnorm=clipnorm,
clipvalue=clipvalue,
global_clipnorm=global_clipnorm,
use_ema=use_ema,
ema_momentum=ema_momentum,
ema_overwrite_frequency=ema_overwrite_frequency,
jit_compile=jit_compile,
**kwargs,
)
if initial_accumulator_value < 0.0:
raise ValueError(
"`initial_accumulator_value` needs to be positive or zero. "
"Received: initial_accumulator_value="
f"{initial_accumulator_value}."
)
if learning_rate_power > 0.0:
raise ValueError(
"`learning_rate_power` needs to be negative or zero. Received: "
f"learning_rate_power={learning_rate_power}."
)
if l1_regularization_strength < 0.0:
raise ValueError(
"`l1_regularization_strength` needs to be positive or zero. "
"Received: l1_regularization_strength="
f"{l1_regularization_strength}."
)
if l2_regularization_strength < 0.0:
raise ValueError(
"`l2_regularization_strength` needs to be positive or zero. "
"Received: l2_regularization_strength="
f"{l2_regularization_strength}."
)
if l2_shrinkage_regularization_strength < 0.0:
raise ValueError(
"`l2_shrinkage_regularization_strength` needs to be positive "
"or zero. Received: l2_shrinkage_regularization_strength"
f"={l2_shrinkage_regularization_strength}."
)
self._learning_rate = self._build_learning_rate(learning_rate)
self.learning_rate_power = learning_rate_power
self.initial_accumulator_value = initial_accumulator_value
self.l1_regularization_strength = l1_regularization_strength
self.l2_regularization_strength = l2_regularization_strength
self.l2_shrinkage_regularization_strength = (
l2_shrinkage_regularization_strength
)
self.beta = beta
def build(self, var_list):
"""Initialize optimizer variables.
Args:
var_list: list of model variables to build Ftrl variables on.
"""
super().build(var_list)
if hasattr(self, "_built") and self._built:
return
self._accumulators = []
self._linears = []
for var in var_list:
self._accumulators.append(
self.add_variable_from_reference(
model_variable=var,
variable_name="accumulator",
initial_value=tf.cast(
tf.fill(
dims=var.shape, value=self.initial_accumulator_value
),
dtype=var.dtype,
),
)
)
self._linears.append(
self.add_variable_from_reference(
model_variable=var, variable_name="linear"
)
)
self._built = True
def update_step(self, gradient, variable):
"""Update step given gradient and the associated model variable."""
lr = tf.cast(self.learning_rate, variable.dtype)
var_key = self._var_key(variable)
accum = self._accumulators[self._index_dict[var_key]]
linear = self._linears[self._index_dict[var_key]]
lr_power = self.learning_rate_power
l2_reg = self.l2_regularization_strength
l2_reg = l2_reg + self.beta / (2.0 * lr)
# Ftrl optimizer has the same implementation for sparse and dense
# gradients update.
grad_to_use = (
gradient + 2 * self.l2_shrinkage_regularization_strength * variable
)
new_accum = accum + tf.pow(gradient, 2)
linear.assign_add(
grad_to_use
- (tf.pow(new_accum, -lr_power) - tf.pow(accum, -lr_power))
/ lr
* variable
)
quadratic = tf.pow(new_accum, (-lr_power)) / lr + 2 * l2_reg
linear_clipped = tf.clip_by_value(
linear,
-self.l1_regularization_strength,
self.l1_regularization_strength,
)
variable.assign((linear_clipped - linear) / quadratic)
accum.assign(new_accum)
def get_config(self):
config = super().get_config()
config.update(
{
"learning_rate": self._serialize_hyperparameter(
self._learning_rate
),
"learning_rate_power": self.learning_rate_power,
"initial_accumulator_value": self.initial_accumulator_value,
"l1_regularization_strength": self.l1_regularization_strength,
"l2_regularization_strength": self.l2_regularization_strength,
"l2_shrinkage_regularization_strength": self.l2_shrinkage_regularization_strength, # noqa: E501
"beta": self.beta,
}
)
return config
Ftrl.__doc__ = Ftrl.__doc__.replace(
"{{base_optimizer_keyword_args}}", optimizer.base_optimizer_keyword_args
)
| tf-keras/tf_keras/optimizers/ftrl.py/0 | {
"file_path": "tf-keras/tf_keras/optimizers/ftrl.py",
"repo_id": "tf-keras",
"token_count": 4358
} | 195 |
# Copyright 2015 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 Nadam."""
import numpy as np
import tensorflow.compat.v2 as tf
from tf_keras.optimizers.legacy import nadam
def get_beta_accumulators(opt, dtype):
local_step = tf.cast(opt.iterations + 1, dtype)
beta_1_t = tf.cast(opt._get_hyper("beta_1"), dtype)
beta_1_power = tf.pow(beta_1_t, local_step)
beta_2_t = tf.cast(opt._get_hyper("beta_2"), dtype)
beta_2_power = tf.pow(beta_2_t, local_step)
return (beta_1_power, beta_2_power)
def update_m_cache(m_cache, t, beta1=0.9):
mu_t = beta1 * (1 - 0.5 * 0.96 ** (0.004 * (t + 1)))
m_cache_t = m_cache * mu_t
return m_cache_t
def nadam_update_numpy(
param,
g_t,
t,
m,
v,
m_cache,
alpha=0.001,
beta1=0.9,
beta2=0.999,
epsilon=1e-8,
):
mu_t = beta1 * (1 - 0.5 * 0.96 ** (0.004 * (t + 1)))
mu_t_1 = beta1 * (1 - 0.5 * 0.96 ** (0.004 * (t + 2)))
m_cache_t_1 = m_cache * mu_t_1
g_prime_t = g_t / (1 - m_cache)
m_t = beta1 * m + (1 - beta1) * g_t
v_t = beta2 * v + (1 - beta2) * g_t * g_t
m_prime_t = m_t / (1 - m_cache_t_1)
v_prime_t = v_t / (1 - beta2 ** (t + 1))
m_bar_t = (1 - mu_t) * g_prime_t + mu_t_1 * m_prime_t
param_t = param - alpha * m_bar_t / (np.sqrt(v_prime_t) + epsilon)
return param_t, m_t, v_t
class NadamOptimizerTest(tf.test.TestCase):
def testSparse(self):
# TODO(tanzheny, omalleyt): Fix test in eager mode.
sparse_epsilon = 1e-7
for dtype in [tf.half, tf.float32, tf.float64]:
with tf.Graph().as_default(), self.cached_session():
# Initialize variables for numpy implementation.
m0, v0, m1, v1, mcache = 0.0, 0.0, 0.0, 0.0, 1.0
var0_np = np.array([1.0, 1.0, 2.0], dtype=dtype.as_numpy_dtype)
grads0_np = np.array([0.1, 0, 0.1], dtype=dtype.as_numpy_dtype)
var1_np = np.array([3.0, 3.0, 4.0], dtype=dtype.as_numpy_dtype)
grads1_np = np.array(
[0.01, 0, 0.01], dtype=dtype.as_numpy_dtype
)
var0 = tf.Variable(var0_np)
var1 = tf.Variable(var1_np)
grads0_np_indices = np.array([0, 2], dtype=np.int32)
grads0 = tf.IndexedSlices(
tf.constant(grads0_np[grads0_np_indices]),
tf.constant(grads0_np_indices),
tf.constant([3]),
)
grads1_np_indices = np.array([0, 2], dtype=np.int32)
grads1 = tf.IndexedSlices(
tf.constant(grads1_np[grads1_np_indices]),
tf.constant(grads1_np_indices),
tf.constant([3]),
)
opt = nadam.Nadam(epsilon=sparse_epsilon)
update = opt.apply_gradients(
zip([grads0, grads1], [var0, var1])
)
self.evaluate(tf.compat.v1.global_variables_initializer())
# Fetch params to validate initial values
self.assertAllClose([1.0, 1.0, 2.0], var0)
self.assertAllClose([3.0, 3.0, 4.0], var1)
beta1_power, beta2_power = get_beta_accumulators(opt, dtype)
# Run 3 steps of Nadam
for t in range(3):
self.assertAllCloseAccordingToType(
0.9 ** (t + 1), beta1_power
)
self.assertAllCloseAccordingToType(
0.999 ** (t + 1), beta2_power
)
update.run()
mcache = update_m_cache(mcache, t)
var0_np, m0, v0 = nadam_update_numpy(
var0_np,
grads0_np,
t,
m0,
v0,
mcache,
epsilon=sparse_epsilon,
)
var1_np, m1, v1 = nadam_update_numpy(
var1_np,
grads1_np,
t,
m1,
v1,
mcache,
epsilon=sparse_epsilon,
)
# Validate updated params
self.assertAllCloseAccordingToType(var0_np, var0)
self.assertAllCloseAccordingToType(var1_np, var1)
def testBasic(self):
# TODO(tanzheny, omalleyt): Fix test in eager mode.
for dtype in [tf.half, tf.float32, tf.float64]:
with tf.Graph().as_default(), self.cached_session():
# Initialize variables for numpy implementation.
m0, v0, m1, v1, mcache = 0.0, 0.0, 0.0, 0.0, 1.0
var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)
grads0_np = np.array([0.1, 0.1], dtype=dtype.as_numpy_dtype)
var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)
grads1_np = np.array([0.01, 0.01], dtype=dtype.as_numpy_dtype)
var0 = tf.Variable(var0_np)
var1 = tf.Variable(var1_np)
grads0 = tf.constant(grads0_np)
grads1 = tf.constant(grads1_np)
opt = nadam.Nadam()
update = opt.apply_gradients(
zip([grads0, grads1], [var0, var1])
)
self.evaluate(tf.compat.v1.global_variables_initializer())
# Fetch params to validate initial values
self.assertAllClose([1.0, 2.0], var0)
self.assertAllClose([3.0, 4.0], var1)
# Run 3 steps of Nadam
for t in range(3):
update.run()
mcache = update_m_cache(mcache, t)
var0_np, m0, v0 = nadam_update_numpy(
var0_np, grads0_np, t, m0, v0, mcache
)
var1_np, m1, v1 = nadam_update_numpy(
var1_np, grads1_np, t, m1, v1, mcache
)
# Validate updated params
self.assertAllCloseAccordingToType(var0_np, var0)
self.assertAllCloseAccordingToType(var1_np, var1)
def testConstructNAdamWithLR(self):
opt = nadam.Nadam(lr=1.0)
opt_2 = nadam.Nadam(learning_rate=0.1, lr=1.0)
opt_3 = nadam.Nadam(learning_rate=0.1)
self.assertIsInstance(opt.lr, tf.Variable)
self.assertIsInstance(opt_2.lr, tf.Variable)
self.assertIsInstance(opt_3.lr, tf.Variable)
self.evaluate(tf.compat.v1.global_variables_initializer())
self.assertAllClose(self.evaluate(opt.lr), (1.0))
self.assertAllClose(self.evaluate(opt_2.lr), (1.0))
self.assertAllClose(self.evaluate(opt_3.lr), (0.1))
def testConstructNAdamWithScheduleDecay(self):
opt = nadam.Nadam(schedule_decay=0.2)
self.assertIsInstance(opt.decay, tf.Variable)
self.evaluate(tf.compat.v1.global_variables_initializer())
self.assertAllClose(self.evaluate(opt.decay), (0.2))
if __name__ == "__main__":
tf.test.main()
| tf-keras/tf_keras/optimizers/legacy/nadam_test.py/0 | {
"file_path": "tf-keras/tf_keras/optimizers/legacy/nadam_test.py",
"repo_id": "tf-keras",
"token_count": 4454
} | 196 |
# Description:
# Contains the learning rate schedule API,
# Placeholder: load unaliased py_library
load("@org_keras//tf_keras:tf_keras.bzl", "cuda_py_test")
package(
# copybara:uncomment default_applicable_licenses = ["//tf_keras:license"],
default_visibility = ["//tf_keras:friends"],
licenses = ["notice"],
)
py_library(
name = "learning_rate_schedule",
srcs = [
"learning_rate_schedule.py",
],
srcs_version = "PY3",
deps = [
"//:expect_tensorflow_installed",
"//tf_keras/utils:generic_utils",
],
)
cuda_py_test(
name = "learning_rate_schedule_test",
size = "medium",
srcs = ["learning_rate_schedule_test.py"],
shard_count = 4,
deps = [
"//:expect_absl_installed", # absl/testing:parameterized
"//:expect_numpy_installed",
"//:expect_tensorflow_installed",
"//tf_keras",
"//tf_keras/optimizers/legacy:optimizers",
"//tf_keras/testing_infra:test_combinations",
],
)
| tf-keras/tf_keras/optimizers/schedules/BUILD/0 | {
"file_path": "tf-keras/tf_keras/optimizers/schedules/BUILD",
"repo_id": "tf-keras",
"token_count": 451
} | 197 |
# Copyright 2015 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.
# ==============================================================================
"""Utilities for preprocessing sequence data.
Deprecated: `tf.keras.preprocessing.sequence` APIs are not recommended for new
code. Prefer `tf.keras.utils.timeseries_dataset_from_array` and
the `tf.data` APIs which provide a much more flexible mechanisms for dealing
with sequences. See the [tf.data guide](https://www.tensorflow.org/guide/data)
for more details.
"""
import json
import random
import numpy as np
from tf_keras.utils import data_utils
# isort: off
from tensorflow.python.util.tf_export import keras_export
def _remove_long_seq(maxlen, seq, label):
"""Removes sequences that exceed the maximum length.
Args:
maxlen: Int, maximum length of the output sequences.
seq: List of lists, where each sublist is a sequence.
label: List where each element is an integer.
Returns:
new_seq, new_label: shortened lists for `seq` and `label`.
"""
new_seq, new_label = [], []
for x, y in zip(seq, label):
if len(x) < maxlen:
new_seq.append(x)
new_label.append(y)
return new_seq, new_label
@keras_export("keras.preprocessing.sequence.TimeseriesGenerator")
class TimeseriesGenerator(data_utils.Sequence):
"""Utility class for generating batches of temporal data.
Deprecated: `tf.keras.preprocessing.sequence.TimeseriesGenerator` does not
operate on tensors and is not recommended for new code. Prefer using a
`tf.data.Dataset` which provides a more efficient and flexible mechanism for
batching, shuffling, and windowing input. See the
[tf.data guide](https://www.tensorflow.org/guide/data) for more details.
This class takes in a sequence of data-points gathered at
equal intervals, along with time series parameters such as
stride, length of history, etc., to produce batches for
training/validation.
Arguments:
data: Indexable generator (such as list or Numpy array)
containing consecutive data points (timesteps).
The data should be at 2D, and axis 0 is expected
to be the time dimension.
targets: Targets corresponding to timesteps in `data`.
It should have same length as `data`.
length: Length of the output sequences (in number of timesteps).
sampling_rate: Period between successive individual timesteps
within sequences. For rate `r`, timesteps
`data[i]`, `data[i-r]`, ... `data[i - length]`
are used for create a sample sequence.
stride: Period between successive output sequences.
For stride `s`, consecutive output samples would
be centered around `data[i]`, `data[i+s]`, `data[i+2*s]`, etc.
start_index: Data points earlier than `start_index` will not be used
in the output sequences. This is useful to reserve part of the
data for test or validation.
end_index: Data points later than `end_index` will not be used
in the output sequences. This is useful to reserve part of the
data for test or validation.
shuffle: Whether to shuffle output samples,
or instead draw them in chronological order.
reverse: Boolean: if `true`, timesteps in each output sample will be
in reverse chronological order.
batch_size: Number of timeseries samples in each batch
(except maybe the last one).
Returns:
A [Sequence](
https://www.tensorflow.org/api_docs/python/tf/tf_keras/utils/Sequence)
instance.
Examples:
```python
from tf_keras.preprocessing.sequence import TimeseriesGenerator
import numpy as np
data = np.array([[i] for i in range(50)])
targets = np.array([[i] for i in range(50)])
data_gen = TimeseriesGenerator(data, targets,
length=10, sampling_rate=2,
batch_size=2)
assert len(data_gen) == 20
batch_0 = data_gen[0]
x, y = batch_0
assert np.array_equal(x,
np.array([[[0], [2], [4], [6], [8]],
[[1], [3], [5], [7], [9]]]))
assert np.array_equal(y,
np.array([[10], [11]]))
```
"""
def __init__(
self,
data,
targets,
length,
sampling_rate=1,
stride=1,
start_index=0,
end_index=None,
shuffle=False,
reverse=False,
batch_size=128,
):
if len(data) != len(targets):
raise ValueError(
"Data and targets have to be"
+ f" of same length. Data length is {len(data)}"
+ f" while target length is {len(targets)}"
)
self.data = data
self.targets = targets
self.length = length
self.sampling_rate = sampling_rate
self.stride = stride
self.start_index = start_index + length
if end_index is None:
end_index = len(data) - 1
self.end_index = end_index
self.shuffle = shuffle
self.reverse = reverse
self.batch_size = batch_size
if self.start_index > self.end_index:
raise ValueError(
"`start_index+length=%i > end_index=%i` "
"is disallowed, as no part of the sequence "
"would be left to be used as current step."
% (self.start_index, self.end_index)
)
def __len__(self):
return (
self.end_index - self.start_index + self.batch_size * self.stride
) // (self.batch_size * self.stride)
def __getitem__(self, index):
if self.shuffle:
rows = np.random.randint(
self.start_index, self.end_index + 1, size=self.batch_size
)
else:
i = self.start_index + self.batch_size * self.stride * index
rows = np.arange(
i,
min(i + self.batch_size * self.stride, self.end_index + 1),
self.stride,
)
samples = np.array(
[
self.data[row - self.length : row : self.sampling_rate]
for row in rows
]
)
targets = np.array([self.targets[row] for row in rows])
if self.reverse:
return samples[:, ::-1, ...], targets
return samples, targets
def get_config(self):
"""Returns the TimeseriesGenerator configuration as Python dictionary.
Returns:
A Python dictionary with the TimeseriesGenerator configuration.
"""
data = self.data
if type(self.data).__module__ == np.__name__:
data = self.data.tolist()
try:
json_data = json.dumps(data)
except TypeError as e:
raise TypeError("Data not JSON Serializable:", data) from e
targets = self.targets
if type(self.targets).__module__ == np.__name__:
targets = self.targets.tolist()
try:
json_targets = json.dumps(targets)
except TypeError as e:
raise TypeError("Targets not JSON Serializable:", targets) from e
return {
"data": json_data,
"targets": json_targets,
"length": self.length,
"sampling_rate": self.sampling_rate,
"stride": self.stride,
"start_index": self.start_index,
"end_index": self.end_index,
"shuffle": self.shuffle,
"reverse": self.reverse,
"batch_size": self.batch_size,
}
def to_json(self, **kwargs):
"""Returns a JSON string containing the generator's configuration.
Args:
**kwargs: Additional keyword arguments to be passed
to `json.dumps()`.
Returns:
A JSON string containing the tokenizer configuration.
"""
config = self.get_config()
timeseries_generator_config = {
"class_name": self.__class__.__name__,
"config": config,
}
return json.dumps(timeseries_generator_config, **kwargs)
@keras_export("keras.preprocessing.sequence.make_sampling_table")
def make_sampling_table(size, sampling_factor=1e-5):
"""Generates a word rank-based probabilistic sampling table.
Used for generating the `sampling_table` argument for `skipgrams`.
`sampling_table[i]` is the probability of sampling
the word i-th most common word in a dataset
(more common words should be sampled less frequently, for balance).
The sampling probabilities are generated according
to the sampling distribution used in word2vec:
```
p(word) = (min(1, sqrt(word_frequency / sampling_factor) /
(word_frequency / sampling_factor)))
```
We assume that the word frequencies follow Zipf's law (s=1) to derive
a numerical approximation of frequency(rank):
`frequency(rank) ~ 1/(rank * (log(rank) + gamma) + 1/2 - 1/(12*rank))`
where `gamma` is the Euler-Mascheroni constant.
Args:
size: Int, number of possible words to sample.
sampling_factor: The sampling factor in the word2vec formula.
Returns:
A 1D Numpy array of length `size` where the ith entry
is the probability that a word of rank i should be sampled.
"""
gamma = 0.577
rank = np.arange(size)
rank[0] = 1
inv_fq = rank * (np.log(rank) + gamma) + 0.5 - 1.0 / (12.0 * rank)
f = sampling_factor * inv_fq
return np.minimum(1.0, f / np.sqrt(f))
@keras_export("keras.preprocessing.sequence.skipgrams")
def skipgrams(
sequence,
vocabulary_size,
window_size=4,
negative_samples=1.0,
shuffle=True,
categorical=False,
sampling_table=None,
seed=None,
):
"""Generates skipgram word pairs.
This function transforms a sequence of word indexes (list of integers)
into tuples of words of the form:
- (word, word in the same window), with label 1 (positive samples).
- (word, random word from the vocabulary), with label 0 (negative samples).
Read more about Skipgram in this gnomic paper by Mikolov et al.:
[Efficient Estimation of Word Representations in
Vector Space](http://arxiv.org/pdf/1301.3781v3.pdf)
Args:
sequence: A word sequence (sentence), encoded as a list
of word indices (integers). If using a `sampling_table`,
word indices are expected to match the rank
of the words in a reference dataset (e.g. 10 would encode
the 10-th most frequently occurring token).
Note that index 0 is expected to be a non-word and will be skipped.
vocabulary_size: Int, maximum possible word index + 1
window_size: Int, size of sampling windows (technically half-window).
The window of a word `w_i` will be
`[i - window_size, i + window_size+1]`.
negative_samples: Float >= 0. 0 for no negative (i.e. random) samples.
1 for same number as positive samples.
shuffle: Whether to shuffle the word couples before returning them.
categorical: bool. if False, labels will be
integers (eg. `[0, 1, 1 .. ]`),
if `True`, labels will be categorical, e.g.
`[[1,0],[0,1],[0,1] .. ]`.
sampling_table: 1D array of size `vocabulary_size` where the entry i
encodes the probability to sample a word of rank i.
seed: Random seed.
Returns:
couples, labels: where `couples` are int pairs and
`labels` are either 0 or 1.
Note:
By convention, index 0 in the vocabulary is
a non-word and will be skipped.
"""
couples = []
labels = []
for i, wi in enumerate(sequence):
if not wi:
continue
if sampling_table is not None:
if sampling_table[wi] < random.random():
continue
window_start = max(0, i - window_size)
window_end = min(len(sequence), i + window_size + 1)
for j in range(window_start, window_end):
if j != i:
wj = sequence[j]
if not wj:
continue
couples.append([wi, wj])
if categorical:
labels.append([0, 1])
else:
labels.append(1)
if negative_samples > 0:
num_negative_samples = int(len(labels) * negative_samples)
words = [c[0] for c in couples]
random.shuffle(words)
couples += [
[words[i % len(words)], random.randint(1, vocabulary_size - 1)]
for i in range(num_negative_samples)
]
if categorical:
labels += [[1, 0]] * num_negative_samples
else:
labels += [0] * num_negative_samples
if shuffle:
if seed is None:
seed = random.randint(0, 10e6)
random.seed(seed)
random.shuffle(couples)
random.seed(seed)
random.shuffle(labels)
return couples, labels
| tf-keras/tf_keras/preprocessing/sequence.py/0 | {
"file_path": "tf-keras/tf_keras/preprocessing/sequence.py",
"repo_id": "tf-keras",
"token_count": 5919
} | 198 |
# Copyright 2018 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 that save the model's config into different formats."""
# isort: off
import threading
from tensorflow.python.util.tf_export import keras_export
from tf_keras.saving.legacy import serialization
MODULE_OBJECTS = threading.local()
@keras_export("keras.models.model_from_config")
def model_from_config(config, custom_objects=None):
"""Instantiates a TF-Keras model from its config.
Usage:
```
# for a Functional API model
tf.keras.Model().from_config(model.get_config())
# for a Sequential model
tf.keras.Sequential().from_config(model.get_config())
```
Args:
config: Configuration dictionary.
custom_objects: Optional dictionary mapping names
(strings) to custom classes or functions to be
considered during deserialization.
Returns:
A TF-Keras model instance (uncompiled).
Raises:
TypeError: if `config` is not a dictionary.
"""
if isinstance(config, list):
raise TypeError(
"`model_from_config` expects a dictionary, not a list. "
f"Received: config={config}. Did you meant to use "
"`Sequential.from_config(config)`?"
)
from tf_keras import layers
global MODULE_OBJECTS
if not hasattr(MODULE_OBJECTS, "ALL_OBJECTS"):
layers.serialization.populate_deserializable_objects()
MODULE_OBJECTS.ALL_OBJECTS = layers.serialization.LOCAL.ALL_OBJECTS
return serialization.deserialize_keras_object(
config,
module_objects=MODULE_OBJECTS.ALL_OBJECTS,
custom_objects=custom_objects,
printable_module_name="layer",
)
@keras_export("keras.models.model_from_yaml")
def model_from_yaml(yaml_string, custom_objects=None):
"""Parses a yaml model configuration file and returns a model instance.
Note: Since TF 2.6, this method is no longer supported and will raise a
RuntimeError.
Args:
yaml_string: YAML string or open file encoding a model configuration.
custom_objects: Optional dictionary mapping names
(strings) to custom classes or functions to be
considered during deserialization.
Returns:
A TF-Keras model instance (uncompiled).
Raises:
RuntimeError: announces that the method poses a security risk
"""
raise RuntimeError(
"Method `model_from_yaml()` has been removed due to security risk of "
"arbitrary code execution. Please use `Model.to_json()` and "
"`model_from_json()` instead."
)
@keras_export("keras.models.model_from_json")
def model_from_json(json_string, custom_objects=None):
"""Parses a JSON model configuration string and returns a model instance.
Usage:
>>> model = tf.keras.Sequential([
... tf.keras.layers.Dense(5, input_shape=(3,)),
... tf.keras.layers.Softmax()])
>>> config = model.to_json()
>>> loaded_model = tf.keras.models.model_from_json(config)
Args:
json_string: JSON string encoding a model configuration.
custom_objects: Optional dictionary mapping names
(strings) to custom classes or functions to be
considered during deserialization.
Returns:
A TF-Keras model instance (uncompiled).
"""
from tf_keras.layers import (
deserialize_from_json,
)
return deserialize_from_json(json_string, custom_objects=custom_objects)
| tf-keras/tf_keras/saving/legacy/model_config.py/0 | {
"file_path": "tf-keras/tf_keras/saving/legacy/model_config.py",
"repo_id": "tf-keras",
"token_count": 1478
} | 199 |
# Copyright 2019 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.
# ==============================================================================
"""Classes and functions implementing to Model SavedModel serialization."""
from tf_keras.saving.legacy import saving_utils
from tf_keras.saving.legacy.saved_model import constants
from tf_keras.saving.legacy.saved_model import layer_serialization
from tf_keras.saving.legacy.saved_model import save_impl
class ModelSavedModelSaver(layer_serialization.LayerSavedModelSaver):
"""Model SavedModel serialization."""
@property
def object_identifier(self):
return constants.MODEL_IDENTIFIER
def _python_properties_internal(self):
metadata = super()._python_properties_internal()
# Network stateful property is dependent on the child layers.
metadata.pop("stateful")
metadata["is_graph_network"] = self.obj._is_graph_network
spec = self.obj.save_spec(dynamic_batch=False)
metadata["full_save_spec"] = spec
# save_spec is saved for forward compatibility on older TF versions.
metadata["save_spec"] = None if spec is None else spec[0][0]
metadata.update(
saving_utils.model_metadata(
self.obj, include_optimizer=True, require_config=False
)
)
return metadata
def _get_serialized_attributes_internal(self, serialization_cache):
default_signature = None
# Create a default signature function if this is the only object in the
# cache (i.e. this is the root level object).
if len(serialization_cache[constants.KERAS_CACHE_KEY]) == 1:
default_signature = save_impl.default_save_signature(self.obj)
# Other than the default signature function, all other attributes match
# with the ones serialized by Layer.
objects, functions = super()._get_serialized_attributes_internal(
serialization_cache
)
functions["_default_save_signature"] = default_signature
return objects, functions
class SequentialSavedModelSaver(ModelSavedModelSaver):
@property
def object_identifier(self):
return constants.SEQUENTIAL_IDENTIFIER
| tf-keras/tf_keras/saving/legacy/saved_model/model_serialization.py/0 | {
"file_path": "tf-keras/tf_keras/saving/legacy/saved_model/model_serialization.py",
"repo_id": "tf-keras",
"token_count": 925
} | 200 |
# Copyright 2022 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.
# ==============================================================================
"""Public API surface for saving APIs."""
import os
import warnings
import zipfile
import tensorflow.compat.v2 as tf
from tensorflow.python.util.tf_export import keras_export
from tf_keras.saving import saving_lib
from tf_keras.saving.legacy import save as legacy_sm_saving_lib
from tf_keras.utils import io_utils
try:
import h5py
except ImportError:
h5py = None
is_oss = True
def _support_gcs_uri(filepath, save_format, is_oss):
"""Supports GCS URIs through bigstore via a temporary file."""
gs_filepath = None
if str(filepath).startswith("gs://") and save_format != "tf":
gs_filepath = filepath
if not is_oss:
gs_filepath = filepath.replace("gs://", "/bigstore/")
filepath = os.path.join(
saving_lib.get_temp_dir(), os.path.basename(gs_filepath)
)
return gs_filepath, filepath
@keras_export("keras.saving.save_model", "keras.models.save_model")
def save_model(model, filepath, overwrite=True, save_format=None, **kwargs):
"""Saves a model as a TensorFlow SavedModel or HDF5 file.
See the [Serialization and Saving guide](
https://keras.io/guides/serialization_and_saving/) for details.
Args:
model: TF-Keras model instance to be saved.
filepath: `str` or `pathlib.Path` object. Path where to save the model.
overwrite: Whether we should overwrite any existing model at the target
location, or instead ask the user via an interactive prompt.
save_format: Either `"keras"`, `"tf"`, `"h5"`,
indicating whether to save the model
in the native TF-Keras format (`.keras`),
in the TensorFlow SavedModel format (referred to as "SavedModel"
below), or in the legacy HDF5 format (`.h5`).
Defaults to `"tf"` in TF 2.X, and `"h5"` in TF 1.X.
SavedModel format arguments:
include_optimizer: Only applied to SavedModel and legacy HDF5 formats.
If False, do not save the optimizer state. Defaults to True.
signatures: Only applies to SavedModel format. Signatures to save
with the SavedModel. See the `signatures` argument in
`tf.saved_model.save` for details.
options: Only applies to SavedModel format.
`tf.saved_model.SaveOptions` object that specifies SavedModel
saving options.
save_traces: Only applies to SavedModel format. When enabled, the
SavedModel will store the function traces for each layer. This
can be disabled, so that only the configs of each layer are stored.
Defaults to `True`. Disabling this will decrease serialization time
and reduce file size, but it requires that all custom layers/models
implement a `get_config()` method.
Example:
```python
model = tf.keras.Sequential([
tf.keras.layers.Dense(5, input_shape=(3,)),
tf.keras.layers.Softmax()])
model.save("model.keras")
loaded_model = tf.keras.saving.load_model("model.keras")
x = tf.random.uniform((10, 3))
assert np.allclose(model.predict(x), loaded_model.predict(x))
```
Note that `model.save()` is an alias for `tf.keras.saving.save_model()`.
The SavedModel or HDF5 file contains:
- The model's configuration (architecture)
- The model's weights
- The model's optimizer's state (if any)
Thus models can be reinstantiated in the exact same state, without any of
the code used for model definition or training.
Note that the model weights may have different scoped names after being
loaded. Scoped names include the model/layer names, such as
`"dense_1/kernel:0"`. It is recommended that you use the layer properties to
access specific variables, e.g. `model.get_layer("dense_1").kernel`.
__SavedModel serialization format__
With `save_format="tf"`, the model and all trackable objects attached
to the it (e.g. layers and variables) are saved as a TensorFlow SavedModel.
The model config, weights, and optimizer are included in the SavedModel.
Additionally, for every TF-Keras layer attached to the model, the SavedModel
stores:
* The config and metadata -- e.g. name, dtype, trainable status
* Traced call and loss functions, which are stored as TensorFlow
subgraphs.
The traced functions allow the SavedModel format to save and load custom
layers without the original class definition.
You can choose to not save the traced functions by disabling the
`save_traces` option. This will decrease the time it takes to save the model
and the amount of disk space occupied by the output SavedModel. If you
enable this option, then you _must_ provide all custom class definitions
when loading the model. See the `custom_objects` argument in
`tf.keras.saving.load_model`.
"""
save_format = get_save_format(filepath, save_format)
# Supports GCS URIs through bigstore via a temporary file
gs_filepath, filepath = _support_gcs_uri(filepath, save_format, is_oss)
# Deprecation warnings
if save_format == "h5":
warnings.warn(
"You are saving your model as an HDF5 file via `model.save()`. "
"This file format is considered legacy. "
"We recommend using instead the native TF-Keras format, "
"e.g. `model.save('my_model.keras')`.",
stacklevel=2,
)
if save_format == "keras":
# If file exists and should not be overwritten.
try:
exists = os.path.exists(filepath)
except TypeError:
exists = False
if exists and not overwrite:
proceed = io_utils.ask_to_proceed_with_overwrite(filepath)
if not proceed:
return
if kwargs:
raise ValueError(
"The following argument(s) are not supported "
f"with the native TF-Keras format: {list(kwargs.keys())}"
)
saving_lib.save_model(model, filepath)
else:
# Legacy case
return legacy_sm_saving_lib.save_model(
model,
filepath,
overwrite=overwrite,
save_format=save_format,
**kwargs,
)
@keras_export("keras.saving.load_model", "keras.models.load_model")
def load_model(
filepath, custom_objects=None, compile=True, safe_mode=True, **kwargs
):
"""Loads a model saved via `model.save()`.
Args:
filepath: `str` or `pathlib.Path` object, path to the saved model file.
custom_objects: Optional dictionary mapping names
(strings) to custom classes or functions to be
considered during deserialization.
compile: Boolean, whether to compile the model after loading.
safe_mode: Boolean, whether to disallow unsafe `lambda` deserialization.
When `safe_mode=False`, loading an object has the potential to
trigger arbitrary code execution. This argument is only
applicable to the TF-Keras v3 model format. Defaults to True.
SavedModel format arguments:
options: Only applies to SavedModel format.
Optional `tf.saved_model.LoadOptions` object that specifies
SavedModel loading options.
Returns:
A TF-Keras model instance. If the original model was compiled,
and the argument `compile=True` is set, then the returned model
will be compiled. Otherwise, the model will be left uncompiled.
Example:
```python
model = tf.keras.Sequential([
tf.keras.layers.Dense(5, input_shape=(3,)),
tf.keras.layers.Softmax()])
model.save("model.keras")
loaded_model = tf.keras.saving.load_model("model.keras")
x = tf.random.uniform((10, 3))
assert np.allclose(model.predict(x), loaded_model.predict(x))
```
Note that the model variables may have different name values
(`var.name` property, e.g. `"dense_1/kernel:0"`) after being reloaded.
It is recommended that you use layer attributes to
access specific variables, e.g. `model.get_layer("dense_1").kernel`.
"""
# Supports GCS URIs by copying data to temporary file
save_format = get_save_format(filepath, save_format=None)
gs_filepath, filepath = _support_gcs_uri(filepath, save_format, is_oss)
if gs_filepath is not None:
tf.io.gfile.copy(gs_filepath, filepath, overwrite=True)
is_keras_zip = str(filepath).endswith(".keras") and zipfile.is_zipfile(
filepath
)
# Support for remote zip files
if (
saving_lib.is_remote_path(filepath)
and not tf.io.gfile.isdir(filepath)
and not is_keras_zip
):
local_path = os.path.join(
saving_lib.get_temp_dir(), os.path.basename(filepath)
)
# Copy from remote to temporary local directory
tf.io.gfile.copy(filepath, local_path, overwrite=True)
# Switch filepath to local zipfile for loading model
if zipfile.is_zipfile(local_path):
filepath = local_path
is_keras_zip = True
if is_keras_zip:
if kwargs:
raise ValueError(
"The following argument(s) are not supported "
f"with the native TF-Keras format: {list(kwargs.keys())}"
)
return saving_lib.load_model(
filepath,
custom_objects=custom_objects,
compile=compile,
safe_mode=safe_mode,
)
# Legacy case.
return legacy_sm_saving_lib.load_model(
filepath, custom_objects=custom_objects, compile=compile, **kwargs
)
def save_weights(model, filepath, overwrite=True, **kwargs):
# Supports GCS URIs through bigstore via a temporary file
save_format = get_save_format(filepath, save_format=None)
gs_filepath, filepath = _support_gcs_uri(filepath, save_format, is_oss)
if str(filepath).endswith(".weights.h5"):
# If file exists and should not be overwritten.
try:
exists = os.path.exists(filepath)
except TypeError:
exists = False
if exists and not overwrite:
proceed = io_utils.ask_to_proceed_with_overwrite(filepath)
if not proceed:
return
saving_lib.save_weights_only(model, filepath)
else:
legacy_sm_saving_lib.save_weights(
model, filepath, overwrite=overwrite, **kwargs
)
def load_weights(model, filepath, skip_mismatch=False, **kwargs):
# Supports GCS URIs by copying data to temporary file
save_format = get_save_format(filepath, save_format=None)
gs_filepath, filepath = _support_gcs_uri(filepath, save_format, is_oss)
if gs_filepath is not None:
tf.io.gfile.copy(gs_filepath, filepath, overwrite=True)
if str(filepath).endswith(".keras") and zipfile.is_zipfile(filepath):
saving_lib.load_weights_only(
model, filepath, skip_mismatch=skip_mismatch
)
elif str(filepath).endswith(".weights.h5"):
saving_lib.load_weights_only(
model, filepath, skip_mismatch=skip_mismatch
)
else:
return legacy_sm_saving_lib.load_weights(
model, filepath, skip_mismatch=skip_mismatch, **kwargs
)
def get_save_format(filepath, save_format):
if save_format:
if save_format == "keras_v3":
return "keras"
if save_format == "keras":
if saving_lib.saving_v3_enabled():
return "keras"
else:
return "h5"
if save_format in ("h5", "hdf5"):
return "h5"
if save_format in ("tf", "tensorflow"):
return "tf"
raise ValueError(
"Unknown `save_format` argument. Expected one of "
"'keras', 'tf', or 'h5'. "
f"Received: save_format={save_format}"
)
# No save format specified: infer from filepath.
if str(filepath).endswith(".keras"):
if saving_lib.saving_v3_enabled():
return "keras"
else:
return "h5"
if str(filepath).endswith((".h5", ".hdf5")):
return "h5"
if h5py is not None and isinstance(filepath, h5py.File):
return "h5"
# No recognizable file format: default to TF in TF2 and h5 in TF1.
if tf.__internal__.tf2.enabled():
return "tf"
else:
return "h5"
| tf-keras/tf_keras/saving/saving_api.py/0 | {
"file_path": "tf-keras/tf_keras/saving/saving_api.py",
"repo_id": "tf-keras",
"token_count": 5281
} | 201 |
# Copyright 2019 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 convert_to_constants.py."""
import os
import numpy as np
import tensorflow.compat.v2 as tf
import tf_keras as keras
from tf_keras.testing_infra import test_utils
# isort: off
from tensorflow.python.framework import convert_to_constants
from tensorflow.python.saved_model.load import load
from tensorflow.python.saved_model.save import save
class VariablesToConstantsTest(tf.test.TestCase):
def _freezeModel(self, model):
"""Freezes the model.
Args:
model: Function.
Returns:
root: AutoTrackable object with original ConcreteFunction.
output_func: frozen ConcreteFunction.
"""
root = tf.Module()
root.f = model
input_func = root.f.get_concrete_function()
output_func = convert_to_constants.convert_variables_to_constants_v2(
input_func, lower_control_flow=False
)
return root, output_func
def _hasStatefulPartitionedCallOp(self, graph_def):
"""Determines if a StatefulPartitionedCall op exists in the graph."""
for node in graph_def.node:
if node.op == "StatefulPartitionedCall":
return True
return False
def _getNumVariables(self, graph_def):
"""Returns the number of ReadVariableOp in the graph."""
return sum(node.op == "ReadVariableOp" for node in graph_def.node)
def _testConvertedFunction(
self, obj, func, converted_concrete_func, input_data
):
# Ensure the converted graph has no variables and no function calls.
constant_graph_def = converted_concrete_func.graph.as_graph_def()
self.assertEqual(0, self._getNumVariables(constant_graph_def))
self.assertFalse(self._hasStatefulPartitionedCallOp(constant_graph_def))
# Check that the converted ConcreteFunction produces the same result as
# the original Function.
expected_value = tf.nest.flatten(func(**input_data))
actual_value = tf.nest.flatten(converted_concrete_func(**input_data))
for expected, actual in zip(expected_value, actual_value):
np.testing.assert_almost_equal(expected.numpy(), actual.numpy())
# Ensure the shape is retained.
for tensor in converted_concrete_func.inputs:
actual_shape = input_data[tensor.name.split(":")[0]].shape
self.assertEqual(tensor.shape, actual_shape)
# Save the converted ConcreteFunction as a signature.
save_dir = os.path.join(self.get_temp_dir(), "frozen_saved_model")
root = tf.Module()
root.f = converted_concrete_func
save(root, save_dir, {"mykey": converted_concrete_func})
# Load it back and make sure it works.
loaded_obj = load(save_dir)
actual_value = tf.nest.flatten(
loaded_obj.signatures["mykey"](**input_data)
)
for expected, actual in zip(expected_value, actual_value):
np.testing.assert_almost_equal(expected.numpy(), actual.numpy())
@test_utils.run_v2_only
def testKerasModel(self):
"""Test a basic TF-Keras model with Variables."""
input_data = {"x": tf.constant(1.0, shape=[1, 1])}
# Create a simple TF-Keras model.
x = [-1, 0, 1, 2, 3, 4]
y = [-3, -1, 1, 3, 5, 7]
model = keras.models.Sequential(
[keras.layers.Dense(units=1, input_shape=[1])]
)
model.compile(optimizer="sgd", loss="mean_squared_error")
model.fit(x, y, epochs=1)
@tf.function(
input_signature=[tf.TensorSpec(shape=[1, 1], dtype=tf.float32)]
)
def to_save(x):
return model(x)
root, output_func = self._freezeModel(to_save)
self._testConvertedFunction(root, root.f, output_func, input_data)
@test_utils.run_v2_only
def testKerasLSTM(self):
"""Test a TF-Keras LSTM containing dynamic_rnn ops."""
input_data = {
"x": tf.constant(
np.array(
np.random.random_sample((10, 10, 10)), dtype=np.float32
)
)
}
model = keras.models.Sequential(
[keras.layers.LSTM(units=10, input_shape=(10, 10))]
)
@tf.function(
input_signature=[
tf.TensorSpec(shape=[10, 10, 10], dtype=tf.float32)
]
)
def to_save(x):
return model(x)
root, output_func = self._freezeModel(to_save)
self._testConvertedFunction(root, root.f, output_func, input_data)
@test_utils.run_v2_only
def testEmbeddings(self):
"""Test model with embeddings."""
input_data = {
"x": tf.constant(
np.array(np.random.random_sample((20)), dtype=np.int32)
)
}
class EmbeddingModel(keras.Model):
def __init__(self):
super().__init__()
self.shared_weights = self.add_weight(
"weights",
shape=(2000, 300),
dtype=tf.float32,
initializer=tf.compat.v1.random_normal_initializer(
mean=0.0, stddev=300 ** (-0.5)
),
)
@tf.function(
input_signature=[tf.TensorSpec(shape=(20), dtype=tf.int32)]
)
def func(self, x):
return tf.gather(self.shared_weights, x)
model = EmbeddingModel()
root, output_func = self._freezeModel(model.func)
self._testConvertedFunction(root, root.f, output_func, input_data)
if __name__ == "__main__":
tf.test.main()
| tf-keras/tf_keras/tests/convert_to_constants_test.py/0 | {
"file_path": "tf-keras/tf_keras/tests/convert_to_constants_test.py",
"repo_id": "tf-keras",
"token_count": 2838
} | 202 |
# Copyright 2018 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 serialization functions."""
import json
import tensorflow.compat.v2 as tf
from tf_keras.engine import input_layer
from tf_keras.engine import sequential
from tf_keras.engine import training
from tf_keras.layers import core
from tf_keras.saving.legacy.saved_model import json_utils
from tf_keras.testing_infra import test_combinations
@test_combinations.generate(test_combinations.combine(mode=["graph", "eager"]))
class SerializationTests(test_combinations.TestCase):
def test_serialize_dense(self):
dense = core.Dense(3)
dense(tf.constant([[4.0]]))
round_trip = json.loads(
json.dumps(dense, default=json_utils.get_json_type)
)
self.assertEqual(3, round_trip["config"]["units"])
def test_serialize_sequential(self):
model = sequential.Sequential()
model.add(core.Dense(4))
model.add(core.Dense(5))
model(tf.constant([[1.0]]))
sequential_round_trip = json.loads(
json.dumps(model, default=json_utils.get_json_type)
)
self.assertEqual(
# Note that `config['layers'][0]` will be an InputLayer in V2
# (but not in V1)
5,
sequential_round_trip["config"]["layers"][-1]["config"]["units"],
)
def test_serialize_model(self):
x = input_layer.Input(shape=[3])
y = core.Dense(10)(x)
model = training.Model(x, y)
model(tf.constant([[1.0, 1.0, 1.0]]))
model_round_trip = json.loads(
json.dumps(model, default=json_utils.get_json_type)
)
self.assertEqual(
10, model_round_trip["config"]["layers"][1]["config"]["units"]
)
if __name__ == "__main__":
tf.test.main()
| tf-keras/tf_keras/tests/serialization_util_test.py/0 | {
"file_path": "tf-keras/tf_keras/tests/serialization_util_test.py",
"repo_id": "tf-keras",
"token_count": 963
} | 203 |
# Copyright 2016 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 TF-Keras generic Python utils."""
import os
import sys
from functools import partial
import numpy as np
import tensorflow.compat.v2 as tf
import tf_keras as keras
from tf_keras.saving import serialization_lib
from tf_keras.saving.legacy import serialization
from tf_keras.testing_infra import test_utils
from tf_keras.utils import generic_utils
from tf_keras.utils import io_utils
class SnakeCaseTest(tf.test.TestCase):
def test_snake_case(self):
self.assertEqual(generic_utils.to_snake_case("SomeClass"), "some_class")
self.assertEqual(generic_utils.to_snake_case("Conv2D"), "conv2d")
self.assertEqual(
generic_utils.to_snake_case("ConvLSTM2D"), "conv_lstm2d"
)
class HasArgTest(tf.test.TestCase):
def test_has_arg(self):
def f_x(x):
return x
def f_x_args(x, *args):
_ = args
return x
def f_x_kwargs(x, **kwargs):
_ = kwargs
return x
def f(a, b, c):
return a + b + c
partial_f = partial(f, b=1)
self.assertTrue(
keras.utils.generic_utils.has_arg(f_x, "x", accept_all=False)
)
self.assertFalse(
keras.utils.generic_utils.has_arg(f_x, "y", accept_all=False)
)
self.assertTrue(
keras.utils.generic_utils.has_arg(f_x_args, "x", accept_all=False)
)
self.assertFalse(
keras.utils.generic_utils.has_arg(f_x_args, "y", accept_all=False)
)
self.assertTrue(
keras.utils.generic_utils.has_arg(f_x_kwargs, "x", accept_all=False)
)
self.assertFalse(
keras.utils.generic_utils.has_arg(f_x_kwargs, "y", accept_all=False)
)
self.assertTrue(
keras.utils.generic_utils.has_arg(f_x_kwargs, "y", accept_all=True)
)
self.assertTrue(
keras.utils.generic_utils.has_arg(partial_f, "c", accept_all=True)
)
class SerializeKerasObjectTest(tf.test.TestCase):
def test_serialize_none(self):
serialized = serialization_lib.serialize_keras_object(None)
self.assertEqual(serialized, None)
deserialized = serialization_lib.deserialize_keras_object(serialized)
self.assertEqual(deserialized, None)
def test_serializable_object(self):
class SerializableInt(int):
"""A serializable object to pass out of a test layer's config."""
def __new__(cls, value):
return int.__new__(cls, value)
def get_config(self):
return {"value": int(self)}
@classmethod
def from_config(cls, config):
return cls(**config)
layer = keras.layers.Dense(
SerializableInt(3),
activation="relu",
kernel_initializer="ones",
bias_regularizer="l2",
)
config = keras.layers.serialize(layer)
new_layer = keras.layers.deserialize(
config, custom_objects={"SerializableInt": SerializableInt}
)
self.assertEqual(new_layer.activation, keras.activations.relu)
self.assertEqual(
new_layer.bias_regularizer.__class__, keras.regularizers.L2
)
self.assertEqual(new_layer.units.__class__, SerializableInt)
self.assertEqual(new_layer.units, 3)
def test_nested_serializable_object(self):
class SerializableInt(int):
"""A serializable object to pass out of a test layer's config."""
def __new__(cls, value):
return int.__new__(cls, value)
def get_config(self):
return {"value": int(self)}
@classmethod
def from_config(cls, config):
return cls(**config)
class SerializableNestedInt(int):
"""A serializable object containing another serializable object."""
def __new__(cls, value, int_obj):
obj = int.__new__(cls, value)
obj.int_obj = int_obj
return obj
def get_config(self):
return {"value": int(self), "int_obj": self.int_obj}
@classmethod
def from_config(cls, config):
return cls(**config)
nested_int = SerializableInt(4)
layer = keras.layers.Dense(
SerializableNestedInt(3, nested_int),
name="SerializableNestedInt",
activation="relu",
kernel_initializer="ones",
bias_regularizer="l2",
)
config = keras.layers.serialize(layer)
new_layer = keras.layers.deserialize(
config,
custom_objects={
"SerializableInt": SerializableInt,
"SerializableNestedInt": SerializableNestedInt,
},
)
# Make sure the string field doesn't get convert to custom object, even
# they have same value.
self.assertEqual(new_layer.name, "SerializableNestedInt")
self.assertEqual(new_layer.activation, keras.activations.relu)
self.assertEqual(
new_layer.bias_regularizer.__class__, keras.regularizers.L2
)
self.assertEqual(new_layer.units.__class__, SerializableNestedInt)
self.assertEqual(new_layer.units, 3)
self.assertEqual(new_layer.units.int_obj.__class__, SerializableInt)
self.assertEqual(new_layer.units.int_obj, 4)
def test_nested_serializable_fn(self):
def serializable_fn(x):
"""A serializable function to pass out of a test layer's config."""
return x
class SerializableNestedInt(int):
"""A serializable object containing a serializable function."""
def __new__(cls, value, fn):
obj = int.__new__(cls, value)
obj.fn = fn
return obj
def get_config(self):
return {"value": int(self), "fn": self.fn}
@classmethod
def from_config(cls, config):
return cls(**config)
layer = keras.layers.Dense(
SerializableNestedInt(3, serializable_fn),
activation="relu",
kernel_initializer="ones",
bias_regularizer="l2",
)
config = keras.layers.serialize(layer)
new_layer = keras.layers.deserialize(
config,
custom_objects={
"serializable_fn": serializable_fn,
"SerializableNestedInt": SerializableNestedInt,
},
)
self.assertEqual(new_layer.activation, keras.activations.relu)
self.assertIsInstance(new_layer.bias_regularizer, keras.regularizers.L2)
self.assertIsInstance(new_layer.units, SerializableNestedInt)
self.assertEqual(new_layer.units, 3)
self.assertIs(new_layer.units.fn, serializable_fn)
def test_serialize_type_object_initializer(self):
layer = keras.layers.Dense(
1,
kernel_initializer=keras.initializers.ones,
bias_initializer=keras.initializers.zeros,
)
config = keras.layers.serialize(layer)
self.assertEqual(
config["config"]["bias_initializer"]["class_name"], "Zeros"
)
self.assertEqual(
config["config"]["kernel_initializer"]["class_name"], "Ones"
)
def test_serializable_with_old_config(self):
# model config generated by tf-1.2.1
old_model_config = {
"class_name": "Sequential",
"config": [
{
"class_name": "Dense",
"config": {
"name": "dense_1",
"trainable": True,
"batch_input_shape": [None, 784],
"dtype": "float32",
"units": 32,
"activation": "linear",
"use_bias": True,
"kernel_initializer": {
"class_name": "Ones",
"config": {"dtype": "float32"},
},
"bias_initializer": {
"class_name": "Zeros",
"config": {"dtype": "float32"},
},
"kernel_regularizer": None,
"bias_regularizer": None,
"activity_regularizer": None,
"kernel_constraint": None,
"bias_constraint": None,
},
}
],
}
old_model = serialization_lib.deserialize_keras_object(
old_model_config, module_objects={"Sequential": keras.Sequential}
)
new_model = keras.Sequential(
[
keras.layers.Dense(
32, input_dim=784, kernel_initializer="Ones"
),
]
)
input_data = np.random.normal(2, 1, (5, 784))
output = old_model.predict(input_data)
expected_output = new_model.predict(input_data)
self.assertAllEqual(output, expected_output)
def test_deserialize_unknown_object(self):
class CustomLayer(keras.layers.Layer):
pass
layer = CustomLayer()
config = serialization_lib.serialize_keras_object(layer)
if tf.__internal__.tf2.enabled():
with self.assertRaisesRegex(
TypeError,
"Could not locate class 'CustomLayer'. Make sure custom classes", # noqa: E501
):
serialization_lib.deserialize_keras_object(config)
else:
with self.assertRaisesRegex(
ValueError, "using a `keras.utils.custom_object_scope`"
):
serialization.deserialize_keras_object(config)
restored = serialization_lib.deserialize_keras_object(
config, custom_objects={"CustomLayer": CustomLayer}
)
self.assertIsInstance(restored, CustomLayer)
class SliceArraysTest(tf.test.TestCase):
def test_slice_arrays(self):
input_a = list([1, 2, 3])
self.assertEqual(
keras.utils.generic_utils.slice_arrays(input_a, start=0),
[None, None, None],
)
self.assertEqual(
keras.utils.generic_utils.slice_arrays(input_a, stop=3),
[None, None, None],
)
self.assertEqual(
keras.utils.generic_utils.slice_arrays(input_a, start=0, stop=1),
[None, None, None],
)
# object() alone isn't compatible with WeakKeyDictionary, which we use to
# track shared configs.
class MaybeSharedObject:
pass
class CustomModelX(keras.Model):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.dense1 = keras.layers.Dense(1)
self.train_step_message = "This is my training step"
def call(self, inputs):
return self.dense1(inputs)
def train_step(self, data):
tf.print(self.train_step_message)
x, y = data
with tf.GradientTape() as tape:
y_pred = self(x)
loss = self.compiled_loss(y, y_pred)
gradients = tape.gradient(loss, self.trainable_variables)
self.optimizer.apply_gradients(zip(gradients, self.trainable_variables))
return {}
def func_that_returns_one(self):
return 1
class SharedObjectScopeTest(tf.test.TestCase):
def test_shared_object_saving_scope_single_object_doesnt_export_id(self):
with serialization.SharedObjectSavingScope() as scope:
single_object = MaybeSharedObject()
self.assertIsNone(scope.get_config(single_object))
single_object_config = scope.create_config({}, single_object)
self.assertIsNotNone(single_object_config)
self.assertNotIn(
serialization.SHARED_OBJECT_KEY, single_object_config
)
def test_shared_object_saving_scope_shared_object_exports_id(self):
with serialization.SharedObjectSavingScope() as scope:
shared_object = MaybeSharedObject()
self.assertIsNone(scope.get_config(shared_object))
scope.create_config({}, shared_object)
first_object_config = scope.get_config(shared_object)
second_object_config = scope.get_config(shared_object)
self.assertIn(serialization.SHARED_OBJECT_KEY, first_object_config)
self.assertIn(serialization.SHARED_OBJECT_KEY, second_object_config)
self.assertIs(first_object_config, second_object_config)
def test_shared_object_loading_scope_noop(self):
# Test that, without a context manager scope, adding configs will do
# nothing.
obj_id = 1
obj = MaybeSharedObject()
serialization._shared_object_loading_scope().set(obj_id, obj)
self.assertIsNone(
serialization._shared_object_loading_scope().get(obj_id)
)
def test_shared_object_loading_scope_returns_shared_obj(self):
obj_id = 1
obj = MaybeSharedObject()
with serialization.SharedObjectLoadingScope() as scope:
scope.set(obj_id, obj)
self.assertIs(scope.get(obj_id), obj)
def test_nested_shared_object_saving_scopes(self):
my_obj = MaybeSharedObject()
with serialization.SharedObjectSavingScope() as scope_1:
scope_1.create_config({}, my_obj)
with serialization.SharedObjectSavingScope() as scope_2:
# Nesting saving scopes should return the original scope and
# should not clear any objects we're tracking.
self.assertIs(scope_1, scope_2)
self.assertIsNotNone(scope_2.get_config(my_obj))
self.assertIsNotNone(scope_1.get_config(my_obj))
self.assertIsNone(serialization._shared_object_saving_scope())
def test_custom_object_scope_correct_class_saved_model(self):
temp_dir = os.path.join(self.get_temp_dir(), "my_model")
subclassed_model = CustomModelX()
subclassed_model.compile(optimizer="adam", loss="mse")
x = np.random.random((100, 32))
y = np.random.random((100, 1))
subclassed_model.fit(x, y, epochs=1)
subclassed_model.save(temp_dir, save_format="tf")
with keras.utils.custom_object_scope({"CustomModelX": CustomModelX}):
loaded_model = keras.models.load_model(temp_dir)
io_utils.enable_interactive_logging()
# `tf.print` writes to stderr.
with self.captureWritesToStream(sys.stderr) as printed:
loaded_model.fit(x, y, epochs=1)
if tf.__internal__.tf2.enabled():
# `tf.print` message is only available in stderr in TF2.
# Check that custom `train_step` is used.
self.assertRegex(printed.contents(), "This is my training step")
# Check that the custom class does get used.
self.assertIsInstance(loaded_model, CustomModelX)
# Check that the custom method is available.
self.assertEqual(loaded_model.func_that_returns_one(), 1)
@test_utils.run_v2_only
def test_custom_object_scope_correct_class_keras_v3(self):
temp_dir = os.path.join(self.get_temp_dir(), "my_model.keras")
subclassed_model = CustomModelX()
subclassed_model.compile(optimizer="adam", loss="mse")
x = np.random.random((100, 32))
y = np.random.random((100, 1))
subclassed_model.fit(x, y, epochs=1)
subclassed_model.save(temp_dir, save_format="keras_v3")
with keras.utils.custom_object_scope({"CustomModelX": CustomModelX}):
loaded_model = keras.models.load_model(temp_dir)
io_utils.enable_interactive_logging()
# `tf.print` writes to stderr.
with self.captureWritesToStream(sys.stderr) as printed:
loaded_model.fit(x, y, epochs=1)
if tf.__internal__.tf2.enabled():
# `tf.print` message is only available in stderr in TF2.
# Check that custom `train_step` is used.
self.assertRegex(printed.contents(), "This is my training step")
# Check that the custom class does get used.
self.assertIsInstance(loaded_model, CustomModelX)
# Check that the custom method is available.
self.assertEqual(loaded_model.func_that_returns_one(), 1)
if __name__ == "__main__":
tf.test.main()
| tf-keras/tf_keras/utils/generic_utils_test.py/0 | {
"file_path": "tf-keras/tf_keras/utils/generic_utils_test.py",
"repo_id": "tf-keras",
"token_count": 8235
} | 204 |
# Copyright 2015 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.
# ==============================================================================
"""Utils related to keras metrics."""
import functools
import weakref
from enum import Enum
import numpy as np
import tensorflow.compat.v2 as tf
from tf_keras import backend
from tf_keras.utils import losses_utils
from tf_keras.utils import tf_utils
from tf_keras.utils.generic_utils import to_list
NEG_INF = -1e10
class Reduction(Enum):
"""Types of metrics reduction.
Contains the following values:
* `SUM`: Scalar sum of weighted values.
* `SUM_OVER_BATCH_SIZE`: Scalar sum of weighted values divided by
number of elements.
* `WEIGHTED_MEAN`: Scalar sum of weighted values divided by sum of weights.
"""
SUM = "sum"
SUM_OVER_BATCH_SIZE = "sum_over_batch_size"
WEIGHTED_MEAN = "weighted_mean"
def update_state_wrapper(update_state_fn):
"""Decorator to wrap metric `update_state()` with `add_update()`.
Args:
update_state_fn: function that accumulates metric statistics.
Returns:
Decorated function that wraps `update_state_fn()` with `add_update()`.
"""
def decorated(metric_obj, *args, **kwargs):
"""Decorated function with `add_update()`."""
strategy = tf.distribute.get_strategy()
for weight in metric_obj.weights:
if (
backend.is_tpu_strategy(strategy)
and not strategy.extended.variable_created_in_scope(weight)
and not tf.distribute.in_cross_replica_context()
):
raise ValueError(
"Trying to run metric.update_state in replica context when "
"the metric was not created in TPUStrategy scope. "
"Make sure the keras Metric is created in TPUstrategy "
"scope. "
)
with tf_utils.graph_context_for_symbolic_tensors(*args, **kwargs):
result = update_state_fn(*args, **kwargs)
if not tf.executing_eagerly():
result = tf.compat.v1.get_default_graph().get_operations()[-1]
metric_obj.add_update(result)
return result
return tf.__internal__.decorator.make_decorator(update_state_fn, decorated)
def result_wrapper(result_fn):
"""Decorator to wrap metric `result()` function in `merge_call()`.
Result computation is an idempotent operation that simply calculates the
metric value using the state variables.
If metric state variables are distributed across replicas/devices and
`result()` is requested from the context of one device - This function wraps
`result()` in a distribution strategy `merge_call()`. With this,
the metric state variables will be aggregated across devices.
Args:
result_fn: function that computes the metric result.
Returns:
Decorated function that wraps `result_fn()` in distribution strategy
`merge_call()`.
"""
def decorated(metric_obj, *args):
"""Decorated function with merge_call."""
replica_context = tf.distribute.get_replica_context()
# The purpose of using `merge_call` to call `result()` is to trigger
# cross replica aggregation of metric state variables
# (SyncOnReadVariable). After we introduced
# `variable_sync_on_read_context`, in principle there is no need to use
# `merge_call` here. However the branch still exists because:
#
# 1. TF-Keras V1 training code sometimes assumes `result_t` is the same
# tensor across replicas (achieved by `merge_call`). With
# `variable_sync_on_read_context` each replica gets their own tensors
# residing on replica's device, thus breaking the assumption.
# 2. TF-Keras c/fit creates a tf.function (a.k.a, train_function) that
# returns the metric values of the first replica. With
# `variable_sync_on_read_context` since each replica gets their own
# tensors, the metric result tensors on the non-first replicas are
# not in the return value of train_function, making TF graph
# optimizer prune the branch that computes and aggregates those
# metric results. As a result, if NCCL is used to do the aggregation,
# the program will hang because NCCL ops are only launched on the
# non-pruned first replica.
#
# We condition on strategy_supports_no_merge_call() since we know if it
# is True, the program uses `jit_compile` to compile replica fn, meaning
# it is not V1 training (hence #1 is okay), and no pruning will happen
# as compiled functions are not inlined (hence #2 is okay).
if (
replica_context is None
or tf.__internal__.distribute.strategy_supports_no_merge_call()
):
with tf.__internal__.distribute.variable_sync_on_read_context():
raw_result = result_fn(*args)
# Results need to be wrapped in a `tf.identity` op to ensure
# correct execution order.
if isinstance(raw_result, (tf.Tensor, tf.Variable, float, int)):
result_t = tf.identity(raw_result)
elif isinstance(raw_result, dict):
result_t = tf.nest.map_structure(tf.identity, raw_result)
else:
try:
result_t = tf.identity(raw_result)
except (ValueError, TypeError):
raise RuntimeError(
"The output of `metric.result()` can only be a "
"single Tensor/Variable, or a dict of "
"Tensors/Variables. "
f"For metric {metric_obj.name}, "
f"got result {raw_result}."
)
else:
# TODO(psv): Test distribution of metrics using different
# distribution strategies.
# Creating a wrapper for merge_fn. merge_call invokes the given
# merge_fn with distribution object as the first parameter. We
# create a wrapper here so that the result function need not have
# that parameter.
def merge_fn_wrapper(distribution, merge_fn, *args):
# We will get `PerReplica` merge function. Taking the first one
# as all are identical copies of the function that we had passed
# below.
result = distribution.experimental_local_results(merge_fn)[0](
*args
)
# Wrapping result in identity so that control dependency between
# update_op from `update_state` and result works in case result
# returns a tensor.
return tf.nest.map_structure(tf.identity, result)
# Wrapping result in merge_call. merge_call is used when we want to
# leave replica mode and compute a value in cross replica mode.
result_t = replica_context.merge_call(
merge_fn_wrapper, args=(result_fn,) + args
)
# We are saving the result op here to be used in train/test execution
# functions. This basically gives the result op that was generated with
# a control dep to the updates for these workflows.
metric_obj._call_result = result_t
return result_t
return tf.__internal__.decorator.make_decorator(result_fn, decorated)
def weakmethod(method):
"""Creates a weak reference to the bound method."""
cls = method.im_class
func = method.im_func
instance_ref = weakref.ref(method.im_self)
@functools.wraps(method)
def inner(*args, **kwargs):
return func.__get__(instance_ref(), cls)(*args, **kwargs)
del method
return inner
def assert_thresholds_range(thresholds):
if thresholds is not None:
invalid_thresholds = [
t for t in thresholds if t is None or t < 0 or t > 1
]
if invalid_thresholds:
raise ValueError(
"Threshold values must be in [0, 1]. "
f"Received: {invalid_thresholds}"
)
def parse_init_thresholds(thresholds, default_threshold=0.5):
if thresholds is not None:
assert_thresholds_range(to_list(thresholds))
thresholds = to_list(
default_threshold if thresholds is None else thresholds
)
return thresholds
class ConfusionMatrix(Enum):
TRUE_POSITIVES = "tp"
FALSE_POSITIVES = "fp"
TRUE_NEGATIVES = "tn"
FALSE_NEGATIVES = "fn"
class AUCCurve(Enum):
"""Type of AUC Curve (ROC or PR)."""
ROC = "ROC"
PR = "PR"
@staticmethod
def from_str(key):
if key in ("pr", "PR"):
return AUCCurve.PR
elif key in ("roc", "ROC"):
return AUCCurve.ROC
else:
raise ValueError(
f'Invalid AUC curve value: "{key}". '
'Expected values are ["PR", "ROC"]'
)
class AUCSummationMethod(Enum):
"""Type of AUC summation method.
https://en.wikipedia.org/wiki/Riemann_sum)
Contains the following values:
* 'interpolation': Applies mid-point summation scheme for `ROC` curve. For
`PR` curve, interpolates (true/false) positives but not the ratio that is
precision (see Davis & Goadrich 2006 for details).
* 'minoring': Applies left summation for increasing intervals and right
summation for decreasing intervals.
* 'majoring': Applies right summation for increasing intervals and left
summation for decreasing intervals.
"""
INTERPOLATION = "interpolation"
MAJORING = "majoring"
MINORING = "minoring"
@staticmethod
def from_str(key):
if key in ("interpolation", "Interpolation"):
return AUCSummationMethod.INTERPOLATION
elif key in ("majoring", "Majoring"):
return AUCSummationMethod.MAJORING
elif key in ("minoring", "Minoring"):
return AUCSummationMethod.MINORING
else:
raise ValueError(
f'Invalid AUC summation method value: "{key}". '
'Expected values are ["interpolation", "majoring", "minoring"]'
)
def _update_confusion_matrix_variables_optimized(
variables_to_update,
y_true,
y_pred,
thresholds,
multi_label=False,
sample_weights=None,
label_weights=None,
thresholds_with_epsilon=False,
):
"""Update confusion matrix variables with memory efficient alternative.
Note that the thresholds need to be evenly distributed within the list, eg,
the diff between consecutive elements are the same.
To compute TP/FP/TN/FN, we are measuring a binary classifier
C(t) = (predictions >= t)
at each threshold 't'. So we have
TP(t) = sum( C(t) * true_labels )
FP(t) = sum( C(t) * false_labels )
But, computing C(t) requires computation for each t. To make it fast,
observe that C(t) is a cumulative integral, and so if we have
thresholds = [t_0, ..., t_{n-1}]; t_0 < ... < t_{n-1}
where n = num_thresholds, and if we can compute the bucket function
B(i) = Sum( (predictions == t), t_i <= t < t{i+1} )
then we get
C(t_i) = sum( B(j), j >= i )
which is the reversed cumulative sum in tf.cumsum().
We can compute B(i) efficiently by taking advantage of the fact that
our thresholds are evenly distributed, in that
width = 1.0 / (num_thresholds - 1)
thresholds = [0.0, 1*width, 2*width, 3*width, ..., 1.0]
Given a prediction value p, we can map it to its bucket by
bucket_index(p) = floor( p * (num_thresholds - 1) )
so we can use tf.math.unsorted_segment_sum() to update the buckets in one
pass.
Consider following example:
y_true = [0, 0, 1, 1]
y_pred = [0.1, 0.5, 0.3, 0.9]
thresholds = [0.0, 0.5, 1.0]
num_buckets = 2 # [0.0, 1.0], (1.0, 2.0]
bucket_index(y_pred) = tf.math.floor(y_pred * num_buckets)
= tf.math.floor([0.2, 1.0, 0.6, 1.8])
= [0, 0, 0, 1]
# The meaning of this bucket is that if any of the label is true,
# then 1 will be added to the corresponding bucket with the index.
# Eg, if the label for 0.2 is true, then 1 will be added to bucket 0. If the
# label for 1.8 is true, then 1 will be added to bucket 1.
#
# Note the second item "1.0" is floored to 0, since the value need to be
# strictly larger than the bucket lower bound.
# In the implementation, we use tf.math.ceil() - 1 to achieve this.
tp_bucket_value = tf.math.unsorted_segment_sum(true_labels, bucket_indices,
num_segments=num_thresholds)
= [1, 1, 0]
# For [1, 1, 0] here, it means there is 1 true value contributed by bucket
# 0, and 1 value contributed by bucket 1. When we aggregate them to
# together, the result become [a + b + c, b + c, c], since large thresholds
# will always contribute to the value for smaller thresholds.
true_positive = tf.math.cumsum(tp_bucket_value, reverse=True)
= [2, 1, 0]
This implementation exhibits a run time and space complexity of O(T + N),
where T is the number of thresholds and N is the size of predictions.
Metrics that rely on standard implementation instead exhibit a complexity of
O(T * N).
Args:
variables_to_update: Dictionary with 'tp', 'fn', 'tn', 'fp' as valid keys
and corresponding variables to update as values.
y_true: A floating point `Tensor` whose shape matches `y_pred`. Will be
cast to `bool`.
y_pred: A floating point `Tensor` of arbitrary shape and whose values are
in the range `[0, 1]`.
thresholds: A sorted floating point `Tensor` with value in `[0, 1]`.
It need to be evenly distributed (the diff between each element need to
be the same).
multi_label: Optional boolean indicating whether multidimensional
prediction/labels should be treated as multilabel responses, or
flattened into a single label. When True, the valus of
`variables_to_update` must have a second dimension equal to the number
of labels in y_true and y_pred, and those tensors must not be
RaggedTensors.
sample_weights: Optional `Tensor` whose rank is either 0, or the same rank
as `y_true`, and must be broadcastable to `y_true` (i.e., all dimensions
must be either `1`, or the same as the corresponding `y_true`
dimension).
label_weights: Optional tensor of non-negative weights for multilabel
data. The weights are applied when calculating TP, FP, FN, and TN
without explicit multilabel handling (i.e. when the data is to be
flattened).
thresholds_with_epsilon: Optional boolean indicating whether the leading
and tailing thresholds has any epsilon added for floating point
imprecisions. It will change how we handle the leading and tailing
bucket.
Returns:
Update op.
"""
num_thresholds = thresholds.shape.as_list()[0]
if sample_weights is None:
sample_weights = 1.0
else:
sample_weights = tf.__internal__.ops.broadcast_weights(
tf.cast(sample_weights, dtype=y_pred.dtype), y_pred
)
if not multi_label:
sample_weights = tf.reshape(sample_weights, [-1])
if label_weights is None:
label_weights = 1.0
else:
label_weights = tf.expand_dims(label_weights, 0)
label_weights = tf.__internal__.ops.broadcast_weights(
label_weights, y_pred
)
if not multi_label:
label_weights = tf.reshape(label_weights, [-1])
weights = tf.cast(tf.multiply(sample_weights, label_weights), y_true.dtype)
# We shouldn't need this, but in case there are predict value that is out of
# the range of [0.0, 1.0]
y_pred = tf.clip_by_value(y_pred, clip_value_min=0.0, clip_value_max=1.0)
y_true = tf.cast(tf.cast(y_true, tf.bool), y_true.dtype)
if not multi_label:
y_true = tf.reshape(y_true, [-1])
y_pred = tf.reshape(y_pred, [-1])
true_labels = tf.multiply(y_true, weights)
false_labels = tf.multiply((1.0 - y_true), weights)
# Compute the bucket indices for each prediction value.
# Since the predict value has to be strictly greater than the thresholds,
# eg, buckets like [0, 0.5], (0.5, 1], and 0.5 belongs to first bucket.
# We have to use math.ceil(val) - 1 for the bucket.
bucket_indices = tf.math.ceil(y_pred * (num_thresholds - 1)) - 1
if thresholds_with_epsilon:
# In this case, the first bucket should actually take into account since
# the any prediction between [0.0, 1.0] should be larger than the first
# threshold. We change the bucket value from -1 to 0.
bucket_indices = tf.nn.relu(bucket_indices)
bucket_indices = tf.cast(bucket_indices, tf.int32)
if multi_label:
# We need to run bucket segment sum for each of the label class. In the
# multi_label case, the rank of the label is 2. We first transpose it so
# that the label dim becomes the first and we can parallel run though
# them.
true_labels = tf.transpose(true_labels)
false_labels = tf.transpose(false_labels)
bucket_indices = tf.transpose(bucket_indices)
def gather_bucket(label_and_bucket_index):
label, bucket_index = (
label_and_bucket_index[0],
label_and_bucket_index[1],
)
return tf.math.unsorted_segment_sum(
data=label,
segment_ids=bucket_index,
num_segments=num_thresholds,
)
tp_bucket_v = tf.vectorized_map(
gather_bucket, (true_labels, bucket_indices), warn=False
)
fp_bucket_v = tf.vectorized_map(
gather_bucket, (false_labels, bucket_indices), warn=False
)
tp = tf.transpose(tf.cumsum(tp_bucket_v, reverse=True, axis=1))
fp = tf.transpose(tf.cumsum(fp_bucket_v, reverse=True, axis=1))
else:
tp_bucket_v = tf.math.unsorted_segment_sum(
data=true_labels,
segment_ids=bucket_indices,
num_segments=num_thresholds,
)
fp_bucket_v = tf.math.unsorted_segment_sum(
data=false_labels,
segment_ids=bucket_indices,
num_segments=num_thresholds,
)
tp = tf.cumsum(tp_bucket_v, reverse=True)
fp = tf.cumsum(fp_bucket_v, reverse=True)
# fn = sum(true_labels) - tp
# tn = sum(false_labels) - fp
if (
ConfusionMatrix.TRUE_NEGATIVES in variables_to_update
or ConfusionMatrix.FALSE_NEGATIVES in variables_to_update
):
if multi_label:
total_true_labels = tf.reduce_sum(true_labels, axis=1)
total_false_labels = tf.reduce_sum(false_labels, axis=1)
else:
total_true_labels = tf.reduce_sum(true_labels)
total_false_labels = tf.reduce_sum(false_labels)
update_ops = []
if ConfusionMatrix.TRUE_POSITIVES in variables_to_update:
variable = variables_to_update[ConfusionMatrix.TRUE_POSITIVES]
update_ops.append(variable.assign_add(tp))
if ConfusionMatrix.FALSE_POSITIVES in variables_to_update:
variable = variables_to_update[ConfusionMatrix.FALSE_POSITIVES]
update_ops.append(variable.assign_add(fp))
if ConfusionMatrix.TRUE_NEGATIVES in variables_to_update:
variable = variables_to_update[ConfusionMatrix.TRUE_NEGATIVES]
tn = total_false_labels - fp
update_ops.append(variable.assign_add(tn))
if ConfusionMatrix.FALSE_NEGATIVES in variables_to_update:
variable = variables_to_update[ConfusionMatrix.FALSE_NEGATIVES]
fn = total_true_labels - tp
update_ops.append(variable.assign_add(fn))
return tf.group(update_ops)
def is_evenly_distributed_thresholds(thresholds):
"""Check if the thresholds list is evenly distributed.
We could leverage evenly distributed thresholds to use less memory when
calculate metrcis like AUC where each individual threshold need to be
evaluated.
Args:
thresholds: A python list or tuple, or 1D numpy array whose value is
ranged in [0, 1].
Returns:
boolean, whether the values in the inputs are evenly distributed.
"""
# Check the list value and see if it is evenly distributed.
num_thresholds = len(thresholds)
if num_thresholds < 3:
return False
even_thresholds = np.arange(num_thresholds, dtype=np.float32) / (
num_thresholds - 1
)
return np.allclose(thresholds, even_thresholds, atol=backend.epsilon())
def update_confusion_matrix_variables(
variables_to_update,
y_true,
y_pred,
thresholds,
top_k=None,
class_id=None,
sample_weight=None,
multi_label=False,
label_weights=None,
thresholds_distributed_evenly=False,
):
"""Returns op to update the given confusion matrix variables.
For every pair of values in y_true and y_pred:
true_positive: y_true == True and y_pred > thresholds
false_negatives: y_true == True and y_pred <= thresholds
true_negatives: y_true == False and y_pred <= thresholds
false_positive: y_true == False and y_pred > thresholds
The results will be weighted and added together. When multiple thresholds
are provided, we will repeat the same for every threshold.
For estimation of these metrics over a stream of data, the function creates
an `update_op` operation that updates the given variables.
If `sample_weight` is `None`, weights default to 1.
Use weights of 0 to mask values.
Args:
variables_to_update: Dictionary with 'tp', 'fn', 'tn', 'fp' as valid keys
and corresponding variables to update as values.
y_true: A `Tensor` whose shape matches `y_pred`. Will be cast to `bool`.
y_pred: A floating point `Tensor` of arbitrary shape and whose values are
in the range `[0, 1]`.
thresholds: A float value, float tensor, python list, or tuple of float
thresholds in `[0, 1]`, or NEG_INF (used when top_k is set).
top_k: Optional int, indicates that the positive labels should be limited
to the top k predictions.
class_id: Optional int, limits the prediction and labels to the class
specified by this argument.
sample_weight: Optional `Tensor` whose rank is either 0, or the same rank
as `y_true`, and must be broadcastable to `y_true` (i.e., all dimensions
must be either `1`, or the same as the corresponding `y_true`
dimension).
multi_label: Optional boolean indicating whether multidimensional
prediction/labels should be treated as multilabel responses, or
flattened into a single label. When True, the valus of
`variables_to_update` must have a second dimension equal to the number
of labels in y_true and y_pred, and those tensors must not be
RaggedTensors.
label_weights: (optional) tensor of non-negative weights for multilabel
data. The weights are applied when calculating TP, FP, FN, and TN
without explicit multilabel handling (i.e. when the data is to be
flattened).
thresholds_distributed_evenly: Boolean, whether the thresholds are evenly
distributed within the list. An optimized method will be used if this is
the case. See _update_confusion_matrix_variables_optimized() for more
details.
Returns:
Update op.
Raises:
ValueError: If `y_pred` and `y_true` have mismatched shapes, or if
`sample_weight` is not `None` and its shape doesn't match `y_pred`, or
if `variables_to_update` contains invalid keys.
"""
if multi_label and label_weights is not None:
raise ValueError(
"`label_weights` for multilabel data should be handled "
"outside of `update_confusion_matrix_variables` when "
"`multi_label` is True."
)
if variables_to_update is None:
return
if not any(
key for key in variables_to_update if key in list(ConfusionMatrix)
):
raise ValueError(
"Please provide at least one valid confusion matrix "
"variable to update. Valid variable key options are: "
f'"{list(ConfusionMatrix)}". '
f'Received: "{variables_to_update.keys()}"'
)
variable_dtype = list(variables_to_update.values())[0].dtype
y_true = tf.cast(y_true, dtype=variable_dtype)
y_pred = tf.cast(y_pred, dtype=variable_dtype)
if thresholds_distributed_evenly:
# Check whether the thresholds has any leading or tailing epsilon added
# for floating point imprecision. The leading and tailing threshold will
# be handled bit differently as the corner case. At this point,
# thresholds should be a list/array with more than 2 items, and ranged
# between [0, 1]. See is_evenly_distributed_thresholds() for more
# details.
thresholds_with_epsilon = thresholds[0] < 0.0 or thresholds[-1] > 1.0
thresholds = tf.convert_to_tensor(thresholds, dtype=variable_dtype)
num_thresholds = thresholds.shape.as_list()[0]
if multi_label:
one_thresh = tf.equal(
tf.cast(1, dtype=tf.int32),
tf.rank(thresholds),
name="one_set_of_thresholds_cond",
)
else:
[y_pred, y_true], _ = ragged_assert_compatible_and_get_flat_values(
[y_pred, y_true], sample_weight
)
one_thresh = tf.cast(True, dtype=tf.bool)
invalid_keys = [
key for key in variables_to_update if key not in list(ConfusionMatrix)
]
if invalid_keys:
raise ValueError(
f'Invalid keys: "{invalid_keys}". '
f'Valid variable key options are: "{list(ConfusionMatrix)}"'
)
if sample_weight is None:
y_pred, y_true = losses_utils.squeeze_or_expand_dimensions(
y_pred, y_true
)
else:
sample_weight = tf.cast(sample_weight, dtype=variable_dtype)
(
y_pred,
y_true,
sample_weight,
) = losses_utils.squeeze_or_expand_dimensions(
y_pred, y_true, sample_weight=sample_weight
)
y_pred.shape.assert_is_compatible_with(y_true.shape)
if top_k is not None:
y_pred = _filter_top_k(y_pred, top_k)
if class_id is not None:
# Preserve dimension to match with sample_weight
y_true = y_true[..., class_id, None]
y_pred = y_pred[..., class_id, None]
if thresholds_distributed_evenly:
return _update_confusion_matrix_variables_optimized(
variables_to_update,
y_true,
y_pred,
thresholds,
multi_label=multi_label,
sample_weights=sample_weight,
label_weights=label_weights,
thresholds_with_epsilon=thresholds_with_epsilon,
)
pred_shape = tf.shape(y_pred)
num_predictions = pred_shape[0]
if y_pred.shape.ndims == 1:
num_labels = 1
else:
num_labels = tf.math.reduce_prod(pred_shape[1:], axis=0)
thresh_label_tile = tf.where(
one_thresh, num_labels, tf.ones([], dtype=tf.int32)
)
# Reshape predictions and labels, adding a dim for thresholding.
if multi_label:
predictions_extra_dim = tf.expand_dims(y_pred, 0)
labels_extra_dim = tf.expand_dims(tf.cast(y_true, dtype=tf.bool), 0)
else:
# Flatten predictions and labels when not multilabel.
predictions_extra_dim = tf.reshape(y_pred, [1, -1])
labels_extra_dim = tf.reshape(tf.cast(y_true, dtype=tf.bool), [1, -1])
# Tile the thresholds for every prediction.
if multi_label:
thresh_pretile_shape = [num_thresholds, 1, -1]
thresh_tiles = [1, num_predictions, thresh_label_tile]
data_tiles = [num_thresholds, 1, 1]
else:
thresh_pretile_shape = [num_thresholds, -1]
thresh_tiles = [1, num_predictions * num_labels]
data_tiles = [num_thresholds, 1]
thresh_tiled = tf.tile(
tf.reshape(thresholds, thresh_pretile_shape), tf.stack(thresh_tiles)
)
# Tile the predictions for every threshold.
preds_tiled = tf.tile(predictions_extra_dim, data_tiles)
# Compare predictions and threshold.
pred_is_pos = tf.greater(preds_tiled, thresh_tiled)
# Tile labels by number of thresholds
label_is_pos = tf.tile(labels_extra_dim, data_tiles)
if sample_weight is not None:
sample_weight = tf.__internal__.ops.broadcast_weights(
tf.cast(sample_weight, dtype=variable_dtype), y_pred
)
weights_tiled = tf.tile(
tf.reshape(sample_weight, thresh_tiles), data_tiles
)
else:
weights_tiled = None
if label_weights is not None and not multi_label:
label_weights = tf.expand_dims(label_weights, 0)
label_weights = tf.__internal__.ops.broadcast_weights(
label_weights, y_pred
)
label_weights_tiled = tf.tile(
tf.reshape(label_weights, thresh_tiles), data_tiles
)
if weights_tiled is None:
weights_tiled = label_weights_tiled
else:
weights_tiled = tf.multiply(weights_tiled, label_weights_tiled)
update_ops = []
def weighted_assign_add(label, pred, weights, var):
label_and_pred = tf.cast(tf.logical_and(label, pred), dtype=var.dtype)
if weights is not None:
label_and_pred *= tf.cast(weights, dtype=var.dtype)
return var.assign_add(tf.reduce_sum(label_and_pred, 1))
loop_vars = {
ConfusionMatrix.TRUE_POSITIVES: (label_is_pos, pred_is_pos),
}
update_tn = ConfusionMatrix.TRUE_NEGATIVES in variables_to_update
update_fp = ConfusionMatrix.FALSE_POSITIVES in variables_to_update
update_fn = ConfusionMatrix.FALSE_NEGATIVES in variables_to_update
if update_fn or update_tn:
pred_is_neg = tf.logical_not(pred_is_pos)
loop_vars[ConfusionMatrix.FALSE_NEGATIVES] = (label_is_pos, pred_is_neg)
if update_fp or update_tn:
label_is_neg = tf.logical_not(label_is_pos)
loop_vars[ConfusionMatrix.FALSE_POSITIVES] = (label_is_neg, pred_is_pos)
if update_tn:
loop_vars[ConfusionMatrix.TRUE_NEGATIVES] = (
label_is_neg,
pred_is_neg,
)
for matrix_cond, (label, pred) in loop_vars.items():
if matrix_cond in variables_to_update:
update_ops.append(
weighted_assign_add(
label, pred, weights_tiled, variables_to_update[matrix_cond]
)
)
return tf.group(update_ops)
def _filter_top_k(x, k):
"""Filters top-k values in the last dim of x and set the rest to NEG_INF.
Used for computing top-k prediction values in dense labels (which has the
same shape as predictions) for recall and precision top-k metrics.
Args:
x: tensor with any dimensions.
k: the number of values to keep.
Returns:
tensor with same shape and dtype as x.
"""
_, top_k_idx = tf.math.top_k(x, k, sorted=False)
top_k_mask = tf.reduce_sum(
tf.one_hot(top_k_idx, tf.shape(x)[-1], axis=-1), axis=-2
)
return x * top_k_mask + NEG_INF * (1 - top_k_mask)
def ragged_assert_compatible_and_get_flat_values(values, mask=None):
"""If ragged, it checks the compatibility and then returns the flat_values.
Note: If two tensors are dense, it does not check their compatibility.
Note: Although two ragged tensors with different ragged ranks could have
identical overall rank and dimension sizes and hence be compatible,
we do not support those cases.
Args:
values: A list of potentially ragged tensor of the same ragged_rank.
mask: A potentially ragged tensor of the same ragged_rank as elements in
Values.
Returns:
A tuple in which the first element is the list of tensors and the second
is the mask tensor. ([Values], mask). Mask and the element in Values
are equal to the flat_values of the input arguments (if they were
ragged).
"""
if isinstance(values, list):
is_all_ragged = all(isinstance(rt, tf.RaggedTensor) for rt in values)
is_any_ragged = any(isinstance(rt, tf.RaggedTensor) for rt in values)
else:
is_all_ragged = isinstance(values, tf.RaggedTensor)
is_any_ragged = is_all_ragged
if is_all_ragged and ((mask is None) or isinstance(mask, tf.RaggedTensor)):
to_be_stripped = False
if not isinstance(values, list):
values = [values]
to_be_stripped = True
# NOTE: we leave the flat_values compatibility to
# tf.TensorShape `assert_is_compatible_with` check if both dynamic
# dimensions are equal and then use the flat_values.
nested_row_split_list = [rt.nested_row_splits for rt in values]
assertion_list = _assert_splits_match(nested_row_split_list)
# if both are ragged sample_weights also should be ragged with same
# dims.
if isinstance(mask, tf.RaggedTensor):
assertion_list_for_mask = _assert_splits_match(
[nested_row_split_list[0], mask.nested_row_splits]
)
with tf.control_dependencies(assertion_list_for_mask):
mask = tf.expand_dims(mask.flat_values, -1)
# values has at least 1 element.
flat_values = []
for value in values:
with tf.control_dependencies(assertion_list):
flat_values.append(tf.expand_dims(value.flat_values, -1))
values = flat_values[0] if to_be_stripped else flat_values
elif is_any_ragged:
raise TypeError(
"Some of the inputs are not tf.RaggedTensor. "
f"Input received: {values}"
)
# values are empty or value are not ragged and mask is ragged.
elif isinstance(mask, tf.RaggedTensor):
raise TypeError(
"Ragged mask is not allowed with non-ragged inputs. "
f"Input received: {values}, mask received: {mask}"
)
return values, mask
def _assert_splits_match(nested_splits_lists):
"""Checks that the given splits lists are identical.
Performs static tests to ensure that the given splits lists are identical,
and returns a list of control dependency op tensors that check that they are
fully identical.
Args:
nested_splits_lists: A list of nested_splits_lists, where each split_list
is a list of `splits` tensors from a `RaggedTensor`, ordered from
outermost ragged dimension to innermost ragged dimension.
Returns:
A list of control dependency op tensors.
Raises:
ValueError: If the splits are not identical.
"""
error_msg = (
"Inputs must have identical ragged splits. "
f"Input received: {nested_splits_lists}"
)
for splits_list in nested_splits_lists:
if len(splits_list) != len(nested_splits_lists[0]):
raise ValueError(error_msg)
return [
tf.debugging.assert_equal(s1, s2, message=error_msg)
for splits_list in nested_splits_lists[1:]
for (s1, s2) in zip(nested_splits_lists[0], splits_list)
]
def binary_matches(y_true, y_pred, threshold=0.5):
"""Creates int Tensor, 1 for label-prediction match, 0 for mismatch.
Args:
y_true: Ground truth values, of shape (batch_size, d0, .. dN).
y_pred: The predicted values, of shape (batch_size, d0, .. dN).
threshold: (Optional) Float representing the threshold for deciding
whether prediction values are 1 or 0.
Returns:
Binary matches, of shape (batch_size, d0, .. dN).
"""
y_pred = tf.convert_to_tensor(y_pred)
threshold = tf.cast(threshold, y_pred.dtype)
y_pred = tf.cast(y_pred > threshold, y_pred.dtype)
return tf.cast(tf.equal(y_true, y_pred), backend.floatx())
def sparse_categorical_matches(y_true, y_pred):
"""Creates float Tensor, 1.0 for label-prediction match, 0.0 for mismatch.
You can provide logits of classes as `y_pred`, since argmax of
logits and probabilities are same.
Args:
y_true: Integer ground truth values.
y_pred: The prediction values.
Returns:
Match tensor: 1.0 for label-prediction match, 0.0 for mismatch.
"""
reshape_matches = False
y_pred = tf.convert_to_tensor(y_pred)
y_true = tf.convert_to_tensor(y_true)
y_true_org_shape = tf.shape(y_true)
y_pred_rank = y_pred.shape.ndims
y_true_rank = y_true.shape.ndims
# If the shape of y_true is (num_samples, 1), squeeze to (num_samples,)
if (
(y_true_rank is not None)
and (y_pred_rank is not None)
and (len(backend.int_shape(y_true)) == len(backend.int_shape(y_pred)))
):
y_true = tf.squeeze(y_true, [-1])
reshape_matches = True
y_pred = tf.math.argmax(y_pred, axis=-1)
# If the predicted output and actual output types don't match, force cast
# them to match.
if backend.dtype(y_pred) != backend.dtype(y_true):
y_pred = tf.cast(y_pred, backend.dtype(y_true))
matches = tf.cast(tf.equal(y_true, y_pred), backend.floatx())
if reshape_matches:
matches = tf.reshape(matches, shape=y_true_org_shape)
return matches
def sparse_top_k_categorical_matches(y_true, y_pred, k=5):
"""Creates float Tensor, 1.0 for label-TopK_prediction match, 0.0 for
mismatch.
Args:
y_true: tensor of true targets.
y_pred: tensor of predicted targets.
k: (Optional) Number of top elements to look at for computing accuracy.
Defaults to `5`.
Returns:
Match tensor: 1.0 for label-prediction match, 0.0 for mismatch.
"""
reshape_matches = False
y_true = tf.convert_to_tensor(y_true)
y_pred = tf.convert_to_tensor(y_pred)
y_true_rank = y_true.shape.ndims
y_pred_rank = y_pred.shape.ndims
y_true_org_shape = tf.shape(y_true)
# Flatten y_pred to (batch_size, num_samples) and y_true to (num_samples,)
if (y_true_rank is not None) and (y_pred_rank is not None):
if y_pred_rank > 2:
y_pred = tf.reshape(y_pred, [-1, y_pred.shape[-1]])
if y_true_rank > 1:
reshape_matches = True
y_true = tf.reshape(y_true, [-1])
matches = tf.cast(
tf.math.in_top_k(
predictions=y_pred, targets=tf.cast(y_true, "int32"), k=k
),
dtype=backend.floatx(),
)
# returned matches is expected to have same shape as y_true input
if reshape_matches:
return tf.reshape(matches, shape=y_true_org_shape)
return matches
| tf-keras/tf_keras/utils/metrics_utils.py/0 | {
"file_path": "tf-keras/tf_keras/utils/metrics_utils.py",
"repo_id": "tf-keras",
"token_count": 16583
} | 205 |
# Copyright 2018 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.
# ==============================================================================
"""Thread utilities."""
import abc
import threading
from absl import logging
from tensorflow.python.util.tf_export import keras_export
@keras_export("keras.utils.TimedThread", v1=[])
class TimedThread:
"""Time-based interval Threads.
Runs a timed thread every x seconds. It can be used to run a threaded
function alongside model training or any other snippet of code.
Args:
interval: The interval, in seconds, to wait between calls to the
`on_interval` function.
**kwargs: additional args that are passed to `threading.Thread`. By
default, `Thread` is started as a `daemon` thread unless
overridden by the user in `kwargs`.
Examples:
```python
class TimedLogIterations(keras.utils.TimedThread):
def __init__(self, model, interval):
self.model = model
super().__init__(interval)
def on_interval(self):
# Logs Optimizer iterations every x seconds
try:
opt_iterations = self.model.optimizer.iterations.numpy()
print(f"Epoch: {epoch}, Optimizer Iterations: {opt_iterations}")
except Exception as e:
print(str(e)) # To prevent thread from getting killed
# `start` and `stop` the `TimerThread` manually. If the `on_interval` call
# requires access to `model` or other objects, override `__init__` method.
# Wrap it in a `try-except` to handle exceptions and `stop` the thread run.
timed_logs = TimedLogIterations(model=model, interval=5)
timed_logs.start()
try:
model.fit(...)
finally:
timed_logs.stop()
# Alternatively, run the `TimedThread` in a context manager
with TimedLogIterations(model=model, interval=5):
model.fit(...)
# If the timed thread instance needs access to callback events,
# subclass both `TimedThread` and `Callback`. Note that when calling
# `super`, they will have to called for each parent class if both of them
# have the method that needs to be run. Also, note that `Callback` has
# access to `model` as an attribute and need not be explictly provided.
class LogThreadCallback(
keras.utils.TimedThread, keras.callbacks.Callback
):
def __init__(self, interval):
self._epoch = 0
keras.utils.TimedThread.__init__(self, interval)
keras.callbacks.Callback.__init__(self)
def on_interval(self):
if self.epoch:
opt_iter = self.model.optimizer.iterations.numpy()
logging.info(f"Epoch: {self._epoch}, Opt Iteration: {opt_iter}")
def on_epoch_begin(self, epoch, logs=None):
self._epoch = epoch
with LogThreadCallback(interval=5) as thread_callback:
# It's required to pass `thread_callback` to also `callbacks` arg of
# `model.fit` to be triggered on callback events.
model.fit(..., callbacks=[thread_callback])
```
"""
def __init__(self, interval, **kwargs):
self.interval = interval
self.daemon = kwargs.pop("daemon", True)
self.thread_kwargs = kwargs
self.thread = None
self.thread_stop_event = None
def _call_on_interval(self):
# Runs indefinitely once thread is started
while not self.thread_stop_event.is_set():
self.on_interval()
self.thread_stop_event.wait(self.interval)
def start(self):
"""Creates and starts the thread run."""
if self.thread and self.thread.is_alive():
logging.warning("Thread is already running.")
return
self.thread = threading.Thread(
target=self._call_on_interval,
daemon=self.daemon,
**self.thread_kwargs
)
self.thread_stop_event = threading.Event()
self.thread.start()
def stop(self):
"""Stops the thread run."""
if self.thread_stop_event:
self.thread_stop_event.set()
def is_alive(self):
"""Returns True if thread is running. Otherwise returns False."""
if self.thread:
return self.thread.is_alive()
return False
def __enter__(self):
# Starts the thread in context manager
self.start()
return self
def __exit__(self, *args, **kwargs):
# Stops the thread run.
self.stop()
@abc.abstractmethod
def on_interval(self):
"""User-defined behavior that is called in the thread."""
raise NotImplementedError(
"Runs every x interval seconds. Needs to be "
"implemented in subclasses of `TimedThread`"
)
| tf-keras/tf_keras/utils/timed_threads.py/0 | {
"file_path": "tf-keras/tf_keras/utils/timed_threads.py",
"repo_id": "tf-keras",
"token_count": 2096
} | 206 |
# Copyright 2020 The AutoKeras Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import pytest
import tensorflow as tf
from autokeras import test_utils
from autokeras.analysers import output_analysers
def test_clf_head_one_hot_shape_error():
analyser = output_analysers.ClassificationAnalyser(name="a", num_classes=9)
dataset = tf.data.Dataset.from_tensor_slices(
test_utils.generate_one_hot_labels(dtype="np", num_classes=10)
).batch(32)
with pytest.raises(ValueError) as info:
for data in dataset:
analyser.update(data)
analyser.finalize()
assert "Expect the target data for a to have shape" in str(info.value)
def test_clf_head_more_dim_error():
analyser = output_analysers.ClassificationAnalyser(name="a", num_classes=9)
dataset = tf.data.Dataset.from_tensor_slices(
np.random.rand(100, 32, 32, 3)
).batch(32)
with pytest.raises(ValueError) as info:
for data in dataset:
analyser.update(data)
analyser.finalize()
assert "Expect the target data for a to have shape" in str(info.value)
def test_wrong_num_classes_error():
analyser = output_analysers.ClassificationAnalyser(name="a", num_classes=5)
dataset = tf.data.Dataset.from_tensor_slices(np.random.rand(10, 3)).batch(
32
)
with pytest.raises(ValueError) as info:
for data in dataset:
analyser.update(data)
analyser.finalize()
assert "Expect the target data for a to have shape" in str(info.value)
def test_one_class_error():
analyser = output_analysers.ClassificationAnalyser(name="a")
dataset = tf.data.Dataset.from_tensor_slices(
np.array(["a", "a", "a"])
).batch(32)
with pytest.raises(ValueError) as info:
for data in dataset:
analyser.update(data)
analyser.finalize()
assert "Expect the target data for a to have at least 2 classes" in str(
info.value
)
def test_infer_ten_classes():
analyser = output_analysers.ClassificationAnalyser(name="a")
dataset = test_utils.generate_one_hot_labels(
dtype="dataset", num_classes=10
)
for data in dataset:
analyser.update(data)
analyser.finalize()
assert analyser.num_classes == 10
def test_infer_single_column_two_classes():
analyser = output_analysers.ClassificationAnalyser(name="a")
dataset = tf.data.Dataset.from_tensor_slices(
np.random.randint(0, 2, 10)
).batch(32)
for data in dataset:
analyser.update(data)
analyser.finalize()
assert analyser.num_classes == 2
def test_specify_five_classes():
analyser = output_analysers.ClassificationAnalyser(name="a", num_classes=5)
dataset = tf.data.Dataset.from_tensor_slices(np.random.rand(10, 5)).batch(
32
)
for data in dataset:
analyser.update(data)
analyser.finalize()
assert analyser.num_classes == 5
def test_specify_two_classes_fit_single_column():
analyser = output_analysers.ClassificationAnalyser(name="a", num_classes=2)
dataset = tf.data.Dataset.from_tensor_slices(np.random.rand(10, 1)).batch(
32
)
for data in dataset:
analyser.update(data)
analyser.finalize()
assert analyser.num_classes == 2
def test_multi_label_two_classes_has_two_columns():
analyser = output_analysers.ClassificationAnalyser(
name="a", multi_label=True
)
dataset = tf.data.Dataset.from_tensor_slices(np.random.rand(10, 2)).batch(
32
)
for data in dataset:
analyser.update(data)
analyser.finalize()
assert analyser.encoded
def test_reg_with_specified_output_dim_error():
analyser = output_analysers.RegressionAnalyser(name="a", output_dim=3)
dataset = tf.data.Dataset.from_tensor_slices(np.random.rand(10, 2)).batch(
32
)
with pytest.raises(ValueError) as info:
for data in dataset:
analyser.update(data)
analyser.finalize()
assert "Expect the target data for a to have shape" in str(info.value)
def test_reg_with_specified_output_dim_and_single_column_doesnt_crash():
analyser = output_analysers.RegressionAnalyser(name="a", output_dim=1)
dataset = tf.data.Dataset.from_tensor_slices(np.random.rand(10)).batch(32)
for data in dataset:
analyser.update(data)
analyser.finalize()
| autokeras/autokeras/analysers/output_analysers_test.py/0 | {
"file_path": "autokeras/autokeras/analysers/output_analysers_test.py",
"repo_id": "autokeras",
"token_count": 1956
} | 0 |
# Copyright 2020 The AutoKeras Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import tensorflow as tf
from autokeras.utils import data_utils
class Adapter(object):
"""Adpat the input and output format for Keras Model.
Adapter is used by the input nodes and the heads of the hypermodel. It do
some type checking for the data and converts it to tf.data.Dataset format.
It also batches the dataset if it is not batched.
"""
def check(self, dataset):
"""Check if the dataset is valid for the input node.
# Arguments
dataset: Usually numpy.ndarray, pandas.DataFrame or
tensorflow.Dataset. The dataset to be checked.
# Returns
Boolean. Whether the dataset is in compatible format.
"""
return True
def convert_to_dataset(self, dataset, batch_size):
"""Convert supported formats of datasets to batched tf.data.Dataset.
# Arguments
dataset: Usually numpy.ndarray, pandas.DataFrame or
tensorflow.Dataset. The dataset to be converted.
batch_size: Int. The batch_size to batch the dataset.
# Returns
tf.data.Dataset. The converted dataset.
"""
if isinstance(dataset, np.ndarray):
dataset = tf.data.Dataset.from_tensor_slices(dataset)
return data_utils.batch_dataset(dataset, batch_size)
def adapt(self, dataset, batch_size):
"""Check, convert and batch the dataset.
# Arguments
dataset: Usually numpy.ndarray, pandas.DataFrame or
tensorflow.Dataset. The dataset to be converted.
batch_size: Int. The batch_size to batch the dataset.
# Returns
tf.data.Dataset. The converted dataset.
"""
self.check(dataset)
dataset = self.convert_to_dataset(dataset, batch_size)
return dataset
| autokeras/autokeras/engine/adapter.py/0 | {
"file_path": "autokeras/autokeras/engine/adapter.py",
"repo_id": "autokeras",
"token_count": 911
} | 1 |
# Copyright 2020 The AutoKeras Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import keras_tuner
from tensorflow import keras
from tensorflow import nest
from autokeras import blocks as blocks_module
from autokeras import keras_layers
from autokeras import nodes as nodes_module
from autokeras.engine import head as head_module
from autokeras.engine import serializable
from autokeras.utils import io_utils
def feature_encoding_input(block):
"""Fetch the column_types and column_names.
The values are fetched for FeatureEncoding from StructuredDataInput.
"""
if not isinstance(block.inputs[0], nodes_module.StructuredDataInput):
raise TypeError(
"CategoricalToNumerical can only be used with StructuredDataInput."
)
block.column_types = block.inputs[0].column_types
block.column_names = block.inputs[0].column_names
# Compile the graph.
COMPILE_FUNCTIONS = {
blocks_module.StructuredDataBlock: [feature_encoding_input],
blocks_module.CategoricalToNumerical: [feature_encoding_input],
}
def load_graph(filepath, custom_objects=None):
if custom_objects is None:
custom_objects = {}
with keras.utils.custom_object_scope(custom_objects):
return Graph.from_config(io_utils.load_json(filepath))
class Graph(keras_tuner.HyperModel, serializable.Serializable):
"""A graph consists of connected Blocks, or Heads.
# Arguments
inputs: A list of input node(s) for the Graph.
outputs: A list of output node(s) for the Graph.
"""
def __init__(self, inputs=None, outputs=None, **kwargs):
super().__init__(**kwargs)
self.inputs = nest.flatten(inputs)
self.outputs = nest.flatten(outputs)
self._node_to_id = {}
self._nodes = []
self.blocks = []
self._block_to_id = {}
if inputs and outputs:
self._build_network()
# Temporary attributes
self.epochs = None
self.num_samples = None
def compile(self):
"""Share the information between blocks."""
for block in self.blocks:
for func in COMPILE_FUNCTIONS.get(block.__class__, []):
func(block)
def _build_network(self):
self._node_to_id = {}
# Recursively find all the interested nodes.
for input_node in self.inputs:
self._search_network(input_node, self.outputs, set(), set())
self._nodes = sorted(
list(self._node_to_id.keys()), key=lambda x: self._node_to_id[x]
)
for node in self.inputs + self.outputs:
if node not in self._node_to_id:
raise ValueError("Inputs and outputs not connected.")
# Find the blocks.
blocks = []
for input_node in self._nodes:
for block in input_node.out_blocks:
if (
any(
[
output_node in self._node_to_id
for output_node in block.outputs
]
)
and block not in blocks
):
blocks.append(block)
# Check if all the inputs of the blocks are set as inputs.
for block in blocks:
for input_node in block.inputs:
if input_node not in self._node_to_id:
raise ValueError(
"A required input is missing for HyperModel "
"{name}.".format(name=block.name)
)
# Calculate the in degree of all the nodes
in_degree = [0] * len(self._nodes)
for node_id, node in enumerate(self._nodes):
in_degree[node_id] = len(
[block for block in node.in_blocks if block in blocks]
)
# Add the blocks in topological order.
self.blocks = []
self._block_to_id = {}
while len(blocks) != 0:
new_added = []
# Collect blocks with in degree 0.
for block in blocks:
if any(
[in_degree[self._node_to_id[node]] for node in block.inputs]
):
continue
new_added.append(block)
# Remove the collected blocks from blocks.
for block in new_added:
blocks.remove(block)
for block in new_added:
# Add the collected blocks to the Graph.
self._add_block(block)
# Decrease the in degree of the output nodes.
for output_node in block.outputs:
output_node_id = self._node_to_id[output_node]
in_degree[output_node_id] -= 1
def _search_network(
self, input_node, outputs, in_stack_nodes, visited_nodes
):
visited_nodes.add(input_node)
in_stack_nodes.add(input_node)
outputs_reached = False
if input_node in outputs:
outputs_reached = True
for block in input_node.out_blocks:
for output_node in block.outputs:
if output_node in in_stack_nodes:
raise ValueError("The network has a cycle.")
if output_node not in visited_nodes:
self._search_network(
output_node, outputs, in_stack_nodes, visited_nodes
)
if output_node in self._node_to_id.keys():
outputs_reached = True
if outputs_reached:
self._add_node(input_node)
in_stack_nodes.remove(input_node)
def _add_block(self, block):
if block not in self.blocks:
block_id = len(self.blocks)
self._block_to_id[block] = block_id
self.blocks.append(block)
def _add_node(self, input_node):
if input_node not in self._node_to_id:
self._node_to_id[input_node] = len(self._node_to_id)
def get_config(self):
blocks = [blocks_module.serialize(block) for block in self.blocks]
nodes = {
str(self._node_to_id[node]): nodes_module.serialize(node)
for node in self.inputs
}
block_inputs = {
str(block_id): [self._node_to_id[node] for node in block.inputs]
for block_id, block in enumerate(self.blocks)
}
block_outputs = {
str(block_id): [self._node_to_id[node] for node in block.outputs]
for block_id, block in enumerate(self.blocks)
}
outputs = [self._node_to_id[node] for node in self.outputs]
return {
"blocks": blocks, # Dict {id: serialized}.
"nodes": nodes, # Dict {id: serialized}.
"outputs": outputs, # List of node_ids.
"block_inputs": block_inputs, # Dict {id: List of node_ids}.
"block_outputs": block_outputs, # Dict {id: List of node_ids}.
}
@classmethod
def from_config(cls, config):
blocks = [
blocks_module.deserialize(block) for block in config["blocks"]
]
nodes = {
int(node_id): nodes_module.deserialize(node)
for node_id, node in config["nodes"].items()
}
inputs = [nodes[node_id] for node_id in nodes]
for block_id, block in enumerate(blocks):
input_nodes = [
nodes[node_id]
for node_id in config["block_inputs"][str(block_id)]
]
output_nodes = nest.flatten(block(input_nodes))
for output_node, node_id in zip(
output_nodes, config["block_outputs"][str(block_id)]
):
nodes[node_id] = output_node
outputs = [nodes[node_id] for node_id in config["outputs"]]
return cls(inputs=inputs, outputs=outputs)
def build(self, hp):
"""Build the HyperModel into a Keras Model."""
self.compile()
keras_nodes = {}
keras_input_nodes = []
for node in self.inputs:
node_id = self._node_to_id[node]
input_node = node.build_node(hp)
output_node = node.build(hp, input_node)
keras_input_nodes.append(input_node)
keras_nodes[node_id] = output_node
for block in self.blocks:
temp_inputs = [
keras_nodes[self._node_to_id[input_node]]
for input_node in block.inputs
]
outputs = block.build(hp, inputs=temp_inputs)
outputs = nest.flatten(outputs)
for output_node, real_output_node in zip(block.outputs, outputs):
keras_nodes[self._node_to_id[output_node]] = real_output_node
model = keras.Model(
keras_input_nodes,
[
keras_nodes[self._node_to_id[output_node]]
for output_node in self.outputs
],
)
return self._compile_keras_model(hp, model)
def _get_metrics(self):
metrics = {}
for output_node in self.outputs:
block = output_node.in_blocks[0]
if isinstance(block, head_module.Head):
metrics[block.name] = block.metrics
return metrics
def _get_loss(self):
loss = {}
for output_node in self.outputs:
block = output_node.in_blocks[0]
if isinstance(block, head_module.Head):
loss[block.name] = block.loss
return loss
def _compile_keras_model(self, hp, model):
# Specify hyperparameters from compile(...)
optimizer_name = hp.Choice(
"optimizer",
["adam", "sgd", "adam_weight_decay"],
default="adam",
)
# TODO: add adadelta optimizer when it can optimize embedding layer on
# GPU.
learning_rate = hp.Choice(
"learning_rate", [1e-1, 1e-2, 1e-3, 1e-4, 2e-5, 1e-5], default=1e-3
)
if optimizer_name == "adam":
optimizer = keras.optimizers.Adam(learning_rate=learning_rate)
elif optimizer_name == "sgd":
optimizer = keras.optimizers.SGD(learning_rate=learning_rate)
elif optimizer_name == "adam_weight_decay":
steps_per_epoch = int(self.num_samples / self.batch_size)
num_train_steps = steps_per_epoch * self.epochs
warmup_steps = int(
self.epochs * self.num_samples * 0.1 / self.batch_size
)
lr_schedule = keras.optimizers.schedules.PolynomialDecay(
initial_learning_rate=learning_rate,
decay_steps=num_train_steps,
end_learning_rate=0.0,
)
if warmup_steps:
lr_schedule = keras_layers.WarmUp(
initial_learning_rate=learning_rate,
decay_schedule_fn=lr_schedule,
warmup_steps=warmup_steps,
)
optimizer = keras.optimizers.experimental.AdamW(
learning_rate=lr_schedule,
weight_decay=0.01,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-6,
)
model.compile(
optimizer=optimizer,
metrics=self._get_metrics(),
loss=self._get_loss(),
)
return model
def save(self, filepath):
io_utils.save_json(filepath, self.get_config())
def set_io_shapes(self, shapes):
for node, shape in zip(self.inputs, nest.flatten(shapes[0])):
node.shape = tuple(shape[1:])
for node, shape in zip(self.outputs, nest.flatten(shapes[1])):
node.in_blocks[0].shape = tuple(shape[1:])
def set_fit_args(self, validation_split, epochs=None):
self.epochs = epochs
# Epochs not specified by the user
if self.epochs is None:
self.epochs = 1
# num_samples from analysers are before split
self.num_samples = self.inputs[0].num_samples * (1 - validation_split)
@property
def batch_size(self):
return self.inputs[0].batch_size
| autokeras/autokeras/graph.py/0 | {
"file_path": "autokeras/autokeras/graph.py",
"repo_id": "autokeras",
"token_count": 6146
} | 2 |
# Copyright 2020 The AutoKeras Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import tensorflow as tf
from autokeras import test_utils
from autokeras.preprocessors import common
from autokeras.utils import data_utils
def test_time_series_input_transform():
dataset = tf.data.Dataset.from_tensor_slices(np.random.rand(100, 32)).batch(
32
)
preprocessor = common.SlidingWindow(lookback=2, batch_size=32)
x = preprocessor.transform(dataset)
assert data_utils.dataset_shape(x).as_list() == [None, 2, 32]
def test_categorical_to_numerical_input_transform():
x_train = np.array([["a", "ab", 2.1], ["b", "bc", 1.0], ["a", "bc", "nan"]])
preprocessor = common.CategoricalToNumericalPreprocessor(
column_names=["column_a", "column_b", "column_c"],
column_types={
"column_a": "categorical",
"column_b": "categorical",
"column_c": "numerical",
},
)
dataset = tf.data.Dataset.from_tensor_slices(x_train).batch(32)
preprocessor.fit(tf.data.Dataset.from_tensor_slices(x_train).batch(32))
results = preprocessor.transform(dataset)
for result in results:
assert result[0][0] == result[2][0]
assert result[0][0] != result[1][0]
assert result[0][1] != result[1][1]
assert result[0][1] != result[2][1]
assert result[2][2] == 0
assert result.dtype == tf.float32
def test_cast_to_int32_return_int32():
dataset = test_utils.generate_one_hot_labels(100, 10, "dataset")
dataset = dataset.map(lambda x: tf.cast(x, tf.uint8))
dataset = common.CastToInt32().transform(dataset)
for data in dataset:
assert data.dtype == tf.int32
break
| autokeras/autokeras/preprocessors/common_test.py/0 | {
"file_path": "autokeras/autokeras/preprocessors/common_test.py",
"repo_id": "autokeras",
"token_count": 865
} | 3 |
<jupyter_start><jupyter_code>!pip install autokeras
import numpy as np
import tensorflow as tf
from tensorflow.keras.datasets import mnist
import autokeras as ak<jupyter_output><empty_output><jupyter_text>In this tutorial, we show how to customize your search space with[AutoModel](/auto_model/automodel-class) and how to implement your own blockas search space. This API is mainly for advanced users who already know whattheir model should look like. Customized Search SpaceFirst, let us see how we can build the following neural network using thebuilding blocks in AutoKeras.graph LR id1(ImageInput) --> id2(Normalization) id2 --> id3(Image Augmentation) id3 --> id4(Convolutional) id3 --> id5(ResNet V2) id4 --> id6(Merge) id5 --> id6 id6 --> id7(Classification Head)We can make use of the [AutoModel](/auto_model/automodel-class) API inAutoKeras to implemented as follows.The usage is the same as the [Keras functionalAPI](https://www.tensorflow.org/guide/keras/functional).Since this is just a demo, we use small amount of `max_trials` and `epochs`.<jupyter_code>input_node = ak.ImageInput()
output_node = ak.Normalization()(input_node)
output_node1 = ak.ConvBlock()(output_node)
output_node2 = ak.ResNetBlock(version="v2")(output_node)
output_node = ak.Merge()([output_node1, output_node2])
output_node = ak.ClassificationHead()(output_node)
auto_model = ak.AutoModel(
inputs=input_node, outputs=output_node, overwrite=True, max_trials=1
)<jupyter_output><empty_output><jupyter_text>Whild building the model, the blocks used need to follow this topology:`Preprocessor` -> `Block` -> `Head`. `Normalization` and `ImageAugmentation`are `Preprocessor`s.`ClassificationHead` is `Head`. The rest are `Block`s.In the code above, we use `ak.ResNetBlock(version='v2')` to specify the versionof ResNet to use. There are many other arguments to specify for each buildingblock. For most of the arguments, if not specified, they would be tunedautomatically. Please refer to the documentation links at the bottom of thepage for more details.Then, we prepare some data to run the model.<jupyter_code>(x_train, y_train), (x_test, y_test) = mnist.load_data()
print(x_train.shape) # (60000, 28, 28)
print(y_train.shape) # (60000,)
print(y_train[:3]) # array([7, 2, 1], dtype=uint8)
# Feed the AutoModel with training data.
auto_model.fit(x_train[:100], y_train[:100], epochs=1)
# Predict with the best model.
predicted_y = auto_model.predict(x_test)
# Evaluate the best model with testing data.
print(auto_model.evaluate(x_test, y_test))<jupyter_output><empty_output><jupyter_text>For multiple input nodes and multiple heads search space, you can refer to[this section](/tutorial/multi/customized-search-space). Validation DataIf you would like to provide your own validation data or change the ratio ofthe validation data, please refer to the Validation Data section of thetutorials of [ImageClassification](/tutorial/image_classification/validation-data), [TextClassification](/tutorial/text_classification/validation-data), [StructuredDataClassification](/tutorial/structured_data_classification/validation-data),[Multi-task and Multiple Validation](/tutorial/multi/validation-data). Data FormatYou can refer to the documentation of[ImageInput](/node/imageinput-class),[StructuredDataInput](/node/structureddatainput-class),[TextInput](/node/textinput-class),[RegressionHead](/block/regressionhead-class),[ClassificationHead](/block/classificationhead-class),for the format of different types of data.You can also refer to the Data Format section of the tutorials of[Image Classification](/tutorial/image_classification/data-format),[Text Classification](/tutorial/text_classification/data-format),[Structured DataClassification](/tutorial/structured_data_classification/data-format). Implement New BlockYou can extend the [Block](/base/block-class)class to implement your own building blocks and use it with[AutoModel](/auto_model/automodel-class).The first step is to learn how to write a build function for[KerasTuner](https://keras-team.github.io/keras-tuner/usage-the-basics). Youneed to override the [build function](/base/build-method) of the block. Thefollowing example shows how to implement a single Dense layer block whosenumber of neurons is tunable.<jupyter_code>class SingleDenseLayerBlock(ak.Block):
def build(self, hp, inputs=None):
# Get the input_node from inputs.
input_node = tf.nest.flatten(inputs)[0]
layer = tf.keras.layers.Dense(
hp.Int("num_units", min_value=32, max_value=512, step=32)
)
output_node = layer(input_node)
return output_node<jupyter_output><empty_output><jupyter_text>You can connect it with other blocks and build it into an[AutoModel](/auto_model/automodel-class).<jupyter_code># Build the AutoModel
input_node = ak.Input()
output_node = SingleDenseLayerBlock()(input_node)
output_node = ak.RegressionHead()(output_node)
auto_model = ak.AutoModel(input_node, output_node, overwrite=True, max_trials=1)
# Prepare Data
num_instances = 100
x_train = np.random.rand(num_instances, 20).astype(np.float32)
y_train = np.random.rand(num_instances, 1).astype(np.float32)
x_test = np.random.rand(num_instances, 20).astype(np.float32)
y_test = np.random.rand(num_instances, 1).astype(np.float32)
# Train the model
auto_model.fit(x_train, y_train, epochs=1)
print(auto_model.evaluate(x_test, y_test))<jupyter_output><empty_output> | autokeras/docs/ipynb/customized.ipynb/0 | {
"file_path": "autokeras/docs/ipynb/customized.ipynb",
"repo_id": "autokeras",
"token_count": 1772
} | 4 |
import inspect
import warnings
import black
from sphinx.util.inspect import signature
from sphinx.util.inspect import stringify_signature
from . import utils
def get_signature_start(function):
"""For the Dense layer, it should return the string 'keras.layers.Dense'"""
if utils.ismethod(function):
prefix = f"{utils.get_class_from_method(function).__name__}."
else:
try:
prefix = f"{function.__module__}."
except AttributeError:
warnings.warn(
f"function {function} has no module. "
f"It will not be included in the signature."
)
prefix = ""
return f"{prefix}{function.__name__}"
def get_signature_end(function):
sig = signature(function)
signature_end = stringify_signature(sig, show_annotation=False)
if utils.ismethod(function):
signature_end = signature_end.replace("(self, ", "(")
signature_end = signature_end.replace("(self)", "()")
return signature_end
def get_function_signature(function, override=None, max_line_length: int = 110):
if override is None:
signature_start = get_signature_start(function)
else:
signature_start = override
signature_end = get_signature_end(function)
return format_signature(signature_start, signature_end, max_line_length)
def get_class_signature(cls, override=None, max_line_length: int = 110):
if override is None:
signature_start = f"{cls.__module__}.{cls.__name__}"
else:
signature_start = override
signature_end = get_signature_end(cls.__init__)
return format_signature(signature_start, signature_end, max_line_length)
def get_signature(object_, override=None, max_line_length: int = 110):
if inspect.isclass(object_):
return get_class_signature(object_, override, max_line_length)
else:
return get_function_signature(object_, override, max_line_length)
def format_signature(
signature_start: str, signature_end: str, max_line_length: int = 110
):
"""pretty formatting to avoid long signatures on one single line"""
# first, we make it look like a real function declaration.
fake_signature_start = "x" * len(signature_start)
fake_signature = fake_signature_start + signature_end
fake_python_code = f"def {fake_signature}:\n pass\n"
# we format with black
mode = black.FileMode(line_length=max_line_length)
formatted_fake_python_code = black.format_str(fake_python_code, mode=mode)
# we make the final, multiline signature
new_signature_end = extract_signature_end(formatted_fake_python_code)
return signature_start + new_signature_end
def extract_signature_end(function_definition):
start = function_definition.find("(")
stop = function_definition.rfind(")")
return function_definition[start : stop + 1]
| autokeras/docs/keras_autodoc/get_signatures.py/0 | {
"file_path": "autokeras/docs/keras_autodoc/get_signatures.py",
"repo_id": "autokeras",
"token_count": 1067
} | 5 |
This package is developed by [DATA LAB](http://faculty.cs.tamu.edu/xiahu/) at Texas A&M University,
collaborating with [keras-team](https://github.com/keras-team) for version 1.0 and above.
## Core Team
[**Haifeng Jin**](https://github.com/haifeng-jin):
Created, designed and implemented the AutoKeras system.
Maintainer.
[**François Chollet**](https://github.com/fchollet):
The API and system architecture design for AutoKeras 1.0.
Code reviews for pull requests.
[**Qingquan Song**](https://github.com/song3134):
Designed the neural architecture search algorithms.
Implemented the tabular data classification and regression module.
[**Xia "Ben" Hu**](http://faculty.cs.tamu.edu/xiahu/):
Project lead and maintainer.
| autokeras/docs/templates/about.md/0 | {
"file_path": "autokeras/docs/templates/about.md",
"repo_id": "autokeras",
"token_count": 237
} | 6 |
# Library import
import numpy as np
import tensorflow as tf
import autokeras as ak
# Prepare example Data - Shape 1D
num_instances = 100
num_features = 5
x_train = np.random.rand(num_instances, num_features).astype(np.float32)
y_train = np.zeros(num_instances).astype(np.float32)
y_train[0 : int(num_instances / 2)] = 1
x_test = np.random.rand(num_instances, num_features).astype(np.float32)
y_test = np.zeros(num_instances).astype(np.float32)
y_train[0 : int(num_instances / 2)] = 1
x_train = np.expand_dims(
x_train, axis=2
) # This step it's very important an CNN will only accept this data shape
print(x_train.shape)
print(y_train.shape)
# Prepare Automodel for search
input_node = ak.Input()
output_node = ak.ConvBlock()(input_node)
# output_node = ak.DenseBlock()(output_node) #optional
# output_node = ak.SpatialReduction()(output_node) #optional
output_node = ak.ClassificationHead(num_classes=2, multi_label=True)(
output_node
)
auto_model = ak.AutoModel(
inputs=input_node, outputs=output_node, overwrite=True, max_trials=1
)
# Search
auto_model.fit(x_train, y_train, epochs=1)
print(auto_model.evaluate(x_test, y_test))
# Export as a Keras Model
model = auto_model.export_model()
print(type(model.summary()))
# print model as image
tf.keras.utils.plot_model(
model, show_shapes=True, expand_nested=True, to_file="name.png"
)
| autokeras/examples/automodel_with_cnn.py/0 | {
"file_path": "autokeras/examples/automodel_with_cnn.py",
"repo_id": "autokeras",
"token_count": 511
} | 7 |
pytest tests --cov-report html --cov-report xml:cov.xml --cov=autokeras
| autokeras/shell/cov.sh/0 | {
"file_path": "autokeras/shell/cov.sh",
"repo_id": "autokeras",
"token_count": 28
} | 8 |
# Title of RFC
| Status | (Proposed / Accepted / Implemented / Obsolete) |
:-------------- |:---------------------------------------------------- |
| **Author(s)** | My Name ([email protected]), AN Other ([email protected]) |
| **Sponsor** | A N Expert ([email protected]) |
| **Updated** | YYYY-MM-DD |
| **Obsoletes** | RFC it replaces, else remove this header |
## Objective
What are we doing and why? What problem will this solve? What are the goals and
non-goals? This is your executive summary; keep it short, elaborate below.
## Motivation
Why this is a valuable problem to solve? What background information is needed
to show how this design addresses the problem?
Which users are affected by the problem? Why is it a problem? What data supports
this? What related work exists?
## User Benefit
How will users (or other contributors) benefit from this work? What would be the
headline in the release notes or blog post?
## Design Proposal
This is the meat of the document, where you explain your proposal. If you have
multiple alternatives, be sure to use sub-sections for better separation of the
idea, and list pros/cons to each approach. If there are alternatives that you
have eliminated, you should also list those here, and explain why you believe
your chosen approach is superior.
Factors to consider include:
* UX and usability
* How will this change impact users, and how will that be managed?
* Performance implications
* Dependencies
* Maintenance
* Backwards compatibility
## Detailed Design
This section is optional. Elaborate on details if they’re important to
understanding the design, but would make it hard to read the proposal section
above.
## Questions and Discussion Topics
Seed this with open questions you require feedback on from the RFC process. | governance/rfcs/yyyymmdd-rfc-template.md/0 | {
"file_path": "governance/rfcs/yyyymmdd-rfc-template.md",
"repo_id": "governance",
"token_count": 535
} | 9 |
"""ResNeXt models for Keras.
# Reference paper
- [Aggregated Residual Transformations for Deep Neural Networks]
(https://arxiv.org/abs/1611.05431) (CVPR 2017)
# Reference implementations
- [TensorNets]
(https://github.com/taehoonlee/tensornets/blob/master/tensornets/resnets.py)
- [Torch ResNeXt]
(https://github.com/facebookresearch/ResNeXt/blob/master/models/resnext.lua)
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from . import imagenet_utils
from .imagenet_utils import decode_predictions
from .resnet_common import ResNeXt50
from .resnet_common import ResNeXt101
def preprocess_input(x, **kwargs):
"""Preprocesses a numpy array encoding a batch of images.
# Arguments
x: a 4D numpy array consists of RGB values within [0, 255].
data_format: data format of the image tensor.
# Returns
Preprocessed array.
"""
return imagenet_utils.preprocess_input(x, mode='torch', **kwargs)
| keras-applications/keras_applications/resnext.py/0 | {
"file_path": "keras-applications/keras_applications/resnext.py",
"repo_id": "keras-applications",
"token_count": 362
} | 10 |
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
{%- block site_meta %}
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% if page and page.is_homepage %}<meta name="description" content="{{ config.site_description }}">{% endif %}
{% if config.site_author %}<meta name="author" content="{{ config.site_author }}">{% endif %}
{% if page and page.canonical_url %}<link rel="canonical" href="{{ page.canonical_url }}">{% endif %}
{% if config.site_favicon %}<link rel="shortcut icon" href="{{ config.site_favicon|url }}">
{% else %}<link rel="shortcut icon" href="{{ 'img/favicon.ico'|url }}">{% endif %}
{%- endblock %}
{%- block htmltitle %}
<title>{% if page and page.title and not page.is_hompage %}{{ page.title }} - {% endif %}{{ config.site_name }}</title>
{%- endblock %}
{%- block styles %}
<link href='https://fonts.googleapis.com/css?family=Lato:400,700|Source+Sans+Pro:400,700|Inconsolata:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="{{ 'css/theme.css'|url }}" type="text/css" />
<link rel="stylesheet" href="{{ 'css/theme_extra.css'|url }}" type="text/css" />
{%- if config.theme.highlightjs %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css">
{%- endif %}
{%- for path in config['extra_css'] %}
<link href="{{ path|url }}" rel="stylesheet">
{%- endfor %}
{%- endblock %}
{%- block libs %}
{% if page %}
<script>
// Current page data
var mkdocs_page_name = {{ page.title|tojson|safe }};
var mkdocs_page_input_path = {{ page.file.src_path|string|tojson|safe }};
var mkdocs_page_url = {{ page.abs_url|tojson|safe }};
</script>
{% endif %}
<script src="{{ 'js/jquery-2.1.1.min.js'|url }}" defer></script>
<script src="{{ 'js/modernizr-2.8.3.min.js'|url }}" defer></script>
{%- if config.theme.highlightjs %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
{%- for lang in config.theme.hljs_languages %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/languages/{{lang}}.min.js"></script>
{%- endfor %}
<script>hljs.initHighlightingOnLoad();</script>
{%- endif %}
{%- endblock %}
{%- block extrahead %} {% endblock %}
{%- block analytics %}
{% if config.google_analytics %}
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', '{{ config.google_analytics[0] }}', '{{ config.google_analytics[1] }}');
ga('send', 'pageview');
</script>
{% endif %}
{%- endblock %}
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
{# SIDE NAV, TOGGLES ON MOBILE #}
<nav data-toggle="wy-nav-shift" class="wy-nav-side stickynav">
<div class="wy-side-scroll">
<a href="{{ homepage_url }}">
<div class="keras-logo">
<img src="/img/keras-logo-small.jpg" class="keras-logo-img">
Keras-contrib Docs
</div>
</a>
<div class="wy-side-nav-search">
{%- block search_button %}
{% if 'search' in config['plugins'] %}{% include "searchbox.html" %}{% endif %}
{%- endblock %}
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
{%- block site_nav %}
{%- set navlevel = 1 %}
{%- for nav_item in nav %}
{%- if nav_item.is_section %}
<p class="caption"><span class="caption-text">{{ nav_item.title }}</span></p>
<ul{% if nav_item.active %} class="current"{% endif %}>
{%- for nav_item in nav_item.children %}
<li class="toctree-l{{ navlevel }}{% if nav_item.active %} current{% endif %}">
{%- include 'nav.html' %}
</li>
{%- endfor %}
</ul>
{%- elif config.theme.include_homepage_in_sidebar or (not nav_item == nav.homepage) %}
<ul{% if nav_item.active %} class="current"{% endif %}>
<li class="toctree-l{{ navlevel }}{% if nav_item.active %} current{% endif %}">
{%- include 'nav.html' %}
</li>
</ul>
{%- endif %}
{%- endfor %}
{%- endblock %}
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
{# MOBILE NAV, TRIGGLES SIDE NAV ON TOGGLE #}
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="{{ nav.homepage.url|url }}">{{ config.site_name }}</a>
</nav>
{# PAGE CONTENT #}
<div class="wy-nav-content">
<div class="rst-content">
{% include "breadcrumbs.html" %}
<div role="main">
<div class="section">
{% block content %}
{{ page.content }}
{% endblock %}
</div>
</div>
{%- block footer %}
{% include "footer.html" %}
{% endblock %}
</div>
</div>
</section>
</div>
{% include "versions.html" %}
{%- block scripts %}
<script>var base_url = '{{ base_url }}';</script>
<script src="{{ 'js/theme.js'|url }}" defer></script>
{%- for path in config['extra_javascript'] %}
<script src="{{ path|url }}" defer></script>
{%- endfor %}
<script type="text/javascript" defer>
window.onload = function () {
SphinxRtdTheme.Navigation.enable({{ 'true' if config.theme.sticky_navigation else 'false' }});
};
</script>
{%- endblock %}
</body>
</html>
{% if page and page.is_homepage %}
<!--
MkDocs version : {{ mkdocs_version }}
Build Date UTC : {{ build_date_utc }}
-->
{% endif %}
| keras-contrib/contrib_docs/theme/base.html/0 | {
"file_path": "keras-contrib/contrib_docs/theme/base.html",
"repo_id": "keras-contrib",
"token_count": 2900
} | 11 |
'''Train a simple deep CNN on the CIFAR10 small images dataset using
a triangular cyclic learning rate (CLR) policy.
It gets to 75% validation accuracy in 15 epochs, and 79% after 40 epochs;
compare to 25 and 50 epochs respectively without CLR.
'''
from __future__ import print_function
from __future__ import absolute_import
import keras
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras_contrib.callbacks import CyclicLR
import os
batch_size = 100
epochs = 50
num_classes = 10
data_augmentation = True
num_predictions = 20
save_dir = os.path.join(os.getcwd(), 'saved_models')
model_name = 'keras_cifar10_trained_model.h5'
# The data, split between train and test sets:
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
# Convert class vectors to binary class matrices.
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
model = Sequential()
model.add(Conv2D(32, (3, 3), padding='same',
input_shape=x_train.shape[1:]))
model.add(Activation('relu'))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (3, 3), padding='same'))
model.add(Activation('relu'))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes))
model.add(Activation('softmax'))
# initiate RMSprop optimizer
opt = keras.optimizers.rmsprop(lr=0.0001, decay=1e-6)
# initiate CyclicLR LR scheduler
clr = CyclicLR(
base_lr=0.0001,
max_lr=0.0005,
step_size=2000,
mode='triangular')
# Let's train the model using RMSprop
model.compile(loss='categorical_crossentropy',
optimizer=opt,
metrics=['accuracy'])
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
if not data_augmentation:
print('Not using data augmentation.')
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
validation_data=(x_test, y_test),
callbacks=[clr],
shuffle=True)
else:
print('Using real-time data augmentation.')
# This will do preprocessing and realtime data augmentation:
datagen = ImageDataGenerator(
featurewise_center=False, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=False, # divide inputs by std of the dataset
samplewise_std_normalization=False, # divide each input by its std
zca_whitening=False, # apply ZCA whitening
zca_epsilon=1e-06, # epsilon for ZCA whitening
rotation_range=0,
# randomly rotate images in the range (degrees, 0 to 180)
# randomly shift images horizontally (fraction of total width)
width_shift_range=0.1,
# randomly shift images vertically (fraction of total height)
height_shift_range=0.1,
shear_range=0., # set range for random shear
zoom_range=0., # set range for random zoom
channel_shift_range=0., # set range for random channel shifts
# set mode for filling points outside the input boundaries
fill_mode='nearest',
cval=0., # value used for fill_mode = "constant"
horizontal_flip=True, # randomly flip images
vertical_flip=False, # randomly flip images
# set rescaling factor (applied before any other transformation)
rescale=None,
# set function that will be applied on each input
preprocessing_function=None,
# image data format, either "channels_first" or "channels_last"
data_format=None,
# fraction of images reserved for validation (strictly between 0 and 1)
validation_split=0.0)
# Compute quantities required for feature-wise normalization
# (std, mean, and principal components if ZCA whitening is applied).
datagen.fit(x_train)
# Fit the model on the batches generated by datagen.flow().
model.fit_generator(datagen.flow(x_train, y_train,
batch_size=batch_size),
epochs=epochs,
validation_data=(x_test, y_test),
callbacks=[clr],
workers=4)
# Save model and weights
if not os.path.isdir(save_dir):
os.makedirs(save_dir)
model_path = os.path.join(save_dir, model_name)
model.save(model_path)
print('Saved trained model at %s ' % model_path)
# Score trained model.
scores = model.evaluate(x_test, y_test, verbose=1)
print('Test loss:', scores[0])
print('Test accuracy:', scores[1])
| keras-contrib/examples/cifar10_clr.py/0 | {
"file_path": "keras-contrib/examples/cifar10_clr.py",
"repo_id": "keras-contrib",
"token_count": 2074
} | 12 |
# -*- coding: utf-8 -*-
"""Wide Residual Network models for Keras.
# Reference
- [Wide Residual Networks](https://arxiv.org/abs/1605.07146)
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import warnings
from keras.models import Model
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.pooling import MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Input, Conv2D
from keras.layers.merge import add
from keras.layers.normalization import BatchNormalization
from keras.utils.layer_utils import convert_all_kernels_in_model
from keras.utils.data_utils import get_file
from keras.engine.topology import get_source_inputs
from keras_applications.imagenet_utils import _obtain_input_shape
import keras.backend as K
TH_WEIGHTS_PATH = ('https://github.com/titu1994/Wide-Residual-Networks/'
'releases/download/v1.2/wrn_28_8_th_kernels_th_dim_ordering.h5')
TF_WEIGHTS_PATH = ('https://github.com/titu1994/Wide-Residual-Networks/'
'releases/download/v1.2/wrn_28_8_tf_kernels_tf_dim_ordering.h5')
TH_WEIGHTS_PATH_NO_TOP = ('https://github.com/titu1994/Wide-Residual-Networks/releases/'
'download/v1.2/wrn_28_8_th_kernels_th_dim_ordering_no_top.h5')
TF_WEIGHTS_PATH_NO_TOP = ('https://github.com/titu1994/Wide-Residual-Networks/releases/'
'download/v1.2/wrn_28_8_tf_kernels_tf_dim_ordering_no_top.h5')
def WideResidualNetwork(depth=28, width=8, dropout_rate=0.0,
include_top=True, weights='cifar10',
input_tensor=None, input_shape=None,
classes=10, activation='softmax'):
"""Instantiate the Wide Residual Network architecture,
optionally loading weights pre-trained
on CIFAR-10. Note that when using TensorFlow,
for best performance you should set
`image_dim_ordering="tf"` in your Keras config
at ~/.keras/keras.json.
The model and the weights are compatible with both
TensorFlow and Theano. The dimension ordering
convention used by the model is the one
specified in your Keras config file.
# Arguments
depth: number or layers in the DenseNet
width: multiplier to the ResNet width (number of filters)
dropout_rate: dropout rate
include_top: whether to include the fully-connected
layer at the top of the network.
weights: one of `None` (random initialization) or
"cifar10" (pre-training on CIFAR-10)..
input_tensor: optional Keras tensor (i.e. output of `layers.Input()`)
to use as image input for the model.
input_shape: optional shape tuple, only to be specified
if `include_top` is False (otherwise the input shape
has to be `(32, 32, 3)` (with `tf` dim ordering)
or `(3, 32, 32)` (with `th` dim ordering).
It should have exactly 3 inputs channels,
and width and height should be no smaller than 8.
E.g. `(200, 200, 3)` would be one valid value.
classes: optional number of classes to classify images
into, only to be specified if `include_top` is True, and
if no `weights` argument is specified.
# Returns
A Keras model instance.
"""
if weights not in {'cifar10', None}:
raise ValueError('The `weights` argument should be either '
'`None` (random initialization) or `cifar10` '
'(pre-training on CIFAR-10).')
if weights == 'cifar10' and include_top and classes != 10:
raise ValueError('If using `weights` as CIFAR 10 with `include_top`'
' as true, `classes` should be 10')
if (depth - 4) % 6 != 0:
raise ValueError('Depth of the network must be such that (depth - 4)'
'should be divisible by 6.')
# Determine proper input shape
input_shape = _obtain_input_shape(input_shape,
default_size=32,
min_size=8,
data_format=K.image_dim_ordering(),
require_flatten=include_top)
if input_tensor is None:
img_input = Input(shape=input_shape)
else:
if not K.is_keras_tensor(input_tensor):
img_input = Input(tensor=input_tensor, shape=input_shape)
else:
img_input = input_tensor
x = __create_wide_residual_network(classes, img_input, include_top, depth, width,
dropout_rate, activation)
# Ensure that the model takes into account
# any potential predecessors of `input_tensor`.
if input_tensor is not None:
inputs = get_source_inputs(input_tensor)
else:
inputs = img_input
# Create model.
model = Model(inputs, x, name='wide-resnet')
# load weights
if weights == 'cifar10':
if (depth == 28) and (width == 8) and (dropout_rate == 0.0):
# Default parameters match. Weights for this model exist:
if K.image_dim_ordering() == 'th':
if include_top:
h5_file = 'wide_resnet_28_8_th_dim_ordering_th_kernels.h5'
weights_path = get_file(h5_file,
TH_WEIGHTS_PATH,
cache_subdir='models')
else:
h5_file = 'wide_resnet_28_8_th_dim_ordering_th_kernels_no_top.h5'
weights_path = get_file(h5_file,
TH_WEIGHTS_PATH_NO_TOP,
cache_subdir='models')
model.load_weights(weights_path)
if K.backend() == 'tensorflow':
warnings.warn('You are using the TensorFlow backend, yet you '
'are using the Theano '
'image dimension ordering convention '
'(`image_dim_ordering="th"`). '
'For best performance, set '
'`image_dim_ordering="tf"` in '
'your Keras config '
'at ~/.keras/keras.json.')
convert_all_kernels_in_model(model)
else:
if include_top:
h5_file = 'wide_resnet_28_8_tf_dim_ordering_tf_kernels.h5'
weights_path = get_file(h5_file,
TF_WEIGHTS_PATH,
cache_subdir='models')
else:
h5_file = 'wide_resnet_28_8_tf_dim_ordering_tf_kernels_no_top.h5'
weights_path = get_file(h5_file,
TF_WEIGHTS_PATH_NO_TOP,
cache_subdir='models')
model.load_weights(weights_path)
if K.backend() == 'theano':
convert_all_kernels_in_model(model)
return model
def __conv1_block(input):
x = Conv2D(16, (3, 3), padding='same')(input)
channel_axis = 1 if K.image_data_format() == 'channels_first' else -1
x = BatchNormalization(axis=channel_axis)(x)
x = Activation('relu')(x)
return x
def __conv2_block(input, k=1, dropout=0.0):
init = input
channel_axis = 1 if K.image_data_format() == 'channels_first' else -1
# Check if input number of filters is same as 16 * k, else create
# convolution2d for this input
if K.image_data_format() == 'channels_first':
if init._keras_shape[1] != 16 * k:
init = Conv2D(16 * k, (1, 1), activation='linear', padding='same')(init)
else:
if init._keras_shape[-1] != 16 * k:
init = Conv2D(16 * k, (1, 1), activation='linear', padding='same')(init)
x = Conv2D(16 * k, (3, 3), padding='same')(input)
x = BatchNormalization(axis=channel_axis)(x)
x = Activation('relu')(x)
if dropout > 0.0:
x = Dropout(dropout)(x)
x = Conv2D(16 * k, (3, 3), padding='same')(x)
x = BatchNormalization(axis=channel_axis)(x)
x = Activation('relu')(x)
m = add([init, x])
return m
def __conv3_block(input, k=1, dropout=0.0):
init = input
channel_axis = 1 if K.image_data_format() == 'channels_first' else -1
# Check if input number of filters is same as 32 * k, else
# create convolution2d for this input
if K.image_data_format() == 'channels_first':
if init._keras_shape[1] != 32 * k:
init = Conv2D(32 * k, (1, 1), activation='linear', padding='same')(init)
else:
if init._keras_shape[-1] != 32 * k:
init = Conv2D(32 * k, (1, 1), activation='linear', padding='same')(init)
x = Conv2D(32 * k, (3, 3), padding='same')(input)
x = BatchNormalization(axis=channel_axis)(x)
x = Activation('relu')(x)
if dropout > 0.0:
x = Dropout(dropout)(x)
x = Conv2D(32 * k, (3, 3), padding='same')(x)
x = BatchNormalization(axis=channel_axis)(x)
x = Activation('relu')(x)
m = add([init, x])
return m
def ___conv4_block(input, k=1, dropout=0.0):
init = input
channel_axis = 1 if K.image_dim_ordering() == 'th' else -1
# Check if input number of filters is same as 64 * k, else
# create convolution2d for this input
if K.image_dim_ordering() == 'th':
if init._keras_shape[1] != 64 * k:
init = Conv2D(64 * k, (1, 1), activation='linear', padding='same')(init)
else:
if init._keras_shape[-1] != 64 * k:
init = Conv2D(64 * k, (1, 1), activation='linear', padding='same')(init)
x = Conv2D(64 * k, (3, 3), padding='same')(input)
x = BatchNormalization(axis=channel_axis)(x)
x = Activation('relu')(x)
if dropout > 0.0:
x = Dropout(dropout)(x)
x = Conv2D(64 * k, (3, 3), padding='same')(x)
x = BatchNormalization(axis=channel_axis)(x)
x = Activation('relu')(x)
m = add([init, x])
return m
def __create_wide_residual_network(nb_classes, img_input, include_top, depth=28,
width=8, dropout=0.0, activation='softmax'):
''' Creates a Wide Residual Network with specified parameters
Args:
nb_classes: Number of output classes
img_input: Input tensor or layer
include_top: Flag to include the last dense layer
depth: Depth of the network. Compute N = (n - 4) / 6.
For a depth of 16, n = 16, N = (16 - 4) / 6 = 2
For a depth of 28, n = 28, N = (28 - 4) / 6 = 4
For a depth of 40, n = 40, N = (40 - 4) / 6 = 6
width: Width of the network.
dropout: Adds dropout if value is greater than 0.0
Returns:a Keras Model
'''
N = (depth - 4) // 6
x = __conv1_block(img_input)
nb_conv = 4
for i in range(N):
x = __conv2_block(x, width, dropout)
nb_conv += 2
x = MaxPooling2D((2, 2))(x)
for i in range(N):
x = __conv3_block(x, width, dropout)
nb_conv += 2
x = MaxPooling2D((2, 2))(x)
for i in range(N):
x = ___conv4_block(x, width, dropout)
nb_conv += 2
if include_top:
x = GlobalAveragePooling2D()(x)
x = Dense(nb_classes, activation=activation)(x)
return x
| keras-contrib/keras_contrib/applications/wide_resnet.py/0 | {
"file_path": "keras-contrib/keras_contrib/applications/wide_resnet.py",
"repo_id": "keras-contrib",
"token_count": 5694
} | 13 |
#!/usr/bin/env python
# coding=utf-8
"""
This is a script for downloading and converting the pascal voc 2012 dataset
and the berkeley extended version.
# original PASCAL VOC 2012
# 2 GB
# http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar
# berkeley augmented Pascal VOC
# 1.3 GB
# http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/semantic_contours/benchmark.tgz
This can be run as an independent executable to download
the dataset or be imported by scripts used for larger experiments.
If you aren't sure run this to do a full download + conversion setup of the dataset:
./data_pascal_voc.py pascal_voc_setup
""" # pylint: disable=E501
from __future__ import division, print_function, unicode_literals
import os
import shutil
import errno
from sacred import Ingredient, Experiment
from keras.utils import get_file
import skimage.io as io
# ============== Ingredient 2: dataset =======================
data_pascal_voc = Experiment("dataset")
def mkdir_p(path):
# http://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def pascal_segmentation_lut():
"""Return look-up table with number and correspondng class names
for PASCAL VOC segmentation dataset. Two special classes are: 0 -
background and 255 - ambigious region. All others are numerated from
1 to 20.
Returns
-------
classes_lut : dict
look-up table with number and correspondng class names
"""
class_names = ['background', 'aeroplane', 'bicycle', 'bird', 'boat',
'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable',
'dog', 'horse', 'motorbike', 'person', 'potted-plant',
'sheep', 'sofa', 'train', 'tv/monitor', 'ambigious']
enumerated_array = enumerate(class_names[:-1])
classes_lut = list(enumerated_array)
# Add a special class representing ambigious regions
# which has index 255.
classes_lut.append((255, class_names[-1]))
classes_lut = dict(classes_lut)
return classes_lut
def get_pascal_segmentation_images_lists_txts(pascal_root):
"""Return full paths to files in PASCAL VOC with train and val image name lists.
This function returns full paths to files which contain names of images
and respective annotations for the segmentation in PASCAL VOC.
Parameters
----------
pascal_root : string
Full path to the root of PASCAL VOC dataset.
Returns
-------
full_filenames_txts : [string, string, string]
Array that contains paths for train/val/trainval txts with images names.
"""
segmentation_relative_folder = 'ImageSets/Segmentation'
segmentation_folder = os.path.join(pascal_root, segmentation_relative_folder)
pascal_train_list_filename = os.path.join(segmentation_folder, 'train.txt')
pascal_validation_list_filename = os.path.join(segmentation_folder, 'val.txt')
pascal_trainval_list_filename = os.path.join(segmentation_folder, 'trainval.txt')
return [
pascal_train_list_filename,
pascal_validation_list_filename,
pascal_trainval_list_filename
]
def readlines_with_strip(filename):
"""Reads lines from specified file with whitespaced removed on both sides.
The function reads each line in the specified file and applies string.strip()
function to each line which results in removing all whitespaces on both ends
of each string. Also removes the newline symbol which is usually present
after the lines wre read using readlines() function.
Parameters
----------
filename : string
Full path to the root of PASCAL VOC dataset.
Returns
-------
clean_lines : array of strings
Strings that were read from the file and cleaned up.
"""
# Get raw filnames from the file
with open(filename, 'r') as f:
lines = f.readlines()
# Clean filenames from whitespaces and newline symbols
return map(lambda x: x.strip(), lines)
def readlines_with_strip_array_version(filenames_array):
"""The function that is similar to readlines_with_strip() but for filenames array.
Applies readlines_with_strip() to each filename in the array.
Parameters
----------
filenames_array : array of strings
Array of strings. Each specifies a path to a file.
Returns
-------
clean_lines : array of (array of strings)
Strings that were read from the file and cleaned up.
"""
return map(readlines_with_strip, filenames_array)
def add_full_path_and_extention_to_filenames(filenames_array, full_path, extention):
"""Concatenates full path to the left of the image and file extention to the right.
The function accepts array of filenames without fullpath and extention like 'cat'
and adds specified full path and extetion to each of the filenames in the array like
'full/path/to/somewhere/cat.jpg.
Parameters
----------
filenames_array : array of strings
Array of strings representing filenames
full_path : string
Full path string to be added on the left to each filename
extention : string
Extention string to be added on the right to each filename
Returns
-------
full_filenames : array of strings
updated array with filenames
"""
return map(lambda x: os.path.join(full_path, x) + '.' + extention, filenames_array)
def add_full_path_and_extention_to_filenames_array_version(filenames_array_array,
full_path,
extention):
"""Array version of the add_full_path_and_extention_to_filenames() function.
Applies add_full_path_and_extention_to_filenames() to each element of array.
Parameters
----------
filenames_array_array : array of array of strings
Array of strings representing filenames
full_path : string
Full path string to be added on the left to each filename
extention : string
Extention string to be added on the right to each filename
Returns
-------
full_filenames : array of array of strings
updated array of array with filenames
"""
return map(lambda x: add_full_path_and_extention_to_filenames(x,
full_path,
extention),
filenames_array_array)
def get_pascal_segmentation_image_annotation_filenames_pairs(pascal_root):
"""Return (image, annotation) filenames pairs from PASCAL VOC segmentation dataset.
Returns three dimensional array where first dimension represents the type
of the dataset: train, val or trainval in the respective order. Second
dimension represents the a pair of images in that belongs to a particular
dataset. And third one is responsible for the first or second element in the
dataset.
Parameters
----------
pascal_root : string
Path to the PASCAL VOC dataset root that is usually named 'VOC2012'
after being extracted from tar file.
Returns
-------
image_annotation_filename_pairs :
Array with filename pairs.
"""
pascal_relative_images_folder = 'JPEGImages'
pascal_relative_class_annotations_folder = 'SegmentationClass'
images_extention = 'jpg'
annotations_extention = 'png'
pascal_images_folder = os.path.join(
pascal_root, pascal_relative_images_folder)
pascal_class_annotations_folder = os.path.join(
pascal_root, pascal_relative_class_annotations_folder)
pascal_images_lists_txts = get_pascal_segmentation_images_lists_txts(
pascal_root)
pascal_image_names = readlines_with_strip_array_version(
pascal_images_lists_txts)
images_full_names = add_full_path_and_extention_to_filenames_array_version(
pascal_image_names,
pascal_images_folder,
images_extention,
)
annotations_full_names = add_full_path_and_extention_to_filenames_array_version(
pascal_image_names,
pascal_class_annotations_folder,
annotations_extention,
)
# Combine so that we have [(images full filenames, annotation full names), .. ]
# where each element in the array represent train, val, trainval sets.
# Overall, we have 3 elements in the array.
temp = zip(images_full_names, annotations_full_names)
# Now we should combine the elements of images full filenames annotation full names
# so that we have pairs of respective image plus annotation
# [[(pair_1), (pair_1), ..], [(pair_1), (pair_2), ..] ..]
# Overall, we have 3 elements -- representing train/val/trainval datasets
image_annotation_filename_pairs = map(lambda x: zip(*x), temp)
return image_annotation_filename_pairs
@data_pascal_voc.command
def convert_pascal_berkeley_augmented_mat_annotations_to_png(
pascal_berkeley_augmented_root):
""" Creates a new folder in the root folder of the dataset with annotations stored
in .png. The function accepts a full path to the root of Berkeley augmented Pascal
VOC segmentation dataset and converts annotations that are stored in .mat files to
.png files. It creates a new folder dataset/cls_png where all the converted files
will be located. If this directory already exists the function does nothing. The
Berkley augmented dataset can be downloaded from here:
http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/semantic_contours/benchmark.tgz
Parameters
----------
pascal_berkeley_augmented_root : string
Full path to the root of augmented Berkley PASCAL VOC dataset.
""" # pylint: disable=E501
import scipy.io
def read_class_annotation_array_from_berkeley_mat(mat_filename, key='GTcls'):
# Mat to png conversion for
# http://www.cs.berkeley.edu/~bharath2/codes/SBD/download.html
# 'GTcls' key is for class segmentation
# 'GTinst' key is for instance segmentation
# Credit:
# https://github.com/martinkersner/train-DeepLab/blob/master/utils.py
mat = scipy.io.loadmat(mat_filename, mat_dtype=True,
squeeze_me=True, struct_as_record=False)
return mat[key].Segmentation
mat_file_extension_string = '.mat'
png_file_extension_string = '.png'
relative_path_to_annotation_mat_files = 'dataset/cls'
relative_path_to_annotation_png_files = 'dataset/cls_png'
mat_file_extension_string_length = len(mat_file_extension_string)
annotation_mat_files_fullpath = os.path.join(pascal_berkeley_augmented_root,
relative_path_to_annotation_mat_files)
annotation_png_save_fullpath = os.path.join(pascal_berkeley_augmented_root,
relative_path_to_annotation_png_files)
# Create the folder where all the converted png files will be placed
# If the folder already exists, do nothing
if not os.path.exists(annotation_png_save_fullpath):
os.makedirs(annotation_png_save_fullpath)
else:
return
mat_files_names = os.listdir(annotation_mat_files_fullpath)
for current_mat_file_name in mat_files_names:
current_file_name_without_extention = current_mat_file_name[
:-mat_file_extension_string_length]
current_mat_file_full_path = os.path.join(annotation_mat_files_fullpath,
current_mat_file_name)
current_png_file_full_path_to_be_saved = os.path.join(
annotation_png_save_fullpath,
current_file_name_without_extention,
)
current_png_file_full_path_to_be_saved += png_file_extension_string
annotation_array = read_class_annotation_array_from_berkeley_mat(
current_mat_file_full_path)
# TODO: hide 'low-contrast' image warning during saving.
io.imsave(current_png_file_full_path_to_be_saved, annotation_array)
def get_pascal_berkeley_augmented_segmentation_images_lists_txts(pascal_berkeley_root):
"""Return full paths to files in PASCAL Berkley augmented VOC with train and
val image name lists. This function returns full paths to files which contain names
of images and respective annotations for the segmentation in PASCAL VOC.
Parameters
----------
pascal_berkeley_root : string
Full path to the root of PASCAL VOC Berkley augmented dataset.
Returns
-------
full_filenames_txts : [string, string]
Array that contains paths for train/val txts with images names.
"""
segmentation_relative_folder = 'dataset'
segmentation_folder = os.path.join(pascal_berkeley_root,
segmentation_relative_folder)
# TODO: add function that will joing both train.txt and val.txt into
# trainval.txt
pascal_train_list_filename = os.path.join(segmentation_folder,
'train.txt')
pascal_validation_list_filename = os.path.join(segmentation_folder,
'val.txt')
return [
pascal_train_list_filename,
pascal_validation_list_filename
]
def get_pascal_berkeley_augmented_segmentation_image_annotation_filenames_pairs(
pascal_berkeley_root):
"""Return (image, annotation) filenames pairs from PASCAL Berkeley VOC segmentation
dataset. Returns three dimensional array where first dimension represents the type
of the dataset: train, val in the respective order. Second
dimension represents the a pair of images in that belongs to a particular
dataset. And third one is responsible for the first or second element in the
dataset.
Parameters
----------
pascal_berkeley_root : string
Path to the PASCAL Berkeley VOC dataset root that is usually named
'benchmark_RELEASE' after being extracted from tar file.
Returns
-------
image_annotation_filename_pairs :
Array with filename pairs.
"""
pascal_relative_images_folder = 'dataset/img'
pascal_relative_class_annotations_folder = 'dataset/cls_png'
images_extention = 'jpg'
annotations_extention = 'png'
pascal_images_folder = os.path.join(
pascal_berkeley_root, pascal_relative_images_folder)
pascal_class_annotations_folder = os.path.join(
pascal_berkeley_root, pascal_relative_class_annotations_folder)
pascal_images_lists_txts = (
get_pascal_berkeley_augmented_segmentation_images_lists_txts(
pascal_berkeley_root))
pascal_image_names = readlines_with_strip_array_version(
pascal_images_lists_txts)
images_full_names = add_full_path_and_extention_to_filenames_array_version(
pascal_image_names,
pascal_images_folder,
images_extention,
)
annotations_full_names = add_full_path_and_extention_to_filenames_array_version(
pascal_image_names,
pascal_class_annotations_folder,
annotations_extention,
)
# Combine so that we have [(images full filenames, annotation full names), .. ]
# where each element in the array represent train, val, trainval sets.
# Overall, we have 3 elements in the array.
temp = zip(images_full_names, annotations_full_names)
# Now we should combine the elements of images full filenames annotation full names
# so that we have pairs of respective image plus annotation
# [[(pair_1), (pair_1), ..], [(pair_1), (pair_2), ..] ..]
# Overall, we have 3 elements -- representing train/val/trainval datasets
image_annotation_filename_pairs = map(lambda x: zip(*x), temp)
return image_annotation_filename_pairs
def get_pascal_berkeley_augmented_selected_image_annotation_filenames_pairs(
pascal_berkeley_root,
selected_names,
):
"""Returns (image, annotation) filenames pairs from PASCAL Berkeley VOC segmentation
dataset for selected names. The function accepts the selected file names from PASCAL
Berkeley VOC segmentation dataset and returns image, annotation pairs with fullpath
and extention for those names.
Parameters
----------
pascal_berkeley_root : string
Path to the PASCAL Berkeley VOC dataset root that is usually named
'benchmark_RELEASE' after being extracted from tar file.
selected_names : array of strings
Selected filenames from PASCAL VOC Berkeley that can be read from txt files that
come with dataset.
Returns
-------
image_annotation_pairs :
Array with filename pairs with fullnames.
"""
pascal_relative_images_folder = 'dataset/img'
pascal_relative_class_annotations_folder = 'dataset/cls_png'
images_extention = 'jpg'
annotations_extention = 'png'
pascal_images_folder = os.path.join(
pascal_berkeley_root, pascal_relative_images_folder)
pascal_class_annotations_folder = os.path.join(
pascal_berkeley_root, pascal_relative_class_annotations_folder)
images_full_names = add_full_path_and_extention_to_filenames(
selected_names,
pascal_images_folder,
images_extention,
)
annotations_full_names = add_full_path_and_extention_to_filenames(
selected_names,
pascal_class_annotations_folder,
annotations_extention,
)
image_annotation_pairs = zip(images_full_names,
annotations_full_names)
return image_annotation_pairs
def get_pascal_selected_image_annotation_filenames_pairs(pascal_root, selected_names):
"""Returns (image, annotation) filenames pairs from PASCAL VOC segmentation dataset
for selected names. The function accepts the selected file names from PASCAL VOC
segmentation dataset and returns image, annotation pairs with fullpath and extention
for those names.
Parameters
----------
pascal_root : string
Path to the PASCAL VOC dataset root that is usually named 'VOC2012'
after being extracted from tar file.
selected_names : array of strings
Selected filenames from PASCAL VOC that can be read from txt files that
come with dataset.
Returns
-------
image_annotation_pairs :
Array with filename pairs with fullnames.
"""
pascal_relative_images_folder = 'JPEGImages'
pascal_relative_class_annotations_folder = 'SegmentationClass'
images_extention = 'jpg'
annotations_extention = 'png'
pascal_images_folder = os.path.join(
pascal_root, pascal_relative_images_folder)
pascal_class_annotations_folder = os.path.join(
pascal_root, pascal_relative_class_annotations_folder)
images_full_names = add_full_path_and_extention_to_filenames(selected_names,
pascal_images_folder,
images_extention)
annotations_full_names = add_full_path_and_extention_to_filenames(
selected_names,
pascal_class_annotations_folder,
annotations_extention,
)
image_annotation_pairs = zip(images_full_names,
annotations_full_names)
return image_annotation_pairs
def get_augmented_pascal_image_annotation_filename_pairs(pascal_root,
pascal_berkeley_root,
mode=2):
"""Returns image/annotation filenames pairs train/val splits from combined Pascal
VOC. Returns two arrays with train and validation split respectively that has
image full filename/ annotation full filename pairs in each of the that were derived
from PASCAL and PASCAL Berkeley Augmented dataset. The Berkley augmented dataset
can be downloaded from here:
http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/semantic_contours/benchmark.tgz
Consider running convert_pascal_berkeley_augmented_mat_annotations_to_png() after
extraction.
The PASCAL VOC dataset can be downloaded from here:
http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar
Consider specifying root full names for both of them as arguments for this function
after extracting them.
The function has three type of train/val splits(credit matconvnet-fcn):
Let BT, BV, PT, PV, and PX be the Berkeley training and validation
sets and PASCAL segmentation challenge training, validation, and
test sets. Let T, V, X the final trainig, validation, and test
sets.
Mode 1::
V = PV (same validation set as PASCAL)
Mode 2:: (default))
V = PV \ BT (PASCAL val set that is not a Berkeley training
image)
Mode 3::
V = PV \ (BV + BT)
In all cases:
S = PT + PV + BT + BV
X = PX (the test set is uncahgend)
T = (S \ V) \ X (the rest is training material)
Parameters
----------
pascal_root : string
Path to the PASCAL VOC dataset root that is usually named 'VOC2012'
after being extracted from tar file.
pascal_berkeley_root : string
Path to the PASCAL Berkeley VOC dataset root that is usually named
'benchmark_RELEASE' after being extracted from tar file.
mode: int
The type of train/val data split. Read the function main description for more
info.
Returns
-------
image_annotation_pairs : Array with filename pairs with fullnames.
[[(str, str), .. , (str, str)][(str, str), .., (str, str)]]
""" # pylint: disable=E501
pascal_txts = get_pascal_segmentation_images_lists_txts(
pascal_root=pascal_root)
berkeley_txts = get_pascal_berkeley_augmented_segmentation_images_lists_txts(
pascal_berkeley_root=pascal_berkeley_root)
pascal_name_lists = readlines_with_strip_array_version(pascal_txts)
berkeley_name_lists = readlines_with_strip_array_version(berkeley_txts)
pascal_train_name_set, pascal_val_name_set, _ = map(
lambda x: set(x), pascal_name_lists)
berkeley_train_name_set, berkeley_val_name_set = map(
lambda x: set(x), berkeley_name_lists)
all_berkeley = berkeley_train_name_set | berkeley_val_name_set
all_pascal = pascal_train_name_set | pascal_val_name_set
everything = all_berkeley | all_pascal
# Extract the validation subset based on selected mode
if mode == 1:
# 1449 validation images, 10582 training images
validation = pascal_val_name_set
if mode == 2:
# 904 validatioin images, 11127 training images
validation = pascal_val_name_set - berkeley_train_name_set
if mode == 3:
# 346 validation images, 11685 training images
validation = pascal_val_name_set - all_berkeley
# The rest of the dataset is for training
train = everything - validation
# Get the part that can be extracted from berkeley
train_from_berkeley = train & all_berkeley
# The rest of the data will be loaded from pascal
train_from_pascal = train - train_from_berkeley
train_from_berkeley_image_annotation_pairs = (
get_pascal_berkeley_augmented_selected_image_annotation_filenames_pairs(
pascal_berkeley_root,
list(train_from_berkeley)))
train_from_pascal_image_annotation_pairs = \
get_pascal_selected_image_annotation_filenames_pairs(pascal_root,
list(train_from_pascal))
overall_train_image_annotation_filename_pairs = \
list(train_from_berkeley_image_annotation_pairs) + \
list(train_from_pascal_image_annotation_pairs)
overall_val_image_annotation_filename_pairs = \
get_pascal_selected_image_annotation_filenames_pairs(pascal_root,
validation)
return (overall_train_image_annotation_filename_pairs,
overall_val_image_annotation_filename_pairs)
def pascal_filename_pairs_to_imageset_txt(voc_imageset_txt_path, filename_pairs,
image_extension='.jpg'):
with open(voc_imageset_txt_path, 'w') as txtfile:
[txtfile.write(os.path.splitext(os.path.basename(file1))[0] + '\n')
for file1, file2 in filename_pairs if file1.endswith(image_extension)]
def pascal_combine_annotation_files(filename_pairs, output_annotations_path):
mkdir_p(output_annotations_path)
for img_path, gt_path in filename_pairs:
shutil.copy2(gt_path, output_annotations_path)
@data_pascal_voc.config
def voc_config():
# TODO(ahundt) add md5 sums for each file
verbose = True
dataset_root = os.path.join(os.path.expanduser("~"), '.keras', 'datasets')
dataset_path = dataset_root + '/VOC2012'
# sys.path.append("tf-image-segmentation/")
# os.environ["CUDA_VISIBLE_DEVICES"] = '1'
# based on https://github.com/martinkersner/train-DeepLab
# original PASCAL VOC 2012
# wget
# http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar
# # 2 GB
pascal_root = dataset_path + '/VOCdevkit/VOC2012'
# berkeley augmented Pascal VOC
# wget
# http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/semantic_contours/benchmark.tgz
# # 1.3 GB
# Pascal Context
# http://www.cs.stanford.edu/~roozbeh/pascal-context/
# http://www.cs.stanford.edu/~roozbeh/pascal-context/trainval.tar.gz
pascal_berkeley_root = dataset_path + '/benchmark_RELEASE'
urls = [
'http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar',
'http://www.eecs.berkeley.edu/Research/Projects/'
'CS/vision/grouping/semantic_contours/benchmark.tgz',
'http://www.cs.stanford.edu/~roozbeh/pascal-context/trainval.tar.gz',
'http://www.cs.stanford.edu/~roozbeh/pascal-context/33_context_labels.tar.gz',
'http://www.cs.stanford.edu/~roozbeh/pascal-context/59_context_labels.tar.gz',
'http://www.cs.stanford.edu/~roozbeh/pascal-context/33_labels.txt',
'http://www.cs.stanford.edu/~roozbeh/pascal-context/59_labels.txt'
]
filenames = ['VOCtrainval_11-May-2012.tar',
'benchmark.tgz',
'trainval.tar.gz',
'33_context_labels.tar.gz',
'59_context_labels.tar.gz',
'33_labels.txt',
'59_labels.txt'
]
md5s = ['6cd6e144f989b92b3379bac3b3de84fd',
'82b4d87ceb2ed10f6038a1cba92111cb',
'df034edb2c12aa7d33b42b20bb1796e3',
'180101cfc01c71867b6686207f071eb9',
'f85d450010762a0e1080304286ce30ed',
'8840f5439b471aecf991ac6448b826e6',
'993901f2d930cc038c406845f08fa082']
combined_imageset_train_txt = dataset_path + '/combined_imageset_train.txt'
combined_imageset_val_txt = dataset_path + '/combined_imageset_val.txt'
combined_annotations_path = dataset_path + '/combined_annotations'
# see get_augmented_pascal_image_annotation_filename_pairs()
voc_data_subset_mode = 2
@data_pascal_voc.capture
def pascal_voc_files(dataset_path, filenames, dataset_root, urls, md5s):
print(dataset_path)
print(dataset_root)
print(urls)
print(filenames)
print(md5s)
return [dataset_path + filename for filename in filenames]
@data_pascal_voc.command
def pascal_voc_download(dataset_path, filenames, dataset_root, urls, md5s):
zip_paths = pascal_voc_files(
dataset_path, filenames, dataset_root, urls, md5s)
for url, filename, md5 in zip(urls, filenames, md5s):
path = get_file(filename, url, md5_hash=md5,
extract=True, cache_subdir=dataset_path)
@data_pascal_voc.command
def pascal_voc_berkeley_combined(dataset_path,
pascal_root,
pascal_berkeley_root,
voc_data_subset_mode,
combined_imageset_train_txt,
combined_imageset_val_txt,
combined_annotations_path):
# Returns a list of (image, annotation)
# filename pairs (filename.jpg, filename.png)
overall_train_image_annotation_filename_pairs, \
overall_val_image_annotation_filename_pairs = \
get_augmented_pascal_image_annotation_filename_pairs(
pascal_root=pascal_root,
pascal_berkeley_root=pascal_berkeley_root,
mode=voc_data_subset_mode)
# combine the annotation files into one folder
pascal_combine_annotation_files(
list(overall_train_image_annotation_filename_pairs) +
list(overall_val_image_annotation_filename_pairs),
combined_annotations_path)
# generate the train imageset txt
pascal_filename_pairs_to_imageset_txt(
combined_imageset_train_txt,
overall_train_image_annotation_filename_pairs
)
# generate the val imageset txt
pascal_filename_pairs_to_imageset_txt(
combined_imageset_val_txt,
overall_val_image_annotation_filename_pairs
)
@data_pascal_voc.command
def pascal_voc_setup(filenames, dataset_path, pascal_root,
pascal_berkeley_root, dataset_root,
voc_data_subset_mode,
urls, md5s,
combined_imageset_train_txt,
combined_imageset_val_txt,
combined_annotations_path):
# download the dataset
pascal_voc_download(dataset_path, filenames,
dataset_root, urls, md5s)
# convert the relevant files to a more useful format
convert_pascal_berkeley_augmented_mat_annotations_to_png(
pascal_berkeley_root)
pascal_voc_berkeley_combined(dataset_path,
pascal_root,
pascal_berkeley_root,
voc_data_subset_mode,
combined_imageset_train_txt,
combined_imageset_val_txt,
combined_annotations_path)
@data_pascal_voc.automain
def main(filenames, dataset_path, pascal_root,
pascal_berkeley_root, dataset_root,
voc_data_subset_mode,
urls, md5s,
combined_imageset_train_txt,
combined_imageset_val_txt,
combined_annotations_path):
voc_config()
pascal_voc_setup(filenames, dataset_path, pascal_root,
pascal_berkeley_root, dataset_root,
voc_data_subset_mode,
urls, md5s,
combined_imageset_train_txt,
combined_imageset_val_txt,
combined_annotations_path)
| keras-contrib/keras_contrib/datasets/pascal_voc.py/0 | {
"file_path": "keras-contrib/keras_contrib/datasets/pascal_voc.py",
"repo_id": "keras-contrib",
"token_count": 12911
} | 14 |
from keras.layers import Layer, InputSpec
from keras import initializers, regularizers, constraints
from keras import backend as K
from keras_contrib import backend as KC
class GroupNormalization(Layer):
"""Group normalization layer.
Group Normalization divides the channels into groups and computes
within each group
the mean and variance for normalization.
Group Normalization's computation is independent
of batch sizes, and its accuracy is stable in a wide range of batch sizes.
Relation to Layer Normalization:
If the number of groups is set to 1, then this operation becomes identical to
Layer Normalization.
Relation to Instance Normalization:
If the number of groups is set to the
input dimension (number of groups is equal
to number of channels), then this operation becomes
identical to Instance Normalization.
# Arguments
groups: Integer, the number of groups for Group Normalization.
Can be in the range [1, N] where N is the input dimension.
The input dimension must be divisible by the number of groups.
axis: Integer, the axis that should be normalized
(typically the features axis).
For instance, after a `Conv2D` layer with
`data_format="channels_first"`,
set `axis=1` in `BatchNormalization`.
epsilon: Small float added to variance to avoid dividing by zero.
center: If True, add offset of `beta` to normalized tensor.
If False, `beta` is ignored.
scale: If True, multiply by `gamma`.
If False, `gamma` is not used.
When the next layer is linear (also e.g. `nn.relu`),
this can be disabled since the scaling
will be done by the next layer.
beta_initializer: Initializer for the beta weight.
gamma_initializer: Initializer for the gamma weight.
beta_regularizer: Optional regularizer for the beta weight.
gamma_regularizer: Optional regularizer for the gamma weight.
beta_constraint: Optional constraint for the beta weight.
gamma_constraint: Optional constraint for the gamma weight.
# Input shape
Arbitrary. Use the keyword argument `input_shape`
(tuple of integers, does not include the samples axis)
when using this layer as the first layer in a model.
# Output shape
Same shape as input.
# References
- [Group Normalization](https://arxiv.org/abs/1803.08494)
"""
def __init__(self,
groups=32,
axis=-1,
epsilon=1e-5,
center=True,
scale=True,
beta_initializer='zeros',
gamma_initializer='ones',
beta_regularizer=None,
gamma_regularizer=None,
beta_constraint=None,
gamma_constraint=None,
**kwargs):
super(GroupNormalization, self).__init__(**kwargs)
self.supports_masking = True
self.groups = groups
self.axis = axis
self.epsilon = epsilon
self.center = center
self.scale = scale
self.beta_initializer = initializers.get(beta_initializer)
self.gamma_initializer = initializers.get(gamma_initializer)
self.beta_regularizer = regularizers.get(beta_regularizer)
self.gamma_regularizer = regularizers.get(gamma_regularizer)
self.beta_constraint = constraints.get(beta_constraint)
self.gamma_constraint = constraints.get(gamma_constraint)
def build(self, input_shape):
dim = input_shape[self.axis]
if dim is None:
raise ValueError('Axis ' + str(self.axis) + ' of '
'input tensor should have a defined dimension '
'but the layer received an input with shape ' +
str(input_shape) + '.')
if dim < self.groups:
raise ValueError('Number of groups (' + str(self.groups) + ') cannot be '
'more than the number of channels (' +
str(dim) + ').')
if dim % self.groups != 0:
raise ValueError('Number of groups (' + str(self.groups) + ') must be a '
'multiple of the number of channels (' +
str(dim) + ').')
self.input_spec = InputSpec(ndim=len(input_shape),
axes={self.axis: dim})
shape = (dim,)
if self.scale:
self.gamma = self.add_weight(shape=shape,
name='gamma',
initializer=self.gamma_initializer,
regularizer=self.gamma_regularizer,
constraint=self.gamma_constraint)
else:
self.gamma = None
if self.center:
self.beta = self.add_weight(shape=shape,
name='beta',
initializer=self.beta_initializer,
regularizer=self.beta_regularizer,
constraint=self.beta_constraint)
else:
self.beta = None
self.built = True
def call(self, inputs, **kwargs):
input_shape = K.int_shape(inputs)
tensor_input_shape = K.shape(inputs)
# Prepare broadcasting shape.
reduction_axes = list(range(len(input_shape)))
del reduction_axes[self.axis]
broadcast_shape = [1] * len(input_shape)
broadcast_shape[self.axis] = input_shape[self.axis] // self.groups
broadcast_shape.insert(1, self.groups)
reshape_group_shape = K.shape(inputs)
group_axes = [reshape_group_shape[i] for i in range(len(input_shape))]
group_axes[self.axis] = input_shape[self.axis] // self.groups
group_axes.insert(1, self.groups)
# reshape inputs to new group shape
group_shape = [group_axes[0], self.groups] + group_axes[2:]
group_shape = K.stack(group_shape)
inputs = K.reshape(inputs, group_shape)
group_reduction_axes = list(range(len(group_axes)))
mean, variance = KC.moments(inputs, group_reduction_axes[2:],
keep_dims=True)
inputs = (inputs - mean) / (K.sqrt(variance + self.epsilon))
# prepare broadcast shape
inputs = K.reshape(inputs, group_shape)
outputs = inputs
# In this case we must explicitly broadcast all parameters.
if self.scale:
broadcast_gamma = K.reshape(self.gamma, broadcast_shape)
outputs = outputs * broadcast_gamma
if self.center:
broadcast_beta = K.reshape(self.beta, broadcast_shape)
outputs = outputs + broadcast_beta
# finally we reshape the output back to the input shape
outputs = K.reshape(outputs, tensor_input_shape)
return outputs
def get_config(self):
config = {
'groups': self.groups,
'axis': self.axis,
'epsilon': self.epsilon,
'center': self.center,
'scale': self.scale,
'beta_initializer': initializers.serialize(self.beta_initializer),
'gamma_initializer': initializers.serialize(self.gamma_initializer),
'beta_regularizer': regularizers.serialize(self.beta_regularizer),
'gamma_regularizer': regularizers.serialize(self.gamma_regularizer),
'beta_constraint': constraints.serialize(self.beta_constraint),
'gamma_constraint': constraints.serialize(self.gamma_constraint)
}
base_config = super(GroupNormalization, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
def compute_output_shape(self, input_shape):
return input_shape
| keras-contrib/keras_contrib/layers/normalization/groupnormalization.py/0 | {
"file_path": "keras-contrib/keras_contrib/layers/normalization/groupnormalization.py",
"repo_id": "keras-contrib",
"token_count": 3639
} | 15 |
import numpy as np
from keras import backend as K
def get_standard_values():
'''
These are just a set of floats used for testing the activation
functions, and are useful in multiple tests.
'''
return np.array([[0, 0.1, 0.5, 0.9, 1.0]], dtype=K.floatx())
def validate_activation(activation):
activation(get_standard_values())
| keras-contrib/keras_contrib/tests/activations.py/0 | {
"file_path": "keras-contrib/keras_contrib/tests/activations.py",
"repo_id": "keras-contrib",
"token_count": 123
} | 16 |
import pytest
import numpy as np
import sys
if sys.version_info > (3, 0):
from io import StringIO
else:
from StringIO import StringIO
from keras_contrib import callbacks
from keras.models import Sequential, Model
from keras.layers import Input, Dense, Conv2D, Flatten, Activation
from keras import backend as K
n_out = 11
# with 1 neuron dead, 1/11 is just below the threshold of 10% with verbose = False
def check_print(do_train, expected_warnings, nr_dead=None, perc_dead=None):
"""
Receive stdout to check if correct warning message is delivered
:param nr_dead: int
:param perc_dead: float, 10% should be written as 0.1
"""
saved_stdout = sys.stdout
out = StringIO()
out.flush()
sys.stdout = out # overwrite current stdout
do_train()
# get prints, can be something like: "Layer
# dense (#0) has 2 dead neurons (20.00%)!"
stdoutput = out.getvalue().strip()
str_to_count = "dead neurons"
count = stdoutput.count(str_to_count)
sys.stdout = saved_stdout # restore stdout
out.close()
assert expected_warnings == count
if expected_warnings and (nr_dead is not None):
str_to_check = 'has {} dead'.format(nr_dead)
assert str_to_check in stdoutput, '"{}" not in "{}"'.format(str_to_check,
stdoutput)
if expected_warnings and (perc_dead is not None):
str_to_check = 'neurons ({:.2%})!'.format(perc_dead)
assert str_to_check in stdoutput, '"{}" not in "{}"'.format(str_to_check,
stdoutput)
def test_DeadDeadReluDetector():
n_samples = 9
input_shape = (n_samples, 3, 4) # 4 input features
shape_out = (n_samples, 3, n_out) # 11 output features
shape_weights = (4, n_out)
# ignore batch size
input_shape_dense = tuple(input_shape[1:])
def do_test(weights, expected_warnings, verbose, nr_dead=None, perc_dead=None):
def do_train():
dataset = np.ones(input_shape) # data to be fed as training
model = Sequential()
model.add(Dense(n_out, activation='relu', input_shape=input_shape_dense,
use_bias=False, weights=[weights], name='dense'))
model.compile(optimizer='sgd', loss='categorical_crossentropy')
model.fit(
dataset,
np.ones(shape_out),
batch_size=1,
epochs=1,
callbacks=[callbacks.DeadReluDetector(dataset, verbose=verbose)],
verbose=False
)
check_print(do_train, expected_warnings, nr_dead, perc_dead)
# weights that correspond to NN with 1/11 neurons dead
weights_1_dead = np.ones(shape_weights)
# weights that correspond to NN with 2/11 neurons dead
weights_2_dead = np.ones(shape_weights)
# weights that correspond to all neurons dead
weights_all_dead = np.zeros(shape_weights)
weights_1_dead[:, 0] = 0
weights_2_dead[:, 0:2] = 0
do_test(weights_1_dead, verbose=True,
expected_warnings=1, nr_dead=1, perc_dead=1. / n_out)
do_test(weights_1_dead, verbose=False, expected_warnings=0)
do_test(weights_2_dead, verbose=True,
expected_warnings=1, nr_dead=2, perc_dead=2. / n_out)
# do_test(weights_all_dead, verbose=True, expected_warnings=1,
# nr_dead=n_out, perc_dead=1.)
def test_DeadDeadReluDetector_bias():
n_samples = 9
input_shape = (n_samples, 4) # 4 input features
shape_weights = (4, n_out)
shape_bias = (n_out, )
shape_out = (n_samples, n_out) # 11 output features
# ignore batch size
input_shape_dense = tuple(input_shape[1:])
def do_test(weights, bias, expected_warnings, verbose,
nr_dead=None, perc_dead=None):
def do_train():
dataset = np.ones(input_shape) # data to be fed as training
model = Sequential()
model.add(Dense(n_out, activation='relu', input_shape=input_shape_dense,
use_bias=True, weights=[weights, bias], name='dense'))
model.compile(optimizer='sgd', loss='categorical_crossentropy')
model.fit(
dataset,
np.ones(shape_out),
batch_size=1,
epochs=1,
callbacks=[callbacks.DeadReluDetector(dataset, verbose=verbose)],
verbose=False
)
check_print(do_train, expected_warnings, nr_dead, perc_dead)
# weights that correspond to NN with 1/11 neurons dead
weights_1_dead = np.ones(shape_weights)
# weights that correspond to NN with 2/11 neurons dead
weights_2_dead = np.ones(shape_weights)
# weights that correspond to all neurons dead
weights_all_dead = np.zeros(shape_weights)
weights_1_dead[:, 0] = 0
weights_2_dead[:, 0:2] = 0
bias = np.zeros(shape_bias)
do_test(weights_1_dead, bias, verbose=True, expected_warnings=1,
nr_dead=1, perc_dead=1. / n_out)
do_test(weights_1_dead, bias, verbose=False, expected_warnings=0)
do_test(weights_2_dead, bias, verbose=True, expected_warnings=1,
nr_dead=2, perc_dead=2. / n_out)
# do_test(weights_all_dead, bias, verbose=True,
# expected_warnings=1, nr_dead=n_out, perc_dead=1.)
def test_DeadDeadReluDetector_conv():
n_samples = 9
# (5, 5) kernel, 4 input featuremaps and 11 output featuremaps
if K.image_data_format() == 'channels_last':
input_shape = (n_samples, 5, 5, 4)
else:
input_shape = (n_samples, 4, 5, 5)
# ignore batch size
input_shape_conv = tuple(input_shape[1:])
shape_weights = (5, 5, 4, n_out)
shape_out = (n_samples, n_out)
def do_test(weights_bias, expected_warnings, verbose,
nr_dead=None, perc_dead=None):
"""
:param perc_dead: as float, 10% should be written as 0.1
"""
def do_train():
dataset = np.ones(input_shape) # data to be fed as training
model = Sequential()
model.add(Conv2D(n_out, (5, 5), activation='relu',
input_shape=input_shape_conv,
use_bias=True, weights=weights_bias, name='conv'))
model.add(Flatten()) # to handle Theano's categorical crossentropy
model.compile(optimizer='sgd', loss='categorical_crossentropy')
model.fit(
dataset,
np.ones(shape_out),
batch_size=1,
epochs=1,
callbacks=[callbacks.DeadReluDetector(dataset, verbose=verbose)],
verbose=False
)
check_print(do_train, expected_warnings, nr_dead, perc_dead)
# weights that correspond to NN with 1/11 neurons dead
weights_1_dead = np.ones(shape_weights)
weights_1_dead[..., 0] = 0
# weights that correspond to NN with 2/11 neurons dead
weights_2_dead = np.ones(shape_weights)
weights_2_dead[..., 0:2] = 0
# weights that correspond to NN with all neurons dead
weights_all_dead = np.zeros(shape_weights)
bias = np.zeros((11, ))
weights_bias_1_dead = [weights_1_dead, bias]
weights_bias_2_dead = [weights_2_dead, bias]
weights_bias_all_dead = [weights_all_dead, bias]
do_test(weights_bias_1_dead, verbose=True, expected_warnings=1,
nr_dead=1, perc_dead=1. / n_out)
do_test(weights_bias_1_dead, verbose=False, expected_warnings=0)
do_test(weights_bias_2_dead, verbose=True, expected_warnings=1,
nr_dead=2, perc_dead=2. / n_out)
# do_test(weights_bias_all_dead, verbose=True, expected_warnings=1,
# nr_dead=n_out, perc_dead=1.)
def test_DeadDeadReluDetector_activation():
"""
Tests that using "Activation" layer does not throw error
"""
input_data = Input(shape=(1,))
output_data = Activation('relu')(input_data)
model = Model(input_data, output_data)
model.compile(optimizer='adadelta', loss='binary_crossentropy')
model.fit(
np.array([[1]]),
np.array([[1]]),
epochs=1,
validation_data=(np.array([[1]]), np.array([[1]])),
callbacks=[callbacks.DeadReluDetector(np.array([[1]]))]
)
if __name__ == '__main__':
pytest.main([__file__])
| keras-contrib/tests/keras_contrib/callbacks/dead_relu_detector_test.py/0 | {
"file_path": "keras-contrib/tests/keras_contrib/callbacks/dead_relu_detector_test.py",
"repo_id": "keras-contrib",
"token_count": 3859
} | 17 |
import pytest
import numpy as np
from keras_contrib.utils.test_utils import is_tf_keras
from numpy.testing import assert_allclose
from keras.layers import Conv2D
from keras.models import Sequential
from keras.optimizers import Adam
from keras.losses import sparse_categorical_crossentropy
from keras import backend as K
from keras_contrib.losses import DSSIMObjective
allobj = []
def test_objective_shapes_3d():
y_a = K.variable(np.random.random((5, 6, 7)))
y_b = K.variable(np.random.random((5, 6, 7)))
for obj in allobj:
objective_output = obj(y_a, y_b)
assert K.eval(objective_output).shape == (5, 6)
def test_objective_shapes_2d():
y_a = K.variable(np.random.random((6, 7)))
y_b = K.variable(np.random.random((6, 7)))
for obj in allobj:
objective_output = obj(y_a, y_b)
assert K.eval(objective_output).shape == (6,)
def test_cce_one_hot():
y_a = K.variable(np.random.randint(0, 7, (5, 6)))
y_b = K.variable(np.random.random((5, 6, 7)))
objective_output = sparse_categorical_crossentropy(y_a, y_b)
assert K.eval(objective_output).shape == (5, 6)
y_a = K.variable(np.random.randint(0, 7, (6,)))
y_b = K.variable(np.random.random((6, 7)))
assert K.eval(sparse_categorical_crossentropy(y_a, y_b)).shape == (6,)
def test_DSSIM_channels_last():
prev_data = K.image_data_format()
K.set_image_data_format('channels_last')
for input_dim, kernel_size in zip([32, 33], [2, 3]):
input_shape = [input_dim, input_dim, 3]
X = np.random.random_sample(4 * input_dim * input_dim * 3)
X = X.reshape([4] + input_shape)
y = np.random.random_sample(4 * input_dim * input_dim * 3)
y = y.reshape([4] + input_shape)
model = Sequential()
model.add(Conv2D(32, (3, 3), padding='same', input_shape=input_shape,
activation='relu'))
model.add(Conv2D(3, (3, 3), padding='same', input_shape=input_shape,
activation='relu'))
adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8)
model.compile(loss=DSSIMObjective(kernel_size=kernel_size),
metrics=['mse'],
optimizer=adam)
model.fit(X, y, batch_size=2, epochs=1, shuffle='batch')
# Test same
x1 = K.constant(X, 'float32')
x2 = K.constant(X, 'float32')
dssim = DSSIMObjective(kernel_size=kernel_size)
assert_allclose(0.0, K.eval(dssim(x1, x2)), atol=1e-4)
# Test opposite
x1 = K.zeros([4] + input_shape)
x2 = K.ones([4] + input_shape)
dssim = DSSIMObjective(kernel_size=kernel_size)
assert_allclose(0.5, K.eval(dssim(x1, x2)), atol=1e-4)
K.set_image_data_format(prev_data)
@pytest.mark.xfail(is_tf_keras,
reason='TODO fix this.',
strict=True)
def test_DSSIM_channels_first():
prev_data = K.image_data_format()
K.set_image_data_format('channels_first')
for input_dim, kernel_size in zip([32, 33], [2, 3]):
input_shape = [3, input_dim, input_dim]
X = np.random.random_sample(4 * input_dim * input_dim * 3)
X = X.reshape([4] + input_shape)
y = np.random.random_sample(4 * input_dim * input_dim * 3)
y = y.reshape([4] + input_shape)
model = Sequential()
model.add(Conv2D(32, (3, 3), padding='same', input_shape=input_shape,
activation='relu'))
model.add(Conv2D(3, (3, 3), padding='same', input_shape=input_shape,
activation='relu'))
adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8)
model.compile(loss=DSSIMObjective(kernel_size=kernel_size), metrics=['mse'],
optimizer=adam)
model.fit(X, y, batch_size=2, epochs=1, shuffle='batch')
# Test same
x1 = K.constant(X, 'float32')
x2 = K.constant(X, 'float32')
dssim = DSSIMObjective(kernel_size=kernel_size)
assert_allclose(0.0, K.eval(dssim(x1, x2)), atol=1e-4)
# Test opposite
x1 = K.zeros([4] + input_shape)
x2 = K.ones([4] + input_shape)
dssim = DSSIMObjective(kernel_size=kernel_size)
assert_allclose(0.5, K.eval(dssim(x1, x2)), atol=1e-4)
K.set_image_data_format(prev_data)
if __name__ == '__main__':
pytest.main([__file__])
| keras-contrib/tests/keras_contrib/losses/dssim_test.py/0 | {
"file_path": "keras-contrib/tests/keras_contrib/losses/dssim_test.py",
"repo_id": "keras-contrib",
"token_count": 2144
} | 18 |
"""Benchmark activation layers.
To run benchmarks, see the following command for an example, please change the
flag to your custom value:
```
python3 -m benchmarks.layer_benchmark.activation_benchmark \
--benchmark_name=benchmark_elu \
--num_samples=2048 \
--batch_size=256 \
--jit_compile=True
```
"""
from absl import app
from absl import flags
from benchmarks.layer_benchmark.base_benchmark import LayerBenchmark
FLAGS = flags.FLAGS
def benchmark_elu(
num_samples,
batch_size,
jit_compile=True,
):
layer_name = "ELU"
init_args = {}
benchmark = LayerBenchmark(
layer_name,
init_args,
input_shape=[256, 256],
jit_compile=jit_compile,
)
benchmark.benchmark_predict(
num_samples=num_samples,
batch_size=batch_size,
)
benchmark.benchmark_train(
num_samples=num_samples,
batch_size=batch_size,
)
def benchmark_prelu(
num_samples,
batch_size,
jit_compile=True,
):
layer_name = "PReLU"
init_args = {}
benchmark = LayerBenchmark(
layer_name,
init_args,
input_shape=[256, 256],
jit_compile=jit_compile,
)
benchmark.benchmark_predict(
num_samples=num_samples,
batch_size=batch_size,
)
benchmark.benchmark_train(
num_samples=num_samples,
batch_size=batch_size,
)
def benchmark_relu(
num_samples,
batch_size,
jit_compile=True,
):
layer_name = "ReLU"
init_args = {}
benchmark = LayerBenchmark(
layer_name,
init_args,
input_shape=[256, 256],
jit_compile=jit_compile,
)
benchmark.benchmark_predict(
num_samples=num_samples,
batch_size=batch_size,
)
benchmark.benchmark_train(
num_samples=num_samples,
batch_size=batch_size,
)
def benchmark_leaky_relu(
num_samples,
batch_size,
jit_compile=True,
):
layer_name = "LeakyReLU"
init_args = {}
benchmark = LayerBenchmark(
layer_name,
init_args,
input_shape=[256, 256],
jit_compile=jit_compile,
)
benchmark.benchmark_predict(
num_samples=num_samples,
batch_size=batch_size,
)
benchmark.benchmark_train(
num_samples=num_samples,
batch_size=batch_size,
)
def benchmark_softmax(
num_samples,
batch_size,
jit_compile=True,
):
layer_name = "Softmax"
init_args = {}
benchmark = LayerBenchmark(
layer_name,
init_args,
input_shape=[256, 256],
jit_compile=jit_compile,
)
benchmark.benchmark_predict(
num_samples=num_samples,
batch_size=batch_size,
)
benchmark.benchmark_train(
num_samples=num_samples,
batch_size=batch_size,
)
BENCHMARK_NAMES = {
"benchmark_elu": benchmark_elu,
"benchmark_relu": benchmark_relu,
"benchmark_leaky_relu": benchmark_leaky_relu,
"benchmark_prelu": benchmark_prelu,
"benchmark_softmax": benchmark_softmax,
}
def main(_):
benchmark_name = FLAGS.benchmark_name
num_samples = FLAGS.num_samples
batch_size = FLAGS.batch_size
jit_compile = FLAGS.jit_compile
if benchmark_name is None:
for name, benchmark_fn in BENCHMARK_NAMES.items():
benchmark_fn(num_samples, batch_size, jit_compile)
return
if benchmark_name not in BENCHMARK_NAMES:
raise ValueError(
f"Invalid benchmark name: {benchmark_name}, `benchmark_name` must "
f"be one of {BENCHMARK_NAMES.keys()}"
)
benchmark_fn = BENCHMARK_NAMES[benchmark_name]
benchmark_fn(num_samples, batch_size, jit_compile)
if __name__ == "__main__":
app.run(main)
| keras-core/benchmarks/layer_benchmark/activation_benchmark.py/0 | {
"file_path": "keras-core/benchmarks/layer_benchmark/activation_benchmark.py",
"repo_id": "keras-core",
"token_count": 1744
} | 19 |
"""
Title: Text generation with a miniature GPT
Author: [Apoorv Nandan](https://twitter.com/NandanApoorv)
Date created: 2020/05/29
Last modified: 2020/05/29
Description: Implement a miniature version of GPT and train it to generate text.
Accelerator: GPU
"""
"""
## Introduction
This example demonstrates how to implement an autoregressive language model
using a miniature version of the GPT model.
The model consists of a single Transformer block with causal masking
in its attention layer.
We use the text from the IMDB sentiment classification dataset for training
and generate new movie reviews for a given prompt.
When using this script with your own dataset, make sure it has at least
1 million words.
This example should be run with `tf-nightly>=2.3.0-dev20200531` or
with TensorFlow 2.3 or higher.
**References:**
- [GPT](https://www.semanticscholar.org/paper/Improving-Language-Understanding-by-Generative-Radford/cd18800a0fe0b668a1cc19f2ec95b5003d0a5035)
- [GPT-2](https://www.semanticscholar.org/paper/Language-Models-are-Unsupervised-Multitask-Learners-Radford-Wu/9405cc0d6169988371b2755e573cc28650d14dfe)
- [GPT-3](https://arxiv.org/abs/2005.14165)
"""
"""
## Setup
"""
# We set the backend to TensorFlow. The code works with
# both `tensorflow` and `torch`. It does not work with JAX
# due to the behavior of `jax.numpy.tile` in a jit scope
# (used in `causal_attention_mask()`: `tile` in JAX does
# not support a dynamic `reps` argument.
# You can make the code work in JAX by wrapping the
# inside of the `causal_attention_mask` function in
# a decorator to prevent jit compilation:
# `with jax.ensure_compile_time_eval():`.
import os
os.environ['KERAS_BACKEND'] = 'tensorflow'
import keras_core as keras
from keras_core import layers
from keras_core import ops
from keras_core.layers import TextVectorization
import numpy as np
import os
import string
import random
import tensorflow
import tensorflow.data as tf_data
import tensorflow.strings as tf_strings
"""
## Implement a Transformer block as a layer
"""
def causal_attention_mask(batch_size, n_dest, n_src, dtype):
"""
Mask the upper half of the dot product matrix in self attention.
This prevents flow of information from future tokens to current token.
1's in the lower triangle, counting from the lower right corner.
"""
i = ops.arange(n_dest)[:, None]
j = ops.arange(n_src)
m = i >= j - n_src + n_dest
mask = ops.cast(m, dtype)
mask = ops.reshape(mask, [1, n_dest, n_src])
mult = ops.concatenate(
[ops.expand_dims(batch_size, -1), ops.convert_to_tensor([1, 1])], 0
)
return ops.tile(mask, mult)
class TransformerBlock(layers.Layer):
def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1):
super().__init__()
self.att = layers.MultiHeadAttention(num_heads, embed_dim)
self.ffn = keras.Sequential(
[
layers.Dense(ff_dim, activation="relu"),
layers.Dense(embed_dim),
]
)
self.layernorm1 = layers.LayerNormalization(epsilon=1e-6)
self.layernorm2 = layers.LayerNormalization(epsilon=1e-6)
self.dropout1 = layers.Dropout(rate)
self.dropout2 = layers.Dropout(rate)
def call(self, inputs):
input_shape = ops.shape(inputs)
batch_size = input_shape[0]
seq_len = input_shape[1]
causal_mask = causal_attention_mask(batch_size, seq_len, seq_len, "bool")
attention_output = self.att(inputs, inputs, attention_mask=causal_mask)
attention_output = self.dropout1(attention_output)
out1 = self.layernorm1(inputs + attention_output)
ffn_output = self.ffn(out1)
ffn_output = self.dropout2(ffn_output)
return self.layernorm2(out1 + ffn_output)
"""
## Implement an embedding layer
Create two separate embedding layers: one for tokens and one for token index
(positions).
"""
class TokenAndPositionEmbedding(layers.Layer):
def __init__(self, maxlen, vocab_size, embed_dim):
super().__init__()
self.token_emb = layers.Embedding(input_dim=vocab_size, output_dim=embed_dim)
self.pos_emb = layers.Embedding(input_dim=maxlen, output_dim=embed_dim)
def call(self, x):
maxlen = ops.shape(x)[-1]
positions = ops.arange(0, maxlen, 1)
positions = self.pos_emb(positions)
x = self.token_emb(x)
return x + positions
"""
## Implement the miniature GPT model
"""
vocab_size = 20000 # Only consider the top 20k words
maxlen = 80 # Max sequence size
embed_dim = 256 # Embedding size for each token
num_heads = 2 # Number of attention heads
feed_forward_dim = 256 # Hidden layer size in feed forward network inside transformer
def create_model():
inputs = layers.Input(shape=(maxlen,), dtype="int32")
embedding_layer = TokenAndPositionEmbedding(maxlen, vocab_size, embed_dim)
x = embedding_layer(inputs)
transformer_block = TransformerBlock(embed_dim, num_heads, feed_forward_dim)
x = transformer_block(x)
outputs = layers.Dense(vocab_size)(x)
model = keras.Model(inputs=inputs, outputs=[outputs, x])
loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True)
model.compile(
"adam",
loss=[loss_fn, None],
) # No loss and optimization based on word embeddings from transformer block
return model
"""
## Prepare the data for word-level language modelling
Download the IMDB dataset and combine training and validation sets for a text
generation task.
"""
"""shell
curl -O https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz
tar -xf aclImdb_v1.tar.gz
"""
batch_size = 128
# The dataset contains each review in a separate text file
# The text files are present in four different folders
# Create a list all files
filenames = []
directories = [
"aclImdb/train/pos",
"aclImdb/train/neg",
"aclImdb/test/pos",
"aclImdb/test/neg",
]
for dir in directories:
for f in os.listdir(dir):
filenames.append(os.path.join(dir, f))
print(f"{len(filenames)} files")
# Create a dataset from text files
random.shuffle(filenames)
text_ds = tf_data.TextLineDataset(filenames)
text_ds = text_ds.shuffle(buffer_size=256)
text_ds = text_ds.batch(batch_size)
def custom_standardization(input_string):
"""Remove html line-break tags and handle punctuation"""
lowercased = tf_strings.lower(input_string)
stripped_html = tf_strings.regex_replace(lowercased, "<br />", " ")
return tf_strings.regex_replace(stripped_html, f"([{string.punctuation}])", r" \1")
# Create a vectorization layer and adapt it to the text
vectorize_layer = TextVectorization(
standardize=custom_standardization,
max_tokens=vocab_size - 1,
output_mode="int",
output_sequence_length=maxlen + 1,
)
vectorize_layer.adapt(text_ds)
vocab = vectorize_layer.get_vocabulary() # To get words back from token indices
def prepare_lm_inputs_labels(text):
"""
Shift word sequences by 1 position so that the target for position (i) is
word at position (i+1). The model will use all words up till position (i)
to predict the next word.
"""
text = tensorflow.expand_dims(text, -1)
tokenized_sentences = vectorize_layer(text)
x = tokenized_sentences[:, :-1]
y = tokenized_sentences[:, 1:]
return x, y
text_ds = text_ds.map(prepare_lm_inputs_labels, num_parallel_calls=tf_data.AUTOTUNE)
text_ds = text_ds.prefetch(tf_data.AUTOTUNE)
"""
## Implement a Keras callback for generating text
"""
class TextGenerator(keras.callbacks.Callback):
"""A callback to generate text from a trained model.
1. Feed some starting prompt to the model
2. Predict probabilities for the next token
3. Sample the next token and add it to the next input
Arguments:
max_tokens: Integer, the number of tokens to be generated after prompt.
start_tokens: List of integers, the token indices for the starting prompt.
index_to_word: List of strings, obtained from the TextVectorization layer.
top_k: Integer, sample from the `top_k` token predictions.
print_every: Integer, print after this many epochs.
"""
def __init__(
self, max_tokens, start_tokens, index_to_word, top_k=10, print_every=1
):
self.max_tokens = max_tokens
self.start_tokens = start_tokens
self.index_to_word = index_to_word
self.print_every = print_every
self.k = top_k
def sample_from(self, logits):
logits, indices = ops.top_k(logits, k=self.k, sorted=True)
indices = np.asarray(indices).astype("int32")
preds = keras.activations.softmax(ops.expand_dims(logits, 0))[0]
preds = np.asarray(preds).astype("float32")
return np.random.choice(indices, p=preds)
def detokenize(self, number):
return self.index_to_word[number]
def on_epoch_end(self, epoch, logs=None):
start_tokens = [_ for _ in self.start_tokens]
if (epoch + 1) % self.print_every != 0:
return
num_tokens_generated = 0
tokens_generated = []
while num_tokens_generated <= self.max_tokens:
pad_len = maxlen - len(start_tokens)
sample_index = len(start_tokens) - 1
if pad_len < 0:
x = start_tokens[:maxlen]
sample_index = maxlen - 1
elif pad_len > 0:
x = start_tokens + [0] * pad_len
else:
x = start_tokens
x = np.array([x])
y, _ = self.model.predict(x)
sample_token = self.sample_from(y[0][sample_index])
tokens_generated.append(sample_token)
start_tokens.append(sample_token)
num_tokens_generated = len(tokens_generated)
txt = " ".join(
[self.detokenize(_) for _ in self.start_tokens + tokens_generated]
)
print(f"generated text:\n{txt}\n")
# Tokenize starting prompt
word_to_index = {}
for index, word in enumerate(vocab):
word_to_index[word] = index
start_prompt = "this movie is"
start_tokens = [word_to_index.get(_, 1) for _ in start_prompt.split()]
num_tokens_generated = 40
text_gen_callback = TextGenerator(num_tokens_generated, start_tokens, vocab)
"""
## Train the model
Note: This code should preferably be run on GPU.
"""
model = create_model()
model.fit(text_ds, verbose=2, epochs=25, callbacks=[text_gen_callback])
| keras-core/examples/keras_io/generative/text_generation_with_miniature_gpt.py/0 | {
"file_path": "keras-core/examples/keras_io/generative/text_generation_with_miniature_gpt.py",
"repo_id": "keras-core",
"token_count": 4105
} | 20 |
"""
Title: Denoising Diffusion Probabilistic Model
Author: [A_K_Nain](https://twitter.com/A_K_Nain)
Date created: 2022/11/30
Last modified: 2022/12/07
Description: Generating images of flowers with denoising diffusion probabilistic models.
"""
"""
## Introduction
Generative modeling experienced tremendous growth in the last five years. Models like
VAEs, GANs, and flow-based models proved to be a great success in generating
high-quality content, especially images. Diffusion models are a new type of generative
model that has proven to be better than previous approaches.
Diffusion models are inspired by non-equilibrium thermodynamics, and they learn to
generate by denoising. Learning by denoising consists of two processes,
each of which is a Markov Chain. These are:
1. The forward process: In the forward process, we slowly add random noise to the data
in a series of time steps `(t1, t2, ..., tn )`. Samples at the current time step are
drawn from a Gaussian distribution where the mean of the distribution is conditioned
on the sample at the previous time step, and the variance of the distribution follows
a fixed schedule. At the end of the forward process, the samples end up with a pure
noise distribution.
2. The reverse process: During the reverse process, we try to undo the added noise at
every time step. We start with the pure noise distribution (the last step of the
forward process) and try to denoise the samples in the backward direction
`(tn, tn-1, ..., t1)`.
We implement the [Denoising Diffusion Probabilistic Models](https://arxiv.org/abs/2006.11239)
paper or DDPMs for short in this code example. It was the first paper demonstrating
the use of diffusion models for generating high-quality images. The authors proved
that a certain parameterization of diffusion models reveals an equivalence with
denoising score matching over multiple noise levels during training and with annealed
Langevin dynamics during sampling that generates the best quality results.
This paper replicates both the Markov chains (forward process and reverse process)
involved in the diffusion process but for images. The forward process is fixed and
gradually adds Gaussian noise to the images according to a fixed variance schedule
denoted by beta in the paper. This is what the diffusion process looks like in case
of images: (image -> noise::noise -> image)

The paper describes two algorithms, one for training the model, and the other for
sampling from the trained model. Training is performed by optimizing the usual
variational bound on negative log-likelihood. The objective function is further
simplified, and the network is treated as a noise prediction network. Once optimized,
we can sample from the network to generate new images from noise samples. Here is an
overview of both algorithms as presented in the paper:

**Note:** DDPM is just one way of implementing a diffusion model. Also, the sampling
algorithm in the DDPM replicates the complete Markov chain. Hence it's slow in
generating new samples compared to other generative models like GANs. Lots of research
efforts have been made to address this issue. One such example is Denoising Diffusion
Implicit Models, or DDIM for short, where the authors replaced the Markov chain with a
non-Markovian process to sample faster. You can find the code example for DDIM
[here](https://keras.io/examples/generative/ddim/)
Implementing a DDPM model is simple. We define a model that takes
two inputs: Images and the randomly sampled time steps. At each training step, we
perform the following operations to train our model:
1. Sample random noise to be added to the inputs.
2. Apply the forward process to diffuse the inputs with the sampled noise.
3. Your model takes these noisy samples as inputs and outputs the noise
prediction for each time step.
4. Given true noise and predicted noise, we calculate the loss values
5. We then calculate the gradients and update the model weights.
Given that our model knows how to denoise a noisy sample at a given time step,
we can leverage this idea to generate new samples, starting from a pure noise
distribution.
"""
"""
## Setup
"""
import math
import numpy as np
import matplotlib.pyplot as plt
# Requires TensorFlow >=2.11 for the GroupNormalization layer.
import tensorflow as tf
import keras_core as keras
from keras_core import layers
import tensorflow_datasets as tfds
"""
## Hyperparameters
"""
batch_size = 32
num_epochs = 1 # Just for the sake of demonstration
total_timesteps = 1000
norm_groups = 8 # Number of groups used in GroupNormalization layer
learning_rate = 2e-4
img_size = 64
img_channels = 3
clip_min = -1.0
clip_max = 1.0
first_conv_channels = 64
channel_multiplier = [1, 2, 4, 8]
widths = [first_conv_channels * mult for mult in channel_multiplier]
has_attention = [False, False, True, True]
num_res_blocks = 2 # Number of residual blocks
dataset_name = "oxford_flowers102"
splits = ["train"]
"""
## Dataset
We use the [Oxford Flowers 102](https://www.tensorflow.org/datasets/catalog/oxford_flowers102)
dataset for generating images of flowers. In terms of preprocessing, we use center
cropping for resizing the images to the desired image size, and we rescale the pixel
values in the range `[-1.0, 1.0]`. This is in line with the range of the pixel values that
was applied by the authors of the [DDPMs paper](https://arxiv.org/abs/2006.11239). For
augmenting training data, we randomly flip the images left/right.
"""
# Load the dataset
(ds,) = tfds.load(
dataset_name, split=splits, with_info=False, shuffle_files=True
)
def augment(img):
"""Flips an image left/right randomly."""
return tf.image.random_flip_left_right(img)
def resize_and_rescale(img, size):
"""Resize the image to the desired size first and then
rescale the pixel values in the range [-1.0, 1.0].
Args:
img: Image tensor
size: Desired image size for resizing
Returns:
Resized and rescaled image tensor
"""
height = tf.shape(img)[0]
width = tf.shape(img)[1]
crop_size = tf.minimum(height, width)
img = tf.image.crop_to_bounding_box(
img,
(height - crop_size) // 2,
(width - crop_size) // 2,
crop_size,
crop_size,
)
# Resize
img = tf.cast(img, dtype=tf.float32)
img = tf.image.resize(img, size=size, antialias=True)
# Rescale the pixel values
img = img / 127.5 - 1.0
img = tf.clip_by_value(img, clip_min, clip_max)
return img
def train_preprocessing(x):
img = x["image"]
img = resize_and_rescale(img, size=(img_size, img_size))
img = augment(img)
return img
train_ds = (
ds.map(train_preprocessing, num_parallel_calls=tf.data.AUTOTUNE)
.batch(batch_size, drop_remainder=True)
.shuffle(batch_size * 2)
.prefetch(tf.data.AUTOTUNE)
)
"""
## Gaussian diffusion utilities
We define the forward process and the reverse process
as a separate utility. Most of the code in this utility has been borrowed
from the original implementation with some slight modifications.
"""
class GaussianDiffusion:
"""Gaussian diffusion utility.
Args:
beta_start: Start value of the scheduled variance
beta_end: End value of the scheduled variance
timesteps: Number of time steps in the forward process
"""
def __init__(
self,
beta_start=1e-4,
beta_end=0.02,
timesteps=1000,
clip_min=-1.0,
clip_max=1.0,
):
self.beta_start = beta_start
self.beta_end = beta_end
self.timesteps = timesteps
self.clip_min = clip_min
self.clip_max = clip_max
# Define the linear variance schedule
self.betas = betas = np.linspace(
beta_start,
beta_end,
timesteps,
dtype=np.float64, # Using float64 for better precision
)
self.num_timesteps = int(timesteps)
alphas = 1.0 - betas
alphas_cumprod = np.cumprod(alphas, axis=0)
alphas_cumprod_prev = np.append(1.0, alphas_cumprod[:-1])
self.betas = tf.constant(betas, dtype=tf.float32)
self.alphas_cumprod = tf.constant(alphas_cumprod, dtype=tf.float32)
self.alphas_cumprod_prev = tf.constant(
alphas_cumprod_prev, dtype=tf.float32
)
# Calculations for diffusion q(x_t | x_{t-1}) and others
self.sqrt_alphas_cumprod = tf.constant(
np.sqrt(alphas_cumprod), dtype=tf.float32
)
self.sqrt_one_minus_alphas_cumprod = tf.constant(
np.sqrt(1.0 - alphas_cumprod), dtype=tf.float32
)
self.log_one_minus_alphas_cumprod = tf.constant(
np.log(1.0 - alphas_cumprod), dtype=tf.float32
)
self.sqrt_recip_alphas_cumprod = tf.constant(
np.sqrt(1.0 / alphas_cumprod), dtype=tf.float32
)
self.sqrt_recipm1_alphas_cumprod = tf.constant(
np.sqrt(1.0 / alphas_cumprod - 1), dtype=tf.float32
)
# Calculations for posterior q(x_{t-1} | x_t, x_0)
posterior_variance = (
betas * (1.0 - alphas_cumprod_prev) / (1.0 - alphas_cumprod)
)
self.posterior_variance = tf.constant(
posterior_variance, dtype=tf.float32
)
# Log calculation clipped because the posterior variance is 0 at the beginning
# of the diffusion chain
self.posterior_log_variance_clipped = tf.constant(
np.log(np.maximum(posterior_variance, 1e-20)), dtype=tf.float32
)
self.posterior_mean_coef1 = tf.constant(
betas * np.sqrt(alphas_cumprod_prev) / (1.0 - alphas_cumprod),
dtype=tf.float32,
)
self.posterior_mean_coef2 = tf.constant(
(1.0 - alphas_cumprod_prev)
* np.sqrt(alphas)
/ (1.0 - alphas_cumprod),
dtype=tf.float32,
)
def _extract(self, a, t, x_shape):
"""Extract some coefficients at specified timesteps,
then reshape to [batch_size, 1, 1, 1, 1, ...] for broadcasting purposes.
Args:
a: Tensor to extract from
t: Timestep for which the coefficients are to be extracted
x_shape: Shape of the current batched samples
"""
batch_size = x_shape[0]
out = tf.gather(a, t)
return tf.reshape(out, [batch_size, 1, 1, 1])
def q_mean_variance(self, x_start, t):
"""Extracts the mean, and the variance at current timestep.
Args:
x_start: Initial sample (before the first diffusion step)
t: Current timestep
"""
x_start_shape = tf.shape(x_start)
mean = (
self._extract(self.sqrt_alphas_cumprod, t, x_start_shape) * x_start
)
variance = self._extract(1.0 - self.alphas_cumprod, t, x_start_shape)
log_variance = self._extract(
self.log_one_minus_alphas_cumprod, t, x_start_shape
)
return mean, variance, log_variance
def q_sample(self, x_start, t, noise):
"""Diffuse the data.
Args:
x_start: Initial sample (before the first diffusion step)
t: Current timestep
noise: Gaussian noise to be added at the current timestep
Returns:
Diffused samples at timestep `t`
"""
x_start_shape = tf.shape(x_start)
return (
self._extract(self.sqrt_alphas_cumprod, t, tf.shape(x_start))
* x_start
+ self._extract(
self.sqrt_one_minus_alphas_cumprod, t, x_start_shape
)
* noise
)
def predict_start_from_noise(self, x_t, t, noise):
x_t_shape = tf.shape(x_t)
return (
self._extract(self.sqrt_recip_alphas_cumprod, t, x_t_shape) * x_t
- self._extract(self.sqrt_recipm1_alphas_cumprod, t, x_t_shape)
* noise
)
def q_posterior(self, x_start, x_t, t):
"""Compute the mean and variance of the diffusion
posterior q(x_{t-1} | x_t, x_0).
Args:
x_start: Stating point(sample) for the posterior computation
x_t: Sample at timestep `t`
t: Current timestep
Returns:
Posterior mean and variance at current timestep
"""
x_t_shape = tf.shape(x_t)
posterior_mean = (
self._extract(self.posterior_mean_coef1, t, x_t_shape) * x_start
+ self._extract(self.posterior_mean_coef2, t, x_t_shape) * x_t
)
posterior_variance = self._extract(
self.posterior_variance, t, x_t_shape
)
posterior_log_variance_clipped = self._extract(
self.posterior_log_variance_clipped, t, x_t_shape
)
return (
posterior_mean,
posterior_variance,
posterior_log_variance_clipped,
)
def p_mean_variance(self, pred_noise, x, t, clip_denoised=True):
x_recon = self.predict_start_from_noise(x, t=t, noise=pred_noise)
if clip_denoised:
x_recon = tf.clip_by_value(x_recon, self.clip_min, self.clip_max)
(
model_mean,
posterior_variance,
posterior_log_variance,
) = self.q_posterior(x_start=x_recon, x_t=x, t=t)
return model_mean, posterior_variance, posterior_log_variance
def p_sample(self, pred_noise, x, t, clip_denoised=True):
"""Sample from the diffuison model.
Args:
pred_noise: Noise predicted by the diffusion model
x: Samples at a given timestep for which the noise was predicted
t: Current timestep
clip_denoised (bool): Whether to clip the predicted noise
within the specified range or not.
"""
model_mean, _, model_log_variance = self.p_mean_variance(
pred_noise, x=x, t=t, clip_denoised=clip_denoised
)
noise = tf.random.normal(shape=x.shape, dtype=x.dtype)
# No noise when t == 0
nonzero_mask = tf.reshape(
1 - tf.cast(tf.equal(t, 0), tf.float32), [tf.shape(x)[0], 1, 1, 1]
)
return (
model_mean + nonzero_mask * tf.exp(0.5 * model_log_variance) * noise
)
"""
## Network architecture
U-Net, originally developed for semantic segmentation, is an architecture that is
widely used for implementing diffusion models but with some slight modifications:
1. The network accepts two inputs: Image and time step
2. Self-attention between the convolution blocks once we reach a specific resolution
(16x16 in the paper)
3. Group Normalization instead of weight normalization
We implement most of the things as used in the original paper. We use the
`swish` activation function throughout the network. We use the variance scaling
kernel initializer.
The only difference here is the number of groups used for the
`GroupNormalization` layer. For the flowers dataset,
we found that a value of `groups=8` produces better results
compared to the default value of `groups=32`. Dropout is optional and should be
used where chances of over fitting is high. In the paper, the authors used dropout
only when training on CIFAR10.
"""
# Kernel initializer to use
def kernel_init(scale):
scale = max(scale, 1e-10)
return keras.initializers.VarianceScaling(
scale, mode="fan_avg", distribution="uniform"
)
class AttentionBlock(layers.Layer):
"""Applies self-attention.
Args:
units: Number of units in the dense layers
groups: Number of groups to be used for GroupNormalization layer
"""
def __init__(self, units, groups=8, **kwargs):
self.units = units
self.groups = groups
super().__init__(**kwargs)
self.norm = layers.GroupNormalization(groups=groups)
self.query = layers.Dense(units, kernel_initializer=kernel_init(1.0))
self.key = layers.Dense(units, kernel_initializer=kernel_init(1.0))
self.value = layers.Dense(units, kernel_initializer=kernel_init(1.0))
self.proj = layers.Dense(units, kernel_initializer=kernel_init(0.0))
def call(self, inputs):
batch_size = tf.shape(inputs)[0]
height = tf.shape(inputs)[1]
width = tf.shape(inputs)[2]
scale = tf.cast(self.units, tf.float32) ** (-0.5)
inputs = self.norm(inputs)
q = self.query(inputs)
k = self.key(inputs)
v = self.value(inputs)
attn_score = tf.einsum("bhwc, bHWc->bhwHW", q, k) * scale
attn_score = tf.reshape(
attn_score, [batch_size, height, width, height * width]
)
attn_score = tf.nn.softmax(attn_score, -1)
attn_score = tf.reshape(
attn_score, [batch_size, height, width, height, width]
)
proj = tf.einsum("bhwHW,bHWc->bhwc", attn_score, v)
proj = self.proj(proj)
return inputs + proj
class TimeEmbedding(layers.Layer):
def __init__(self, dim, **kwargs):
super().__init__(**kwargs)
self.dim = dim
self.half_dim = dim // 2
self.emb = math.log(10000) / (self.half_dim - 1)
self.emb = tf.exp(tf.range(self.half_dim, dtype=tf.float32) * -self.emb)
def call(self, inputs):
inputs = tf.cast(inputs, dtype=tf.float32)
emb = inputs[:, None] * self.emb[None, :]
emb = tf.concat([tf.sin(emb), tf.cos(emb)], axis=-1)
return emb
def ResidualBlock(width, groups=8, activation_fn=keras.activations.swish):
def apply(inputs):
x, t = inputs
input_width = x.shape[3]
if input_width == width:
residual = x
else:
residual = layers.Conv2D(
width, kernel_size=1, kernel_initializer=kernel_init(1.0)
)(x)
temb = activation_fn(t)
temb = layers.Dense(width, kernel_initializer=kernel_init(1.0))(temb)[
:, None, None, :
]
x = layers.GroupNormalization(groups=groups)(x)
x = activation_fn(x)
x = layers.Conv2D(
width,
kernel_size=3,
padding="same",
kernel_initializer=kernel_init(1.0),
)(x)
x = layers.Add()([x, temb])
x = layers.GroupNormalization(groups=groups)(x)
x = activation_fn(x)
x = layers.Conv2D(
width,
kernel_size=3,
padding="same",
kernel_initializer=kernel_init(0.0),
)(x)
x = layers.Add()([x, residual])
return x
return apply
def DownSample(width):
def apply(x):
x = layers.Conv2D(
width,
kernel_size=3,
strides=2,
padding="same",
kernel_initializer=kernel_init(1.0),
)(x)
return x
return apply
def UpSample(width, interpolation="nearest"):
def apply(x):
x = layers.UpSampling2D(size=2, interpolation=interpolation)(x)
x = layers.Conv2D(
width,
kernel_size=3,
padding="same",
kernel_initializer=kernel_init(1.0),
)(x)
return x
return apply
def TimeMLP(units, activation_fn=keras.activations.swish):
def apply(inputs):
temb = layers.Dense(
units, activation=activation_fn, kernel_initializer=kernel_init(1.0)
)(inputs)
temb = layers.Dense(units, kernel_initializer=kernel_init(1.0))(temb)
return temb
return apply
def build_model(
img_size,
img_channels,
widths,
has_attention,
num_res_blocks=2,
norm_groups=8,
interpolation="nearest",
activation_fn=keras.activations.swish,
):
image_input = layers.Input(
shape=(img_size, img_size, img_channels), name="image_input"
)
time_input = keras.Input(shape=(), dtype=tf.int64, name="time_input")
x = layers.Conv2D(
first_conv_channels,
kernel_size=(3, 3),
padding="same",
kernel_initializer=kernel_init(1.0),
)(image_input)
temb = TimeEmbedding(dim=first_conv_channels * 4)(time_input)
temb = TimeMLP(units=first_conv_channels * 4, activation_fn=activation_fn)(
temb
)
skips = [x]
# DownBlock
for i in range(len(widths)):
for _ in range(num_res_blocks):
x = ResidualBlock(
widths[i], groups=norm_groups, activation_fn=activation_fn
)([x, temb])
if has_attention[i]:
x = AttentionBlock(widths[i], groups=norm_groups)(x)
skips.append(x)
if widths[i] != widths[-1]:
x = DownSample(widths[i])(x)
skips.append(x)
# MiddleBlock
x = ResidualBlock(
widths[-1], groups=norm_groups, activation_fn=activation_fn
)([x, temb])
x = AttentionBlock(widths[-1], groups=norm_groups)(x)
x = ResidualBlock(
widths[-1], groups=norm_groups, activation_fn=activation_fn
)([x, temb])
# UpBlock
for i in reversed(range(len(widths))):
for _ in range(num_res_blocks + 1):
x = layers.Concatenate(axis=-1)([x, skips.pop()])
x = ResidualBlock(
widths[i], groups=norm_groups, activation_fn=activation_fn
)([x, temb])
if has_attention[i]:
x = AttentionBlock(widths[i], groups=norm_groups)(x)
if i != 0:
x = UpSample(widths[i], interpolation=interpolation)(x)
# End block
x = layers.GroupNormalization(groups=norm_groups)(x)
x = activation_fn(x)
x = layers.Conv2D(
3, (3, 3), padding="same", kernel_initializer=kernel_init(0.0)
)(x)
return keras.Model([image_input, time_input], x, name="unet")
"""
## Training
We follow the same setup for training the diffusion model as described
in the paper. We use `Adam` optimizer with a learning rate of `2e-4`.
We use EMA on model parameters with a decay factor of 0.999. We
treat our model as noise prediction network i.e. at every training step, we
input a batch of images and corresponding time steps to our UNet,
and the network outputs the noise as predictions.
The only difference is that we aren't using the Kernel Inception Distance (KID)
or Frechet Inception Distance (FID) for evaluating the quality of generated
samples during training. This is because both these metrics are compute heavy
and are skipped for the brevity of implementation.
**Note: ** We are using mean squared error as the loss function which is aligned with
the paper, and theoretically makes sense. In practice, though, it is also common to
use mean absolute error or Huber loss as the loss function.
"""
class DiffusionModel(keras.Model):
def __init__(self, network, ema_network, timesteps, gdf_util, ema=0.999):
super().__init__()
self.network = network
self.ema_network = ema_network
self.timesteps = timesteps
self.gdf_util = gdf_util
self.ema = ema
def train_step(self, images):
# 1. Get the batch size
batch_size = tf.shape(images)[0]
# 2. Sample timesteps uniformly
t = tf.random.uniform(
minval=0, maxval=self.timesteps, shape=(batch_size,), dtype=tf.int64
)
with tf.GradientTape() as tape:
# 3. Sample random noise to be added to the images in the batch
noise = tf.random.normal(shape=tf.shape(images), dtype=images.dtype)
# 4. Diffuse the images with noise
images_t = self.gdf_util.q_sample(images, t, noise)
# 5. Pass the diffused images and time steps to the network
pred_noise = self.network([images_t, t], training=True)
# 6. Calculate the loss
loss = self.loss(noise, pred_noise)
# 7. Get the gradients
gradients = tape.gradient(loss, self.network.trainable_weights)
# 8. Update the weights of the network
self.optimizer.apply_gradients(
zip(gradients, self.network.trainable_weights)
)
# 9. Updates the weight values for the network with EMA weights
for weight, ema_weight in zip(
self.network.weights, self.ema_network.weights
):
ema_weight.assign(self.ema * ema_weight + (1 - self.ema) * weight)
# 10. Return loss values
return {"loss": loss}
def generate_images(self, num_images=16):
# 1. Randomly sample noise (starting point for reverse process)
samples = tf.random.normal(
shape=(num_images, img_size, img_size, img_channels),
dtype=tf.float32,
)
# 2. Sample from the model iteratively
for t in reversed(range(0, self.timesteps)):
tt = tf.cast(tf.fill(num_images, t), dtype=tf.int64)
pred_noise = self.ema_network.predict(
[samples, tt], verbose=0, batch_size=num_images
)
samples = self.gdf_util.p_sample(
pred_noise, samples, tt, clip_denoised=True
)
# 3. Return generated samples
return samples
def plot_images(
self, epoch=None, logs=None, num_rows=2, num_cols=8, figsize=(12, 5)
):
"""Utility to plot images using the diffusion model during training."""
generated_samples = self.generate_images(num_images=num_rows * num_cols)
generated_samples = (
tf.clip_by_value(generated_samples * 127.5 + 127.5, 0.0, 255.0)
.numpy()
.astype(np.uint8)
)
_, ax = plt.subplots(num_rows, num_cols, figsize=figsize)
for i, image in enumerate(generated_samples):
if num_rows == 1:
ax[i].imshow(image)
ax[i].axis("off")
else:
ax[i // num_cols, i % num_cols].imshow(image)
ax[i // num_cols, i % num_cols].axis("off")
plt.tight_layout()
plt.show()
# Build the unet model
network = build_model(
img_size=img_size,
img_channels=img_channels,
widths=widths,
has_attention=has_attention,
num_res_blocks=num_res_blocks,
norm_groups=norm_groups,
activation_fn=keras.activations.swish,
)
ema_network = build_model(
img_size=img_size,
img_channels=img_channels,
widths=widths,
has_attention=has_attention,
num_res_blocks=num_res_blocks,
norm_groups=norm_groups,
activation_fn=keras.activations.swish,
)
ema_network.set_weights(
network.get_weights()
) # Initially the weights are the same
# Get an instance of the Gaussian Diffusion utilities
gdf_util = GaussianDiffusion(timesteps=total_timesteps)
# Get the model
model = DiffusionModel(
network=network,
ema_network=ema_network,
gdf_util=gdf_util,
timesteps=total_timesteps,
)
# Compile the model
model.compile(
loss=keras.losses.MeanSquaredError(),
optimizer=keras.optimizers.Adam(learning_rate=learning_rate),
jit_compile=False,
)
# Train the model
model.fit(
train_ds,
epochs=num_epochs,
batch_size=batch_size,
callbacks=[keras.callbacks.LambdaCallback(on_epoch_end=model.plot_images)],
)
"""
## Results
We trained this model for 800 epochs on a V100 GPU,
and each epoch took almost 8 seconds to finish. We load those weights
here, and we generate a few samples starting from pure noise.
"""
"""shell
curl -LO https://github.com/AakashKumarNain/ddpms/releases/download/v3.0.0/checkpoints.zip
unzip -qq checkpoints.zip
"""
# Load the model weights
model.ema_network.load_weights("checkpoints/diffusion_model_checkpoint")
# Generate and plot some samples
model.plot_images(num_rows=4, num_cols=8)
"""
## Conclusion
We successfully implemented and trained a diffusion model exactly in the same
fashion as implemented by the authors of the DDPMs paper. You can find the
original implementation [here](https://github.com/hojonathanho/diffusion).
There are a few things that you can try to improve the model:
1. Increasing the width of each block. A bigger model can learn to denoise
in fewer epochs, though you may have to take care of overfitting.
2. We implemented the linear schedule for variance scheduling. You can implement
other schemes like cosine scheduling and compare the performance.
"""
"""
## References
1. [Denoising Diffusion Probabilistic Models](https://arxiv.org/abs/2006.11239)
2. [Author's implementation](https://github.com/hojonathanho/diffusion)
3. [A deep dive into DDPMs](https://magic-with-latents.github.io/latent/posts/ddpms/part3/)
4. [Denoising Diffusion Implicit Models](https://keras.io/examples/generative/ddim/)
5. [Annotated Diffusion Model](https://huggingface.co/blog/annotated-diffusion)
6. [AIAIART](https://www.youtube.com/watch?v=XTs7M6TSK9I&t=14s)
"""
| keras-core/examples/keras_io/tensorflow/generative/ddpm.py/0 | {
"file_path": "keras-core/examples/keras_io/tensorflow/generative/ddpm.py",
"repo_id": "keras-core",
"token_count": 11992
} | 21 |
"""
Title: Text classification from scratch
Authors: Mark Omernick, Francois Chollet
Date created: 2019/11/06
Last modified: 2020/05/17
Description: Text sentiment classification starting from raw text files.
Accelerator: GPU
"""
"""
## Introduction
This example shows how to do text classification starting from raw text (as
a set of text files on disk). We demonstrate the workflow on the IMDB sentiment
classification dataset (unprocessed version). We use the `TextVectorization` layer for
word splitting & indexing.
"""
"""
## Setup
"""
import tensorflow as tf
import keras_core as keras
from keras_core.layers import TextVectorization
from keras_core import layers
import string
import re
import os
from pathlib import Path
"""
## Load the data: IMDB movie review sentiment classification
Let's download the data and inspect its structure.
"""
fpath = keras.utils.get_file(
origin="https://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz"
)
dirpath = Path(fpath).parent.absolute()
os.system(f"tar -xf {fpath} -C {dirpath}")
"""
The `aclImdb` folder contains a `train` and `test` subfolder:
"""
os.system(f"ls {dirpath}/aclImdb")
os.system(f"ls {dirpath}/aclImdb/train")
os.system(f"ls {dirpath}/aclImdb/test")
"""
The `aclImdb/train/pos` and `aclImdb/train/neg` folders contain text files, each of
which represents one review (either positive or negative):
"""
os.system(f"cat {dirpath}/aclImdb/train/pos/6248_7.txt")
"""
We are only interested in the `pos` and `neg` subfolders, so let's delete the rest:
"""
os.system(f"rm -r {dirpath}/aclImdb/train/unsup")
"""
You can use the utility `keras.utils.text_dataset_from_directory` to
generate a labeled `tf.data.Dataset` object from a set of text files on disk filed
into class-specific folders.
Let's use it to generate the training, validation, and test datasets. The validation
and training datasets are generated from two subsets of the `train` directory, with 20%
of samples going to the validation dataset and 80% going to the training dataset.
Having a validation dataset in addition to the test dataset is useful for tuning
hyperparameters, such as the model architecture, for which the test dataset should not
be used.
Before putting the model out into the real world however, it should be retrained using all
available training data (without creating a validation dataset), so its performance is maximized.
When using the `validation_split` & `subset` arguments, make sure to either specify a
random seed, or to pass `shuffle=False`, so that the validation & training splits you
get have no overlap.
"""
batch_size = 32
raw_train_ds, raw_val_ds = keras.utils.text_dataset_from_directory(
f"{dirpath}/aclImdb/train",
batch_size=batch_size,
validation_split=0.2,
subset="both",
seed=1337,
)
raw_test_ds = keras.utils.text_dataset_from_directory(
f"{dirpath}/aclImdb/test", batch_size=batch_size
)
print(f"Number of batches in raw_train_ds: {raw_train_ds.cardinality()}")
print(f"Number of batches in raw_val_ds: {raw_val_ds.cardinality()}")
print(f"Number of batches in raw_test_ds: {raw_test_ds.cardinality()}")
"""
Let's preview a few samples:
"""
# It's important to take a look at your raw data to ensure your normalization
# and tokenization will work as expected. We can do that by taking a few
# examples from the training set and looking at them.
# This is one of the places where eager execution shines:
# we can just evaluate these tensors using .numpy()
# instead of needing to evaluate them in a Session/Graph context.
for text_batch, label_batch in raw_train_ds.take(1):
for i in range(5):
print(text_batch.numpy()[i])
print(label_batch.numpy()[i])
"""
## Prepare the data
In particular, we remove `<br />` tags.
"""
# Having looked at our data above, we see that the raw text contains HTML break
# tags of the form '<br />'. These tags will not be removed by the default
# standardizer (which doesn't strip HTML). Because of this, we will need to
# create a custom standardization function.
def custom_standardization(input_data):
lowercase = tf.strings.lower(input_data)
stripped_html = tf.strings.regex_replace(lowercase, "<br />", " ")
return tf.strings.regex_replace(
stripped_html, f"[{re.escape(string.punctuation)}]", ""
)
# Model constants.
max_features = 20000
embedding_dim = 128
sequence_length = 500
# Now that we have our custom standardization, we can instantiate our text
# vectorization layer. We are using this layer to normalize, split, and map
# strings to integers, so we set our 'output_mode' to 'int'.
# Note that we're using the default split function,
# and the custom standardization defined above.
# We also set an explicit maximum sequence length, since the CNNs later in our
# model won't support ragged sequences.
vectorize_layer = TextVectorization(
standardize=custom_standardization,
max_tokens=max_features,
output_mode="int",
output_sequence_length=sequence_length,
)
# Now that the vocab layer has been created, call `adapt` on a text-only
# dataset to create the vocabulary. You don't have to batch, but for very large
# datasets this means you're not keeping spare copies of the dataset in memory.
# Let's make a text-only dataset (no labels):
text_ds = raw_train_ds.map(lambda x, y: x)
# Let's call `adapt`:
vectorize_layer.adapt(text_ds)
"""
## Two options to vectorize the data
There are 2 ways we can use our text vectorization layer:
**Option 1: Make it part of the model**, so as to obtain a model that processes raw
strings, like this:
"""
"""
```python
text_input = keras.Input(shape=(1,), dtype=tf.string, name='text')
x = vectorize_layer(text_input)
x = layers.Embedding(max_features + 1, embedding_dim)(x)
...
```
**Option 2: Apply it to the text dataset** to obtain a dataset of word indices, then
feed it into a model that expects integer sequences as inputs.
An important difference between the two is that option 2 enables you to do
**asynchronous CPU processing and buffering** of your data when training on GPU.
So if you're training the model on GPU, you probably want to go with this option to get
the best performance. This is what we will do below.
If we were to export our model to production, we'd ship a model that accepts raw
strings as input, like in the code snippet for option 1 above. This can be done after
training. We do this in the last section.
"""
def vectorize_text(text, label):
text = tf.expand_dims(text, -1)
return vectorize_layer(text), label
# Vectorize the data.
train_ds = raw_train_ds.map(vectorize_text)
val_ds = raw_val_ds.map(vectorize_text)
test_ds = raw_test_ds.map(vectorize_text)
# Do async prefetching / buffering of the data for best performance on GPU.
train_ds = train_ds.cache().prefetch(buffer_size=10)
val_ds = val_ds.cache().prefetch(buffer_size=10)
test_ds = test_ds.cache().prefetch(buffer_size=10)
"""
## Build a model
We choose a simple 1D convnet starting with an `Embedding` layer.
"""
# A integer input for vocab indices.
inputs = keras.Input(shape=(sequence_length,), dtype="int64")
# Next, we add a layer to map those vocab indices into a space of dimensionality
# 'embedding_dim'.
x = keras.layers.Embedding(max_features, embedding_dim)(inputs)
x = layers.Dropout(0.5)(x)
# Conv1D + global max pooling
x = layers.Conv1D(128, 7, padding="valid", activation="relu", strides=3)(x)
x = layers.Conv1D(128, 7, padding="valid", activation="relu", strides=3)(x)
x = layers.GlobalMaxPooling1D()(x)
# We add a vanilla hidden layer:
x = layers.Dense(128, activation="relu")(x)
x = layers.Dropout(0.5)(x)
# We project onto a single unit output layer, and squash it with a sigmoid:
predictions = layers.Dense(1, activation="sigmoid", name="predictions")(x)
model = keras.Model(inputs, predictions)
model.summary()
model.compile(
loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]
)
"""
## Train the model
"""
epochs = 3
# Fit the model using the train and test datasets.
model.fit(train_ds, validation_data=val_ds, epochs=epochs)
"""
## Evaluate the model on the test set
"""
model.evaluate(test_ds)
"""
## Make an end-to-end model
If you want to obtain a model capable of processing raw strings, you can simply
create a new model (using the weights we just trained):
"""
# A string input
inputs = keras.Input(shape=(1,), dtype="string")
# Turn strings into vocab indices
indices = vectorize_layer(inputs)
# Turn vocab indices into predictions
outputs = model(indices)
# Our end to end model
end_to_end_model = keras.Model(inputs, outputs)
end_to_end_model.compile(
loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"]
)
# Test it with `raw_test_ds`, which yields raw strings
end_to_end_model.evaluate(raw_test_ds)
| keras-core/examples/keras_io/tensorflow/nlp/text_classification_from_scratch.py/0 | {
"file_path": "keras-core/examples/keras_io/tensorflow/nlp/text_classification_from_scratch.py",
"repo_id": "keras-core",
"token_count": 2772
} | 22 |
"""
Title: Involutional neural networks
Author: [Aritra Roy Gosthipaty](https://twitter.com/ariG23498)
Date created: 2021/07/25
Last modified: 2021/07/25
Description: Deep dive into location-specific and channel-agnostic "involution" kernels.
Accelerator: GPU
"""
"""
## Introduction
Convolution has been the basis of most modern neural
networks for computer vision. A convolution kernel is
spatial-agnostic and channel-specific. Because of this, it isn't able
to adapt to different visual patterns with respect to
different spatial locations. Along with location-related problems, the
receptive field of convolution creates challenges with regard to capturing
long-range spatial interactions.
To address the above issues, Li et. al. rethink the properties
of convolution in
[Involution: Inverting the Inherence of Convolution for VisualRecognition](https://arxiv.org/abs/2103.06255).
The authors propose the "involution kernel", that is location-specific and
channel-agnostic. Due to the location-specific nature of the operation,
the authors say that self-attention falls under the design paradigm of
involution.
This example describes the involution kernel, compares two image
classification models, one with convolution and the other with
involution, and also tries drawing a parallel with the self-attention
layer.
"""
"""
## Setup
"""
import tensorflow as tf
import keras_core as keras
import matplotlib.pyplot as plt
# Set seed for reproducibility.
tf.random.set_seed(42)
"""
## Convolution
Convolution remains the mainstay of deep neural networks for computer vision.
To understand Involution, it is necessary to talk about the
convolution operation.

Consider an input tensor **X** with dimensions **H**, **W** and
**C_in**. We take a collection of **C_out** convolution kernels each of
shape **K**, **K**, **C_in**. With the multiply-add operation between
the input tensor and the kernels we obtain an output tensor **Y** with
dimensions **H**, **W**, **C_out**.
In the diagram above `C_out=3`. This makes the output tensor of shape H,
W and 3. One can notice that the convoltuion kernel does not depend on
the spatial position of the input tensor which makes it
**location-agnostic**. On the other hand, each channel in the output
tensor is based on a specific convolution filter which makes is
**channel-specific**.
"""
"""
## Involution
The idea is to have an operation that is both **location-specific**
and **channel-agnostic**. Trying to implement these specific properties poses
a challenge. With a fixed number of involution kernels (for each
spatial position) we will **not** be able to process variable-resolution
input tensors.
To solve this problem, the authors have considered *generating* each
kernel conditioned on specific spatial positions. With this method, we
should be able to process variable-resolution input tensors with ease.
The diagram below provides an intuition on this kernel generation
method.

"""
class Involution(keras.layers.Layer):
def __init__(
self, channel, group_number, kernel_size, stride, reduction_ratio, name
):
super().__init__(name=name)
# Initialize the parameters.
self.channel = channel
self.group_number = group_number
self.kernel_size = kernel_size
self.stride = stride
self.reduction_ratio = reduction_ratio
def build(self, input_shape):
# Get the shape of the input.
(_, height, width, num_channels) = input_shape
# Scale the height and width with respect to the strides.
height = height // self.stride
width = width // self.stride
# Define a layer that average pools the input tensor
# if stride is more than 1.
self.stride_layer = (
keras.layers.AveragePooling2D(
pool_size=self.stride, strides=self.stride, padding="same"
)
if self.stride > 1
else tf.identity
)
# Define the kernel generation layer.
self.kernel_gen = keras.Sequential(
[
keras.layers.Conv2D(
filters=self.channel // self.reduction_ratio, kernel_size=1
),
keras.layers.BatchNormalization(),
keras.layers.ReLU(),
keras.layers.Conv2D(
filters=self.kernel_size
* self.kernel_size
* self.group_number,
kernel_size=1,
),
]
)
# Define reshape layers
self.kernel_reshape = keras.layers.Reshape(
target_shape=(
height,
width,
self.kernel_size * self.kernel_size,
1,
self.group_number,
)
)
self.input_patches_reshape = keras.layers.Reshape(
target_shape=(
height,
width,
self.kernel_size * self.kernel_size,
num_channels // self.group_number,
self.group_number,
)
)
self.output_reshape = keras.layers.Reshape(
target_shape=(height, width, num_channels)
)
def call(self, x):
# Generate the kernel with respect to the input tensor.
# B, H, W, K*K*G
kernel_input = self.stride_layer(x)
kernel = self.kernel_gen(kernel_input)
# reshape the kerenl
# B, H, W, K*K, 1, G
kernel = self.kernel_reshape(kernel)
# Extract input patches.
# B, H, W, K*K*C
input_patches = tf.image.extract_patches(
images=x,
sizes=[1, self.kernel_size, self.kernel_size, 1],
strides=[1, self.stride, self.stride, 1],
rates=[1, 1, 1, 1],
padding="SAME",
)
# Reshape the input patches to align with later operations.
# B, H, W, K*K, C//G, G
input_patches = self.input_patches_reshape(input_patches)
# Compute the multiply-add operation of kernels and patches.
# B, H, W, K*K, C//G, G
output = tf.multiply(kernel, input_patches)
# B, H, W, C//G, G
output = tf.reduce_sum(output, axis=3)
# Reshape the output kernel.
# B, H, W, C
output = self.output_reshape(output)
# Return the output tensor and the kernel.
return output, kernel
"""
## Testing the Involution layer
"""
# Define the input tensor.
input_tensor = tf.random.normal((32, 256, 256, 3))
# Compute involution with stride 1.
output_tensor, _ = Involution(
channel=3,
group_number=1,
kernel_size=5,
stride=1,
reduction_ratio=1,
name="inv_1",
)(input_tensor)
print(f"with stride 1 ouput shape: {output_tensor.shape}")
# Compute involution with stride 2.
output_tensor, _ = Involution(
channel=3,
group_number=1,
kernel_size=5,
stride=2,
reduction_ratio=1,
name="inv_2",
)(input_tensor)
print(f"with stride 2 ouput shape: {output_tensor.shape}")
# Compute involution with stride 1, channel 16 and reduction ratio 2.
output_tensor, _ = Involution(
channel=16,
group_number=1,
kernel_size=5,
stride=1,
reduction_ratio=2,
name="inv_3",
)(input_tensor)
print(
"with channel 16 and reduction ratio 2 ouput shape: {}".format(
output_tensor.shape
)
)
"""
## Image Classification
In this section, we will build an image-classifier model. There will
be two models one with convolutions and the other with involutions.
The image-classification model is heavily inspired by this
[Convolutional Neural Network (CNN)](https://www.tensorflow.org/tutorials/images/cnn)
tutorial from Google.
"""
"""
## Get the CIFAR10 Dataset
"""
# Load the CIFAR10 dataset.
print("loading the CIFAR10 dataset...")
(
(train_images, train_labels),
(
test_images,
test_labels,
),
) = keras.datasets.cifar10.load_data()
# Normalize pixel values to be between 0 and 1.
(train_images, test_images) = (train_images / 255.0, test_images / 255.0)
# Shuffle and batch the dataset.
train_ds = (
tf.data.Dataset.from_tensor_slices((train_images, train_labels))
.shuffle(256)
.batch(256)
)
test_ds = tf.data.Dataset.from_tensor_slices((test_images, test_labels)).batch(
256
)
"""
## Visualise the data
"""
class_names = [
"airplane",
"automobile",
"bird",
"cat",
"deer",
"dog",
"frog",
"horse",
"ship",
"truck",
]
plt.figure(figsize=(10, 10))
for i in range(25):
plt.subplot(5, 5, i + 1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i])
plt.xlabel(class_names[train_labels[i][0]])
plt.show()
"""
## Convolutional Neural Network
"""
# Build the conv model.
print("building the convolution model...")
conv_model = keras.Sequential(
[
keras.layers.Conv2D(
32, (3, 3), input_shape=(32, 32, 3), padding="same"
),
keras.layers.ReLU(name="relu1"),
keras.layers.MaxPooling2D((2, 2)),
keras.layers.Conv2D(64, (3, 3), padding="same"),
keras.layers.ReLU(name="relu2"),
keras.layers.MaxPooling2D((2, 2)),
keras.layers.Conv2D(64, (3, 3), padding="same"),
keras.layers.ReLU(name="relu3"),
keras.layers.Flatten(),
keras.layers.Dense(64, activation="relu"),
keras.layers.Dense(10),
]
)
# Compile the mode with the necessary loss function and optimizer.
print("compiling the convolution model...")
conv_model.compile(
optimizer="adam",
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=["accuracy"],
jit_compile=False,
)
# Train the model.
print("conv model training...")
conv_hist = conv_model.fit(train_ds, epochs=20, validation_data=test_ds)
"""
## Involutional Neural Network
"""
# Build the involution model.
print("building the involution model...")
inputs = keras.Input(shape=(32, 32, 3))
x, _ = Involution(
channel=3,
group_number=1,
kernel_size=3,
stride=1,
reduction_ratio=2,
name="inv_1",
)(inputs)
x = keras.layers.ReLU()(x)
x = keras.layers.MaxPooling2D((2, 2))(x)
x, _ = Involution(
channel=3,
group_number=1,
kernel_size=3,
stride=1,
reduction_ratio=2,
name="inv_2",
)(x)
x = keras.layers.ReLU()(x)
x = keras.layers.MaxPooling2D((2, 2))(x)
x, _ = Involution(
channel=3,
group_number=1,
kernel_size=3,
stride=1,
reduction_ratio=2,
name="inv_3",
)(x)
x = keras.layers.ReLU()(x)
x = keras.layers.Flatten()(x)
x = keras.layers.Dense(64, activation="relu")(x)
outputs = keras.layers.Dense(10)(x)
inv_model = keras.Model(inputs=[inputs], outputs=[outputs], name="inv_model")
# Compile the mode with the necessary loss function and optimizer.
print("compiling the involution model...")
inv_model.compile(
optimizer="adam",
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=["accuracy"],
jit_compile=False,
)
# train the model
print("inv model training...")
inv_hist = inv_model.fit(train_ds, epochs=20, validation_data=test_ds)
"""
## Comparisons
In this section, we will be looking at both the models and compare a
few pointers.
"""
"""
### Parameters
One can see that with a similar architecture the parameters in a CNN
is much larger than that of an INN (Involutional Neural Network).
"""
conv_model.summary()
inv_model.summary()
"""
### Loss and Accuracy Plots
Here, the loss and the accuracy plots demonstrate that INNs are slow
learners (with lower parameters).
"""
plt.figure(figsize=(20, 5))
plt.subplot(1, 2, 1)
plt.title("Convolution Loss")
plt.plot(conv_hist.history["loss"], label="loss")
plt.plot(conv_hist.history["val_loss"], label="val_loss")
plt.legend()
plt.subplot(1, 2, 2)
plt.title("Involution Loss")
plt.plot(inv_hist.history["loss"], label="loss")
plt.plot(inv_hist.history["val_loss"], label="val_loss")
plt.legend()
plt.show()
plt.figure(figsize=(20, 5))
plt.subplot(1, 2, 1)
plt.title("Convolution Accuracy")
plt.plot(conv_hist.history["accuracy"], label="accuracy")
plt.plot(conv_hist.history["val_accuracy"], label="val_accuracy")
plt.legend()
plt.subplot(1, 2, 2)
plt.title("Involution Accuracy")
plt.plot(inv_hist.history["accuracy"], label="accuracy")
plt.plot(inv_hist.history["val_accuracy"], label="val_accuracy")
plt.legend()
plt.show()
"""
## Visualizing Involution Kernels
To visualize the kernels, we take the sum of **K×K** values from each
involution kernel. **All the representatives at different spatial
locations frame the corresponding heat map.**
The authors mention:
"Our proposed involution is reminiscent of self-attention and
essentially could become a generalized version of it."
With the visualization of the kernel we can indeed obtain an attention
map of the image. The learned involution kernels provides attention to
individual spatial positions of the input tensor. The
**location-specific** property makes involution a generic space of models
in which self-attention belongs.
"""
layer_names = ["inv_1", "inv_2", "inv_3"]
# The kernel is the second output of the layer
outputs = [inv_model.get_layer(name).output[1] for name in layer_names]
vis_model = keras.Model(inv_model.input, outputs)
fig, axes = plt.subplots(nrows=10, ncols=4, figsize=(10, 30))
for ax, test_image in zip(axes, test_images[:10]):
inv_out = vis_model.predict(test_image[None, ...])
inv1_kernel, inv2_kernel, inv3_kernel = inv_out
inv1_kernel = tf.reduce_sum(inv1_kernel, axis=[-1, -2, -3])
inv2_kernel = tf.reduce_sum(inv2_kernel, axis=[-1, -2, -3])
inv3_kernel = tf.reduce_sum(inv3_kernel, axis=[-1, -2, -3])
ax[0].imshow(keras.utils.array_to_img(test_image))
ax[0].set_title("Input Image")
ax[1].imshow(keras.utils.array_to_img(inv1_kernel[0, ..., None]))
ax[1].set_title("Involution Kernel 1")
ax[2].imshow(keras.utils.array_to_img(inv2_kernel[0, ..., None]))
ax[2].set_title("Involution Kernel 2")
ax[3].imshow(keras.utils.array_to_img(inv3_kernel[0, ..., None]))
ax[3].set_title("Involution Kernel 3")
"""
## Conclusions
In this example, the main focus was to build an `Involution` layer which
can be easily reused. While our comparisons were based on a specific
task, feel free to use the layer for different tasks and report your
results.
According to me, the key take-away of involution is its
relationship with self-attention. The intuition behind location-specific
and channel-spefic processing makes sense in a lot of tasks.
Moving forward one can:
- Look at [Yannick's video](https://youtu.be/pH2jZun8MoY) on
involution for a better understanding.
- Experiment with the various hyperparameters of the involution layer.
- Build different models with the involution layer.
- Try building a different kernel generation method altogether.
You can use the trained model hosted on [Hugging Face Hub](https://huggingface.co/keras-io/involution)
and try the demo on [Hugging Face Spaces](https://huggingface.co/spaces/keras-io/involution).
"""
| keras-core/examples/keras_io/tensorflow/vision/involution.py/0 | {
"file_path": "keras-core/examples/keras_io/tensorflow/vision/involution.py",
"repo_id": "keras-core",
"token_count": 5961
} | 23 |
from keras_core import backend
from keras_core import layers
from keras_core.api_export import keras_core_export
from keras_core.applications import imagenet_utils
from keras_core.models import Functional
from keras_core.ops import operation_utils
from keras_core.utils import file_utils
BASE_WEIGHTS_PATH = (
"https://storage.googleapis.com/tensorflow/keras-applications/densenet/"
)
DENSENET121_WEIGHT_PATH = (
BASE_WEIGHTS_PATH + "densenet121_weights_tf_dim_ordering_tf_kernels.h5"
)
DENSENET121_WEIGHT_PATH_NO_TOP = (
BASE_WEIGHTS_PATH
+ "densenet121_weights_tf_dim_ordering_tf_kernels_notop.h5"
)
DENSENET169_WEIGHT_PATH = (
BASE_WEIGHTS_PATH + "densenet169_weights_tf_dim_ordering_tf_kernels.h5"
)
DENSENET169_WEIGHT_PATH_NO_TOP = (
BASE_WEIGHTS_PATH
+ "densenet169_weights_tf_dim_ordering_tf_kernels_notop.h5"
)
DENSENET201_WEIGHT_PATH = (
BASE_WEIGHTS_PATH + "densenet201_weights_tf_dim_ordering_tf_kernels.h5"
)
DENSENET201_WEIGHT_PATH_NO_TOP = (
BASE_WEIGHTS_PATH
+ "densenet201_weights_tf_dim_ordering_tf_kernels_notop.h5"
)
def dense_block(x, blocks, name):
"""A dense block.
Args:
x: input tensor.
blocks: integer, the number of building blocks.
name: string, block label.
Returns:
Output tensor for the block.
"""
for i in range(blocks):
x = conv_block(x, 32, name=name + "_block" + str(i + 1))
return x
def transition_block(x, reduction, name):
"""A transition block.
Args:
x: input tensor.
reduction: float, compression rate at transition layers.
name: string, block label.
Returns:
Output tensor for the block.
"""
bn_axis = 3 if backend.image_data_format() == "channels_last" else 1
x = layers.BatchNormalization(
axis=bn_axis, epsilon=1.001e-5, name=name + "_bn"
)(x)
x = layers.Activation("relu", name=name + "_relu")(x)
x = layers.Conv2D(
int(x.shape[bn_axis] * reduction),
1,
use_bias=False,
name=name + "_conv",
)(x)
x = layers.AveragePooling2D(2, strides=2, name=name + "_pool")(x)
return x
def conv_block(x, growth_rate, name):
"""A building block for a dense block.
Args:
x: input tensor.
growth_rate: float, growth rate at dense layers.
name: string, block label.
Returns:
Output tensor for the block.
"""
bn_axis = 3 if backend.image_data_format() == "channels_last" else 1
x1 = layers.BatchNormalization(
axis=bn_axis, epsilon=1.001e-5, name=name + "_0_bn"
)(x)
x1 = layers.Activation("relu", name=name + "_0_relu")(x1)
x1 = layers.Conv2D(
4 * growth_rate, 1, use_bias=False, name=name + "_1_conv"
)(x1)
x1 = layers.BatchNormalization(
axis=bn_axis, epsilon=1.001e-5, name=name + "_1_bn"
)(x1)
x1 = layers.Activation("relu", name=name + "_1_relu")(x1)
x1 = layers.Conv2D(
growth_rate, 3, padding="same", use_bias=False, name=name + "_2_conv"
)(x1)
x = layers.Concatenate(axis=bn_axis, name=name + "_concat")([x, x1])
return x
def DenseNet(
blocks,
include_top=True,
weights="imagenet",
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
classifier_activation="softmax",
):
"""Instantiates the DenseNet architecture.
Reference:
- [Densely Connected Convolutional Networks](
https://arxiv.org/abs/1608.06993) (CVPR 2017)
This function returns a Keras image classification model,
optionally loaded with weights pre-trained on ImageNet.
For image classification use cases, see
[this page for detailed examples](
https://keras.io/api/applications/#usage-examples-for-image-classification-models).
For transfer learning use cases, make sure to read the
[guide to transfer learning & fine-tuning](
https://keras.io/guides/transfer_learning/).
Note: each Keras Application expects a specific kind of input preprocessing.
For DenseNet, call `keras_core.applications.densenet.preprocess_input`
on your inputs before passing them to the model.
`densenet.preprocess_input` will scale pixels between 0 and 1 and then
will normalize each channel with respect to the ImageNet
dataset statistics.
Args:
blocks: numbers of building blocks for the four dense layers.
include_top: whether to include the fully-connected
layer at the top of the network.
weights: one of `None` (random initialization),
`"imagenet"` (pre-training on ImageNet),
or the path to the weights file to be loaded.
input_tensor: optional Keras tensor
(i.e. output of `layers.Input()`)
to use as image input for the model.
input_shape: optional shape tuple, only to be specified
if `include_top` is False (otherwise the input shape
has to be `(224, 224, 3)`
(with `'channels_last'` data format)
or `(3, 224, 224)` (with `'channels_first'` data format).
It should have exactly 3 inputs channels,
and width and height should be no smaller than 32.
E.g. `(200, 200, 3)` would be one valid value.
pooling: optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model will be
the 4D tensor output of the
last convolutional block.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional block, and thus
the output of the model will be a 2D tensor.
- `max` means that global max pooling will
be applied.
classes: optional number of classes to classify images
into, only to be specified if `include_top` is `True`, and
if no `weights` argument is specified.
classifier_activation: A `str` or callable.
The activation function to use
on the "top" layer. Ignored unless `include_top=True`. Set
`classifier_activation=None` to return the logits of the "top"
layer. When loading pretrained weights, `classifier_activation`
can only be `None` or `"softmax"`.
Returns:
A model instance.
"""
if not (weights in {"imagenet", None} or file_utils.exists(weights)):
raise ValueError(
"The `weights` argument should be either "
"`None` (random initialization), `imagenet` "
"(pre-training on ImageNet), "
"or the path to the weights file to be loaded."
)
if weights == "imagenet" and include_top and classes != 1000:
raise ValueError(
'If using `weights` as `"imagenet"` with `include_top`'
" as true, `classes` should be 1000"
)
# Determine proper input shape
input_shape = imagenet_utils.obtain_input_shape(
input_shape,
default_size=224,
min_size=32,
data_format=backend.image_data_format(),
require_flatten=include_top,
weights=weights,
)
if input_tensor is None:
img_input = layers.Input(shape=input_shape)
else:
if not backend.is_keras_tensor(input_tensor):
img_input = layers.Input(tensor=input_tensor, shape=input_shape)
else:
img_input = input_tensor
bn_axis = 3 if backend.image_data_format() == "channels_last" else 1
x = layers.ZeroPadding2D(padding=((3, 3), (3, 3)))(img_input)
x = layers.Conv2D(64, 7, strides=2, use_bias=False, name="conv1_conv")(x)
x = layers.BatchNormalization(
axis=bn_axis, epsilon=1.001e-5, name="conv1_bn"
)(x)
x = layers.Activation("relu", name="conv1_relu")(x)
x = layers.ZeroPadding2D(padding=((1, 1), (1, 1)))(x)
x = layers.MaxPooling2D(3, strides=2, name="pool1")(x)
x = dense_block(x, blocks[0], name="conv2")
x = transition_block(x, 0.5, name="pool2")
x = dense_block(x, blocks[1], name="conv3")
x = transition_block(x, 0.5, name="pool3")
x = dense_block(x, blocks[2], name="conv4")
x = transition_block(x, 0.5, name="pool4")
x = dense_block(x, blocks[3], name="conv5")
x = layers.BatchNormalization(axis=bn_axis, epsilon=1.001e-5, name="bn")(x)
x = layers.Activation("relu", name="relu")(x)
if include_top:
x = layers.GlobalAveragePooling2D(name="avg_pool")(x)
imagenet_utils.validate_activation(classifier_activation, weights)
x = layers.Dense(
classes, activation=classifier_activation, name="predictions"
)(x)
else:
if pooling == "avg":
x = layers.GlobalAveragePooling2D(name="avg_pool")(x)
elif pooling == "max":
x = layers.GlobalMaxPooling2D(name="max_pool")(x)
# Ensure that the model takes into account
# any potential predecessors of `input_tensor`.
if input_tensor is not None:
inputs = operation_utils.get_source_inputs(input_tensor)
else:
inputs = img_input
# Create model.
if blocks == [6, 12, 24, 16]:
model = Functional(inputs, x, name="densenet121")
elif blocks == [6, 12, 32, 32]:
model = Functional(inputs, x, name="densenet169")
elif blocks == [6, 12, 48, 32]:
model = Functional(inputs, x, name="densenet201")
else:
model = Functional(inputs, x, name="densenet")
# Load weights.
if weights == "imagenet":
if include_top:
if blocks == [6, 12, 24, 16]:
weights_path = file_utils.get_file(
"densenet121_weights_tf_dim_ordering_tf_kernels.h5",
DENSENET121_WEIGHT_PATH,
cache_subdir="models",
file_hash="9d60b8095a5708f2dcce2bca79d332c7",
)
elif blocks == [6, 12, 32, 32]:
weights_path = file_utils.get_file(
"densenet169_weights_tf_dim_ordering_tf_kernels.h5",
DENSENET169_WEIGHT_PATH,
cache_subdir="models",
file_hash="d699b8f76981ab1b30698df4c175e90b",
)
elif blocks == [6, 12, 48, 32]:
weights_path = file_utils.get_file(
"densenet201_weights_tf_dim_ordering_tf_kernels.h5",
DENSENET201_WEIGHT_PATH,
cache_subdir="models",
file_hash="1ceb130c1ea1b78c3bf6114dbdfd8807",
)
else:
if blocks == [6, 12, 24, 16]:
weights_path = file_utils.get_file(
"densenet121_weights_tf_dim_ordering_tf_kernels_notop.h5",
DENSENET121_WEIGHT_PATH_NO_TOP,
cache_subdir="models",
file_hash="30ee3e1110167f948a6b9946edeeb738",
)
elif blocks == [6, 12, 32, 32]:
weights_path = file_utils.get_file(
"densenet169_weights_tf_dim_ordering_tf_kernels_notop.h5",
DENSENET169_WEIGHT_PATH_NO_TOP,
cache_subdir="models",
file_hash="b8c4d4c20dd625c148057b9ff1c1176b",
)
elif blocks == [6, 12, 48, 32]:
weights_path = file_utils.get_file(
"densenet201_weights_tf_dim_ordering_tf_kernels_notop.h5",
DENSENET201_WEIGHT_PATH_NO_TOP,
cache_subdir="models",
file_hash="c13680b51ded0fb44dff2d8f86ac8bb1",
)
model.load_weights(weights_path)
elif weights is not None:
model.load_weights(weights)
return model
@keras_core_export(
[
"keras_core.applications.densenet.DenseNet121",
"keras_core.applications.DenseNet121",
]
)
def DenseNet121(
include_top=True,
weights="imagenet",
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
classifier_activation="softmax",
):
"""Instantiates the Densenet121 architecture."""
return DenseNet(
[6, 12, 24, 16],
include_top,
weights,
input_tensor,
input_shape,
pooling,
classes,
classifier_activation,
)
@keras_core_export(
[
"keras_core.applications.densenet.DenseNet169",
"keras_core.applications.DenseNet169",
]
)
def DenseNet169(
include_top=True,
weights="imagenet",
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
classifier_activation="softmax",
):
"""Instantiates the Densenet169 architecture."""
return DenseNet(
[6, 12, 32, 32],
include_top,
weights,
input_tensor,
input_shape,
pooling,
classes,
classifier_activation,
)
@keras_core_export(
[
"keras_core.applications.densenet.DenseNet201",
"keras_core.applications.DenseNet201",
]
)
def DenseNet201(
include_top=True,
weights="imagenet",
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
classifier_activation="softmax",
):
"""Instantiates the Densenet201 architecture."""
return DenseNet(
[6, 12, 48, 32],
include_top,
weights,
input_tensor,
input_shape,
pooling,
classes,
classifier_activation,
)
@keras_core_export("keras_core.applications.densenet.preprocess_input")
def preprocess_input(x, data_format=None):
return imagenet_utils.preprocess_input(
x, data_format=data_format, mode="torch"
)
@keras_core_export("keras_core.applications.densenet.decode_predictions")
def decode_predictions(preds, top=5):
return imagenet_utils.decode_predictions(preds, top=top)
preprocess_input.__doc__ = imagenet_utils.PREPROCESS_INPUT_DOC.format(
mode="",
ret=imagenet_utils.PREPROCESS_INPUT_RET_DOC_TORCH,
error=imagenet_utils.PREPROCESS_INPUT_ERROR_DOC,
)
decode_predictions.__doc__ = imagenet_utils.decode_predictions.__doc__
DOC = """
Reference:
- [Densely Connected Convolutional Networks](
https://arxiv.org/abs/1608.06993) (CVPR 2017)
Optionally loads weights pre-trained on ImageNet.
Note that the data format convention used by the model is
the one specified in your Keras config at `~/.keras/keras.json`.
Note: each Keras Application expects a specific kind of input preprocessing.
For DenseNet, call `keras_core.applications.densenet.preprocess_input`
on your inputs before passing them to the model.
Args:
include_top: whether to include the fully-connected
layer at the top of the network.
weights: one of `None` (random initialization),
`"imagenet"` (pre-training on ImageNet),
or the path to the weights file to be loaded.
input_tensor: optional Keras tensor
(i.e. output of `layers.Input()`)
to use as image input for the model.
input_shape: optional shape tuple, only to be specified
if `include_top` is False (otherwise the input shape
has to be `(224, 224, 3)` (with `'channels_last'` data format)
or `(3, 224, 224)` (with `'channels_first'` data format).
It should have exactly 3 inputs channels,
and width and height should be no smaller than 32.
E.g. `(200, 200, 3)` would be one valid value.
pooling: Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model will be
the 4D tensor output of the
last convolutional block.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional block, and thus
the output of the model will be a 2D tensor.
- `max` means that global max pooling will
be applied.
classes: optional number of classes to classify images
into, only to be specified if `include_top` is `True`, and
if no `weights` argument is specified.
classifier_activation: A `str` or callable.
The activation function to use
on the "top" layer. Ignored unless `include_top=True`. Set
`classifier_activation=None` to return the logits
of the "top" layer. When loading pretrained weights,
`classifier_activation` can only be `None` or `"softmax"`.
Returns:
A Keras model instance.
"""
setattr(DenseNet121, "__doc__", DenseNet121.__doc__ + DOC)
setattr(DenseNet169, "__doc__", DenseNet169.__doc__ + DOC)
setattr(DenseNet201, "__doc__", DenseNet201.__doc__ + DOC)
| keras-core/keras_core/applications/densenet.py/0 | {
"file_path": "keras-core/keras_core/applications/densenet.py",
"repo_id": "keras-core",
"token_count": 7407
} | 24 |
from keras_core.backend.config import backend
if backend() == "torch":
# When using the torch backend,
# torch needs to be imported first, otherwise it will segfault
# upon import.
import torch
from keras_core.backend.common.keras_tensor import KerasTensor
from keras_core.backend.common.keras_tensor import any_symbolic_tensors
from keras_core.backend.common.keras_tensor import is_keras_tensor
from keras_core.backend.common.name_scope import name_scope
from keras_core.backend.common.stateless_scope import StatelessScope
from keras_core.backend.common.stateless_scope import get_stateless_scope
from keras_core.backend.common.stateless_scope import in_stateless_scope
from keras_core.backend.common.variables import AutocastScope
from keras_core.backend.common.variables import get_autocast_scope
from keras_core.backend.common.variables import is_float_dtype
from keras_core.backend.common.variables import is_int_dtype
from keras_core.backend.common.variables import standardize_dtype
from keras_core.backend.common.variables import standardize_shape
from keras_core.backend.config import epsilon
from keras_core.backend.config import floatx
from keras_core.backend.config import image_data_format
from keras_core.backend.config import set_epsilon
from keras_core.backend.config import set_floatx
from keras_core.backend.config import set_image_data_format
from keras_core.backend.config import standardize_data_format
from keras_core.utils.io_utils import print_msg
# Import backend functions.
if backend() == "tensorflow":
print_msg("Using TensorFlow backend")
from keras_core.backend.tensorflow import * # noqa: F403
distribution_lib = None
elif backend() == "jax":
print_msg("Using JAX backend.")
from keras_core.backend.jax import * # noqa: F403
elif backend() == "torch":
print_msg("Using PyTorch backend.")
from keras_core.backend.torch import * # noqa: F403
distribution_lib = None
elif backend() == "numpy":
print_msg(
"Using NumPy backend.\nThe NumPy backend does not support "
"training. It should only be used for inference, evaluation, "
"and debugging."
)
from keras_core.backend.numpy import * # noqa: F403
distribution_lib = None
else:
raise ValueError(f"Unable to import backend : {backend()}")
| keras-core/keras_core/backend/__init__.py/0 | {
"file_path": "keras-core/keras_core/backend/__init__.py",
"repo_id": "keras-core",
"token_count": 789
} | 25 |
from keras_core import backend
from keras_core.api_export import keras_core_export
if backend.backend() == "tensorflow":
BackendVariable = backend.tensorflow.core.Variable
backend_name_scope = backend.tensorflow.core.name_scope
elif backend.backend() == "jax":
BackendVariable = backend.jax.core.Variable
backend_name_scope = backend.common.name_scope.name_scope
elif backend.backend() == "torch":
BackendVariable = backend.torch.core.Variable
backend_name_scope = backend.common.name_scope.name_scope
elif backend.backend() == "numpy":
from keras_core.backend.numpy.core import Variable as NumpyVariable
BackendVariable = NumpyVariable
backend_name_scope = backend.common.name_scope.name_scope
else:
raise RuntimeError(f"Invalid backend: {backend.backend()}")
@keras_core_export("keras_core.Variable")
class Variable(BackendVariable):
pass
@keras_core_export("keras_core.name_scope")
class name_scope(backend_name_scope):
pass
| keras-core/keras_core/backend/exports.py/0 | {
"file_path": "keras-core/keras_core/backend/exports.py",
"repo_id": "keras-core",
"token_count": 337
} | 26 |
import numpy as np
from keras_core.backend import standardize_dtype
from keras_core.backend.jax.math import fft as jax_fft
from keras_core.backend.jax.math import fft2 as jax_fft2
from keras_core.backend.numpy.core import convert_to_tensor
from keras_core.utils.module_utils import scipy
def segment_sum(data, segment_ids, num_segments=None, sorted=False):
if num_segments is None:
num_segments = np.amax(segment_ids) + 1
valid_indices = segment_ids >= 0 # Ignore segment_ids that are -1
valid_data = data[valid_indices]
valid_segment_ids = segment_ids[valid_indices]
data_shape = list(valid_data.shape)
data_shape[
0
] = num_segments # Replace first dimension (which corresponds to segments)
if sorted:
result = np.zeros(data_shape, dtype=valid_data.dtype)
np.add.at(result, valid_segment_ids, valid_data)
else:
sort_indices = np.argsort(valid_segment_ids)
sorted_segment_ids = valid_segment_ids[sort_indices]
sorted_data = valid_data[sort_indices]
result = np.zeros(data_shape, dtype=valid_data.dtype)
np.add.at(result, sorted_segment_ids, sorted_data)
return result
def segment_max(data, segment_ids, num_segments=None, sorted=False):
if num_segments is None:
num_segments = np.amax(segment_ids) + 1
valid_indices = segment_ids >= 0 # Ignore segment_ids that are -1
valid_data = data[valid_indices]
valid_segment_ids = segment_ids[valid_indices]
data_shape = list(valid_data.shape)
data_shape[
0
] = num_segments # Replace first dimension (which corresponds to segments)
if sorted:
result = np.zeros(data_shape, dtype=valid_data.dtype)
np.maximum.at(result, valid_segment_ids, valid_data)
else:
sort_indices = np.argsort(valid_segment_ids)
sorted_segment_ids = valid_segment_ids[sort_indices]
sorted_data = valid_data[sort_indices]
result = np.zeros(data_shape, dtype=valid_data.dtype)
np.maximum.at(result, sorted_segment_ids, sorted_data)
return result
def top_k(x, k, sorted=False):
sorted_indices = np.argsort(x, axis=-1)[..., ::-1]
sorted_values = np.sort(x, axis=-1)[..., ::-1]
if sorted:
# Take the k largest values.
top_k_values = sorted_values[..., :k]
top_k_indices = sorted_indices[..., :k]
else:
# Partition the array such that all values larger than the k-th
# largest value are to the right of it.
top_k_values = np.partition(x, -k, axis=-1)[..., -k:]
top_k_indices = np.argpartition(x, -k, axis=-1)[..., -k:]
# Get the indices in sorted order.
idx = np.argsort(-top_k_values, axis=-1)
# Get the top k values and their indices.
top_k_values = np.take_along_axis(top_k_values, idx, axis=-1)
top_k_indices = np.take_along_axis(top_k_indices, idx, axis=-1)
return top_k_values, top_k_indices
def in_top_k(targets, predictions, k):
targets = targets[:, None]
topk_values = top_k(predictions, k)[0]
targets_values = np.take_along_axis(predictions, targets, axis=-1)
mask = targets_values >= topk_values
return np.any(mask, axis=-1)
def logsumexp(x, axis=None, keepdims=False):
max_x = np.max(x, axis=axis, keepdims=True)
result = np.log(np.sum(np.exp(x - max_x), axis=axis, keepdims=True)) + max_x
return np.squeeze(result) if not keepdims else result
def qr(x, mode="reduced"):
if mode not in {"reduced", "complete"}:
raise ValueError(
"`mode` argument value not supported. "
"Expected one of {'reduced', 'complete'}. "
f"Received: mode={mode}"
)
return np.linalg.qr(x, mode=mode)
def extract_sequences(x, sequence_length, sequence_stride):
*batch_shape, _ = x.shape
batch_shape = list(batch_shape)
shape = x.shape[:-1] + (
(x.shape[-1] - (sequence_length - sequence_stride)) // sequence_stride,
sequence_length,
)
strides = x.strides[:-1] + (
sequence_stride * x.strides[-1],
x.strides[-1],
)
x = np.lib.stride_tricks.as_strided(x, shape=shape, strides=strides)
return np.reshape(x, (*batch_shape, *x.shape[-2:]))
def _get_complex_tensor_from_tuple(x):
if not isinstance(x, (tuple, list)) or len(x) != 2:
raise ValueError(
"Input `x` should be a tuple of two tensors - real and imaginary."
f"Received: x={x}"
)
# `convert_to_tensor` does not support passing complex tensors. We separate
# the input out into real and imaginary and convert them separately.
real, imag = x
# Check shapes.
if real.shape != imag.shape:
raise ValueError(
"Input `x` should be a tuple of two tensors - real and imaginary."
"Both the real and imaginary parts should have the same shape. "
f"Received: x[0].shape = {real.shape}, x[1].shape = {imag.shape}"
)
# Ensure dtype is float.
if not np.issubdtype(real.dtype, np.floating) or not np.issubdtype(
imag.dtype, np.floating
):
raise ValueError(
"At least one tensor in input `x` is not of type float."
f"Received: x={x}."
)
complex_input = real + 1j * imag
return complex_input
def fft(x):
real, imag = jax_fft(x)
return np.array(real), np.array(imag)
def fft2(x):
real, imag = jax_fft2(x)
return np.array(real), np.array(imag)
def rfft(x, fft_length=None):
complex_output = np.fft.rfft(x, n=fft_length, axis=-1, norm="backward")
# numpy always outputs complex128, so we need to recast the dtype
return (
np.real(complex_output).astype(x.dtype),
np.imag(complex_output).astype(x.dtype),
)
def irfft(x, fft_length=None):
complex_input = _get_complex_tensor_from_tuple(x)
# numpy always outputs float64, so we need to recast the dtype
return np.fft.irfft(
complex_input, n=fft_length, axis=-1, norm="backward"
).astype(x[0].dtype)
def stft(
x, sequence_length, sequence_stride, fft_length, window="hann", center=True
):
if standardize_dtype(x.dtype) not in {"float32", "float64"}:
raise TypeError(
"Invalid input type. Expected `float32` or `float64`. "
f"Received: input type={x.dtype}"
)
if fft_length < sequence_length:
raise ValueError(
"`fft_length` must equal or larger than `sequence_length`. "
f"Received: sequence_length={sequence_length}, "
f"fft_length={fft_length}"
)
if isinstance(window, str):
if window not in {"hann", "hamming"}:
raise ValueError(
"If a string is passed to `window`, it must be one of "
f'`"hann"`, `"hamming"`. Received: window={window}'
)
x = convert_to_tensor(x)
ori_dtype = x.dtype
if center:
pad_width = [(0, 0) for _ in range(len(x.shape))]
pad_width[-1] = (fft_length // 2, fft_length // 2)
x = np.pad(x, pad_width, mode="reflect")
l_pad = (fft_length - sequence_length) // 2
r_pad = fft_length - sequence_length - l_pad
if window is not None:
if isinstance(window, str):
win = convert_to_tensor(
scipy.signal.get_window(window, sequence_length), dtype=x.dtype
)
else:
win = convert_to_tensor(window, dtype=x.dtype)
if len(win.shape) != 1 or win.shape[-1] != sequence_length:
raise ValueError(
"The shape of `window` must be equal to [sequence_length]."
f"Received: window shape={win.shape}"
)
win = np.pad(win, [[l_pad, r_pad]])
else:
win = np.ones((sequence_length + l_pad + r_pad), dtype=x.dtype)
x = scipy.signal.stft(
x,
fs=1.0,
window=win,
nperseg=(sequence_length + l_pad + r_pad),
noverlap=(sequence_length + l_pad + r_pad - sequence_stride),
nfft=fft_length,
boundary=None,
padded=False,
)[-1]
# scale and swap to (..., num_sequences, fft_bins)
x = x / np.sqrt(1.0 / win.sum() ** 2)
x = np.swapaxes(x, -2, -1)
return np.real(x).astype(ori_dtype), np.imag(x).astype(ori_dtype)
def istft(
x,
sequence_length,
sequence_stride,
fft_length,
length=None,
window="hann",
center=True,
):
x = _get_complex_tensor_from_tuple(x)
dtype = np.real(x).dtype
expected_output_len = fft_length + sequence_stride * (x.shape[-2] - 1)
l_pad = (fft_length - sequence_length) // 2
r_pad = fft_length - sequence_length - l_pad
if window is not None:
if isinstance(window, str):
win = convert_to_tensor(
scipy.signal.get_window(window, sequence_length), dtype=dtype
)
else:
win = convert_to_tensor(window, dtype=dtype)
if len(win.shape) != 1 or win.shape[-1] != sequence_length:
raise ValueError(
"The shape of `window` must be equal to [sequence_length]."
f"Received: window shape={win.shape}"
)
win = np.pad(win, [[l_pad, r_pad]])
else:
win = np.ones((sequence_length + l_pad + r_pad), dtype=dtype)
x = scipy.signal.istft(
x,
fs=1.0,
window=win,
nperseg=(sequence_length + l_pad + r_pad),
noverlap=(sequence_length + l_pad + r_pad - sequence_stride),
nfft=fft_length,
boundary=False,
time_axis=-2,
freq_axis=-1,
)[-1]
# scale
x = x / win.sum() if window is not None else x / sequence_stride
start = 0 if center is False else fft_length // 2
if length is not None:
end = start + length
elif center is True:
end = -(fft_length // 2)
else:
end = expected_output_len
return x[..., start:end]
def rsqrt(x):
return 1.0 / np.sqrt(x)
| keras-core/keras_core/backend/numpy/math.py/0 | {
"file_path": "keras-core/keras_core/backend/numpy/math.py",
"repo_id": "keras-core",
"token_count": 4576
} | 27 |
# flake8: noqa
import numpy as np
import pytest
import tensorflow as tf
from tensorflow.python.eager import context
from keras_core import backend
from keras_core import testing
from keras_core.optimizers.sgd import SGD
@pytest.mark.skipif(
backend.backend() != "tensorflow",
reason="The distribute test can only run with TF backend.",
)
class OptimizerDistributeTest(testing.TestCase):
def setUp(self):
super().setUp()
# Need at least 2 devices for distribution related tests.
cpus = tf.config.list_physical_devices("CPU")
context._reset_context()
tf.config.set_logical_device_configuration(
cpus[0],
[
tf.config.LogicalDeviceConfiguration(),
tf.config.LogicalDeviceConfiguration(),
],
)
self.strategy = tf.distribute.MirroredStrategy(["CPU:0", "CPU:1"])
def test_config(self):
with self.strategy.scope():
optimizer = SGD(
learning_rate=0.5,
momentum=0.06,
nesterov=True,
weight_decay=0.004,
)
self.run_class_serialization_test(optimizer)
def test_single_step(self):
with self.strategy.scope():
optimizer = SGD(
learning_rate=0.5,
momentum=0.06,
)
grads = tf.constant([1.0, 6.0, 7.0, 2.0])
vars = backend.Variable([1.0, 2.0, 3.0, 4.0]).value
self.strategy.run(
lambda: optimizer.apply_gradients(zip([grads], [vars]))
)
self.assertAllClose(
vars, [0.5, -1.0, -0.5, 3.0], rtol=1e-4, atol=1e-4
)
def test_weight_decay(self):
with self.strategy.scope():
grads, var1, var2, var3 = (
tf.zeros(()),
backend.Variable(2.0).value,
backend.Variable(3.0, name="exclude").value,
backend.Variable(4.0).value,
)
optimizer_1 = SGD(learning_rate=1.0, weight_decay=0.004)
self.strategy.run(
lambda: optimizer_1.apply_gradients(zip([grads], [var1]))
)
optimizer_2 = SGD(learning_rate=1.0, weight_decay=0.004)
def opt2_run():
optimizer_2.exclude_from_weight_decay(var_names=["exclude"])
optimizer_2.apply_gradients(zip([grads, grads], [var1, var2]))
self.strategy.run(opt2_run)
optimizer_3 = SGD(learning_rate=1.0, weight_decay=0.004)
def opt3_run():
optimizer_3.exclude_from_weight_decay(var_list=[var3])
optimizer_3.apply_gradients(zip([grads, grads], [var1, var3]))
self.strategy.run(opt3_run)
self.assertAlmostEqual(var1.numpy(), 1.9760959)
self.assertAlmostEqual(var2.numpy(), 3.0)
self.assertAlmostEqual(var3.numpy(), 4.0)
def test_correctness_with_golden(self):
with self.strategy.scope():
optimizer = SGD(nesterov=True)
x = backend.Variable(np.ones([10])).value
grads = np.arange(0.1, 1.1, 0.1)
first_grads = np.full((10,), 0.01)
# fmt: off
golden = np.array(
[[0.9999, 0.9999, 0.9999, 0.9999, 0.9999, 0.9999, 0.9999, 0.9999,
0.9999, 0.9999], [0.9989, 0.9979, 0.9969, 0.9959, 0.9949, 0.9939,
0.9929, 0.9919, 0.9909, 0.9899], [0.9979, 0.9959, 0.9939, 0.9919,
0.9899, 0.9879, 0.9859, 0.9839, 0.9819, 0.9799], [0.9969, 0.9939,
0.9909, 0.9879, 0.9849, 0.9819, 0.9789, 0.9759, 0.9729, 0.9699],
[0.9959, 0.9919, 0.9879, 0.9839, 0.9799, 0.9759, 0.9719, 0.9679,
0.9639, 0.9599]]
)
# fmt: on
self.strategy.run(
lambda: optimizer.apply_gradients(zip([first_grads], [x]))
)
for i in range(5):
self.assertAllClose(x, golden[i], rtol=5e-4, atol=5e-4)
self.strategy.run(
lambda: optimizer.apply_gradients(zip([grads], [x]))
)
def test_clip_norm(self):
with self.strategy.scope():
optimizer = SGD(clipnorm=1)
grad = [np.array([100.0, 100.0])]
clipped_grad = optimizer._clip_gradients(grad)
self.assertAllClose(clipped_grad[0], [2**0.5 / 2, 2**0.5 / 2])
def test_clip_value(self):
with self.strategy.scope():
optimizer = SGD(clipvalue=1)
grad = [np.array([100.0, 100.0])]
clipped_grad = optimizer._clip_gradients(grad)
self.assertAllClose(clipped_grad[0], [1.0, 1.0])
| keras-core/keras_core/backend/tensorflow/optimizer_distribute_test.py/0 | {
"file_path": "keras-core/keras_core/backend/tensorflow/optimizer_distribute_test.py",
"repo_id": "keras-core",
"token_count": 2533
} | 28 |
import torch
from keras_core import ops
from keras_core import optimizers
from keras_core.backend.torch.optimizers import torch_parallel_optimizer
class Adagrad(
torch_parallel_optimizer.TorchParallelOptimizer, optimizers.Adagrad
):
def _parallel_update_step(
self,
grads,
variables,
learning_rate,
):
keras_variables = variables
variables = [v.value for v in variables]
dtype = variables[0].dtype
lr = ops.cast(learning_rate, dtype)
accumulators = [
self._accumulators[self._get_variable_index(variable)].value
for variable in keras_variables
]
torch._foreach_add_(accumulators, torch._foreach_mul(grads, grads))
torch._foreach_add_(
variables,
torch._foreach_div(
torch._foreach_mul(grads, lr),
torch._foreach_sqrt(
torch._foreach_add(accumulators, self.epsilon)
),
),
alpha=-1,
)
| keras-core/keras_core/backend/torch/optimizers/torch_adagrad.py/0 | {
"file_path": "keras-core/keras_core/backend/torch/optimizers/torch_adagrad.py",
"repo_id": "keras-core",
"token_count": 510
} | 29 |
import pytest
from keras_core import callbacks
from keras_core import layers
from keras_core import optimizers
from keras_core import testing
from keras_core.models import Sequential
from keras_core.testing import test_utils
from keras_core.utils import io_utils
from keras_core.utils import numerical_utils
class ReduceLROnPlateauTest(testing.TestCase):
def setUp(self):
(x_train, y_train), (x_test, y_test) = test_utils.get_test_data(
train_samples=10,
test_samples=10,
input_shape=(3,),
num_classes=2,
)
y_test = numerical_utils.to_categorical(y_test)
y_train = numerical_utils.to_categorical(y_train)
model = Sequential([layers.Dense(5), layers.Dense(2)])
model.compile(
loss="mse",
optimizer=optimizers.Adam(0.1),
)
self.model = model
self.x_train = x_train
self.x_test = x_test
self.y_train = y_train
self.y_test = y_test
@pytest.mark.requires_trainable_backend
def test_reduces_lr_with_model_fit(self):
reduce_lr = callbacks.ReduceLROnPlateau(
patience=1, factor=0.1, monitor="val_loss", min_delta=100
)
self.model.fit(
self.x_train,
self.y_train,
validation_data=(self.x_test, self.y_test),
callbacks=[reduce_lr],
epochs=2,
)
self.assertEqual(self.model.optimizer.learning_rate.value, 0.01)
@pytest.mark.requires_trainable_backend
def test_throws_when_optimizer_has_schedule(self):
reduce_lr = callbacks.ReduceLROnPlateau(
patience=1, factor=0.1, monitor="val_loss", min_delta=100
)
self.model.compile(
loss="mse",
optimizer=optimizers.Adam(
optimizers.schedules.PolynomialDecay(
initial_learning_rate=0.1, decay_steps=10
)
),
)
with self.assertRaisesRegex(
TypeError,
"This optimizer was created with a `LearningRateSchedule`",
):
self.model.fit(
self.x_train,
self.y_train,
validation_data=(self.x_test, self.y_test),
callbacks=[reduce_lr],
epochs=2,
)
@pytest.mark.requires_trainable_backend
def test_verbose_logging(self):
reduce_lr = callbacks.ReduceLROnPlateau(
patience=1, factor=0.1, monitor="val_loss", min_delta=100, verbose=1
)
io_utils.disable_interactive_logging()
io_utils.set_logging_verbosity("INFO")
with self.assertLogs() as logs:
self.model.fit(
self.x_train,
self.y_train,
validation_data=(self.x_test, self.y_test),
callbacks=[reduce_lr],
epochs=2,
)
expected_log = "ReduceLROnPlateau reducing learning rate to 0.01"
self.assertTrue(any(expected_log in log for log in logs.output))
@pytest.mark.requires_trainable_backend
def test_honors_min_lr(self):
reduce_lr = callbacks.ReduceLROnPlateau(
patience=1,
factor=0.1,
monitor="val_loss",
min_delta=10,
min_lr=0.005,
)
self.model.fit(
self.x_train,
self.y_train,
validation_data=(self.x_test, self.y_test),
callbacks=[reduce_lr],
epochs=4,
)
self.assertEqual(self.model.optimizer.learning_rate.value, 0.005)
@pytest.mark.requires_trainable_backend
def test_cooldown(self):
reduce_lr = callbacks.ReduceLROnPlateau(
patience=1,
factor=0.1,
monitor="val_loss",
min_delta=100,
cooldown=2,
)
self.model.fit(
self.x_train,
self.y_train,
validation_data=(self.x_test, self.y_test),
callbacks=[reduce_lr],
epochs=4,
)
# With a cooldown of 2 epochs, we should only reduce the LR every other
# epoch, so after 4 epochs we will have reduced 2 times.
self.assertAllClose(self.model.optimizer.learning_rate.value, 0.001)
| keras-core/keras_core/callbacks/reduce_lr_on_plateau_test.py/0 | {
"file_path": "keras-core/keras_core/callbacks/reduce_lr_on_plateau_test.py",
"repo_id": "keras-core",
"token_count": 2236
} | 30 |
"""Fashion-MNIST dataset."""
import gzip
import os
import numpy as np
from keras_core.api_export import keras_core_export
from keras_core.utils.file_utils import get_file
@keras_core_export("keras_core.datasets.fashion_mnist.load_data")
def load_data():
"""Loads the Fashion-MNIST dataset.
This is a dataset of 60,000 28x28 grayscale images of 10 fashion categories,
along with a test set of 10,000 images. This dataset can be used as
a drop-in replacement for MNIST.
The classes are:
| Label | Description |
|:-----:|-------------|
| 0 | T-shirt/top |
| 1 | Trouser |
| 2 | Pullover |
| 3 | Dress |
| 4 | Coat |
| 5 | Sandal |
| 6 | Shirt |
| 7 | Sneaker |
| 8 | Bag |
| 9 | Ankle boot |
Returns:
Tuple of NumPy arrays: `(x_train, y_train), (x_test, y_test)`.
**`x_train`**: `uint8` NumPy array of grayscale image data with shapes
`(60000, 28, 28)`, containing the training data.
**`y_train`**: `uint8` NumPy array of labels (integers in range 0-9)
with shape `(60000,)` for the training data.
**`x_test`**: `uint8` NumPy array of grayscale image data with shapes
(10000, 28, 28), containing the test data.
**`y_test`**: `uint8` NumPy array of labels (integers in range 0-9)
with shape `(10000,)` for the test data.
Example:
```python
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
assert x_train.shape == (60000, 28, 28)
assert x_test.shape == (10000, 28, 28)
assert y_train.shape == (60000,)
assert y_test.shape == (10000,)
```
License:
The copyright for Fashion-MNIST is held by Zalando SE.
Fashion-MNIST is licensed under the [MIT license](
https://github.com/zalandoresearch/fashion-mnist/blob/master/LICENSE).
"""
dirname = os.path.join("datasets", "fashion-mnist")
base = "https://storage.googleapis.com/tensorflow/tf-keras-datasets/"
files = [
"train-labels-idx1-ubyte.gz",
"train-images-idx3-ubyte.gz",
"t10k-labels-idx1-ubyte.gz",
"t10k-images-idx3-ubyte.gz",
]
paths = []
for fname in files:
paths.append(get_file(fname, origin=base + fname, cache_subdir=dirname))
with gzip.open(paths[0], "rb") as lbpath:
y_train = np.frombuffer(lbpath.read(), np.uint8, offset=8)
with gzip.open(paths[1], "rb") as imgpath:
x_train = np.frombuffer(imgpath.read(), np.uint8, offset=16).reshape(
len(y_train), 28, 28
)
with gzip.open(paths[2], "rb") as lbpath:
y_test = np.frombuffer(lbpath.read(), np.uint8, offset=8)
with gzip.open(paths[3], "rb") as imgpath:
x_test = np.frombuffer(imgpath.read(), np.uint8, offset=16).reshape(
len(y_test), 28, 28
)
return (x_train, y_train), (x_test, y_test)
| keras-core/keras_core/datasets/fashion_mnist.py/0 | {
"file_path": "keras-core/keras_core/datasets/fashion_mnist.py",
"repo_id": "keras-core",
"token_count": 1316
} | 31 |
from keras_core.api_export import keras_core_export
from keras_core.layers.activations.activation import Activation
from keras_core.layers.activations.elu import ELU
from keras_core.layers.activations.leaky_relu import LeakyReLU
from keras_core.layers.activations.prelu import PReLU
from keras_core.layers.activations.relu import ReLU
from keras_core.layers.activations.softmax import Softmax
from keras_core.layers.attention.additive_attention import AdditiveAttention
from keras_core.layers.attention.attention import Attention
from keras_core.layers.attention.multi_head_attention import MultiHeadAttention
from keras_core.layers.convolutional.conv1d import Conv1D
from keras_core.layers.convolutional.conv1d_transpose import Conv1DTranspose
from keras_core.layers.convolutional.conv2d import Conv2D
from keras_core.layers.convolutional.conv2d_transpose import Conv2DTranspose
from keras_core.layers.convolutional.conv3d import Conv3D
from keras_core.layers.convolutional.conv3d_transpose import Conv3DTranspose
from keras_core.layers.convolutional.depthwise_conv1d import DepthwiseConv1D
from keras_core.layers.convolutional.depthwise_conv2d import DepthwiseConv2D
from keras_core.layers.convolutional.separable_conv1d import SeparableConv1D
from keras_core.layers.convolutional.separable_conv2d import SeparableConv2D
from keras_core.layers.core.dense import Dense
from keras_core.layers.core.einsum_dense import EinsumDense
from keras_core.layers.core.embedding import Embedding
from keras_core.layers.core.identity import Identity
from keras_core.layers.core.input_layer import Input
from keras_core.layers.core.input_layer import InputLayer
from keras_core.layers.core.lambda_layer import Lambda
from keras_core.layers.core.masking import Masking
from keras_core.layers.core.wrapper import Wrapper
from keras_core.layers.layer import Layer
from keras_core.layers.merging.add import Add
from keras_core.layers.merging.add import add
from keras_core.layers.merging.average import Average
from keras_core.layers.merging.average import average
from keras_core.layers.merging.concatenate import Concatenate
from keras_core.layers.merging.concatenate import concatenate
from keras_core.layers.merging.dot import Dot
from keras_core.layers.merging.dot import dot
from keras_core.layers.merging.maximum import Maximum
from keras_core.layers.merging.maximum import maximum
from keras_core.layers.merging.minimum import Minimum
from keras_core.layers.merging.minimum import minimum
from keras_core.layers.merging.multiply import Multiply
from keras_core.layers.merging.multiply import multiply
from keras_core.layers.merging.subtract import Subtract
from keras_core.layers.merging.subtract import subtract
from keras_core.layers.normalization.batch_normalization import (
BatchNormalization,
)
from keras_core.layers.normalization.group_normalization import (
GroupNormalization,
)
from keras_core.layers.normalization.layer_normalization import (
LayerNormalization,
)
from keras_core.layers.normalization.spectral_normalization import (
SpectralNormalization,
)
from keras_core.layers.normalization.unit_normalization import UnitNormalization
from keras_core.layers.pooling.average_pooling1d import AveragePooling1D
from keras_core.layers.pooling.average_pooling2d import AveragePooling2D
from keras_core.layers.pooling.average_pooling3d import AveragePooling3D
from keras_core.layers.pooling.global_average_pooling1d import (
GlobalAveragePooling1D,
)
from keras_core.layers.pooling.global_average_pooling2d import (
GlobalAveragePooling2D,
)
from keras_core.layers.pooling.global_average_pooling3d import (
GlobalAveragePooling3D,
)
from keras_core.layers.pooling.global_max_pooling1d import GlobalMaxPooling1D
from keras_core.layers.pooling.global_max_pooling2d import GlobalMaxPooling2D
from keras_core.layers.pooling.global_max_pooling3d import GlobalMaxPooling3D
from keras_core.layers.pooling.max_pooling1d import MaxPooling1D
from keras_core.layers.pooling.max_pooling2d import MaxPooling2D
from keras_core.layers.pooling.max_pooling3d import MaxPooling3D
from keras_core.layers.preprocessing.category_encoding import CategoryEncoding
from keras_core.layers.preprocessing.center_crop import CenterCrop
from keras_core.layers.preprocessing.discretization import Discretization
from keras_core.layers.preprocessing.hashed_crossing import HashedCrossing
from keras_core.layers.preprocessing.hashing import Hashing
from keras_core.layers.preprocessing.index_lookup import IndexLookup
from keras_core.layers.preprocessing.integer_lookup import IntegerLookup
from keras_core.layers.preprocessing.normalization import Normalization
from keras_core.layers.preprocessing.random_brightness import RandomBrightness
from keras_core.layers.preprocessing.random_contrast import RandomContrast
from keras_core.layers.preprocessing.random_crop import RandomCrop
from keras_core.layers.preprocessing.random_flip import RandomFlip
from keras_core.layers.preprocessing.random_rotation import RandomRotation
from keras_core.layers.preprocessing.random_translation import RandomTranslation
from keras_core.layers.preprocessing.random_zoom import RandomZoom
from keras_core.layers.preprocessing.rescaling import Rescaling
from keras_core.layers.preprocessing.resizing import Resizing
from keras_core.layers.preprocessing.string_lookup import StringLookup
from keras_core.layers.preprocessing.text_vectorization import TextVectorization
from keras_core.layers.regularization.activity_regularization import (
ActivityRegularization,
)
from keras_core.layers.regularization.dropout import Dropout
from keras_core.layers.regularization.gaussian_dropout import GaussianDropout
from keras_core.layers.regularization.gaussian_noise import GaussianNoise
from keras_core.layers.regularization.spatial_dropout import SpatialDropout1D
from keras_core.layers.regularization.spatial_dropout import SpatialDropout2D
from keras_core.layers.regularization.spatial_dropout import SpatialDropout3D
from keras_core.layers.reshaping.cropping1d import Cropping1D
from keras_core.layers.reshaping.cropping2d import Cropping2D
from keras_core.layers.reshaping.cropping3d import Cropping3D
from keras_core.layers.reshaping.flatten import Flatten
from keras_core.layers.reshaping.permute import Permute
from keras_core.layers.reshaping.repeat_vector import RepeatVector
from keras_core.layers.reshaping.reshape import Reshape
from keras_core.layers.reshaping.up_sampling1d import UpSampling1D
from keras_core.layers.reshaping.up_sampling2d import UpSampling2D
from keras_core.layers.reshaping.up_sampling3d import UpSampling3D
from keras_core.layers.reshaping.zero_padding1d import ZeroPadding1D
from keras_core.layers.reshaping.zero_padding2d import ZeroPadding2D
from keras_core.layers.reshaping.zero_padding3d import ZeroPadding3D
from keras_core.layers.rnn.bidirectional import Bidirectional
from keras_core.layers.rnn.conv_lstm1d import ConvLSTM1D
from keras_core.layers.rnn.conv_lstm2d import ConvLSTM2D
from keras_core.layers.rnn.conv_lstm3d import ConvLSTM3D
from keras_core.layers.rnn.gru import GRU
from keras_core.layers.rnn.gru import GRUCell
from keras_core.layers.rnn.lstm import LSTM
from keras_core.layers.rnn.lstm import LSTMCell
from keras_core.layers.rnn.rnn import RNN
from keras_core.layers.rnn.simple_rnn import SimpleRNN
from keras_core.layers.rnn.simple_rnn import SimpleRNNCell
from keras_core.layers.rnn.stacked_rnn_cells import StackedRNNCells
from keras_core.layers.rnn.time_distributed import TimeDistributed
from keras_core.saving import serialization_lib
@keras_core_export("keras_core.layers.serialize")
def serialize(layer):
"""Returns the layer configuration as a Python dict.
Args:
layer: A `keras.layers.Layer` instance to serialize.
Returns:
Python dict which contains the configuration of the layer.
"""
return serialization_lib.serialize_keras_object(layer)
@keras_core_export("keras_core.layers.deserialize")
def deserialize(config, custom_objects=None):
"""Returns a Keras layer object via its configuration.
Args:
config: A python dict containing a serialized layer configuration.
custom_objects: Optional dictionary mapping names (strings) to custom
objects (classes and functions) to be considered during
deserialization.
Returns:
A Keras layer instance.
"""
obj = serialization_lib.deserialize_keras_object(
config,
custom_objects=custom_objects,
)
if not isinstance(obj, Layer):
raise ValueError(
"`keras.layers.deserialize` was passed a `config` object that is "
f"not a `keras.layers.Layer`. Received: {config}"
)
return obj
| keras-core/keras_core/layers/__init__.py/0 | {
"file_path": "keras-core/keras_core/layers/__init__.py",
"repo_id": "keras-core",
"token_count": 2961
} | 32 |
import numpy as np
from keras_core import layers
from keras_core import testing
class AdditiveAttentionTest(testing.TestCase):
def test_attention_basics(self):
# No scale
self.run_layer_test(
layers.AdditiveAttention,
init_kwargs={
"use_scale": True,
"dropout": 0.5,
},
input_shape=[(2, 3, 4), (2, 4, 4)],
expected_output_shape=(2, 3, 4),
expected_num_trainable_weights=1,
expected_num_non_trainable_weights=0,
expected_num_seed_generators=0,
expected_num_losses=0,
supports_masking=True,
run_training_check=False,
)
# Sale.
self.run_layer_test(
layers.AdditiveAttention,
init_kwargs={
"use_scale": False,
"dropout": 0.5,
},
input_shape=[(2, 3, 4), (2, 4, 4)],
expected_output_shape=(2, 3, 4),
expected_num_trainable_weights=0,
expected_num_non_trainable_weights=0,
expected_num_seed_generators=0,
expected_num_losses=0,
supports_masking=True,
run_training_check=False,
)
def test_attention_correctness(self):
query = np.array([[[1.0, 0.0], [0.0, 1.0]]])
key = np.array([[[0.0, 1.0], [1.0, 0.0]]])
value = np.array([[[1.0, 2.0], [3.0, 4.0]]])
layer = layers.AdditiveAttention(use_scale=False)
output, scores = layer(
[query, value, key],
return_attention_scores=True,
)
self.assertAllClose(
output, [[[1.727, 2.727], [2.272, 3.272]]], atol=1e-3
)
self.assertAllClose(
scores, [[[0.636, 0.363], [0.363, 0.636]]], atol=1e-3
)
def test_attention_with_mask(self):
layer = layers.AdditiveAttention(use_scale=False)
query = np.array([[[1.0, 0.0], [0.0, 1.0]]])
value = np.array([[[1.0, 1.0], [1.0, 1.0]]])
query_mask = np.array([[True, False]])
value_mask = np.array([[True, False]])
output, scores = layer(
[query, value],
mask=[query_mask, value_mask],
return_attention_scores=True,
)
self.assertAllClose(output, [[[1.0, 1.0], [0.0, 0.0]]])
self.assertAllClose(scores, [[[1.0, 0.0], [1.0, 0.0]]])
def test_attention_errors(self):
layer = layers.AdditiveAttention()
tensor = np.array([[[1.0, 1.0], [1.0, 1.0]]])
with self.assertRaisesRegex(ValueError, "must be called on a list"):
layer(tensor)
with self.assertRaisesRegex(ValueError, "length 2 or 3"):
layer([tensor, tensor, tensor, tensor])
with self.assertRaisesRegex(ValueError, "layer mask must be a list"):
layer([tensor, tensor], mask=tensor)
with self.assertRaisesRegex(ValueError, "length 2 or 3"):
layer([tensor, tensor], mask=[tensor])
| keras-core/keras_core/layers/attention/additive_attention_test.py/0 | {
"file_path": "keras-core/keras_core/layers/attention/additive_attention_test.py",
"repo_id": "keras-core",
"token_count": 1595
} | 33 |
import numpy as np
import pytest
from absl.testing import parameterized
from numpy.lib.stride_tricks import as_strided
from keras_core import layers
from keras_core import testing
def _same_padding(input_size, kernel_size, stride):
if input_size % stride == 0:
padding = max(kernel_size - stride, 0)
else:
padding = max(kernel_size - (input_size % stride), 0)
return padding // 2, padding - padding // 2
def np_conv1d(
x,
kernel_weights,
bias_weights,
strides,
padding,
data_format,
dilation_rate,
groups,
):
if data_format == "channels_first":
x = x.swapaxes(1, 2)
if isinstance(strides, (tuple, list)):
h_stride = strides[0]
else:
h_stride = strides
if isinstance(dilation_rate, (tuple, list)):
dilation_rate = dilation_rate[0]
kernel_size, ch_in, ch_out = kernel_weights.shape
if dilation_rate > 1:
new_kernel_size = kernel_size + (dilation_rate - 1) * (kernel_size - 1)
new_kernel_weights = np.zeros(
(new_kernel_size, ch_in, ch_out), dtype=kernel_weights.dtype
)
new_kernel_weights[::dilation_rate] = kernel_weights
kernel_weights = new_kernel_weights
kernel_size = kernel_weights.shape[0]
if padding != "valid":
n_batch, h_x, _ = x.shape
h_pad = _same_padding(h_x, kernel_size, h_stride)
npad = [(0, 0)] * x.ndim
if padding == "causal":
npad[1] = (h_pad[0] + h_pad[1], 0)
else:
npad[1] = h_pad
x = np.pad(x, pad_width=npad, mode="constant", constant_values=0)
n_batch, h_x, _ = x.shape
h_out = int((h_x - kernel_size) / h_stride) + 1
kernel_weights = kernel_weights.reshape(-1, ch_out)
bias_weights = bias_weights.reshape(1, ch_out)
out_grps = []
for grp in range(1, groups + 1):
x_in = x[..., (grp - 1) * ch_in : grp * ch_in]
stride_shape = (n_batch, h_out, kernel_size, ch_in)
strides = (
x_in.strides[0],
h_stride * x_in.strides[1],
x_in.strides[1],
x_in.strides[2],
)
inner_dim = kernel_size * ch_in
x_strided = as_strided(
x_in, shape=stride_shape, strides=strides
).reshape(n_batch, h_out, inner_dim)
ch_out_groups = ch_out // groups
kernel_weights_grp = kernel_weights[
..., (grp - 1) * ch_out_groups : grp * ch_out_groups
]
bias_weights_grp = bias_weights[
..., (grp - 1) * ch_out_groups : grp * ch_out_groups
]
out_grps.append(x_strided @ kernel_weights_grp + bias_weights_grp)
out = np.concatenate(out_grps, axis=-1)
if data_format == "channels_first":
out = out.swapaxes(1, 2)
return out
def np_conv2d(
x,
kernel_weights,
bias_weights,
strides,
padding,
data_format,
dilation_rate,
groups,
):
if data_format == "channels_first":
x = x.transpose((0, 2, 3, 1))
if isinstance(strides, (tuple, list)):
h_stride, w_stride = strides
else:
h_stride = strides
w_stride = strides
if isinstance(dilation_rate, (tuple, list)):
h_dilation, w_dilation = dilation_rate
else:
h_dilation = dilation_rate
w_dilation = dilation_rate
h_kernel, w_kernel, ch_in, ch_out = kernel_weights.shape
if h_dilation > 1 or w_dilation > 1:
new_h_kernel = h_kernel + (h_dilation - 1) * (h_kernel - 1)
new_w_kernel = w_kernel + (w_dilation - 1) * (w_kernel - 1)
new_kenel_size_tuple = (new_h_kernel, new_w_kernel)
new_kernel_weights = np.zeros(
(*new_kenel_size_tuple, ch_in, ch_out),
dtype=kernel_weights.dtype,
)
new_kernel_weights[::h_dilation, ::w_dilation] = kernel_weights
kernel_weights = new_kernel_weights
h_kernel, w_kernel = kernel_weights.shape[:2]
if padding == "same":
n_batch, h_x, w_x, _ = x.shape
h_pad = _same_padding(h_x, h_kernel, h_stride)
w_pad = _same_padding(w_x, w_kernel, w_stride)
npad = [(0, 0)] * x.ndim
npad[1] = h_pad
npad[2] = w_pad
x = np.pad(x, pad_width=npad, mode="constant", constant_values=0)
n_batch, h_x, w_x, _ = x.shape
h_out = int((h_x - h_kernel) / h_stride) + 1
w_out = int((w_x - w_kernel) / w_stride) + 1
out_grps = []
for grp in range(1, groups + 1):
x_in = x[..., (grp - 1) * ch_in : grp * ch_in]
stride_shape = (n_batch, h_out, w_out, h_kernel, w_kernel, ch_in)
strides = (
x_in.strides[0],
h_stride * x_in.strides[1],
w_stride * x_in.strides[2],
x_in.strides[1],
x_in.strides[2],
x_in.strides[3],
)
inner_dim = h_kernel * w_kernel * ch_in
x_strided = as_strided(
x_in, shape=stride_shape, strides=strides
).reshape(-1, inner_dim)
ch_out_groups = ch_out // groups
kernel_weights_grp = kernel_weights[
..., (grp - 1) * ch_out_groups : grp * ch_out_groups
].reshape(-1, ch_out_groups)
bias_weights_grp = bias_weights[
..., (grp - 1) * ch_out_groups : grp * ch_out_groups
]
out_grps.append(x_strided @ kernel_weights_grp + bias_weights_grp)
out = np.concatenate(out_grps, axis=-1).reshape(
n_batch, h_out, w_out, ch_out
)
if data_format == "channels_first":
out = out.transpose((0, 3, 1, 2))
return out
def np_conv3d(
x,
kernel_weights,
bias_weights,
strides,
padding,
data_format,
dilation_rate,
groups,
):
if data_format == "channels_first":
x = x.transpose((0, 2, 3, 4, 1))
if isinstance(strides, (tuple, list)):
h_stride, w_stride, d_stride = strides
else:
h_stride = strides
w_stride = strides
d_stride = strides
if isinstance(dilation_rate, (tuple, list)):
h_dilation, w_dilation, d_dilation = dilation_rate
else:
h_dilation = dilation_rate
w_dilation = dilation_rate
d_dilation = dilation_rate
h_kernel, w_kernel, d_kernel, ch_in, ch_out = kernel_weights.shape
if h_dilation > 1 or w_dilation > 1 or d_dilation > 1:
new_h_kernel = h_kernel + (h_dilation - 1) * (h_kernel - 1)
new_w_kernel = w_kernel + (w_dilation - 1) * (w_kernel - 1)
new_d_kernel = d_kernel + (d_dilation - 1) * (d_kernel - 1)
new_kenel_size_tuple = (new_h_kernel, new_w_kernel, new_d_kernel)
new_kernel_weights = np.zeros(
(*new_kenel_size_tuple, ch_in, ch_out),
dtype=kernel_weights.dtype,
)
new_kernel_weights[
::h_dilation, ::w_dilation, ::d_dilation
] = kernel_weights
kernel_weights = new_kernel_weights
h_kernel, w_kernel, d_kernel = kernel_weights.shape[:3]
if padding == "same":
n_batch, h_x, w_x, d_x, _ = x.shape
h_pad = _same_padding(h_x, h_kernel, h_stride)
w_pad = _same_padding(w_x, w_kernel, w_stride)
d_pad = _same_padding(d_x, d_kernel, d_stride)
npad = [(0, 0)] * x.ndim
npad[1] = h_pad
npad[2] = w_pad
npad[3] = d_pad
x = np.pad(x, pad_width=npad, mode="constant", constant_values=0)
n_batch, h_x, w_x, d_x, _ = x.shape
h_out = int((h_x - h_kernel) / h_stride) + 1
w_out = int((w_x - w_kernel) / w_stride) + 1
d_out = int((d_x - d_kernel) / d_stride) + 1
out_grps = []
for grp in range(1, groups + 1):
x_in = x[..., (grp - 1) * ch_in : grp * ch_in]
stride_shape = (
n_batch,
h_out,
w_out,
d_out,
h_kernel,
w_kernel,
d_kernel,
ch_in,
)
strides = (
x_in.strides[0],
h_stride * x_in.strides[1],
w_stride * x_in.strides[2],
d_stride * x_in.strides[3],
x_in.strides[1],
x_in.strides[2],
x_in.strides[3],
x_in.strides[4],
)
inner_dim = h_kernel * w_kernel * d_kernel * ch_in
x_strided = as_strided(
x_in, shape=stride_shape, strides=strides
).reshape(-1, inner_dim)
ch_out_groups = ch_out // groups
kernel_weights_grp = kernel_weights[
..., (grp - 1) * ch_out_groups : grp * ch_out_groups
].reshape(-1, ch_out_groups)
bias_weights_grp = bias_weights[
..., (grp - 1) * ch_out_groups : grp * ch_out_groups
]
out_grps.append(x_strided @ kernel_weights_grp + bias_weights_grp)
out = np.concatenate(out_grps, axis=-1).reshape(
n_batch, h_out, w_out, d_out, ch_out
)
if data_format == "channels_first":
out = out.transpose((0, 4, 1, 2, 3))
return out
class ConvBasicTest(testing.TestCase, parameterized.TestCase):
@parameterized.parameters(
{
"filters": 5,
"kernel_size": 2,
"strides": 1,
"padding": "valid",
"data_format": "channels_last",
"dilation_rate": 1,
"groups": 1,
"input_shape": (3, 5, 4),
"output_shape": (3, 4, 5),
},
{
"filters": 6,
"kernel_size": 2,
"strides": 1,
"padding": "same",
"data_format": "channels_last",
"dilation_rate": (2,),
"groups": 2,
"input_shape": (3, 4, 4),
"output_shape": (3, 4, 6),
},
{
"filters": 6,
"kernel_size": 2,
"strides": 1,
"padding": "causal",
"data_format": "channels_last",
"dilation_rate": (2,),
"groups": 2,
"input_shape": (3, 4, 4),
"output_shape": (3, 4, 6),
},
{
"filters": 6,
"kernel_size": 2,
"strides": (2,),
"padding": "valid",
"data_format": "channels_last",
"dilation_rate": 1,
"groups": 2,
"input_shape": (3, 5, 4),
"output_shape": (3, 2, 6),
},
)
@pytest.mark.requires_trainable_backend
def test_conv1d_basic(
self,
filters,
kernel_size,
strides,
padding,
data_format,
dilation_rate,
groups,
input_shape,
output_shape,
):
self.run_layer_test(
layers.Conv1D,
init_kwargs={
"filters": filters,
"kernel_size": kernel_size,
"strides": strides,
"padding": padding,
"data_format": data_format,
"dilation_rate": dilation_rate,
"groups": groups,
},
input_shape=input_shape,
expected_output_shape=output_shape,
expected_num_trainable_weights=2,
expected_num_non_trainable_weights=0,
expected_num_losses=0,
supports_masking=False,
)
@parameterized.parameters(
{
"filters": 5,
"kernel_size": 2,
"strides": 1,
"padding": "valid",
"data_format": "channels_last",
"dilation_rate": 1,
"groups": 1,
"input_shape": (3, 5, 5, 4),
"output_shape": (3, 4, 4, 5),
},
{
"filters": 6,
"kernel_size": 2,
"strides": 1,
"padding": "same",
"data_format": "channels_last",
"dilation_rate": (2, 2),
"groups": 2,
"input_shape": (3, 4, 4, 4),
"output_shape": (3, 4, 4, 6),
},
{
"filters": 6,
"kernel_size": (2, 2),
"strides": (2, 1),
"padding": "valid",
"data_format": "channels_last",
"dilation_rate": (1, 1),
"groups": 2,
"input_shape": (3, 5, 5, 4),
"output_shape": (3, 2, 4, 6),
},
)
@pytest.mark.requires_trainable_backend
def test_conv2d_basic(
self,
filters,
kernel_size,
strides,
padding,
data_format,
dilation_rate,
groups,
input_shape,
output_shape,
):
self.run_layer_test(
layers.Conv2D,
init_kwargs={
"filters": filters,
"kernel_size": kernel_size,
"strides": strides,
"padding": padding,
"data_format": data_format,
"dilation_rate": dilation_rate,
"groups": groups,
},
input_shape=input_shape,
expected_output_shape=output_shape,
expected_num_trainable_weights=2,
expected_num_non_trainable_weights=0,
expected_num_losses=0,
supports_masking=False,
)
@parameterized.parameters(
{
"filters": 5,
"kernel_size": 2,
"strides": 1,
"padding": "valid",
"data_format": "channels_last",
"dilation_rate": 1,
"groups": 1,
"input_shape": (3, 5, 5, 5, 4),
"output_shape": (3, 4, 4, 4, 5),
},
{
"filters": 6,
"kernel_size": 2,
"strides": 1,
"padding": "same",
"data_format": "channels_last",
"dilation_rate": (2, 2, 2),
"groups": 2,
"input_shape": (3, 4, 4, 4, 4),
"output_shape": (3, 4, 4, 4, 6),
},
{
"filters": 6,
"kernel_size": (2, 2, 3),
"strides": (2, 1, 2),
"padding": "valid",
"data_format": "channels_last",
"dilation_rate": (1, 1, 1),
"groups": 2,
"input_shape": (3, 5, 5, 5, 4),
"output_shape": (3, 2, 4, 2, 6),
},
)
@pytest.mark.requires_trainable_backend
def test_conv3d_basic(
self,
filters,
kernel_size,
strides,
padding,
data_format,
dilation_rate,
groups,
input_shape,
output_shape,
):
self.run_layer_test(
layers.Conv3D,
init_kwargs={
"filters": filters,
"kernel_size": kernel_size,
"strides": strides,
"padding": padding,
"data_format": data_format,
"dilation_rate": dilation_rate,
"groups": groups,
},
input_shape=input_shape,
expected_output_shape=output_shape,
expected_num_trainable_weights=2,
expected_num_non_trainable_weights=0,
expected_num_losses=0,
supports_masking=False,
)
def test_bad_init_args(self):
# `filters` is not positive.
with self.assertRaises(ValueError):
layers.Conv1D(filters=0, kernel_size=1)
# `kernel_size` has 0.
with self.assertRaises(ValueError):
layers.Conv2D(filters=2, kernel_size=(1, 0))
# `strides` has 0.
with self.assertRaises(ValueError):
layers.Conv2D(filters=2, kernel_size=(2, 2), strides=(1, 0))
# `dilation_rate > 1` while `strides > 1`.
with self.assertRaises(ValueError):
layers.Conv2D(
filters=2, kernel_size=(2, 2), strides=2, dilation_rate=(2, 1)
)
# `filters` cannot be divided by `groups`.
with self.assertRaises(ValueError):
layers.Conv2D(filters=5, kernel_size=(2, 2), groups=2)
class ConvCorrectnessTest(testing.TestCase, parameterized.TestCase):
@parameterized.parameters(
{
"filters": 5,
"kernel_size": 2,
"strides": 1,
"padding": "valid",
"data_format": "channels_last",
"dilation_rate": 1,
"groups": 1,
},
{
"filters": 6,
"kernel_size": 2,
"strides": 1,
"padding": "same",
"data_format": "channels_last",
"dilation_rate": (2,),
"groups": 2,
},
{
"filters": 6,
"kernel_size": 2,
"strides": 1,
"padding": "causal",
"data_format": "channels_last",
"dilation_rate": (2,),
"groups": 2,
},
{
"filters": 6,
"kernel_size": (2,),
"strides": (2,),
"padding": "valid",
"data_format": "channels_last",
"dilation_rate": 1,
"groups": 2,
},
{
"filters": 6,
"kernel_size": (2,),
"strides": (2,),
"padding": "valid",
"data_format": "channels_first",
"dilation_rate": 1,
"groups": 2,
},
)
def test_conv1d(
self,
filters,
kernel_size,
strides,
padding,
data_format,
dilation_rate,
groups,
):
layer = layers.Conv1D(
filters=filters,
kernel_size=kernel_size,
strides=strides,
padding=padding,
data_format=data_format,
dilation_rate=dilation_rate,
groups=groups,
)
inputs = np.random.normal(size=[2, 8, 4])
layer.build(input_shape=inputs.shape)
kernel_shape = layer.kernel.shape
kernel_weights = np.random.normal(size=kernel_shape)
bias_weights = np.random.normal(size=(filters,))
layer.kernel.assign(kernel_weights)
layer.bias.assign(bias_weights)
outputs = layer(inputs)
expected = np_conv1d(
inputs,
kernel_weights,
bias_weights,
strides=strides,
padding=padding,
data_format=data_format,
dilation_rate=dilation_rate,
groups=groups,
)
self.assertAllClose(outputs, expected)
@parameterized.parameters(
{
"filters": 5,
"kernel_size": 2,
"strides": 1,
"padding": "valid",
"data_format": "channels_last",
"dilation_rate": 1,
"groups": 1,
},
{
"filters": 4,
"kernel_size": 3,
"strides": 2,
"padding": "same",
"data_format": "channels_last",
"dilation_rate": 1,
"groups": 1,
},
{
"filters": 6,
"kernel_size": 2,
"strides": 1,
"padding": "same",
"data_format": "channels_last",
"dilation_rate": (2, 2),
"groups": 2,
},
{
"filters": 6,
"kernel_size": 2,
"strides": 1,
"padding": "same",
"data_format": "channels_last",
"dilation_rate": (2, 3),
"groups": 2,
},
{
"filters": 6,
"kernel_size": (4, 3),
"strides": (2, 1),
"padding": "valid",
"data_format": "channels_last",
"dilation_rate": (1, 1),
"groups": 2,
},
{
"filters": 6,
"kernel_size": (4, 3),
"strides": (2, 1),
"padding": "valid",
"data_format": "channels_first",
"dilation_rate": (1, 1),
"groups": 2,
},
)
def test_conv2d(
self,
filters,
kernel_size,
strides,
padding,
data_format,
dilation_rate,
groups,
):
layer = layers.Conv2D(
filters=filters,
kernel_size=kernel_size,
strides=strides,
padding=padding,
data_format=data_format,
dilation_rate=dilation_rate,
groups=groups,
)
inputs = np.random.normal(size=[2, 8, 8, 4])
layer.build(input_shape=inputs.shape)
kernel_shape = layer.kernel.shape
kernel_weights = np.random.normal(size=kernel_shape)
bias_weights = np.random.normal(size=(filters,))
layer.kernel.assign(kernel_weights)
layer.bias.assign(bias_weights)
outputs = layer(inputs)
expected = np_conv2d(
inputs,
kernel_weights,
bias_weights,
strides=strides,
padding=padding,
data_format=data_format,
dilation_rate=dilation_rate,
groups=groups,
)
self.assertAllClose(outputs, expected, rtol=5e-4)
@parameterized.parameters(
{
"filters": 5,
"kernel_size": 2,
"strides": 1,
"padding": "valid",
"data_format": "channels_last",
"dilation_rate": 1,
"groups": 1,
},
{
"filters": 6,
"kernel_size": 2,
"strides": 1,
"padding": "same",
"data_format": "channels_last",
"dilation_rate": (2, 2, 2),
"groups": 2,
},
{
"filters": 6,
"kernel_size": 2,
"strides": 1,
"padding": "same",
"data_format": "channels_last",
"dilation_rate": (2, 3, 4),
"groups": 2,
},
{
"filters": 6,
"kernel_size": (2, 2, 3),
"strides": (2, 1, 2),
"padding": "valid",
"data_format": "channels_last",
"dilation_rate": (1, 1, 1),
"groups": 2,
},
{
"filters": 6,
"kernel_size": (2, 2, 3),
"strides": (2, 1, 2),
"padding": "valid",
"data_format": "channels_first",
"dilation_rate": (1, 1, 1),
"groups": 2,
},
)
def test_conv3d(
self,
filters,
kernel_size,
strides,
padding,
data_format,
dilation_rate,
groups,
):
layer = layers.Conv3D(
filters=filters,
kernel_size=kernel_size,
strides=strides,
padding=padding,
data_format=data_format,
dilation_rate=dilation_rate,
groups=groups,
)
inputs = np.random.normal(size=[2, 8, 8, 8, 4])
layer.build(input_shape=inputs.shape)
kernel_shape = layer.kernel.shape
kernel_weights = np.random.normal(size=kernel_shape)
bias_weights = np.random.normal(size=(filters,))
layer.kernel.assign(kernel_weights)
layer.bias.assign(bias_weights)
outputs = layer(inputs)
expected = np_conv3d(
inputs,
kernel_weights,
bias_weights,
strides=strides,
padding=padding,
data_format=data_format,
dilation_rate=dilation_rate,
groups=groups,
)
self.assertAllClose(outputs, expected, rtol=5e-4)
| keras-core/keras_core/layers/convolutional/conv_test.py/0 | {
"file_path": "keras-core/keras_core/layers/convolutional/conv_test.py",
"repo_id": "keras-core",
"token_count": 13078
} | 34 |
import pytest
from absl.testing import parameterized
from keras_core import backend
from keras_core import layers
from keras_core import testing
class IdentityTest(testing.TestCase, parameterized.TestCase):
@parameterized.named_parameters(
[
{"testcase_name": "dense", "sparse": False},
{"testcase_name": "sparse", "sparse": True},
]
)
@pytest.mark.requires_trainable_backend
def test_identity_basics(self, sparse):
if sparse and not backend.SUPPORTS_SPARSE_TENSORS:
pytest.skip("Backend does not support sparse tensors.")
self.run_layer_test(
layers.Identity,
init_kwargs={},
input_shape=(2, 3),
input_sparse=sparse,
expected_output_shape=(2, 3),
expected_output_sparse=sparse,
expected_num_trainable_weights=0,
expected_num_non_trainable_weights=0,
expected_num_seed_generators=0,
expected_num_losses=0,
run_training_check=not sparse,
supports_masking=True,
)
| keras-core/keras_core/layers/core/identity_test.py/0 | {
"file_path": "keras-core/keras_core/layers/core/identity_test.py",
"repo_id": "keras-core",
"token_count": 510
} | 35 |
Subsets and Splits