index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
724,826 | scipy.sparse._dok | astype | null | def astype(self, dtype, casting='unsafe', copy=True):
dtype = np.dtype(dtype)
if self.dtype != dtype:
result = self._dok_container(self.shape, dtype=dtype)
data = np.array(list(self._dict.values()), dtype=dtype)
result._dict = dict(zip(self._dict, data))
return result
elif copy:
return self.copy()
return self
| (self, dtype, casting='unsafe', copy=True) |
724,827 | scipy.sparse._dok | clear | null | def clear(self):
return self._dict.clear()
| (self) |
724,829 | scipy.sparse._dok | conjtransp | Return the conjugate transpose. | def conjtransp(self):
"""Return the conjugate transpose."""
if self.ndim == 1:
new = self.tocoo()
new.data = new.data.conjugate()
return new
M, N = self.shape
new = self._dok_container((N, M), dtype=self.dtype)
new._dict = {(right, left): np.conj(val) for (left, right), val in self.items()}
return new
| (self) |
724,830 | scipy.sparse._base | conjugate | Element-wise complex conjugation.
If the array/matrix is of non-complex data type and `copy` is False,
this method does nothing and the data is not copied.
Parameters
----------
copy : bool, optional
If True, the result is guaranteed to not share data with self.
Returns
-------
A : The element-wise complex conjugate.
| def conjugate(self, copy=True):
"""Element-wise complex conjugation.
If the array/matrix is of non-complex data type and `copy` is False,
this method does nothing and the data is not copied.
Parameters
----------
copy : bool, optional
If True, the result is guaranteed to not share data with self.
Returns
-------
A : The element-wise complex conjugate.
"""
if np.issubdtype(self.dtype, np.complexfloating):
return self.tocsr(copy=copy).conjugate(copy=False)
elif copy:
return self.copy()
else:
return self
| (self, copy=True) |
724,831 | scipy.sparse._dok | copy | Returns a copy of this array/matrix.
No data/indices will be shared between the returned value and current
array/matrix.
| def copy(self):
new = self._dok_container(self.shape, dtype=self.dtype)
new._dict.update(self._dict)
return new
| (self) |
724,832 | scipy.sparse._dok | count_nonzero | Number of non-zero entries, equivalent to
np.count_nonzero(a.toarray())
Unlike the nnz property, which return the number of stored
entries (the length of the data attribute), this method counts the
actual number of non-zero entries in data.
| def count_nonzero(self):
return sum(x != 0 for x in self.values())
| (self) |
724,833 | scipy.sparse._dok | diagonal | null | def diagonal(self, k=0):
if self.ndim == 2:
return super().diagonal(k)
raise ValueError("diagonal requires two dimensions")
| (self, k=0) |
724,835 | scipy.sparse._dok | get | This provides dict.get method functionality with type checking | def get(self, key, default=0.0):
"""This provides dict.get method functionality with type checking"""
if key in self._dict:
return self._dict[key]
if isintlike(key) and self.ndim == 1:
key = (key,)
if self.ndim != len(key):
raise IndexError(f'Index {key} length needs to match self.shape')
try:
for i in key:
assert isintlike(i)
except (AssertionError, TypeError, ValueError) as e:
raise IndexError('Index must be or consist of integers.') from e
key = tuple(i + M if i < 0 else i for i, M in zip(key, self.shape))
if any(i < 0 or i >= M for i, M in zip(key, self.shape)):
raise IndexError('Index out of bounds.')
if self.ndim == 1:
key = key[0]
return self._dict.get(key, default)
| (self, key, default=0.0) |
724,837 | scipy.sparse._dok | get_shape | Get shape of a sparse matrix. | def get_shape(self):
"""Get shape of a sparse matrix."""
return self._shape
| (self) |
724,843 | scipy.sparse._dok | items | null | def items(self):
return self._dict.items()
| (self) |
724,844 | scipy.sparse._dok | keys | null | def keys(self):
return self._dict.keys()
| (self) |
724,845 | scipy.sparse._base | maximum | Element-wise maximum between this and another array/matrix. | def maximum(self, other):
"""Element-wise maximum between this and another array/matrix."""
return self.tocsr().maximum(other)
| (self, other) |
724,847 | scipy.sparse._base | minimum | Element-wise minimum between this and another array/matrix. | def minimum(self, other):
"""Element-wise minimum between this and another array/matrix."""
return self.tocsr().minimum(other)
| (self, other) |
724,848 | scipy.sparse._base | multiply | Point-wise multiplication by another array/matrix. | def multiply(self, other):
"""Point-wise multiplication by another array/matrix."""
return self.tocsr().multiply(other)
| (self, other) |
724,849 | scipy.sparse._base | nonzero | Nonzero indices of the array/matrix.
Returns a tuple of arrays (row,col) containing the indices
of the non-zero elements of the array.
Examples
--------
>>> from scipy.sparse import csr_array
>>> A = csr_array([[1,2,0],[0,0,3],[4,0,5]])
>>> A.nonzero()
(array([0, 0, 1, 2, 2]), array([0, 1, 2, 0, 2]))
| def nonzero(self):
"""Nonzero indices of the array/matrix.
Returns a tuple of arrays (row,col) containing the indices
of the non-zero elements of the array.
Examples
--------
>>> from scipy.sparse import csr_array
>>> A = csr_array([[1,2,0],[0,0,3],[4,0,5]])
>>> A.nonzero()
(array([0, 0, 1, 2, 2]), array([0, 1, 2, 0, 2]))
"""
# convert to COOrdinate format
A = self.tocoo()
nz_mask = A.data != 0
return (A.row[nz_mask], A.col[nz_mask])
| (self) |
724,850 | scipy.sparse._dok | pop | null | def pop(self, key, default=None, /):
return self._dict.pop(key, default)
| (self, key, default=None, /) |
724,851 | scipy.sparse._dok | popitem | null | def popitem(self):
return self._dict.popitem()
| (self) |
724,852 | scipy.sparse._base | power | Element-wise power. | def power(self, n, dtype=None):
"""Element-wise power."""
return self.tocsr().power(n, dtype=dtype)
| (self, n, dtype=None) |
724,854 | scipy.sparse._dok | resize | Resize the array/matrix in-place to dimensions given by ``shape``
Any elements that lie within the new shape will remain at the same
indices, while non-zero elements lying outside the new shape are
removed.
Parameters
----------
shape : (int, int)
number of rows and columns in the new array/matrix
Notes
-----
The semantics are not identical to `numpy.ndarray.resize` or
`numpy.resize`. Here, the same data will be maintained at each index
before and after reshape, if that index is within the new bounds. In
numpy, resizing maintains contiguity of the array, moving elements
around in the logical array but not within a flattened representation.
We give no guarantees about whether the underlying data attributes
(arrays, etc.) will be modified in place or replaced with new objects.
| def resize(self, *shape):
is_array = isinstance(self, sparray)
shape = check_shape(shape, allow_1d=is_array)
if len(shape) != len(self.shape):
# TODO implement resize across dimensions
raise NotImplementedError
if self.ndim == 1:
newN = shape[-1]
for i in list(self._dict):
if i >= newN:
del self._dict[i]
self._shape = shape
return
newM, newN = shape
M, N = self.shape
if newM < M or newN < N:
# Remove all elements outside new dimensions
for i, j in list(self.keys()):
if i >= newM or j >= newN:
del self._dict[i, j]
self._shape = shape
| (self, *shape) |
724,855 | scipy.sparse._dok | set_shape | null | def set_shape(self, shape):
new_matrix = self.reshape(shape, copy=False).asformat(self.format)
self.__dict__ = new_matrix.__dict__
| (self, shape) |
724,856 | scipy.sparse._dok | setdefault | null | def setdefault(self, key, default=None, /):
return self._dict.setdefault(key, default)
| (self, key, default=None, /) |
724,858 | scipy.sparse._base | sum |
Sum the array/matrix elements over a given axis.
Parameters
----------
axis : {-2, -1, 0, 1, None} optional
Axis along which the sum is computed. The default is to
compute the sum of all the array/matrix elements, returning a scalar
(i.e., `axis` = `None`).
dtype : dtype, optional
The type of the returned array/matrix and of the accumulator in which
the elements are summed. The dtype of `a` is used by default
unless `a` has an integer dtype of less precision than the default
platform integer. In that case, if `a` is signed then the platform
integer is used while if `a` is unsigned then an unsigned integer
of the same precision as the platform integer is used.
.. versionadded:: 0.18.0
out : np.matrix, optional
Alternative output matrix in which to place the result. It must
have the same shape as the expected output, but the type of the
output values will be cast if necessary.
.. versionadded:: 0.18.0
Returns
-------
sum_along_axis : np.matrix
A matrix with the same shape as `self`, with the specified
axis removed.
See Also
--------
numpy.matrix.sum : NumPy's implementation of 'sum' for matrices
| def sum(self, axis=None, dtype=None, out=None):
"""
Sum the array/matrix elements over a given axis.
Parameters
----------
axis : {-2, -1, 0, 1, None} optional
Axis along which the sum is computed. The default is to
compute the sum of all the array/matrix elements, returning a scalar
(i.e., `axis` = `None`).
dtype : dtype, optional
The type of the returned array/matrix and of the accumulator in which
the elements are summed. The dtype of `a` is used by default
unless `a` has an integer dtype of less precision than the default
platform integer. In that case, if `a` is signed then the platform
integer is used while if `a` is unsigned then an unsigned integer
of the same precision as the platform integer is used.
.. versionadded:: 0.18.0
out : np.matrix, optional
Alternative output matrix in which to place the result. It must
have the same shape as the expected output, but the type of the
output values will be cast if necessary.
.. versionadded:: 0.18.0
Returns
-------
sum_along_axis : np.matrix
A matrix with the same shape as `self`, with the specified
axis removed.
See Also
--------
numpy.matrix.sum : NumPy's implementation of 'sum' for matrices
"""
validateaxis(axis)
# Mimic numpy's casting.
res_dtype = get_sum_dtype(self.dtype)
if self.ndim == 1:
if axis not in (None, -1, 0):
raise ValueError("axis must be None, -1 or 0")
ret = (self @ np.ones(self.shape, dtype=res_dtype)).astype(dtype)
if out is not None:
if any(dim != 1 for dim in out.shape):
raise ValueError("dimensions do not match")
out[...] = ret
return ret
# We use multiplication by a matrix of ones to achieve this.
# For some sparse array formats more efficient methods are
# possible -- these should override this function.
M, N = self.shape
if axis is None:
# sum over rows and columns
return (
self @ self._ascontainer(np.ones((N, 1), dtype=res_dtype))
).sum(dtype=dtype, out=out)
if axis < 0:
axis += 2
# axis = 0 or 1 now
if axis == 0:
# sum over columns
ret = self._ascontainer(
np.ones((1, M), dtype=res_dtype)
) @ self
else:
# sum over rows
ret = self @ self._ascontainer(
np.ones((N, 1), dtype=res_dtype)
)
if out is not None and out.shape != ret.shape:
raise ValueError("dimensions do not match")
return ret.sum(axis=axis, dtype=dtype, out=out)
| (self, axis=None, dtype=None, out=None) |
724,859 | scipy.sparse._base | toarray |
Return a dense ndarray representation of this sparse array/matrix.
Parameters
----------
order : {'C', 'F'}, optional
Whether to store multidimensional data in C (row-major)
or Fortran (column-major) order in memory. The default
is 'None', which provides no ordering guarantees.
Cannot be specified in conjunction with the `out`
argument.
out : ndarray, 2-D, optional
If specified, uses this array as the output buffer
instead of allocating a new array to return. The provided
array must have the same shape and dtype as the sparse
array/matrix on which you are calling the method. For most
sparse types, `out` is required to be memory contiguous
(either C or Fortran ordered).
Returns
-------
arr : ndarray, 2-D
An array with the same shape and containing the same
data represented by the sparse array/matrix, with the requested
memory order. If `out` was passed, the same object is
returned after being modified in-place to contain the
appropriate values.
| def toarray(self, order=None, out=None):
"""
Return a dense ndarray representation of this sparse array/matrix.
Parameters
----------
order : {'C', 'F'}, optional
Whether to store multidimensional data in C (row-major)
or Fortran (column-major) order in memory. The default
is 'None', which provides no ordering guarantees.
Cannot be specified in conjunction with the `out`
argument.
out : ndarray, 2-D, optional
If specified, uses this array as the output buffer
instead of allocating a new array to return. The provided
array must have the same shape and dtype as the sparse
array/matrix on which you are calling the method. For most
sparse types, `out` is required to be memory contiguous
(either C or Fortran ordered).
Returns
-------
arr : ndarray, 2-D
An array with the same shape and containing the same
data represented by the sparse array/matrix, with the requested
memory order. If `out` was passed, the same object is
returned after being modified in-place to contain the
appropriate values.
"""
return self.tocoo(copy=False).toarray(order=order, out=out)
| (self, order=None, out=None) |
724,861 | scipy.sparse._dok | tocoo | Convert this array/matrix to COOrdinate format.
With copy=False, the data/indices may be shared between this array/matrix and
the resultant coo_array/matrix.
| def tocoo(self, copy=False):
nnz = self.nnz
if nnz == 0:
return self._coo_container(self.shape, dtype=self.dtype)
idx_dtype = self._get_index_dtype(maxval=max(self.shape))
data = np.fromiter(self.values(), dtype=self.dtype, count=nnz)
# handle 1d keys specially b/c not a tuple
inds = zip(*self.keys()) if self.ndim > 1 else (self.keys(),)
coords = tuple(np.fromiter(ix, dtype=idx_dtype, count=nnz) for ix in inds)
A = self._coo_container((data, coords), shape=self.shape, dtype=self.dtype)
A.has_canonical_format = True
return A
| (self, copy=False) |
724,862 | scipy.sparse._dok | tocsc | Convert this array/matrix to Compressed Sparse Column format.
With copy=False, the data/indices may be shared between this array/matrix and
the resultant csc_array/matrix.
| def tocsc(self, copy=False):
if self.ndim == 1:
raise NotImplementedError("tocsr() not valid for 1d sparse array")
return self.tocoo(copy=False).tocsc(copy=copy)
| (self, copy=False) |
724,863 | scipy.sparse._base | tocsr | Convert this array/matrix to Compressed Sparse Row format.
With copy=False, the data/indices may be shared between this array/matrix and
the resultant csr_array/matrix.
| def tocsr(self, copy=False):
"""Convert this array/matrix to Compressed Sparse Row format.
With copy=False, the data/indices may be shared between this array/matrix and
the resultant csr_array/matrix.
"""
return self.tocoo(copy=copy).tocsr(copy=False)
| (self, copy=False) |
724,866 | scipy.sparse._dok | todok | Convert this array/matrix to Dictionary Of Keys format.
With copy=False, the data/indices may be shared between this array/matrix and
the resultant dok_array/matrix.
| def todok(self, copy=False):
if copy:
return self.copy()
return self
| (self, copy=False) |
724,869 | scipy.sparse._dok | transpose |
Reverses the dimensions of the sparse array/matrix.
Parameters
----------
axes : None, optional
This argument is in the signature *solely* for NumPy
compatibility reasons. Do not pass in anything except
for the default value.
copy : bool, optional
Indicates whether or not attributes of `self` should be
copied whenever possible. The degree to which attributes
are copied varies depending on the type of sparse array/matrix
being used.
Returns
-------
p : `self` with the dimensions reversed.
Notes
-----
If `self` is a `csr_array` or a `csc_array`, then this will return a
`csc_array` or a `csr_array`, respectively.
See Also
--------
numpy.transpose : NumPy's implementation of 'transpose' for ndarrays
| def transpose(self, axes=None, copy=False):
if self.ndim == 1:
return self.copy()
if axes is not None and axes != (1, 0):
raise ValueError(
"Sparse arrays/matrices do not support "
"an 'axes' parameter because swapping "
"dimensions is the only logical permutation."
)
M, N = self.shape
new = self._dok_container((N, M), dtype=self.dtype, copy=copy)
new._dict.update((((right, left), val) for (left, right), val in self.items()))
return new
| (self, axes=None, copy=False) |
724,870 | scipy.sparse._dok | update | null | def update(self, val):
# Prevent direct usage of update
raise NotImplementedError("Direct update to DOK sparse format is not allowed.")
| (self, val) |
724,871 | scipy.sparse._dok | values | null | def values(self):
return self._dict.values()
| (self) |
724,872 | markov_clustering.mcl | expand |
Apply cluster expansion to the given matrix by raising
the matrix to the given power.
:param matrix: The matrix to be expanded
:param power: Cluster expansion parameter
:returns: The expanded matrix
| def expand(matrix, power):
"""
Apply cluster expansion to the given matrix by raising
the matrix to the given power.
:param matrix: The matrix to be expanded
:param power: Cluster expansion parameter
:returns: The expanded matrix
"""
if isspmatrix(matrix):
return matrix ** power
return np.linalg.matrix_power(matrix, power)
| (matrix, power) |
724,873 | scipy.sparse._extract | find | Return the indices and values of the nonzero elements of a matrix
Parameters
----------
A : dense or sparse array or matrix
Matrix whose nonzero elements are desired.
Returns
-------
(I,J,V) : tuple of arrays
I,J, and V contain the row indices, column indices, and values
of the nonzero entries.
Examples
--------
>>> from scipy.sparse import csr_array, find
>>> A = csr_array([[7.0, 8.0, 0],[0, 0, 9.0]])
>>> find(A)
(array([0, 0, 1], dtype=int32),
array([0, 1, 2], dtype=int32),
array([ 7., 8., 9.]))
| def find(A):
"""Return the indices and values of the nonzero elements of a matrix
Parameters
----------
A : dense or sparse array or matrix
Matrix whose nonzero elements are desired.
Returns
-------
(I,J,V) : tuple of arrays
I,J, and V contain the row indices, column indices, and values
of the nonzero entries.
Examples
--------
>>> from scipy.sparse import csr_array, find
>>> A = csr_array([[7.0, 8.0, 0],[0, 0, 9.0]])
>>> find(A)
(array([0, 0, 1], dtype=int32),
array([0, 1, 2], dtype=int32),
array([ 7., 8., 9.]))
"""
A = coo_array(A, copy=True)
A.sum_duplicates()
# remove explicit zeros
nz_mask = A.data != 0
return A.row[nz_mask], A.col[nz_mask], A.data[nz_mask]
| (A) |
724,874 | markov_clustering.mcl | get_clusters |
Retrieve the clusters from the matrix
:param matrix: The matrix produced by the MCL algorithm
:returns: A list of tuples where each tuple represents a cluster and
contains the indices of the nodes belonging to the cluster
| def get_clusters(matrix):
"""
Retrieve the clusters from the matrix
:param matrix: The matrix produced by the MCL algorithm
:returns: A list of tuples where each tuple represents a cluster and
contains the indices of the nodes belonging to the cluster
"""
if not isspmatrix(matrix):
# cast to sparse so that we don't need to handle different
# matrix types
matrix = csc_matrix(matrix)
# get the attractors - non-zero elements of the matrix diagonal
attractors = matrix.diagonal().nonzero()[0]
# somewhere to put the clusters
clusters = set()
# the nodes in the same row as each attractor form a cluster
for attractor in attractors:
cluster = tuple(matrix.getrow(attractor).nonzero()[1].tolist())
clusters.add(cluster)
return sorted(list(clusters))
| (matrix) |
724,875 | markov_clustering.mcl | inflate |
Apply cluster inflation to the given matrix by raising
each element to the given power.
:param matrix: The matrix to be inflated
:param power: Cluster inflation parameter
:returns: The inflated matrix
| def inflate(matrix, power):
"""
Apply cluster inflation to the given matrix by raising
each element to the given power.
:param matrix: The matrix to be inflated
:param power: Cluster inflation parameter
:returns: The inflated matrix
"""
if isspmatrix(matrix):
return normalize(matrix.power(power))
return normalize(np.power(matrix, power))
| (matrix, power) |
724,876 | markov_clustering.modularity | is_undirected |
Determine if the matrix reprensents a directed graph
:param matrix: The matrix to tested
:returns: boolean
| def is_undirected(matrix):
"""
Determine if the matrix reprensents a directed graph
:param matrix: The matrix to tested
:returns: boolean
"""
if isspmatrix(matrix):
return sparse_allclose(matrix, matrix.transpose())
return np.allclose(matrix, matrix.T)
| (matrix) |
724,877 | scipy.sparse._base | isspmatrix | Is `x` of a sparse matrix type?
Parameters
----------
x
object to check for being a sparse matrix
Returns
-------
bool
True if `x` is a sparse matrix, False otherwise
Examples
--------
>>> import numpy as np
>>> from scipy.sparse import csr_array, csr_matrix, isspmatrix
>>> isspmatrix(csr_matrix([[5]]))
True
>>> isspmatrix(csr_array([[5]]))
False
>>> isspmatrix(np.array([[5]]))
False
>>> isspmatrix(5)
False
| def isspmatrix(x):
"""Is `x` of a sparse matrix type?
Parameters
----------
x
object to check for being a sparse matrix
Returns
-------
bool
True if `x` is a sparse matrix, False otherwise
Examples
--------
>>> import numpy as np
>>> from scipy.sparse import csr_array, csr_matrix, isspmatrix
>>> isspmatrix(csr_matrix([[5]]))
True
>>> isspmatrix(csr_array([[5]]))
False
>>> isspmatrix(np.array([[5]]))
False
>>> isspmatrix(5)
False
"""
return isinstance(x, spmatrix)
| (x) |
724,878 | markov_clustering.mcl | iterate |
Run a single iteration (expansion + inflation) of the mcl algorithm
:param matrix: The matrix to perform the iteration on
:param expansion: Cluster expansion factor
:param inflation: Cluster inflation factor
| def iterate(matrix, expansion, inflation):
"""
Run a single iteration (expansion + inflation) of the mcl algorithm
:param matrix: The matrix to perform the iteration on
:param expansion: Cluster expansion factor
:param inflation: Cluster inflation factor
"""
# Expansion
matrix = expand(matrix, expansion)
# Inflation
matrix = inflate(matrix, inflation)
return matrix
| (matrix, expansion, inflation) |
724,880 | markov_clustering.modularity | modularity |
Compute the modularity
:param matrix: The adjacency matrix
:param clusters: The clusters returned by get_clusters
:returns: modularity value
| def modularity(matrix, clusters):
"""
Compute the modularity
:param matrix: The adjacency matrix
:param clusters: The clusters returned by get_clusters
:returns: modularity value
"""
matrix = convert_to_adjacency_matrix(matrix)
m = matrix.sum()
if isspmatrix(matrix):
matrix_2 = matrix.tocsr(copy=True)
else :
matrix_2 = matrix
if is_undirected(matrix):
expected = lambda i,j : (( matrix_2[i,:].sum() + matrix[:,i].sum() )*
( matrix[:,j].sum() + matrix_2[j,:].sum() ))
else:
expected = lambda i,j : ( matrix_2[i,:].sum()*matrix[:,j].sum() )
delta = delta_matrix(matrix, clusters)
indices = np.array(delta.nonzero())
Q = sum( matrix[i, j] - expected(i, j)/m for i, j in indices.T )/m
return Q
| (matrix, clusters) |
724,881 | markov_clustering.mcl | normalize |
Normalize the columns of the given matrix
:param matrix: The matrix to be normalized
:returns: The normalized matrix
| def normalize(matrix):
"""
Normalize the columns of the given matrix
:param matrix: The matrix to be normalized
:returns: The normalized matrix
"""
return sklearn.preprocessing.normalize(matrix, norm="l1", axis=0)
| (matrix) |
724,884 | markov_clustering.mcl | prune |
Prune the matrix so that very small edges are removed.
The maximum value in each column is never pruned.
:param matrix: The matrix to be pruned
:param threshold: The value below which edges will be removed
:returns: The pruned matrix
| def prune(matrix, threshold):
"""
Prune the matrix so that very small edges are removed.
The maximum value in each column is never pruned.
:param matrix: The matrix to be pruned
:param threshold: The value below which edges will be removed
:returns: The pruned matrix
"""
if isspmatrix(matrix):
pruned = dok_matrix(matrix.shape)
pruned[matrix >= threshold] = matrix[matrix >= threshold]
pruned = pruned.tocsc()
else:
pruned = matrix.copy()
pruned[pruned < threshold] = 0
# keep max value in each column. same behaviour for dense/sparse
num_cols = matrix.shape[1]
row_indices = matrix.argmax(axis=0).reshape((num_cols,))
col_indices = np.arange(num_cols)
pruned[row_indices, col_indices] = matrix[row_indices, col_indices]
return pruned
| (matrix, threshold) |
724,885 | markov_clustering.mcl | run_mcl |
Perform MCL on the given similarity matrix
:param matrix: The similarity matrix to cluster
:param expansion: The cluster expansion factor
:param inflation: The cluster inflation factor
:param loop_value: Initialization value for self-loops
:param iterations: Maximum number of iterations
(actual number of iterations will be less if convergence is reached)
:param pruning_threshold: Threshold below which matrix elements will be set
set to 0
:param pruning_frequency: Perform pruning every 'pruning_frequency'
iterations.
:param convergence_check_frequency: Perform the check for convergence
every convergence_check_frequency iterations
:param verbose: Print extra information to the console
:returns: The final matrix
| def run_mcl(matrix, expansion=2, inflation=2, loop_value=1,
iterations=100, pruning_threshold=0.001, pruning_frequency=1,
convergence_check_frequency=1, verbose=False):
"""
Perform MCL on the given similarity matrix
:param matrix: The similarity matrix to cluster
:param expansion: The cluster expansion factor
:param inflation: The cluster inflation factor
:param loop_value: Initialization value for self-loops
:param iterations: Maximum number of iterations
(actual number of iterations will be less if convergence is reached)
:param pruning_threshold: Threshold below which matrix elements will be set
set to 0
:param pruning_frequency: Perform pruning every 'pruning_frequency'
iterations.
:param convergence_check_frequency: Perform the check for convergence
every convergence_check_frequency iterations
:param verbose: Print extra information to the console
:returns: The final matrix
"""
assert expansion > 1, "Invalid expansion parameter"
assert inflation > 1, "Invalid inflation parameter"
assert loop_value >= 0, "Invalid loop_value"
assert iterations > 0, "Invalid number of iterations"
assert pruning_threshold >= 0, "Invalid pruning_threshold"
assert pruning_frequency > 0, "Invalid pruning_frequency"
assert convergence_check_frequency > 0, "Invalid convergence_check_frequency"
printer = MessagePrinter(verbose)
printer.print("-" * 50)
printer.print("MCL Parameters")
printer.print("Expansion: {}".format(expansion))
printer.print("Inflation: {}".format(inflation))
if pruning_threshold > 0:
printer.print("Pruning threshold: {}, frequency: {} iteration{}".format(
pruning_threshold, pruning_frequency, "s" if pruning_frequency > 1 else ""))
else:
printer.print("No pruning")
printer.print("Convergence check: {} iteration{}".format(
convergence_check_frequency, "s" if convergence_check_frequency > 1 else ""))
printer.print("Maximum iterations: {}".format(iterations))
printer.print("{} matrix mode".format("Sparse" if isspmatrix(matrix) else "Dense"))
printer.print("-" * 50)
# Initialize self-loops
if loop_value > 0:
matrix = add_self_loops(matrix, loop_value)
# Normalize
matrix = normalize(matrix)
# iterations
for i in range(iterations):
printer.print("Iteration {}".format(i + 1))
# store current matrix for convergence checking
last_mat = matrix.copy()
# perform MCL expansion and inflation
matrix = iterate(matrix, expansion, inflation)
# prune
if pruning_threshold > 0 and i % pruning_frequency == pruning_frequency - 1:
printer.print("Pruning")
matrix = prune(matrix, pruning_threshold)
# Check for convergence
if i % convergence_check_frequency == convergence_check_frequency - 1:
printer.print("Checking for convergence")
if converged(matrix, last_mat):
printer.print("Converged after {} iteration{}".format(i + 1, "s" if i > 0 else ""))
break
printer.print("-" * 50)
return matrix
| (matrix, expansion=2, inflation=2, loop_value=1, iterations=100, pruning_threshold=0.001, pruning_frequency=1, convergence_check_frequency=1, verbose=False) |
724,887 | markov_clustering.mcl | sparse_allclose |
Version of np.allclose for use with sparse matrices
| def sparse_allclose(a, b, rtol=1e-5, atol=1e-8):
"""
Version of np.allclose for use with sparse matrices
"""
c = np.abs(a - b) - rtol * np.abs(b)
# noinspection PyUnresolvedReferences
return c.max() <= atol
| (a, b, rtol=1e-05, atol=1e-08) |
724,890 | pipfile.api | Pipfile | null | class Pipfile(object):
def __init__(self, filename):
super(Pipfile, self).__init__()
self.filename = filename
self.data = None
@staticmethod
def find(max_depth=3):
"""Returns the path of a Pipfile in parent directories."""
i = 0
for c, d, f in walk_up(os.getcwd()):
i += 1
if i < max_depth:
if 'Pipfile':
p = os.path.join(c, 'Pipfile')
if os.path.isfile(p):
return p
raise RuntimeError('No Pipfile found!')
@classmethod
def load(klass, filename):
"""Load a Pipfile from a given filename."""
p = PipfileParser(filename=filename)
pipfile = klass(filename=filename)
pipfile.data = p.parse()
return pipfile
@property
def hash(self):
"""Returns the SHA256 of the pipfile's data."""
content = json.dumps(self.data, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(content.encode("utf8")).hexdigest()
@property
def contents(self):
"""Returns the contents of the pipfile."""
with codecs.open(self.filename, 'r', 'utf-8') as f:
return f.read()
def lock(self):
"""Returns a JSON representation of the Pipfile."""
data = self.data
data['_meta']['hash'] = {"sha256": self.hash}
# return _json.dumps(data)
return json.dumps(data, indent=4, separators=(',', ': '))
def assert_requirements(self):
""""Asserts PEP 508 specifiers."""
# Support for 508's implementation_version.
if hasattr(sys, 'implementation'):
implementation_version = format_full_version(sys.implementation.version)
else:
implementation_version = "0"
# Default to cpython for 2.7.
if hasattr(sys, 'implementation'):
implementation_name = sys.implementation.name
else:
implementation_name = 'cpython'
lookup = {
'os_name': os.name,
'sys_platform': sys.platform,
'platform_machine': platform.machine(),
'platform_python_implementation': platform.python_implementation(),
'platform_release': platform.release(),
'platform_system': platform.system(),
'platform_version': platform.version(),
'python_version': platform.python_version()[:3],
'python_full_version': platform.python_version(),
'implementation_name': implementation_name,
'implementation_version': implementation_version
}
# Assert each specified requirement.
for marker, specifier in self.data['_meta']['requires'].items():
if marker in lookup:
try:
assert lookup[marker] == specifier
except AssertionError:
raise AssertionError('Specifier {!r} does not match {!r}.'.format(marker, specifier))
| (filename) |
724,891 | pipfile.api | __init__ | null | def __init__(self, filename):
super(Pipfile, self).__init__()
self.filename = filename
self.data = None
| (self, filename) |
724,892 | pipfile.api | assert_requirements | "Asserts PEP 508 specifiers. | def assert_requirements(self):
""""Asserts PEP 508 specifiers."""
# Support for 508's implementation_version.
if hasattr(sys, 'implementation'):
implementation_version = format_full_version(sys.implementation.version)
else:
implementation_version = "0"
# Default to cpython for 2.7.
if hasattr(sys, 'implementation'):
implementation_name = sys.implementation.name
else:
implementation_name = 'cpython'
lookup = {
'os_name': os.name,
'sys_platform': sys.platform,
'platform_machine': platform.machine(),
'platform_python_implementation': platform.python_implementation(),
'platform_release': platform.release(),
'platform_system': platform.system(),
'platform_version': platform.version(),
'python_version': platform.python_version()[:3],
'python_full_version': platform.python_version(),
'implementation_name': implementation_name,
'implementation_version': implementation_version
}
# Assert each specified requirement.
for marker, specifier in self.data['_meta']['requires'].items():
if marker in lookup:
try:
assert lookup[marker] == specifier
except AssertionError:
raise AssertionError('Specifier {!r} does not match {!r}.'.format(marker, specifier))
| (self) |
724,893 | pipfile.api | find | Returns the path of a Pipfile in parent directories. | @staticmethod
def find(max_depth=3):
"""Returns the path of a Pipfile in parent directories."""
i = 0
for c, d, f in walk_up(os.getcwd()):
i += 1
if i < max_depth:
if 'Pipfile':
p = os.path.join(c, 'Pipfile')
if os.path.isfile(p):
return p
raise RuntimeError('No Pipfile found!')
| (max_depth=3) |
724,894 | pipfile.api | lock | Returns a JSON representation of the Pipfile. | def lock(self):
"""Returns a JSON representation of the Pipfile."""
data = self.data
data['_meta']['hash'] = {"sha256": self.hash}
# return _json.dumps(data)
return json.dumps(data, indent=4, separators=(',', ': '))
| (self) |
724,897 | pipfile.api | load | Loads a pipfile from a given path.
If none is provided, one will try to be found.
| def load(pipfile_path=None):
"""Loads a pipfile from a given path.
If none is provided, one will try to be found.
"""
if pipfile_path is None:
pipfile_path = Pipfile.find()
return Pipfile.load(filename=pipfile_path)
| (pipfile_path=None) |
724,898 | tf_keras.src.engine.input_layer | Input | `Input()` is used to instantiate a TF-Keras tensor.
A TF-Keras tensor is a symbolic tensor-like object, which we augment with
certain attributes that allow us to build a TF-Keras model just by knowing
the inputs and outputs of the model.
For instance, if `a`, `b` and `c` are TF-Keras tensors,
it becomes possible to do:
`model = Model(input=[a, b], output=c)`
Args:
shape: A shape tuple (integers), not including the batch size.
For instance, `shape=(32,)` indicates that the expected input
will be batches of 32-dimensional vectors. Elements of this tuple
can be None; 'None' elements represent dimensions where the shape is
not known.
batch_size: optional static batch size (integer).
name: An optional name string for the layer.
Should be unique in a model (do not reuse the same name twice).
It will be autogenerated if it isn't provided.
dtype: The data type expected by the input, as a string
(`float32`, `float64`, `int32`...)
sparse: A boolean specifying whether the placeholder to be created is
sparse. Only one of 'ragged' and 'sparse' can be True. Note that,
if `sparse` is False, sparse tensors can still be passed into the
input - they will be densified with a default value of 0.
tensor: Optional existing tensor to wrap into the `Input` layer.
If set, the layer will use the `tf.TypeSpec` of this tensor rather
than creating a new placeholder tensor.
ragged: A boolean specifying whether the placeholder to be created is
ragged. Only one of 'ragged' and 'sparse' can be True. In this case,
values of 'None' in the 'shape' argument represent ragged
dimensions. For more information about RaggedTensors, see
[this guide](https://www.tensorflow.org/guide/ragged_tensor).
type_spec: A `tf.TypeSpec` object to create the input placeholder from.
When provided, all other args except name must be None.
**kwargs: deprecated arguments support. Supports `batch_shape` and
`batch_input_shape`.
Returns:
A `tensor`.
Example:
```python
# this is a logistic regression in Keras
x = Input(shape=(32,))
y = Dense(16, activation='softmax')(x)
model = Model(x, y)
```
Note that even if eager execution is enabled,
`Input` produces a symbolic tensor-like object (i.e. a placeholder).
This symbolic tensor-like object can be used with lower-level
TensorFlow ops that take tensors as inputs, as such:
```python
x = Input(shape=(32,))
y = tf.square(x) # This op will be treated like a layer
model = Model(x, y)
```
(This behavior does not work for higher-order TensorFlow APIs such as
control flow and being directly watched by a `tf.GradientTape`).
However, the resulting model will not track any variables that were
used as inputs to TensorFlow ops. All variable usages must happen within
TF-Keras layers to make sure they will be tracked by the model's weights.
The TF-Keras Input can also create a placeholder from an arbitrary
`tf.TypeSpec`, e.g:
```python
x = Input(type_spec=tf.RaggedTensorSpec(shape=[None, None],
dtype=tf.float32, ragged_rank=1))
y = x.values
model = Model(x, y)
```
When passing an arbitrary `tf.TypeSpec`, it must represent the signature of
an entire batch instead of just one example.
Raises:
ValueError: If both `sparse` and `ragged` are provided.
ValueError: If both `shape` and (`batch_input_shape` or `batch_shape`) are
provided.
ValueError: If `shape`, `tensor` and `type_spec` are None.
ValueError: If arguments besides `type_spec` are non-None while
`type_spec` is passed.
ValueError: if any unrecognized parameters are provided.
| @keras_export("keras.layers.InputLayer")
class InputLayer(base_layer.Layer):
"""Layer to be used as an entry point into a Network (a graph of layers).
It can either wrap an existing tensor (pass an `input_tensor` argument)
or create a placeholder tensor (pass arguments `input_shape`, and
optionally, `dtype`).
It is generally recommend to use the TF-Keras Functional model via `Input`,
(which creates an `InputLayer`) without directly using `InputLayer`.
When using `InputLayer` with the TF-Keras Sequential model, it can be
skipped by moving the `input_shape` parameter to the first layer after the
`InputLayer`.
This class can create placeholders for `tf.Tensors`, `tf.SparseTensors`, and
`tf.RaggedTensors` by choosing `sparse=True` or `ragged=True`. Note that
`sparse` and `ragged` can't be configured to `True` at the same time.
Usage:
```python
# With explicit InputLayer.
model = tf.keras.Sequential([
tf.keras.layers.InputLayer(input_shape=(4,)),
tf.keras.layers.Dense(8)])
model.compile(tf.keras.optimizers.RMSprop(0.001), loss='mse')
model.fit(np.zeros((10, 4)),
np.ones((10, 8)))
# Without InputLayer and let the first layer to have the input_shape.
# TF-Keras will add a input for the model behind the scene.
model = tf.keras.Sequential([
tf.keras.layers.Dense(8, input_shape=(4,))])
model.compile(tf.keras.optimizers.RMSprop(0.001), loss='mse')
model.fit(np.zeros((10, 4)),
np.ones((10, 8)))
```
Args:
input_shape: Shape tuple (not including the batch axis), or
`TensorShape` instance (not including the batch axis).
batch_size: Optional input batch size (integer or `None`).
dtype: Optional datatype of the input. When not provided, the Keras
default `float` type will be used.
input_tensor: Optional tensor to use as layer input. If set, the layer
will use the `tf.TypeSpec` of this tensor rather
than creating a new placeholder tensor.
sparse: Boolean, whether the placeholder created is meant to be sparse.
Defaults to `False`.
ragged: Boolean, whether the placeholder created is meant to be ragged.
In this case, values of `None` in the `shape` argument represent
ragged dimensions. For more information about `tf.RaggedTensor`, see
[this guide](https://www.tensorflow.org/guide/ragged_tensor).
Defaults to `False`.
type_spec: A `tf.TypeSpec` object to create Input from. This
`tf.TypeSpec` represents the entire batch. When provided, all other
args except name must be `None`.
name: Optional name of the layer (string).
"""
@traceback_utils.filter_traceback
def __init__(
self,
input_shape=None,
batch_size=None,
dtype=None,
input_tensor=None,
sparse=None,
name=None,
ragged=None,
type_spec=None,
**kwargs,
):
self._init_input_shape = input_shape
self._init_batch_size = batch_size
self._init_dtype = dtype
self._init_sparse = sparse
self._init_ragged = ragged
self._init_type_spec = type_spec
strategy = tf.distribute.get_strategy()
if (
strategy
and batch_size is not None
and distributed_training_utils.global_batch_size_supported(strategy)
):
if batch_size % strategy.num_replicas_in_sync != 0:
raise ValueError(
"The `batch_size` argument ({}) must be divisible by "
"the number of replicas ({})".format(
batch_size, strategy.num_replicas_in_sync
)
)
batch_size = batch_size // strategy.num_replicas_in_sync
if "batch_input_shape" in kwargs:
batch_input_shape = kwargs.pop("batch_input_shape")
if input_shape and batch_input_shape:
raise ValueError(
"Only provide the input_shape OR "
"batch_input_shape argument to "
"InputLayer, not both at the same time."
)
# Set the input shape and batch size from the batch_input_shape.
# Note that batch_input_shape can be None (unknown rank) or []
# (scalar), in which case the batch size must be None.
if batch_input_shape:
batch_size = batch_input_shape[0]
input_shape = batch_input_shape[1:]
if kwargs:
raise ValueError(
f"Unrecognized keyword arguments: {list(kwargs.keys())}"
)
if sparse and ragged:
raise ValueError(
"Cannot set both sparse and ragged to True in a TF-Keras input."
)
if not name:
prefix = "input"
name = prefix + "_" + str(backend.get_uid(prefix))
if not dtype:
if input_tensor is None:
dtype = backend.floatx()
else:
dtype = backend.dtype(input_tensor)
elif input_tensor is not None and input_tensor.dtype != dtype:
raise ValueError(
"`input_tensor.dtype` differs from `dtype`. Received: "
f"input_tensor.dtype={input_tensor.dtype} "
f"but expected dtype={dtype}"
)
super().__init__(dtype=dtype, name=name)
self.built = True
self.sparse = True if sparse else False
self.ragged = True if ragged else False
self.batch_size = batch_size
self.supports_masking = True
if isinstance(input_shape, tf.TensorShape):
input_shape = tuple(input_shape.as_list())
elif isinstance(input_shape, int):
input_shape = (input_shape,)
if type_spec is not None:
args_that_must_be_none = [
("(input_)shape", self._init_input_shape),
("batch_size", self._init_batch_size),
("dtype", self._init_dtype),
("input_tensor", input_tensor),
("sparse", self._init_sparse),
("ragged", self._init_ragged),
]
for arg_name, arg in args_that_must_be_none:
_assert_other_arg_none(arg_name, arg)
if not tf.compat.v1.executing_eagerly_outside_functions():
raise ValueError(
"Creating TF-Keras inputs from a type_spec is only "
"supported when eager execution is enabled."
)
# Needed for type_spec deserialization since TypeSpec objects
# are not Keras-native (not automatically deserialized).
if isinstance(type_spec, dict):
type_spec = serialization_lib.deserialize_keras_object(
type_spec
)
input_tensor = keras_tensor.keras_tensor_from_type_spec(type_spec)
if isinstance(input_tensor, keras_tensor.SparseKerasTensor):
self.sparse = True
if isinstance(input_tensor, keras_tensor.RaggedKerasTensor):
self.ragged = True
self.is_placeholder = True
try:
self._batch_input_shape = tuple(input_tensor.shape.as_list())
except ValueError:
# If the shape cannot be represented as a tuple (e.g. unknown
# rank)
self._batch_input_shape = None
elif input_tensor is None:
if input_shape is not None:
batch_input_shape = (batch_size,) + tuple(input_shape)
else:
batch_input_shape = None
graph = backend.get_graph()
with graph.as_default():
input_tensor = backend.placeholder(
shape=batch_input_shape,
dtype=dtype,
name=self.name,
sparse=sparse,
ragged=ragged,
)
self.is_placeholder = True
self._batch_input_shape = batch_input_shape
else:
if tf.compat.v1.executing_eagerly_outside_functions():
if not isinstance(input_tensor, keras_tensor.KerasTensor):
input_tensor = keras_tensor.keras_tensor_from_tensor(
input_tensor
)
else:
if not tf_utils.is_symbolic_tensor(input_tensor):
raise ValueError(
"You should not pass an EagerTensor to `Input`. "
"For example, instead of creating an "
"`InputLayer`, you should instantiate your model "
"and directly call it on your input."
)
self.is_placeholder = False
try:
self._batch_input_shape = tuple(input_tensor.shape.as_list())
except ValueError:
# If the shape cannot be represented as a tuple (e.g. unknown
# rank)
self._batch_input_shape = None
# Create an input node.
input_tensor._keras_mask = None
node_module.Node(layer=self, outputs=input_tensor)
# Store type spec
if isinstance(input_tensor, keras_tensor.KerasTensor) or (
tf_utils.is_extension_type(input_tensor)
):
self._type_spec = input_tensor._type_spec
else:
self._type_spec = tf.TensorSpec(
shape=input_tensor.shape,
dtype=input_tensor.dtype,
name=self.name,
)
def get_config(self):
if self._init_type_spec is not None:
config = {"name": self.name, "type_spec": self._init_type_spec}
else:
config = {
"batch_input_shape": self._batch_input_shape,
"dtype": self.dtype,
"sparse": self.sparse,
"ragged": self.ragged,
"name": self.name,
}
return config
@property
def _trackable_saved_model_saver(self):
return layer_serialization.InputLayerSavedModelSaver(self)
| (shape=None, batch_size=None, name=None, dtype=None, sparse=None, tensor=None, ragged=None, type_spec=None, **kwargs) |
724,899 | tf_keras.src.engine.training | Model | A model grouping layers into an object with training/inference features.
Args:
inputs: The input(s) of the model: a `keras.Input` object or a
combination of `keras.Input` objects in a dict, list or tuple.
outputs: The output(s) of the model: a tensor that originated from
`keras.Input` objects or a combination of such tensors in a dict,
list or tuple. See Functional API example below.
name: String, the name of the model.
There are two ways to instantiate a `Model`:
1 - With the "Functional API", where you start from `Input`,
you chain layer calls to specify the model's forward pass,
and finally you create your model from inputs and outputs:
```python
import tensorflow as tf
inputs = tf.keras.Input(shape=(3,))
x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
```
Note: Only dicts, lists, and tuples of input tensors are supported. Nested
inputs are not supported (e.g. lists of list or dicts of dict).
A new Functional API model can also be created by using the
intermediate tensors. This enables you to quickly extract sub-components
of the model.
Example:
```python
inputs = keras.Input(shape=(None, None, 3))
processed = keras.layers.RandomCrop(width=32, height=32)(inputs)
conv = keras.layers.Conv2D(filters=2, kernel_size=3)(processed)
pooling = keras.layers.GlobalAveragePooling2D()(conv)
feature = keras.layers.Dense(10)(pooling)
full_model = keras.Model(inputs, feature)
backbone = keras.Model(processed, conv)
activations = keras.Model(conv, feature)
```
Note that the `backbone` and `activations` models are not
created with `keras.Input` objects, but with the tensors that are originated
from `keras.Input` objects. Under the hood, the layers and weights will
be shared across these models, so that user can train the `full_model`, and
use `backbone` or `activations` to do feature extraction.
The inputs and outputs of the model can be nested structures of tensors as
well, and the created models are standard Functional API models that support
all the existing APIs.
2 - By subclassing the `Model` class: in that case, you should define your
layers in `__init__()` and you should implement the model's forward pass
in `call()`.
```python
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
def call(self, inputs):
x = self.dense1(inputs)
return self.dense2(x)
model = MyModel()
```
If you subclass `Model`, you can optionally have
a `training` argument (boolean) in `call()`, which you can use to specify
a different behavior in training and inference:
```python
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
self.dropout = tf.keras.layers.Dropout(0.5)
def call(self, inputs, training=False):
x = self.dense1(inputs)
if training:
x = self.dropout(x, training=training)
return self.dense2(x)
model = MyModel()
```
Once the model is created, you can config the model with losses and metrics
with `model.compile()`, train the model with `model.fit()`, or use the model
to do prediction with `model.predict()`.
| class Model(base_layer.Layer, version_utils.ModelVersionSelector):
"""A model grouping layers into an object with training/inference features.
Args:
inputs: The input(s) of the model: a `keras.Input` object or a
combination of `keras.Input` objects in a dict, list or tuple.
outputs: The output(s) of the model: a tensor that originated from
`keras.Input` objects or a combination of such tensors in a dict,
list or tuple. See Functional API example below.
name: String, the name of the model.
There are two ways to instantiate a `Model`:
1 - With the "Functional API", where you start from `Input`,
you chain layer calls to specify the model's forward pass,
and finally you create your model from inputs and outputs:
```python
import tensorflow as tf
inputs = tf.keras.Input(shape=(3,))
x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
```
Note: Only dicts, lists, and tuples of input tensors are supported. Nested
inputs are not supported (e.g. lists of list or dicts of dict).
A new Functional API model can also be created by using the
intermediate tensors. This enables you to quickly extract sub-components
of the model.
Example:
```python
inputs = keras.Input(shape=(None, None, 3))
processed = keras.layers.RandomCrop(width=32, height=32)(inputs)
conv = keras.layers.Conv2D(filters=2, kernel_size=3)(processed)
pooling = keras.layers.GlobalAveragePooling2D()(conv)
feature = keras.layers.Dense(10)(pooling)
full_model = keras.Model(inputs, feature)
backbone = keras.Model(processed, conv)
activations = keras.Model(conv, feature)
```
Note that the `backbone` and `activations` models are not
created with `keras.Input` objects, but with the tensors that are originated
from `keras.Input` objects. Under the hood, the layers and weights will
be shared across these models, so that user can train the `full_model`, and
use `backbone` or `activations` to do feature extraction.
The inputs and outputs of the model can be nested structures of tensors as
well, and the created models are standard Functional API models that support
all the existing APIs.
2 - By subclassing the `Model` class: in that case, you should define your
layers in `__init__()` and you should implement the model's forward pass
in `call()`.
```python
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
def call(self, inputs):
x = self.dense1(inputs)
return self.dense2(x)
model = MyModel()
```
If you subclass `Model`, you can optionally have
a `training` argument (boolean) in `call()`, which you can use to specify
a different behavior in training and inference:
```python
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
self.dropout = tf.keras.layers.Dropout(0.5)
def call(self, inputs, training=False):
x = self.dense1(inputs)
if training:
x = self.dropout(x, training=training)
return self.dense2(x)
model = MyModel()
```
Once the model is created, you can config the model with losses and metrics
with `model.compile()`, train the model with `model.fit()`, or use the model
to do prediction with `model.predict()`.
"""
_TF_MODULE_IGNORED_PROPERTIES = frozenset(
itertools.chain(
(
"_train_counter",
"_test_counter",
"_predict_counter",
"_steps_per_execution",
"_compiled_trainable_state",
),
base_layer.Layer._TF_MODULE_IGNORED_PROPERTIES,
)
)
_SCALAR_UPRANKING_ON = False
def __new__(cls, *args, **kwargs):
# Signature detection
if is_functional_model_init_params(args, kwargs) and cls == Model:
# Functional model
from tf_keras.src.engine import functional
return functional.Functional(skip_init=True, *args, **kwargs)
else:
return super(Model, cls).__new__(cls, *args, **kwargs)
@tf.__internal__.tracking.no_automatic_dependency_tracking
@traceback_utils.filter_traceback
def __init__(self, *args, **kwargs):
self._is_model_for_instrumentation = True
# Special case for Subclassed Functional Model, which we couldn't detect
# when __new__ is called. We only realize it is a functional model when
# it calls super.__init__ with input and output tensor.
from tf_keras.src.engine import functional
if is_functional_model_init_params(args, kwargs) and not isinstance(
self, functional.Functional
):
# Filter the kwargs for multiple inheritance.
supported_kwargs = [
"inputs",
"outputs",
"name",
"trainable",
"skip_init",
]
model_kwargs = {
k: kwargs[k] for k in kwargs if k in supported_kwargs
}
other_kwargs = {
k: kwargs[k] for k in kwargs if k not in supported_kwargs
}
inject_functional_model_class(self.__class__)
functional.Functional.__init__(self, *args, **model_kwargs)
# In case there is any multiple inheritance here, we need to call
# the __init__ for any class that appears after the Functional
# class.
clz_to_init = []
found_functional_class = False
for clz in self.__class__.__bases__:
if issubclass(clz, functional.Functional):
found_functional_class = True
continue
if found_functional_class:
clz_to_init.append(clz)
if clz_to_init:
for clz in clz_to_init:
clz.__init__(self, *args, **other_kwargs)
elif other_kwargs:
# In case there are unused kwargs, we should raise an error to
# user, in case they have a typo in the param name.
raise TypeError(
"The following keyword arguments passed to `Model` aren't "
"supported: {}.".format(other_kwargs)
)
return
# The following are implemented as property functions:
# self.trainable_weights
# self.non_trainable_weights
# `inputs` / `outputs` will only appear in kwargs if either are
# misspelled.
generic_utils.validate_kwargs(
kwargs,
{
"trainable",
"dtype",
"dynamic",
"name",
"autocast",
"inputs",
"outputs",
},
)
super().__init__(**kwargs)
# By default, Model is a subclass model, which is not in graph network.
self._is_graph_network = False
self.inputs = None
self.outputs = None
self.input_names = None
self.output_names = None
# stop_training is used by callback to stop training when error happens
self.stop_training = False
self.history = None
# These objects are used in the default `Model.compile`. They are not
# guaranteed to be set after `Model.compile` is called, as users can
# override compile with custom logic.
self.compiled_loss = None
self.compiled_metrics = None
# This is True for Sequential networks and Functional networks.
self._compute_output_and_mask_jointly = False
# Don't reset compilation if already done. This may occur if calling
# `__init__` (or `_init_graph_network`) on an already-compiled model
# such as a Sequential model. Sequential models may need to rebuild
# themselves after compilation.
self._maybe_create_attribute("_is_compiled", False)
self._maybe_create_attribute("optimizer", None)
# Model must be created under scope of DistStrat it will be trained
# with.
if tf.distribute.has_strategy():
self._distribution_strategy = tf.distribute.get_strategy()
else:
self._distribution_strategy = None
self._distribute_reduction_method = None
self._cluster_coordinator = None
# Defaults to value of `tf.config.experimental_functions_run_eagerly`.
self._run_eagerly = None
# Initialize cache attrs.
self._reset_compile_cache()
# Fault-tolerance handler. Set in `ModelCheckpoint`.
self._training_state = None
self._saved_model_inputs_spec = None
self._saved_model_arg_spec = None
self._checkpoint = tf.train.Checkpoint(root=weakref.ref(self))
self._steps_per_execution = None
self._steps_per_execution_tuner = None
self._autotune_steps_per_execution = False
self._layout_map = layout_map_lib.get_current_layout_map()
self._init_batch_counters()
self._base_model_initialized = True
# `jit_compile` starts off with None as default and gets overwritten by
# the value specified in `Model.compile`, and this is effective for
# `fit`, `evaluate`, and `predict`.
self._jit_compile = None
def _create_counter_variable(self, init_value):
"""Helper function for counter variable creation.
For the DTensor use case with layout map, since the variable are not
tracked by model, they can't be visited by the layout map, and need to
be properly initialized as DVariable.
"""
# This function should be removed after we move to the strategy based
# implementation for DTensor.
if self._layout_map is None:
agg = tf.VariableAggregation.ONLY_FIRST_REPLICA
return tf.Variable(init_value, dtype="int64", aggregation=agg)
else:
layout = dtensor_api.Layout.replicated(
mesh=self._layout_map.get_default_mesh(), rank=0
)
return dtensor_api.DVariable(
init_value, dtype="int64", layout=layout
)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _init_batch_counters(self):
# Untracked Variables, used to keep track of mini-batches seen in `fit`,
# `evaluate`, and `predict`.
if not tf.inside_function():
# Creating variables inside tf.function is not allowed, hence
# these would otherwise prevent users from creating TF-Keras layers
# inside tf.function.
# These variables are not connected to outputs so they have no
# effect on graph generation anyway.
self._train_counter = self._create_counter_variable(0)
self._test_counter = self._create_counter_variable(0)
self._predict_counter = self._create_counter_variable(0)
def __setattr__(self, name, value):
if not getattr(self, "_self_setattr_tracking", True):
super().__setattr__(name, value)
return
if all(
isinstance(v, (base_layer.Layer, tf.Variable))
or base_layer_utils.has_weights(v)
for v in tf.nest.flatten(value)
):
try:
self._base_model_initialized
except AttributeError:
raise RuntimeError(
"It looks like you are subclassing `Model` and you "
"forgot to call `super().__init__()`."
" Always start with this line."
)
super().__setattr__(name, value)
def __reduce__(self):
if self.built:
return (
pickle_utils.deserialize_model_from_bytecode,
(pickle_utils.serialize_model_as_bytecode(self),),
)
else:
# SavedModel (and hence serialize_model_as_bytecode) only support
# built models, but if the model is not built,
# it may be possible to serialize as a plain Python object,
# as long as the constituent parts (layers, optimizers, losses,
# etc.) can be serialized as plain Python objects. Thus we call up
# the superclass hierarchy to get an implementation of __reduce__
# that can pickle this Model as a plain Python object.
return super().__reduce__()
def __deepcopy__(self, memo):
if self.built:
new = pickle_utils.deserialize_model_from_bytecode(
pickle_utils.serialize_model_as_bytecode(self)
)
memo[id(self)] = new
else:
# See comment in __reduce__ for explanation
deserializer, serialized, *rest = super().__reduce__()
new = deserializer(*serialized)
memo[id(self)] = new
if rest:
state = copy.deepcopy(rest[0], memo=memo)
new.__setstate__(state)
return new
def __copy__(self):
return self.__deepcopy__({})
@generic_utils.default
def build(self, input_shape):
"""Builds the model based on input shapes received.
This is to be used for subclassed models, which do not know at
instantiation time what their inputs look like.
This method only exists for users who want to call `model.build()` in a
standalone way (as a substitute for calling the model on real data to
build it). It will never be called by the framework (and thus it will
never throw unexpected errors in an unrelated workflow).
Args:
input_shape: Single tuple, `TensorShape` instance, or list/dict of
shapes, where shapes are tuples, integers, or `TensorShape`
instances.
Raises:
ValueError:
1. In case of invalid user-provided data (not of type tuple,
list, `TensorShape`, or dict).
2. If the model requires call arguments that are agnostic
to the input shapes (positional or keyword arg in call
signature).
3. If not all layers were properly built.
4. If float type inputs are not supported within the layers.
In each of these cases, the user should build their model by calling
it on real tensor data.
"""
if self._is_graph_network:
super().build(input_shape)
return
if input_shape is None:
raise ValueError(
"Input shape must be defined when calling `build()` on "
"a `Model` subclass."
)
valid_types = (tuple, list, tf.TensorShape, dict)
if not isinstance(input_shape, valid_types):
raise ValueError(
"Specified input shape is not one of the valid types. "
"Please specify a batch input shape of type tuple or "
"list of input shapes. User provided "
"input type: {}.".format(type(input_shape))
)
if input_shape and not self.inputs:
# We create placeholders for the `None`s in the shape and build the
# model in a Graph. Since tf.Variable is compatible with both eager
# execution and graph building, the variables created after building
# the model in a Graph are still valid when executing eagerly.
if tf.executing_eagerly():
graph = tf.__internal__.FuncGraph("build_graph")
else:
graph = backend.get_graph()
with graph.as_default():
if isinstance(input_shape, list) and all(
d is None or isinstance(d, int) for d in input_shape
):
input_shape = tuple(input_shape)
if isinstance(input_shape, list):
x = [
base_layer_utils.generate_placeholders_from_shape(shape)
for shape in input_shape
]
elif isinstance(input_shape, dict):
x = {
k: base_layer_utils.generate_placeholders_from_shape(
shape
)
for k, shape in input_shape.items()
}
else:
x = base_layer_utils.generate_placeholders_from_shape(
input_shape
)
kwargs = {}
call_signature = self._call_spec.full_argspec
call_args = call_signature.args
# Exclude `self`, `inputs`, and any argument with a default
# value.
if len(call_args) > 2:
if call_signature.defaults:
call_args = call_args[2 : -len(call_signature.defaults)]
else:
call_args = call_args[2:]
for arg in call_args:
if arg == "training":
# Case where `training` is a positional arg with no
# default.
kwargs["training"] = False
else:
# Has invalid call signature with unknown positional
# arguments.
raise ValueError(
"Currently, you cannot build your model if it "
"has positional or keyword arguments that are "
"not inputs to the model, but are required for "
"its `call()` method. Instead, in order to "
"instantiate and build your model, `call()` "
"your model on real tensor data with all "
"expected call arguments. The argument "
"for `call()` can be a single list/tuple that "
"contains multiple inputs."
)
elif len(call_args) < 2:
# Signature without `inputs`.
raise ValueError(
"You can only call `build()` on a model if its "
"`call()` method accepts an `inputs` argument."
)
try:
self.call(x, **kwargs)
except (tf.errors.InvalidArgumentError, TypeError) as e:
raise ValueError(
"You cannot build your model by calling `build` "
"if your layers do not support float type inputs. "
"Instead, in order to instantiate and build your "
"model, call your model on real tensor data (of "
"the correct dtype).\n\nThe actual error from "
f"`call` is: {e}."
)
super().build(input_shape)
@traceback_utils.filter_traceback
def __call__(self, *args, **kwargs):
if self._layout_map is not None and not self.built:
# Note that this method is only overridden for DTensor and layout
# injection purpose.
# Capture the inputs and create graph input as replacement for model
# to initialize its weights first.
copied_args = copy.copy(args)
copied_kwargs = copy.copy(kwargs)
(
inputs,
copied_args,
copied_kwargs,
) = self._call_spec.split_out_first_arg(copied_args, copied_kwargs)
def _convert_to_graph_inputs(x):
if isinstance(x, (tf.Tensor, np.ndarray, float, int)):
x = tf.convert_to_tensor(x)
return input_layer_module.Input(x.shape)
# TODO(scottzhu): maybe better handle mask and training flag.
inputs = tf.nest.map_structure(_convert_to_graph_inputs, inputs)
copied_args = tf.nest.map_structure(
_convert_to_graph_inputs, copied_args
)
copied_kwargs = tf.nest.map_structure(
_convert_to_graph_inputs, copied_kwargs
)
with layout_map_lib.layout_map_scope(self._layout_map):
# We ignore the result here.
super().__call__(inputs, *copied_args, **copied_kwargs)
layout_map_lib._map_subclass_model_variable(self, self._layout_map)
return super().__call__(*args, **kwargs)
@doc_controls.doc_in_current_and_subclasses
def call(self, inputs, training=None, mask=None):
"""Calls the model on new inputs and returns the outputs as tensors.
In this case `call()` just reapplies
all ops in the graph to the new inputs
(e.g. build a new computational graph from the provided inputs).
Note: This method should not be called directly. It is only meant to be
overridden when subclassing `tf.keras.Model`.
To call a model on an input, always use the `__call__()` method,
i.e. `model(inputs)`, which relies on the underlying `call()` method.
Args:
inputs: Input tensor, or dict/list/tuple of input tensors.
training: Boolean or boolean scalar tensor, indicating whether to
run the `Network` in training mode or inference mode.
mask: A mask or list of masks. A mask can be either a boolean tensor
or None (no mask). For more details, check the guide
[here](https://www.tensorflow.org/guide/keras/masking_and_padding).
Returns:
A tensor if there is a single output, or
a list of tensors if there are more than one outputs.
"""
raise NotImplementedError(
"Unimplemented `tf.keras.Model.call()`: if you "
"intend to create a `Model` with the Functional "
"API, please provide `inputs` and `outputs` "
"arguments. Otherwise, subclass `Model` with an "
"overridden `call()` method."
)
@traceback_utils.filter_traceback
def compile(
self,
optimizer="rmsprop",
loss=None,
metrics=None,
loss_weights=None,
weighted_metrics=None,
run_eagerly=None,
steps_per_execution=None,
jit_compile=None,
pss_evaluation_shards=0,
**kwargs,
):
"""Configures the model for training.
Example:
```python
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),
loss=tf.keras.losses.BinaryCrossentropy(),
metrics=[tf.keras.metrics.BinaryAccuracy(),
tf.keras.metrics.FalseNegatives()])
```
Args:
optimizer: String (name of optimizer) or optimizer instance. See
`tf.keras.optimizers`.
loss: Loss function. May be a string (name of loss function), or
a `tf.keras.losses.Loss` instance. See `tf.keras.losses`. A loss
function is any callable with the signature `loss = fn(y_true,
y_pred)`, where `y_true` are the ground truth values, and
`y_pred` are the model's predictions.
`y_true` should have shape
`(batch_size, d0, .. dN)` (except in the case of
sparse loss functions such as
sparse categorical crossentropy which expects integer arrays of
shape `(batch_size, d0, .. dN-1)`).
`y_pred` should have shape `(batch_size, d0, .. dN)`.
The loss function should return a float tensor.
If a custom `Loss` instance is
used and reduction is set to `None`, return value has shape
`(batch_size, d0, .. dN-1)` i.e. per-sample or per-timestep loss
values; otherwise, it is a scalar. If the model has multiple
outputs, you can use a different loss on each output by passing a
dictionary or a list of losses. The loss value that will be
minimized by the model will then be the sum of all individual
losses, unless `loss_weights` is specified.
metrics: List of metrics to be evaluated by the model during
training and testing. Each of this can be a string (name of a
built-in function), function or a `tf.keras.metrics.Metric`
instance. See `tf.keras.metrics`. Typically you will use
`metrics=['accuracy']`.
A function is any callable with the signature `result = fn(y_true,
y_pred)`. To specify different metrics for different outputs of a
multi-output model, you could also pass a dictionary, such as
`metrics={'output_a':'accuracy', 'output_b':['accuracy', 'mse']}`.
You can also pass a list to specify a metric or a list of metrics
for each output, such as
`metrics=[['accuracy'], ['accuracy', 'mse']]`
or `metrics=['accuracy', ['accuracy', 'mse']]`. When you pass the
strings 'accuracy' or 'acc', we convert this to one of
`tf.keras.metrics.BinaryAccuracy`,
`tf.keras.metrics.CategoricalAccuracy`,
`tf.keras.metrics.SparseCategoricalAccuracy` based on the shapes
of the targets and of the model output. We do a similar
conversion for the strings 'crossentropy' and 'ce' as well.
The metrics passed here are evaluated without sample weighting; if
you would like sample weighting to apply, you can specify your
metrics via the `weighted_metrics` argument instead.
loss_weights: Optional list or dictionary specifying scalar
coefficients (Python floats) to weight the loss contributions of
different model outputs. The loss value that will be minimized by
the model will then be the *weighted sum* of all individual
losses, weighted by the `loss_weights` coefficients. If a list,
it is expected to have a 1:1 mapping to the model's outputs. If a
dict, it is expected to map output names (strings) to scalar
coefficients.
weighted_metrics: List of metrics to be evaluated and weighted by
`sample_weight` or `class_weight` during training and testing.
run_eagerly: Bool. If `True`, this `Model`'s logic will not be
wrapped in a `tf.function`. Recommended to leave this as `None`
unless your `Model` cannot be run inside a `tf.function`.
`run_eagerly=True` is not supported when using
`tf.distribute.experimental.ParameterServerStrategy`. Defaults to
`False`.
steps_per_execution: Int or `'auto'`. The number of batches to
run during each `tf.function` call. If set to "auto", keras will
automatically tune `steps_per_execution` during runtime. Running
multiple batches inside a single `tf.function` call can greatly
improve performance on TPUs, when used with distributed strategies
such as `ParameterServerStrategy`, or with small models with a
large Python overhead. At most, one full epoch will be run each
execution. If a number larger than the size of the epoch is
passed, the execution will be truncated to the size of the epoch.
Note that if `steps_per_execution` is set to `N`,
`Callback.on_batch_begin` and `Callback.on_batch_end` methods will
only be called every `N` batches (i.e. before/after each
`tf.function` execution). Defaults to `1`.
jit_compile: If `True`, compile the model training step with XLA.
[XLA](https://www.tensorflow.org/xla) is an optimizing compiler
for machine learning.
`jit_compile` is not enabled for by default.
Note that `jit_compile=True`
may not necessarily work for all models.
For more information on supported operations please refer to the
[XLA documentation](https://www.tensorflow.org/xla).
Also refer to
[known XLA issues](https://www.tensorflow.org/xla/known_issues)
for more details.
pss_evaluation_shards: Integer or 'auto'. Used for
`tf.distribute.ParameterServerStrategy` training only. This arg
sets the number of shards to split the dataset into, to enable an
exact visitation guarantee for evaluation, meaning the model will
be applied to each dataset element exactly once, even if workers
fail. The dataset must be sharded to ensure separate workers do
not process the same data. The number of shards should be at least
the number of workers for good performance. A value of 'auto'
turns on exact evaluation and uses a heuristic for the number of
shards based on the number of workers. 0, meaning no
visitation guarantee is provided. NOTE: Custom implementations of
`Model.test_step` will be ignored when doing exact evaluation.
Defaults to `0`.
**kwargs: Arguments supported for backwards compatibility only.
"""
if jit_compile and not tf_utils.can_jit_compile(warn=True):
jit_compile = False
self._compile_config = serialization_lib.Config(
optimizer=optimizer,
loss=loss,
metrics=metrics,
loss_weights=loss_weights,
weighted_metrics=weighted_metrics,
run_eagerly=run_eagerly,
steps_per_execution=steps_per_execution,
jit_compile=jit_compile,
)
with self.distribute_strategy.scope():
if "experimental_steps_per_execution" in kwargs:
logging.warning(
"The argument `steps_per_execution` is no longer "
"experimental. Pass `steps_per_execution` instead of "
"`experimental_steps_per_execution`."
)
if not steps_per_execution:
steps_per_execution = kwargs.pop(
"experimental_steps_per_execution"
)
# When compiling from an already-serialized model, we do not want to
# reapply some processing steps (e.g. metric renaming for
# multi-output models, which have prefixes added for each
# corresponding output name).
from_serialized = kwargs.pop("from_serialized", False)
self._validate_compile(optimizer, metrics, **kwargs)
self._run_eagerly = run_eagerly
self.optimizer = self._get_optimizer(optimizer)
mesh = None
if self._layout_map is not None:
mesh = self._layout_map.get_default_mesh()
if isinstance(loss, compile_utils.LossesContainer):
self.compiled_loss = loss
else:
self.compiled_loss = compile_utils.LossesContainer(
loss,
loss_weights,
output_names=self.output_names,
mesh=mesh,
)
self.compiled_metrics = compile_utils.MetricsContainer(
metrics,
weighted_metrics,
output_names=self.output_names,
from_serialized=from_serialized,
mesh=mesh,
)
if steps_per_execution == "auto":
if self._steps_per_execution is None:
self._configure_steps_per_execution(1)
self._steps_per_execution_tuner = (
steps_per_execution_tuning.StepsPerExecutionTuner(
self.optimizer, self._steps_per_execution
)
)
self._autotune_steps_per_execution = True
else:
self._configure_steps_per_execution(steps_per_execution or 1)
self._pss_evaluation_shards = self._infer_exact_eval_shards(
pss_evaluation_shards
)
# Initializes attrs that are reset each time `compile` is called.
self._reset_compile_cache()
self._is_compiled = True
self.loss = loss or {}
if (self._run_eagerly or self.dynamic) and jit_compile:
raise ValueError(
"You cannot enable `run_eagerly` and `jit_compile` "
"at the same time."
)
else:
self._jit_compile = jit_compile
def _get_optimizer(self, optimizer):
"""Wraps `optimizer` in `LossScaleOptimizer` if necessary."""
def _get_single_optimizer(opt):
opt = optimizers.get(opt)
if self.dtype_policy.name == "mixed_float16" and not isinstance(
opt, lso.BaseLossScaleOptimizer
):
# Loss scaling is necessary with mixed_float16 for models to
# converge to the same accuracy as with float32.
opt = lso.BaseLossScaleOptimizer(opt)
return opt
return tf.nest.map_structure(_get_single_optimizer, optimizer)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _reset_compile_cache(self):
self.train_function = None
self.test_function = None
self.predict_function = None
# Used to cache the `tf.function`'ed `train_function` to be logged in
# TensorBoard, since the original `train_function` is not necessarily
# a `tf.function` (e.g., with ParameterServerStrategy, the
# `train_function` is a scheduling of the actual training function to a
# remote worker).
self.train_tf_function = None
# Used to cache `trainable` attr of `Layer`s for `fit`.
self._compiled_trainable_state = self._get_trainable_state()
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _configure_steps_per_execution(self, steps_per_execution):
self._steps_per_execution = self._create_counter_variable(
steps_per_execution
)
@property
def _should_compute_mask(self):
return False
@property
def metrics(self):
"""Return metrics added using `compile()` or `add_metric()`.
Note: Metrics passed to `compile()` are available only after a
`keras.Model` has been trained/evaluated on actual data.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> [m.name for m in model.metrics]
[]
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> model.fit(x, y)
>>> [m.name for m in model.metrics]
['loss', 'mae']
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> d = tf.keras.layers.Dense(2, name='out')
>>> output_1 = d(inputs)
>>> output_2 = d(inputs)
>>> model = tf.keras.models.Model(
... inputs=inputs, outputs=[output_1, output_2])
>>> model.add_metric(
... tf.reduce_sum(output_2), name='mean', aggregation='mean')
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
>>> model.fit(x, (y, y))
>>> [m.name for m in model.metrics]
['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',
'out_1_acc', 'mean']
"""
metrics = []
if self._is_compiled:
if self.compiled_loss is not None:
metrics += self.compiled_loss.metrics
if self.compiled_metrics is not None:
metrics += self.compiled_metrics.metrics
for l in self._flatten_layers():
metrics.extend(l._metrics)
return metrics
@property
def metrics_names(self):
"""Returns the model's display labels for all outputs.
Note: `metrics_names` are available only after a `keras.Model` has been
trained/evaluated on actual data.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> model.metrics_names
[]
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> model.fit(x, y)
>>> model.metrics_names
['loss', 'mae']
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> d = tf.keras.layers.Dense(2, name='out')
>>> output_1 = d(inputs)
>>> output_2 = d(inputs)
>>> model = tf.keras.models.Model(
... inputs=inputs, outputs=[output_1, output_2])
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
>>> model.fit(x, (y, y))
>>> model.metrics_names
['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',
'out_1_acc']
"""
# This property includes all output names including `loss` and
# per-output losses for backward compatibility.
return [m.name for m in self.metrics]
@property
def distribute_strategy(self):
"""The `tf.distribute.Strategy` this model was created under."""
return self._distribution_strategy or tf.distribute.get_strategy()
@property
def run_eagerly(self):
"""Settable attribute indicating whether the model should run eagerly.
Running eagerly means that your model will be run step by step,
like Python code. Your model might run slower, but it should become
easier for you to debug it by stepping into individual layer calls.
By default, we will attempt to compile your model to a static graph to
deliver the best execution performance.
Returns:
Boolean, whether the model should run eagerly.
"""
if self.dynamic and self._run_eagerly == False:
# TODO(fchollet): consider using py_func to enable this.
raise ValueError(
"Your model contains layers that can only be "
"successfully run in eager execution (layers "
"constructed with `dynamic=True`). "
"You cannot set `run_eagerly=False`."
)
if self._cluster_coordinator and self._run_eagerly:
raise ValueError(
"When using `Model` with `ParameterServerStrategy`, "
"`run_eagerly` is not supported."
)
# Run eagerly logic, by priority:
# (1) Dynamic models must be run eagerly.
# (2) Explicitly setting run_eagerly causes a Model to be run eagerly.
# (3) Not explicitly setting run_eagerly defaults to TF's global
# setting.
return (
self.dynamic
or self._run_eagerly
or (tf.config.functions_run_eagerly() and self._run_eagerly is None)
)
@run_eagerly.setter
def run_eagerly(self, value):
self._run_eagerly = value
@property
def autotune_steps_per_execution(self):
"""Settable property to enable tuning for steps_per_execution"""
return self._autotune_steps_per_execution
@autotune_steps_per_execution.setter
def autotune_steps_per_execution(self, value):
self._autotune_steps_per_execution = value
if value and self._steps_per_execution_tuner is None:
if self._steps_per_execution is None:
self._configure_steps_per_execution(1)
self._steps_per_execution_tuner = (
steps_per_execution_tuning.StepsPerExecutionTuner(
self.optimizer, self._steps_per_execution
)
)
@property
def steps_per_execution(self):
"""Settable `steps_per_execution variable. Requires a compiled model."""
return self._steps_per_execution
@steps_per_execution.setter
def steps_per_execution(self, value):
if self._steps_per_execution is None:
self._configure_steps_per_execution(value)
else:
self._steps_per_execution.assign(value)
@property
def jit_compile(self):
"""Specify whether to compile the model with XLA.
[XLA](https://www.tensorflow.org/xla) is an optimizing compiler
for machine learning. `jit_compile` is not enabled by default.
Note that `jit_compile=True` may not necessarily work for all models.
For more information on supported operations please refer to the
[XLA documentation](https://www.tensorflow.org/xla). Also refer to
[known XLA issues](https://www.tensorflow.org/xla/known_issues)
for more details.
"""
return self._jit_compile
@jit_compile.setter
def jit_compile(self, value):
# Function remains cached with previous jit_compile settings
if self._jit_compile == value:
# Avoid resetting compiler cache if possible if the value is the
# same
return
# Check if TensorFlow is compiled with XLA before setting the value
if value and not tf_utils.can_jit_compile(warn=True):
self._jit_compile = False
return
self._jit_compile = value
# Setting `jit_compile` should invalidate previously cached functions.
self._reset_compile_cache()
@property
def distribute_reduction_method(self):
"""The method employed to reduce per-replica values during training.
Unless specified, the value "auto" will be assumed, indicating that
the reduction strategy should be chosen based on the current
running environment.
See `reduce_per_replica` function for more details.
"""
return self._distribute_reduction_method or "auto"
@distribute_reduction_method.setter
def distribute_reduction_method(self, value):
self._distribute_reduction_method = value
def _validate_target_and_loss(self, y, loss):
"""Raises error if target or loss is not found.
This method verifies that the target and loss are properly populated
when applicable, or raises errors.
Args:
y: the target for training.
loss: the total loss tensor including loss added via `compile` and
`add_loss`.
"""
# `self.loss` references the loss added via `compile` call. If users
# have provided such, the target must be provided; otherwise it's a user
# error. Note that `self.loss` does not include losses added via
# `add_loss`, and it is a valid use when such loss from `add_loss`
# exists and target does not.
if self.loss and y is None:
raise ValueError(
"Target data is missing. Your model was compiled with "
f"loss={self.loss}, "
"and therefore expects target data to be provided in `fit()`."
)
# For training, there must be compiled loss or regularization loss to
# exist in order to apply the gradients. If one is not found, it means
# no loss was supplied via `compile` or `add_loss`.
elif loss is None:
raise ValueError(
"No loss found. You may have forgotten to provide a `loss` "
"argument in the `compile()` method."
)
def train_step(self, data):
"""The logic for one training step.
This method can be overridden to support custom training logic.
For concrete examples of how to override this method see
[Customizing what happens in fit](
https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit).
This method is called by `Model.make_train_function`.
This method should contain the mathematical logic for one step of
training. This typically includes the forward pass, loss calculation,
backpropagation, and metric updates.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_train_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the
values of the `Model`'s metrics are returned. Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data)
# Run forward pass.
with tf.GradientTape() as tape:
y_pred = self(x, training=True)
loss = self.compute_loss(x, y, y_pred, sample_weight)
self._validate_target_and_loss(y, loss)
# Run backwards pass.
self.optimizer.minimize(loss, self.trainable_variables, tape=tape)
return self.compute_metrics(x, y, y_pred, sample_weight)
def compute_loss(self, x=None, y=None, y_pred=None, sample_weight=None):
"""Compute the total loss, validate it, and return it.
Subclasses can optionally override this method to provide custom loss
computation logic.
Example:
```python
class MyModel(tf.keras.Model):
def __init__(self, *args, **kwargs):
super(MyModel, self).__init__(*args, **kwargs)
self.loss_tracker = tf.keras.metrics.Mean(name='loss')
def compute_loss(self, x, y, y_pred, sample_weight):
loss = tf.reduce_mean(tf.math.squared_difference(y_pred, y))
loss += tf.add_n(self.losses)
self.loss_tracker.update_state(loss)
return loss
def reset_metrics(self):
self.loss_tracker.reset_states()
@property
def metrics(self):
return [self.loss_tracker]
tensors = tf.random.uniform((10, 10)), tf.random.uniform((10,))
dataset = tf.data.Dataset.from_tensor_slices(tensors).repeat().batch(1)
inputs = tf.keras.layers.Input(shape=(10,), name='my_input')
outputs = tf.keras.layers.Dense(10)(inputs)
model = MyModel(inputs, outputs)
model.add_loss(tf.reduce_sum(outputs))
optimizer = tf.keras.optimizers.SGD()
model.compile(optimizer, loss='mse', steps_per_execution=10)
model.fit(dataset, epochs=2, steps_per_epoch=10)
print('My custom loss: ', model.loss_tracker.result().numpy())
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
The total loss as a `tf.Tensor`, or `None` if no loss results (which
is the case when called by `Model.test_step`).
"""
del x # The default implementation does not use `x`.
return self.compiled_loss(
y, y_pred, sample_weight, regularization_losses=self.losses
)
def compute_metrics(self, x, y, y_pred, sample_weight):
"""Update metric states and collect all metrics to be returned.
Subclasses can optionally override this method to provide custom metric
updating and collection logic.
Example:
```python
class MyModel(tf.keras.Sequential):
def compute_metrics(self, x, y, y_pred, sample_weight):
# This super call updates `self.compiled_metrics` and returns
# results for all metrics listed in `self.metrics`.
metric_results = super(MyModel, self).compute_metrics(
x, y, y_pred, sample_weight)
# Note that `self.custom_metric` is not listed in `self.metrics`.
self.custom_metric.update_state(x, y, y_pred, sample_weight)
metric_results['custom_metric_name'] = self.custom_metric.result()
return metric_results
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model.call(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end()`. Typically, the
values of the metrics listed in `self.metrics` are returned. Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
del x # The default implementation does not use `x`.
self.compiled_metrics.update_state(y, y_pred, sample_weight)
return self.get_metrics_result()
def get_metrics_result(self):
"""Returns the model's metrics values as a dict.
If any of the metric result is a dict (containing multiple metrics),
each of them gets added to the top level returned dict of this method.
Returns:
A `dict` containing values of the metrics listed in `self.metrics`.
Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
# Collect metrics to return
return_metrics = {}
for metric in self.metrics:
result = metric.result()
if isinstance(result, dict):
return_metrics.update(result)
else:
return_metrics[metric.name] = result
return return_metrics
def _validate_and_get_metrics_result(self, logs):
"""Returns model metrics as a dict if the keys match with input logs.
When the training / evalution is performed with asynchronous steps, such
as the case with `tf.distribute.ParameterServerStrategy`, the last
scheduled `train / test_step` may not give the latest metrics because it
is not guaranteed to be executed the last. This method gets metrics from
the model directly instead of relying on the return from last step
function.
It logs a warning if the metric results could not be overridden when
used with `tf.distribute.ParameterServerStrategy`.
When the user has custom train / test step functions, the metrics
returned may be different from `Model.metrics`. In those instances,
this function will be no-op and return the logs.
Args:
logs: A `dict` of metrics returned by train / test step function.
Returns:
A `dict` containing values of the metrics listed in `self.metrics`
when logs and model metrics keys match. Otherwise it returns input
`logs`.
"""
PSS_WARN_MSG = "Could not get Model metric results. \
Using the results of last step function could lead to incorrect \
results when used with ParameterServerStrategy"
try:
metric_logs = self.get_metrics_result()
except TypeError:
if self._cluster_coordinator:
logging.warning(PSS_WARN_MSG)
else:
# Verify that train / test step logs passed and metric logs have
# matching keys. Could be different when using custom step functions
if isinstance(logs, dict) and set(logs.keys()) == set(
metric_logs.keys()
):
logs = tf_utils.sync_to_numpy_or_python_type(metric_logs)
elif self._cluster_coordinator:
logging.warning(PSS_WARN_MSG)
return logs
def _aggregate_exact_metrics(self, logs):
# When doing exact evaluation, `logs` is a list of each data shard's
# metric variables, which will be used to update the metrics.
for shard_result in logs:
for metric in self.metrics:
if metric.name not in shard_result.keys():
logging.log_first_n(
logging.WARN,
f"No matching result found for metric {metric.name}. "
"This metric's computed result may be incorrect.",
3,
)
continue
metric_result = shard_result[metric.name]
if len(metric_result) != len(metric.weights):
raise ValueError(
f"Expected {len(metric.weights)} variables in result "
f"for metric {metric.name}, but found "
f"{len(metric_result)}."
)
for weight, val in zip(metric.weights, metric_result):
weight.assign_add(val)
return self.get_metrics_result()
def make_train_function(self, force=False):
"""Creates a function that executes one step of training.
This method can be overridden to support custom training logic.
This method is called by `Model.fit` and `Model.train_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual training
logic to `Model.train_step`.
This function is cached the first time `Model.fit` or
`Model.train_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the train function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_train_batch_end`, such as
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
if self.train_function is not None and not force:
return self.train_function
def step_function(model, iterator):
"""Runs a single training step."""
def run_step(data):
outputs = model.train_step(data)
# Ensure counter is updated only if `train_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._train_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def train_function(iterator):
"""Runs a training execution with a single step."""
return step_function(self, iterator)
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
if self._cluster_coordinator:
self.train_function = (
lambda it: self._cluster_coordinator.schedule(
train_function, args=(it,)
)
)
else:
self.train_function = train_function
# If we're using a coordinator, use the value of
# self._steps_per_execution at the time the function is
# called/scheduled, and not when it is actually executed.
elif self._cluster_coordinator:
def train_function(iterator, steps_per_execution):
"""Runs a training execution with multiple steps."""
for _ in tf.range(steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
self.train_function = lambda it: self._cluster_coordinator.schedule(
train_function, args=(it, self._steps_per_execution.value())
)
else:
def train_function(iterator):
"""Runs a training execution with multiple steps."""
for _ in tf.range(self._steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
self.train_function = train_function
return self.train_function
@traceback_utils.filter_traceback
def fit(
self,
x=None,
y=None,
batch_size=None,
epochs=1,
verbose="auto",
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_batch_size=None,
validation_freq=1,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
):
"""Trains the model for a fixed number of epochs (dataset iterations).
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A `tf.data` dataset. Should return a tuple
of either `(inputs, targets)` or
`(inputs, targets, sample_weights)`.
- A generator or `keras.utils.Sequence` returning `(inputs,
targets)` or `(inputs, targets, sample_weights)`.
- A `tf.keras.utils.experimental.DatasetCreator`, which wraps a
callable that takes a single argument of type
`tf.distribute.InputContext`, and returns a `tf.data.Dataset`.
`DatasetCreator` should be used when users prefer to specify the
per-replica batching and sharding logic for the `Dataset`.
See `tf.keras.utils.experimental.DatasetCreator` doc for more
information.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given below. If these
include `sample_weights` as a third component, note that sample
weighting applies to the `weighted_metrics` argument but not the
`metrics` argument in `compile()`. If using
`tf.distribute.experimental.ParameterServerStrategy`, only
`DatasetCreator` type is supported for `x`.
y: Target data. Like the input data `x`,
it could be either Numpy array(s) or TensorFlow tensor(s).
It should be consistent with `x` (you cannot have Numpy inputs and
tensor targets, or inversely). If `x` is a dataset, generator,
or `keras.utils.Sequence` instance, `y` should
not be specified (since targets will be obtained from `x`).
batch_size: Integer or `None`.
Number of samples per gradient 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).
epochs: Integer. Number of epochs to train the model.
An epoch is an iteration over the entire `x` and `y`
data provided
(unless the `steps_per_epoch` flag is set to
something other than None).
Note that in conjunction with `initial_epoch`,
`epochs` is to be understood as "final epoch".
The model is not trained for a number of iterations
given by `epochs`, but merely until the epoch
of index `epochs` is reached.
verbose: 'auto', 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = one line per epoch.
'auto' becomes 1 for most cases, but 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so verbose=2 is
recommended when not running interactively (eg, in a production
environment). Defaults to 'auto'.
callbacks: List of `keras.callbacks.Callback` instances.
List of callbacks to apply during training.
See `tf.keras.callbacks`. Note
`tf.keras.callbacks.ProgbarLogger` and
`tf.keras.callbacks.History` callbacks are created automatically
and need not be passed into `model.fit`.
`tf.keras.callbacks.ProgbarLogger` is created or not based on
`verbose` argument to `model.fit`.
Callbacks with batch-level calls are currently unsupported with
`tf.distribute.experimental.ParameterServerStrategy`, and users
are advised to implement epoch-level calls instead with an
appropriate `steps_per_epoch` value.
validation_split: Float between 0 and 1.
Fraction of the training data to be used as validation data.
The model will set apart this fraction of the training data,
will not train on it, and will evaluate
the loss and any model metrics
on this data at the end of each epoch.
The validation data is selected from the last samples
in the `x` and `y` data provided, before shuffling. This
argument is not supported when `x` is a dataset, generator or
`keras.utils.Sequence` instance.
If both `validation_data` and `validation_split` are provided,
`validation_data` will override `validation_split`.
`validation_split` is not yet supported with
`tf.distribute.experimental.ParameterServerStrategy`.
validation_data: Data on which to evaluate
the loss and any model metrics at the end of each epoch.
The model will not be trained on this data. Thus, note the fact
that the validation loss of data provided using
`validation_split` or `validation_data` is not affected by
regularization layers like noise and dropout.
`validation_data` will override `validation_split`.
`validation_data` could be:
- A tuple `(x_val, y_val)` of Numpy arrays or tensors.
- A tuple `(x_val, y_val, val_sample_weights)` of NumPy
arrays.
- A `tf.data.Dataset`.
- A Python generator or `keras.utils.Sequence` returning
`(inputs, targets)` or `(inputs, targets, sample_weights)`.
`validation_data` is not yet supported with
`tf.distribute.experimental.ParameterServerStrategy`.
shuffle: Boolean (whether to shuffle the training data
before each epoch) or str (for 'batch'). This argument is
ignored when `x` is a generator or an object of tf.data.Dataset.
'batch' is a special option for dealing
with the limitations of HDF5 data; it shuffles in batch-sized
chunks. Has no effect when `steps_per_epoch` is not `None`.
class_weight: Optional dictionary mapping class indices (integers)
to a weight (float) value, used for weighting the loss function
(during training only).
This can be useful to tell the model to
"pay more attention" to samples from
an under-represented class. When `class_weight` is specified
and targets have a rank of 2 or greater, either `y` must be
one-hot encoded, or an explicit final dimension of `1` must
be included for sparse class labels.
sample_weight: Optional Numpy array of weights for
the training samples, used for weighting the loss function
(during training only). You can either pass a flat (1D)
Numpy array with the same length as the input samples
(1:1 mapping between weights and samples),
or in the case of temporal data,
you can pass a 2D array with shape
`(samples, sequence_length)`,
to apply a different weight to every timestep of every sample.
This argument is not supported when `x` is a dataset, generator,
or `keras.utils.Sequence` instance, instead provide the
sample_weights as the third element of `x`.
Note that sample weighting does not apply to metrics specified
via the `metrics` argument in `compile()`. To apply sample
weighting to your metrics, you can specify them via the
`weighted_metrics` in `compile()` instead.
initial_epoch: Integer.
Epoch at which to start training
(useful for resuming a previous training run).
steps_per_epoch: Integer or `None`.
Total number of steps (batches of samples)
before declaring one epoch finished and starting the
next epoch. 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_per_epoch'
is None, the epoch will run until the input dataset is
exhausted. When passing an infinitely repeating dataset, you
must specify the `steps_per_epoch` argument. If
`steps_per_epoch=-1` the training will run indefinitely with an
infinitely repeating dataset. This argument is not supported
with array inputs.
When using `tf.distribute.experimental.ParameterServerStrategy`:
* `steps_per_epoch=None` is not supported.
validation_steps: Only relevant if `validation_data` is provided and
is a `tf.data` dataset. Total number of steps (batches of
samples) to draw before stopping when performing validation
at the end of every epoch. If 'validation_steps' is None,
validation will run until the `validation_data` dataset is
exhausted. In the case of an infinitely repeated dataset, it
will run into an infinite loop. If 'validation_steps' is
specified and only part of the dataset will be consumed, the
evaluation will start from the beginning of the dataset at each
epoch. This ensures that the same validation samples are used
every time.
validation_batch_size: Integer or `None`.
Number of samples per validation batch.
If unspecified, will default to `batch_size`.
Do not specify the `validation_batch_size` if your data is in
the form of datasets, generators, or `keras.utils.Sequence`
instances (since they generate batches).
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.
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the generator
queue. If unspecified, `max_queue_size` will default to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up
when using process-based threading. If unspecified, `workers`
will default to 1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
Unpacking behavior for iterator-like inputs:
A common pattern is to pass a tf.data.Dataset, generator, or
tf.keras.utils.Sequence to the `x` argument of fit, which will in fact
yield not only features (x) but optionally targets (y) and sample
weights. TF-Keras requires that the output of such iterator-likes be
unambiguous. The iterator should return a tuple of length 1, 2, or 3,
where the optional second and third elements will be used for y and
sample_weight respectively. Any other type provided will be wrapped in
a length one tuple, effectively treating everything as 'x'. When
yielding dicts, they should still adhere to the top-level tuple
structure.
e.g. `({"x0": x0, "x1": x1}, y)`. TF-Keras will not attempt to
separate features, targets, and weights from the keys of a single
dict.
A notable unsupported data type is the namedtuple. The reason is
that it behaves like both an ordered datatype (tuple) and a mapping
datatype (dict). So given a namedtuple of the form:
`namedtuple("example_tuple", ["y", "x"])`
it is ambiguous whether to reverse the order of the elements when
interpreting the value. Even worse is a tuple of the form:
`namedtuple("other_tuple", ["x", "y", "z"])`
where it is unclear if the tuple was intended to be unpacked into x,
y, and sample_weight or passed through as a single element to `x`. As
a result the data processing code will simply raise a ValueError if it
encounters a namedtuple. (Along with instructions to remedy the
issue.)
Returns:
A `History` object. Its `History.history` attribute is
a record of training loss values and metrics values
at successive epochs, as well as validation loss values
and validation metrics values (if applicable).
Raises:
RuntimeError: 1. If the model was never compiled or,
2. If `model.fit` is wrapped in `tf.function`.
ValueError: In case of mismatch between the provided input data
and what the model expects or when the input data is empty.
"""
# Legacy graph support is contained in `training_v1.Model`.
version_utils.disallow_legacy_graph("Model", "fit")
self._assert_compile_was_called()
self._check_call_args("fit")
_disallow_inside_tf_function("fit")
verbose = _get_verbosity(verbose, self.distribute_strategy)
if validation_split and validation_data is None:
# Create the validation data using the training data. Only supported
# for `Tensor` and `NumPy` input.
(
x,
y,
sample_weight,
), validation_data = data_adapter.train_validation_split(
(x, y, sample_weight), validation_split=validation_split
)
if validation_data:
(
val_x,
val_y,
val_sample_weight,
) = data_adapter.unpack_x_y_sample_weight(validation_data)
if self.distribute_strategy._should_use_with_coordinator:
self._cluster_coordinator = (
tf.distribute.experimental.coordinator.ClusterCoordinator(
self.distribute_strategy
)
)
with self.distribute_strategy.scope(), training_utils.RespectCompiledTrainableState( # noqa: E501
self
):
# Creates a `tf.data.Dataset` and handles batch and epoch iteration.
data_handler = data_adapter.get_data_handler(
x=x,
y=y,
sample_weight=sample_weight,
batch_size=batch_size,
steps_per_epoch=steps_per_epoch,
initial_epoch=initial_epoch,
epochs=epochs,
shuffle=shuffle,
class_weight=class_weight,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=epochs,
steps=data_handler.inferred_steps,
)
self.stop_training = False
self.train_function = self.make_train_function()
self._train_counter.assign(0)
callbacks.on_train_begin()
training_logs = None
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
# Handle fault-tolerance for multi-worker.
# TODO(omalleyt): Fix the ordering issues that mean this has to
# happen after `callbacks.on_train_begin`.
steps_per_epoch_inferred = (
steps_per_epoch or data_handler.inferred_steps
)
(
data_handler._initial_epoch,
data_handler._initial_step,
) = self._maybe_load_initial_counters_from_ckpt(
steps_per_epoch_inferred, initial_epoch
)
logs = None
for epoch, iterator in data_handler.enumerate_epochs():
self.reset_metrics()
callbacks.on_epoch_begin(epoch)
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
with tf.profiler.experimental.Trace(
"train",
epoch_num=epoch,
step_num=step,
batch_size=batch_size,
_r=1,
):
callbacks.on_train_batch_begin(step)
tmp_logs = self.train_function(iterator)
if data_handler.should_sync:
context.async_wait()
# No error, now safe to assign to logs.
logs = tmp_logs
end_step = step + data_handler.step_increment
callbacks.on_train_batch_end(end_step, logs)
if self.stop_training:
break
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if logs is None:
raise ValueError(
"Unexpected result of `train_function` "
"(Empty logs). This could be due to issues in input "
"pipeline that resulted in an empty dataset. "
"Otherwise, please use "
"`Model.compile(..., run_eagerly=True)`, or "
"`tf.config.run_functions_eagerly(True)` for more "
"information of where went wrong, or file a "
"issue/bug to `tf.keras`."
)
# Override with model metrics instead of last step logs
logs = self._validate_and_get_metrics_result(logs)
epoch_logs = copy.copy(logs)
# Run validation.
if validation_data and self._should_eval(
epoch, validation_freq
):
if self._pss_evaluation_shards:
self._disallow_exact_eval_with_add_metrics()
# Create data_handler for evaluation and cache it.
if getattr(self, "_eval_data_handler", None) is None:
self._eval_data_handler = data_adapter.get_data_handler(
x=val_x,
y=val_y,
sample_weight=val_sample_weight,
batch_size=validation_batch_size or batch_size,
steps_per_epoch=validation_steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
pss_evaluation_shards=self._pss_evaluation_shards,
)
val_logs = self.evaluate(
x=val_x,
y=val_y,
sample_weight=val_sample_weight,
batch_size=validation_batch_size or batch_size,
steps=validation_steps,
callbacks=callbacks,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
return_dict=True,
_use_cached_eval_dataset=True,
)
val_logs = {
"val_" + name: val for name, val in val_logs.items()
}
epoch_logs.update(val_logs)
callbacks.on_epoch_end(epoch, epoch_logs)
training_logs = epoch_logs
if self.stop_training:
break
if isinstance(self.optimizer, optimizer.Optimizer) and epochs > 0:
self.optimizer.finalize_variable_values(
self.trainable_variables
)
# If eval data_handler exists, delete it after all epochs are done.
if getattr(self, "_eval_data_handler", None) is not None:
del self._eval_data_handler
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_train_end(logs=training_logs)
return self.history
def test_step(self, data):
"""The logic for one evaluation step.
This method can be overridden to support custom evaluation logic.
This method is called by `Model.make_test_function`.
This function should contain the mathematical logic for one step of
evaluation.
This typically includes the forward pass, loss calculation, and metrics
updates.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_test_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the
values of the `Model`'s metrics are returned.
"""
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data)
y_pred = self(x, training=False)
# Updates stateful loss metrics.
self.compute_loss(x, y, y_pred, sample_weight)
return self.compute_metrics(x, y, y_pred, sample_weight)
def _make_test_function_exact(self):
if getattr(self, "_shard_test_function", None):
return self._shard_test_function
def step_function(batch):
def run_step(data):
# TODO(b/272050910): Use sample_weight for weighted metrics.
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(
data
)
y_pred = self(x, training=False)
return x, y, y_pred, sample_weight
if self._jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
outputs = self.distribute_strategy.run(run_step, args=(batch,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
def shard_test_function(dataset, total_shards, shard_idx):
# Copy loss and metric variables to the worker and work with them
# locally. This ensures each shard function is atomic: if a worker
# is preempted, the intermediate progress is discarded and that
# shard is retried. This in turn guarantees exactly-once visitation.
local_unweighted_metrics, local_weighted_metrics = [], []
with tf_utils.with_metric_local_vars_scope():
# TODO(jmullenbach): implement and use a clone for
# `MetricsContainer` and use its `update_state` method directly.
for metric in self.compiled_metrics.unweighted_metrics:
if metric is not None:
local_unweighted_metrics.append(
base_metric.clone_metric(metric)
)
for metric in self.compiled_metrics.weighted_metrics:
if metric is not None:
local_weighted_metrics.append(
base_metric.clone_metric(metric)
)
local_loss = compile_utils.LossesContainer.from_config(
self.compiled_loss.get_config()
)
dataset = input_ops.auto_shard_dataset(
dataset, total_shards, shard_idx
)
iterator = iter(dataset)
with distribute_utils.cache_variable_reads():
for batch in iterator:
x, y, y_pred, sample_weight = step_function(batch)
for weighted_metric in local_weighted_metrics:
weighted_metric.update_state(y, y_pred, sample_weight)
for unweighted_metric in local_unweighted_metrics:
unweighted_metric.update_state(y, y_pred)
local_loss(y, y_pred, sample_weight)
local_metrics = (
local_unweighted_metrics
+ local_weighted_metrics
+ local_loss.metrics
)
outputs = {metric.name: metric.weights for metric in local_metrics}
with tf.control_dependencies(_minimum_control_deps(outputs)):
self._test_counter.assign_add(1)
return outputs
if not self.run_eagerly:
shard_test_function = tf.function(
shard_test_function, reduce_retracing=True
)
self._shard_test_function = (
lambda *args: self._cluster_coordinator.schedule(
shard_test_function,
args=args,
)
)
return self._shard_test_function
def make_test_function(self, force=False):
"""Creates a function that executes one step of evaluation.
This method can be overridden to support custom evaluation logic.
This method is called by `Model.evaluate` and `Model.test_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.test_step`.
This function is cached the first time `Model.evaluate` or
`Model.test_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the test function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_test_batch_end`.
"""
if self.test_function is not None and not force:
return self.test_function
def step_function(model, iterator):
"""Runs a single evaluation step."""
def run_step(data):
outputs = model.test_step(data)
# Ensure counter is updated only if `test_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._test_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def test_function(iterator):
"""Runs a test execution with a single step."""
return step_function(self, iterator)
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
if self._cluster_coordinator:
self.test_function = (
lambda it: self._cluster_coordinator.schedule(
test_function, args=(it,)
)
)
else:
self.test_function = test_function
# If we're using a coordinator, use the value of
# self._steps_per_execution at the time the function is
# called/scheduled, and not when it is actually executed.
elif self._cluster_coordinator:
def test_function(iterator, steps_per_execution):
"""Runs a test execution with multiple steps."""
for _ in tf.range(steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
self.test_function = lambda it: self._cluster_coordinator.schedule(
test_function, args=(it, self._steps_per_execution.value())
)
else:
def test_function(iterator):
"""Runs a test execution with multiple steps."""
for _ in tf.range(self._steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
self.test_function = test_function
return self.test_function
@traceback_utils.filter_traceback
def evaluate(
self,
x=None,
y=None,
batch_size=None,
verbose="auto",
sample_weight=None,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
return_dict=False,
**kwargs,
):
"""Returns the loss value & metrics values for the model in test mode.
Computation is done in batches (see the `batch_size` arg.)
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A `tf.data` dataset. Should return a tuple
of either `(inputs, targets)` or
`(inputs, targets, sample_weights)`.
- A generator or `keras.utils.Sequence` returning `(inputs,
targets)` or `(inputs, targets, sample_weights)`.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given in the `Unpacking
behavior for iterator-like inputs` section of `Model.fit`.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s). It should be consistent with `x`
(you cannot have Numpy inputs and tensor targets, or inversely).
If `x` is a dataset, generator or `keras.utils.Sequence` instance,
`y` should not be specified (since targets will be obtained from
the iterator/dataset).
batch_size: Integer or `None`. Number of samples per batch of
computation. If unspecified, `batch_size` will default to 32. Do
not specify the `batch_size` if your data is in the form of a
dataset, generators, or `keras.utils.Sequence` instances (since
they generate batches).
verbose: `"auto"`, 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = single line.
`"auto"` becomes 1 for most cases, and to 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so `verbose=2` is
recommended when not running interactively (e.g. in a production
environment). Defaults to 'auto'.
sample_weight: Optional Numpy array of weights for the test samples,
used for weighting the loss function. You can either pass a flat
(1D) Numpy array with the same length as the input samples
(1:1 mapping between weights and samples), or in the case of
temporal data, you can pass a 2D array with shape `(samples,
sequence_length)`, to apply a different weight to every
timestep of every sample. This argument is not supported when
`x` is a dataset, instead pass sample weights as the third
element of `x`.
steps: Integer or `None`. Total number of steps (batches of samples)
before declaring the evaluation round finished. Ignored with the
default value of `None`. If x is a `tf.data` dataset and `steps`
is None, 'evaluate' will run until the dataset is exhausted. This
argument is not supported with array inputs.
callbacks: List of `keras.callbacks.Callback` instances. List of
callbacks to apply during evaluation. See
[callbacks](https://www.tensorflow.org/api_docs/python/tf/tf_keras/callbacks).
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the generator
queue. If unspecified, `max_queue_size` will default to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, `workers` will default to
1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
**kwargs: Unused at this time.
See the discussion of `Unpacking behavior for iterator-like inputs` for
`Model.fit`.
Returns:
Scalar test 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 scalar outputs.
Raises:
RuntimeError: If `model.evaluate` is wrapped in a `tf.function`.
"""
version_utils.disallow_legacy_graph("Model", "evaluate")
self._assert_compile_was_called()
self._check_call_args("evaluate")
self._check_sample_weight_warning(x, sample_weight)
_disallow_inside_tf_function("evaluate")
use_cached_eval_dataset = kwargs.pop("_use_cached_eval_dataset", False)
if kwargs:
raise TypeError(f"Invalid keyword arguments: {list(kwargs.keys())}")
if self.distribute_strategy._should_use_with_coordinator:
self._cluster_coordinator = (
tf.distribute.experimental.coordinator.ClusterCoordinator(
self.distribute_strategy
)
)
verbose = _get_verbosity(verbose, self.distribute_strategy)
if self._pss_evaluation_shards:
self._disallow_exact_eval_with_add_metrics()
with self.distribute_strategy.scope():
# Use cached evaluation data only when it's called in `Model.fit`
if (
use_cached_eval_dataset
and getattr(self, "_eval_data_handler", None) is not None
):
data_handler = self._eval_data_handler
else:
# Creates a `tf.data.Dataset` and handles batch and epoch
# iteration.
data_handler = data_adapter.get_data_handler(
x=x,
y=y,
sample_weight=sample_weight,
batch_size=batch_size,
steps_per_epoch=steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
pss_evaluation_shards=self._pss_evaluation_shards,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=1,
steps=data_handler.inferred_steps,
)
# Initialize to prevent errors if 0 epochs are evaluated.
logs = {}
test_function_runner = self._get_test_function_runner(callbacks)
self._test_counter.assign(0)
callbacks.on_test_begin()
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
for (
_,
dataset_or_iterator,
) in data_handler.enumerate_epochs(): # Single epoch.
self.reset_metrics()
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
with tf.profiler.experimental.Trace(
"test", step_num=step, _r=1
):
callbacks.on_test_batch_begin(step)
logs = test_function_runner.run_step(
dataset_or_iterator,
data_handler,
step,
self._pss_evaluation_shards,
)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
# Override with model metrics instead of last step logs
if self._pss_evaluation_shards:
logs = self._aggregate_exact_metrics(logs)
else:
logs = self._validate_and_get_metrics_result(logs)
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_test_end(logs=logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def _disallow_exact_eval_with_add_metrics(self):
metrics_from_add_metric = [
metric
for layer in self._flatten_layers()
for metric in layer._metrics
]
compiled_metrics = self.compiled_metrics.metrics
if any(
[
metric not in compiled_metrics
for metric in metrics_from_add_metric
]
):
raise ValueError(
"Detected that a metric was added to this model "
"via `Model.add_metric`. This is not currently "
"supported when using exact evaluation with "
"`tf.distribute.ParameterServerStrategy`."
)
def _infer_exact_eval_shards(self, pss_evaluation_shards):
if not self.distribute_strategy._should_use_with_coordinator:
return 0
if pss_evaluation_shards == "auto":
# TODO(b/264265138) evaluate and improve this heuristic
return self.distribute_strategy._num_workers * 5
return pss_evaluation_shards
def _get_test_function_runner(self, callbacks):
if (
self._pss_evaluation_shards
and self.distribute_strategy._should_use_with_coordinator
):
self.test_function = self._make_test_function_exact()
test_function_runner = _ExactTestFunction(
self.test_function, callbacks
)
else:
self.test_function = self.make_test_function()
test_function_runner = _TestFunction(self.test_function, callbacks)
return test_function_runner
def predict_step(self, data):
"""The logic for one inference step.
This method can be overridden to support custom inference logic.
This method is called by `Model.make_predict_function`.
This method should contain the mathematical logic for one step of
inference. This typically includes the forward pass.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_predict_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
The result of one inference step, typically the output of calling the
`Model` on data.
"""
x, _, _ = data_adapter.unpack_x_y_sample_weight(data)
return self(x, training=False)
def make_predict_function(self, force=False):
"""Creates a function that executes one step of inference.
This method can be overridden to support custom inference logic.
This method is called by `Model.predict` and `Model.predict_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.predict_step`.
This function is cached the first time `Model.predict` or
`Model.predict_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the predict function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return the outputs of the `Model`.
"""
if self.predict_function is not None and not force:
return self.predict_function
def step_function(model, iterator):
"""Runs a single evaluation step."""
def run_step(data):
outputs = model.predict_step(data)
# Ensure counter is updated only if `test_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._predict_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs, self.distribute_strategy, reduction="concat"
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def predict_function(iterator):
"""Runs an evaluation execution with a single step."""
return step_function(self, iterator)
else:
def predict_function(iterator):
"""Runs an evaluation execution with multiple steps."""
outputs = step_function(self, iterator)
for _ in tf.range(self._steps_per_execution - 1):
tf.autograph.experimental.set_loop_options(
shape_invariants=[
(
outputs,
tf.nest.map_structure(
lambda t: tf_utils.get_tensor_spec(
t, dynamic_batch=True
).shape,
outputs,
),
)
]
)
step_outputs = step_function(self, iterator)
outputs = tf.nest.map_structure(
lambda t1, t2: concat([t1, t2]), outputs, step_outputs
)
return outputs
if not self.run_eagerly:
predict_function = tf.function(
predict_function, reduce_retracing=True
)
self.predict_function = predict_function
return self.predict_function
@traceback_utils.filter_traceback
def predict(
self,
x,
batch_size=None,
verbose="auto",
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
):
"""Generates output predictions for the input samples.
Computation is done in batches. This method is designed for batch
processing of large numbers of inputs. It is not intended for use inside
of loops that iterate over your data and process small numbers of inputs
at a time.
For small numbers of inputs that fit in one batch,
directly use `__call__()` for faster execution, e.g.,
`model(x)`, or `model(x, training=False)` if you have layers such as
`tf.keras.layers.BatchNormalization` that behave differently during
inference. You may pair the individual model call with a `tf.function`
for additional performance inside your inner loop.
If you need access to numpy array values instead of tensors after your
model call, you can use `tensor.numpy()` to get the numpy array value of
an eager tensor.
Also, note the fact that test loss is not affected by
regularization layers like noise and dropout.
Note: See [this FAQ entry](
https://keras.io/getting_started/faq/#whats-the-difference-between-model-methods-predict-and-call)
for more details about the difference between `Model` methods
`predict()` and `__call__()`.
Args:
x: Input samples. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A `tf.data` dataset.
- A generator or `keras.utils.Sequence` instance.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given in the `Unpacking
behavior for iterator-like inputs` section of `Model.fit`.
batch_size: Integer or `None`.
Number of samples per batch.
If unspecified, `batch_size` will default to 32.
Do not specify the `batch_size` if your data is in the
form of dataset, generators, or `keras.utils.Sequence` instances
(since they generate batches).
verbose: `"auto"`, 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = single line.
`"auto"` becomes 1 for most cases, and to 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so `verbose=2` is
recommended when not running interactively (e.g. in a production
environment). Defaults to 'auto'.
steps: Total number of steps (batches of samples)
before declaring the prediction round finished.
Ignored with the default value of `None`. If x is a `tf.data`
dataset and `steps` is None, `predict()` will
run until the input dataset is exhausted.
callbacks: List of `keras.callbacks.Callback` instances.
List of callbacks to apply during prediction.
See [callbacks](
https://www.tensorflow.org/api_docs/python/tf/tf_keras/callbacks).
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the
generator queue. If unspecified, `max_queue_size` will default
to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, `workers` will default
to 1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
See the discussion of `Unpacking behavior for iterator-like inputs` for
`Model.fit`. Note that Model.predict uses the same interpretation rules
as `Model.fit` and `Model.evaluate`, so inputs must be unambiguous for
all three methods.
Returns:
Numpy array(s) of predictions.
Raises:
RuntimeError: If `model.predict` is wrapped in a `tf.function`.
ValueError: In case of mismatch between the provided
input data and the model's expectations,
or in case a stateful model receives a number of samples
that is not a multiple of the batch size.
"""
version_utils.disallow_legacy_graph("Model", "predict")
self._check_call_args("predict")
_disallow_inside_tf_function("predict")
# TODO(yashkatariya): Cache model on the coordinator for faster
# prediction. If running under PSS, then swap it with OneDeviceStrategy
# so that execution will run on the coordinator.
original_pss_strategy = None
if self.distribute_strategy._should_use_with_coordinator:
original_pss_strategy = self.distribute_strategy
self._distribution_strategy = None
# Cluster coordinator is set by `.fit()` and `.evaluate()` which is not
# needed in `.predict()` because all the predictions happen on the
# coordinator/locally.
if self._cluster_coordinator:
self._cluster_coordinator = None
verbose = _get_verbosity(verbose, self.distribute_strategy)
outputs = None
with self.distribute_strategy.scope():
# Creates a `tf.data.Dataset` and handles batch and epoch iteration.
dataset_types = (tf.compat.v1.data.Dataset, tf.data.Dataset)
if (
self._in_multi_worker_mode()
or _is_tpu_multi_host(self.distribute_strategy)
) and isinstance(x, dataset_types):
try:
options = tf.data.Options()
data_option = tf.data.experimental.AutoShardPolicy.DATA
options.experimental_distribute.auto_shard_policy = (
data_option
)
x = x.with_options(options)
except ValueError:
warnings.warn(
"Using Model.predict with MultiWorkerMirroredStrategy "
"or TPUStrategy and AutoShardPolicy.FILE might lead to "
"out-of-order result. Consider setting it to "
"AutoShardPolicy.DATA.",
stacklevel=2,
)
data_handler = data_adapter.get_data_handler(
x=x,
batch_size=batch_size,
steps_per_epoch=steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=1,
steps=data_handler.inferred_steps,
)
self.predict_function = self.make_predict_function()
self._predict_counter.assign(0)
callbacks.on_predict_begin()
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
batch_outputs = None
for _, iterator in data_handler.enumerate_epochs(): # Single epoch.
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
callbacks.on_predict_batch_begin(step)
tmp_batch_outputs = self.predict_function(iterator)
if data_handler.should_sync:
context.async_wait()
batch_outputs = (
tmp_batch_outputs # No error, now safe to assign.
)
if outputs is None:
outputs = tf.nest.map_structure(
lambda batch_output: [batch_output],
batch_outputs,
)
else:
tf.__internal__.nest.map_structure_up_to(
batch_outputs,
lambda output, batch_output: output.append(
batch_output
),
outputs,
batch_outputs,
)
end_step = step + data_handler.step_increment
callbacks.on_predict_batch_end(
end_step, {"outputs": batch_outputs}
)
if batch_outputs is None:
raise ValueError(
"Unexpected result of `predict_function` "
"(Empty batch_outputs). Please use "
"`Model.compile(..., run_eagerly=True)`, or "
"`tf.config.run_functions_eagerly(True)` for more "
"information of where went wrong, or file a "
"issue/bug to `tf.keras`."
)
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_predict_end()
all_outputs = tf.__internal__.nest.map_structure_up_to(
batch_outputs, potentially_ragged_concat, outputs
)
# If originally PSS strategy was used, then replace it back since
# predict is running under `OneDeviceStrategy` after the swap and once
# its done we need to replace it back to PSS again.
if original_pss_strategy is not None:
self._distribution_strategy = original_pss_strategy
return tf_utils.sync_to_numpy_or_python_type(all_outputs)
def reset_metrics(self):
"""Resets the state of all the metrics in the model.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> _ = model.fit(x, y, verbose=0)
>>> assert all(float(m.result()) for m in model.metrics)
>>> model.reset_metrics()
>>> assert all(float(m.result()) == 0 for m in model.metrics)
"""
for m in self.metrics:
m.reset_state()
def train_on_batch(
self,
x,
y=None,
sample_weight=None,
class_weight=None,
reset_metrics=True,
return_dict=False,
):
"""Runs a single gradient update on a single batch of data.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s).
sample_weight: Optional array of the same length as x, containing
weights to apply to the model's loss for each sample. In the case
of temporal data, you can pass a 2D array with shape (samples,
sequence_length), to apply a different weight to every timestep of
every sample.
class_weight: Optional dictionary mapping class indices (integers)
to a weight (float) to apply to the model's loss for the samples
from this class during training. This can be useful to tell the
model to "pay more attention" to samples from an under-represented
class. When `class_weight` is specified and targets have a rank of
2 or greater, either `y` must be one-hot encoded, or an explicit
final dimension of `1` must be included for sparse class labels.
reset_metrics: If `True`, the metrics returned will be only for this
batch. If `False`, the metrics will be statefully accumulated
across batches.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
Returns:
Scalar training 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 scalar outputs.
Raises:
RuntimeError: If `model.train_on_batch` is wrapped in a `tf.function`.
"""
self._assert_compile_was_called()
self._check_call_args("train_on_batch")
_disallow_inside_tf_function("train_on_batch")
if reset_metrics:
self.reset_metrics()
with self.distribute_strategy.scope(), training_utils.RespectCompiledTrainableState( # noqa: E501
self
):
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x, y, sample_weight, class_weight
)
self.train_function = self.make_train_function()
logs = self.train_function(iterator)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def test_on_batch(
self,
x,
y=None,
sample_weight=None,
reset_metrics=True,
return_dict=False,
):
"""Test the model on a single batch of samples.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays (in case the
model has multiple inputs).
- A TensorFlow tensor, or a list of tensors (in case the model has
multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s). It should be consistent with `x`
(you cannot have Numpy inputs and tensor targets, or inversely).
sample_weight: Optional array of the same length as x, containing
weights to apply to the model's loss for each sample. In the case
of temporal data, you can pass a 2D array with shape (samples,
sequence_length), to apply a different weight to every timestep of
every sample.
reset_metrics: If `True`, the metrics returned will be only for this
batch. If `False`, the metrics will be statefully accumulated
across batches.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
Returns:
Scalar test 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 scalar outputs.
Raises:
RuntimeError: If `model.test_on_batch` is wrapped in a
`tf.function`.
"""
self._assert_compile_was_called()
self._check_call_args("test_on_batch")
_disallow_inside_tf_function("test_on_batch")
if reset_metrics:
self.reset_metrics()
with self.distribute_strategy.scope():
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x, y, sample_weight
)
self.test_function = self.make_test_function()
logs = self.test_function(iterator)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def predict_on_batch(self, x):
"""Returns predictions for a single batch of samples.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays (in case the
model has multiple inputs).
- A TensorFlow tensor, or a list of tensors (in case the model has
multiple inputs).
Returns:
Numpy array(s) of predictions.
Raises:
RuntimeError: If `model.predict_on_batch` is wrapped in a
`tf.function`.
"""
self._check_call_args("predict_on_batch")
_disallow_inside_tf_function("predict_on_batch")
with self.distribute_strategy.scope():
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x
)
self.predict_function = self.make_predict_function()
outputs = self.predict_function(iterator)
return tf_utils.sync_to_numpy_or_python_type(outputs)
@doc_controls.do_not_generate_docs
def fit_generator(
self,
generator,
steps_per_epoch=None,
epochs=1,
verbose=1,
callbacks=None,
validation_data=None,
validation_steps=None,
validation_freq=1,
class_weight=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
shuffle=True,
initial_epoch=0,
):
"""Fits the model on data yielded batch-by-batch by a Python generator.
DEPRECATED:
`Model.fit` now supports generators, so there is no longer any need to
use this endpoint.
"""
warnings.warn(
"`Model.fit_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.fit`, which supports generators.",
stacklevel=2,
)
return self.fit(
generator,
steps_per_epoch=steps_per_epoch,
epochs=epochs,
verbose=verbose,
callbacks=callbacks,
validation_data=validation_data,
validation_steps=validation_steps,
validation_freq=validation_freq,
class_weight=class_weight,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
shuffle=shuffle,
initial_epoch=initial_epoch,
)
@doc_controls.do_not_generate_docs
def evaluate_generator(
self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0,
):
"""Evaluates the model on a data generator.
DEPRECATED:
`Model.evaluate` now supports generators, so there is no longer any
need to use this endpoint.
"""
warnings.warn(
"`Model.evaluate_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.evaluate`, which supports generators.",
stacklevel=2,
)
self._check_call_args("evaluate_generator")
return self.evaluate(
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks,
)
@doc_controls.do_not_generate_docs
def predict_generator(
self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0,
):
"""Generates predictions for the input samples from a data generator.
DEPRECATED:
`Model.predict` now supports generators, so there is no longer any
need to use this endpoint.
"""
warnings.warn(
"`Model.predict_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.predict`, which supports generators.",
stacklevel=2,
)
return self.predict(
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks,
)
######################################################################
# Functions below are not training related. They are for model weights
# tracking, save/load, serialization, etc.
######################################################################
@property
def trainable_weights(self):
self._assert_weights_created()
if not self._trainable:
return []
trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
trainable_variables += trackable_obj.trainable_variables
trainable_variables += self._trainable_weights
return self._dedup_weights(trainable_variables)
@property
def non_trainable_weights(self):
self._assert_weights_created()
non_trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
non_trainable_variables += trackable_obj.non_trainable_variables
if not self._trainable:
# Return order is all trainable vars, then all non-trainable vars.
trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
trainable_variables += trackable_obj.trainable_variables
non_trainable_variables = (
trainable_variables
+ self._trainable_weights
+ non_trainable_variables
+ self._non_trainable_weights
)
else:
non_trainable_variables = (
non_trainable_variables + self._non_trainable_weights
)
return self._dedup_weights(non_trainable_variables)
def get_weights(self):
"""Retrieves the weights of the model.
Returns:
A flat list of Numpy arrays.
"""
with self.distribute_strategy.scope():
return super().get_weights()
@traceback_utils.filter_traceback
def save(self, 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.models.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.models.save_model()`.
"""
saving_api.save_model(
self,
filepath=filepath,
overwrite=overwrite,
save_format=save_format,
**kwargs,
)
@traceback_utils.filter_traceback
def save_weights(
self, filepath, overwrite=True, save_format=None, options=None
):
"""Saves all layer weights.
Either saves in HDF5 or in TensorFlow format based on the `save_format`
argument.
When saving in HDF5 format, the weight file has:
- `layer_names` (attribute), a list of strings
(ordered names of model layers).
- For every layer, a `group` named `layer.name`
- For every such layer group, a group attribute `weight_names`,
a list of strings
(ordered names of weights tensor of the layer).
- For every weight in the layer, a dataset
storing the weight value, named after the weight tensor.
When saving in TensorFlow format, all objects referenced by the network
are saved in the same format as `tf.train.Checkpoint`, including any
`Layer` instances or `Optimizer` instances assigned to object
attributes. For networks constructed from inputs and outputs using
`tf.keras.Model(inputs, outputs)`, `Layer` instances used by the network
are tracked/saved automatically. For user-defined classes which inherit
from `tf.keras.Model`, `Layer` instances must be assigned to object
attributes, typically in the constructor. See the documentation of
`tf.train.Checkpoint` and `tf.keras.Model` for details.
While the formats are the same, do not mix `save_weights` and
`tf.train.Checkpoint`. Checkpoints saved by `Model.save_weights` should
be loaded using `Model.load_weights`. Checkpoints saved using
`tf.train.Checkpoint.save` should be restored using the corresponding
`tf.train.Checkpoint.restore`. Prefer `tf.train.Checkpoint` over
`save_weights` for training checkpoints.
The TensorFlow format matches objects and variables by starting at a
root object, `self` for `save_weights`, and greedily matching attribute
names. For `Model.save` this is the `Model`, and for `Checkpoint.save`
this is the `Checkpoint` even if the `Checkpoint` has a model attached.
This means saving a `tf.keras.Model` using `save_weights` and loading
into a `tf.train.Checkpoint` with a `Model` attached (or vice versa)
will not match the `Model`'s variables. See the
[guide to training checkpoints](
https://www.tensorflow.org/guide/checkpoint) for details on
the TensorFlow format.
Args:
filepath: String or PathLike, path to the file to save the weights
to. When saving in TensorFlow format, this is the prefix used
for checkpoint files (multiple files are generated). Note that
the '.h5' suffix causes weights to be saved in HDF5 format.
overwrite: Whether to silently overwrite any existing file at the
target location, or provide the user with a manual prompt.
save_format: Either 'tf' or 'h5'. A `filepath` ending in '.h5' or
'.keras' will default to HDF5 if `save_format` is `None`.
Otherwise, `None` becomes 'tf'. Defaults to `None`.
options: Optional `tf.train.CheckpointOptions` object that specifies
options for saving weights.
Raises:
ImportError: If `h5py` is not available when attempting to save in
HDF5 format.
"""
saving_api.save_weights(
self,
filepath=filepath,
overwrite=overwrite,
save_format=save_format,
options=options,
)
@traceback_utils.filter_traceback
def load_weights(
self, filepath, skip_mismatch=False, by_name=False, options=None
):
"""Loads all layer weights from a saved files.
The saved file could be a SavedModel file, a `.keras` file (v3 saving
format), or a file created via `model.save_weights()`.
By default, weights are loaded based on the network's
topology. This means the architecture should be the same as when the
weights were saved. Note that layers that don't have weights are not
taken into account in the topological ordering, so adding or removing
layers is fine as long as they don't have weights.
**Partial weight loading**
If you have modified your model, for instance by adding a new layer
(with weights) or by changing the shape of the weights of a layer,
you can choose to ignore errors and continue loading
by setting `skip_mismatch=True`. In this case any layer with
mismatching weights will be skipped. A warning will be displayed
for each skipped layer.
**Weight loading by name**
If your weights are saved as a `.h5` file created
via `model.save_weights()`, you can use the argument `by_name=True`.
In this case, weights are loaded into layers only if they share
the same name. This is useful for fine-tuning or transfer-learning
models where some of the layers have changed.
Note that only topological loading (`by_name=False`) is supported when
loading weights from the `.keras` v3 format or from the TensorFlow
SavedModel format.
Args:
filepath: String, path to the weights file to load. For weight files
in TensorFlow format, this is the file prefix (the same as was
passed to `save_weights()`). This can also be a path to a
SavedModel or a `.keras` file (v3 saving format) saved
via `model.save()`.
skip_mismatch: Boolean, whether to skip loading of layers where
there is a mismatch in the number of weights, or a mismatch in
the shape of the weights.
by_name: Boolean, whether to load weights by name or by topological
order. Only topological loading is supported for weight files in
the `.keras` v3 format or in the TensorFlow SavedModel format.
options: Optional `tf.train.CheckpointOptions` object that specifies
options for loading weights (only valid for a SavedModel file).
"""
return saving_api.load_weights(
self,
filepath=filepath,
by_name=by_name,
skip_mismatch=skip_mismatch,
options=options,
)
def _updated_config(self):
"""Util shared between different serialization methods.
Returns:
Model config with TF-Keras version information added.
"""
from tf_keras.src import __version__ as keras_version
config = self.get_config()
model_config = {
"class_name": self.__class__.__name__,
"config": config,
"keras_version": keras_version,
"backend": backend.backend(),
}
return model_config
@generic_utils.default
def get_config(self):
"""Returns the config of the `Model`.
Config is a Python dictionary (serializable) containing the
configuration of an object, which in this case is a `Model`. This allows
the `Model` to be be reinstantiated later (without its trained weights)
from this configuration.
Note that `get_config()` does not guarantee to return a fresh copy of
dict every time it is called. The callers should make a copy of the
returned dict if they want to modify it.
Developers of subclassed `Model` are advised to override this method,
and continue to update the dict from `super(MyModel, self).get_config()`
to provide the proper configuration of this `Model`. The default config
will return config dict for init parameters if they are basic types.
Raises `NotImplementedError` when in cases where a custom
`get_config()` implementation is required for the subclassed model.
Returns:
Python dictionary containing the configuration of this `Model`.
"""
# If sublcass doesn't implement `get_config()` parse from init args
# otherwise default to empty dict
if generic_utils.is_default(self.get_config):
try:
config = base_layer.Layer.get_config(self)
except NotImplementedError:
config = {}
logging.warning(
"Model's `__init__()` arguments contain non-serializable "
"objects. Please implement a `get_config()` method in the "
"subclassed Model for proper saving and loading. "
"Defaulting to empty config."
)
else:
config = {}
return config
@classmethod
def from_config(cls, config, custom_objects=None):
# `from_config` assumes `cls` is either `Functional` or a child class of
# `Functional`. In the case that `cls` is meant to behave like a child
# class of `Functional` but only inherits from the `Model` class, we
# have to call `cls(...)` instead of `Functional.from_config`.
from tf_keras.src.engine import functional
with serialization.SharedObjectLoadingScope():
functional_config_keys = [
"name",
"layers",
"input_layers",
"output_layers",
]
is_functional_config = all(
key in config for key in functional_config_keys
)
argspec = tf_inspect.getfullargspec(cls.__init__)
functional_init_args = tf_inspect.getfullargspec(
functional.Functional.__init__
).args[1:]
revivable_as_functional = (
cls in {functional.Functional, Model}
or argspec.args[1:] == functional_init_args
or (argspec.varargs == "args" and argspec.varkw == "kwargs")
)
if is_functional_config and revivable_as_functional:
# Revive Functional model
# (but not Functional subclasses with a custom __init__)
inputs, outputs, layers = functional.reconstruct_from_config(
config, custom_objects
)
model = cls(
inputs=inputs, outputs=outputs, name=config.get("name")
)
functional.connect_ancillary_layers(model, layers)
else:
# Either the model has a custom __init__, or the config
# does not contain all the information necessary to
# revive a Functional model. This happens when the user creates
# subclassed models where `get_config()` is returning
# insufficient information to be considered a Functional model.
# In this case, we fall back to provide all config into the
# constructor of the class.
try:
model = cls(**config)
except TypeError as e:
raise TypeError(
"Unable to revive model from config. When overriding "
"the `get_config()` method, make sure that the "
"returned config contains all items used as arguments "
f"in the constructor to {cls}, "
"which is the default behavior. "
"You can override this default behavior by defining a "
"`from_config(cls, config)` class method to specify "
"how to create an "
f"instance of {cls.__name__} from its config.\n\n"
f"Received config={config}\n\n"
f"Error encountered during deserialization: {e}"
)
return model
def to_json(self, **kwargs):
"""Returns a JSON string containing the network configuration.
To load a network from a JSON save file, use
`keras.models.model_from_json(json_string, custom_objects={})`.
Args:
**kwargs: Additional keyword arguments to be passed to
*`json.dumps()`.
Returns:
A JSON string.
"""
model_config = self._updated_config()
return json.dumps(
model_config, default=json_utils.get_json_type, **kwargs
)
def to_yaml(self, **kwargs):
"""Returns a yaml string containing the network configuration.
Note: Since TF 2.6, this method is no longer supported and will raise a
RuntimeError.
To load a network from a yaml save file, use
`keras.models.model_from_yaml(yaml_string, custom_objects={})`.
`custom_objects` should be a dictionary mapping
the names of custom losses / layers / etc to the corresponding
functions / classes.
Args:
**kwargs: Additional keyword arguments
to be passed to `yaml.dump()`.
Returns:
A YAML string.
Raises:
RuntimeError: announces that the method poses a security risk
"""
raise RuntimeError(
"Method `model.to_yaml()` has been removed due to security risk of "
"arbitrary code execution. Please use `model.to_json()` instead."
)
def reset_states(self):
for layer in self.layers:
if hasattr(layer, "reset_states") and getattr(
layer, "stateful", False
):
layer.reset_states()
@property
@doc_controls.do_not_generate_docs
def state_updates(self):
"""Deprecated, do NOT use!
Returns the `updates` from all layers that are stateful.
This is useful for separating training updates and
state updates, e.g. when we need to update a layer's internal state
during prediction.
Returns:
A list of update ops.
"""
warnings.warn(
"`Model.state_updates` will be removed in a future version. "
"This property should not be used in TensorFlow 2.0, "
"as `updates` are applied automatically.",
stacklevel=2,
)
state_updates = []
for layer in self.layers:
if getattr(layer, "stateful", False):
if hasattr(layer, "updates"):
state_updates += layer.updates
return state_updates
@property
def weights(self):
"""Returns the list of all layer variables/weights.
Note: This will not track the weights of nested `tf.Modules` that are
not themselves TF-Keras layers.
Returns:
A list of variables.
"""
return self._dedup_weights(self._undeduplicated_weights)
@property
def _undeduplicated_weights(self):
"""Returns the undeduplicated list of all layer variables/weights."""
self._assert_weights_created()
weights = []
for layer in self._self_tracked_trackables:
weights += layer.variables
weights += self._trainable_weights + self._non_trainable_weights
return weights
def summary(
self,
line_length=None,
positions=None,
print_fn=None,
expand_nested=False,
show_trainable=False,
layer_range=None,
):
"""Prints a string summary of the network.
Args:
line_length: Total length of printed lines
(e.g. set this to adapt the display to different
terminal window sizes).
positions: Relative or absolute positions of log elements
in each line. If not provided, becomes
`[0.3, 0.6, 0.70, 1.]`. Defaults to `None`.
print_fn: Print function to use. By default, prints to `stdout`.
If `stdout` doesn't work in your environment, change to `print`.
It will be called on each line of the summary.
You can set it to a custom function
in order to capture the string summary.
expand_nested: Whether to expand the nested models.
Defaults to `False`.
show_trainable: Whether to show if a layer is trainable.
Defaults to `False`.
layer_range: a list or tuple of 2 strings,
which is the starting layer name and ending layer name
(both inclusive) indicating the range of layers to be printed
in summary. It also accepts regex patterns instead of exact
name. In such case, start predicate will be the first element
it matches to `layer_range[0]` and the end predicate will be
the last element it matches to `layer_range[1]`.
By default `None` which considers all layers of model.
Raises:
ValueError: if `summary()` is called before the model is built.
"""
if not self.built:
raise ValueError(
"This model has not yet been built. "
"Build the model first by calling `build()` or by calling "
"the model on a batch of data."
)
layer_utils.print_summary(
self,
line_length=line_length,
positions=positions,
print_fn=print_fn,
expand_nested=expand_nested,
show_trainable=show_trainable,
layer_range=layer_range,
)
@property
def layers(self):
return list(self._flatten_layers(include_self=False, recursive=False))
@layers.setter
def layers(self, _):
raise AttributeError(
"`Model.layers` attribute is reserved and should not be used. "
"Please use another name."
)
def get_layer(self, name=None, index=None):
"""Retrieves a layer based on either its name (unique) or index.
If `name` and `index` are both provided, `index` will take precedence.
Indices are based on order of horizontal graph traversal (bottom-up).
Args:
name: String, name of layer.
index: Integer, index of layer.
Returns:
A layer instance.
"""
# TODO(fchollet): We could build a dictionary based on layer names
# since they are constant, but we have not done that yet.
if index is not None and name is not None:
raise ValueError(
"Provide only a layer name or a layer index. Received: "
f"index={index}, name={name}."
)
if index is not None:
if len(self.layers) <= index:
raise ValueError(
f"Was asked to retrieve layer at index {index}"
f" but model only has {len(self.layers)}"
" layers."
)
else:
return self.layers[index]
if name is not None:
for layer in self.layers:
if layer.name == name:
return layer
raise ValueError(
f"No such layer: {name}. Existing layers are: "
f"{list(layer.name for layer in self.layers)}."
)
raise ValueError(
"Provide either a layer name or layer index at `get_layer`."
)
def get_weight_paths(self):
"""Retrieve all the variables and their paths for the model.
The variable path (string) is a stable key to identify a `tf.Variable`
instance owned by the model. It can be used to specify variable-specific
configurations (e.g. DTensor, quantization) from a global view.
This method returns a dict with weight object paths as keys
and the corresponding `tf.Variable` instances as values.
Note that if the model is a subclassed model and the weights haven't
been initialized, an empty dict will be returned.
Returns:
A dict where keys are variable paths and values are `tf.Variable`
instances.
Example:
```python
class SubclassModel(tf.keras.Model):
def __init__(self, name=None):
super().__init__(name=name)
self.d1 = tf.keras.layers.Dense(10)
self.d2 = tf.keras.layers.Dense(20)
def call(self, inputs):
x = self.d1(inputs)
return self.d2(x)
model = SubclassModel()
model(tf.zeros((10, 10)))
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': model.d1.kernel,
# 'd1.bias': model.d1.bias,
# 'd2.kernel': model.d2.kernel,
# 'd2.bias': model.d2.bias,
# }
# Functional model
inputs = tf.keras.Input((10,), batch_size=10)
x = tf.keras.layers.Dense(20, name='d1')(inputs)
output = tf.keras.layers.Dense(30, name='d2')(x)
model = tf.keras.Model(inputs, output)
d1 = model.layers[1]
d2 = model.layers[2]
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': d1.kernel,
# 'd1.bias': d1.bias,
# 'd2.kernel': d2.kernel,
# 'd2.bias': d2.bias,
# }
```
"""
result = {}
(
descendants,
object_paths_dict,
) = tf.__internal__.tracking.ObjectGraphView(
self
).breadth_first_traversal()
for descendant in descendants:
if isinstance(descendant, tf.Variable):
trackable_references = object_paths_dict[descendant]
object_path = ".".join([t.name for t in trackable_references])
result[object_path] = descendant
return result
def get_compile_config(self):
"""Returns a serialized config with information for compiling the model.
This method returns a config dictionary containing all the information
(optimizer, loss, metrics, etc.) with which the model was compiled.
Returns:
A dict containing information for compiling the model.
"""
if self._is_compiled and hasattr(self, "_compile_config"):
return self._compile_config.serialize()
def compile_from_config(self, config):
"""Compiles the model with the information given in config.
This method uses the information in the config (optimizer, loss,
metrics, etc.) to compile the model.
Args:
config: Dict containing information for compiling the model.
"""
has_overridden_compile = self.__class__.compile != Model.compile
if has_overridden_compile:
logging.warning(
"`compile()` was not called as part of model loading "
"because the model's `compile()` method is custom. "
"All subclassed Models that have `compile()` "
"overridden should also override "
"`get_compile_config()` and `compile_from_config(config)`. "
"Alternatively, you can "
"call `compile()` manually after loading."
)
return
config = saving_lib.deserialize_keras_object(config)
self.compile(**config)
if (
hasattr(self, "optimizer")
# Exempt legacy optimizers.
and isinstance(self.optimizer, optimizer.Optimizer)
and self.built
):
# Create optimizer variables.
self.optimizer.build(self.trainable_variables)
def export(self, filepath):
"""Create a SavedModel artifact for inference (e.g. via TF-Serving).
This method lets you export a model to a lightweight SavedModel artifact
that contains the model's forward pass only (its `call()` method)
and can be served via e.g. TF-Serving. The forward pass is registered
under the name `serve()` (see example below).
The original code of the model (including any custom layers you may
have used) is *no longer* necessary to reload the artifact -- it is
entirely standalone.
Args:
filepath: `str` or `pathlib.Path` object. Path where to save
the artifact.
Example:
```python
# Create the artifact
model.export("path/to/location")
# Later, in a different process / environment...
reloaded_artifact = tf.saved_model.load("path/to/location")
predictions = reloaded_artifact.serve(input_data)
```
If you would like to customize your serving endpoints, you can
use the lower-level `keras.export.ExportArchive` class. The `export()`
method relies on `ExportArchive` internally.
"""
from tf_keras.src.export import export_lib
export_lib.export_model(self, filepath)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _set_save_spec(self, inputs, args=None, kwargs=None):
"""Defines the save spec so that serialization can trace `call()`.
The TensorSpecs of the call function `inputs`, `args`, and `kwargs` are
saved into a tuple of `([inputs] + args, kwargs)`. The input
`TensorSpec` names are updated to match the built `input_names`.
The specs can be retrieved with the `save_spec` property.
Args:
inputs: possibly nested inputs passed into the call function.
args: a list of positional arguments passed into call.
kwargs: a dictionary of keyword arguments passed into call.
"""
if self._saved_model_inputs_spec is not None:
return # Already set.
args = args or []
kwargs = kwargs or {}
input_names = self.input_names
if not input_names:
input_names = compile_utils.create_pseudo_input_names(inputs)
flat_inputs = tf.nest.flatten(inputs)
inputs_spec = []
for name, tensor in zip(input_names, flat_inputs):
inputs_spec.append(
tf_utils.get_tensor_spec(tensor, dynamic_batch=False, name=name)
)
inputs_spec = tf.nest.pack_sequence_as(inputs, inputs_spec)
super()._set_save_spec(inputs_spec, args, kwargs)
# Store the input shapes
if (
self.__class__.__name__ == "Sequential"
and self._build_input_shape is None
):
self._build_input_shape = tf.nest.map_structure(
lambda x: None if x is None else x.shape, inputs_spec
)
def save_spec(self, dynamic_batch=True):
"""Returns the `tf.TensorSpec` of call args as a tuple `(args, kwargs)`.
This value is automatically defined after calling the model for the
first time. Afterwards, you can use it when exporting the model for
serving:
```python
model = tf.keras.Model(...)
@tf.function
def serve(*args, **kwargs):
outputs = model(*args, **kwargs)
# Apply postprocessing steps, or add additional outputs.
...
return outputs
# arg_specs is `[tf.TensorSpec(...), ...]`. kwarg_specs, in this
# example, is an empty dict since functional models do not use keyword
# arguments.
arg_specs, kwarg_specs = model.save_spec()
model.save(path, signatures={
'serving_default': serve.get_concrete_function(*arg_specs,
**kwarg_specs)
})
```
Args:
dynamic_batch: Whether to set the batch sizes of all the returned
`tf.TensorSpec` to `None`. (Note that when defining functional or
Sequential models with `tf.keras.Input([...], batch_size=X)`, the
batch size will always be preserved). Defaults to `True`.
Returns:
If the model inputs are defined, returns a tuple `(args, kwargs)`. All
elements in `args` and `kwargs` are `tf.TensorSpec`.
If the model inputs are not defined, returns `None`.
The model inputs are automatically set when calling the model,
`model.fit`, `model.evaluate` or `model.predict`.
"""
return self._get_save_spec(dynamic_batch, inputs_only=False)
def _assert_weights_created(self):
"""Asserts that all the weights for the model have been created.
For a non-dynamic model, the weights must already be created after the
layer has been called. For a dynamic model, the exact list of weights
can never be known for certain since it may change at any time during
execution.
We run this check right before accessing weights or getting the Numpy
value for the current weights. Otherwise, if the layer has never been
called, the user would just get an empty list, which is misleading.
Raises:
ValueError: if the weights of the network have not yet been created.
"""
if self.dynamic:
return
if (
"build" in self.__class__.__dict__
and self.__class__ != Model
and not self.built
):
# For any model that has customized build() method but hasn't been
# invoked yet, this will cover both sequential and subclass model.
# Also make sure to exclude Model class itself which has build()
# defined.
raise ValueError(
f"Weights for model '{self.name}' have not yet been "
"created. "
"Weights are created when the model is first called on "
"inputs or `build()` is called with an `input_shape`."
)
def _check_call_args(self, method_name):
"""Check that `call()` has only one positional arg."""
# Always allow first arg, regardless of arg name.
fullargspec = self._call_spec.full_argspec
if fullargspec.defaults:
positional_args = fullargspec.args[: -len(fullargspec.defaults)]
else:
positional_args = fullargspec.args
if "training" in positional_args:
positional_args.remove("training")
# self and first arg can be positional.
if len(positional_args) > 2:
extra_args = positional_args[2:]
raise ValueError(
f"Models passed to `{method_name}` can only have `training` "
"and the first argument in `call()` as positional arguments, "
f"found: {extra_args}."
)
def _validate_compile(self, optimizer, metrics, **kwargs):
"""Performs validation checks for the default `compile()`."""
if any(
isinstance(opt, optimizer_v1.Optimizer)
for opt in tf.nest.flatten(optimizer)
):
raise ValueError(
f"`tf.compat.v1.keras` Optimizer ({optimizer}) is "
"not supported when eager execution is enabled. Use a "
"`tf.keras` Optimizer instead, or disable eager "
"execution."
)
kwargs.pop("cloning", None) # Legacy DistStrat argument, never used.
kwargs.pop("experimental_run_tf_function", None) # Always `True`.
distribute_arg = kwargs.pop("distribute", None)
if distribute_arg is not None:
raise ValueError(
"`distribute` argument in compile is not available in TF 2.0. "
"Please create the model under the `strategy.scope()`. "
f"Received: {distribute_arg}."
)
target_tensor_arg = kwargs.pop("target_tensors", None)
if target_tensor_arg is not None:
raise ValueError(
"`target_tensors` argument is not supported when executing "
f"eagerly. Received: {target_tensor_arg}."
)
invalid_kwargs = set(kwargs) - {"sample_weight_mode"}
if invalid_kwargs:
raise TypeError(
"Invalid keyword argument(s) in `compile()`: "
f"{(invalid_kwargs,)}. Valid keyword arguments include "
'"cloning", "experimental_run_tf_function", "distribute",'
' "target_tensors", or "sample_weight_mode".'
)
# Model must be created and compiled with the same DistStrat.
if self.built and tf.distribute.has_strategy():
strategy = tf.distribute.get_strategy()
for v in self.variables:
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Variable ({v}) was not created in the distribution "
f"strategy scope of ({strategy}). It is most likely "
"because some layers, model, or optimizer was being "
"created outside the distribution strategy scope. Try "
"to make sure your code looks similar "
"to the following.\nwith strategy.scope():\n"
" model=_create_model()\n"
" model.compile(...)"
)
# Model metrics must be created in the same distribution strategy scope
# as the model.
strategy = self.distribute_strategy
for metric in tf.nest.flatten(metrics):
for v in getattr(metric, "variables", []):
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Metric ({metric}) passed to `model.compile` was "
"created inside a different distribution strategy "
"scope than the model. All metrics must be created "
"in the same distribution strategy "
f"scope as the model (in this case {strategy}). "
"If you pass in a string identifier for a metric to "
"compile, the metric will automatically be created "
"in the correct distribution strategy scope."
)
# Model metrics must be created in the same distribution strategy scope
# as the model.
for opt in tf.nest.flatten(optimizer):
for v in getattr(opt, "_weights", []):
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Optimizer ({optimizer}) passed to `model.compile` "
"was created inside a different distribution strategy "
"scope than the model. All optimizers must be created "
"in the same distribution strategy scope as the model "
f"(in this case {strategy}). If you pass in a string "
"identifier for an optimizer to compile, the optimizer "
"will automatically be created in the correct "
"distribution strategy scope."
)
def _maybe_load_initial_counters_from_ckpt(
self, steps_per_epoch, initial_epoch
):
"""Maybe load initial epoch from ckpt, considering worker recovery.
Refer to tensorflow/python/tf_keras/distribute/worker_training_state.py
for more information.
Args:
steps_per_epoch: The number of step per epoch.
initial_epoch: The original initial_epoch user passes in `fit()`.
mode: The mode for running `model.fit()`.
Returns:
If the training is recovering from previous failure under multi-worker
training setting, return the (epoch, step) the training is supposed to
continue at. Otherwise, return the `initial_epoch, initial_step` the
user passes in.
"""
initial_step = 0
if self._training_state is not None:
return self._training_state.maybe_load_initial_counters_from_ckpt(
steps_per_epoch, initial_epoch, mode=ModeKeys.TRAIN
)
return (initial_epoch, initial_step)
def _assert_compile_was_called(self):
# Checks whether `compile` has been called. If it has been called,
# then the optimizer is set. This is different from whether the
# model is compiled
# (i.e. whether the model is built and its inputs/outputs are set).
if not self._is_compiled:
raise RuntimeError(
"You must compile your model before "
"training/testing. "
"Use `model.compile(optimizer, loss)`."
)
def _check_sample_weight_warning(self, x, sample_weight):
# Datasets can include sample weight, by returning a tuple with the
# structure of `(x, y, sample_weight)`.
sample_weight_present = sample_weight is not None or (
isinstance(x, tf.data.Dataset)
and isinstance(x.element_spec, tuple)
and len(x.element_spec) == 3
)
if (
sample_weight_present
and self.compiled_metrics._user_weighted_metrics is None
):
logging.warning(
"`evaluate()` received a value for `sample_weight`, but "
"`weighted_metrics` were not provided. Did you mean to pass "
"metrics to `weighted_metrics` in `compile()`? If this is "
"intentional you can pass `weighted_metrics=[]` to `compile()` "
"in order to silence this warning."
)
def _set_inputs(self, inputs, outputs=None, training=None):
"""This method is for compat with Modelv1. Only inputs are needed
here."""
self._set_save_spec(inputs)
@property
def _trackable_saved_model_saver(self):
return model_serialization.ModelSavedModelSaver(self)
def _trackable_children(self, save_type="checkpoint", **kwargs):
if save_type == "savedmodel":
# SavedModel needs to ignore the execution functions.
train_function = self.train_function
test_function = self.test_function
predict_function = self.predict_function
train_tf_function = self.train_tf_function
self.train_function = None
self.test_function = None
self.predict_function = None
self.train_tf_function = None
children = super()._trackable_children(save_type, **kwargs)
if save_type == "savedmodel":
self.train_function = train_function
self.test_function = test_function
self.predict_function = predict_function
self.train_tf_function = train_tf_function
return children
def _should_eval(self, epoch, validation_freq):
epoch = epoch + 1 # one-index the user-facing epoch.
if isinstance(validation_freq, int):
return epoch % validation_freq == 0
elif isinstance(validation_freq, list):
return epoch in validation_freq
else:
raise ValueError(
"Expected `validation_freq` to be a list or int. "
f"Received: validation_freq={validation_freq} of the "
f"type {type(validation_freq)}."
)
######################################################################
# Functions below exist only as v1 / v2 compatibility shims.
######################################################################
def _get_compile_args(self, user_metrics=True):
"""Used for saving or cloning a Model.
Args:
user_metrics: Whether to return user-supplied metrics or `Metric`
objects. If True, returns the user-supplied metrics.
Defaults to `True`.
Returns:
Dictionary of arguments that were used when compiling the model.
"""
self._assert_compile_was_called()
saved_metrics = self.compiled_metrics._user_metrics
saved_weighted_metrics = self.compiled_metrics._user_weighted_metrics
if not user_metrics:
if saved_metrics is not None:
saved_metrics = self.compiled_metrics._metrics
if saved_weighted_metrics is not None:
saved_weighted_metrics = self.compiled_metrics._weighted_metrics
compile_args = {
"optimizer": self.optimizer,
"loss": self.compiled_loss._user_losses,
"metrics": saved_metrics,
"weighted_metrics": saved_weighted_metrics,
"loss_weights": self.compiled_loss._user_loss_weights,
}
return compile_args
def _get_callback_model(self):
return self
def _in_multi_worker_mode(self):
return self.distribute_strategy.extended._in_multi_worker_mode()
@property
def _compile_was_called(self):
return self._is_compiled
| (*args, **kwargs) |
724,900 | tf_keras.src.engine.training | __call__ | # 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.
# ==============================================================================
"""Training-related part of the TF-Keras engine."""
import copy
import itertools
import json
import warnings
import weakref
import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow.python.distribute import distribute_utils
from tensorflow.python.distribute import input_ops
from tensorflow.python.eager import context
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util.tf_export import keras_export
from tensorflow.tools.docs import doc_controls
from tf_keras.src import backend
from tf_keras.src import callbacks as callbacks_module
from tf_keras.src import optimizers
from tf_keras.src.dtensor import dtensor_api
from tf_keras.src.dtensor import layout_map as layout_map_lib
from tf_keras.src.engine import base_layer
from tf_keras.src.engine import base_layer_utils
from tf_keras.src.engine import compile_utils
from tf_keras.src.engine import data_adapter
from tf_keras.src.engine import input_layer as input_layer_module
from tf_keras.src.engine import training_utils
from tf_keras.src.metrics import base_metric
from tf_keras.src.mixed_precision import loss_scale_optimizer as lso
from tf_keras.src.optimizers import optimizer
from tf_keras.src.optimizers import optimizer_v1
from tf_keras.src.saving import pickle_utils
from tf_keras.src.saving import saving_api
from tf_keras.src.saving import saving_lib
from tf_keras.src.saving import serialization_lib
from tf_keras.src.saving.legacy import serialization
from tf_keras.src.saving.legacy.saved_model import json_utils
from tf_keras.src.saving.legacy.saved_model import model_serialization
from tf_keras.src.utils import generic_utils
from tf_keras.src.utils import io_utils
from tf_keras.src.utils import layer_utils
from tf_keras.src.utils import steps_per_execution_tuning
from tf_keras.src.utils import tf_inspect
from tf_keras.src.utils import tf_utils
from tf_keras.src.utils import traceback_utils
from tf_keras.src.utils import version_utils
from tf_keras.src.utils.mode_keys import ModeKeys
try:
import h5py
except ImportError:
h5py = None
@keras_export("keras.Model", "keras.models.Model")
class Model(base_layer.Layer, version_utils.ModelVersionSelector):
"""A model grouping layers into an object with training/inference features.
Args:
inputs: The input(s) of the model: a `keras.Input` object or a
combination of `keras.Input` objects in a dict, list or tuple.
outputs: The output(s) of the model: a tensor that originated from
`keras.Input` objects or a combination of such tensors in a dict,
list or tuple. See Functional API example below.
name: String, the name of the model.
There are two ways to instantiate a `Model`:
1 - With the "Functional API", where you start from `Input`,
you chain layer calls to specify the model's forward pass,
and finally you create your model from inputs and outputs:
```python
import tensorflow as tf
inputs = tf.keras.Input(shape=(3,))
x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
```
Note: Only dicts, lists, and tuples of input tensors are supported. Nested
inputs are not supported (e.g. lists of list or dicts of dict).
A new Functional API model can also be created by using the
intermediate tensors. This enables you to quickly extract sub-components
of the model.
Example:
```python
inputs = keras.Input(shape=(None, None, 3))
processed = keras.layers.RandomCrop(width=32, height=32)(inputs)
conv = keras.layers.Conv2D(filters=2, kernel_size=3)(processed)
pooling = keras.layers.GlobalAveragePooling2D()(conv)
feature = keras.layers.Dense(10)(pooling)
full_model = keras.Model(inputs, feature)
backbone = keras.Model(processed, conv)
activations = keras.Model(conv, feature)
```
Note that the `backbone` and `activations` models are not
created with `keras.Input` objects, but with the tensors that are originated
from `keras.Input` objects. Under the hood, the layers and weights will
be shared across these models, so that user can train the `full_model`, and
use `backbone` or `activations` to do feature extraction.
The inputs and outputs of the model can be nested structures of tensors as
well, and the created models are standard Functional API models that support
all the existing APIs.
2 - By subclassing the `Model` class: in that case, you should define your
layers in `__init__()` and you should implement the model's forward pass
in `call()`.
```python
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
def call(self, inputs):
x = self.dense1(inputs)
return self.dense2(x)
model = MyModel()
```
If you subclass `Model`, you can optionally have
a `training` argument (boolean) in `call()`, which you can use to specify
a different behavior in training and inference:
```python
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
self.dropout = tf.keras.layers.Dropout(0.5)
def call(self, inputs, training=False):
x = self.dense1(inputs)
if training:
x = self.dropout(x, training=training)
return self.dense2(x)
model = MyModel()
```
Once the model is created, you can config the model with losses and metrics
with `model.compile()`, train the model with `model.fit()`, or use the model
to do prediction with `model.predict()`.
"""
_TF_MODULE_IGNORED_PROPERTIES = frozenset(
itertools.chain(
(
"_train_counter",
"_test_counter",
"_predict_counter",
"_steps_per_execution",
"_compiled_trainable_state",
),
base_layer.Layer._TF_MODULE_IGNORED_PROPERTIES,
)
)
_SCALAR_UPRANKING_ON = False
def __new__(cls, *args, **kwargs):
# Signature detection
if is_functional_model_init_params(args, kwargs) and cls == Model:
# Functional model
from tf_keras.src.engine import functional
return functional.Functional(skip_init=True, *args, **kwargs)
else:
return super(Model, cls).__new__(cls, *args, **kwargs)
@tf.__internal__.tracking.no_automatic_dependency_tracking
@traceback_utils.filter_traceback
def __init__(self, *args, **kwargs):
self._is_model_for_instrumentation = True
# Special case for Subclassed Functional Model, which we couldn't detect
# when __new__ is called. We only realize it is a functional model when
# it calls super.__init__ with input and output tensor.
from tf_keras.src.engine import functional
if is_functional_model_init_params(args, kwargs) and not isinstance(
self, functional.Functional
):
# Filter the kwargs for multiple inheritance.
supported_kwargs = [
"inputs",
"outputs",
"name",
"trainable",
"skip_init",
]
model_kwargs = {
k: kwargs[k] for k in kwargs if k in supported_kwargs
}
other_kwargs = {
k: kwargs[k] for k in kwargs if k not in supported_kwargs
}
inject_functional_model_class(self.__class__)
functional.Functional.__init__(self, *args, **model_kwargs)
# In case there is any multiple inheritance here, we need to call
# the __init__ for any class that appears after the Functional
# class.
clz_to_init = []
found_functional_class = False
for clz in self.__class__.__bases__:
if issubclass(clz, functional.Functional):
found_functional_class = True
continue
if found_functional_class:
clz_to_init.append(clz)
if clz_to_init:
for clz in clz_to_init:
clz.__init__(self, *args, **other_kwargs)
elif other_kwargs:
# In case there are unused kwargs, we should raise an error to
# user, in case they have a typo in the param name.
raise TypeError(
"The following keyword arguments passed to `Model` aren't "
"supported: {}.".format(other_kwargs)
)
return
# The following are implemented as property functions:
# self.trainable_weights
# self.non_trainable_weights
# `inputs` / `outputs` will only appear in kwargs if either are
# misspelled.
generic_utils.validate_kwargs(
kwargs,
{
"trainable",
"dtype",
"dynamic",
"name",
"autocast",
"inputs",
"outputs",
},
)
super().__init__(**kwargs)
# By default, Model is a subclass model, which is not in graph network.
self._is_graph_network = False
self.inputs = None
self.outputs = None
self.input_names = None
self.output_names = None
# stop_training is used by callback to stop training when error happens
self.stop_training = False
self.history = None
# These objects are used in the default `Model.compile`. They are not
# guaranteed to be set after `Model.compile` is called, as users can
# override compile with custom logic.
self.compiled_loss = None
self.compiled_metrics = None
# This is True for Sequential networks and Functional networks.
self._compute_output_and_mask_jointly = False
# Don't reset compilation if already done. This may occur if calling
# `__init__` (or `_init_graph_network`) on an already-compiled model
# such as a Sequential model. Sequential models may need to rebuild
# themselves after compilation.
self._maybe_create_attribute("_is_compiled", False)
self._maybe_create_attribute("optimizer", None)
# Model must be created under scope of DistStrat it will be trained
# with.
if tf.distribute.has_strategy():
self._distribution_strategy = tf.distribute.get_strategy()
else:
self._distribution_strategy = None
self._distribute_reduction_method = None
self._cluster_coordinator = None
# Defaults to value of `tf.config.experimental_functions_run_eagerly`.
self._run_eagerly = None
# Initialize cache attrs.
self._reset_compile_cache()
# Fault-tolerance handler. Set in `ModelCheckpoint`.
self._training_state = None
self._saved_model_inputs_spec = None
self._saved_model_arg_spec = None
self._checkpoint = tf.train.Checkpoint(root=weakref.ref(self))
self._steps_per_execution = None
self._steps_per_execution_tuner = None
self._autotune_steps_per_execution = False
self._layout_map = layout_map_lib.get_current_layout_map()
self._init_batch_counters()
self._base_model_initialized = True
# `jit_compile` starts off with None as default and gets overwritten by
# the value specified in `Model.compile`, and this is effective for
# `fit`, `evaluate`, and `predict`.
self._jit_compile = None
def _create_counter_variable(self, init_value):
"""Helper function for counter variable creation.
For the DTensor use case with layout map, since the variable are not
tracked by model, they can't be visited by the layout map, and need to
be properly initialized as DVariable.
"""
# This function should be removed after we move to the strategy based
# implementation for DTensor.
if self._layout_map is None:
agg = tf.VariableAggregation.ONLY_FIRST_REPLICA
return tf.Variable(init_value, dtype="int64", aggregation=agg)
else:
layout = dtensor_api.Layout.replicated(
mesh=self._layout_map.get_default_mesh(), rank=0
)
return dtensor_api.DVariable(
init_value, dtype="int64", layout=layout
)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _init_batch_counters(self):
# Untracked Variables, used to keep track of mini-batches seen in `fit`,
# `evaluate`, and `predict`.
if not tf.inside_function():
# Creating variables inside tf.function is not allowed, hence
# these would otherwise prevent users from creating TF-Keras layers
# inside tf.function.
# These variables are not connected to outputs so they have no
# effect on graph generation anyway.
self._train_counter = self._create_counter_variable(0)
self._test_counter = self._create_counter_variable(0)
self._predict_counter = self._create_counter_variable(0)
def __setattr__(self, name, value):
if not getattr(self, "_self_setattr_tracking", True):
super().__setattr__(name, value)
return
if all(
isinstance(v, (base_layer.Layer, tf.Variable))
or base_layer_utils.has_weights(v)
for v in tf.nest.flatten(value)
):
try:
self._base_model_initialized
except AttributeError:
raise RuntimeError(
"It looks like you are subclassing `Model` and you "
"forgot to call `super().__init__()`."
" Always start with this line."
)
super().__setattr__(name, value)
def __reduce__(self):
if self.built:
return (
pickle_utils.deserialize_model_from_bytecode,
(pickle_utils.serialize_model_as_bytecode(self),),
)
else:
# SavedModel (and hence serialize_model_as_bytecode) only support
# built models, but if the model is not built,
# it may be possible to serialize as a plain Python object,
# as long as the constituent parts (layers, optimizers, losses,
# etc.) can be serialized as plain Python objects. Thus we call up
# the superclass hierarchy to get an implementation of __reduce__
# that can pickle this Model as a plain Python object.
return super().__reduce__()
def __deepcopy__(self, memo):
if self.built:
new = pickle_utils.deserialize_model_from_bytecode(
pickle_utils.serialize_model_as_bytecode(self)
)
memo[id(self)] = new
else:
# See comment in __reduce__ for explanation
deserializer, serialized, *rest = super().__reduce__()
new = deserializer(*serialized)
memo[id(self)] = new
if rest:
state = copy.deepcopy(rest[0], memo=memo)
new.__setstate__(state)
return new
def __copy__(self):
return self.__deepcopy__({})
@generic_utils.default
def build(self, input_shape):
"""Builds the model based on input shapes received.
This is to be used for subclassed models, which do not know at
instantiation time what their inputs look like.
This method only exists for users who want to call `model.build()` in a
standalone way (as a substitute for calling the model on real data to
build it). It will never be called by the framework (and thus it will
never throw unexpected errors in an unrelated workflow).
Args:
input_shape: Single tuple, `TensorShape` instance, or list/dict of
shapes, where shapes are tuples, integers, or `TensorShape`
instances.
Raises:
ValueError:
1. In case of invalid user-provided data (not of type tuple,
list, `TensorShape`, or dict).
2. If the model requires call arguments that are agnostic
to the input shapes (positional or keyword arg in call
signature).
3. If not all layers were properly built.
4. If float type inputs are not supported within the layers.
In each of these cases, the user should build their model by calling
it on real tensor data.
"""
if self._is_graph_network:
super().build(input_shape)
return
if input_shape is None:
raise ValueError(
"Input shape must be defined when calling `build()` on "
"a `Model` subclass."
)
valid_types = (tuple, list, tf.TensorShape, dict)
if not isinstance(input_shape, valid_types):
raise ValueError(
"Specified input shape is not one of the valid types. "
"Please specify a batch input shape of type tuple or "
"list of input shapes. User provided "
"input type: {}.".format(type(input_shape))
)
if input_shape and not self.inputs:
# We create placeholders for the `None`s in the shape and build the
# model in a Graph. Since tf.Variable is compatible with both eager
# execution and graph building, the variables created after building
# the model in a Graph are still valid when executing eagerly.
if tf.executing_eagerly():
graph = tf.__internal__.FuncGraph("build_graph")
else:
graph = backend.get_graph()
with graph.as_default():
if isinstance(input_shape, list) and all(
d is None or isinstance(d, int) for d in input_shape
):
input_shape = tuple(input_shape)
if isinstance(input_shape, list):
x = [
base_layer_utils.generate_placeholders_from_shape(shape)
for shape in input_shape
]
elif isinstance(input_shape, dict):
x = {
k: base_layer_utils.generate_placeholders_from_shape(
shape
)
for k, shape in input_shape.items()
}
else:
x = base_layer_utils.generate_placeholders_from_shape(
input_shape
)
kwargs = {}
call_signature = self._call_spec.full_argspec
call_args = call_signature.args
# Exclude `self`, `inputs`, and any argument with a default
# value.
if len(call_args) > 2:
if call_signature.defaults:
call_args = call_args[2 : -len(call_signature.defaults)]
else:
call_args = call_args[2:]
for arg in call_args:
if arg == "training":
# Case where `training` is a positional arg with no
# default.
kwargs["training"] = False
else:
# Has invalid call signature with unknown positional
# arguments.
raise ValueError(
"Currently, you cannot build your model if it "
"has positional or keyword arguments that are "
"not inputs to the model, but are required for "
"its `call()` method. Instead, in order to "
"instantiate and build your model, `call()` "
"your model on real tensor data with all "
"expected call arguments. The argument "
"for `call()` can be a single list/tuple that "
"contains multiple inputs."
)
elif len(call_args) < 2:
# Signature without `inputs`.
raise ValueError(
"You can only call `build()` on a model if its "
"`call()` method accepts an `inputs` argument."
)
try:
self.call(x, **kwargs)
except (tf.errors.InvalidArgumentError, TypeError) as e:
raise ValueError(
"You cannot build your model by calling `build` "
"if your layers do not support float type inputs. "
"Instead, in order to instantiate and build your "
"model, call your model on real tensor data (of "
"the correct dtype).\n\nThe actual error from "
f"`call` is: {e}."
)
super().build(input_shape)
@traceback_utils.filter_traceback
def __call__(self, *args, **kwargs):
if self._layout_map is not None and not self.built:
# Note that this method is only overridden for DTensor and layout
# injection purpose.
# Capture the inputs and create graph input as replacement for model
# to initialize its weights first.
copied_args = copy.copy(args)
copied_kwargs = copy.copy(kwargs)
(
inputs,
copied_args,
copied_kwargs,
) = self._call_spec.split_out_first_arg(copied_args, copied_kwargs)
def _convert_to_graph_inputs(x):
if isinstance(x, (tf.Tensor, np.ndarray, float, int)):
x = tf.convert_to_tensor(x)
return input_layer_module.Input(x.shape)
# TODO(scottzhu): maybe better handle mask and training flag.
inputs = tf.nest.map_structure(_convert_to_graph_inputs, inputs)
copied_args = tf.nest.map_structure(
_convert_to_graph_inputs, copied_args
)
copied_kwargs = tf.nest.map_structure(
_convert_to_graph_inputs, copied_kwargs
)
with layout_map_lib.layout_map_scope(self._layout_map):
# We ignore the result here.
super().__call__(inputs, *copied_args, **copied_kwargs)
layout_map_lib._map_subclass_model_variable(self, self._layout_map)
return super().__call__(*args, **kwargs)
@doc_controls.doc_in_current_and_subclasses
def call(self, inputs, training=None, mask=None):
"""Calls the model on new inputs and returns the outputs as tensors.
In this case `call()` just reapplies
all ops in the graph to the new inputs
(e.g. build a new computational graph from the provided inputs).
Note: This method should not be called directly. It is only meant to be
overridden when subclassing `tf.keras.Model`.
To call a model on an input, always use the `__call__()` method,
i.e. `model(inputs)`, which relies on the underlying `call()` method.
Args:
inputs: Input tensor, or dict/list/tuple of input tensors.
training: Boolean or boolean scalar tensor, indicating whether to
run the `Network` in training mode or inference mode.
mask: A mask or list of masks. A mask can be either a boolean tensor
or None (no mask). For more details, check the guide
[here](https://www.tensorflow.org/guide/keras/masking_and_padding).
Returns:
A tensor if there is a single output, or
a list of tensors if there are more than one outputs.
"""
raise NotImplementedError(
"Unimplemented `tf.keras.Model.call()`: if you "
"intend to create a `Model` with the Functional "
"API, please provide `inputs` and `outputs` "
"arguments. Otherwise, subclass `Model` with an "
"overridden `call()` method."
)
@traceback_utils.filter_traceback
def compile(
self,
optimizer="rmsprop",
loss=None,
metrics=None,
loss_weights=None,
weighted_metrics=None,
run_eagerly=None,
steps_per_execution=None,
jit_compile=None,
pss_evaluation_shards=0,
**kwargs,
):
"""Configures the model for training.
Example:
```python
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),
loss=tf.keras.losses.BinaryCrossentropy(),
metrics=[tf.keras.metrics.BinaryAccuracy(),
tf.keras.metrics.FalseNegatives()])
```
Args:
optimizer: String (name of optimizer) or optimizer instance. See
`tf.keras.optimizers`.
loss: Loss function. May be a string (name of loss function), or
a `tf.keras.losses.Loss` instance. See `tf.keras.losses`. A loss
function is any callable with the signature `loss = fn(y_true,
y_pred)`, where `y_true` are the ground truth values, and
`y_pred` are the model's predictions.
`y_true` should have shape
`(batch_size, d0, .. dN)` (except in the case of
sparse loss functions such as
sparse categorical crossentropy which expects integer arrays of
shape `(batch_size, d0, .. dN-1)`).
`y_pred` should have shape `(batch_size, d0, .. dN)`.
The loss function should return a float tensor.
If a custom `Loss` instance is
used and reduction is set to `None`, return value has shape
`(batch_size, d0, .. dN-1)` i.e. per-sample or per-timestep loss
values; otherwise, it is a scalar. If the model has multiple
outputs, you can use a different loss on each output by passing a
dictionary or a list of losses. The loss value that will be
minimized by the model will then be the sum of all individual
losses, unless `loss_weights` is specified.
metrics: List of metrics to be evaluated by the model during
training and testing. Each of this can be a string (name of a
built-in function), function or a `tf.keras.metrics.Metric`
instance. See `tf.keras.metrics`. Typically you will use
`metrics=['accuracy']`.
A function is any callable with the signature `result = fn(y_true,
y_pred)`. To specify different metrics for different outputs of a
multi-output model, you could also pass a dictionary, such as
`metrics={'output_a':'accuracy', 'output_b':['accuracy', 'mse']}`.
You can also pass a list to specify a metric or a list of metrics
for each output, such as
`metrics=[['accuracy'], ['accuracy', 'mse']]`
or `metrics=['accuracy', ['accuracy', 'mse']]`. When you pass the
strings 'accuracy' or 'acc', we convert this to one of
`tf.keras.metrics.BinaryAccuracy`,
`tf.keras.metrics.CategoricalAccuracy`,
`tf.keras.metrics.SparseCategoricalAccuracy` based on the shapes
of the targets and of the model output. We do a similar
conversion for the strings 'crossentropy' and 'ce' as well.
The metrics passed here are evaluated without sample weighting; if
you would like sample weighting to apply, you can specify your
metrics via the `weighted_metrics` argument instead.
loss_weights: Optional list or dictionary specifying scalar
coefficients (Python floats) to weight the loss contributions of
different model outputs. The loss value that will be minimized by
the model will then be the *weighted sum* of all individual
losses, weighted by the `loss_weights` coefficients. If a list,
it is expected to have a 1:1 mapping to the model's outputs. If a
dict, it is expected to map output names (strings) to scalar
coefficients.
weighted_metrics: List of metrics to be evaluated and weighted by
`sample_weight` or `class_weight` during training and testing.
run_eagerly: Bool. If `True`, this `Model`'s logic will not be
wrapped in a `tf.function`. Recommended to leave this as `None`
unless your `Model` cannot be run inside a `tf.function`.
`run_eagerly=True` is not supported when using
`tf.distribute.experimental.ParameterServerStrategy`. Defaults to
`False`.
steps_per_execution: Int or `'auto'`. The number of batches to
run during each `tf.function` call. If set to "auto", keras will
automatically tune `steps_per_execution` during runtime. Running
multiple batches inside a single `tf.function` call can greatly
improve performance on TPUs, when used with distributed strategies
such as `ParameterServerStrategy`, or with small models with a
large Python overhead. At most, one full epoch will be run each
execution. If a number larger than the size of the epoch is
passed, the execution will be truncated to the size of the epoch.
Note that if `steps_per_execution` is set to `N`,
`Callback.on_batch_begin` and `Callback.on_batch_end` methods will
only be called every `N` batches (i.e. before/after each
`tf.function` execution). Defaults to `1`.
jit_compile: If `True`, compile the model training step with XLA.
[XLA](https://www.tensorflow.org/xla) is an optimizing compiler
for machine learning.
`jit_compile` is not enabled for by default.
Note that `jit_compile=True`
may not necessarily work for all models.
For more information on supported operations please refer to the
[XLA documentation](https://www.tensorflow.org/xla).
Also refer to
[known XLA issues](https://www.tensorflow.org/xla/known_issues)
for more details.
pss_evaluation_shards: Integer or 'auto'. Used for
`tf.distribute.ParameterServerStrategy` training only. This arg
sets the number of shards to split the dataset into, to enable an
exact visitation guarantee for evaluation, meaning the model will
be applied to each dataset element exactly once, even if workers
fail. The dataset must be sharded to ensure separate workers do
not process the same data. The number of shards should be at least
the number of workers for good performance. A value of 'auto'
turns on exact evaluation and uses a heuristic for the number of
shards based on the number of workers. 0, meaning no
visitation guarantee is provided. NOTE: Custom implementations of
`Model.test_step` will be ignored when doing exact evaluation.
Defaults to `0`.
**kwargs: Arguments supported for backwards compatibility only.
"""
if jit_compile and not tf_utils.can_jit_compile(warn=True):
jit_compile = False
self._compile_config = serialization_lib.Config(
optimizer=optimizer,
loss=loss,
metrics=metrics,
loss_weights=loss_weights,
weighted_metrics=weighted_metrics,
run_eagerly=run_eagerly,
steps_per_execution=steps_per_execution,
jit_compile=jit_compile,
)
with self.distribute_strategy.scope():
if "experimental_steps_per_execution" in kwargs:
logging.warning(
"The argument `steps_per_execution` is no longer "
"experimental. Pass `steps_per_execution` instead of "
"`experimental_steps_per_execution`."
)
if not steps_per_execution:
steps_per_execution = kwargs.pop(
"experimental_steps_per_execution"
)
# When compiling from an already-serialized model, we do not want to
# reapply some processing steps (e.g. metric renaming for
# multi-output models, which have prefixes added for each
# corresponding output name).
from_serialized = kwargs.pop("from_serialized", False)
self._validate_compile(optimizer, metrics, **kwargs)
self._run_eagerly = run_eagerly
self.optimizer = self._get_optimizer(optimizer)
mesh = None
if self._layout_map is not None:
mesh = self._layout_map.get_default_mesh()
if isinstance(loss, compile_utils.LossesContainer):
self.compiled_loss = loss
else:
self.compiled_loss = compile_utils.LossesContainer(
loss,
loss_weights,
output_names=self.output_names,
mesh=mesh,
)
self.compiled_metrics = compile_utils.MetricsContainer(
metrics,
weighted_metrics,
output_names=self.output_names,
from_serialized=from_serialized,
mesh=mesh,
)
if steps_per_execution == "auto":
if self._steps_per_execution is None:
self._configure_steps_per_execution(1)
self._steps_per_execution_tuner = (
steps_per_execution_tuning.StepsPerExecutionTuner(
self.optimizer, self._steps_per_execution
)
)
self._autotune_steps_per_execution = True
else:
self._configure_steps_per_execution(steps_per_execution or 1)
self._pss_evaluation_shards = self._infer_exact_eval_shards(
pss_evaluation_shards
)
# Initializes attrs that are reset each time `compile` is called.
self._reset_compile_cache()
self._is_compiled = True
self.loss = loss or {}
if (self._run_eagerly or self.dynamic) and jit_compile:
raise ValueError(
"You cannot enable `run_eagerly` and `jit_compile` "
"at the same time."
)
else:
self._jit_compile = jit_compile
def _get_optimizer(self, optimizer):
"""Wraps `optimizer` in `LossScaleOptimizer` if necessary."""
def _get_single_optimizer(opt):
opt = optimizers.get(opt)
if self.dtype_policy.name == "mixed_float16" and not isinstance(
opt, lso.BaseLossScaleOptimizer
):
# Loss scaling is necessary with mixed_float16 for models to
# converge to the same accuracy as with float32.
opt = lso.BaseLossScaleOptimizer(opt)
return opt
return tf.nest.map_structure(_get_single_optimizer, optimizer)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _reset_compile_cache(self):
self.train_function = None
self.test_function = None
self.predict_function = None
# Used to cache the `tf.function`'ed `train_function` to be logged in
# TensorBoard, since the original `train_function` is not necessarily
# a `tf.function` (e.g., with ParameterServerStrategy, the
# `train_function` is a scheduling of the actual training function to a
# remote worker).
self.train_tf_function = None
# Used to cache `trainable` attr of `Layer`s for `fit`.
self._compiled_trainable_state = self._get_trainable_state()
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _configure_steps_per_execution(self, steps_per_execution):
self._steps_per_execution = self._create_counter_variable(
steps_per_execution
)
@property
def _should_compute_mask(self):
return False
@property
def metrics(self):
"""Return metrics added using `compile()` or `add_metric()`.
Note: Metrics passed to `compile()` are available only after a
`keras.Model` has been trained/evaluated on actual data.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> [m.name for m in model.metrics]
[]
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> model.fit(x, y)
>>> [m.name for m in model.metrics]
['loss', 'mae']
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> d = tf.keras.layers.Dense(2, name='out')
>>> output_1 = d(inputs)
>>> output_2 = d(inputs)
>>> model = tf.keras.models.Model(
... inputs=inputs, outputs=[output_1, output_2])
>>> model.add_metric(
... tf.reduce_sum(output_2), name='mean', aggregation='mean')
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
>>> model.fit(x, (y, y))
>>> [m.name for m in model.metrics]
['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',
'out_1_acc', 'mean']
"""
metrics = []
if self._is_compiled:
if self.compiled_loss is not None:
metrics += self.compiled_loss.metrics
if self.compiled_metrics is not None:
metrics += self.compiled_metrics.metrics
for l in self._flatten_layers():
metrics.extend(l._metrics)
return metrics
@property
def metrics_names(self):
"""Returns the model's display labels for all outputs.
Note: `metrics_names` are available only after a `keras.Model` has been
trained/evaluated on actual data.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> model.metrics_names
[]
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> model.fit(x, y)
>>> model.metrics_names
['loss', 'mae']
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> d = tf.keras.layers.Dense(2, name='out')
>>> output_1 = d(inputs)
>>> output_2 = d(inputs)
>>> model = tf.keras.models.Model(
... inputs=inputs, outputs=[output_1, output_2])
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
>>> model.fit(x, (y, y))
>>> model.metrics_names
['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',
'out_1_acc']
"""
# This property includes all output names including `loss` and
# per-output losses for backward compatibility.
return [m.name for m in self.metrics]
@property
def distribute_strategy(self):
"""The `tf.distribute.Strategy` this model was created under."""
return self._distribution_strategy or tf.distribute.get_strategy()
@property
def run_eagerly(self):
"""Settable attribute indicating whether the model should run eagerly.
Running eagerly means that your model will be run step by step,
like Python code. Your model might run slower, but it should become
easier for you to debug it by stepping into individual layer calls.
By default, we will attempt to compile your model to a static graph to
deliver the best execution performance.
Returns:
Boolean, whether the model should run eagerly.
"""
if self.dynamic and self._run_eagerly == False:
# TODO(fchollet): consider using py_func to enable this.
raise ValueError(
"Your model contains layers that can only be "
"successfully run in eager execution (layers "
"constructed with `dynamic=True`). "
"You cannot set `run_eagerly=False`."
)
if self._cluster_coordinator and self._run_eagerly:
raise ValueError(
"When using `Model` with `ParameterServerStrategy`, "
"`run_eagerly` is not supported."
)
# Run eagerly logic, by priority:
# (1) Dynamic models must be run eagerly.
# (2) Explicitly setting run_eagerly causes a Model to be run eagerly.
# (3) Not explicitly setting run_eagerly defaults to TF's global
# setting.
return (
self.dynamic
or self._run_eagerly
or (tf.config.functions_run_eagerly() and self._run_eagerly is None)
)
@run_eagerly.setter
def run_eagerly(self, value):
self._run_eagerly = value
@property
def autotune_steps_per_execution(self):
"""Settable property to enable tuning for steps_per_execution"""
return self._autotune_steps_per_execution
@autotune_steps_per_execution.setter
def autotune_steps_per_execution(self, value):
self._autotune_steps_per_execution = value
if value and self._steps_per_execution_tuner is None:
if self._steps_per_execution is None:
self._configure_steps_per_execution(1)
self._steps_per_execution_tuner = (
steps_per_execution_tuning.StepsPerExecutionTuner(
self.optimizer, self._steps_per_execution
)
)
@property
def steps_per_execution(self):
"""Settable `steps_per_execution variable. Requires a compiled model."""
return self._steps_per_execution
@steps_per_execution.setter
def steps_per_execution(self, value):
if self._steps_per_execution is None:
self._configure_steps_per_execution(value)
else:
self._steps_per_execution.assign(value)
@property
def jit_compile(self):
"""Specify whether to compile the model with XLA.
[XLA](https://www.tensorflow.org/xla) is an optimizing compiler
for machine learning. `jit_compile` is not enabled by default.
Note that `jit_compile=True` may not necessarily work for all models.
For more information on supported operations please refer to the
[XLA documentation](https://www.tensorflow.org/xla). Also refer to
[known XLA issues](https://www.tensorflow.org/xla/known_issues)
for more details.
"""
return self._jit_compile
@jit_compile.setter
def jit_compile(self, value):
# Function remains cached with previous jit_compile settings
if self._jit_compile == value:
# Avoid resetting compiler cache if possible if the value is the
# same
return
# Check if TensorFlow is compiled with XLA before setting the value
if value and not tf_utils.can_jit_compile(warn=True):
self._jit_compile = False
return
self._jit_compile = value
# Setting `jit_compile` should invalidate previously cached functions.
self._reset_compile_cache()
@property
def distribute_reduction_method(self):
"""The method employed to reduce per-replica values during training.
Unless specified, the value "auto" will be assumed, indicating that
the reduction strategy should be chosen based on the current
running environment.
See `reduce_per_replica` function for more details.
"""
return self._distribute_reduction_method or "auto"
@distribute_reduction_method.setter
def distribute_reduction_method(self, value):
self._distribute_reduction_method = value
def _validate_target_and_loss(self, y, loss):
"""Raises error if target or loss is not found.
This method verifies that the target and loss are properly populated
when applicable, or raises errors.
Args:
y: the target for training.
loss: the total loss tensor including loss added via `compile` and
`add_loss`.
"""
# `self.loss` references the loss added via `compile` call. If users
# have provided such, the target must be provided; otherwise it's a user
# error. Note that `self.loss` does not include losses added via
# `add_loss`, and it is a valid use when such loss from `add_loss`
# exists and target does not.
if self.loss and y is None:
raise ValueError(
"Target data is missing. Your model was compiled with "
f"loss={self.loss}, "
"and therefore expects target data to be provided in `fit()`."
)
# For training, there must be compiled loss or regularization loss to
# exist in order to apply the gradients. If one is not found, it means
# no loss was supplied via `compile` or `add_loss`.
elif loss is None:
raise ValueError(
"No loss found. You may have forgotten to provide a `loss` "
"argument in the `compile()` method."
)
def train_step(self, data):
"""The logic for one training step.
This method can be overridden to support custom training logic.
For concrete examples of how to override this method see
[Customizing what happens in fit](
https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit).
This method is called by `Model.make_train_function`.
This method should contain the mathematical logic for one step of
training. This typically includes the forward pass, loss calculation,
backpropagation, and metric updates.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_train_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the
values of the `Model`'s metrics are returned. Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data)
# Run forward pass.
with tf.GradientTape() as tape:
y_pred = self(x, training=True)
loss = self.compute_loss(x, y, y_pred, sample_weight)
self._validate_target_and_loss(y, loss)
# Run backwards pass.
self.optimizer.minimize(loss, self.trainable_variables, tape=tape)
return self.compute_metrics(x, y, y_pred, sample_weight)
def compute_loss(self, x=None, y=None, y_pred=None, sample_weight=None):
"""Compute the total loss, validate it, and return it.
Subclasses can optionally override this method to provide custom loss
computation logic.
Example:
```python
class MyModel(tf.keras.Model):
def __init__(self, *args, **kwargs):
super(MyModel, self).__init__(*args, **kwargs)
self.loss_tracker = tf.keras.metrics.Mean(name='loss')
def compute_loss(self, x, y, y_pred, sample_weight):
loss = tf.reduce_mean(tf.math.squared_difference(y_pred, y))
loss += tf.add_n(self.losses)
self.loss_tracker.update_state(loss)
return loss
def reset_metrics(self):
self.loss_tracker.reset_states()
@property
def metrics(self):
return [self.loss_tracker]
tensors = tf.random.uniform((10, 10)), tf.random.uniform((10,))
dataset = tf.data.Dataset.from_tensor_slices(tensors).repeat().batch(1)
inputs = tf.keras.layers.Input(shape=(10,), name='my_input')
outputs = tf.keras.layers.Dense(10)(inputs)
model = MyModel(inputs, outputs)
model.add_loss(tf.reduce_sum(outputs))
optimizer = tf.keras.optimizers.SGD()
model.compile(optimizer, loss='mse', steps_per_execution=10)
model.fit(dataset, epochs=2, steps_per_epoch=10)
print('My custom loss: ', model.loss_tracker.result().numpy())
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
The total loss as a `tf.Tensor`, or `None` if no loss results (which
is the case when called by `Model.test_step`).
"""
del x # The default implementation does not use `x`.
return self.compiled_loss(
y, y_pred, sample_weight, regularization_losses=self.losses
)
def compute_metrics(self, x, y, y_pred, sample_weight):
"""Update metric states and collect all metrics to be returned.
Subclasses can optionally override this method to provide custom metric
updating and collection logic.
Example:
```python
class MyModel(tf.keras.Sequential):
def compute_metrics(self, x, y, y_pred, sample_weight):
# This super call updates `self.compiled_metrics` and returns
# results for all metrics listed in `self.metrics`.
metric_results = super(MyModel, self).compute_metrics(
x, y, y_pred, sample_weight)
# Note that `self.custom_metric` is not listed in `self.metrics`.
self.custom_metric.update_state(x, y, y_pred, sample_weight)
metric_results['custom_metric_name'] = self.custom_metric.result()
return metric_results
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model.call(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end()`. Typically, the
values of the metrics listed in `self.metrics` are returned. Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
del x # The default implementation does not use `x`.
self.compiled_metrics.update_state(y, y_pred, sample_weight)
return self.get_metrics_result()
def get_metrics_result(self):
"""Returns the model's metrics values as a dict.
If any of the metric result is a dict (containing multiple metrics),
each of them gets added to the top level returned dict of this method.
Returns:
A `dict` containing values of the metrics listed in `self.metrics`.
Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
# Collect metrics to return
return_metrics = {}
for metric in self.metrics:
result = metric.result()
if isinstance(result, dict):
return_metrics.update(result)
else:
return_metrics[metric.name] = result
return return_metrics
def _validate_and_get_metrics_result(self, logs):
"""Returns model metrics as a dict if the keys match with input logs.
When the training / evalution is performed with asynchronous steps, such
as the case with `tf.distribute.ParameterServerStrategy`, the last
scheduled `train / test_step` may not give the latest metrics because it
is not guaranteed to be executed the last. This method gets metrics from
the model directly instead of relying on the return from last step
function.
It logs a warning if the metric results could not be overridden when
used with `tf.distribute.ParameterServerStrategy`.
When the user has custom train / test step functions, the metrics
returned may be different from `Model.metrics`. In those instances,
this function will be no-op and return the logs.
Args:
logs: A `dict` of metrics returned by train / test step function.
Returns:
A `dict` containing values of the metrics listed in `self.metrics`
when logs and model metrics keys match. Otherwise it returns input
`logs`.
"""
PSS_WARN_MSG = "Could not get Model metric results. \
Using the results of last step function could lead to incorrect \
results when used with ParameterServerStrategy"
try:
metric_logs = self.get_metrics_result()
except TypeError:
if self._cluster_coordinator:
logging.warning(PSS_WARN_MSG)
else:
# Verify that train / test step logs passed and metric logs have
# matching keys. Could be different when using custom step functions
if isinstance(logs, dict) and set(logs.keys()) == set(
metric_logs.keys()
):
logs = tf_utils.sync_to_numpy_or_python_type(metric_logs)
elif self._cluster_coordinator:
logging.warning(PSS_WARN_MSG)
return logs
def _aggregate_exact_metrics(self, logs):
# When doing exact evaluation, `logs` is a list of each data shard's
# metric variables, which will be used to update the metrics.
for shard_result in logs:
for metric in self.metrics:
if metric.name not in shard_result.keys():
logging.log_first_n(
logging.WARN,
f"No matching result found for metric {metric.name}. "
"This metric's computed result may be incorrect.",
3,
)
continue
metric_result = shard_result[metric.name]
if len(metric_result) != len(metric.weights):
raise ValueError(
f"Expected {len(metric.weights)} variables in result "
f"for metric {metric.name}, but found "
f"{len(metric_result)}."
)
for weight, val in zip(metric.weights, metric_result):
weight.assign_add(val)
return self.get_metrics_result()
def make_train_function(self, force=False):
"""Creates a function that executes one step of training.
This method can be overridden to support custom training logic.
This method is called by `Model.fit` and `Model.train_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual training
logic to `Model.train_step`.
This function is cached the first time `Model.fit` or
`Model.train_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the train function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_train_batch_end`, such as
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
if self.train_function is not None and not force:
return self.train_function
def step_function(model, iterator):
"""Runs a single training step."""
def run_step(data):
outputs = model.train_step(data)
# Ensure counter is updated only if `train_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._train_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def train_function(iterator):
"""Runs a training execution with a single step."""
return step_function(self, iterator)
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
if self._cluster_coordinator:
self.train_function = (
lambda it: self._cluster_coordinator.schedule(
train_function, args=(it,)
)
)
else:
self.train_function = train_function
# If we're using a coordinator, use the value of
# self._steps_per_execution at the time the function is
# called/scheduled, and not when it is actually executed.
elif self._cluster_coordinator:
def train_function(iterator, steps_per_execution):
"""Runs a training execution with multiple steps."""
for _ in tf.range(steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
self.train_function = lambda it: self._cluster_coordinator.schedule(
train_function, args=(it, self._steps_per_execution.value())
)
else:
def train_function(iterator):
"""Runs a training execution with multiple steps."""
for _ in tf.range(self._steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
self.train_function = train_function
return self.train_function
@traceback_utils.filter_traceback
def fit(
self,
x=None,
y=None,
batch_size=None,
epochs=1,
verbose="auto",
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_batch_size=None,
validation_freq=1,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
):
"""Trains the model for a fixed number of epochs (dataset iterations).
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A `tf.data` dataset. Should return a tuple
of either `(inputs, targets)` or
`(inputs, targets, sample_weights)`.
- A generator or `keras.utils.Sequence` returning `(inputs,
targets)` or `(inputs, targets, sample_weights)`.
- A `tf.keras.utils.experimental.DatasetCreator`, which wraps a
callable that takes a single argument of type
`tf.distribute.InputContext`, and returns a `tf.data.Dataset`.
`DatasetCreator` should be used when users prefer to specify the
per-replica batching and sharding logic for the `Dataset`.
See `tf.keras.utils.experimental.DatasetCreator` doc for more
information.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given below. If these
include `sample_weights` as a third component, note that sample
weighting applies to the `weighted_metrics` argument but not the
`metrics` argument in `compile()`. If using
`tf.distribute.experimental.ParameterServerStrategy`, only
`DatasetCreator` type is supported for `x`.
y: Target data. Like the input data `x`,
it could be either Numpy array(s) or TensorFlow tensor(s).
It should be consistent with `x` (you cannot have Numpy inputs and
tensor targets, or inversely). If `x` is a dataset, generator,
or `keras.utils.Sequence` instance, `y` should
not be specified (since targets will be obtained from `x`).
batch_size: Integer or `None`.
Number of samples per gradient 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).
epochs: Integer. Number of epochs to train the model.
An epoch is an iteration over the entire `x` and `y`
data provided
(unless the `steps_per_epoch` flag is set to
something other than None).
Note that in conjunction with `initial_epoch`,
`epochs` is to be understood as "final epoch".
The model is not trained for a number of iterations
given by `epochs`, but merely until the epoch
of index `epochs` is reached.
verbose: 'auto', 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = one line per epoch.
'auto' becomes 1 for most cases, but 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so verbose=2 is
recommended when not running interactively (eg, in a production
environment). Defaults to 'auto'.
callbacks: List of `keras.callbacks.Callback` instances.
List of callbacks to apply during training.
See `tf.keras.callbacks`. Note
`tf.keras.callbacks.ProgbarLogger` and
`tf.keras.callbacks.History` callbacks are created automatically
and need not be passed into `model.fit`.
`tf.keras.callbacks.ProgbarLogger` is created or not based on
`verbose` argument to `model.fit`.
Callbacks with batch-level calls are currently unsupported with
`tf.distribute.experimental.ParameterServerStrategy`, and users
are advised to implement epoch-level calls instead with an
appropriate `steps_per_epoch` value.
validation_split: Float between 0 and 1.
Fraction of the training data to be used as validation data.
The model will set apart this fraction of the training data,
will not train on it, and will evaluate
the loss and any model metrics
on this data at the end of each epoch.
The validation data is selected from the last samples
in the `x` and `y` data provided, before shuffling. This
argument is not supported when `x` is a dataset, generator or
`keras.utils.Sequence` instance.
If both `validation_data` and `validation_split` are provided,
`validation_data` will override `validation_split`.
`validation_split` is not yet supported with
`tf.distribute.experimental.ParameterServerStrategy`.
validation_data: Data on which to evaluate
the loss and any model metrics at the end of each epoch.
The model will not be trained on this data. Thus, note the fact
that the validation loss of data provided using
`validation_split` or `validation_data` is not affected by
regularization layers like noise and dropout.
`validation_data` will override `validation_split`.
`validation_data` could be:
- A tuple `(x_val, y_val)` of Numpy arrays or tensors.
- A tuple `(x_val, y_val, val_sample_weights)` of NumPy
arrays.
- A `tf.data.Dataset`.
- A Python generator or `keras.utils.Sequence` returning
`(inputs, targets)` or `(inputs, targets, sample_weights)`.
`validation_data` is not yet supported with
`tf.distribute.experimental.ParameterServerStrategy`.
shuffle: Boolean (whether to shuffle the training data
before each epoch) or str (for 'batch'). This argument is
ignored when `x` is a generator or an object of tf.data.Dataset.
'batch' is a special option for dealing
with the limitations of HDF5 data; it shuffles in batch-sized
chunks. Has no effect when `steps_per_epoch` is not `None`.
class_weight: Optional dictionary mapping class indices (integers)
to a weight (float) value, used for weighting the loss function
(during training only).
This can be useful to tell the model to
"pay more attention" to samples from
an under-represented class. When `class_weight` is specified
and targets have a rank of 2 or greater, either `y` must be
one-hot encoded, or an explicit final dimension of `1` must
be included for sparse class labels.
sample_weight: Optional Numpy array of weights for
the training samples, used for weighting the loss function
(during training only). You can either pass a flat (1D)
Numpy array with the same length as the input samples
(1:1 mapping between weights and samples),
or in the case of temporal data,
you can pass a 2D array with shape
`(samples, sequence_length)`,
to apply a different weight to every timestep of every sample.
This argument is not supported when `x` is a dataset, generator,
or `keras.utils.Sequence` instance, instead provide the
sample_weights as the third element of `x`.
Note that sample weighting does not apply to metrics specified
via the `metrics` argument in `compile()`. To apply sample
weighting to your metrics, you can specify them via the
`weighted_metrics` in `compile()` instead.
initial_epoch: Integer.
Epoch at which to start training
(useful for resuming a previous training run).
steps_per_epoch: Integer or `None`.
Total number of steps (batches of samples)
before declaring one epoch finished and starting the
next epoch. 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_per_epoch'
is None, the epoch will run until the input dataset is
exhausted. When passing an infinitely repeating dataset, you
must specify the `steps_per_epoch` argument. If
`steps_per_epoch=-1` the training will run indefinitely with an
infinitely repeating dataset. This argument is not supported
with array inputs.
When using `tf.distribute.experimental.ParameterServerStrategy`:
* `steps_per_epoch=None` is not supported.
validation_steps: Only relevant if `validation_data` is provided and
is a `tf.data` dataset. Total number of steps (batches of
samples) to draw before stopping when performing validation
at the end of every epoch. If 'validation_steps' is None,
validation will run until the `validation_data` dataset is
exhausted. In the case of an infinitely repeated dataset, it
will run into an infinite loop. If 'validation_steps' is
specified and only part of the dataset will be consumed, the
evaluation will start from the beginning of the dataset at each
epoch. This ensures that the same validation samples are used
every time.
validation_batch_size: Integer or `None`.
Number of samples per validation batch.
If unspecified, will default to `batch_size`.
Do not specify the `validation_batch_size` if your data is in
the form of datasets, generators, or `keras.utils.Sequence`
instances (since they generate batches).
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.
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the generator
queue. If unspecified, `max_queue_size` will default to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up
when using process-based threading. If unspecified, `workers`
will default to 1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
Unpacking behavior for iterator-like inputs:
A common pattern is to pass a tf.data.Dataset, generator, or
tf.keras.utils.Sequence to the `x` argument of fit, which will in fact
yield not only features (x) but optionally targets (y) and sample
weights. TF-Keras requires that the output of such iterator-likes be
unambiguous. The iterator should return a tuple of length 1, 2, or 3,
where the optional second and third elements will be used for y and
sample_weight respectively. Any other type provided will be wrapped in
a length one tuple, effectively treating everything as 'x'. When
yielding dicts, they should still adhere to the top-level tuple
structure.
e.g. `({"x0": x0, "x1": x1}, y)`. TF-Keras will not attempt to
separate features, targets, and weights from the keys of a single
dict.
A notable unsupported data type is the namedtuple. The reason is
that it behaves like both an ordered datatype (tuple) and a mapping
datatype (dict). So given a namedtuple of the form:
`namedtuple("example_tuple", ["y", "x"])`
it is ambiguous whether to reverse the order of the elements when
interpreting the value. Even worse is a tuple of the form:
`namedtuple("other_tuple", ["x", "y", "z"])`
where it is unclear if the tuple was intended to be unpacked into x,
y, and sample_weight or passed through as a single element to `x`. As
a result the data processing code will simply raise a ValueError if it
encounters a namedtuple. (Along with instructions to remedy the
issue.)
Returns:
A `History` object. Its `History.history` attribute is
a record of training loss values and metrics values
at successive epochs, as well as validation loss values
and validation metrics values (if applicable).
Raises:
RuntimeError: 1. If the model was never compiled or,
2. If `model.fit` is wrapped in `tf.function`.
ValueError: In case of mismatch between the provided input data
and what the model expects or when the input data is empty.
"""
# Legacy graph support is contained in `training_v1.Model`.
version_utils.disallow_legacy_graph("Model", "fit")
self._assert_compile_was_called()
self._check_call_args("fit")
_disallow_inside_tf_function("fit")
verbose = _get_verbosity(verbose, self.distribute_strategy)
if validation_split and validation_data is None:
# Create the validation data using the training data. Only supported
# for `Tensor` and `NumPy` input.
(
x,
y,
sample_weight,
), validation_data = data_adapter.train_validation_split(
(x, y, sample_weight), validation_split=validation_split
)
if validation_data:
(
val_x,
val_y,
val_sample_weight,
) = data_adapter.unpack_x_y_sample_weight(validation_data)
if self.distribute_strategy._should_use_with_coordinator:
self._cluster_coordinator = (
tf.distribute.experimental.coordinator.ClusterCoordinator(
self.distribute_strategy
)
)
with self.distribute_strategy.scope(), training_utils.RespectCompiledTrainableState( # noqa: E501
self
):
# Creates a `tf.data.Dataset` and handles batch and epoch iteration.
data_handler = data_adapter.get_data_handler(
x=x,
y=y,
sample_weight=sample_weight,
batch_size=batch_size,
steps_per_epoch=steps_per_epoch,
initial_epoch=initial_epoch,
epochs=epochs,
shuffle=shuffle,
class_weight=class_weight,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=epochs,
steps=data_handler.inferred_steps,
)
self.stop_training = False
self.train_function = self.make_train_function()
self._train_counter.assign(0)
callbacks.on_train_begin()
training_logs = None
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
# Handle fault-tolerance for multi-worker.
# TODO(omalleyt): Fix the ordering issues that mean this has to
# happen after `callbacks.on_train_begin`.
steps_per_epoch_inferred = (
steps_per_epoch or data_handler.inferred_steps
)
(
data_handler._initial_epoch,
data_handler._initial_step,
) = self._maybe_load_initial_counters_from_ckpt(
steps_per_epoch_inferred, initial_epoch
)
logs = None
for epoch, iterator in data_handler.enumerate_epochs():
self.reset_metrics()
callbacks.on_epoch_begin(epoch)
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
with tf.profiler.experimental.Trace(
"train",
epoch_num=epoch,
step_num=step,
batch_size=batch_size,
_r=1,
):
callbacks.on_train_batch_begin(step)
tmp_logs = self.train_function(iterator)
if data_handler.should_sync:
context.async_wait()
# No error, now safe to assign to logs.
logs = tmp_logs
end_step = step + data_handler.step_increment
callbacks.on_train_batch_end(end_step, logs)
if self.stop_training:
break
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if logs is None:
raise ValueError(
"Unexpected result of `train_function` "
"(Empty logs). This could be due to issues in input "
"pipeline that resulted in an empty dataset. "
"Otherwise, please use "
"`Model.compile(..., run_eagerly=True)`, or "
"`tf.config.run_functions_eagerly(True)` for more "
"information of where went wrong, or file a "
"issue/bug to `tf.keras`."
)
# Override with model metrics instead of last step logs
logs = self._validate_and_get_metrics_result(logs)
epoch_logs = copy.copy(logs)
# Run validation.
if validation_data and self._should_eval(
epoch, validation_freq
):
if self._pss_evaluation_shards:
self._disallow_exact_eval_with_add_metrics()
# Create data_handler for evaluation and cache it.
if getattr(self, "_eval_data_handler", None) is None:
self._eval_data_handler = data_adapter.get_data_handler(
x=val_x,
y=val_y,
sample_weight=val_sample_weight,
batch_size=validation_batch_size or batch_size,
steps_per_epoch=validation_steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
pss_evaluation_shards=self._pss_evaluation_shards,
)
val_logs = self.evaluate(
x=val_x,
y=val_y,
sample_weight=val_sample_weight,
batch_size=validation_batch_size or batch_size,
steps=validation_steps,
callbacks=callbacks,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
return_dict=True,
_use_cached_eval_dataset=True,
)
val_logs = {
"val_" + name: val for name, val in val_logs.items()
}
epoch_logs.update(val_logs)
callbacks.on_epoch_end(epoch, epoch_logs)
training_logs = epoch_logs
if self.stop_training:
break
if isinstance(self.optimizer, optimizer.Optimizer) and epochs > 0:
self.optimizer.finalize_variable_values(
self.trainable_variables
)
# If eval data_handler exists, delete it after all epochs are done.
if getattr(self, "_eval_data_handler", None) is not None:
del self._eval_data_handler
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_train_end(logs=training_logs)
return self.history
def test_step(self, data):
"""The logic for one evaluation step.
This method can be overridden to support custom evaluation logic.
This method is called by `Model.make_test_function`.
This function should contain the mathematical logic for one step of
evaluation.
This typically includes the forward pass, loss calculation, and metrics
updates.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_test_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the
values of the `Model`'s metrics are returned.
"""
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data)
y_pred = self(x, training=False)
# Updates stateful loss metrics.
self.compute_loss(x, y, y_pred, sample_weight)
return self.compute_metrics(x, y, y_pred, sample_weight)
def _make_test_function_exact(self):
if getattr(self, "_shard_test_function", None):
return self._shard_test_function
def step_function(batch):
def run_step(data):
# TODO(b/272050910): Use sample_weight for weighted metrics.
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(
data
)
y_pred = self(x, training=False)
return x, y, y_pred, sample_weight
if self._jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
outputs = self.distribute_strategy.run(run_step, args=(batch,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
def shard_test_function(dataset, total_shards, shard_idx):
# Copy loss and metric variables to the worker and work with them
# locally. This ensures each shard function is atomic: if a worker
# is preempted, the intermediate progress is discarded and that
# shard is retried. This in turn guarantees exactly-once visitation.
local_unweighted_metrics, local_weighted_metrics = [], []
with tf_utils.with_metric_local_vars_scope():
# TODO(jmullenbach): implement and use a clone for
# `MetricsContainer` and use its `update_state` method directly.
for metric in self.compiled_metrics.unweighted_metrics:
if metric is not None:
local_unweighted_metrics.append(
base_metric.clone_metric(metric)
)
for metric in self.compiled_metrics.weighted_metrics:
if metric is not None:
local_weighted_metrics.append(
base_metric.clone_metric(metric)
)
local_loss = compile_utils.LossesContainer.from_config(
self.compiled_loss.get_config()
)
dataset = input_ops.auto_shard_dataset(
dataset, total_shards, shard_idx
)
iterator = iter(dataset)
with distribute_utils.cache_variable_reads():
for batch in iterator:
x, y, y_pred, sample_weight = step_function(batch)
for weighted_metric in local_weighted_metrics:
weighted_metric.update_state(y, y_pred, sample_weight)
for unweighted_metric in local_unweighted_metrics:
unweighted_metric.update_state(y, y_pred)
local_loss(y, y_pred, sample_weight)
local_metrics = (
local_unweighted_metrics
+ local_weighted_metrics
+ local_loss.metrics
)
outputs = {metric.name: metric.weights for metric in local_metrics}
with tf.control_dependencies(_minimum_control_deps(outputs)):
self._test_counter.assign_add(1)
return outputs
if not self.run_eagerly:
shard_test_function = tf.function(
shard_test_function, reduce_retracing=True
)
self._shard_test_function = (
lambda *args: self._cluster_coordinator.schedule(
shard_test_function,
args=args,
)
)
return self._shard_test_function
def make_test_function(self, force=False):
"""Creates a function that executes one step of evaluation.
This method can be overridden to support custom evaluation logic.
This method is called by `Model.evaluate` and `Model.test_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.test_step`.
This function is cached the first time `Model.evaluate` or
`Model.test_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the test function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_test_batch_end`.
"""
if self.test_function is not None and not force:
return self.test_function
def step_function(model, iterator):
"""Runs a single evaluation step."""
def run_step(data):
outputs = model.test_step(data)
# Ensure counter is updated only if `test_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._test_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def test_function(iterator):
"""Runs a test execution with a single step."""
return step_function(self, iterator)
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
if self._cluster_coordinator:
self.test_function = (
lambda it: self._cluster_coordinator.schedule(
test_function, args=(it,)
)
)
else:
self.test_function = test_function
# If we're using a coordinator, use the value of
# self._steps_per_execution at the time the function is
# called/scheduled, and not when it is actually executed.
elif self._cluster_coordinator:
def test_function(iterator, steps_per_execution):
"""Runs a test execution with multiple steps."""
for _ in tf.range(steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
self.test_function = lambda it: self._cluster_coordinator.schedule(
test_function, args=(it, self._steps_per_execution.value())
)
else:
def test_function(iterator):
"""Runs a test execution with multiple steps."""
for _ in tf.range(self._steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
self.test_function = test_function
return self.test_function
@traceback_utils.filter_traceback
def evaluate(
self,
x=None,
y=None,
batch_size=None,
verbose="auto",
sample_weight=None,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
return_dict=False,
**kwargs,
):
"""Returns the loss value & metrics values for the model in test mode.
Computation is done in batches (see the `batch_size` arg.)
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A `tf.data` dataset. Should return a tuple
of either `(inputs, targets)` or
`(inputs, targets, sample_weights)`.
- A generator or `keras.utils.Sequence` returning `(inputs,
targets)` or `(inputs, targets, sample_weights)`.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given in the `Unpacking
behavior for iterator-like inputs` section of `Model.fit`.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s). It should be consistent with `x`
(you cannot have Numpy inputs and tensor targets, or inversely).
If `x` is a dataset, generator or `keras.utils.Sequence` instance,
`y` should not be specified (since targets will be obtained from
the iterator/dataset).
batch_size: Integer or `None`. Number of samples per batch of
computation. If unspecified, `batch_size` will default to 32. Do
not specify the `batch_size` if your data is in the form of a
dataset, generators, or `keras.utils.Sequence` instances (since
they generate batches).
verbose: `"auto"`, 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = single line.
`"auto"` becomes 1 for most cases, and to 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so `verbose=2` is
recommended when not running interactively (e.g. in a production
environment). Defaults to 'auto'.
sample_weight: Optional Numpy array of weights for the test samples,
used for weighting the loss function. You can either pass a flat
(1D) Numpy array with the same length as the input samples
(1:1 mapping between weights and samples), or in the case of
temporal data, you can pass a 2D array with shape `(samples,
sequence_length)`, to apply a different weight to every
timestep of every sample. This argument is not supported when
`x` is a dataset, instead pass sample weights as the third
element of `x`.
steps: Integer or `None`. Total number of steps (batches of samples)
before declaring the evaluation round finished. Ignored with the
default value of `None`. If x is a `tf.data` dataset and `steps`
is None, 'evaluate' will run until the dataset is exhausted. This
argument is not supported with array inputs.
callbacks: List of `keras.callbacks.Callback` instances. List of
callbacks to apply during evaluation. See
[callbacks](https://www.tensorflow.org/api_docs/python/tf/tf_keras/callbacks).
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the generator
queue. If unspecified, `max_queue_size` will default to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, `workers` will default to
1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
**kwargs: Unused at this time.
See the discussion of `Unpacking behavior for iterator-like inputs` for
`Model.fit`.
Returns:
Scalar test 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 scalar outputs.
Raises:
RuntimeError: If `model.evaluate` is wrapped in a `tf.function`.
"""
version_utils.disallow_legacy_graph("Model", "evaluate")
self._assert_compile_was_called()
self._check_call_args("evaluate")
self._check_sample_weight_warning(x, sample_weight)
_disallow_inside_tf_function("evaluate")
use_cached_eval_dataset = kwargs.pop("_use_cached_eval_dataset", False)
if kwargs:
raise TypeError(f"Invalid keyword arguments: {list(kwargs.keys())}")
if self.distribute_strategy._should_use_with_coordinator:
self._cluster_coordinator = (
tf.distribute.experimental.coordinator.ClusterCoordinator(
self.distribute_strategy
)
)
verbose = _get_verbosity(verbose, self.distribute_strategy)
if self._pss_evaluation_shards:
self._disallow_exact_eval_with_add_metrics()
with self.distribute_strategy.scope():
# Use cached evaluation data only when it's called in `Model.fit`
if (
use_cached_eval_dataset
and getattr(self, "_eval_data_handler", None) is not None
):
data_handler = self._eval_data_handler
else:
# Creates a `tf.data.Dataset` and handles batch and epoch
# iteration.
data_handler = data_adapter.get_data_handler(
x=x,
y=y,
sample_weight=sample_weight,
batch_size=batch_size,
steps_per_epoch=steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
pss_evaluation_shards=self._pss_evaluation_shards,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=1,
steps=data_handler.inferred_steps,
)
# Initialize to prevent errors if 0 epochs are evaluated.
logs = {}
test_function_runner = self._get_test_function_runner(callbacks)
self._test_counter.assign(0)
callbacks.on_test_begin()
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
for (
_,
dataset_or_iterator,
) in data_handler.enumerate_epochs(): # Single epoch.
self.reset_metrics()
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
with tf.profiler.experimental.Trace(
"test", step_num=step, _r=1
):
callbacks.on_test_batch_begin(step)
logs = test_function_runner.run_step(
dataset_or_iterator,
data_handler,
step,
self._pss_evaluation_shards,
)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
# Override with model metrics instead of last step logs
if self._pss_evaluation_shards:
logs = self._aggregate_exact_metrics(logs)
else:
logs = self._validate_and_get_metrics_result(logs)
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_test_end(logs=logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def _disallow_exact_eval_with_add_metrics(self):
metrics_from_add_metric = [
metric
for layer in self._flatten_layers()
for metric in layer._metrics
]
compiled_metrics = self.compiled_metrics.metrics
if any(
[
metric not in compiled_metrics
for metric in metrics_from_add_metric
]
):
raise ValueError(
"Detected that a metric was added to this model "
"via `Model.add_metric`. This is not currently "
"supported when using exact evaluation with "
"`tf.distribute.ParameterServerStrategy`."
)
def _infer_exact_eval_shards(self, pss_evaluation_shards):
if not self.distribute_strategy._should_use_with_coordinator:
return 0
if pss_evaluation_shards == "auto":
# TODO(b/264265138) evaluate and improve this heuristic
return self.distribute_strategy._num_workers * 5
return pss_evaluation_shards
def _get_test_function_runner(self, callbacks):
if (
self._pss_evaluation_shards
and self.distribute_strategy._should_use_with_coordinator
):
self.test_function = self._make_test_function_exact()
test_function_runner = _ExactTestFunction(
self.test_function, callbacks
)
else:
self.test_function = self.make_test_function()
test_function_runner = _TestFunction(self.test_function, callbacks)
return test_function_runner
def predict_step(self, data):
"""The logic for one inference step.
This method can be overridden to support custom inference logic.
This method is called by `Model.make_predict_function`.
This method should contain the mathematical logic for one step of
inference. This typically includes the forward pass.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_predict_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
The result of one inference step, typically the output of calling the
`Model` on data.
"""
x, _, _ = data_adapter.unpack_x_y_sample_weight(data)
return self(x, training=False)
def make_predict_function(self, force=False):
"""Creates a function that executes one step of inference.
This method can be overridden to support custom inference logic.
This method is called by `Model.predict` and `Model.predict_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.predict_step`.
This function is cached the first time `Model.predict` or
`Model.predict_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the predict function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return the outputs of the `Model`.
"""
if self.predict_function is not None and not force:
return self.predict_function
def step_function(model, iterator):
"""Runs a single evaluation step."""
def run_step(data):
outputs = model.predict_step(data)
# Ensure counter is updated only if `test_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._predict_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs, self.distribute_strategy, reduction="concat"
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def predict_function(iterator):
"""Runs an evaluation execution with a single step."""
return step_function(self, iterator)
else:
def predict_function(iterator):
"""Runs an evaluation execution with multiple steps."""
outputs = step_function(self, iterator)
for _ in tf.range(self._steps_per_execution - 1):
tf.autograph.experimental.set_loop_options(
shape_invariants=[
(
outputs,
tf.nest.map_structure(
lambda t: tf_utils.get_tensor_spec(
t, dynamic_batch=True
).shape,
outputs,
),
)
]
)
step_outputs = step_function(self, iterator)
outputs = tf.nest.map_structure(
lambda t1, t2: concat([t1, t2]), outputs, step_outputs
)
return outputs
if not self.run_eagerly:
predict_function = tf.function(
predict_function, reduce_retracing=True
)
self.predict_function = predict_function
return self.predict_function
@traceback_utils.filter_traceback
def predict(
self,
x,
batch_size=None,
verbose="auto",
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
):
"""Generates output predictions for the input samples.
Computation is done in batches. This method is designed for batch
processing of large numbers of inputs. It is not intended for use inside
of loops that iterate over your data and process small numbers of inputs
at a time.
For small numbers of inputs that fit in one batch,
directly use `__call__()` for faster execution, e.g.,
`model(x)`, or `model(x, training=False)` if you have layers such as
`tf.keras.layers.BatchNormalization` that behave differently during
inference. You may pair the individual model call with a `tf.function`
for additional performance inside your inner loop.
If you need access to numpy array values instead of tensors after your
model call, you can use `tensor.numpy()` to get the numpy array value of
an eager tensor.
Also, note the fact that test loss is not affected by
regularization layers like noise and dropout.
Note: See [this FAQ entry](
https://keras.io/getting_started/faq/#whats-the-difference-between-model-methods-predict-and-call)
for more details about the difference between `Model` methods
`predict()` and `__call__()`.
Args:
x: Input samples. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A `tf.data` dataset.
- A generator or `keras.utils.Sequence` instance.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given in the `Unpacking
behavior for iterator-like inputs` section of `Model.fit`.
batch_size: Integer or `None`.
Number of samples per batch.
If unspecified, `batch_size` will default to 32.
Do not specify the `batch_size` if your data is in the
form of dataset, generators, or `keras.utils.Sequence` instances
(since they generate batches).
verbose: `"auto"`, 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = single line.
`"auto"` becomes 1 for most cases, and to 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so `verbose=2` is
recommended when not running interactively (e.g. in a production
environment). Defaults to 'auto'.
steps: Total number of steps (batches of samples)
before declaring the prediction round finished.
Ignored with the default value of `None`. If x is a `tf.data`
dataset and `steps` is None, `predict()` will
run until the input dataset is exhausted.
callbacks: List of `keras.callbacks.Callback` instances.
List of callbacks to apply during prediction.
See [callbacks](
https://www.tensorflow.org/api_docs/python/tf/tf_keras/callbacks).
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the
generator queue. If unspecified, `max_queue_size` will default
to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, `workers` will default
to 1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
See the discussion of `Unpacking behavior for iterator-like inputs` for
`Model.fit`. Note that Model.predict uses the same interpretation rules
as `Model.fit` and `Model.evaluate`, so inputs must be unambiguous for
all three methods.
Returns:
Numpy array(s) of predictions.
Raises:
RuntimeError: If `model.predict` is wrapped in a `tf.function`.
ValueError: In case of mismatch between the provided
input data and the model's expectations,
or in case a stateful model receives a number of samples
that is not a multiple of the batch size.
"""
version_utils.disallow_legacy_graph("Model", "predict")
self._check_call_args("predict")
_disallow_inside_tf_function("predict")
# TODO(yashkatariya): Cache model on the coordinator for faster
# prediction. If running under PSS, then swap it with OneDeviceStrategy
# so that execution will run on the coordinator.
original_pss_strategy = None
if self.distribute_strategy._should_use_with_coordinator:
original_pss_strategy = self.distribute_strategy
self._distribution_strategy = None
# Cluster coordinator is set by `.fit()` and `.evaluate()` which is not
# needed in `.predict()` because all the predictions happen on the
# coordinator/locally.
if self._cluster_coordinator:
self._cluster_coordinator = None
verbose = _get_verbosity(verbose, self.distribute_strategy)
outputs = None
with self.distribute_strategy.scope():
# Creates a `tf.data.Dataset` and handles batch and epoch iteration.
dataset_types = (tf.compat.v1.data.Dataset, tf.data.Dataset)
if (
self._in_multi_worker_mode()
or _is_tpu_multi_host(self.distribute_strategy)
) and isinstance(x, dataset_types):
try:
options = tf.data.Options()
data_option = tf.data.experimental.AutoShardPolicy.DATA
options.experimental_distribute.auto_shard_policy = (
data_option
)
x = x.with_options(options)
except ValueError:
warnings.warn(
"Using Model.predict with MultiWorkerMirroredStrategy "
"or TPUStrategy and AutoShardPolicy.FILE might lead to "
"out-of-order result. Consider setting it to "
"AutoShardPolicy.DATA.",
stacklevel=2,
)
data_handler = data_adapter.get_data_handler(
x=x,
batch_size=batch_size,
steps_per_epoch=steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=1,
steps=data_handler.inferred_steps,
)
self.predict_function = self.make_predict_function()
self._predict_counter.assign(0)
callbacks.on_predict_begin()
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
batch_outputs = None
for _, iterator in data_handler.enumerate_epochs(): # Single epoch.
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
callbacks.on_predict_batch_begin(step)
tmp_batch_outputs = self.predict_function(iterator)
if data_handler.should_sync:
context.async_wait()
batch_outputs = (
tmp_batch_outputs # No error, now safe to assign.
)
if outputs is None:
outputs = tf.nest.map_structure(
lambda batch_output: [batch_output],
batch_outputs,
)
else:
tf.__internal__.nest.map_structure_up_to(
batch_outputs,
lambda output, batch_output: output.append(
batch_output
),
outputs,
batch_outputs,
)
end_step = step + data_handler.step_increment
callbacks.on_predict_batch_end(
end_step, {"outputs": batch_outputs}
)
if batch_outputs is None:
raise ValueError(
"Unexpected result of `predict_function` "
"(Empty batch_outputs). Please use "
"`Model.compile(..., run_eagerly=True)`, or "
"`tf.config.run_functions_eagerly(True)` for more "
"information of where went wrong, or file a "
"issue/bug to `tf.keras`."
)
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_predict_end()
all_outputs = tf.__internal__.nest.map_structure_up_to(
batch_outputs, potentially_ragged_concat, outputs
)
# If originally PSS strategy was used, then replace it back since
# predict is running under `OneDeviceStrategy` after the swap and once
# its done we need to replace it back to PSS again.
if original_pss_strategy is not None:
self._distribution_strategy = original_pss_strategy
return tf_utils.sync_to_numpy_or_python_type(all_outputs)
def reset_metrics(self):
"""Resets the state of all the metrics in the model.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> _ = model.fit(x, y, verbose=0)
>>> assert all(float(m.result()) for m in model.metrics)
>>> model.reset_metrics()
>>> assert all(float(m.result()) == 0 for m in model.metrics)
"""
for m in self.metrics:
m.reset_state()
def train_on_batch(
self,
x,
y=None,
sample_weight=None,
class_weight=None,
reset_metrics=True,
return_dict=False,
):
"""Runs a single gradient update on a single batch of data.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s).
sample_weight: Optional array of the same length as x, containing
weights to apply to the model's loss for each sample. In the case
of temporal data, you can pass a 2D array with shape (samples,
sequence_length), to apply a different weight to every timestep of
every sample.
class_weight: Optional dictionary mapping class indices (integers)
to a weight (float) to apply to the model's loss for the samples
from this class during training. This can be useful to tell the
model to "pay more attention" to samples from an under-represented
class. When `class_weight` is specified and targets have a rank of
2 or greater, either `y` must be one-hot encoded, or an explicit
final dimension of `1` must be included for sparse class labels.
reset_metrics: If `True`, the metrics returned will be only for this
batch. If `False`, the metrics will be statefully accumulated
across batches.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
Returns:
Scalar training 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 scalar outputs.
Raises:
RuntimeError: If `model.train_on_batch` is wrapped in a `tf.function`.
"""
self._assert_compile_was_called()
self._check_call_args("train_on_batch")
_disallow_inside_tf_function("train_on_batch")
if reset_metrics:
self.reset_metrics()
with self.distribute_strategy.scope(), training_utils.RespectCompiledTrainableState( # noqa: E501
self
):
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x, y, sample_weight, class_weight
)
self.train_function = self.make_train_function()
logs = self.train_function(iterator)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def test_on_batch(
self,
x,
y=None,
sample_weight=None,
reset_metrics=True,
return_dict=False,
):
"""Test the model on a single batch of samples.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays (in case the
model has multiple inputs).
- A TensorFlow tensor, or a list of tensors (in case the model has
multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s). It should be consistent with `x`
(you cannot have Numpy inputs and tensor targets, or inversely).
sample_weight: Optional array of the same length as x, containing
weights to apply to the model's loss for each sample. In the case
of temporal data, you can pass a 2D array with shape (samples,
sequence_length), to apply a different weight to every timestep of
every sample.
reset_metrics: If `True`, the metrics returned will be only for this
batch. If `False`, the metrics will be statefully accumulated
across batches.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
Returns:
Scalar test 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 scalar outputs.
Raises:
RuntimeError: If `model.test_on_batch` is wrapped in a
`tf.function`.
"""
self._assert_compile_was_called()
self._check_call_args("test_on_batch")
_disallow_inside_tf_function("test_on_batch")
if reset_metrics:
self.reset_metrics()
with self.distribute_strategy.scope():
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x, y, sample_weight
)
self.test_function = self.make_test_function()
logs = self.test_function(iterator)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def predict_on_batch(self, x):
"""Returns predictions for a single batch of samples.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays (in case the
model has multiple inputs).
- A TensorFlow tensor, or a list of tensors (in case the model has
multiple inputs).
Returns:
Numpy array(s) of predictions.
Raises:
RuntimeError: If `model.predict_on_batch` is wrapped in a
`tf.function`.
"""
self._check_call_args("predict_on_batch")
_disallow_inside_tf_function("predict_on_batch")
with self.distribute_strategy.scope():
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x
)
self.predict_function = self.make_predict_function()
outputs = self.predict_function(iterator)
return tf_utils.sync_to_numpy_or_python_type(outputs)
@doc_controls.do_not_generate_docs
def fit_generator(
self,
generator,
steps_per_epoch=None,
epochs=1,
verbose=1,
callbacks=None,
validation_data=None,
validation_steps=None,
validation_freq=1,
class_weight=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
shuffle=True,
initial_epoch=0,
):
"""Fits the model on data yielded batch-by-batch by a Python generator.
DEPRECATED:
`Model.fit` now supports generators, so there is no longer any need to
use this endpoint.
"""
warnings.warn(
"`Model.fit_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.fit`, which supports generators.",
stacklevel=2,
)
return self.fit(
generator,
steps_per_epoch=steps_per_epoch,
epochs=epochs,
verbose=verbose,
callbacks=callbacks,
validation_data=validation_data,
validation_steps=validation_steps,
validation_freq=validation_freq,
class_weight=class_weight,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
shuffle=shuffle,
initial_epoch=initial_epoch,
)
@doc_controls.do_not_generate_docs
def evaluate_generator(
self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0,
):
"""Evaluates the model on a data generator.
DEPRECATED:
`Model.evaluate` now supports generators, so there is no longer any
need to use this endpoint.
"""
warnings.warn(
"`Model.evaluate_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.evaluate`, which supports generators.",
stacklevel=2,
)
self._check_call_args("evaluate_generator")
return self.evaluate(
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks,
)
@doc_controls.do_not_generate_docs
def predict_generator(
self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0,
):
"""Generates predictions for the input samples from a data generator.
DEPRECATED:
`Model.predict` now supports generators, so there is no longer any
need to use this endpoint.
"""
warnings.warn(
"`Model.predict_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.predict`, which supports generators.",
stacklevel=2,
)
return self.predict(
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks,
)
######################################################################
# Functions below are not training related. They are for model weights
# tracking, save/load, serialization, etc.
######################################################################
@property
def trainable_weights(self):
self._assert_weights_created()
if not self._trainable:
return []
trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
trainable_variables += trackable_obj.trainable_variables
trainable_variables += self._trainable_weights
return self._dedup_weights(trainable_variables)
@property
def non_trainable_weights(self):
self._assert_weights_created()
non_trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
non_trainable_variables += trackable_obj.non_trainable_variables
if not self._trainable:
# Return order is all trainable vars, then all non-trainable vars.
trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
trainable_variables += trackable_obj.trainable_variables
non_trainable_variables = (
trainable_variables
+ self._trainable_weights
+ non_trainable_variables
+ self._non_trainable_weights
)
else:
non_trainable_variables = (
non_trainable_variables + self._non_trainable_weights
)
return self._dedup_weights(non_trainable_variables)
def get_weights(self):
"""Retrieves the weights of the model.
Returns:
A flat list of Numpy arrays.
"""
with self.distribute_strategy.scope():
return super().get_weights()
@traceback_utils.filter_traceback
def save(self, 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.models.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.models.save_model()`.
"""
saving_api.save_model(
self,
filepath=filepath,
overwrite=overwrite,
save_format=save_format,
**kwargs,
)
@traceback_utils.filter_traceback
def save_weights(
self, filepath, overwrite=True, save_format=None, options=None
):
"""Saves all layer weights.
Either saves in HDF5 or in TensorFlow format based on the `save_format`
argument.
When saving in HDF5 format, the weight file has:
- `layer_names` (attribute), a list of strings
(ordered names of model layers).
- For every layer, a `group` named `layer.name`
- For every such layer group, a group attribute `weight_names`,
a list of strings
(ordered names of weights tensor of the layer).
- For every weight in the layer, a dataset
storing the weight value, named after the weight tensor.
When saving in TensorFlow format, all objects referenced by the network
are saved in the same format as `tf.train.Checkpoint`, including any
`Layer` instances or `Optimizer` instances assigned to object
attributes. For networks constructed from inputs and outputs using
`tf.keras.Model(inputs, outputs)`, `Layer` instances used by the network
are tracked/saved automatically. For user-defined classes which inherit
from `tf.keras.Model`, `Layer` instances must be assigned to object
attributes, typically in the constructor. See the documentation of
`tf.train.Checkpoint` and `tf.keras.Model` for details.
While the formats are the same, do not mix `save_weights` and
`tf.train.Checkpoint`. Checkpoints saved by `Model.save_weights` should
be loaded using `Model.load_weights`. Checkpoints saved using
`tf.train.Checkpoint.save` should be restored using the corresponding
`tf.train.Checkpoint.restore`. Prefer `tf.train.Checkpoint` over
`save_weights` for training checkpoints.
The TensorFlow format matches objects and variables by starting at a
root object, `self` for `save_weights`, and greedily matching attribute
names. For `Model.save` this is the `Model`, and for `Checkpoint.save`
this is the `Checkpoint` even if the `Checkpoint` has a model attached.
This means saving a `tf.keras.Model` using `save_weights` and loading
into a `tf.train.Checkpoint` with a `Model` attached (or vice versa)
will not match the `Model`'s variables. See the
[guide to training checkpoints](
https://www.tensorflow.org/guide/checkpoint) for details on
the TensorFlow format.
Args:
filepath: String or PathLike, path to the file to save the weights
to. When saving in TensorFlow format, this is the prefix used
for checkpoint files (multiple files are generated). Note that
the '.h5' suffix causes weights to be saved in HDF5 format.
overwrite: Whether to silently overwrite any existing file at the
target location, or provide the user with a manual prompt.
save_format: Either 'tf' or 'h5'. A `filepath` ending in '.h5' or
'.keras' will default to HDF5 if `save_format` is `None`.
Otherwise, `None` becomes 'tf'. Defaults to `None`.
options: Optional `tf.train.CheckpointOptions` object that specifies
options for saving weights.
Raises:
ImportError: If `h5py` is not available when attempting to save in
HDF5 format.
"""
saving_api.save_weights(
self,
filepath=filepath,
overwrite=overwrite,
save_format=save_format,
options=options,
)
@traceback_utils.filter_traceback
def load_weights(
self, filepath, skip_mismatch=False, by_name=False, options=None
):
"""Loads all layer weights from a saved files.
The saved file could be a SavedModel file, a `.keras` file (v3 saving
format), or a file created via `model.save_weights()`.
By default, weights are loaded based on the network's
topology. This means the architecture should be the same as when the
weights were saved. Note that layers that don't have weights are not
taken into account in the topological ordering, so adding or removing
layers is fine as long as they don't have weights.
**Partial weight loading**
If you have modified your model, for instance by adding a new layer
(with weights) or by changing the shape of the weights of a layer,
you can choose to ignore errors and continue loading
by setting `skip_mismatch=True`. In this case any layer with
mismatching weights will be skipped. A warning will be displayed
for each skipped layer.
**Weight loading by name**
If your weights are saved as a `.h5` file created
via `model.save_weights()`, you can use the argument `by_name=True`.
In this case, weights are loaded into layers only if they share
the same name. This is useful for fine-tuning or transfer-learning
models where some of the layers have changed.
Note that only topological loading (`by_name=False`) is supported when
loading weights from the `.keras` v3 format or from the TensorFlow
SavedModel format.
Args:
filepath: String, path to the weights file to load. For weight files
in TensorFlow format, this is the file prefix (the same as was
passed to `save_weights()`). This can also be a path to a
SavedModel or a `.keras` file (v3 saving format) saved
via `model.save()`.
skip_mismatch: Boolean, whether to skip loading of layers where
there is a mismatch in the number of weights, or a mismatch in
the shape of the weights.
by_name: Boolean, whether to load weights by name or by topological
order. Only topological loading is supported for weight files in
the `.keras` v3 format or in the TensorFlow SavedModel format.
options: Optional `tf.train.CheckpointOptions` object that specifies
options for loading weights (only valid for a SavedModel file).
"""
return saving_api.load_weights(
self,
filepath=filepath,
by_name=by_name,
skip_mismatch=skip_mismatch,
options=options,
)
def _updated_config(self):
"""Util shared between different serialization methods.
Returns:
Model config with TF-Keras version information added.
"""
from tf_keras.src import __version__ as keras_version
config = self.get_config()
model_config = {
"class_name": self.__class__.__name__,
"config": config,
"keras_version": keras_version,
"backend": backend.backend(),
}
return model_config
@generic_utils.default
def get_config(self):
"""Returns the config of the `Model`.
Config is a Python dictionary (serializable) containing the
configuration of an object, which in this case is a `Model`. This allows
the `Model` to be be reinstantiated later (without its trained weights)
from this configuration.
Note that `get_config()` does not guarantee to return a fresh copy of
dict every time it is called. The callers should make a copy of the
returned dict if they want to modify it.
Developers of subclassed `Model` are advised to override this method,
and continue to update the dict from `super(MyModel, self).get_config()`
to provide the proper configuration of this `Model`. The default config
will return config dict for init parameters if they are basic types.
Raises `NotImplementedError` when in cases where a custom
`get_config()` implementation is required for the subclassed model.
Returns:
Python dictionary containing the configuration of this `Model`.
"""
# If sublcass doesn't implement `get_config()` parse from init args
# otherwise default to empty dict
if generic_utils.is_default(self.get_config):
try:
config = base_layer.Layer.get_config(self)
except NotImplementedError:
config = {}
logging.warning(
"Model's `__init__()` arguments contain non-serializable "
"objects. Please implement a `get_config()` method in the "
"subclassed Model for proper saving and loading. "
"Defaulting to empty config."
)
else:
config = {}
return config
@classmethod
def from_config(cls, config, custom_objects=None):
# `from_config` assumes `cls` is either `Functional` or a child class of
# `Functional`. In the case that `cls` is meant to behave like a child
# class of `Functional` but only inherits from the `Model` class, we
# have to call `cls(...)` instead of `Functional.from_config`.
from tf_keras.src.engine import functional
with serialization.SharedObjectLoadingScope():
functional_config_keys = [
"name",
"layers",
"input_layers",
"output_layers",
]
is_functional_config = all(
key in config for key in functional_config_keys
)
argspec = tf_inspect.getfullargspec(cls.__init__)
functional_init_args = tf_inspect.getfullargspec(
functional.Functional.__init__
).args[1:]
revivable_as_functional = (
cls in {functional.Functional, Model}
or argspec.args[1:] == functional_init_args
or (argspec.varargs == "args" and argspec.varkw == "kwargs")
)
if is_functional_config and revivable_as_functional:
# Revive Functional model
# (but not Functional subclasses with a custom __init__)
inputs, outputs, layers = functional.reconstruct_from_config(
config, custom_objects
)
model = cls(
inputs=inputs, outputs=outputs, name=config.get("name")
)
functional.connect_ancillary_layers(model, layers)
else:
# Either the model has a custom __init__, or the config
# does not contain all the information necessary to
# revive a Functional model. This happens when the user creates
# subclassed models where `get_config()` is returning
# insufficient information to be considered a Functional model.
# In this case, we fall back to provide all config into the
# constructor of the class.
try:
model = cls(**config)
except TypeError as e:
raise TypeError(
"Unable to revive model from config. When overriding "
"the `get_config()` method, make sure that the "
"returned config contains all items used as arguments "
f"in the constructor to {cls}, "
"which is the default behavior. "
"You can override this default behavior by defining a "
"`from_config(cls, config)` class method to specify "
"how to create an "
f"instance of {cls.__name__} from its config.\n\n"
f"Received config={config}\n\n"
f"Error encountered during deserialization: {e}"
)
return model
def to_json(self, **kwargs):
"""Returns a JSON string containing the network configuration.
To load a network from a JSON save file, use
`keras.models.model_from_json(json_string, custom_objects={})`.
Args:
**kwargs: Additional keyword arguments to be passed to
*`json.dumps()`.
Returns:
A JSON string.
"""
model_config = self._updated_config()
return json.dumps(
model_config, default=json_utils.get_json_type, **kwargs
)
def to_yaml(self, **kwargs):
"""Returns a yaml string containing the network configuration.
Note: Since TF 2.6, this method is no longer supported and will raise a
RuntimeError.
To load a network from a yaml save file, use
`keras.models.model_from_yaml(yaml_string, custom_objects={})`.
`custom_objects` should be a dictionary mapping
the names of custom losses / layers / etc to the corresponding
functions / classes.
Args:
**kwargs: Additional keyword arguments
to be passed to `yaml.dump()`.
Returns:
A YAML string.
Raises:
RuntimeError: announces that the method poses a security risk
"""
raise RuntimeError(
"Method `model.to_yaml()` has been removed due to security risk of "
"arbitrary code execution. Please use `model.to_json()` instead."
)
def reset_states(self):
for layer in self.layers:
if hasattr(layer, "reset_states") and getattr(
layer, "stateful", False
):
layer.reset_states()
@property
@doc_controls.do_not_generate_docs
def state_updates(self):
"""Deprecated, do NOT use!
Returns the `updates` from all layers that are stateful.
This is useful for separating training updates and
state updates, e.g. when we need to update a layer's internal state
during prediction.
Returns:
A list of update ops.
"""
warnings.warn(
"`Model.state_updates` will be removed in a future version. "
"This property should not be used in TensorFlow 2.0, "
"as `updates` are applied automatically.",
stacklevel=2,
)
state_updates = []
for layer in self.layers:
if getattr(layer, "stateful", False):
if hasattr(layer, "updates"):
state_updates += layer.updates
return state_updates
@property
def weights(self):
"""Returns the list of all layer variables/weights.
Note: This will not track the weights of nested `tf.Modules` that are
not themselves TF-Keras layers.
Returns:
A list of variables.
"""
return self._dedup_weights(self._undeduplicated_weights)
@property
def _undeduplicated_weights(self):
"""Returns the undeduplicated list of all layer variables/weights."""
self._assert_weights_created()
weights = []
for layer in self._self_tracked_trackables:
weights += layer.variables
weights += self._trainable_weights + self._non_trainable_weights
return weights
def summary(
self,
line_length=None,
positions=None,
print_fn=None,
expand_nested=False,
show_trainable=False,
layer_range=None,
):
"""Prints a string summary of the network.
Args:
line_length: Total length of printed lines
(e.g. set this to adapt the display to different
terminal window sizes).
positions: Relative or absolute positions of log elements
in each line. If not provided, becomes
`[0.3, 0.6, 0.70, 1.]`. Defaults to `None`.
print_fn: Print function to use. By default, prints to `stdout`.
If `stdout` doesn't work in your environment, change to `print`.
It will be called on each line of the summary.
You can set it to a custom function
in order to capture the string summary.
expand_nested: Whether to expand the nested models.
Defaults to `False`.
show_trainable: Whether to show if a layer is trainable.
Defaults to `False`.
layer_range: a list or tuple of 2 strings,
which is the starting layer name and ending layer name
(both inclusive) indicating the range of layers to be printed
in summary. It also accepts regex patterns instead of exact
name. In such case, start predicate will be the first element
it matches to `layer_range[0]` and the end predicate will be
the last element it matches to `layer_range[1]`.
By default `None` which considers all layers of model.
Raises:
ValueError: if `summary()` is called before the model is built.
"""
if not self.built:
raise ValueError(
"This model has not yet been built. "
"Build the model first by calling `build()` or by calling "
"the model on a batch of data."
)
layer_utils.print_summary(
self,
line_length=line_length,
positions=positions,
print_fn=print_fn,
expand_nested=expand_nested,
show_trainable=show_trainable,
layer_range=layer_range,
)
@property
def layers(self):
return list(self._flatten_layers(include_self=False, recursive=False))
@layers.setter
def layers(self, _):
raise AttributeError(
"`Model.layers` attribute is reserved and should not be used. "
"Please use another name."
)
def get_layer(self, name=None, index=None):
"""Retrieves a layer based on either its name (unique) or index.
If `name` and `index` are both provided, `index` will take precedence.
Indices are based on order of horizontal graph traversal (bottom-up).
Args:
name: String, name of layer.
index: Integer, index of layer.
Returns:
A layer instance.
"""
# TODO(fchollet): We could build a dictionary based on layer names
# since they are constant, but we have not done that yet.
if index is not None and name is not None:
raise ValueError(
"Provide only a layer name or a layer index. Received: "
f"index={index}, name={name}."
)
if index is not None:
if len(self.layers) <= index:
raise ValueError(
f"Was asked to retrieve layer at index {index}"
f" but model only has {len(self.layers)}"
" layers."
)
else:
return self.layers[index]
if name is not None:
for layer in self.layers:
if layer.name == name:
return layer
raise ValueError(
f"No such layer: {name}. Existing layers are: "
f"{list(layer.name for layer in self.layers)}."
)
raise ValueError(
"Provide either a layer name or layer index at `get_layer`."
)
def get_weight_paths(self):
"""Retrieve all the variables and their paths for the model.
The variable path (string) is a stable key to identify a `tf.Variable`
instance owned by the model. It can be used to specify variable-specific
configurations (e.g. DTensor, quantization) from a global view.
This method returns a dict with weight object paths as keys
and the corresponding `tf.Variable` instances as values.
Note that if the model is a subclassed model and the weights haven't
been initialized, an empty dict will be returned.
Returns:
A dict where keys are variable paths and values are `tf.Variable`
instances.
Example:
```python
class SubclassModel(tf.keras.Model):
def __init__(self, name=None):
super().__init__(name=name)
self.d1 = tf.keras.layers.Dense(10)
self.d2 = tf.keras.layers.Dense(20)
def call(self, inputs):
x = self.d1(inputs)
return self.d2(x)
model = SubclassModel()
model(tf.zeros((10, 10)))
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': model.d1.kernel,
# 'd1.bias': model.d1.bias,
# 'd2.kernel': model.d2.kernel,
# 'd2.bias': model.d2.bias,
# }
# Functional model
inputs = tf.keras.Input((10,), batch_size=10)
x = tf.keras.layers.Dense(20, name='d1')(inputs)
output = tf.keras.layers.Dense(30, name='d2')(x)
model = tf.keras.Model(inputs, output)
d1 = model.layers[1]
d2 = model.layers[2]
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': d1.kernel,
# 'd1.bias': d1.bias,
# 'd2.kernel': d2.kernel,
# 'd2.bias': d2.bias,
# }
```
"""
result = {}
(
descendants,
object_paths_dict,
) = tf.__internal__.tracking.ObjectGraphView(
self
).breadth_first_traversal()
for descendant in descendants:
if isinstance(descendant, tf.Variable):
trackable_references = object_paths_dict[descendant]
object_path = ".".join([t.name for t in trackable_references])
result[object_path] = descendant
return result
def get_compile_config(self):
"""Returns a serialized config with information for compiling the model.
This method returns a config dictionary containing all the information
(optimizer, loss, metrics, etc.) with which the model was compiled.
Returns:
A dict containing information for compiling the model.
"""
if self._is_compiled and hasattr(self, "_compile_config"):
return self._compile_config.serialize()
def compile_from_config(self, config):
"""Compiles the model with the information given in config.
This method uses the information in the config (optimizer, loss,
metrics, etc.) to compile the model.
Args:
config: Dict containing information for compiling the model.
"""
has_overridden_compile = self.__class__.compile != Model.compile
if has_overridden_compile:
logging.warning(
"`compile()` was not called as part of model loading "
"because the model's `compile()` method is custom. "
"All subclassed Models that have `compile()` "
"overridden should also override "
"`get_compile_config()` and `compile_from_config(config)`. "
"Alternatively, you can "
"call `compile()` manually after loading."
)
return
config = saving_lib.deserialize_keras_object(config)
self.compile(**config)
if (
hasattr(self, "optimizer")
# Exempt legacy optimizers.
and isinstance(self.optimizer, optimizer.Optimizer)
and self.built
):
# Create optimizer variables.
self.optimizer.build(self.trainable_variables)
def export(self, filepath):
"""Create a SavedModel artifact for inference (e.g. via TF-Serving).
This method lets you export a model to a lightweight SavedModel artifact
that contains the model's forward pass only (its `call()` method)
and can be served via e.g. TF-Serving. The forward pass is registered
under the name `serve()` (see example below).
The original code of the model (including any custom layers you may
have used) is *no longer* necessary to reload the artifact -- it is
entirely standalone.
Args:
filepath: `str` or `pathlib.Path` object. Path where to save
the artifact.
Example:
```python
# Create the artifact
model.export("path/to/location")
# Later, in a different process / environment...
reloaded_artifact = tf.saved_model.load("path/to/location")
predictions = reloaded_artifact.serve(input_data)
```
If you would like to customize your serving endpoints, you can
use the lower-level `keras.export.ExportArchive` class. The `export()`
method relies on `ExportArchive` internally.
"""
from tf_keras.src.export import export_lib
export_lib.export_model(self, filepath)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _set_save_spec(self, inputs, args=None, kwargs=None):
"""Defines the save spec so that serialization can trace `call()`.
The TensorSpecs of the call function `inputs`, `args`, and `kwargs` are
saved into a tuple of `([inputs] + args, kwargs)`. The input
`TensorSpec` names are updated to match the built `input_names`.
The specs can be retrieved with the `save_spec` property.
Args:
inputs: possibly nested inputs passed into the call function.
args: a list of positional arguments passed into call.
kwargs: a dictionary of keyword arguments passed into call.
"""
if self._saved_model_inputs_spec is not None:
return # Already set.
args = args or []
kwargs = kwargs or {}
input_names = self.input_names
if not input_names:
input_names = compile_utils.create_pseudo_input_names(inputs)
flat_inputs = tf.nest.flatten(inputs)
inputs_spec = []
for name, tensor in zip(input_names, flat_inputs):
inputs_spec.append(
tf_utils.get_tensor_spec(tensor, dynamic_batch=False, name=name)
)
inputs_spec = tf.nest.pack_sequence_as(inputs, inputs_spec)
super()._set_save_spec(inputs_spec, args, kwargs)
# Store the input shapes
if (
self.__class__.__name__ == "Sequential"
and self._build_input_shape is None
):
self._build_input_shape = tf.nest.map_structure(
lambda x: None if x is None else x.shape, inputs_spec
)
def save_spec(self, dynamic_batch=True):
"""Returns the `tf.TensorSpec` of call args as a tuple `(args, kwargs)`.
This value is automatically defined after calling the model for the
first time. Afterwards, you can use it when exporting the model for
serving:
```python
model = tf.keras.Model(...)
@tf.function
def serve(*args, **kwargs):
outputs = model(*args, **kwargs)
# Apply postprocessing steps, or add additional outputs.
...
return outputs
# arg_specs is `[tf.TensorSpec(...), ...]`. kwarg_specs, in this
# example, is an empty dict since functional models do not use keyword
# arguments.
arg_specs, kwarg_specs = model.save_spec()
model.save(path, signatures={
'serving_default': serve.get_concrete_function(*arg_specs,
**kwarg_specs)
})
```
Args:
dynamic_batch: Whether to set the batch sizes of all the returned
`tf.TensorSpec` to `None`. (Note that when defining functional or
Sequential models with `tf.keras.Input([...], batch_size=X)`, the
batch size will always be preserved). Defaults to `True`.
Returns:
If the model inputs are defined, returns a tuple `(args, kwargs)`. All
elements in `args` and `kwargs` are `tf.TensorSpec`.
If the model inputs are not defined, returns `None`.
The model inputs are automatically set when calling the model,
`model.fit`, `model.evaluate` or `model.predict`.
"""
return self._get_save_spec(dynamic_batch, inputs_only=False)
def _assert_weights_created(self):
"""Asserts that all the weights for the model have been created.
For a non-dynamic model, the weights must already be created after the
layer has been called. For a dynamic model, the exact list of weights
can never be known for certain since it may change at any time during
execution.
We run this check right before accessing weights or getting the Numpy
value for the current weights. Otherwise, if the layer has never been
called, the user would just get an empty list, which is misleading.
Raises:
ValueError: if the weights of the network have not yet been created.
"""
if self.dynamic:
return
if (
"build" in self.__class__.__dict__
and self.__class__ != Model
and not self.built
):
# For any model that has customized build() method but hasn't been
# invoked yet, this will cover both sequential and subclass model.
# Also make sure to exclude Model class itself which has build()
# defined.
raise ValueError(
f"Weights for model '{self.name}' have not yet been "
"created. "
"Weights are created when the model is first called on "
"inputs or `build()` is called with an `input_shape`."
)
def _check_call_args(self, method_name):
"""Check that `call()` has only one positional arg."""
# Always allow first arg, regardless of arg name.
fullargspec = self._call_spec.full_argspec
if fullargspec.defaults:
positional_args = fullargspec.args[: -len(fullargspec.defaults)]
else:
positional_args = fullargspec.args
if "training" in positional_args:
positional_args.remove("training")
# self and first arg can be positional.
if len(positional_args) > 2:
extra_args = positional_args[2:]
raise ValueError(
f"Models passed to `{method_name}` can only have `training` "
"and the first argument in `call()` as positional arguments, "
f"found: {extra_args}."
)
def _validate_compile(self, optimizer, metrics, **kwargs):
"""Performs validation checks for the default `compile()`."""
if any(
isinstance(opt, optimizer_v1.Optimizer)
for opt in tf.nest.flatten(optimizer)
):
raise ValueError(
f"`tf.compat.v1.keras` Optimizer ({optimizer}) is "
"not supported when eager execution is enabled. Use a "
"`tf.keras` Optimizer instead, or disable eager "
"execution."
)
kwargs.pop("cloning", None) # Legacy DistStrat argument, never used.
kwargs.pop("experimental_run_tf_function", None) # Always `True`.
distribute_arg = kwargs.pop("distribute", None)
if distribute_arg is not None:
raise ValueError(
"`distribute` argument in compile is not available in TF 2.0. "
"Please create the model under the `strategy.scope()`. "
f"Received: {distribute_arg}."
)
target_tensor_arg = kwargs.pop("target_tensors", None)
if target_tensor_arg is not None:
raise ValueError(
"`target_tensors` argument is not supported when executing "
f"eagerly. Received: {target_tensor_arg}."
)
invalid_kwargs = set(kwargs) - {"sample_weight_mode"}
if invalid_kwargs:
raise TypeError(
"Invalid keyword argument(s) in `compile()`: "
f"{(invalid_kwargs,)}. Valid keyword arguments include "
'"cloning", "experimental_run_tf_function", "distribute",'
' "target_tensors", or "sample_weight_mode".'
)
# Model must be created and compiled with the same DistStrat.
if self.built and tf.distribute.has_strategy():
strategy = tf.distribute.get_strategy()
for v in self.variables:
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Variable ({v}) was not created in the distribution "
f"strategy scope of ({strategy}). It is most likely "
"because some layers, model, or optimizer was being "
"created outside the distribution strategy scope. Try "
"to make sure your code looks similar "
"to the following.\nwith strategy.scope():\n"
" model=_create_model()\n"
" model.compile(...)"
)
# Model metrics must be created in the same distribution strategy scope
# as the model.
strategy = self.distribute_strategy
for metric in tf.nest.flatten(metrics):
for v in getattr(metric, "variables", []):
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Metric ({metric}) passed to `model.compile` was "
"created inside a different distribution strategy "
"scope than the model. All metrics must be created "
"in the same distribution strategy "
f"scope as the model (in this case {strategy}). "
"If you pass in a string identifier for a metric to "
"compile, the metric will automatically be created "
"in the correct distribution strategy scope."
)
# Model metrics must be created in the same distribution strategy scope
# as the model.
for opt in tf.nest.flatten(optimizer):
for v in getattr(opt, "_weights", []):
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Optimizer ({optimizer}) passed to `model.compile` "
"was created inside a different distribution strategy "
"scope than the model. All optimizers must be created "
"in the same distribution strategy scope as the model "
f"(in this case {strategy}). If you pass in a string "
"identifier for an optimizer to compile, the optimizer "
"will automatically be created in the correct "
"distribution strategy scope."
)
def _maybe_load_initial_counters_from_ckpt(
self, steps_per_epoch, initial_epoch
):
"""Maybe load initial epoch from ckpt, considering worker recovery.
Refer to tensorflow/python/tf_keras/distribute/worker_training_state.py
for more information.
Args:
steps_per_epoch: The number of step per epoch.
initial_epoch: The original initial_epoch user passes in `fit()`.
mode: The mode for running `model.fit()`.
Returns:
If the training is recovering from previous failure under multi-worker
training setting, return the (epoch, step) the training is supposed to
continue at. Otherwise, return the `initial_epoch, initial_step` the
user passes in.
"""
initial_step = 0
if self._training_state is not None:
return self._training_state.maybe_load_initial_counters_from_ckpt(
steps_per_epoch, initial_epoch, mode=ModeKeys.TRAIN
)
return (initial_epoch, initial_step)
def _assert_compile_was_called(self):
# Checks whether `compile` has been called. If it has been called,
# then the optimizer is set. This is different from whether the
# model is compiled
# (i.e. whether the model is built and its inputs/outputs are set).
if not self._is_compiled:
raise RuntimeError(
"You must compile your model before "
"training/testing. "
"Use `model.compile(optimizer, loss)`."
)
def _check_sample_weight_warning(self, x, sample_weight):
# Datasets can include sample weight, by returning a tuple with the
# structure of `(x, y, sample_weight)`.
sample_weight_present = sample_weight is not None or (
isinstance(x, tf.data.Dataset)
and isinstance(x.element_spec, tuple)
and len(x.element_spec) == 3
)
if (
sample_weight_present
and self.compiled_metrics._user_weighted_metrics is None
):
logging.warning(
"`evaluate()` received a value for `sample_weight`, but "
"`weighted_metrics` were not provided. Did you mean to pass "
"metrics to `weighted_metrics` in `compile()`? If this is "
"intentional you can pass `weighted_metrics=[]` to `compile()` "
"in order to silence this warning."
)
def _set_inputs(self, inputs, outputs=None, training=None):
"""This method is for compat with Modelv1. Only inputs are needed
here."""
self._set_save_spec(inputs)
@property
def _trackable_saved_model_saver(self):
return model_serialization.ModelSavedModelSaver(self)
def _trackable_children(self, save_type="checkpoint", **kwargs):
if save_type == "savedmodel":
# SavedModel needs to ignore the execution functions.
train_function = self.train_function
test_function = self.test_function
predict_function = self.predict_function
train_tf_function = self.train_tf_function
self.train_function = None
self.test_function = None
self.predict_function = None
self.train_tf_function = None
children = super()._trackable_children(save_type, **kwargs)
if save_type == "savedmodel":
self.train_function = train_function
self.test_function = test_function
self.predict_function = predict_function
self.train_tf_function = train_tf_function
return children
def _should_eval(self, epoch, validation_freq):
epoch = epoch + 1 # one-index the user-facing epoch.
if isinstance(validation_freq, int):
return epoch % validation_freq == 0
elif isinstance(validation_freq, list):
return epoch in validation_freq
else:
raise ValueError(
"Expected `validation_freq` to be a list or int. "
f"Received: validation_freq={validation_freq} of the "
f"type {type(validation_freq)}."
)
######################################################################
# Functions below exist only as v1 / v2 compatibility shims.
######################################################################
def _get_compile_args(self, user_metrics=True):
"""Used for saving or cloning a Model.
Args:
user_metrics: Whether to return user-supplied metrics or `Metric`
objects. If True, returns the user-supplied metrics.
Defaults to `True`.
Returns:
Dictionary of arguments that were used when compiling the model.
"""
self._assert_compile_was_called()
saved_metrics = self.compiled_metrics._user_metrics
saved_weighted_metrics = self.compiled_metrics._user_weighted_metrics
if not user_metrics:
if saved_metrics is not None:
saved_metrics = self.compiled_metrics._metrics
if saved_weighted_metrics is not None:
saved_weighted_metrics = self.compiled_metrics._weighted_metrics
compile_args = {
"optimizer": self.optimizer,
"loss": self.compiled_loss._user_losses,
"metrics": saved_metrics,
"weighted_metrics": saved_weighted_metrics,
"loss_weights": self.compiled_loss._user_loss_weights,
}
return compile_args
def _get_callback_model(self):
return self
def _in_multi_worker_mode(self):
return self.distribute_strategy.extended._in_multi_worker_mode()
@property
def _compile_was_called(self):
return self._is_compiled
| (self, *args, **kwargs) |
|
724,905 | tf_keras.src.engine.training | __init__ | def __new__(cls, *args, **kwargs):
# Signature detection
if is_functional_model_init_params(args, kwargs) and cls == Model:
# Functional model
from tf_keras.src.engine import functional
return functional.Functional(skip_init=True, *args, **kwargs)
else:
return super(Model, cls).__new__(cls, *args, **kwargs)
| (self, *args, **kwargs) |
|
724,906 | tf_keras.src.engine.training | __new__ | null | def __new__(cls, *args, **kwargs):
# Signature detection
if is_functional_model_init_params(args, kwargs) and cls == Model:
# Functional model
from tf_keras.src.engine import functional
return functional.Functional(skip_init=True, *args, **kwargs)
else:
return super(Model, cls).__new__(cls, *args, **kwargs)
| (cls, *args, **kwargs) |
724,916 | tf_keras.src.engine.base_layer | _autographed_call | null | def _autographed_call(self):
# 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 self._should_use_autograph():
return tf.__internal__.autograph.tf_convert(
self.call, tf.__internal__.autograph.control_status_ctx()
)
return self.call
| (self) |
724,951 | tf_keras.src.engine.base_layer | _infer_output_signature | Call the layer on input KerasTensors, returns output KerasTensors. | def _infer_output_signature(self, inputs, args, kwargs, input_masks):
"""Call the layer on input KerasTensors, returns output KerasTensors."""
keras_tensor_inputs = inputs
call_fn = self.call
# 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 self._should_use_autograph():
call_fn = tf.__internal__.autograph.tf_convert(
self.call, tf.__internal__.autograph.control_status_ctx()
)
call_fn = traceback_utils.inject_argument_info_in_traceback(
call_fn,
object_name=f'layer "{self.name}" (type {self.__class__.__name__})',
)
# We enter a scratch graph and build placeholder inputs inside of it
# that match the input args.
# We then call the layer inside of the scratch graph to identify the
# output signatures, then we build KerasTensors corresponding to those
# outputs.
scratch_graph = tf.__internal__.FuncGraph(
str(self.name) + "_scratch_graph"
)
with scratch_graph.as_default():
inputs = tf.nest.map_structure(
keras_tensor.keras_tensor_to_placeholder, inputs
)
args = tf.nest.map_structure(
keras_tensor.keras_tensor_to_placeholder, args
)
kwargs = tf.nest.map_structure(
keras_tensor.keras_tensor_to_placeholder, kwargs
)
input_masks = tf.nest.map_structure(
keras_tensor.keras_tensor_to_placeholder, input_masks
)
with backend.name_scope(self._name_scope()):
with autocast_variable.enable_auto_cast_variables(
self._compute_dtype_object
):
# Build layer if applicable (if the `build` method has been
# overridden).
# TODO(kaftan): do we maybe_build here, or have we already
# done it?
self._maybe_build(inputs)
inputs = self._maybe_cast_inputs(inputs)
outputs = call_fn(inputs, *args, **kwargs)
self._handle_activity_regularization(inputs, outputs)
self._set_mask_metadata(
inputs, outputs, input_masks, build_graph=False
)
outputs = tf.nest.map_structure(
keras_tensor.keras_tensor_from_tensor, outputs
)
self._set_save_spec(keras_tensor_inputs, args, kwargs)
if hasattr(self, "_set_inputs") and not self.inputs:
# TODO(kaftan): figure out if we need to do this at all
# Subclassed network: explicitly set metadata normally set by
# a call to self._set_inputs().
self._set_inputs(inputs, outputs)
del scratch_graph
return outputs
| (self, inputs, args, kwargs, input_masks) |
724,955 | tf_keras.src.engine.base_layer | _instrument_layer_creation | null | def _instrument_layer_creation(self):
self._instrumented_keras_api = False
self._instrumented_keras_layer_class = False
self._instrumented_keras_model_class = False
if not getattr(self, "_disable_keras_instrumentation", False):
self._instrumented_keras_api = True
if getattr(self, "_is_model_for_instrumentation", False):
self._instrumented_keras_model_class = True
else:
self._instrumented_keras_layer_class = True
| (self) |
724,962 | tf_keras.src.engine.base_layer | _maybe_create_attribute | 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.
| @keras_export("keras.layers.Layer")
class Layer(tf.Module, version_utils.LayerVersionSelector):
"""This is the class from which all layers inherit.
A layer is a callable object that takes as input one or more tensors and
that outputs one or more tensors. It involves *computation*, defined
in the `call()` method, and a *state* (weight variables). State can be
created in various places, at the convenience of the subclass implementer:
* in `__init__()`;
* in the optional `build()` method, which is invoked by the first
`__call__()` to the layer, and supplies the shape(s) of the input(s),
which may not have been known at initialization time;
* in the first invocation of `call()`, with some caveats discussed
below.
Layers are recursively composable: If you assign a Layer instance as an
attribute of another Layer, the outer layer will start tracking the weights
created by the inner layer. Nested layers should be instantiated in the
`__init__()` method.
Users will just instantiate a layer and then treat it as a callable.
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. Can also be a
`tf.keras.mixed_precision.Policy`, which allows the computation and
weight dtype to differ. Default of `None` means to use
`tf.keras.mixed_precision.global_policy()`, which is a float32 policy
unless set to different value.
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 weights.
variable_dtype: Alias of `dtype`.
compute_dtype: The dtype of the layer's computations. Layers automatically
cast inputs to this dtype which causes the computations and output to
also be in this dtype. When mixed precision is used with a
`tf.keras.mixed_precision.Policy`, this will be different than
`variable_dtype`.
dtype_policy: The layer's dtype policy. See the
`tf.keras.mixed_precision.Policy` documentation for details.
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), i.e. whether
its potentially-trainable weights should be returned as part of
`layer.trainable_weights`.
input_spec: Optional (list of) `InputSpec` object(s) specifying the
constraints on inputs that can be accepted by the layer.
We recommend that descendants of `Layer` implement the following methods:
* `__init__()`: Defines custom layer attributes, and creates layer weights
that do not depend on input shapes, using `add_weight()`, or other state.
* `build(self, input_shape)`: This method can be used to create weights that
depend on the shape(s) of the input(s), using `add_weight()`, or other
state. `__call__()` will automatically build the layer (if it has not been
built yet) by calling `build()`.
* `call(self, inputs, *args, **kwargs)`: Called in `__call__` after making
sure `build()` has been called. `call()` performs the logic of applying
the layer to the `inputs`. The first invocation may additionally create
state that could not be conveniently created in `build()`; see its
docstring for details.
Two reserved keyword arguments you can optionally use in `call()` are:
- `training` (boolean, whether the call is in inference mode or training
mode). See more details in [the layer/model subclassing guide](
https://www.tensorflow.org/guide/keras/custom_layers_and_models#privileged_training_argument_in_the_call_method)
- `mask` (boolean tensor encoding masked timesteps in the input, used
in RNN layers). See more details in
[the layer/model subclassing guide](
https://www.tensorflow.org/guide/keras/custom_layers_and_models#privileged_mask_argument_in_the_call_method)
A typical signature for this method is `call(self, inputs)`, and user
could optionally add `training` and `mask` if the layer need them. `*args`
and `**kwargs` is only useful for future extension when more input
parameters are planned to be added.
* `get_config(self)`: Returns a dictionary containing the configuration used
to initialize this layer. If the keys differ from the arguments
in `__init__`, then override `from_config(self)` as well.
This method is used when saving
the layer or a model that contains this layer.
Examples:
Here's a basic example: a layer with two variables, `w` and `b`,
that returns `y = w . x + b`.
It shows how to implement `build()` and `call()`.
Variables set as attributes of a layer are tracked as weights
of the layers (in `layer.weights`).
```python
class SimpleDense(Layer):
def __init__(self, units=32):
super(SimpleDense, self).__init__()
self.units = units
def build(self, input_shape): # Create the state of the layer (weights)
w_init = tf.random_normal_initializer()
self.w = tf.Variable(
initial_value=w_init(shape=(input_shape[-1], self.units),
dtype='float32'),
trainable=True)
b_init = tf.zeros_initializer()
self.b = tf.Variable(
initial_value=b_init(shape=(self.units,), dtype='float32'),
trainable=True)
def call(self, inputs): # Defines the computation from inputs to outputs
return tf.matmul(inputs, self.w) + self.b
# Instantiates the layer.
linear_layer = SimpleDense(4)
# This will also call `build(input_shape)` and create the weights.
y = linear_layer(tf.ones((2, 2)))
assert len(linear_layer.weights) == 2
# These weights are trainable, so they're listed in `trainable_weights`:
assert len(linear_layer.trainable_weights) == 2
```
Note that the method `add_weight()` offers a shortcut to create weights:
```python
class SimpleDense(Layer):
def __init__(self, units=32):
super(SimpleDense, self).__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(shape=(input_shape[-1], self.units),
initializer='random_normal',
trainable=True)
self.b = self.add_weight(shape=(self.units,),
initializer='random_normal',
trainable=True)
def call(self, inputs):
return tf.matmul(inputs, self.w) + self.b
```
Besides trainable weights, updated via backpropagation during training,
layers can also have non-trainable weights. These weights are meant to
be updated manually during `call()`. Here's a example layer that computes
the running sum of its inputs:
```python
class ComputeSum(Layer):
def __init__(self, input_dim):
super(ComputeSum, self).__init__()
# Create a non-trainable weight.
self.total = tf.Variable(initial_value=tf.zeros((input_dim,)),
trainable=False)
def call(self, inputs):
self.total.assign_add(tf.reduce_sum(inputs, axis=0))
return self.total
my_sum = ComputeSum(2)
x = tf.ones((2, 2))
y = my_sum(x)
print(y.numpy()) # [2. 2.]
y = my_sum(x)
print(y.numpy()) # [4. 4.]
assert my_sum.weights == [my_sum.total]
assert my_sum.non_trainable_weights == [my_sum.total]
assert my_sum.trainable_weights == []
```
For more information about creating layers, see the guide
[Making new Layers and Models via subclassing](
https://www.tensorflow.org/guide/keras/custom_layers_and_models)
"""
@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.
if not (
isinstance(trainable, bool)
or (
isinstance(trainable, (tf.Tensor, tf.Variable))
and trainable.dtype is tf.bool
)
):
raise TypeError(
"Expected `trainable` argument to be a boolean, "
f"but got: {trainable}"
)
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. (Note that the first call() may also
# create weights, independent of build().)
self.built = False
# Provides information about which inputs are compatible with the layer.
self._input_spec = None
# SavedModel-related attributes.
# Record the build input shape for loading purposes.
# TODO(kathywu): Move this to Layer._set_save_spec once cl/290121460 is
# submitted.
self._build_input_shape = None
self._saved_model_inputs_spec = None
self._saved_model_arg_spec = None
# `Layer.compute_mask` will be called at the end of `Layer.__call__` if
# `Layer.compute_mask` is overridden, or if the `Layer` subclass sets
# `self.supports_masking=True`.
self._supports_masking = not generic_utils.is_default(self.compute_mask)
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 = []
# Ensures the same metric is not added multiple times in
# `MirroredStrategy`.
self._metrics_lock = threading.Lock()
# 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()
)
# Tracks `TrackableDataStructure`s, `Module`s, and `Layer`s.
# Ordered by when the object was assigned as an attr.
# Entries are unique.
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.
if not isinstance(dynamic, bool):
raise TypeError(
"Expected `dynamic` argument to be a boolean, "
f"but got: {dynamic}"
)
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 is 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 Sequential model.
self._auto_track_sub_layers = True
# For backwards 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
# Save outer name scope at layer declaration so that it is preserved at
# the actual layer construction.
self._name_scope_on_declaration = tf.get_current_name_scope()
# Save the temp regularization losses created in the DTensor use case.
# When DTensor is enable, we will first create LazyInitVariable and then
# DVariable with proper layout afterward. For the weights regularization
# loss, we have to create against the DVariable as well.
self._captured_weight_regularizer = []
@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. It is invoked automatically before
the first execution of `call()`.
This is typically used to create the weights of `Layer` subclasses
(at the discretion of the subclass implementer).
Args:
input_shape: Instance of `TensorShape`, or list of instances of
`TensorShape` if the layer expects a list of inputs
(one instance per input).
"""
self._build_input_shape = input_shape
self.built = True
@doc_controls.for_subclass_implementers
def call(self, inputs, *args, **kwargs):
"""This is where the layer's logic lives.
The `call()` method may not create state (except in its first
invocation, wrapping the creation of variables or other resources in
`tf.init_scope()`). It is recommended to create state, including
`tf.Variable` instances and nested `Layer` instances,
in `__init__()`, or in the `build()` method that is
called automatically before `call()` executes for the first time.
Args:
inputs: Input tensor, or dict/list/tuple of input tensors.
The first positional `inputs` argument is subject to special rules:
- `inputs` must be explicitly passed. A layer cannot have zero
arguments, and `inputs` cannot be provided via the default value
of a keyword argument.
- NumPy array or Python scalar values in `inputs` get cast as
tensors.
- TF-Keras mask metadata is only collected from `inputs`.
- Layers are built (`build(input_shape)` method)
using shape info from `inputs` only.
- `input_spec` compatibility is only checked against `inputs`.
- Mixed precision input casting is only applied to `inputs`.
If a layer has tensor arguments in `*args` or `**kwargs`, their
casting behavior in mixed precision should be handled manually.
- The SavedModel input specification is generated using `inputs`
only.
- Integration with various ecosystem packages like TFMOT, TFLite,
TF.js, etc is only supported for `inputs` and not for tensors in
positional and keyword arguments.
*args: Additional positional arguments. May contain tensors, although
this is not recommended, for the reasons above.
**kwargs: Additional keyword arguments. May contain tensors, although
this is not recommended, for the reasons above.
The following optional keyword arguments are reserved:
- `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, 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).
Returns:
A tensor or list/tuple of tensors.
"""
return inputs
@doc_controls.for_subclass_implementers
def add_weight(
self,
name=None,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
trainable=None,
constraint=None,
use_resource=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.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`.
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).
use_resource: Whether to use a `ResourceVariable` or not.
See [this guide](
https://www.tensorflow.org/guide/migrate/tf1_vs_tf2#resourcevariables_instead_of_referencevariables)
for more information.
synchronization: Indicates when a distributed a 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 variable created.
Raises:
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 = ()
kwargs.pop("partitioner", None) # Ignored.
# Validate optional keyword arguments.
for kwarg in kwargs:
if kwarg not in [
"collections",
"experimental_autocast",
"caching_device",
"getter",
"layout",
"experimental_enable_variable_lifting",
]:
raise TypeError("Unknown keyword argument:", kwarg)
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)
layout = kwargs.pop("layout", None)
# Specially handling of auto layout fetch, based on the variable name
# and attribute name. For built-in keras layers, usually the variable
# name, eg 'kernel', will match with a 'kernel_layout' attribute name on
# the instance. We will try to do this auto fetch if layout is not
# explicitly specified. This is mainly a quick workaround for not
# applying too many interface change to built-in layers, until DTensor
# is a public API. Also see dtensor.utils.allow_initializer_layout for
# more details.
# TODO(scottzhu): Remove this once dtensor is public to end user.
if not layout and name:
layout = getattr(self, name + "_layout", 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 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 = initializers.get("zeros")
# NOTES:Do we need to support for handling DT_STRING and DT_COMPLEX
# here?
elif "getter" not in kwargs:
# 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(
f"An initializer for variable {name} of type "
f"{dtype.base_dtype} is required for layer "
f"{self.name}. Received: {initializer}."
)
getter = kwargs.pop("getter", base_layer_utils.make_variable)
if (
autocast
and self._dtype_policy.compute_dtype
!= self._dtype_policy.variable_dtype
and dtype.is_floating
):
old_getter = getter
# Wrap variable constructor to return an AutoCastVariable.
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
if layout:
getter = functools.partial(getter, layout=layout)
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,
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
def __new__(cls, *args, **kwargs):
# Generate a config to be returned by default by `get_config()`.
arg_names = tf_inspect.getfullargspec(cls.__init__).args
kwargs.update(dict(zip(arg_names[1 : len(args) + 1], args)))
instance = super(Layer, cls).__new__(cls, *args, **kwargs)
# For safety, we only rely on auto-configs for a small set of
# serializable types.
supported_types = (str, int, float, bool, type(None))
try:
flat_arg_values = tf.nest.flatten(kwargs)
auto_get_config = True
for value in flat_arg_values:
if not isinstance(value, supported_types):
auto_get_config = False
break
except TypeError:
auto_get_config = False
try:
instance._auto_get_config = auto_get_config
if auto_get_config:
instance._auto_config = serialization_lib.Config(**kwargs)
except RecursionError:
# Setting an instance attribute in __new__ has the potential
# to trigger an infinite recursion if a subclass overrides
# setattr in an unsafe way.
pass
return instance
@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).
Note that `get_config()` does not guarantee to return a fresh copy of
dict every time it is called. The callers should make a copy of the
returned dict if they want to modify it.
Returns:
Python dictionary.
"""
config = {
"name": self.name,
"trainable": self.trainable,
}
config["dtype"] = policy.serialize(self._dtype_policy)
if hasattr(self, "_batch_input_shape"):
config["batch_input_shape"] = self._batch_input_shape
if not generic_utils.is_default(self.get_config):
# In this case the subclass implements get_config()
return config
# In this case the subclass doesn't implement get_config():
# Let's see if we can autogenerate it.
if getattr(self, "_auto_get_config", False):
xtra_args = set(config.keys())
config.update(self._auto_config.config)
# Remove args non explicitly supported
argspec = tf_inspect.getfullargspec(self.__init__)
if argspec.varkw != "kwargs":
for key in xtra_args - xtra_args.intersection(argspec.args[1:]):
config.pop(key, None)
return config
else:
raise NotImplementedError(
textwrap.dedent(
f"""
Layer {self.__class__.__name__} was created by passing
non-serializable argument values in `__init__()`,
and therefore the layer must override `get_config()` in
order to be serializable. Please implement `get_config()`.
Example:
class CustomLayer(keras.layers.Layer):
def __init__(self, arg1, arg2, **kwargs):
super().__init__(**kwargs)
self.arg1 = arg1
self.arg2 = arg2
def get_config(self):
config = super().get_config()
config.update({{
"arg1": self.arg1,
"arg2": self.arg2,
}})
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.
"""
try:
return cls(**config)
except Exception as e:
raise TypeError(
f"Error when deserializing class '{cls.__name__}' using "
f"config={config}.\n\nException encountered: {e}"
)
def compute_output_shape(self, input_shape):
"""Computes the output shape of the layer.
This method will cause the layer's state to be built, if that has not
happened before. This requires 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 `tf.TensorShape`,
or structure of shape tuples / `tf.TensorShape` instances
(one per output tensor of the layer).
Shape tuples can include None for free dimensions,
instead of an integer.
Returns:
A `tf.TensorShape` instance
or structure of `tf.TensorShape` instances.
"""
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)
graph_name = str(self.name) + "_scratch_graph"
with tf.__internal__.FuncGraph(graph_name).as_default():
input_shape = tf_utils.convert_shapes(
input_shape, to_tuples=False
)
def _make_placeholder_like(shape):
ph = backend.placeholder(shape=shape, dtype=self.dtype)
ph._keras_mask = None
return ph
inputs = tf.nest.map_structure(
_make_placeholder_like, 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(
"Please run in eager mode or implement the `compute_output_shape` "
"method on your layer (%s)." % self.__class__.__name__
)
@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. "
f"Received: {s}."
)
return s.shape
input_shape = tf.nest.map_structure(
check_type_return_shape, input_signature
)
output_shape = self.compute_output_shape(input_shape)
try:
dtype = self.output.dtype
except AttributeError:
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
@traceback_utils.filter_traceback
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.
- If the layer is not built, the method will call `build`.
Raises:
ValueError: if the layer's `call` method returns None (an invalid
value).
RuntimeError: if `super().__init__()` was not called in the
constructor.
"""
if not hasattr(self, "_thread_local"):
raise RuntimeError(
"You must call `super().__init__()` in the layer constructor."
)
# `inputs` (the first arg in the method spec) is special cased in
# layer call due to historical reasons.
# This special casing currently takes the form of:
# - 'inputs' must be explicitly passed. A layer cannot have zero
# arguments, and inputs cannot have been provided via the default
# value of a kwarg.
# - numpy/scalar values in `inputs` get converted to tensors
# - implicit masks / mask metadata are only collected from 'inputs`
# - Layers are built using shape info from 'inputs' only
# - input_spec compatibility is only checked against `inputs`
# - mixed precision casting (autocast) is only applied to `inputs`,
# not to any other argument.
inputs, args, kwargs = self._call_spec.split_out_first_arg(args, kwargs)
input_list = tf.nest.flatten(inputs)
# Functional Model construction mode is invoked when `Layer`s are called
# on symbolic `KerasTensor`s, i.e.:
# >> inputs = tf.keras.Input(10)
# >> outputs = MyLayer()(inputs) # Functional construction mode.
# >> model = tf.keras.Model(inputs, outputs)
if _in_functional_construction_mode(
self, inputs, args, kwargs, input_list
):
return self._functional_construction_call(
inputs, args, kwargs, input_list
)
# Maintains info about the `Layer.call` stack.
call_context = base_layer_utils.call_context()
# Accept NumPy and scalar inputs by converting to Tensors.
if any(
isinstance(x, (tf.Tensor, np.ndarray, float, int))
for x in input_list
):
inputs = tf.nest.map_structure(
_convert_numpy_or_python_types, 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.
input_masks, mask_is_implicit = self._get_input_masks(
inputs, input_list, args, kwargs
)
if self._expects_mask_arg and mask_is_implicit:
kwargs["mask"] = input_masks
# Training mode for `Layer.call` is set via (in order of priority):
# (1) The `training` argument passed to this `Layer.call`, if it is not
# None
# (2) The training mode of an outer `Layer.call`.
# (3) The default mode set by `tf.keras.backend.set_learning_phase` (if
# set)
# (4) Any non-None default value for `training` specified in the call
# signature
# (5) False (treating the layer as if it's in inference)
args, kwargs, training_mode = self._set_training_mode(
args, kwargs, call_context
)
# Losses are cleared for all sublayers on the outermost `Layer.call`.
# Losses are not cleared on inner `Layer.call`s, because sublayers can
# be called multiple times.
if not call_context.in_call:
self._clear_losses()
eager = tf.executing_eagerly()
with call_context.enter(
layer=self,
inputs=inputs,
build_graph=not eager,
training=training_mode,
):
input_spec.assert_input_compatibility(
self.input_spec, inputs, self.name
)
if eager:
call_fn = self.call
name_scope = self._name
else:
name_scope = self._get_unnested_name_scope()
call_fn = self._autographed_call()
call_fn = traceback_utils.inject_argument_info_in_traceback(
call_fn,
object_name=(
f"layer '{self.name}' (type {self.__class__.__name__})"
),
)
with contextlib.ExitStack() as namescope_stack:
if _is_name_scope_on_model_declaration_enabled:
namescope_stack.enter_context(
_name_scope_unnester(self._name_scope_on_declaration)
)
namescope_stack.enter_context(tf.name_scope(name_scope))
if not self.built:
self._maybe_build(inputs)
if self._autocast:
inputs = self._maybe_cast_inputs(inputs, input_list)
with autocast_variable.enable_auto_cast_variables(
self._compute_dtype_object
):
outputs = call_fn(inputs, *args, **kwargs)
if self._activity_regularizer:
self._handle_activity_regularization(inputs, outputs)
if self._supports_masking:
self._set_mask_metadata(
inputs, outputs, input_masks, not eager
)
if self._saved_model_inputs_spec is None:
self._set_save_spec(inputs, args, kwargs)
return outputs
def _get_unnested_name_scope(self):
if _is_name_scope_on_model_declaration_enabled:
with _name_scope_unnester(
self._name_scope_on_declaration
) as relative_name_scope_on_declaration:
# To avoid `tf.name_scope` autoincrement, use absolute path.
relative_name_scope = filter(
None,
[
tf.get_current_name_scope(),
relative_name_scope_on_declaration,
],
)
current_name_scope = "/".join(relative_name_scope) + "/"
if current_name_scope == "/":
current_name_scope = self._name_scope_on_declaration
with tf.name_scope(current_name_scope):
name_scope = self._name_scope() # Avoid autoincrementing.
else:
name_scope = self._name_scope()
return name_scope
@property
def dtype(self):
"""The dtype of the layer weights.
This is equivalent to `Layer.dtype_policy.variable_dtype`. Unless
mixed precision is used, this is the same as `Layer.compute_dtype`, the
dtype of the layer's computations.
"""
return self._dtype_policy.variable_dtype
@property
def name(self):
"""Name of the layer (string), set in the constructor."""
return self._name
@property
def supports_masking(self):
"""Whether this layer supports computing a mask using `compute_mask`."""
return self._supports_masking
@supports_masking.setter
def supports_masking(self, value):
self._supports_masking = value
@property
def dynamic(self):
"""Whether the layer is dynamic (eager-only); set in the constructor."""
return any(layer._dynamic for layer in self._flatten_layers())
@property
@doc_controls.do_not_doc_inheritable
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):
"""Sets trainable attribute for the layer and its sublayers.
When this value is changed during training (e.g. with a
`tf.keras.callbacks.Callback`) you need to call the parent
`tf.keras.Model.make_train_function` with `force=True` in order to
recompile the training graph.
Args:
value: Boolean with the desired state for the layer's trainable
attribute.
"""
for layer in self._flatten_layers():
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):
"""`InputSpec` instance(s) describing the input format for this layer.
When you create a layer subclass, you can set `self.input_spec` to
enable the layer to run input compatibility checks when it is called.
Consider a `Conv2D` layer: it can only be called on a single input
tensor of rank 4. As such, you can set, in `__init__()`:
```python
self.input_spec = tf.keras.layers.InputSpec(ndim=4)
```
Now, if you try to call the layer on an input that isn't rank 4
(for instance, an input of shape `(2,)`, it will raise a
nicely-formatted error:
```
ValueError: Input 0 of layer conv2d is incompatible with the layer:
expected ndim=4, found ndim=1. Full shape received: [2]
```
Input checks that can be specified via `input_spec` include:
- Structure (e.g. a single input, a list of 2 inputs, etc)
- Shape
- Rank (ndim)
- Dtype
For more information, see `tf.keras.layers.InputSpec`.
Returns:
A `tf.keras.layers.InputSpec` instance, or nested structure thereof.
"""
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 not isinstance(v, input_spec.InputSpec):
raise TypeError(
"Layer input_spec must be an instance of InputSpec. "
"Got: {}".format(v)
)
self._input_spec = value
@property
def trainable_weights(self):
"""List of all trainable weights tracked by this layer.
Trainable weights are updated via gradient descent during training.
Returns:
A list of trainable variables.
"""
self._update_trackables()
if self.trainable:
children_weights = self._gather_children_attribute(
"trainable_variables"
)
return self._dedup_weights(
self._trainable_weights + children_weights
)
else:
return []
@property
def non_trainable_weights(self):
"""List of all non-trainable weights tracked by this layer.
Non-trainable weights are *not* updated during training. They are
expected to be updated manually in `call()`.
Returns:
A list of non-trainable variables.
"""
self._update_trackables()
if self.trainable:
children_weights = self._gather_children_attribute(
"non_trainable_variables"
)
non_trainable_weights = (
self._non_trainable_weights + children_weights
)
else:
children_weights = self._gather_children_attribute("variables")
non_trainable_weights = (
self._trainable_weights
+ self._non_trainable_weights
+ children_weights
)
return self._dedup_weights(non_trainable_weights)
@property
def weights(self):
"""Returns the list of all layer variables/weights.
Returns:
A list of variables.
"""
return self.trainable_weights + self.non_trainable_weights
@property
@doc_controls.do_not_generate_docs
def updates(self):
warnings.warn(
"`layer.updates` will be removed in a future version. "
"This property should not be used in TensorFlow 2.0, "
"as `updates` are applied automatically.",
stacklevel=2,
)
return []
@property
def losses(self):
"""List of losses added using the `add_loss()` API.
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.
Examples:
>>> class MyLayer(tf.keras.layers.Layer):
... def call(self, inputs):
... self.add_loss(tf.abs(tf.reduce_mean(inputs)))
... return inputs
>>> l = MyLayer()
>>> l(np.ones((10, 1)))
>>> l.losses
[1.0]
>>> 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.
>>> len(model.losses)
0
>>> model.add_loss(tf.abs(tf.reduce_mean(x)))
>>> len(model.losses)
1
>>> inputs = tf.keras.Input(shape=(10,))
>>> d = tf.keras.layers.Dense(10, kernel_initializer='ones')
>>> x = d(inputs)
>>> outputs = tf.keras.layers.Dense(1)(x)
>>> model = tf.keras.Model(inputs, outputs)
>>> # Weight regularization.
>>> model.add_loss(lambda: tf.reduce_mean(d.kernel))
>>> model.losses
[<tf.Tensor: shape=(), dtype=float32, numpy=1.0>]
Returns:
A list of tensors.
"""
collected_losses = []
for layer in self._flatten_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.
if layer._eager_losses:
# Filter placeholder losses that may have been added by revived
# layers. (see base_layer_utils for details).
if (
layer._eager_losses[0]
is not base_layer_utils.REVIVED_LOSS_PLACEHOLDER
):
collected_losses.extend(layer._eager_losses)
else:
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
def add_loss(self, losses, **kwargs):
"""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(self, inputs):
self.add_loss(tf.abs(tf.reduce_mean(inputs)))
return inputs
```
The same code works in distributed training: the input to `add_loss()`
is treated like a regularization loss and averaged across replicas
by the training loop (both built-in `Model.fit()` and compliant custom
training loops).
The `add_loss` 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,))
d = tf.keras.layers.Dense(10)
x = d(inputs)
outputs = tf.keras.layers.Dense(1)(x)
model = tf.keras.Model(inputs, outputs)
# Weight regularization.
model.add_loss(lambda: tf.reduce_mean(d.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.
**kwargs: Used for backwards compatibility only.
"""
kwargs.pop("inputs", None)
if kwargs:
raise TypeError(f"Unknown keyword arguments: {kwargs.keys()}")
def _tag_callable(loss):
"""Tags callable loss tensor as `_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 = True
return loss
losses = tf.nest.flatten(losses)
callable_losses = []
eager_losses = []
symbolic_losses = []
for loss in losses:
if callable(loss):
callable_losses.append(functools.partial(_tag_callable, loss))
continue
if loss is None:
continue
if not tf.is_tensor(loss) and not isinstance(
loss, keras_tensor.KerasTensor
):
loss = tf.convert_to_tensor(loss, dtype=backend.floatx())
# TF Functions should take the eager path.
if (
tf_utils.is_symbolic_tensor(loss)
or isinstance(loss, keras_tensor.KerasTensor)
) and not base_layer_utils.is_in_tf_function():
symbolic_losses.append(loss)
elif tf.is_tensor(loss):
eager_losses.append(loss)
self._callable_losses.extend(callable_losses)
in_call_context = base_layer_utils.call_context().in_call
if eager_losses and not in_call_context:
raise ValueError(
"Expected a symbolic Tensors or a callable for the loss value. "
"Please wrap your loss computation in a zero argument `lambda`."
)
self._eager_losses.extend(eager_losses)
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):
"""List of metrics attached to the layer.
Returns:
A list of `Metric` objects.
"""
collected_metrics = []
for layer in self._flatten_layers():
if not hasattr(layer, "_metrics_lock"):
continue
with layer._metrics_lock:
collected_metrics.extend(layer._metrics)
return collected_metrics
@doc_controls.do_not_generate_docs
def add_metric(self, value, name=None, **kwargs):
"""Adds metric tensor to the layer.
This method can be used inside the `call()` method of a subclassed layer
or model.
```python
class MyMetricLayer(tf.keras.layers.Layer):
def __init__(self):
super(MyMetricLayer, self).__init__(name='my_metric_layer')
self.mean = tf.keras.metrics.Mean(name='metric_1')
def call(self, inputs):
self.add_metric(self.mean(inputs))
self.add_metric(tf.reduce_sum(inputs), name='metric_2')
return inputs
```
This method can also be called directly on a Functional Model during
construction. In this case, any tensor passed to this Model must
be symbolic and be able to be traced back to the model's `Input`s. These
metrics become part of the model's topology and are tracked when you
save the model via `save()`.
```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)
model.add_metric(math_ops.reduce_sum(x), name='metric_1')
```
Note: Calling `add_metric()` with the result of a metric object on a
Functional Model, as shown in the example below, is not supported. This
is because we cannot trace the metric result tensor back to the model's
inputs.
```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)
model.add_metric(tf.keras.metrics.Mean()(x), name='metric_1')
```
Args:
value: Metric tensor.
name: String metric name.
**kwargs: Additional keyword arguments for backward compatibility.
Accepted values:
`aggregation` - When the `value` tensor provided is not the result
of calling a `keras.Metric` instance, it will be aggregated by
default using a `keras.Metric.Mean`.
"""
kwargs_keys = list(kwargs.keys())
if len(kwargs_keys) > 1 or (
len(kwargs_keys) == 1 and kwargs_keys[0] != "aggregation"
):
raise TypeError(
f"Unknown keyword arguments: {kwargs.keys()}. "
"Expected `aggregation`."
)
from_metric_obj = hasattr(value, "_metric_obj")
is_symbolic = isinstance(value, keras_tensor.KerasTensor)
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))` 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')`"
)
elif from_metric_obj:
name = value._metric_obj.name
if not in_call_context and not is_symbolic:
raise ValueError(
"Expected a symbolic Tensor for the metric value, received: "
+ str(value)
)
# If a metric was added in a Layer's `call` or `build`.
if in_call_context or not getattr(self, "_is_graph_network", False):
# TF Function path should take the eager path.
# If the given metric is available in `metrics` list we just update
# state on it, otherwise we create a new metric instance and
# add it to the `metrics` list.
metric_obj = getattr(value, "_metric_obj", None)
# Tensors that come from a Metric object already updated the Metric
# state.
should_update_state = not metric_obj
name = metric_obj.name if metric_obj else name
with self._metrics_lock:
match = self._get_existing_metric(name)
if match:
metric_obj = match
elif metric_obj:
self._metrics.append(metric_obj)
else:
# Build the metric object with the value's dtype if it
# defines one
metric_obj = metrics_mod.Mean(
name=name, dtype=getattr(value, "dtype", None)
)
self._metrics.append(metric_obj)
if should_update_state:
metric_obj(value)
else:
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.
aggregation = None if from_metric_obj else "mean"
self._graph_network_add_metric(value, aggregation, name)
@doc_controls.do_not_doc_inheritable
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.
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()
# No need to run updates during Functional API construction.
if call_context.in_keras_graph:
return
# Callable updates are disabled by setting `trainable=False`.
if not call_context.frozen:
for update in tf.nest.flatten(updates):
if callable(update):
update()
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: the kernel
matrix and the bias vector. These can be used to set the weights of
another `Dense` layer:
>>> layer_a = tf.keras.layers.Dense(1,
... kernel_initializer=tf.constant_initializer(1.))
>>> a_out = layer_a(tf.convert_to_tensor([[1., 2., 3.]]))
>>> layer_a.get_weights()
[array([[1.],
[1.],
[1.]], dtype=float32), array([0.], dtype=float32)]
>>> layer_b = tf.keras.layers.Dense(1,
... kernel_initializer=tf.constant_initializer(2.))
>>> b_out = layer_b(tf.convert_to_tensor([[10., 20., 30.]]))
>>> layer_b.get_weights()
[array([[2.],
[2.],
[2.]], dtype=float32), array([0.], dtype=float32)]
>>> layer_b.set_weights(layer_a.get_weights())
>>> layer_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(
f"Layer {self.name} weight shape {ref_shape} "
"is not compatible with provided weight "
f"shape {weight_shape}."
)
weight_value_tuples.append((param, weight))
weight_index += 1
backend.batch_set_value(weight_value_tuples)
# Perform any layer defined finalization of the layer state.
for layer in self._flatten_layers():
layer.finalize_state()
def get_weights(self):
"""Returns the current weights of the layer, as NumPy arrays.
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: the kernel
matrix and the bias vector. These can be used to set the weights of
another `Dense` layer:
>>> layer_a = tf.keras.layers.Dense(1,
... kernel_initializer=tf.constant_initializer(1.))
>>> a_out = layer_a(tf.convert_to_tensor([[1., 2., 3.]]))
>>> layer_a.get_weights()
[array([[1.],
[1.],
[1.]], dtype=float32), array([0.], dtype=float32)]
>>> layer_b = tf.keras.layers.Dense(1,
... kernel_initializer=tf.constant_initializer(2.))
>>> b_out = layer_b(tf.convert_to_tensor([[10., 20., 30.]]))
>>> layer_b.get_weights()
[array([[2.],
[2.],
[2.]], dtype=float32), array([0.], dtype=float32)]
>>> layer_b.set_weights(layer_a.get_weights())
>>> layer_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)
@doc_controls.do_not_generate_docs
def finalize_state(self):
"""Finalizes the layers state after updating layer weights.
This function can be subclassed in a layer and will be called after
updating a layer weights. It can be overridden to finalize any
additional layer state after a weight update.
This function will be called after weights of a layer have been restored
from a loaded model.
"""
pass
@doc_controls.do_not_doc_inheritable
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)
@doc_controls.do_not_doc_inheritable
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
@doc_controls.do_not_doc_inheritable
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
@doc_controls.do_not_doc_inheritable
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)
@doc_controls.do_not_doc_inheritable
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"
)
@doc_controls.do_not_doc_inheritable
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"
)
@doc_controls.do_not_doc_inheritable
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"
)
@doc_controls.do_not_doc_inheritable
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
@doc_controls.do_not_doc_inheritable
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` "
f"on layer {self.name}"
", but the layer isn't built. "
"You can build it manually via: "
f"`{self.name}.build(batch_input_shape)`."
)
return layer_utils.count_params(self.weights)
@property
@doc_controls.do_not_doc_inheritable
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(
f'The layer "{self.name}" 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
def dtype_policy(self):
"""The dtype policy associated with this layer.
This is an instance of a `tf.keras.mixed_precision.Policy`.
"""
return self._dtype_policy
@property
def compute_dtype(self):
"""The dtype of the layer's computations.
This is equivalent to `Layer.dtype_policy.compute_dtype`. Unless
mixed precision is used, this is the same as `Layer.dtype`, the dtype of
the weights.
Layers automatically cast their inputs to the compute dtype, which
causes computations and the output to be in the compute dtype as well.
This is done by the base Layer class in `Layer.__call__`, so you do not
have to insert these casts if implementing your own layer.
Layers often perform certain internal computations in higher precision
when `compute_dtype` is float16 or bfloat16 for numeric stability. The
output will still typically be float16 or bfloat16 in such cases.
Returns:
The layer's compute dtype.
"""
return self._dtype_policy.compute_dtype
@property
def variable_dtype(self):
"""Alias of `Layer.dtype`, the dtype of the weights."""
return self.dtype
@property
@doc_controls.do_not_doc_inheritable
def inbound_nodes(self):
"""Return Functional API nodes upstream of this layer."""
return self._inbound_nodes
@property
@doc_controls.do_not_doc_inheritable
def outbound_nodes(self):
"""Return Functional API nodes downstream of this layer."""
return self._outbound_nodes
############################################################################
# Methods & attributes below are public aliases of other methods. #
############################################################################
@property
@doc_controls.do_not_generate_docs
def variables(self):
"""Returns the list of all layer variables/weights.
Alias of `self.weights`.
Note: This will not track the weights of nested `tf.Modules` that are
not themselves TF-Keras layers.
Returns:
A list of variables.
"""
return self.weights
@property
@doc_controls.do_not_generate_docs
def trainable_variables(self):
return self.trainable_weights
@property
@doc_controls.do_not_generate_docs
def non_trainable_variables(self):
return self.non_trainable_weights
@doc_controls.do_not_doc_inheritable
def add_variable(self, *args, **kwargs):
"""Deprecated, do NOT use! Alias for `add_weight`."""
warnings.warn(
"`layer.add_variable` is deprecated and "
"will be removed in a future version. "
"Please use the `layer.add_weight()` method instead.",
stacklevel=2,
)
return self.add_weight(*args, **kwargs)
def get_build_config(self):
"""Returns a dictionary with the layer's input shape.
This method returns a config dict that can be used by
`build_from_config(config)` to create all states (e.g. Variables and
Lookup tables) needed by the layer.
By default, the config only contains the input shape that the layer
was built with. If you're writing a custom layer that creates state in
an unusual way, you should override this method to make sure this state
is already created when TF-Keras attempts to load its value upon model
loading.
Returns:
A dict containing the input shape associated with the layer.
"""
if self._build_input_shape is not None:
def convert_tensorshapes(x):
if isinstance(x, tf.TensorShape) and x._dims:
return tuple(x.as_list())
return x
return {
"input_shape": tf.nest.map_structure(
convert_tensorshapes, self._build_input_shape
)
}
def build_from_config(self, config):
"""Builds the layer's states with the supplied config dict.
By default, this method calls the `build(config["input_shape"])` method,
which creates weights based on the layer's input shape in the supplied
config. If your config contains other information needed to load the
layer's state, you should override this method.
Args:
config: Dict containing the input shape associated with this layer.
"""
input_shape = config["input_shape"]
if input_shape is not None:
self.build(input_shape)
############################################################################
# Methods & attributes below are all private and only used by the framework.
############################################################################
# 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,
)
)
# When loading from a SavedModel, Layers typically can be revived into a
# generic Layer wrapper. Sometimes, however, layers may implement methods
# that go beyond this wrapper, as in the case of PreprocessingLayers'
# `adapt` method. When this is the case, layer implementers can override
# must_restore_from_config to return True; layers with this property must
# be restored into their actual objects (and will fail if the object is
# not available to the restoration code).
_must_restore_from_config = False
def _get_cell_name(self):
canonical_name = get_canonical_name_for_symbol(
self.__class__, api_name="keras", add_prefix_to_v1_names=True
)
if canonical_name is not None:
return f"tf.{canonical_name}"
return self.__class__.__module__ + "." + self.__class__.__name__
def _instrument_layer_creation(self):
self._instrumented_keras_api = False
self._instrumented_keras_layer_class = False
self._instrumented_keras_model_class = False
if not getattr(self, "_disable_keras_instrumentation", False):
self._instrumented_keras_api = True
if getattr(self, "_is_model_for_instrumentation", False):
self._instrumented_keras_model_class = True
else:
self._instrumented_keras_layer_class = True
@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
def _clear_losses(self):
"""Used every step in eager to reset losses."""
# Set to thread local directly to avoid Layer.__setattr__ overhead.
if not getattr(
self, "_self_tracked_trackables", None
): # Fast path for single Layer.
self._thread_local._eager_losses = []
else:
for layer in self._flatten_layers():
layer._thread_local._eager_losses = []
def _keras_tensor_symbolic_call(self, inputs, input_masks, args, kwargs):
if self.dynamic:
# 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.
input_signature = tf.nest.map_structure(
lambda x: tf.TensorSpec(shape=x.shape, dtype=x.dtype), inputs
)
output_signature = self.compute_output_signature(input_signature)
return tf.nest.map_structure(
keras_tensor.KerasTensor, output_signature
)
else:
return self._infer_output_signature(
inputs, args, kwargs, input_masks
)
def _should_use_autograph(self):
if base_layer_utils.from_saved_model(self):
return False
if base_layer_utils.is_subclassed(self):
return True
return False
def _infer_output_signature(self, inputs, args, kwargs, input_masks):
"""Call the layer on input KerasTensors, returns output KerasTensors."""
keras_tensor_inputs = inputs
call_fn = self.call
# 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 self._should_use_autograph():
call_fn = tf.__internal__.autograph.tf_convert(
self.call, tf.__internal__.autograph.control_status_ctx()
)
call_fn = traceback_utils.inject_argument_info_in_traceback(
call_fn,
object_name=f'layer "{self.name}" (type {self.__class__.__name__})',
)
# We enter a scratch graph and build placeholder inputs inside of it
# that match the input args.
# We then call the layer inside of the scratch graph to identify the
# output signatures, then we build KerasTensors corresponding to those
# outputs.
scratch_graph = tf.__internal__.FuncGraph(
str(self.name) + "_scratch_graph"
)
with scratch_graph.as_default():
inputs = tf.nest.map_structure(
keras_tensor.keras_tensor_to_placeholder, inputs
)
args = tf.nest.map_structure(
keras_tensor.keras_tensor_to_placeholder, args
)
kwargs = tf.nest.map_structure(
keras_tensor.keras_tensor_to_placeholder, kwargs
)
input_masks = tf.nest.map_structure(
keras_tensor.keras_tensor_to_placeholder, input_masks
)
with backend.name_scope(self._name_scope()):
with autocast_variable.enable_auto_cast_variables(
self._compute_dtype_object
):
# Build layer if applicable (if the `build` method has been
# overridden).
# TODO(kaftan): do we maybe_build here, or have we already
# done it?
self._maybe_build(inputs)
inputs = self._maybe_cast_inputs(inputs)
outputs = call_fn(inputs, *args, **kwargs)
self._handle_activity_regularization(inputs, outputs)
self._set_mask_metadata(
inputs, outputs, input_masks, build_graph=False
)
outputs = tf.nest.map_structure(
keras_tensor.keras_tensor_from_tensor, outputs
)
self._set_save_spec(keras_tensor_inputs, args, kwargs)
if hasattr(self, "_set_inputs") and not self.inputs:
# TODO(kaftan): figure out if we need to do this at all
# Subclassed network: explicitly set metadata normally set by
# a call to self._set_inputs().
self._set_inputs(inputs, outputs)
del scratch_graph
return outputs
def _functional_construction_call(self, inputs, args, kwargs, input_list):
call_context = base_layer_utils.call_context()
# Accept NumPy and scalar inputs by converting to Tensors.
if any(
isinstance(x, (tf.Tensor, 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, (tf.Tensor, 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, mask_is_implicit = self._get_input_masks(
inputs, input_list, args, kwargs
)
if self._expects_mask_arg and mask_is_implicit:
kwargs["mask"] = input_masks
mask_arg_passed_by_framework = True
# 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 a non-None value.
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 3: `learning_phase()` has been set.
elif backend.global_learning_phase_is_set():
training_value = backend.learning_phase()
# 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)
# Priority 4: trace layer with the default training argument
# specified in the `call` signature (or in inference mode if the
# `call` signature specifies no non-None default).
else:
training_value = self._call_spec.default_training_arg
# In cases (2), (3), (4) the training argument is passed
# automatically by the framework, and will not be hard-coded into
# the model.
if self._expects_training_arg:
args, kwargs = self._call_spec.set_arg_value(
"training", training_value, args, kwargs
)
training_arg_passed_by_framework = True
with call_context.enter(
layer=self, inputs=inputs, build_graph=True, training=training_value
):
# Check input assumptions set after layer building, e.g. input
# shape.
try:
outputs = self._keras_tensor_symbolic_call(
inputs, input_masks, args, kwargs
)
except TypeError as e:
if "DictWrapper" in str(e):
raise TypeError(
f"{self} could not be deserialized properly. Please"
" ensure that components that are Python object"
" instances (layers, models, etc.) returned by"
" `get_config()` are explicitly deserialized in the"
" model's `from_config()` method."
) from e
else:
raise e
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 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")
# Node connectivity does not special-case the first argument.
outputs = self._set_connectivity_metadata(
(inputs,) + args, kwargs, outputs
)
return outputs
def _set_training_mode(self, args, kwargs, call_context):
training_mode = None
if self._expects_training_arg:
# (1) `training` was passed to this `Layer.call`.
if self._call_spec.arg_was_passed("training", args, kwargs):
training_mode = self._call_spec.get_arg_value(
"training", args, kwargs
)
# If no `training` arg was passed, or `None` was explicitly passed,
# the framework will make a decision about the training mode is.
if training_mode is None:
call_ctx_training = call_context.training
# (2) `training` mode is inferred from an outer `Layer.call`.
if call_ctx_training is not None:
training_mode = call_ctx_training
# (3) User set `tf.keras.backend.set_learning_phase`.
elif backend.global_learning_phase_is_set():
training_mode = backend.learning_phase()
# Ensure value is a `bool` or `tf.bool`.
if isinstance(training_mode, bool):
pass
elif tf.is_tensor(training_mode):
training_mode = tf.cast(training_mode, tf.bool)
else:
training_mode = bool(training_mode)
# (4) We default to using `call`'s default value for `training`,
# or treating the layer as if it is in inference if no non-None
# default is specified in the `call` signature.
else:
training_mode = self._call_spec.default_training_arg
# For case (2), (3), (4) `training` arg is passed by framework.
args, kwargs = self._call_spec.set_arg_value(
"training", training_mode, args, kwargs
)
else:
if "training" in kwargs:
# `training` was passed to this `Layer` but is not needed for
# `Layer.call`. It will set the default mode for inner
# `Layer.call`s.
training_mode = kwargs.pop("training")
else:
# Grab the current `training` mode from any outer `Layer.call`.
training_mode = call_context.training
return args, kwargs, training_mode
def _autographed_call(self):
# 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 self._should_use_autograph():
return tf.__internal__.autograph.tf_convert(
self.call, tf.__internal__.autograph.control_status_ctx()
)
return self.call
@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."""
self._dtype_policy = policy.get_policy(dtype)
# Performance optimization: cache the compute dtype as a Dtype object or
# None, so that str to Dtype conversion doesn't happen in
# Layer.__call__.
# TODO(b/157486353): Investigate returning DTypes in Policy.
if self._dtype_policy.compute_dtype:
self._compute_dtype_object = tf.as_dtype(
self._dtype_policy.compute_dtype
)
else:
self._compute_dtype_object = None
@property
def _compute_dtype(self):
"""Deprecated alias of `compute_dtype`."""
return self._dtype_policy.compute_dtype
def _maybe_cast_inputs(self, inputs, input_list=None):
"""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.
input_list: Flat list of input tensors.
Returns:
`inputs`, but tensors may have been casted to self._compute_dtype
"""
if not input_list:
input_list = tf.nest.flatten(inputs)
compute_dtype_object = self._compute_dtype_object
should_autocast = (
self._autocast
and compute_dtype_object
and compute_dtype_object.is_floating
)
if should_autocast and any(
map(self._should_cast_single_input, input_list)
):
# Only perform expensive `nest` operation when needed.
return tf.nest.map_structure(self._cast_single_input, inputs)
else:
return inputs
def _should_cast_single_input(self, x):
if isinstance(x, _AUTOCAST_TYPES):
return (
self._compute_dtype_object
and x.dtype != self._compute_dtype_object
and x.dtype.is_floating
)
return False
def _cast_single_input(self, x):
"""Cast a single Tensor or TensorSpec to the compute dtype."""
if self._should_cast_single_input(x):
return tf.cast(x, self._compute_dtype_object)
else:
return x
# _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):
if not tf.__internal__.tf2.enabled():
return self.name
name_scope = self.name
current_name_scope = tf.__internal__.get_name_scope()
if current_name_scope:
name_scope = current_name_scope + "/" + name_scope
if name_scope:
# Note that the trailing `/` prevents autogenerated
# numerical suffixes to get appended. It will also fully reset
# nested name scope (i.e. the outer name scope has no effect).
name_scope += "/"
return name_scope
def _init_set_name(self, name, zero_based=True):
if name is None:
self._name = backend.unique_object_name(
generic_utils.to_snake_case(self.__class__.__name__),
zero_based=zero_based,
)
elif isinstance(name, str):
backend.observe_object_name(name)
self._name = name
else:
raise TypeError(
f"Expected `name` argument to be a string, but got: {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 _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))
elif isinstance(variable, lazy_variable.LazyInitVariable):
self._captured_weight_regularizer.append(
(name, variable, regularizer)
)
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.shape(output)[0], activity_loss.dtype
)
# Make activity regularization strength batch-agnostic.
mean_activity_loss = tf.math.divide_no_nan(
activity_loss, batch_size
)
self.add_loss(mean_activity_loss)
def _set_mask_metadata(self, inputs, outputs, previous_mask, build_graph):
# Many `Layer`s don't need to call `compute_mask`.
# This method is optimized to do as little work as needed for the common
# case.
if not self._supports_masking:
return
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
)
if mask_already_computed:
if build_graph:
self._set_mask_keras_history_checked(flat_outputs)
return
output_masks = self.compute_mask(inputs, previous_mask)
if output_masks is None:
return
flat_masks = tf.nest.flatten(output_masks)
for tensor, mask in zip(flat_outputs, flat_masks):
try:
tensor._keras_mask = mask
except AttributeError:
# C Type such as np.ndarray.
pass
if build_graph:
self._set_mask_keras_history_checked(flat_outputs)
def _set_mask_keras_history_checked(self, 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 _get_input_masks(self, inputs, input_list, args, kwargs):
if not self._supports_masking and not self._expects_mask_arg:
# Input masks only need to be retrieved if they are needed for
# `call` or `compute_mask`.
input_masks = None
implicit_mask = False
elif self._call_spec.arg_was_passed("mask", args, kwargs):
input_masks = self._call_spec.get_arg_value("mask", args, kwargs)
implicit_mask = False
else:
input_masks = [getattr(t, "_keras_mask", None) for t in input_list]
if all(mask is None for mask in input_masks):
input_masks = None
implicit_mask = False
else:
# Only do expensive `nest` op when masking is actually being
# used.
input_masks = tf.nest.pack_sequence_as(inputs, input_masks)
implicit_mask = True
return input_masks, implicit_mask
def _set_connectivity_metadata(self, args, kwargs, outputs):
# If the layer returns tensors from its inputs unmodified,
# we copy them to avoid loss of KerasHistory metadata.
flat_outputs = tf.nest.flatten(outputs)
flat_inputs = tf.nest.flatten((args, kwargs))
input_ids_set = {id(i) for i in flat_inputs}
outputs_copy = []
for x in flat_outputs:
if id(x) in input_ids_set:
with backend.name_scope(self.name):
x = tf.identity(x)
outputs_copy.append(x)
outputs = tf.nest.pack_sequence_as(outputs, outputs_copy)
# Create node, Node wires itself to inbound and outbound layers. The
# Node constructor actually updates this layer's self._inbound_nodes,
# sets _keras_history on the outputs, and adds itself to the
# `_outbound_nodes` of the layers that produced the inputs to this layer
# call.
node_module.Node(
self, call_args=args, call_kwargs=kwargs, outputs=outputs
)
return outputs
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(
f"The layer {self.name} has never been called "
f"and thus has no defined {attr_name}."
)
if not len(self._inbound_nodes) > node_index:
raise ValueError(
f"Asked to get {attr_name} at node "
f"{node_index}, but the layer has only "
f"{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
# Converts Tensors / CompositeTensors to TensorShapes.
if any(hasattr(x, "shape") for x in input_list):
input_shapes = tf_utils.get_shapes(inputs)
else:
# Converts input shape to TensorShapes.
try:
input_shapes = tf_utils.convert_shapes(
inputs, to_tuples=False
)
except ValueError:
pass
# 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:
with tf.init_scope():
# Using `init_scope` since we want variable assignment in
# `set_weights` to be treated like variable initialization.
self.set_weights(self._initial_weights)
self._initial_weights = None
def _get_trainable_state(self):
"""Get the `trainable` state of each sublayer.
Returns:
A dict mapping all sublayers to their `trainable` value.
"""
trainable_state = weakref.WeakKeyDictionary()
for layer in self._flatten_layers():
trainable_state[layer] = layer.trainable
return trainable_state
def _set_trainable_state(self, trainable_state):
"""Set `trainable` state for each sublayer."""
for layer in self._flatten_layers():
if layer in trainable_state:
layer.trainable = trainable_state[layer]
@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
# Wraps data structures in `Trackable`, unwraps `NoDependency` objects.
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
# When replacing an existing tf.Variable with a new one, we want to
# check its existing position in the
# self._trainable/non_trainable_variable, so that we can put it back to
# the original position.
if isinstance(value, tf.Variable) and isinstance(
getattr(self, name, None), tf.Variable
):
existing_variable = getattr(self, name)
def _get_variable_from_list(var_list, var):
# helper function to get the tf.variable from the list
# the default list.index() use == for comparison, which will
# cause issue for eager tensor.
for i in range(len(var_list)):
if var_list[i] is var:
return i
return None
if existing_variable.trainable:
self._maybe_create_attribute("_trainable_weights", [])
position = _get_variable_from_list(
self._trainable_weights, existing_variable
)
else:
self._maybe_create_attribute("_non_trainable_variable", [])
position = _get_variable_from_list(
self._non_trainable_variable, existing_variable
)
else:
position = None
# 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.
for val in tf.nest.flatten(value):
if isinstance(val, metrics_mod.Metric) and hasattr(
self, "_metrics"
):
self._metrics.append(val)
# Append value to self._self_tracked_trackables if relevant
if getattr(self, "_auto_track_sub_layers", True) and (
isinstance(value, tf.Module) 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.
self._track_variables(value, position=position)
# 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
)
def _update_trackables(self):
"""Track variables added to lists/dicts after creation"""
for trackable_obj in self._self_tracked_trackables:
if isinstance(
trackable_obj, tf.__internal__.tracking.TrackableDataStructure
):
self._track_variables(trackable_obj)
def _track_variables(self, value, position=None):
"""Tracks `Variable`s including `Variable`s in `CompositeTensor`s."""
for val in tf.nest.flatten(value):
if isinstance(val, tf.Variable):
self._track_variable(val, position=position)
elif tf_utils.is_extension_type(val):
# Manually expand extension types to track resource variables.
nested_vals = tf_utils.type_spec_from_value(val)._to_components(
val
)
self._track_variables(nested_vals, position=position)
def _track_variable(self, val, position=None):
"""Tracks the given `tf.Variable`."""
# 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):
return
if position is None:
self._trainable_weights.append(val)
else:
self._trainable_weights.insert(position, val)
else:
if any(val is w for w in self._non_trainable_weights):
return
if position is None:
self._non_trainable_weights.append(val)
else:
self._non_trainable_weights.insert(position, val)
backend.track_variable(val)
def _gather_children_attribute(self, attribute):
assert attribute in {
"variables",
"trainable_variables",
"non_trainable_variables",
}
if hasattr(self, "_self_tracked_trackables"):
nested_layers = self._flatten_modules(
include_self=False, recursive=False
)
return list(
itertools.chain.from_iterable(
getattr(layer, attribute) for layer in nested_layers
)
)
return []
def _flatten_layers(self, recursive=True, include_self=True):
for m in self._flatten_modules(
recursive=recursive, include_self=include_self
):
if isinstance(m, Layer):
yield m
def _flatten_modules(self, recursive=True, include_self=True):
"""Flattens `tf.Module` instances (excluding `Metrics`).
Args:
recursive: Whether to recursively flatten through submodules.
include_self: Whether to include this `Layer` instance.
Yields:
`tf.Module` instance tracked by this `Layer`.
"""
if include_self:
yield self
# Only instantiate set and deque if needed.
trackables = getattr(self, "_self_tracked_trackables", None)
if trackables:
seen_object_ids = set()
deque = collections.deque(trackables)
while deque:
trackable_obj = deque.popleft()
trackable_id = id(trackable_obj)
if trackable_id in seen_object_ids:
continue
seen_object_ids.add(trackable_id)
# Metrics are not considered part of the Layer's topology.
if isinstance(trackable_obj, tf.Module) and not isinstance(
trackable_obj, metrics_mod.Metric
):
yield trackable_obj
# Introspect recursively through sublayers.
if recursive:
subtrackables = getattr(
trackable_obj, "_self_tracked_trackables", None
)
if subtrackables:
deque.extendleft(reversed(subtrackables))
elif isinstance(
trackable_obj,
tf.__internal__.tracking.TrackableDataStructure,
):
# Data structures are introspected even with
# `recursive=False`.
tracked_values = trackable_obj._values
if tracked_values:
deque.extendleft(reversed(tracked_values))
# 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
def _init_call_fn_args(self, expects_training_arg=None):
self._call_spec = layer_utils.CallFunctionSpec(
tf_inspect.getfullargspec(self.call)
)
if expects_training_arg is not None:
self._call_spec.expects_training_arg = expects_training_arg
@property
def _expects_training_arg(self):
"""Whether the call function uses 'training' as a parameter."""
return self._call_spec.expects_training_arg
@property
def _expects_mask_arg(self):
return self._call_spec.expects_mask_arg
@property
def _eager_losses(self):
# A list of loss values containing activity regularizers and losses
# manually added through `add_loss` during eager execution. It is
# cleared after every batch. Because we plan on eventually allowing a
# same model instance to be trained in eager mode or graph mode
# alternatively, we need to keep track of eager losses and symbolic
# losses via separate attributes.
if not hasattr(self._thread_local, "_eager_losses"):
self._thread_local._eager_losses = []
return self._thread_local._eager_losses
@_eager_losses.setter
def _eager_losses(self, losses):
self._thread_local._eager_losses = losses
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.
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _set_save_spec(self, inputs, args=None, kwargs=None):
"""Defines the save spec so that serialization can trace layer calls.
The TensorSpecs of the call function `inputs`, `args`, and `kwargs` are
saved into a tuple of `([inputs] + args, kwargs)`.
Args:
inputs: possibly nested inputs passed into the call function.
args: a list of positional arguments passed into call.
kwargs: a dictionary of keyword arguments passed into call.
"""
if self._saved_model_inputs_spec is not None:
return # Already set.
inputs_spec = tf.nest.map_structure(tf_utils.get_tensor_spec, inputs)
args_spec = tf.nest.map_structure(tf_utils.get_tensor_spec, args or [])
kwargs_spec = {}
# Filter out non-tensor arguments from kwargs.
for key, kwarg in kwargs.items():
flat_kwarg = tf.nest.flatten(kwarg)
flat_specs = [tf_utils.get_tensor_spec(x) for x in flat_kwarg]
if any(s is None for s in flat_specs):
continue
kwargs_spec[key] = tf.nest.pack_sequence_as(kwarg, flat_specs)
self._saved_model_inputs_spec = inputs_spec
self._saved_model_arg_spec = (
[inputs_spec] + list(args_spec),
kwargs_spec,
)
def _get_save_spec(self, dynamic_batch=True, inputs_only=True):
if self._saved_model_inputs_spec is None:
return None
spec = tf.nest.map_structure(
lambda t: tf_utils.get_tensor_spec(t, dynamic_batch=dynamic_batch),
self._saved_model_arg_spec,
)
return spec[0][0] if inputs_only else spec
@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):
"""Info about this layer to be saved into the SavedModel."""
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
@property
def _use_input_spec_as_call_signature(self):
# Whether input spec can be used as the call signature when tracing the
# Layer for SavedModel. By default, this is set to `True` for layers
# exported from the TF-Keras library, because the layers more rigidly
# define the `input_specs` property (many custom layers only set the
# `ndims`)
return (
get_canonical_name_for_symbol(type(self), api_name="keras")
is not None
)
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)
state.pop("_metrics_lock", None)
return state
def __setstate__(self, state):
state["_thread_local"] = threading.local()
state["_metrics_lock"] = threading.Lock()
# Bypass Trackable logic as `__dict__` already contains this info.
object.__setattr__(self, "__dict__", state)
def save_own_variables(self, store):
"""Saves the state of the layer.
You can override this method to take full control of how the state of
the layer is saved upon calling `model.save()`.
Args:
store: Dict where the state of the model will be saved.
"""
all_vars = self._trainable_weights + self._non_trainable_weights
for i, v in enumerate(all_vars):
store[f"{i}"] = v.numpy()
def load_own_variables(self, store):
"""Loads the state of the layer.
You can override this method to take full control of how the state of
the layer is loaded upon calling `keras.models.load_model()`.
Args:
store: Dict from which the state of the model will be loaded.
"""
self._update_trackables()
all_vars = self._trainable_weights + self._non_trainable_weights
if len(store.keys()) != len(all_vars):
raise ValueError(
f"Layer '{self.name}' expected {len(all_vars)} variables, "
"but received "
f"{len(store.keys())} variables during loading. "
f"Expected: {[v.name for v in all_vars]}"
)
for i, v in enumerate(all_vars):
# TODO(rchao): check shapes and raise errors.
v.assign(store[f"{i}"])
| (self, name, default_value) |
724,964 | tf_keras.src.engine.training | _maybe_load_initial_counters_from_ckpt | Maybe load initial epoch from ckpt, considering worker recovery.
Refer to tensorflow/python/tf_keras/distribute/worker_training_state.py
for more information.
Args:
steps_per_epoch: The number of step per epoch.
initial_epoch: The original initial_epoch user passes in `fit()`.
mode: The mode for running `model.fit()`.
Returns:
If the training is recovering from previous failure under multi-worker
training setting, return the (epoch, step) the training is supposed to
continue at. Otherwise, return the `initial_epoch, initial_step` the
user passes in.
| def _maybe_load_initial_counters_from_ckpt(
self, steps_per_epoch, initial_epoch
):
"""Maybe load initial epoch from ckpt, considering worker recovery.
Refer to tensorflow/python/tf_keras/distribute/worker_training_state.py
for more information.
Args:
steps_per_epoch: The number of step per epoch.
initial_epoch: The original initial_epoch user passes in `fit()`.
mode: The mode for running `model.fit()`.
Returns:
If the training is recovering from previous failure under multi-worker
training setting, return the (epoch, step) the training is supposed to
continue at. Otherwise, return the `initial_epoch, initial_step` the
user passes in.
"""
initial_step = 0
if self._training_state is not None:
return self._training_state.maybe_load_initial_counters_from_ckpt(
steps_per_epoch, initial_epoch, mode=ModeKeys.TRAIN
)
return (initial_epoch, initial_step)
| (self, steps_per_epoch, initial_epoch) |
724,978 | tf_keras.src.engine.training | _set_save_spec | Defines the save spec so that serialization can trace `call()`.
The TensorSpecs of the call function `inputs`, `args`, and `kwargs` are
saved into a tuple of `([inputs] + args, kwargs)`. The input
`TensorSpec` names are updated to match the built `input_names`.
The specs can be retrieved with the `save_spec` property.
Args:
inputs: possibly nested inputs passed into the call function.
args: a list of positional arguments passed into call.
kwargs: a dictionary of keyword arguments passed into call.
| def __new__(cls, *args, **kwargs):
# Signature detection
if is_functional_model_init_params(args, kwargs) and cls == Model:
# Functional model
from tf_keras.src.engine import functional
return functional.Functional(skip_init=True, *args, **kwargs)
else:
return super(Model, cls).__new__(cls, *args, **kwargs)
| (self, inputs, args=None, kwargs=None) |
724,983 | tf_keras.src.engine.base_layer | _should_use_autograph | null | def _should_use_autograph(self):
if base_layer_utils.from_saved_model(self):
return False
if base_layer_utils.is_subclassed(self):
return True
return False
| (self) |
724,989 | tf_keras.src.engine.training | _updated_config | Util shared between different serialization methods.
Returns:
Model config with TF-Keras version information added.
| def _updated_config(self):
"""Util shared between different serialization methods.
Returns:
Model config with TF-Keras version information added.
"""
from tf_keras.src import __version__ as keras_version
config = self.get_config()
model_config = {
"class_name": self.__class__.__name__,
"config": config,
"keras_version": keras_version,
"backend": backend.backend(),
}
return model_config
| (self) |
724,994 | tf_keras.src.engine.base_layer | add_metric | Adds metric tensor to the layer.
This method can be used inside the `call()` method of a subclassed layer
or model.
```python
class MyMetricLayer(tf.keras.layers.Layer):
def __init__(self):
super(MyMetricLayer, self).__init__(name='my_metric_layer')
self.mean = tf.keras.metrics.Mean(name='metric_1')
def call(self, inputs):
self.add_metric(self.mean(inputs))
self.add_metric(tf.reduce_sum(inputs), name='metric_2')
return inputs
```
This method can also be called directly on a Functional Model during
construction. In this case, any tensor passed to this Model must
be symbolic and be able to be traced back to the model's `Input`s. These
metrics become part of the model's topology and are tracked when you
save the model via `save()`.
```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)
model.add_metric(math_ops.reduce_sum(x), name='metric_1')
```
Note: Calling `add_metric()` with the result of a metric object on a
Functional Model, as shown in the example below, is not supported. This
is because we cannot trace the metric result tensor back to the model's
inputs.
```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)
model.add_metric(tf.keras.metrics.Mean()(x), name='metric_1')
```
Args:
value: Metric tensor.
name: String metric name.
**kwargs: Additional keyword arguments for backward compatibility.
Accepted values:
`aggregation` - When the `value` tensor provided is not the result
of calling a `keras.Metric` instance, it will be aggregated by
default using a `keras.Metric.Mean`.
| @doc_controls.do_not_generate_docs
def add_metric(self, value, name=None, **kwargs):
"""Adds metric tensor to the layer.
This method can be used inside the `call()` method of a subclassed layer
or model.
```python
class MyMetricLayer(tf.keras.layers.Layer):
def __init__(self):
super(MyMetricLayer, self).__init__(name='my_metric_layer')
self.mean = tf.keras.metrics.Mean(name='metric_1')
def call(self, inputs):
self.add_metric(self.mean(inputs))
self.add_metric(tf.reduce_sum(inputs), name='metric_2')
return inputs
```
This method can also be called directly on a Functional Model during
construction. In this case, any tensor passed to this Model must
be symbolic and be able to be traced back to the model's `Input`s. These
metrics become part of the model's topology and are tracked when you
save the model via `save()`.
```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)
model.add_metric(math_ops.reduce_sum(x), name='metric_1')
```
Note: Calling `add_metric()` with the result of a metric object on a
Functional Model, as shown in the example below, is not supported. This
is because we cannot trace the metric result tensor back to the model's
inputs.
```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)
model.add_metric(tf.keras.metrics.Mean()(x), name='metric_1')
```
Args:
value: Metric tensor.
name: String metric name.
**kwargs: Additional keyword arguments for backward compatibility.
Accepted values:
`aggregation` - When the `value` tensor provided is not the result
of calling a `keras.Metric` instance, it will be aggregated by
default using a `keras.Metric.Mean`.
"""
kwargs_keys = list(kwargs.keys())
if len(kwargs_keys) > 1 or (
len(kwargs_keys) == 1 and kwargs_keys[0] != "aggregation"
):
raise TypeError(
f"Unknown keyword arguments: {kwargs.keys()}. "
"Expected `aggregation`."
)
from_metric_obj = hasattr(value, "_metric_obj")
is_symbolic = isinstance(value, keras_tensor.KerasTensor)
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))` 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')`"
)
elif from_metric_obj:
name = value._metric_obj.name
if not in_call_context and not is_symbolic:
raise ValueError(
"Expected a symbolic Tensor for the metric value, received: "
+ str(value)
)
# If a metric was added in a Layer's `call` or `build`.
if in_call_context or not getattr(self, "_is_graph_network", False):
# TF Function path should take the eager path.
# If the given metric is available in `metrics` list we just update
# state on it, otherwise we create a new metric instance and
# add it to the `metrics` list.
metric_obj = getattr(value, "_metric_obj", None)
# Tensors that come from a Metric object already updated the Metric
# state.
should_update_state = not metric_obj
name = metric_obj.name if metric_obj else name
with self._metrics_lock:
match = self._get_existing_metric(name)
if match:
metric_obj = match
elif metric_obj:
self._metrics.append(metric_obj)
else:
# Build the metric object with the value's dtype if it
# defines one
metric_obj = metrics_mod.Mean(
name=name, dtype=getattr(value, "dtype", None)
)
self._metrics.append(metric_obj)
if should_update_state:
metric_obj(value)
else:
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.
aggregation = None if from_metric_obj else "mean"
self._graph_network_add_metric(value, aggregation, name)
| (self, value, name=None, **kwargs) |
724,995 | tf_keras.src.engine.base_layer | add_update | 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.
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.
| @doc_controls.do_not_doc_inheritable
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.
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()
# No need to run updates during Functional API construction.
if call_context.in_keras_graph:
return
# Callable updates are disabled by setting `trainable=False`.
if not call_context.frozen:
for update in tf.nest.flatten(updates):
if callable(update):
update()
| (self, updates) |
724,996 | tf_keras.src.engine.base_layer | add_variable | Deprecated, do NOT use! Alias for `add_weight`. | @doc_controls.do_not_doc_inheritable
def add_variable(self, *args, **kwargs):
"""Deprecated, do NOT use! Alias for `add_weight`."""
warnings.warn(
"`layer.add_variable` is deprecated and "
"will be removed in a future version. "
"Please use the `layer.add_weight()` method instead.",
stacklevel=2,
)
return self.add_weight(*args, **kwargs)
| (self, *args, **kwargs) |
724,997 | tf_keras.src.engine.base_layer | add_weight | 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`.
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).
use_resource: Whether to use a `ResourceVariable` or not.
See [this guide](
https://www.tensorflow.org/guide/migrate/tf1_vs_tf2#resourcevariables_instead_of_referencevariables)
for more information.
synchronization: Indicates when a distributed a 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 variable created.
Raises:
ValueError: When giving unsupported dtype and no initializer or when
trainable has been set to True with synchronization set as
`ON_READ`.
| @doc_controls.for_subclass_implementers
def add_weight(
self,
name=None,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
trainable=None,
constraint=None,
use_resource=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.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`.
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).
use_resource: Whether to use a `ResourceVariable` or not.
See [this guide](
https://www.tensorflow.org/guide/migrate/tf1_vs_tf2#resourcevariables_instead_of_referencevariables)
for more information.
synchronization: Indicates when a distributed a 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 variable created.
Raises:
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 = ()
kwargs.pop("partitioner", None) # Ignored.
# Validate optional keyword arguments.
for kwarg in kwargs:
if kwarg not in [
"collections",
"experimental_autocast",
"caching_device",
"getter",
"layout",
"experimental_enable_variable_lifting",
]:
raise TypeError("Unknown keyword argument:", kwarg)
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)
layout = kwargs.pop("layout", None)
# Specially handling of auto layout fetch, based on the variable name
# and attribute name. For built-in keras layers, usually the variable
# name, eg 'kernel', will match with a 'kernel_layout' attribute name on
# the instance. We will try to do this auto fetch if layout is not
# explicitly specified. This is mainly a quick workaround for not
# applying too many interface change to built-in layers, until DTensor
# is a public API. Also see dtensor.utils.allow_initializer_layout for
# more details.
# TODO(scottzhu): Remove this once dtensor is public to end user.
if not layout and name:
layout = getattr(self, name + "_layout", 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 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 = initializers.get("zeros")
# NOTES:Do we need to support for handling DT_STRING and DT_COMPLEX
# here?
elif "getter" not in kwargs:
# 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(
f"An initializer for variable {name} of type "
f"{dtype.base_dtype} is required for layer "
f"{self.name}. Received: {initializer}."
)
getter = kwargs.pop("getter", base_layer_utils.make_variable)
if (
autocast
and self._dtype_policy.compute_dtype
!= self._dtype_policy.variable_dtype
and dtype.is_floating
):
old_getter = getter
# Wrap variable constructor to return an AutoCastVariable.
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
if layout:
getter = functools.partial(getter, layout=layout)
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,
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
| (self, name=None, shape=None, dtype=None, initializer=None, regularizer=None, trainable=None, constraint=None, use_resource=None, synchronization=<VariableSynchronization.AUTO: 0>, aggregation=<VariableAggregationV2.NONE: 0>, **kwargs) |
724,999 | tf_keras.src.engine.base_layer | build_from_config | Builds the layer's states with the supplied config dict.
By default, this method calls the `build(config["input_shape"])` method,
which creates weights based on the layer's input shape in the supplied
config. If your config contains other information needed to load the
layer's state, you should override this method.
Args:
config: Dict containing the input shape associated with this layer.
| def build_from_config(self, config):
"""Builds the layer's states with the supplied config dict.
By default, this method calls the `build(config["input_shape"])` method,
which creates weights based on the layer's input shape in the supplied
config. If your config contains other information needed to load the
layer's state, you should override this method.
Args:
config: Dict containing the input shape associated with this layer.
"""
input_shape = config["input_shape"]
if input_shape is not None:
self.build(input_shape)
| (self, config) |
725,000 | tf_keras.src.engine.training | call | Calls the model on new inputs and returns the outputs as tensors.
In this case `call()` just reapplies
all ops in the graph to the new inputs
(e.g. build a new computational graph from the provided inputs).
Note: This method should not be called directly. It is only meant to be
overridden when subclassing `tf.keras.Model`.
To call a model on an input, always use the `__call__()` method,
i.e. `model(inputs)`, which relies on the underlying `call()` method.
Args:
inputs: Input tensor, or dict/list/tuple of input tensors.
training: Boolean or boolean scalar tensor, indicating whether to
run the `Network` in training mode or inference mode.
mask: A mask or list of masks. A mask can be either a boolean tensor
or None (no mask). For more details, check the guide
[here](https://www.tensorflow.org/guide/keras/masking_and_padding).
Returns:
A tensor if there is a single output, or
a list of tensors if there are more than one outputs.
| @doc_controls.doc_in_current_and_subclasses
def call(self, inputs, training=None, mask=None):
"""Calls the model on new inputs and returns the outputs as tensors.
In this case `call()` just reapplies
all ops in the graph to the new inputs
(e.g. build a new computational graph from the provided inputs).
Note: This method should not be called directly. It is only meant to be
overridden when subclassing `tf.keras.Model`.
To call a model on an input, always use the `__call__()` method,
i.e. `model(inputs)`, which relies on the underlying `call()` method.
Args:
inputs: Input tensor, or dict/list/tuple of input tensors.
training: Boolean or boolean scalar tensor, indicating whether to
run the `Network` in training mode or inference mode.
mask: A mask or list of masks. A mask can be either a boolean tensor
or None (no mask). For more details, check the guide
[here](https://www.tensorflow.org/guide/keras/masking_and_padding).
Returns:
A tensor if there is a single output, or
a list of tensors if there are more than one outputs.
"""
raise NotImplementedError(
"Unimplemented `tf.keras.Model.call()`: if you "
"intend to create a `Model` with the Functional "
"API, please provide `inputs` and `outputs` "
"arguments. Otherwise, subclass `Model` with an "
"overridden `call()` method."
)
| (self, inputs, training=None, mask=None) |
725,001 | tf_keras.src.engine.training | compile | Configures the model for training.
Example:
```python
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),
loss=tf.keras.losses.BinaryCrossentropy(),
metrics=[tf.keras.metrics.BinaryAccuracy(),
tf.keras.metrics.FalseNegatives()])
```
Args:
optimizer: String (name of optimizer) or optimizer instance. See
`tf.keras.optimizers`.
loss: Loss function. May be a string (name of loss function), or
a `tf.keras.losses.Loss` instance. See `tf.keras.losses`. A loss
function is any callable with the signature `loss = fn(y_true,
y_pred)`, where `y_true` are the ground truth values, and
`y_pred` are the model's predictions.
`y_true` should have shape
`(batch_size, d0, .. dN)` (except in the case of
sparse loss functions such as
sparse categorical crossentropy which expects integer arrays of
shape `(batch_size, d0, .. dN-1)`).
`y_pred` should have shape `(batch_size, d0, .. dN)`.
The loss function should return a float tensor.
If a custom `Loss` instance is
used and reduction is set to `None`, return value has shape
`(batch_size, d0, .. dN-1)` i.e. per-sample or per-timestep loss
values; otherwise, it is a scalar. If the model has multiple
outputs, you can use a different loss on each output by passing a
dictionary or a list of losses. The loss value that will be
minimized by the model will then be the sum of all individual
losses, unless `loss_weights` is specified.
metrics: List of metrics to be evaluated by the model during
training and testing. Each of this can be a string (name of a
built-in function), function or a `tf.keras.metrics.Metric`
instance. See `tf.keras.metrics`. Typically you will use
`metrics=['accuracy']`.
A function is any callable with the signature `result = fn(y_true,
y_pred)`. To specify different metrics for different outputs of a
multi-output model, you could also pass a dictionary, such as
`metrics={'output_a':'accuracy', 'output_b':['accuracy', 'mse']}`.
You can also pass a list to specify a metric or a list of metrics
for each output, such as
`metrics=[['accuracy'], ['accuracy', 'mse']]`
or `metrics=['accuracy', ['accuracy', 'mse']]`. When you pass the
strings 'accuracy' or 'acc', we convert this to one of
`tf.keras.metrics.BinaryAccuracy`,
`tf.keras.metrics.CategoricalAccuracy`,
`tf.keras.metrics.SparseCategoricalAccuracy` based on the shapes
of the targets and of the model output. We do a similar
conversion for the strings 'crossentropy' and 'ce' as well.
The metrics passed here are evaluated without sample weighting; if
you would like sample weighting to apply, you can specify your
metrics via the `weighted_metrics` argument instead.
loss_weights: Optional list or dictionary specifying scalar
coefficients (Python floats) to weight the loss contributions of
different model outputs. The loss value that will be minimized by
the model will then be the *weighted sum* of all individual
losses, weighted by the `loss_weights` coefficients. If a list,
it is expected to have a 1:1 mapping to the model's outputs. If a
dict, it is expected to map output names (strings) to scalar
coefficients.
weighted_metrics: List of metrics to be evaluated and weighted by
`sample_weight` or `class_weight` during training and testing.
run_eagerly: Bool. If `True`, this `Model`'s logic will not be
wrapped in a `tf.function`. Recommended to leave this as `None`
unless your `Model` cannot be run inside a `tf.function`.
`run_eagerly=True` is not supported when using
`tf.distribute.experimental.ParameterServerStrategy`. Defaults to
`False`.
steps_per_execution: Int or `'auto'`. The number of batches to
run during each `tf.function` call. If set to "auto", keras will
automatically tune `steps_per_execution` during runtime. Running
multiple batches inside a single `tf.function` call can greatly
improve performance on TPUs, when used with distributed strategies
such as `ParameterServerStrategy`, or with small models with a
large Python overhead. At most, one full epoch will be run each
execution. If a number larger than the size of the epoch is
passed, the execution will be truncated to the size of the epoch.
Note that if `steps_per_execution` is set to `N`,
`Callback.on_batch_begin` and `Callback.on_batch_end` methods will
only be called every `N` batches (i.e. before/after each
`tf.function` execution). Defaults to `1`.
jit_compile: If `True`, compile the model training step with XLA.
[XLA](https://www.tensorflow.org/xla) is an optimizing compiler
for machine learning.
`jit_compile` is not enabled for by default.
Note that `jit_compile=True`
may not necessarily work for all models.
For more information on supported operations please refer to the
[XLA documentation](https://www.tensorflow.org/xla).
Also refer to
[known XLA issues](https://www.tensorflow.org/xla/known_issues)
for more details.
pss_evaluation_shards: Integer or 'auto'. Used for
`tf.distribute.ParameterServerStrategy` training only. This arg
sets the number of shards to split the dataset into, to enable an
exact visitation guarantee for evaluation, meaning the model will
be applied to each dataset element exactly once, even if workers
fail. The dataset must be sharded to ensure separate workers do
not process the same data. The number of shards should be at least
the number of workers for good performance. A value of 'auto'
turns on exact evaluation and uses a heuristic for the number of
shards based on the number of workers. 0, meaning no
visitation guarantee is provided. NOTE: Custom implementations of
`Model.test_step` will be ignored when doing exact evaluation.
Defaults to `0`.
**kwargs: Arguments supported for backwards compatibility only.
| # 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.
# ==============================================================================
"""Training-related part of the TF-Keras engine."""
import copy
import itertools
import json
import warnings
import weakref
import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow.python.distribute import distribute_utils
from tensorflow.python.distribute import input_ops
from tensorflow.python.eager import context
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util.tf_export import keras_export
from tensorflow.tools.docs import doc_controls
from tf_keras.src import backend
from tf_keras.src import callbacks as callbacks_module
from tf_keras.src import optimizers
from tf_keras.src.dtensor import dtensor_api
from tf_keras.src.dtensor import layout_map as layout_map_lib
from tf_keras.src.engine import base_layer
from tf_keras.src.engine import base_layer_utils
from tf_keras.src.engine import compile_utils
from tf_keras.src.engine import data_adapter
from tf_keras.src.engine import input_layer as input_layer_module
from tf_keras.src.engine import training_utils
from tf_keras.src.metrics import base_metric
from tf_keras.src.mixed_precision import loss_scale_optimizer as lso
from tf_keras.src.optimizers import optimizer
from tf_keras.src.optimizers import optimizer_v1
from tf_keras.src.saving import pickle_utils
from tf_keras.src.saving import saving_api
from tf_keras.src.saving import saving_lib
from tf_keras.src.saving import serialization_lib
from tf_keras.src.saving.legacy import serialization
from tf_keras.src.saving.legacy.saved_model import json_utils
from tf_keras.src.saving.legacy.saved_model import model_serialization
from tf_keras.src.utils import generic_utils
from tf_keras.src.utils import io_utils
from tf_keras.src.utils import layer_utils
from tf_keras.src.utils import steps_per_execution_tuning
from tf_keras.src.utils import tf_inspect
from tf_keras.src.utils import tf_utils
from tf_keras.src.utils import traceback_utils
from tf_keras.src.utils import version_utils
from tf_keras.src.utils.mode_keys import ModeKeys
try:
import h5py
except ImportError:
h5py = None
@keras_export("keras.Model", "keras.models.Model")
class Model(base_layer.Layer, version_utils.ModelVersionSelector):
"""A model grouping layers into an object with training/inference features.
Args:
inputs: The input(s) of the model: a `keras.Input` object or a
combination of `keras.Input` objects in a dict, list or tuple.
outputs: The output(s) of the model: a tensor that originated from
`keras.Input` objects or a combination of such tensors in a dict,
list or tuple. See Functional API example below.
name: String, the name of the model.
There are two ways to instantiate a `Model`:
1 - With the "Functional API", where you start from `Input`,
you chain layer calls to specify the model's forward pass,
and finally you create your model from inputs and outputs:
```python
import tensorflow as tf
inputs = tf.keras.Input(shape=(3,))
x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
```
Note: Only dicts, lists, and tuples of input tensors are supported. Nested
inputs are not supported (e.g. lists of list or dicts of dict).
A new Functional API model can also be created by using the
intermediate tensors. This enables you to quickly extract sub-components
of the model.
Example:
```python
inputs = keras.Input(shape=(None, None, 3))
processed = keras.layers.RandomCrop(width=32, height=32)(inputs)
conv = keras.layers.Conv2D(filters=2, kernel_size=3)(processed)
pooling = keras.layers.GlobalAveragePooling2D()(conv)
feature = keras.layers.Dense(10)(pooling)
full_model = keras.Model(inputs, feature)
backbone = keras.Model(processed, conv)
activations = keras.Model(conv, feature)
```
Note that the `backbone` and `activations` models are not
created with `keras.Input` objects, but with the tensors that are originated
from `keras.Input` objects. Under the hood, the layers and weights will
be shared across these models, so that user can train the `full_model`, and
use `backbone` or `activations` to do feature extraction.
The inputs and outputs of the model can be nested structures of tensors as
well, and the created models are standard Functional API models that support
all the existing APIs.
2 - By subclassing the `Model` class: in that case, you should define your
layers in `__init__()` and you should implement the model's forward pass
in `call()`.
```python
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
def call(self, inputs):
x = self.dense1(inputs)
return self.dense2(x)
model = MyModel()
```
If you subclass `Model`, you can optionally have
a `training` argument (boolean) in `call()`, which you can use to specify
a different behavior in training and inference:
```python
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
self.dropout = tf.keras.layers.Dropout(0.5)
def call(self, inputs, training=False):
x = self.dense1(inputs)
if training:
x = self.dropout(x, training=training)
return self.dense2(x)
model = MyModel()
```
Once the model is created, you can config the model with losses and metrics
with `model.compile()`, train the model with `model.fit()`, or use the model
to do prediction with `model.predict()`.
"""
_TF_MODULE_IGNORED_PROPERTIES = frozenset(
itertools.chain(
(
"_train_counter",
"_test_counter",
"_predict_counter",
"_steps_per_execution",
"_compiled_trainable_state",
),
base_layer.Layer._TF_MODULE_IGNORED_PROPERTIES,
)
)
_SCALAR_UPRANKING_ON = False
def __new__(cls, *args, **kwargs):
# Signature detection
if is_functional_model_init_params(args, kwargs) and cls == Model:
# Functional model
from tf_keras.src.engine import functional
return functional.Functional(skip_init=True, *args, **kwargs)
else:
return super(Model, cls).__new__(cls, *args, **kwargs)
@tf.__internal__.tracking.no_automatic_dependency_tracking
@traceback_utils.filter_traceback
def __init__(self, *args, **kwargs):
self._is_model_for_instrumentation = True
# Special case for Subclassed Functional Model, which we couldn't detect
# when __new__ is called. We only realize it is a functional model when
# it calls super.__init__ with input and output tensor.
from tf_keras.src.engine import functional
if is_functional_model_init_params(args, kwargs) and not isinstance(
self, functional.Functional
):
# Filter the kwargs for multiple inheritance.
supported_kwargs = [
"inputs",
"outputs",
"name",
"trainable",
"skip_init",
]
model_kwargs = {
k: kwargs[k] for k in kwargs if k in supported_kwargs
}
other_kwargs = {
k: kwargs[k] for k in kwargs if k not in supported_kwargs
}
inject_functional_model_class(self.__class__)
functional.Functional.__init__(self, *args, **model_kwargs)
# In case there is any multiple inheritance here, we need to call
# the __init__ for any class that appears after the Functional
# class.
clz_to_init = []
found_functional_class = False
for clz in self.__class__.__bases__:
if issubclass(clz, functional.Functional):
found_functional_class = True
continue
if found_functional_class:
clz_to_init.append(clz)
if clz_to_init:
for clz in clz_to_init:
clz.__init__(self, *args, **other_kwargs)
elif other_kwargs:
# In case there are unused kwargs, we should raise an error to
# user, in case they have a typo in the param name.
raise TypeError(
"The following keyword arguments passed to `Model` aren't "
"supported: {}.".format(other_kwargs)
)
return
# The following are implemented as property functions:
# self.trainable_weights
# self.non_trainable_weights
# `inputs` / `outputs` will only appear in kwargs if either are
# misspelled.
generic_utils.validate_kwargs(
kwargs,
{
"trainable",
"dtype",
"dynamic",
"name",
"autocast",
"inputs",
"outputs",
},
)
super().__init__(**kwargs)
# By default, Model is a subclass model, which is not in graph network.
self._is_graph_network = False
self.inputs = None
self.outputs = None
self.input_names = None
self.output_names = None
# stop_training is used by callback to stop training when error happens
self.stop_training = False
self.history = None
# These objects are used in the default `Model.compile`. They are not
# guaranteed to be set after `Model.compile` is called, as users can
# override compile with custom logic.
self.compiled_loss = None
self.compiled_metrics = None
# This is True for Sequential networks and Functional networks.
self._compute_output_and_mask_jointly = False
# Don't reset compilation if already done. This may occur if calling
# `__init__` (or `_init_graph_network`) on an already-compiled model
# such as a Sequential model. Sequential models may need to rebuild
# themselves after compilation.
self._maybe_create_attribute("_is_compiled", False)
self._maybe_create_attribute("optimizer", None)
# Model must be created under scope of DistStrat it will be trained
# with.
if tf.distribute.has_strategy():
self._distribution_strategy = tf.distribute.get_strategy()
else:
self._distribution_strategy = None
self._distribute_reduction_method = None
self._cluster_coordinator = None
# Defaults to value of `tf.config.experimental_functions_run_eagerly`.
self._run_eagerly = None
# Initialize cache attrs.
self._reset_compile_cache()
# Fault-tolerance handler. Set in `ModelCheckpoint`.
self._training_state = None
self._saved_model_inputs_spec = None
self._saved_model_arg_spec = None
self._checkpoint = tf.train.Checkpoint(root=weakref.ref(self))
self._steps_per_execution = None
self._steps_per_execution_tuner = None
self._autotune_steps_per_execution = False
self._layout_map = layout_map_lib.get_current_layout_map()
self._init_batch_counters()
self._base_model_initialized = True
# `jit_compile` starts off with None as default and gets overwritten by
# the value specified in `Model.compile`, and this is effective for
# `fit`, `evaluate`, and `predict`.
self._jit_compile = None
def _create_counter_variable(self, init_value):
"""Helper function for counter variable creation.
For the DTensor use case with layout map, since the variable are not
tracked by model, they can't be visited by the layout map, and need to
be properly initialized as DVariable.
"""
# This function should be removed after we move to the strategy based
# implementation for DTensor.
if self._layout_map is None:
agg = tf.VariableAggregation.ONLY_FIRST_REPLICA
return tf.Variable(init_value, dtype="int64", aggregation=agg)
else:
layout = dtensor_api.Layout.replicated(
mesh=self._layout_map.get_default_mesh(), rank=0
)
return dtensor_api.DVariable(
init_value, dtype="int64", layout=layout
)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _init_batch_counters(self):
# Untracked Variables, used to keep track of mini-batches seen in `fit`,
# `evaluate`, and `predict`.
if not tf.inside_function():
# Creating variables inside tf.function is not allowed, hence
# these would otherwise prevent users from creating TF-Keras layers
# inside tf.function.
# These variables are not connected to outputs so they have no
# effect on graph generation anyway.
self._train_counter = self._create_counter_variable(0)
self._test_counter = self._create_counter_variable(0)
self._predict_counter = self._create_counter_variable(0)
def __setattr__(self, name, value):
if not getattr(self, "_self_setattr_tracking", True):
super().__setattr__(name, value)
return
if all(
isinstance(v, (base_layer.Layer, tf.Variable))
or base_layer_utils.has_weights(v)
for v in tf.nest.flatten(value)
):
try:
self._base_model_initialized
except AttributeError:
raise RuntimeError(
"It looks like you are subclassing `Model` and you "
"forgot to call `super().__init__()`."
" Always start with this line."
)
super().__setattr__(name, value)
def __reduce__(self):
if self.built:
return (
pickle_utils.deserialize_model_from_bytecode,
(pickle_utils.serialize_model_as_bytecode(self),),
)
else:
# SavedModel (and hence serialize_model_as_bytecode) only support
# built models, but if the model is not built,
# it may be possible to serialize as a plain Python object,
# as long as the constituent parts (layers, optimizers, losses,
# etc.) can be serialized as plain Python objects. Thus we call up
# the superclass hierarchy to get an implementation of __reduce__
# that can pickle this Model as a plain Python object.
return super().__reduce__()
def __deepcopy__(self, memo):
if self.built:
new = pickle_utils.deserialize_model_from_bytecode(
pickle_utils.serialize_model_as_bytecode(self)
)
memo[id(self)] = new
else:
# See comment in __reduce__ for explanation
deserializer, serialized, *rest = super().__reduce__()
new = deserializer(*serialized)
memo[id(self)] = new
if rest:
state = copy.deepcopy(rest[0], memo=memo)
new.__setstate__(state)
return new
def __copy__(self):
return self.__deepcopy__({})
@generic_utils.default
def build(self, input_shape):
"""Builds the model based on input shapes received.
This is to be used for subclassed models, which do not know at
instantiation time what their inputs look like.
This method only exists for users who want to call `model.build()` in a
standalone way (as a substitute for calling the model on real data to
build it). It will never be called by the framework (and thus it will
never throw unexpected errors in an unrelated workflow).
Args:
input_shape: Single tuple, `TensorShape` instance, or list/dict of
shapes, where shapes are tuples, integers, or `TensorShape`
instances.
Raises:
ValueError:
1. In case of invalid user-provided data (not of type tuple,
list, `TensorShape`, or dict).
2. If the model requires call arguments that are agnostic
to the input shapes (positional or keyword arg in call
signature).
3. If not all layers were properly built.
4. If float type inputs are not supported within the layers.
In each of these cases, the user should build their model by calling
it on real tensor data.
"""
if self._is_graph_network:
super().build(input_shape)
return
if input_shape is None:
raise ValueError(
"Input shape must be defined when calling `build()` on "
"a `Model` subclass."
)
valid_types = (tuple, list, tf.TensorShape, dict)
if not isinstance(input_shape, valid_types):
raise ValueError(
"Specified input shape is not one of the valid types. "
"Please specify a batch input shape of type tuple or "
"list of input shapes. User provided "
"input type: {}.".format(type(input_shape))
)
if input_shape and not self.inputs:
# We create placeholders for the `None`s in the shape and build the
# model in a Graph. Since tf.Variable is compatible with both eager
# execution and graph building, the variables created after building
# the model in a Graph are still valid when executing eagerly.
if tf.executing_eagerly():
graph = tf.__internal__.FuncGraph("build_graph")
else:
graph = backend.get_graph()
with graph.as_default():
if isinstance(input_shape, list) and all(
d is None or isinstance(d, int) for d in input_shape
):
input_shape = tuple(input_shape)
if isinstance(input_shape, list):
x = [
base_layer_utils.generate_placeholders_from_shape(shape)
for shape in input_shape
]
elif isinstance(input_shape, dict):
x = {
k: base_layer_utils.generate_placeholders_from_shape(
shape
)
for k, shape in input_shape.items()
}
else:
x = base_layer_utils.generate_placeholders_from_shape(
input_shape
)
kwargs = {}
call_signature = self._call_spec.full_argspec
call_args = call_signature.args
# Exclude `self`, `inputs`, and any argument with a default
# value.
if len(call_args) > 2:
if call_signature.defaults:
call_args = call_args[2 : -len(call_signature.defaults)]
else:
call_args = call_args[2:]
for arg in call_args:
if arg == "training":
# Case where `training` is a positional arg with no
# default.
kwargs["training"] = False
else:
# Has invalid call signature with unknown positional
# arguments.
raise ValueError(
"Currently, you cannot build your model if it "
"has positional or keyword arguments that are "
"not inputs to the model, but are required for "
"its `call()` method. Instead, in order to "
"instantiate and build your model, `call()` "
"your model on real tensor data with all "
"expected call arguments. The argument "
"for `call()` can be a single list/tuple that "
"contains multiple inputs."
)
elif len(call_args) < 2:
# Signature without `inputs`.
raise ValueError(
"You can only call `build()` on a model if its "
"`call()` method accepts an `inputs` argument."
)
try:
self.call(x, **kwargs)
except (tf.errors.InvalidArgumentError, TypeError) as e:
raise ValueError(
"You cannot build your model by calling `build` "
"if your layers do not support float type inputs. "
"Instead, in order to instantiate and build your "
"model, call your model on real tensor data (of "
"the correct dtype).\n\nThe actual error from "
f"`call` is: {e}."
)
super().build(input_shape)
@traceback_utils.filter_traceback
def __call__(self, *args, **kwargs):
if self._layout_map is not None and not self.built:
# Note that this method is only overridden for DTensor and layout
# injection purpose.
# Capture the inputs and create graph input as replacement for model
# to initialize its weights first.
copied_args = copy.copy(args)
copied_kwargs = copy.copy(kwargs)
(
inputs,
copied_args,
copied_kwargs,
) = self._call_spec.split_out_first_arg(copied_args, copied_kwargs)
def _convert_to_graph_inputs(x):
if isinstance(x, (tf.Tensor, np.ndarray, float, int)):
x = tf.convert_to_tensor(x)
return input_layer_module.Input(x.shape)
# TODO(scottzhu): maybe better handle mask and training flag.
inputs = tf.nest.map_structure(_convert_to_graph_inputs, inputs)
copied_args = tf.nest.map_structure(
_convert_to_graph_inputs, copied_args
)
copied_kwargs = tf.nest.map_structure(
_convert_to_graph_inputs, copied_kwargs
)
with layout_map_lib.layout_map_scope(self._layout_map):
# We ignore the result here.
super().__call__(inputs, *copied_args, **copied_kwargs)
layout_map_lib._map_subclass_model_variable(self, self._layout_map)
return super().__call__(*args, **kwargs)
@doc_controls.doc_in_current_and_subclasses
def call(self, inputs, training=None, mask=None):
"""Calls the model on new inputs and returns the outputs as tensors.
In this case `call()` just reapplies
all ops in the graph to the new inputs
(e.g. build a new computational graph from the provided inputs).
Note: This method should not be called directly. It is only meant to be
overridden when subclassing `tf.keras.Model`.
To call a model on an input, always use the `__call__()` method,
i.e. `model(inputs)`, which relies on the underlying `call()` method.
Args:
inputs: Input tensor, or dict/list/tuple of input tensors.
training: Boolean or boolean scalar tensor, indicating whether to
run the `Network` in training mode or inference mode.
mask: A mask or list of masks. A mask can be either a boolean tensor
or None (no mask). For more details, check the guide
[here](https://www.tensorflow.org/guide/keras/masking_and_padding).
Returns:
A tensor if there is a single output, or
a list of tensors if there are more than one outputs.
"""
raise NotImplementedError(
"Unimplemented `tf.keras.Model.call()`: if you "
"intend to create a `Model` with the Functional "
"API, please provide `inputs` and `outputs` "
"arguments. Otherwise, subclass `Model` with an "
"overridden `call()` method."
)
@traceback_utils.filter_traceback
def compile(
self,
optimizer="rmsprop",
loss=None,
metrics=None,
loss_weights=None,
weighted_metrics=None,
run_eagerly=None,
steps_per_execution=None,
jit_compile=None,
pss_evaluation_shards=0,
**kwargs,
):
"""Configures the model for training.
Example:
```python
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),
loss=tf.keras.losses.BinaryCrossentropy(),
metrics=[tf.keras.metrics.BinaryAccuracy(),
tf.keras.metrics.FalseNegatives()])
```
Args:
optimizer: String (name of optimizer) or optimizer instance. See
`tf.keras.optimizers`.
loss: Loss function. May be a string (name of loss function), or
a `tf.keras.losses.Loss` instance. See `tf.keras.losses`. A loss
function is any callable with the signature `loss = fn(y_true,
y_pred)`, where `y_true` are the ground truth values, and
`y_pred` are the model's predictions.
`y_true` should have shape
`(batch_size, d0, .. dN)` (except in the case of
sparse loss functions such as
sparse categorical crossentropy which expects integer arrays of
shape `(batch_size, d0, .. dN-1)`).
`y_pred` should have shape `(batch_size, d0, .. dN)`.
The loss function should return a float tensor.
If a custom `Loss` instance is
used and reduction is set to `None`, return value has shape
`(batch_size, d0, .. dN-1)` i.e. per-sample or per-timestep loss
values; otherwise, it is a scalar. If the model has multiple
outputs, you can use a different loss on each output by passing a
dictionary or a list of losses. The loss value that will be
minimized by the model will then be the sum of all individual
losses, unless `loss_weights` is specified.
metrics: List of metrics to be evaluated by the model during
training and testing. Each of this can be a string (name of a
built-in function), function or a `tf.keras.metrics.Metric`
instance. See `tf.keras.metrics`. Typically you will use
`metrics=['accuracy']`.
A function is any callable with the signature `result = fn(y_true,
y_pred)`. To specify different metrics for different outputs of a
multi-output model, you could also pass a dictionary, such as
`metrics={'output_a':'accuracy', 'output_b':['accuracy', 'mse']}`.
You can also pass a list to specify a metric or a list of metrics
for each output, such as
`metrics=[['accuracy'], ['accuracy', 'mse']]`
or `metrics=['accuracy', ['accuracy', 'mse']]`. When you pass the
strings 'accuracy' or 'acc', we convert this to one of
`tf.keras.metrics.BinaryAccuracy`,
`tf.keras.metrics.CategoricalAccuracy`,
`tf.keras.metrics.SparseCategoricalAccuracy` based on the shapes
of the targets and of the model output. We do a similar
conversion for the strings 'crossentropy' and 'ce' as well.
The metrics passed here are evaluated without sample weighting; if
you would like sample weighting to apply, you can specify your
metrics via the `weighted_metrics` argument instead.
loss_weights: Optional list or dictionary specifying scalar
coefficients (Python floats) to weight the loss contributions of
different model outputs. The loss value that will be minimized by
the model will then be the *weighted sum* of all individual
losses, weighted by the `loss_weights` coefficients. If a list,
it is expected to have a 1:1 mapping to the model's outputs. If a
dict, it is expected to map output names (strings) to scalar
coefficients.
weighted_metrics: List of metrics to be evaluated and weighted by
`sample_weight` or `class_weight` during training and testing.
run_eagerly: Bool. If `True`, this `Model`'s logic will not be
wrapped in a `tf.function`. Recommended to leave this as `None`
unless your `Model` cannot be run inside a `tf.function`.
`run_eagerly=True` is not supported when using
`tf.distribute.experimental.ParameterServerStrategy`. Defaults to
`False`.
steps_per_execution: Int or `'auto'`. The number of batches to
run during each `tf.function` call. If set to "auto", keras will
automatically tune `steps_per_execution` during runtime. Running
multiple batches inside a single `tf.function` call can greatly
improve performance on TPUs, when used with distributed strategies
such as `ParameterServerStrategy`, or with small models with a
large Python overhead. At most, one full epoch will be run each
execution. If a number larger than the size of the epoch is
passed, the execution will be truncated to the size of the epoch.
Note that if `steps_per_execution` is set to `N`,
`Callback.on_batch_begin` and `Callback.on_batch_end` methods will
only be called every `N` batches (i.e. before/after each
`tf.function` execution). Defaults to `1`.
jit_compile: If `True`, compile the model training step with XLA.
[XLA](https://www.tensorflow.org/xla) is an optimizing compiler
for machine learning.
`jit_compile` is not enabled for by default.
Note that `jit_compile=True`
may not necessarily work for all models.
For more information on supported operations please refer to the
[XLA documentation](https://www.tensorflow.org/xla).
Also refer to
[known XLA issues](https://www.tensorflow.org/xla/known_issues)
for more details.
pss_evaluation_shards: Integer or 'auto'. Used for
`tf.distribute.ParameterServerStrategy` training only. This arg
sets the number of shards to split the dataset into, to enable an
exact visitation guarantee for evaluation, meaning the model will
be applied to each dataset element exactly once, even if workers
fail. The dataset must be sharded to ensure separate workers do
not process the same data. The number of shards should be at least
the number of workers for good performance. A value of 'auto'
turns on exact evaluation and uses a heuristic for the number of
shards based on the number of workers. 0, meaning no
visitation guarantee is provided. NOTE: Custom implementations of
`Model.test_step` will be ignored when doing exact evaluation.
Defaults to `0`.
**kwargs: Arguments supported for backwards compatibility only.
"""
if jit_compile and not tf_utils.can_jit_compile(warn=True):
jit_compile = False
self._compile_config = serialization_lib.Config(
optimizer=optimizer,
loss=loss,
metrics=metrics,
loss_weights=loss_weights,
weighted_metrics=weighted_metrics,
run_eagerly=run_eagerly,
steps_per_execution=steps_per_execution,
jit_compile=jit_compile,
)
with self.distribute_strategy.scope():
if "experimental_steps_per_execution" in kwargs:
logging.warning(
"The argument `steps_per_execution` is no longer "
"experimental. Pass `steps_per_execution` instead of "
"`experimental_steps_per_execution`."
)
if not steps_per_execution:
steps_per_execution = kwargs.pop(
"experimental_steps_per_execution"
)
# When compiling from an already-serialized model, we do not want to
# reapply some processing steps (e.g. metric renaming for
# multi-output models, which have prefixes added for each
# corresponding output name).
from_serialized = kwargs.pop("from_serialized", False)
self._validate_compile(optimizer, metrics, **kwargs)
self._run_eagerly = run_eagerly
self.optimizer = self._get_optimizer(optimizer)
mesh = None
if self._layout_map is not None:
mesh = self._layout_map.get_default_mesh()
if isinstance(loss, compile_utils.LossesContainer):
self.compiled_loss = loss
else:
self.compiled_loss = compile_utils.LossesContainer(
loss,
loss_weights,
output_names=self.output_names,
mesh=mesh,
)
self.compiled_metrics = compile_utils.MetricsContainer(
metrics,
weighted_metrics,
output_names=self.output_names,
from_serialized=from_serialized,
mesh=mesh,
)
if steps_per_execution == "auto":
if self._steps_per_execution is None:
self._configure_steps_per_execution(1)
self._steps_per_execution_tuner = (
steps_per_execution_tuning.StepsPerExecutionTuner(
self.optimizer, self._steps_per_execution
)
)
self._autotune_steps_per_execution = True
else:
self._configure_steps_per_execution(steps_per_execution or 1)
self._pss_evaluation_shards = self._infer_exact_eval_shards(
pss_evaluation_shards
)
# Initializes attrs that are reset each time `compile` is called.
self._reset_compile_cache()
self._is_compiled = True
self.loss = loss or {}
if (self._run_eagerly or self.dynamic) and jit_compile:
raise ValueError(
"You cannot enable `run_eagerly` and `jit_compile` "
"at the same time."
)
else:
self._jit_compile = jit_compile
def _get_optimizer(self, optimizer):
"""Wraps `optimizer` in `LossScaleOptimizer` if necessary."""
def _get_single_optimizer(opt):
opt = optimizers.get(opt)
if self.dtype_policy.name == "mixed_float16" and not isinstance(
opt, lso.BaseLossScaleOptimizer
):
# Loss scaling is necessary with mixed_float16 for models to
# converge to the same accuracy as with float32.
opt = lso.BaseLossScaleOptimizer(opt)
return opt
return tf.nest.map_structure(_get_single_optimizer, optimizer)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _reset_compile_cache(self):
self.train_function = None
self.test_function = None
self.predict_function = None
# Used to cache the `tf.function`'ed `train_function` to be logged in
# TensorBoard, since the original `train_function` is not necessarily
# a `tf.function` (e.g., with ParameterServerStrategy, the
# `train_function` is a scheduling of the actual training function to a
# remote worker).
self.train_tf_function = None
# Used to cache `trainable` attr of `Layer`s for `fit`.
self._compiled_trainable_state = self._get_trainable_state()
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _configure_steps_per_execution(self, steps_per_execution):
self._steps_per_execution = self._create_counter_variable(
steps_per_execution
)
@property
def _should_compute_mask(self):
return False
@property
def metrics(self):
"""Return metrics added using `compile()` or `add_metric()`.
Note: Metrics passed to `compile()` are available only after a
`keras.Model` has been trained/evaluated on actual data.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> [m.name for m in model.metrics]
[]
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> model.fit(x, y)
>>> [m.name for m in model.metrics]
['loss', 'mae']
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> d = tf.keras.layers.Dense(2, name='out')
>>> output_1 = d(inputs)
>>> output_2 = d(inputs)
>>> model = tf.keras.models.Model(
... inputs=inputs, outputs=[output_1, output_2])
>>> model.add_metric(
... tf.reduce_sum(output_2), name='mean', aggregation='mean')
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
>>> model.fit(x, (y, y))
>>> [m.name for m in model.metrics]
['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',
'out_1_acc', 'mean']
"""
metrics = []
if self._is_compiled:
if self.compiled_loss is not None:
metrics += self.compiled_loss.metrics
if self.compiled_metrics is not None:
metrics += self.compiled_metrics.metrics
for l in self._flatten_layers():
metrics.extend(l._metrics)
return metrics
@property
def metrics_names(self):
"""Returns the model's display labels for all outputs.
Note: `metrics_names` are available only after a `keras.Model` has been
trained/evaluated on actual data.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> model.metrics_names
[]
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> model.fit(x, y)
>>> model.metrics_names
['loss', 'mae']
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> d = tf.keras.layers.Dense(2, name='out')
>>> output_1 = d(inputs)
>>> output_2 = d(inputs)
>>> model = tf.keras.models.Model(
... inputs=inputs, outputs=[output_1, output_2])
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
>>> model.fit(x, (y, y))
>>> model.metrics_names
['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',
'out_1_acc']
"""
# This property includes all output names including `loss` and
# per-output losses for backward compatibility.
return [m.name for m in self.metrics]
@property
def distribute_strategy(self):
"""The `tf.distribute.Strategy` this model was created under."""
return self._distribution_strategy or tf.distribute.get_strategy()
@property
def run_eagerly(self):
"""Settable attribute indicating whether the model should run eagerly.
Running eagerly means that your model will be run step by step,
like Python code. Your model might run slower, but it should become
easier for you to debug it by stepping into individual layer calls.
By default, we will attempt to compile your model to a static graph to
deliver the best execution performance.
Returns:
Boolean, whether the model should run eagerly.
"""
if self.dynamic and self._run_eagerly == False:
# TODO(fchollet): consider using py_func to enable this.
raise ValueError(
"Your model contains layers that can only be "
"successfully run in eager execution (layers "
"constructed with `dynamic=True`). "
"You cannot set `run_eagerly=False`."
)
if self._cluster_coordinator and self._run_eagerly:
raise ValueError(
"When using `Model` with `ParameterServerStrategy`, "
"`run_eagerly` is not supported."
)
# Run eagerly logic, by priority:
# (1) Dynamic models must be run eagerly.
# (2) Explicitly setting run_eagerly causes a Model to be run eagerly.
# (3) Not explicitly setting run_eagerly defaults to TF's global
# setting.
return (
self.dynamic
or self._run_eagerly
or (tf.config.functions_run_eagerly() and self._run_eagerly is None)
)
@run_eagerly.setter
def run_eagerly(self, value):
self._run_eagerly = value
@property
def autotune_steps_per_execution(self):
"""Settable property to enable tuning for steps_per_execution"""
return self._autotune_steps_per_execution
@autotune_steps_per_execution.setter
def autotune_steps_per_execution(self, value):
self._autotune_steps_per_execution = value
if value and self._steps_per_execution_tuner is None:
if self._steps_per_execution is None:
self._configure_steps_per_execution(1)
self._steps_per_execution_tuner = (
steps_per_execution_tuning.StepsPerExecutionTuner(
self.optimizer, self._steps_per_execution
)
)
@property
def steps_per_execution(self):
"""Settable `steps_per_execution variable. Requires a compiled model."""
return self._steps_per_execution
@steps_per_execution.setter
def steps_per_execution(self, value):
if self._steps_per_execution is None:
self._configure_steps_per_execution(value)
else:
self._steps_per_execution.assign(value)
@property
def jit_compile(self):
"""Specify whether to compile the model with XLA.
[XLA](https://www.tensorflow.org/xla) is an optimizing compiler
for machine learning. `jit_compile` is not enabled by default.
Note that `jit_compile=True` may not necessarily work for all models.
For more information on supported operations please refer to the
[XLA documentation](https://www.tensorflow.org/xla). Also refer to
[known XLA issues](https://www.tensorflow.org/xla/known_issues)
for more details.
"""
return self._jit_compile
@jit_compile.setter
def jit_compile(self, value):
# Function remains cached with previous jit_compile settings
if self._jit_compile == value:
# Avoid resetting compiler cache if possible if the value is the
# same
return
# Check if TensorFlow is compiled with XLA before setting the value
if value and not tf_utils.can_jit_compile(warn=True):
self._jit_compile = False
return
self._jit_compile = value
# Setting `jit_compile` should invalidate previously cached functions.
self._reset_compile_cache()
@property
def distribute_reduction_method(self):
"""The method employed to reduce per-replica values during training.
Unless specified, the value "auto" will be assumed, indicating that
the reduction strategy should be chosen based on the current
running environment.
See `reduce_per_replica` function for more details.
"""
return self._distribute_reduction_method or "auto"
@distribute_reduction_method.setter
def distribute_reduction_method(self, value):
self._distribute_reduction_method = value
def _validate_target_and_loss(self, y, loss):
"""Raises error if target or loss is not found.
This method verifies that the target and loss are properly populated
when applicable, or raises errors.
Args:
y: the target for training.
loss: the total loss tensor including loss added via `compile` and
`add_loss`.
"""
# `self.loss` references the loss added via `compile` call. If users
# have provided such, the target must be provided; otherwise it's a user
# error. Note that `self.loss` does not include losses added via
# `add_loss`, and it is a valid use when such loss from `add_loss`
# exists and target does not.
if self.loss and y is None:
raise ValueError(
"Target data is missing. Your model was compiled with "
f"loss={self.loss}, "
"and therefore expects target data to be provided in `fit()`."
)
# For training, there must be compiled loss or regularization loss to
# exist in order to apply the gradients. If one is not found, it means
# no loss was supplied via `compile` or `add_loss`.
elif loss is None:
raise ValueError(
"No loss found. You may have forgotten to provide a `loss` "
"argument in the `compile()` method."
)
def train_step(self, data):
"""The logic for one training step.
This method can be overridden to support custom training logic.
For concrete examples of how to override this method see
[Customizing what happens in fit](
https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit).
This method is called by `Model.make_train_function`.
This method should contain the mathematical logic for one step of
training. This typically includes the forward pass, loss calculation,
backpropagation, and metric updates.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_train_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the
values of the `Model`'s metrics are returned. Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data)
# Run forward pass.
with tf.GradientTape() as tape:
y_pred = self(x, training=True)
loss = self.compute_loss(x, y, y_pred, sample_weight)
self._validate_target_and_loss(y, loss)
# Run backwards pass.
self.optimizer.minimize(loss, self.trainable_variables, tape=tape)
return self.compute_metrics(x, y, y_pred, sample_weight)
def compute_loss(self, x=None, y=None, y_pred=None, sample_weight=None):
"""Compute the total loss, validate it, and return it.
Subclasses can optionally override this method to provide custom loss
computation logic.
Example:
```python
class MyModel(tf.keras.Model):
def __init__(self, *args, **kwargs):
super(MyModel, self).__init__(*args, **kwargs)
self.loss_tracker = tf.keras.metrics.Mean(name='loss')
def compute_loss(self, x, y, y_pred, sample_weight):
loss = tf.reduce_mean(tf.math.squared_difference(y_pred, y))
loss += tf.add_n(self.losses)
self.loss_tracker.update_state(loss)
return loss
def reset_metrics(self):
self.loss_tracker.reset_states()
@property
def metrics(self):
return [self.loss_tracker]
tensors = tf.random.uniform((10, 10)), tf.random.uniform((10,))
dataset = tf.data.Dataset.from_tensor_slices(tensors).repeat().batch(1)
inputs = tf.keras.layers.Input(shape=(10,), name='my_input')
outputs = tf.keras.layers.Dense(10)(inputs)
model = MyModel(inputs, outputs)
model.add_loss(tf.reduce_sum(outputs))
optimizer = tf.keras.optimizers.SGD()
model.compile(optimizer, loss='mse', steps_per_execution=10)
model.fit(dataset, epochs=2, steps_per_epoch=10)
print('My custom loss: ', model.loss_tracker.result().numpy())
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
The total loss as a `tf.Tensor`, or `None` if no loss results (which
is the case when called by `Model.test_step`).
"""
del x # The default implementation does not use `x`.
return self.compiled_loss(
y, y_pred, sample_weight, regularization_losses=self.losses
)
def compute_metrics(self, x, y, y_pred, sample_weight):
"""Update metric states and collect all metrics to be returned.
Subclasses can optionally override this method to provide custom metric
updating and collection logic.
Example:
```python
class MyModel(tf.keras.Sequential):
def compute_metrics(self, x, y, y_pred, sample_weight):
# This super call updates `self.compiled_metrics` and returns
# results for all metrics listed in `self.metrics`.
metric_results = super(MyModel, self).compute_metrics(
x, y, y_pred, sample_weight)
# Note that `self.custom_metric` is not listed in `self.metrics`.
self.custom_metric.update_state(x, y, y_pred, sample_weight)
metric_results['custom_metric_name'] = self.custom_metric.result()
return metric_results
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model.call(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end()`. Typically, the
values of the metrics listed in `self.metrics` are returned. Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
del x # The default implementation does not use `x`.
self.compiled_metrics.update_state(y, y_pred, sample_weight)
return self.get_metrics_result()
def get_metrics_result(self):
"""Returns the model's metrics values as a dict.
If any of the metric result is a dict (containing multiple metrics),
each of them gets added to the top level returned dict of this method.
Returns:
A `dict` containing values of the metrics listed in `self.metrics`.
Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
# Collect metrics to return
return_metrics = {}
for metric in self.metrics:
result = metric.result()
if isinstance(result, dict):
return_metrics.update(result)
else:
return_metrics[metric.name] = result
return return_metrics
def _validate_and_get_metrics_result(self, logs):
"""Returns model metrics as a dict if the keys match with input logs.
When the training / evalution is performed with asynchronous steps, such
as the case with `tf.distribute.ParameterServerStrategy`, the last
scheduled `train / test_step` may not give the latest metrics because it
is not guaranteed to be executed the last. This method gets metrics from
the model directly instead of relying on the return from last step
function.
It logs a warning if the metric results could not be overridden when
used with `tf.distribute.ParameterServerStrategy`.
When the user has custom train / test step functions, the metrics
returned may be different from `Model.metrics`. In those instances,
this function will be no-op and return the logs.
Args:
logs: A `dict` of metrics returned by train / test step function.
Returns:
A `dict` containing values of the metrics listed in `self.metrics`
when logs and model metrics keys match. Otherwise it returns input
`logs`.
"""
PSS_WARN_MSG = "Could not get Model metric results. \
Using the results of last step function could lead to incorrect \
results when used with ParameterServerStrategy"
try:
metric_logs = self.get_metrics_result()
except TypeError:
if self._cluster_coordinator:
logging.warning(PSS_WARN_MSG)
else:
# Verify that train / test step logs passed and metric logs have
# matching keys. Could be different when using custom step functions
if isinstance(logs, dict) and set(logs.keys()) == set(
metric_logs.keys()
):
logs = tf_utils.sync_to_numpy_or_python_type(metric_logs)
elif self._cluster_coordinator:
logging.warning(PSS_WARN_MSG)
return logs
def _aggregate_exact_metrics(self, logs):
# When doing exact evaluation, `logs` is a list of each data shard's
# metric variables, which will be used to update the metrics.
for shard_result in logs:
for metric in self.metrics:
if metric.name not in shard_result.keys():
logging.log_first_n(
logging.WARN,
f"No matching result found for metric {metric.name}. "
"This metric's computed result may be incorrect.",
3,
)
continue
metric_result = shard_result[metric.name]
if len(metric_result) != len(metric.weights):
raise ValueError(
f"Expected {len(metric.weights)} variables in result "
f"for metric {metric.name}, but found "
f"{len(metric_result)}."
)
for weight, val in zip(metric.weights, metric_result):
weight.assign_add(val)
return self.get_metrics_result()
def make_train_function(self, force=False):
"""Creates a function that executes one step of training.
This method can be overridden to support custom training logic.
This method is called by `Model.fit` and `Model.train_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual training
logic to `Model.train_step`.
This function is cached the first time `Model.fit` or
`Model.train_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the train function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_train_batch_end`, such as
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
if self.train_function is not None and not force:
return self.train_function
def step_function(model, iterator):
"""Runs a single training step."""
def run_step(data):
outputs = model.train_step(data)
# Ensure counter is updated only if `train_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._train_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def train_function(iterator):
"""Runs a training execution with a single step."""
return step_function(self, iterator)
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
if self._cluster_coordinator:
self.train_function = (
lambda it: self._cluster_coordinator.schedule(
train_function, args=(it,)
)
)
else:
self.train_function = train_function
# If we're using a coordinator, use the value of
# self._steps_per_execution at the time the function is
# called/scheduled, and not when it is actually executed.
elif self._cluster_coordinator:
def train_function(iterator, steps_per_execution):
"""Runs a training execution with multiple steps."""
for _ in tf.range(steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
self.train_function = lambda it: self._cluster_coordinator.schedule(
train_function, args=(it, self._steps_per_execution.value())
)
else:
def train_function(iterator):
"""Runs a training execution with multiple steps."""
for _ in tf.range(self._steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
self.train_function = train_function
return self.train_function
@traceback_utils.filter_traceback
def fit(
self,
x=None,
y=None,
batch_size=None,
epochs=1,
verbose="auto",
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_batch_size=None,
validation_freq=1,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
):
"""Trains the model for a fixed number of epochs (dataset iterations).
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A `tf.data` dataset. Should return a tuple
of either `(inputs, targets)` or
`(inputs, targets, sample_weights)`.
- A generator or `keras.utils.Sequence` returning `(inputs,
targets)` or `(inputs, targets, sample_weights)`.
- A `tf.keras.utils.experimental.DatasetCreator`, which wraps a
callable that takes a single argument of type
`tf.distribute.InputContext`, and returns a `tf.data.Dataset`.
`DatasetCreator` should be used when users prefer to specify the
per-replica batching and sharding logic for the `Dataset`.
See `tf.keras.utils.experimental.DatasetCreator` doc for more
information.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given below. If these
include `sample_weights` as a third component, note that sample
weighting applies to the `weighted_metrics` argument but not the
`metrics` argument in `compile()`. If using
`tf.distribute.experimental.ParameterServerStrategy`, only
`DatasetCreator` type is supported for `x`.
y: Target data. Like the input data `x`,
it could be either Numpy array(s) or TensorFlow tensor(s).
It should be consistent with `x` (you cannot have Numpy inputs and
tensor targets, or inversely). If `x` is a dataset, generator,
or `keras.utils.Sequence` instance, `y` should
not be specified (since targets will be obtained from `x`).
batch_size: Integer or `None`.
Number of samples per gradient 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).
epochs: Integer. Number of epochs to train the model.
An epoch is an iteration over the entire `x` and `y`
data provided
(unless the `steps_per_epoch` flag is set to
something other than None).
Note that in conjunction with `initial_epoch`,
`epochs` is to be understood as "final epoch".
The model is not trained for a number of iterations
given by `epochs`, but merely until the epoch
of index `epochs` is reached.
verbose: 'auto', 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = one line per epoch.
'auto' becomes 1 for most cases, but 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so verbose=2 is
recommended when not running interactively (eg, in a production
environment). Defaults to 'auto'.
callbacks: List of `keras.callbacks.Callback` instances.
List of callbacks to apply during training.
See `tf.keras.callbacks`. Note
`tf.keras.callbacks.ProgbarLogger` and
`tf.keras.callbacks.History` callbacks are created automatically
and need not be passed into `model.fit`.
`tf.keras.callbacks.ProgbarLogger` is created or not based on
`verbose` argument to `model.fit`.
Callbacks with batch-level calls are currently unsupported with
`tf.distribute.experimental.ParameterServerStrategy`, and users
are advised to implement epoch-level calls instead with an
appropriate `steps_per_epoch` value.
validation_split: Float between 0 and 1.
Fraction of the training data to be used as validation data.
The model will set apart this fraction of the training data,
will not train on it, and will evaluate
the loss and any model metrics
on this data at the end of each epoch.
The validation data is selected from the last samples
in the `x` and `y` data provided, before shuffling. This
argument is not supported when `x` is a dataset, generator or
`keras.utils.Sequence` instance.
If both `validation_data` and `validation_split` are provided,
`validation_data` will override `validation_split`.
`validation_split` is not yet supported with
`tf.distribute.experimental.ParameterServerStrategy`.
validation_data: Data on which to evaluate
the loss and any model metrics at the end of each epoch.
The model will not be trained on this data. Thus, note the fact
that the validation loss of data provided using
`validation_split` or `validation_data` is not affected by
regularization layers like noise and dropout.
`validation_data` will override `validation_split`.
`validation_data` could be:
- A tuple `(x_val, y_val)` of Numpy arrays or tensors.
- A tuple `(x_val, y_val, val_sample_weights)` of NumPy
arrays.
- A `tf.data.Dataset`.
- A Python generator or `keras.utils.Sequence` returning
`(inputs, targets)` or `(inputs, targets, sample_weights)`.
`validation_data` is not yet supported with
`tf.distribute.experimental.ParameterServerStrategy`.
shuffle: Boolean (whether to shuffle the training data
before each epoch) or str (for 'batch'). This argument is
ignored when `x` is a generator or an object of tf.data.Dataset.
'batch' is a special option for dealing
with the limitations of HDF5 data; it shuffles in batch-sized
chunks. Has no effect when `steps_per_epoch` is not `None`.
class_weight: Optional dictionary mapping class indices (integers)
to a weight (float) value, used for weighting the loss function
(during training only).
This can be useful to tell the model to
"pay more attention" to samples from
an under-represented class. When `class_weight` is specified
and targets have a rank of 2 or greater, either `y` must be
one-hot encoded, or an explicit final dimension of `1` must
be included for sparse class labels.
sample_weight: Optional Numpy array of weights for
the training samples, used for weighting the loss function
(during training only). You can either pass a flat (1D)
Numpy array with the same length as the input samples
(1:1 mapping between weights and samples),
or in the case of temporal data,
you can pass a 2D array with shape
`(samples, sequence_length)`,
to apply a different weight to every timestep of every sample.
This argument is not supported when `x` is a dataset, generator,
or `keras.utils.Sequence` instance, instead provide the
sample_weights as the third element of `x`.
Note that sample weighting does not apply to metrics specified
via the `metrics` argument in `compile()`. To apply sample
weighting to your metrics, you can specify them via the
`weighted_metrics` in `compile()` instead.
initial_epoch: Integer.
Epoch at which to start training
(useful for resuming a previous training run).
steps_per_epoch: Integer or `None`.
Total number of steps (batches of samples)
before declaring one epoch finished and starting the
next epoch. 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_per_epoch'
is None, the epoch will run until the input dataset is
exhausted. When passing an infinitely repeating dataset, you
must specify the `steps_per_epoch` argument. If
`steps_per_epoch=-1` the training will run indefinitely with an
infinitely repeating dataset. This argument is not supported
with array inputs.
When using `tf.distribute.experimental.ParameterServerStrategy`:
* `steps_per_epoch=None` is not supported.
validation_steps: Only relevant if `validation_data` is provided and
is a `tf.data` dataset. Total number of steps (batches of
samples) to draw before stopping when performing validation
at the end of every epoch. If 'validation_steps' is None,
validation will run until the `validation_data` dataset is
exhausted. In the case of an infinitely repeated dataset, it
will run into an infinite loop. If 'validation_steps' is
specified and only part of the dataset will be consumed, the
evaluation will start from the beginning of the dataset at each
epoch. This ensures that the same validation samples are used
every time.
validation_batch_size: Integer or `None`.
Number of samples per validation batch.
If unspecified, will default to `batch_size`.
Do not specify the `validation_batch_size` if your data is in
the form of datasets, generators, or `keras.utils.Sequence`
instances (since they generate batches).
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.
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the generator
queue. If unspecified, `max_queue_size` will default to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up
when using process-based threading. If unspecified, `workers`
will default to 1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
Unpacking behavior for iterator-like inputs:
A common pattern is to pass a tf.data.Dataset, generator, or
tf.keras.utils.Sequence to the `x` argument of fit, which will in fact
yield not only features (x) but optionally targets (y) and sample
weights. TF-Keras requires that the output of such iterator-likes be
unambiguous. The iterator should return a tuple of length 1, 2, or 3,
where the optional second and third elements will be used for y and
sample_weight respectively. Any other type provided will be wrapped in
a length one tuple, effectively treating everything as 'x'. When
yielding dicts, they should still adhere to the top-level tuple
structure.
e.g. `({"x0": x0, "x1": x1}, y)`. TF-Keras will not attempt to
separate features, targets, and weights from the keys of a single
dict.
A notable unsupported data type is the namedtuple. The reason is
that it behaves like both an ordered datatype (tuple) and a mapping
datatype (dict). So given a namedtuple of the form:
`namedtuple("example_tuple", ["y", "x"])`
it is ambiguous whether to reverse the order of the elements when
interpreting the value. Even worse is a tuple of the form:
`namedtuple("other_tuple", ["x", "y", "z"])`
where it is unclear if the tuple was intended to be unpacked into x,
y, and sample_weight or passed through as a single element to `x`. As
a result the data processing code will simply raise a ValueError if it
encounters a namedtuple. (Along with instructions to remedy the
issue.)
Returns:
A `History` object. Its `History.history` attribute is
a record of training loss values and metrics values
at successive epochs, as well as validation loss values
and validation metrics values (if applicable).
Raises:
RuntimeError: 1. If the model was never compiled or,
2. If `model.fit` is wrapped in `tf.function`.
ValueError: In case of mismatch between the provided input data
and what the model expects or when the input data is empty.
"""
# Legacy graph support is contained in `training_v1.Model`.
version_utils.disallow_legacy_graph("Model", "fit")
self._assert_compile_was_called()
self._check_call_args("fit")
_disallow_inside_tf_function("fit")
verbose = _get_verbosity(verbose, self.distribute_strategy)
if validation_split and validation_data is None:
# Create the validation data using the training data. Only supported
# for `Tensor` and `NumPy` input.
(
x,
y,
sample_weight,
), validation_data = data_adapter.train_validation_split(
(x, y, sample_weight), validation_split=validation_split
)
if validation_data:
(
val_x,
val_y,
val_sample_weight,
) = data_adapter.unpack_x_y_sample_weight(validation_data)
if self.distribute_strategy._should_use_with_coordinator:
self._cluster_coordinator = (
tf.distribute.experimental.coordinator.ClusterCoordinator(
self.distribute_strategy
)
)
with self.distribute_strategy.scope(), training_utils.RespectCompiledTrainableState( # noqa: E501
self
):
# Creates a `tf.data.Dataset` and handles batch and epoch iteration.
data_handler = data_adapter.get_data_handler(
x=x,
y=y,
sample_weight=sample_weight,
batch_size=batch_size,
steps_per_epoch=steps_per_epoch,
initial_epoch=initial_epoch,
epochs=epochs,
shuffle=shuffle,
class_weight=class_weight,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=epochs,
steps=data_handler.inferred_steps,
)
self.stop_training = False
self.train_function = self.make_train_function()
self._train_counter.assign(0)
callbacks.on_train_begin()
training_logs = None
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
# Handle fault-tolerance for multi-worker.
# TODO(omalleyt): Fix the ordering issues that mean this has to
# happen after `callbacks.on_train_begin`.
steps_per_epoch_inferred = (
steps_per_epoch or data_handler.inferred_steps
)
(
data_handler._initial_epoch,
data_handler._initial_step,
) = self._maybe_load_initial_counters_from_ckpt(
steps_per_epoch_inferred, initial_epoch
)
logs = None
for epoch, iterator in data_handler.enumerate_epochs():
self.reset_metrics()
callbacks.on_epoch_begin(epoch)
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
with tf.profiler.experimental.Trace(
"train",
epoch_num=epoch,
step_num=step,
batch_size=batch_size,
_r=1,
):
callbacks.on_train_batch_begin(step)
tmp_logs = self.train_function(iterator)
if data_handler.should_sync:
context.async_wait()
# No error, now safe to assign to logs.
logs = tmp_logs
end_step = step + data_handler.step_increment
callbacks.on_train_batch_end(end_step, logs)
if self.stop_training:
break
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if logs is None:
raise ValueError(
"Unexpected result of `train_function` "
"(Empty logs). This could be due to issues in input "
"pipeline that resulted in an empty dataset. "
"Otherwise, please use "
"`Model.compile(..., run_eagerly=True)`, or "
"`tf.config.run_functions_eagerly(True)` for more "
"information of where went wrong, or file a "
"issue/bug to `tf.keras`."
)
# Override with model metrics instead of last step logs
logs = self._validate_and_get_metrics_result(logs)
epoch_logs = copy.copy(logs)
# Run validation.
if validation_data and self._should_eval(
epoch, validation_freq
):
if self._pss_evaluation_shards:
self._disallow_exact_eval_with_add_metrics()
# Create data_handler for evaluation and cache it.
if getattr(self, "_eval_data_handler", None) is None:
self._eval_data_handler = data_adapter.get_data_handler(
x=val_x,
y=val_y,
sample_weight=val_sample_weight,
batch_size=validation_batch_size or batch_size,
steps_per_epoch=validation_steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
pss_evaluation_shards=self._pss_evaluation_shards,
)
val_logs = self.evaluate(
x=val_x,
y=val_y,
sample_weight=val_sample_weight,
batch_size=validation_batch_size or batch_size,
steps=validation_steps,
callbacks=callbacks,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
return_dict=True,
_use_cached_eval_dataset=True,
)
val_logs = {
"val_" + name: val for name, val in val_logs.items()
}
epoch_logs.update(val_logs)
callbacks.on_epoch_end(epoch, epoch_logs)
training_logs = epoch_logs
if self.stop_training:
break
if isinstance(self.optimizer, optimizer.Optimizer) and epochs > 0:
self.optimizer.finalize_variable_values(
self.trainable_variables
)
# If eval data_handler exists, delete it after all epochs are done.
if getattr(self, "_eval_data_handler", None) is not None:
del self._eval_data_handler
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_train_end(logs=training_logs)
return self.history
def test_step(self, data):
"""The logic for one evaluation step.
This method can be overridden to support custom evaluation logic.
This method is called by `Model.make_test_function`.
This function should contain the mathematical logic for one step of
evaluation.
This typically includes the forward pass, loss calculation, and metrics
updates.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_test_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the
values of the `Model`'s metrics are returned.
"""
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data)
y_pred = self(x, training=False)
# Updates stateful loss metrics.
self.compute_loss(x, y, y_pred, sample_weight)
return self.compute_metrics(x, y, y_pred, sample_weight)
def _make_test_function_exact(self):
if getattr(self, "_shard_test_function", None):
return self._shard_test_function
def step_function(batch):
def run_step(data):
# TODO(b/272050910): Use sample_weight for weighted metrics.
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(
data
)
y_pred = self(x, training=False)
return x, y, y_pred, sample_weight
if self._jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
outputs = self.distribute_strategy.run(run_step, args=(batch,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
def shard_test_function(dataset, total_shards, shard_idx):
# Copy loss and metric variables to the worker and work with them
# locally. This ensures each shard function is atomic: if a worker
# is preempted, the intermediate progress is discarded and that
# shard is retried. This in turn guarantees exactly-once visitation.
local_unweighted_metrics, local_weighted_metrics = [], []
with tf_utils.with_metric_local_vars_scope():
# TODO(jmullenbach): implement and use a clone for
# `MetricsContainer` and use its `update_state` method directly.
for metric in self.compiled_metrics.unweighted_metrics:
if metric is not None:
local_unweighted_metrics.append(
base_metric.clone_metric(metric)
)
for metric in self.compiled_metrics.weighted_metrics:
if metric is not None:
local_weighted_metrics.append(
base_metric.clone_metric(metric)
)
local_loss = compile_utils.LossesContainer.from_config(
self.compiled_loss.get_config()
)
dataset = input_ops.auto_shard_dataset(
dataset, total_shards, shard_idx
)
iterator = iter(dataset)
with distribute_utils.cache_variable_reads():
for batch in iterator:
x, y, y_pred, sample_weight = step_function(batch)
for weighted_metric in local_weighted_metrics:
weighted_metric.update_state(y, y_pred, sample_weight)
for unweighted_metric in local_unweighted_metrics:
unweighted_metric.update_state(y, y_pred)
local_loss(y, y_pred, sample_weight)
local_metrics = (
local_unweighted_metrics
+ local_weighted_metrics
+ local_loss.metrics
)
outputs = {metric.name: metric.weights for metric in local_metrics}
with tf.control_dependencies(_minimum_control_deps(outputs)):
self._test_counter.assign_add(1)
return outputs
if not self.run_eagerly:
shard_test_function = tf.function(
shard_test_function, reduce_retracing=True
)
self._shard_test_function = (
lambda *args: self._cluster_coordinator.schedule(
shard_test_function,
args=args,
)
)
return self._shard_test_function
def make_test_function(self, force=False):
"""Creates a function that executes one step of evaluation.
This method can be overridden to support custom evaluation logic.
This method is called by `Model.evaluate` and `Model.test_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.test_step`.
This function is cached the first time `Model.evaluate` or
`Model.test_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the test function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_test_batch_end`.
"""
if self.test_function is not None and not force:
return self.test_function
def step_function(model, iterator):
"""Runs a single evaluation step."""
def run_step(data):
outputs = model.test_step(data)
# Ensure counter is updated only if `test_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._test_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def test_function(iterator):
"""Runs a test execution with a single step."""
return step_function(self, iterator)
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
if self._cluster_coordinator:
self.test_function = (
lambda it: self._cluster_coordinator.schedule(
test_function, args=(it,)
)
)
else:
self.test_function = test_function
# If we're using a coordinator, use the value of
# self._steps_per_execution at the time the function is
# called/scheduled, and not when it is actually executed.
elif self._cluster_coordinator:
def test_function(iterator, steps_per_execution):
"""Runs a test execution with multiple steps."""
for _ in tf.range(steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
self.test_function = lambda it: self._cluster_coordinator.schedule(
test_function, args=(it, self._steps_per_execution.value())
)
else:
def test_function(iterator):
"""Runs a test execution with multiple steps."""
for _ in tf.range(self._steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
self.test_function = test_function
return self.test_function
@traceback_utils.filter_traceback
def evaluate(
self,
x=None,
y=None,
batch_size=None,
verbose="auto",
sample_weight=None,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
return_dict=False,
**kwargs,
):
"""Returns the loss value & metrics values for the model in test mode.
Computation is done in batches (see the `batch_size` arg.)
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A `tf.data` dataset. Should return a tuple
of either `(inputs, targets)` or
`(inputs, targets, sample_weights)`.
- A generator or `keras.utils.Sequence` returning `(inputs,
targets)` or `(inputs, targets, sample_weights)`.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given in the `Unpacking
behavior for iterator-like inputs` section of `Model.fit`.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s). It should be consistent with `x`
(you cannot have Numpy inputs and tensor targets, or inversely).
If `x` is a dataset, generator or `keras.utils.Sequence` instance,
`y` should not be specified (since targets will be obtained from
the iterator/dataset).
batch_size: Integer or `None`. Number of samples per batch of
computation. If unspecified, `batch_size` will default to 32. Do
not specify the `batch_size` if your data is in the form of a
dataset, generators, or `keras.utils.Sequence` instances (since
they generate batches).
verbose: `"auto"`, 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = single line.
`"auto"` becomes 1 for most cases, and to 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so `verbose=2` is
recommended when not running interactively (e.g. in a production
environment). Defaults to 'auto'.
sample_weight: Optional Numpy array of weights for the test samples,
used for weighting the loss function. You can either pass a flat
(1D) Numpy array with the same length as the input samples
(1:1 mapping between weights and samples), or in the case of
temporal data, you can pass a 2D array with shape `(samples,
sequence_length)`, to apply a different weight to every
timestep of every sample. This argument is not supported when
`x` is a dataset, instead pass sample weights as the third
element of `x`.
steps: Integer or `None`. Total number of steps (batches of samples)
before declaring the evaluation round finished. Ignored with the
default value of `None`. If x is a `tf.data` dataset and `steps`
is None, 'evaluate' will run until the dataset is exhausted. This
argument is not supported with array inputs.
callbacks: List of `keras.callbacks.Callback` instances. List of
callbacks to apply during evaluation. See
[callbacks](https://www.tensorflow.org/api_docs/python/tf/tf_keras/callbacks).
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the generator
queue. If unspecified, `max_queue_size` will default to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, `workers` will default to
1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
**kwargs: Unused at this time.
See the discussion of `Unpacking behavior for iterator-like inputs` for
`Model.fit`.
Returns:
Scalar test 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 scalar outputs.
Raises:
RuntimeError: If `model.evaluate` is wrapped in a `tf.function`.
"""
version_utils.disallow_legacy_graph("Model", "evaluate")
self._assert_compile_was_called()
self._check_call_args("evaluate")
self._check_sample_weight_warning(x, sample_weight)
_disallow_inside_tf_function("evaluate")
use_cached_eval_dataset = kwargs.pop("_use_cached_eval_dataset", False)
if kwargs:
raise TypeError(f"Invalid keyword arguments: {list(kwargs.keys())}")
if self.distribute_strategy._should_use_with_coordinator:
self._cluster_coordinator = (
tf.distribute.experimental.coordinator.ClusterCoordinator(
self.distribute_strategy
)
)
verbose = _get_verbosity(verbose, self.distribute_strategy)
if self._pss_evaluation_shards:
self._disallow_exact_eval_with_add_metrics()
with self.distribute_strategy.scope():
# Use cached evaluation data only when it's called in `Model.fit`
if (
use_cached_eval_dataset
and getattr(self, "_eval_data_handler", None) is not None
):
data_handler = self._eval_data_handler
else:
# Creates a `tf.data.Dataset` and handles batch and epoch
# iteration.
data_handler = data_adapter.get_data_handler(
x=x,
y=y,
sample_weight=sample_weight,
batch_size=batch_size,
steps_per_epoch=steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
pss_evaluation_shards=self._pss_evaluation_shards,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=1,
steps=data_handler.inferred_steps,
)
# Initialize to prevent errors if 0 epochs are evaluated.
logs = {}
test_function_runner = self._get_test_function_runner(callbacks)
self._test_counter.assign(0)
callbacks.on_test_begin()
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
for (
_,
dataset_or_iterator,
) in data_handler.enumerate_epochs(): # Single epoch.
self.reset_metrics()
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
with tf.profiler.experimental.Trace(
"test", step_num=step, _r=1
):
callbacks.on_test_batch_begin(step)
logs = test_function_runner.run_step(
dataset_or_iterator,
data_handler,
step,
self._pss_evaluation_shards,
)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
# Override with model metrics instead of last step logs
if self._pss_evaluation_shards:
logs = self._aggregate_exact_metrics(logs)
else:
logs = self._validate_and_get_metrics_result(logs)
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_test_end(logs=logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def _disallow_exact_eval_with_add_metrics(self):
metrics_from_add_metric = [
metric
for layer in self._flatten_layers()
for metric in layer._metrics
]
compiled_metrics = self.compiled_metrics.metrics
if any(
[
metric not in compiled_metrics
for metric in metrics_from_add_metric
]
):
raise ValueError(
"Detected that a metric was added to this model "
"via `Model.add_metric`. This is not currently "
"supported when using exact evaluation with "
"`tf.distribute.ParameterServerStrategy`."
)
def _infer_exact_eval_shards(self, pss_evaluation_shards):
if not self.distribute_strategy._should_use_with_coordinator:
return 0
if pss_evaluation_shards == "auto":
# TODO(b/264265138) evaluate and improve this heuristic
return self.distribute_strategy._num_workers * 5
return pss_evaluation_shards
def _get_test_function_runner(self, callbacks):
if (
self._pss_evaluation_shards
and self.distribute_strategy._should_use_with_coordinator
):
self.test_function = self._make_test_function_exact()
test_function_runner = _ExactTestFunction(
self.test_function, callbacks
)
else:
self.test_function = self.make_test_function()
test_function_runner = _TestFunction(self.test_function, callbacks)
return test_function_runner
def predict_step(self, data):
"""The logic for one inference step.
This method can be overridden to support custom inference logic.
This method is called by `Model.make_predict_function`.
This method should contain the mathematical logic for one step of
inference. This typically includes the forward pass.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_predict_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
The result of one inference step, typically the output of calling the
`Model` on data.
"""
x, _, _ = data_adapter.unpack_x_y_sample_weight(data)
return self(x, training=False)
def make_predict_function(self, force=False):
"""Creates a function that executes one step of inference.
This method can be overridden to support custom inference logic.
This method is called by `Model.predict` and `Model.predict_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.predict_step`.
This function is cached the first time `Model.predict` or
`Model.predict_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the predict function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return the outputs of the `Model`.
"""
if self.predict_function is not None and not force:
return self.predict_function
def step_function(model, iterator):
"""Runs a single evaluation step."""
def run_step(data):
outputs = model.predict_step(data)
# Ensure counter is updated only if `test_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._predict_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs, self.distribute_strategy, reduction="concat"
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def predict_function(iterator):
"""Runs an evaluation execution with a single step."""
return step_function(self, iterator)
else:
def predict_function(iterator):
"""Runs an evaluation execution with multiple steps."""
outputs = step_function(self, iterator)
for _ in tf.range(self._steps_per_execution - 1):
tf.autograph.experimental.set_loop_options(
shape_invariants=[
(
outputs,
tf.nest.map_structure(
lambda t: tf_utils.get_tensor_spec(
t, dynamic_batch=True
).shape,
outputs,
),
)
]
)
step_outputs = step_function(self, iterator)
outputs = tf.nest.map_structure(
lambda t1, t2: concat([t1, t2]), outputs, step_outputs
)
return outputs
if not self.run_eagerly:
predict_function = tf.function(
predict_function, reduce_retracing=True
)
self.predict_function = predict_function
return self.predict_function
@traceback_utils.filter_traceback
def predict(
self,
x,
batch_size=None,
verbose="auto",
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
):
"""Generates output predictions for the input samples.
Computation is done in batches. This method is designed for batch
processing of large numbers of inputs. It is not intended for use inside
of loops that iterate over your data and process small numbers of inputs
at a time.
For small numbers of inputs that fit in one batch,
directly use `__call__()` for faster execution, e.g.,
`model(x)`, or `model(x, training=False)` if you have layers such as
`tf.keras.layers.BatchNormalization` that behave differently during
inference. You may pair the individual model call with a `tf.function`
for additional performance inside your inner loop.
If you need access to numpy array values instead of tensors after your
model call, you can use `tensor.numpy()` to get the numpy array value of
an eager tensor.
Also, note the fact that test loss is not affected by
regularization layers like noise and dropout.
Note: See [this FAQ entry](
https://keras.io/getting_started/faq/#whats-the-difference-between-model-methods-predict-and-call)
for more details about the difference between `Model` methods
`predict()` and `__call__()`.
Args:
x: Input samples. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A `tf.data` dataset.
- A generator or `keras.utils.Sequence` instance.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given in the `Unpacking
behavior for iterator-like inputs` section of `Model.fit`.
batch_size: Integer or `None`.
Number of samples per batch.
If unspecified, `batch_size` will default to 32.
Do not specify the `batch_size` if your data is in the
form of dataset, generators, or `keras.utils.Sequence` instances
(since they generate batches).
verbose: `"auto"`, 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = single line.
`"auto"` becomes 1 for most cases, and to 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so `verbose=2` is
recommended when not running interactively (e.g. in a production
environment). Defaults to 'auto'.
steps: Total number of steps (batches of samples)
before declaring the prediction round finished.
Ignored with the default value of `None`. If x is a `tf.data`
dataset and `steps` is None, `predict()` will
run until the input dataset is exhausted.
callbacks: List of `keras.callbacks.Callback` instances.
List of callbacks to apply during prediction.
See [callbacks](
https://www.tensorflow.org/api_docs/python/tf/tf_keras/callbacks).
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the
generator queue. If unspecified, `max_queue_size` will default
to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, `workers` will default
to 1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
See the discussion of `Unpacking behavior for iterator-like inputs` for
`Model.fit`. Note that Model.predict uses the same interpretation rules
as `Model.fit` and `Model.evaluate`, so inputs must be unambiguous for
all three methods.
Returns:
Numpy array(s) of predictions.
Raises:
RuntimeError: If `model.predict` is wrapped in a `tf.function`.
ValueError: In case of mismatch between the provided
input data and the model's expectations,
or in case a stateful model receives a number of samples
that is not a multiple of the batch size.
"""
version_utils.disallow_legacy_graph("Model", "predict")
self._check_call_args("predict")
_disallow_inside_tf_function("predict")
# TODO(yashkatariya): Cache model on the coordinator for faster
# prediction. If running under PSS, then swap it with OneDeviceStrategy
# so that execution will run on the coordinator.
original_pss_strategy = None
if self.distribute_strategy._should_use_with_coordinator:
original_pss_strategy = self.distribute_strategy
self._distribution_strategy = None
# Cluster coordinator is set by `.fit()` and `.evaluate()` which is not
# needed in `.predict()` because all the predictions happen on the
# coordinator/locally.
if self._cluster_coordinator:
self._cluster_coordinator = None
verbose = _get_verbosity(verbose, self.distribute_strategy)
outputs = None
with self.distribute_strategy.scope():
# Creates a `tf.data.Dataset` and handles batch and epoch iteration.
dataset_types = (tf.compat.v1.data.Dataset, tf.data.Dataset)
if (
self._in_multi_worker_mode()
or _is_tpu_multi_host(self.distribute_strategy)
) and isinstance(x, dataset_types):
try:
options = tf.data.Options()
data_option = tf.data.experimental.AutoShardPolicy.DATA
options.experimental_distribute.auto_shard_policy = (
data_option
)
x = x.with_options(options)
except ValueError:
warnings.warn(
"Using Model.predict with MultiWorkerMirroredStrategy "
"or TPUStrategy and AutoShardPolicy.FILE might lead to "
"out-of-order result. Consider setting it to "
"AutoShardPolicy.DATA.",
stacklevel=2,
)
data_handler = data_adapter.get_data_handler(
x=x,
batch_size=batch_size,
steps_per_epoch=steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=1,
steps=data_handler.inferred_steps,
)
self.predict_function = self.make_predict_function()
self._predict_counter.assign(0)
callbacks.on_predict_begin()
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
batch_outputs = None
for _, iterator in data_handler.enumerate_epochs(): # Single epoch.
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
callbacks.on_predict_batch_begin(step)
tmp_batch_outputs = self.predict_function(iterator)
if data_handler.should_sync:
context.async_wait()
batch_outputs = (
tmp_batch_outputs # No error, now safe to assign.
)
if outputs is None:
outputs = tf.nest.map_structure(
lambda batch_output: [batch_output],
batch_outputs,
)
else:
tf.__internal__.nest.map_structure_up_to(
batch_outputs,
lambda output, batch_output: output.append(
batch_output
),
outputs,
batch_outputs,
)
end_step = step + data_handler.step_increment
callbacks.on_predict_batch_end(
end_step, {"outputs": batch_outputs}
)
if batch_outputs is None:
raise ValueError(
"Unexpected result of `predict_function` "
"(Empty batch_outputs). Please use "
"`Model.compile(..., run_eagerly=True)`, or "
"`tf.config.run_functions_eagerly(True)` for more "
"information of where went wrong, or file a "
"issue/bug to `tf.keras`."
)
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_predict_end()
all_outputs = tf.__internal__.nest.map_structure_up_to(
batch_outputs, potentially_ragged_concat, outputs
)
# If originally PSS strategy was used, then replace it back since
# predict is running under `OneDeviceStrategy` after the swap and once
# its done we need to replace it back to PSS again.
if original_pss_strategy is not None:
self._distribution_strategy = original_pss_strategy
return tf_utils.sync_to_numpy_or_python_type(all_outputs)
def reset_metrics(self):
"""Resets the state of all the metrics in the model.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> _ = model.fit(x, y, verbose=0)
>>> assert all(float(m.result()) for m in model.metrics)
>>> model.reset_metrics()
>>> assert all(float(m.result()) == 0 for m in model.metrics)
"""
for m in self.metrics:
m.reset_state()
def train_on_batch(
self,
x,
y=None,
sample_weight=None,
class_weight=None,
reset_metrics=True,
return_dict=False,
):
"""Runs a single gradient update on a single batch of data.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s).
sample_weight: Optional array of the same length as x, containing
weights to apply to the model's loss for each sample. In the case
of temporal data, you can pass a 2D array with shape (samples,
sequence_length), to apply a different weight to every timestep of
every sample.
class_weight: Optional dictionary mapping class indices (integers)
to a weight (float) to apply to the model's loss for the samples
from this class during training. This can be useful to tell the
model to "pay more attention" to samples from an under-represented
class. When `class_weight` is specified and targets have a rank of
2 or greater, either `y` must be one-hot encoded, or an explicit
final dimension of `1` must be included for sparse class labels.
reset_metrics: If `True`, the metrics returned will be only for this
batch. If `False`, the metrics will be statefully accumulated
across batches.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
Returns:
Scalar training 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 scalar outputs.
Raises:
RuntimeError: If `model.train_on_batch` is wrapped in a `tf.function`.
"""
self._assert_compile_was_called()
self._check_call_args("train_on_batch")
_disallow_inside_tf_function("train_on_batch")
if reset_metrics:
self.reset_metrics()
with self.distribute_strategy.scope(), training_utils.RespectCompiledTrainableState( # noqa: E501
self
):
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x, y, sample_weight, class_weight
)
self.train_function = self.make_train_function()
logs = self.train_function(iterator)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def test_on_batch(
self,
x,
y=None,
sample_weight=None,
reset_metrics=True,
return_dict=False,
):
"""Test the model on a single batch of samples.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays (in case the
model has multiple inputs).
- A TensorFlow tensor, or a list of tensors (in case the model has
multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s). It should be consistent with `x`
(you cannot have Numpy inputs and tensor targets, or inversely).
sample_weight: Optional array of the same length as x, containing
weights to apply to the model's loss for each sample. In the case
of temporal data, you can pass a 2D array with shape (samples,
sequence_length), to apply a different weight to every timestep of
every sample.
reset_metrics: If `True`, the metrics returned will be only for this
batch. If `False`, the metrics will be statefully accumulated
across batches.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
Returns:
Scalar test 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 scalar outputs.
Raises:
RuntimeError: If `model.test_on_batch` is wrapped in a
`tf.function`.
"""
self._assert_compile_was_called()
self._check_call_args("test_on_batch")
_disallow_inside_tf_function("test_on_batch")
if reset_metrics:
self.reset_metrics()
with self.distribute_strategy.scope():
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x, y, sample_weight
)
self.test_function = self.make_test_function()
logs = self.test_function(iterator)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def predict_on_batch(self, x):
"""Returns predictions for a single batch of samples.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays (in case the
model has multiple inputs).
- A TensorFlow tensor, or a list of tensors (in case the model has
multiple inputs).
Returns:
Numpy array(s) of predictions.
Raises:
RuntimeError: If `model.predict_on_batch` is wrapped in a
`tf.function`.
"""
self._check_call_args("predict_on_batch")
_disallow_inside_tf_function("predict_on_batch")
with self.distribute_strategy.scope():
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x
)
self.predict_function = self.make_predict_function()
outputs = self.predict_function(iterator)
return tf_utils.sync_to_numpy_or_python_type(outputs)
@doc_controls.do_not_generate_docs
def fit_generator(
self,
generator,
steps_per_epoch=None,
epochs=1,
verbose=1,
callbacks=None,
validation_data=None,
validation_steps=None,
validation_freq=1,
class_weight=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
shuffle=True,
initial_epoch=0,
):
"""Fits the model on data yielded batch-by-batch by a Python generator.
DEPRECATED:
`Model.fit` now supports generators, so there is no longer any need to
use this endpoint.
"""
warnings.warn(
"`Model.fit_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.fit`, which supports generators.",
stacklevel=2,
)
return self.fit(
generator,
steps_per_epoch=steps_per_epoch,
epochs=epochs,
verbose=verbose,
callbacks=callbacks,
validation_data=validation_data,
validation_steps=validation_steps,
validation_freq=validation_freq,
class_weight=class_weight,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
shuffle=shuffle,
initial_epoch=initial_epoch,
)
@doc_controls.do_not_generate_docs
def evaluate_generator(
self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0,
):
"""Evaluates the model on a data generator.
DEPRECATED:
`Model.evaluate` now supports generators, so there is no longer any
need to use this endpoint.
"""
warnings.warn(
"`Model.evaluate_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.evaluate`, which supports generators.",
stacklevel=2,
)
self._check_call_args("evaluate_generator")
return self.evaluate(
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks,
)
@doc_controls.do_not_generate_docs
def predict_generator(
self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0,
):
"""Generates predictions for the input samples from a data generator.
DEPRECATED:
`Model.predict` now supports generators, so there is no longer any
need to use this endpoint.
"""
warnings.warn(
"`Model.predict_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.predict`, which supports generators.",
stacklevel=2,
)
return self.predict(
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks,
)
######################################################################
# Functions below are not training related. They are for model weights
# tracking, save/load, serialization, etc.
######################################################################
@property
def trainable_weights(self):
self._assert_weights_created()
if not self._trainable:
return []
trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
trainable_variables += trackable_obj.trainable_variables
trainable_variables += self._trainable_weights
return self._dedup_weights(trainable_variables)
@property
def non_trainable_weights(self):
self._assert_weights_created()
non_trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
non_trainable_variables += trackable_obj.non_trainable_variables
if not self._trainable:
# Return order is all trainable vars, then all non-trainable vars.
trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
trainable_variables += trackable_obj.trainable_variables
non_trainable_variables = (
trainable_variables
+ self._trainable_weights
+ non_trainable_variables
+ self._non_trainable_weights
)
else:
non_trainable_variables = (
non_trainable_variables + self._non_trainable_weights
)
return self._dedup_weights(non_trainable_variables)
def get_weights(self):
"""Retrieves the weights of the model.
Returns:
A flat list of Numpy arrays.
"""
with self.distribute_strategy.scope():
return super().get_weights()
@traceback_utils.filter_traceback
def save(self, 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.models.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.models.save_model()`.
"""
saving_api.save_model(
self,
filepath=filepath,
overwrite=overwrite,
save_format=save_format,
**kwargs,
)
@traceback_utils.filter_traceback
def save_weights(
self, filepath, overwrite=True, save_format=None, options=None
):
"""Saves all layer weights.
Either saves in HDF5 or in TensorFlow format based on the `save_format`
argument.
When saving in HDF5 format, the weight file has:
- `layer_names` (attribute), a list of strings
(ordered names of model layers).
- For every layer, a `group` named `layer.name`
- For every such layer group, a group attribute `weight_names`,
a list of strings
(ordered names of weights tensor of the layer).
- For every weight in the layer, a dataset
storing the weight value, named after the weight tensor.
When saving in TensorFlow format, all objects referenced by the network
are saved in the same format as `tf.train.Checkpoint`, including any
`Layer` instances or `Optimizer` instances assigned to object
attributes. For networks constructed from inputs and outputs using
`tf.keras.Model(inputs, outputs)`, `Layer` instances used by the network
are tracked/saved automatically. For user-defined classes which inherit
from `tf.keras.Model`, `Layer` instances must be assigned to object
attributes, typically in the constructor. See the documentation of
`tf.train.Checkpoint` and `tf.keras.Model` for details.
While the formats are the same, do not mix `save_weights` and
`tf.train.Checkpoint`. Checkpoints saved by `Model.save_weights` should
be loaded using `Model.load_weights`. Checkpoints saved using
`tf.train.Checkpoint.save` should be restored using the corresponding
`tf.train.Checkpoint.restore`. Prefer `tf.train.Checkpoint` over
`save_weights` for training checkpoints.
The TensorFlow format matches objects and variables by starting at a
root object, `self` for `save_weights`, and greedily matching attribute
names. For `Model.save` this is the `Model`, and for `Checkpoint.save`
this is the `Checkpoint` even if the `Checkpoint` has a model attached.
This means saving a `tf.keras.Model` using `save_weights` and loading
into a `tf.train.Checkpoint` with a `Model` attached (or vice versa)
will not match the `Model`'s variables. See the
[guide to training checkpoints](
https://www.tensorflow.org/guide/checkpoint) for details on
the TensorFlow format.
Args:
filepath: String or PathLike, path to the file to save the weights
to. When saving in TensorFlow format, this is the prefix used
for checkpoint files (multiple files are generated). Note that
the '.h5' suffix causes weights to be saved in HDF5 format.
overwrite: Whether to silently overwrite any existing file at the
target location, or provide the user with a manual prompt.
save_format: Either 'tf' or 'h5'. A `filepath` ending in '.h5' or
'.keras' will default to HDF5 if `save_format` is `None`.
Otherwise, `None` becomes 'tf'. Defaults to `None`.
options: Optional `tf.train.CheckpointOptions` object that specifies
options for saving weights.
Raises:
ImportError: If `h5py` is not available when attempting to save in
HDF5 format.
"""
saving_api.save_weights(
self,
filepath=filepath,
overwrite=overwrite,
save_format=save_format,
options=options,
)
@traceback_utils.filter_traceback
def load_weights(
self, filepath, skip_mismatch=False, by_name=False, options=None
):
"""Loads all layer weights from a saved files.
The saved file could be a SavedModel file, a `.keras` file (v3 saving
format), or a file created via `model.save_weights()`.
By default, weights are loaded based on the network's
topology. This means the architecture should be the same as when the
weights were saved. Note that layers that don't have weights are not
taken into account in the topological ordering, so adding or removing
layers is fine as long as they don't have weights.
**Partial weight loading**
If you have modified your model, for instance by adding a new layer
(with weights) or by changing the shape of the weights of a layer,
you can choose to ignore errors and continue loading
by setting `skip_mismatch=True`. In this case any layer with
mismatching weights will be skipped. A warning will be displayed
for each skipped layer.
**Weight loading by name**
If your weights are saved as a `.h5` file created
via `model.save_weights()`, you can use the argument `by_name=True`.
In this case, weights are loaded into layers only if they share
the same name. This is useful for fine-tuning or transfer-learning
models where some of the layers have changed.
Note that only topological loading (`by_name=False`) is supported when
loading weights from the `.keras` v3 format or from the TensorFlow
SavedModel format.
Args:
filepath: String, path to the weights file to load. For weight files
in TensorFlow format, this is the file prefix (the same as was
passed to `save_weights()`). This can also be a path to a
SavedModel or a `.keras` file (v3 saving format) saved
via `model.save()`.
skip_mismatch: Boolean, whether to skip loading of layers where
there is a mismatch in the number of weights, or a mismatch in
the shape of the weights.
by_name: Boolean, whether to load weights by name or by topological
order. Only topological loading is supported for weight files in
the `.keras` v3 format or in the TensorFlow SavedModel format.
options: Optional `tf.train.CheckpointOptions` object that specifies
options for loading weights (only valid for a SavedModel file).
"""
return saving_api.load_weights(
self,
filepath=filepath,
by_name=by_name,
skip_mismatch=skip_mismatch,
options=options,
)
def _updated_config(self):
"""Util shared between different serialization methods.
Returns:
Model config with TF-Keras version information added.
"""
from tf_keras.src import __version__ as keras_version
config = self.get_config()
model_config = {
"class_name": self.__class__.__name__,
"config": config,
"keras_version": keras_version,
"backend": backend.backend(),
}
return model_config
@generic_utils.default
def get_config(self):
"""Returns the config of the `Model`.
Config is a Python dictionary (serializable) containing the
configuration of an object, which in this case is a `Model`. This allows
the `Model` to be be reinstantiated later (without its trained weights)
from this configuration.
Note that `get_config()` does not guarantee to return a fresh copy of
dict every time it is called. The callers should make a copy of the
returned dict if they want to modify it.
Developers of subclassed `Model` are advised to override this method,
and continue to update the dict from `super(MyModel, self).get_config()`
to provide the proper configuration of this `Model`. The default config
will return config dict for init parameters if they are basic types.
Raises `NotImplementedError` when in cases where a custom
`get_config()` implementation is required for the subclassed model.
Returns:
Python dictionary containing the configuration of this `Model`.
"""
# If sublcass doesn't implement `get_config()` parse from init args
# otherwise default to empty dict
if generic_utils.is_default(self.get_config):
try:
config = base_layer.Layer.get_config(self)
except NotImplementedError:
config = {}
logging.warning(
"Model's `__init__()` arguments contain non-serializable "
"objects. Please implement a `get_config()` method in the "
"subclassed Model for proper saving and loading. "
"Defaulting to empty config."
)
else:
config = {}
return config
@classmethod
def from_config(cls, config, custom_objects=None):
# `from_config` assumes `cls` is either `Functional` or a child class of
# `Functional`. In the case that `cls` is meant to behave like a child
# class of `Functional` but only inherits from the `Model` class, we
# have to call `cls(...)` instead of `Functional.from_config`.
from tf_keras.src.engine import functional
with serialization.SharedObjectLoadingScope():
functional_config_keys = [
"name",
"layers",
"input_layers",
"output_layers",
]
is_functional_config = all(
key in config for key in functional_config_keys
)
argspec = tf_inspect.getfullargspec(cls.__init__)
functional_init_args = tf_inspect.getfullargspec(
functional.Functional.__init__
).args[1:]
revivable_as_functional = (
cls in {functional.Functional, Model}
or argspec.args[1:] == functional_init_args
or (argspec.varargs == "args" and argspec.varkw == "kwargs")
)
if is_functional_config and revivable_as_functional:
# Revive Functional model
# (but not Functional subclasses with a custom __init__)
inputs, outputs, layers = functional.reconstruct_from_config(
config, custom_objects
)
model = cls(
inputs=inputs, outputs=outputs, name=config.get("name")
)
functional.connect_ancillary_layers(model, layers)
else:
# Either the model has a custom __init__, or the config
# does not contain all the information necessary to
# revive a Functional model. This happens when the user creates
# subclassed models where `get_config()` is returning
# insufficient information to be considered a Functional model.
# In this case, we fall back to provide all config into the
# constructor of the class.
try:
model = cls(**config)
except TypeError as e:
raise TypeError(
"Unable to revive model from config. When overriding "
"the `get_config()` method, make sure that the "
"returned config contains all items used as arguments "
f"in the constructor to {cls}, "
"which is the default behavior. "
"You can override this default behavior by defining a "
"`from_config(cls, config)` class method to specify "
"how to create an "
f"instance of {cls.__name__} from its config.\n\n"
f"Received config={config}\n\n"
f"Error encountered during deserialization: {e}"
)
return model
def to_json(self, **kwargs):
"""Returns a JSON string containing the network configuration.
To load a network from a JSON save file, use
`keras.models.model_from_json(json_string, custom_objects={})`.
Args:
**kwargs: Additional keyword arguments to be passed to
*`json.dumps()`.
Returns:
A JSON string.
"""
model_config = self._updated_config()
return json.dumps(
model_config, default=json_utils.get_json_type, **kwargs
)
def to_yaml(self, **kwargs):
"""Returns a yaml string containing the network configuration.
Note: Since TF 2.6, this method is no longer supported and will raise a
RuntimeError.
To load a network from a yaml save file, use
`keras.models.model_from_yaml(yaml_string, custom_objects={})`.
`custom_objects` should be a dictionary mapping
the names of custom losses / layers / etc to the corresponding
functions / classes.
Args:
**kwargs: Additional keyword arguments
to be passed to `yaml.dump()`.
Returns:
A YAML string.
Raises:
RuntimeError: announces that the method poses a security risk
"""
raise RuntimeError(
"Method `model.to_yaml()` has been removed due to security risk of "
"arbitrary code execution. Please use `model.to_json()` instead."
)
def reset_states(self):
for layer in self.layers:
if hasattr(layer, "reset_states") and getattr(
layer, "stateful", False
):
layer.reset_states()
@property
@doc_controls.do_not_generate_docs
def state_updates(self):
"""Deprecated, do NOT use!
Returns the `updates` from all layers that are stateful.
This is useful for separating training updates and
state updates, e.g. when we need to update a layer's internal state
during prediction.
Returns:
A list of update ops.
"""
warnings.warn(
"`Model.state_updates` will be removed in a future version. "
"This property should not be used in TensorFlow 2.0, "
"as `updates` are applied automatically.",
stacklevel=2,
)
state_updates = []
for layer in self.layers:
if getattr(layer, "stateful", False):
if hasattr(layer, "updates"):
state_updates += layer.updates
return state_updates
@property
def weights(self):
"""Returns the list of all layer variables/weights.
Note: This will not track the weights of nested `tf.Modules` that are
not themselves TF-Keras layers.
Returns:
A list of variables.
"""
return self._dedup_weights(self._undeduplicated_weights)
@property
def _undeduplicated_weights(self):
"""Returns the undeduplicated list of all layer variables/weights."""
self._assert_weights_created()
weights = []
for layer in self._self_tracked_trackables:
weights += layer.variables
weights += self._trainable_weights + self._non_trainable_weights
return weights
def summary(
self,
line_length=None,
positions=None,
print_fn=None,
expand_nested=False,
show_trainable=False,
layer_range=None,
):
"""Prints a string summary of the network.
Args:
line_length: Total length of printed lines
(e.g. set this to adapt the display to different
terminal window sizes).
positions: Relative or absolute positions of log elements
in each line. If not provided, becomes
`[0.3, 0.6, 0.70, 1.]`. Defaults to `None`.
print_fn: Print function to use. By default, prints to `stdout`.
If `stdout` doesn't work in your environment, change to `print`.
It will be called on each line of the summary.
You can set it to a custom function
in order to capture the string summary.
expand_nested: Whether to expand the nested models.
Defaults to `False`.
show_trainable: Whether to show if a layer is trainable.
Defaults to `False`.
layer_range: a list or tuple of 2 strings,
which is the starting layer name and ending layer name
(both inclusive) indicating the range of layers to be printed
in summary. It also accepts regex patterns instead of exact
name. In such case, start predicate will be the first element
it matches to `layer_range[0]` and the end predicate will be
the last element it matches to `layer_range[1]`.
By default `None` which considers all layers of model.
Raises:
ValueError: if `summary()` is called before the model is built.
"""
if not self.built:
raise ValueError(
"This model has not yet been built. "
"Build the model first by calling `build()` or by calling "
"the model on a batch of data."
)
layer_utils.print_summary(
self,
line_length=line_length,
positions=positions,
print_fn=print_fn,
expand_nested=expand_nested,
show_trainable=show_trainable,
layer_range=layer_range,
)
@property
def layers(self):
return list(self._flatten_layers(include_self=False, recursive=False))
@layers.setter
def layers(self, _):
raise AttributeError(
"`Model.layers` attribute is reserved and should not be used. "
"Please use another name."
)
def get_layer(self, name=None, index=None):
"""Retrieves a layer based on either its name (unique) or index.
If `name` and `index` are both provided, `index` will take precedence.
Indices are based on order of horizontal graph traversal (bottom-up).
Args:
name: String, name of layer.
index: Integer, index of layer.
Returns:
A layer instance.
"""
# TODO(fchollet): We could build a dictionary based on layer names
# since they are constant, but we have not done that yet.
if index is not None and name is not None:
raise ValueError(
"Provide only a layer name or a layer index. Received: "
f"index={index}, name={name}."
)
if index is not None:
if len(self.layers) <= index:
raise ValueError(
f"Was asked to retrieve layer at index {index}"
f" but model only has {len(self.layers)}"
" layers."
)
else:
return self.layers[index]
if name is not None:
for layer in self.layers:
if layer.name == name:
return layer
raise ValueError(
f"No such layer: {name}. Existing layers are: "
f"{list(layer.name for layer in self.layers)}."
)
raise ValueError(
"Provide either a layer name or layer index at `get_layer`."
)
def get_weight_paths(self):
"""Retrieve all the variables and their paths for the model.
The variable path (string) is a stable key to identify a `tf.Variable`
instance owned by the model. It can be used to specify variable-specific
configurations (e.g. DTensor, quantization) from a global view.
This method returns a dict with weight object paths as keys
and the corresponding `tf.Variable` instances as values.
Note that if the model is a subclassed model and the weights haven't
been initialized, an empty dict will be returned.
Returns:
A dict where keys are variable paths and values are `tf.Variable`
instances.
Example:
```python
class SubclassModel(tf.keras.Model):
def __init__(self, name=None):
super().__init__(name=name)
self.d1 = tf.keras.layers.Dense(10)
self.d2 = tf.keras.layers.Dense(20)
def call(self, inputs):
x = self.d1(inputs)
return self.d2(x)
model = SubclassModel()
model(tf.zeros((10, 10)))
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': model.d1.kernel,
# 'd1.bias': model.d1.bias,
# 'd2.kernel': model.d2.kernel,
# 'd2.bias': model.d2.bias,
# }
# Functional model
inputs = tf.keras.Input((10,), batch_size=10)
x = tf.keras.layers.Dense(20, name='d1')(inputs)
output = tf.keras.layers.Dense(30, name='d2')(x)
model = tf.keras.Model(inputs, output)
d1 = model.layers[1]
d2 = model.layers[2]
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': d1.kernel,
# 'd1.bias': d1.bias,
# 'd2.kernel': d2.kernel,
# 'd2.bias': d2.bias,
# }
```
"""
result = {}
(
descendants,
object_paths_dict,
) = tf.__internal__.tracking.ObjectGraphView(
self
).breadth_first_traversal()
for descendant in descendants:
if isinstance(descendant, tf.Variable):
trackable_references = object_paths_dict[descendant]
object_path = ".".join([t.name for t in trackable_references])
result[object_path] = descendant
return result
def get_compile_config(self):
"""Returns a serialized config with information for compiling the model.
This method returns a config dictionary containing all the information
(optimizer, loss, metrics, etc.) with which the model was compiled.
Returns:
A dict containing information for compiling the model.
"""
if self._is_compiled and hasattr(self, "_compile_config"):
return self._compile_config.serialize()
def compile_from_config(self, config):
"""Compiles the model with the information given in config.
This method uses the information in the config (optimizer, loss,
metrics, etc.) to compile the model.
Args:
config: Dict containing information for compiling the model.
"""
has_overridden_compile = self.__class__.compile != Model.compile
if has_overridden_compile:
logging.warning(
"`compile()` was not called as part of model loading "
"because the model's `compile()` method is custom. "
"All subclassed Models that have `compile()` "
"overridden should also override "
"`get_compile_config()` and `compile_from_config(config)`. "
"Alternatively, you can "
"call `compile()` manually after loading."
)
return
config = saving_lib.deserialize_keras_object(config)
self.compile(**config)
if (
hasattr(self, "optimizer")
# Exempt legacy optimizers.
and isinstance(self.optimizer, optimizer.Optimizer)
and self.built
):
# Create optimizer variables.
self.optimizer.build(self.trainable_variables)
def export(self, filepath):
"""Create a SavedModel artifact for inference (e.g. via TF-Serving).
This method lets you export a model to a lightweight SavedModel artifact
that contains the model's forward pass only (its `call()` method)
and can be served via e.g. TF-Serving. The forward pass is registered
under the name `serve()` (see example below).
The original code of the model (including any custom layers you may
have used) is *no longer* necessary to reload the artifact -- it is
entirely standalone.
Args:
filepath: `str` or `pathlib.Path` object. Path where to save
the artifact.
Example:
```python
# Create the artifact
model.export("path/to/location")
# Later, in a different process / environment...
reloaded_artifact = tf.saved_model.load("path/to/location")
predictions = reloaded_artifact.serve(input_data)
```
If you would like to customize your serving endpoints, you can
use the lower-level `keras.export.ExportArchive` class. The `export()`
method relies on `ExportArchive` internally.
"""
from tf_keras.src.export import export_lib
export_lib.export_model(self, filepath)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _set_save_spec(self, inputs, args=None, kwargs=None):
"""Defines the save spec so that serialization can trace `call()`.
The TensorSpecs of the call function `inputs`, `args`, and `kwargs` are
saved into a tuple of `([inputs] + args, kwargs)`. The input
`TensorSpec` names are updated to match the built `input_names`.
The specs can be retrieved with the `save_spec` property.
Args:
inputs: possibly nested inputs passed into the call function.
args: a list of positional arguments passed into call.
kwargs: a dictionary of keyword arguments passed into call.
"""
if self._saved_model_inputs_spec is not None:
return # Already set.
args = args or []
kwargs = kwargs or {}
input_names = self.input_names
if not input_names:
input_names = compile_utils.create_pseudo_input_names(inputs)
flat_inputs = tf.nest.flatten(inputs)
inputs_spec = []
for name, tensor in zip(input_names, flat_inputs):
inputs_spec.append(
tf_utils.get_tensor_spec(tensor, dynamic_batch=False, name=name)
)
inputs_spec = tf.nest.pack_sequence_as(inputs, inputs_spec)
super()._set_save_spec(inputs_spec, args, kwargs)
# Store the input shapes
if (
self.__class__.__name__ == "Sequential"
and self._build_input_shape is None
):
self._build_input_shape = tf.nest.map_structure(
lambda x: None if x is None else x.shape, inputs_spec
)
def save_spec(self, dynamic_batch=True):
"""Returns the `tf.TensorSpec` of call args as a tuple `(args, kwargs)`.
This value is automatically defined after calling the model for the
first time. Afterwards, you can use it when exporting the model for
serving:
```python
model = tf.keras.Model(...)
@tf.function
def serve(*args, **kwargs):
outputs = model(*args, **kwargs)
# Apply postprocessing steps, or add additional outputs.
...
return outputs
# arg_specs is `[tf.TensorSpec(...), ...]`. kwarg_specs, in this
# example, is an empty dict since functional models do not use keyword
# arguments.
arg_specs, kwarg_specs = model.save_spec()
model.save(path, signatures={
'serving_default': serve.get_concrete_function(*arg_specs,
**kwarg_specs)
})
```
Args:
dynamic_batch: Whether to set the batch sizes of all the returned
`tf.TensorSpec` to `None`. (Note that when defining functional or
Sequential models with `tf.keras.Input([...], batch_size=X)`, the
batch size will always be preserved). Defaults to `True`.
Returns:
If the model inputs are defined, returns a tuple `(args, kwargs)`. All
elements in `args` and `kwargs` are `tf.TensorSpec`.
If the model inputs are not defined, returns `None`.
The model inputs are automatically set when calling the model,
`model.fit`, `model.evaluate` or `model.predict`.
"""
return self._get_save_spec(dynamic_batch, inputs_only=False)
def _assert_weights_created(self):
"""Asserts that all the weights for the model have been created.
For a non-dynamic model, the weights must already be created after the
layer has been called. For a dynamic model, the exact list of weights
can never be known for certain since it may change at any time during
execution.
We run this check right before accessing weights or getting the Numpy
value for the current weights. Otherwise, if the layer has never been
called, the user would just get an empty list, which is misleading.
Raises:
ValueError: if the weights of the network have not yet been created.
"""
if self.dynamic:
return
if (
"build" in self.__class__.__dict__
and self.__class__ != Model
and not self.built
):
# For any model that has customized build() method but hasn't been
# invoked yet, this will cover both sequential and subclass model.
# Also make sure to exclude Model class itself which has build()
# defined.
raise ValueError(
f"Weights for model '{self.name}' have not yet been "
"created. "
"Weights are created when the model is first called on "
"inputs or `build()` is called with an `input_shape`."
)
def _check_call_args(self, method_name):
"""Check that `call()` has only one positional arg."""
# Always allow first arg, regardless of arg name.
fullargspec = self._call_spec.full_argspec
if fullargspec.defaults:
positional_args = fullargspec.args[: -len(fullargspec.defaults)]
else:
positional_args = fullargspec.args
if "training" in positional_args:
positional_args.remove("training")
# self and first arg can be positional.
if len(positional_args) > 2:
extra_args = positional_args[2:]
raise ValueError(
f"Models passed to `{method_name}` can only have `training` "
"and the first argument in `call()` as positional arguments, "
f"found: {extra_args}."
)
def _validate_compile(self, optimizer, metrics, **kwargs):
"""Performs validation checks for the default `compile()`."""
if any(
isinstance(opt, optimizer_v1.Optimizer)
for opt in tf.nest.flatten(optimizer)
):
raise ValueError(
f"`tf.compat.v1.keras` Optimizer ({optimizer}) is "
"not supported when eager execution is enabled. Use a "
"`tf.keras` Optimizer instead, or disable eager "
"execution."
)
kwargs.pop("cloning", None) # Legacy DistStrat argument, never used.
kwargs.pop("experimental_run_tf_function", None) # Always `True`.
distribute_arg = kwargs.pop("distribute", None)
if distribute_arg is not None:
raise ValueError(
"`distribute` argument in compile is not available in TF 2.0. "
"Please create the model under the `strategy.scope()`. "
f"Received: {distribute_arg}."
)
target_tensor_arg = kwargs.pop("target_tensors", None)
if target_tensor_arg is not None:
raise ValueError(
"`target_tensors` argument is not supported when executing "
f"eagerly. Received: {target_tensor_arg}."
)
invalid_kwargs = set(kwargs) - {"sample_weight_mode"}
if invalid_kwargs:
raise TypeError(
"Invalid keyword argument(s) in `compile()`: "
f"{(invalid_kwargs,)}. Valid keyword arguments include "
'"cloning", "experimental_run_tf_function", "distribute",'
' "target_tensors", or "sample_weight_mode".'
)
# Model must be created and compiled with the same DistStrat.
if self.built and tf.distribute.has_strategy():
strategy = tf.distribute.get_strategy()
for v in self.variables:
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Variable ({v}) was not created in the distribution "
f"strategy scope of ({strategy}). It is most likely "
"because some layers, model, or optimizer was being "
"created outside the distribution strategy scope. Try "
"to make sure your code looks similar "
"to the following.\nwith strategy.scope():\n"
" model=_create_model()\n"
" model.compile(...)"
)
# Model metrics must be created in the same distribution strategy scope
# as the model.
strategy = self.distribute_strategy
for metric in tf.nest.flatten(metrics):
for v in getattr(metric, "variables", []):
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Metric ({metric}) passed to `model.compile` was "
"created inside a different distribution strategy "
"scope than the model. All metrics must be created "
"in the same distribution strategy "
f"scope as the model (in this case {strategy}). "
"If you pass in a string identifier for a metric to "
"compile, the metric will automatically be created "
"in the correct distribution strategy scope."
)
# Model metrics must be created in the same distribution strategy scope
# as the model.
for opt in tf.nest.flatten(optimizer):
for v in getattr(opt, "_weights", []):
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Optimizer ({optimizer}) passed to `model.compile` "
"was created inside a different distribution strategy "
"scope than the model. All optimizers must be created "
"in the same distribution strategy scope as the model "
f"(in this case {strategy}). If you pass in a string "
"identifier for an optimizer to compile, the optimizer "
"will automatically be created in the correct "
"distribution strategy scope."
)
def _maybe_load_initial_counters_from_ckpt(
self, steps_per_epoch, initial_epoch
):
"""Maybe load initial epoch from ckpt, considering worker recovery.
Refer to tensorflow/python/tf_keras/distribute/worker_training_state.py
for more information.
Args:
steps_per_epoch: The number of step per epoch.
initial_epoch: The original initial_epoch user passes in `fit()`.
mode: The mode for running `model.fit()`.
Returns:
If the training is recovering from previous failure under multi-worker
training setting, return the (epoch, step) the training is supposed to
continue at. Otherwise, return the `initial_epoch, initial_step` the
user passes in.
"""
initial_step = 0
if self._training_state is not None:
return self._training_state.maybe_load_initial_counters_from_ckpt(
steps_per_epoch, initial_epoch, mode=ModeKeys.TRAIN
)
return (initial_epoch, initial_step)
def _assert_compile_was_called(self):
# Checks whether `compile` has been called. If it has been called,
# then the optimizer is set. This is different from whether the
# model is compiled
# (i.e. whether the model is built and its inputs/outputs are set).
if not self._is_compiled:
raise RuntimeError(
"You must compile your model before "
"training/testing. "
"Use `model.compile(optimizer, loss)`."
)
def _check_sample_weight_warning(self, x, sample_weight):
# Datasets can include sample weight, by returning a tuple with the
# structure of `(x, y, sample_weight)`.
sample_weight_present = sample_weight is not None or (
isinstance(x, tf.data.Dataset)
and isinstance(x.element_spec, tuple)
and len(x.element_spec) == 3
)
if (
sample_weight_present
and self.compiled_metrics._user_weighted_metrics is None
):
logging.warning(
"`evaluate()` received a value for `sample_weight`, but "
"`weighted_metrics` were not provided. Did you mean to pass "
"metrics to `weighted_metrics` in `compile()`? If this is "
"intentional you can pass `weighted_metrics=[]` to `compile()` "
"in order to silence this warning."
)
def _set_inputs(self, inputs, outputs=None, training=None):
"""This method is for compat with Modelv1. Only inputs are needed
here."""
self._set_save_spec(inputs)
@property
def _trackable_saved_model_saver(self):
return model_serialization.ModelSavedModelSaver(self)
def _trackable_children(self, save_type="checkpoint", **kwargs):
if save_type == "savedmodel":
# SavedModel needs to ignore the execution functions.
train_function = self.train_function
test_function = self.test_function
predict_function = self.predict_function
train_tf_function = self.train_tf_function
self.train_function = None
self.test_function = None
self.predict_function = None
self.train_tf_function = None
children = super()._trackable_children(save_type, **kwargs)
if save_type == "savedmodel":
self.train_function = train_function
self.test_function = test_function
self.predict_function = predict_function
self.train_tf_function = train_tf_function
return children
def _should_eval(self, epoch, validation_freq):
epoch = epoch + 1 # one-index the user-facing epoch.
if isinstance(validation_freq, int):
return epoch % validation_freq == 0
elif isinstance(validation_freq, list):
return epoch in validation_freq
else:
raise ValueError(
"Expected `validation_freq` to be a list or int. "
f"Received: validation_freq={validation_freq} of the "
f"type {type(validation_freq)}."
)
######################################################################
# Functions below exist only as v1 / v2 compatibility shims.
######################################################################
def _get_compile_args(self, user_metrics=True):
"""Used for saving or cloning a Model.
Args:
user_metrics: Whether to return user-supplied metrics or `Metric`
objects. If True, returns the user-supplied metrics.
Defaults to `True`.
Returns:
Dictionary of arguments that were used when compiling the model.
"""
self._assert_compile_was_called()
saved_metrics = self.compiled_metrics._user_metrics
saved_weighted_metrics = self.compiled_metrics._user_weighted_metrics
if not user_metrics:
if saved_metrics is not None:
saved_metrics = self.compiled_metrics._metrics
if saved_weighted_metrics is not None:
saved_weighted_metrics = self.compiled_metrics._weighted_metrics
compile_args = {
"optimizer": self.optimizer,
"loss": self.compiled_loss._user_losses,
"metrics": saved_metrics,
"weighted_metrics": saved_weighted_metrics,
"loss_weights": self.compiled_loss._user_loss_weights,
}
return compile_args
def _get_callback_model(self):
return self
def _in_multi_worker_mode(self):
return self.distribute_strategy.extended._in_multi_worker_mode()
@property
def _compile_was_called(self):
return self._is_compiled
| (self, optimizer='rmsprop', loss=None, metrics=None, loss_weights=None, weighted_metrics=None, run_eagerly=None, steps_per_execution=None, jit_compile=None, pss_evaluation_shards=0, **kwargs) |
725,002 | tf_keras.src.engine.training | compile_from_config | Compiles the model with the information given in config.
This method uses the information in the config (optimizer, loss,
metrics, etc.) to compile the model.
Args:
config: Dict containing information for compiling the model.
| def compile_from_config(self, config):
"""Compiles the model with the information given in config.
This method uses the information in the config (optimizer, loss,
metrics, etc.) to compile the model.
Args:
config: Dict containing information for compiling the model.
"""
has_overridden_compile = self.__class__.compile != Model.compile
if has_overridden_compile:
logging.warning(
"`compile()` was not called as part of model loading "
"because the model's `compile()` method is custom. "
"All subclassed Models that have `compile()` "
"overridden should also override "
"`get_compile_config()` and `compile_from_config(config)`. "
"Alternatively, you can "
"call `compile()` manually after loading."
)
return
config = saving_lib.deserialize_keras_object(config)
self.compile(**config)
if (
hasattr(self, "optimizer")
# Exempt legacy optimizers.
and isinstance(self.optimizer, optimizer.Optimizer)
and self.built
):
# Create optimizer variables.
self.optimizer.build(self.trainable_variables)
| (self, config) |
725,003 | tf_keras.src.engine.training | compute_loss | Compute the total loss, validate it, and return it.
Subclasses can optionally override this method to provide custom loss
computation logic.
Example:
```python
class MyModel(tf.keras.Model):
def __init__(self, *args, **kwargs):
super(MyModel, self).__init__(*args, **kwargs)
self.loss_tracker = tf.keras.metrics.Mean(name='loss')
def compute_loss(self, x, y, y_pred, sample_weight):
loss = tf.reduce_mean(tf.math.squared_difference(y_pred, y))
loss += tf.add_n(self.losses)
self.loss_tracker.update_state(loss)
return loss
def reset_metrics(self):
self.loss_tracker.reset_states()
@property
def metrics(self):
return [self.loss_tracker]
tensors = tf.random.uniform((10, 10)), tf.random.uniform((10,))
dataset = tf.data.Dataset.from_tensor_slices(tensors).repeat().batch(1)
inputs = tf.keras.layers.Input(shape=(10,), name='my_input')
outputs = tf.keras.layers.Dense(10)(inputs)
model = MyModel(inputs, outputs)
model.add_loss(tf.reduce_sum(outputs))
optimizer = tf.keras.optimizers.SGD()
model.compile(optimizer, loss='mse', steps_per_execution=10)
model.fit(dataset, epochs=2, steps_per_epoch=10)
print('My custom loss: ', model.loss_tracker.result().numpy())
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
The total loss as a `tf.Tensor`, or `None` if no loss results (which
is the case when called by `Model.test_step`).
| def compute_loss(self, x=None, y=None, y_pred=None, sample_weight=None):
"""Compute the total loss, validate it, and return it.
Subclasses can optionally override this method to provide custom loss
computation logic.
Example:
```python
class MyModel(tf.keras.Model):
def __init__(self, *args, **kwargs):
super(MyModel, self).__init__(*args, **kwargs)
self.loss_tracker = tf.keras.metrics.Mean(name='loss')
def compute_loss(self, x, y, y_pred, sample_weight):
loss = tf.reduce_mean(tf.math.squared_difference(y_pred, y))
loss += tf.add_n(self.losses)
self.loss_tracker.update_state(loss)
return loss
def reset_metrics(self):
self.loss_tracker.reset_states()
@property
def metrics(self):
return [self.loss_tracker]
tensors = tf.random.uniform((10, 10)), tf.random.uniform((10,))
dataset = tf.data.Dataset.from_tensor_slices(tensors).repeat().batch(1)
inputs = tf.keras.layers.Input(shape=(10,), name='my_input')
outputs = tf.keras.layers.Dense(10)(inputs)
model = MyModel(inputs, outputs)
model.add_loss(tf.reduce_sum(outputs))
optimizer = tf.keras.optimizers.SGD()
model.compile(optimizer, loss='mse', steps_per_execution=10)
model.fit(dataset, epochs=2, steps_per_epoch=10)
print('My custom loss: ', model.loss_tracker.result().numpy())
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
The total loss as a `tf.Tensor`, or `None` if no loss results (which
is the case when called by `Model.test_step`).
"""
del x # The default implementation does not use `x`.
return self.compiled_loss(
y, y_pred, sample_weight, regularization_losses=self.losses
)
| (self, x=None, y=None, y_pred=None, sample_weight=None) |
725,005 | tf_keras.src.engine.training | compute_metrics | Update metric states and collect all metrics to be returned.
Subclasses can optionally override this method to provide custom metric
updating and collection logic.
Example:
```python
class MyModel(tf.keras.Sequential):
def compute_metrics(self, x, y, y_pred, sample_weight):
# This super call updates `self.compiled_metrics` and returns
# results for all metrics listed in `self.metrics`.
metric_results = super(MyModel, self).compute_metrics(
x, y, y_pred, sample_weight)
# Note that `self.custom_metric` is not listed in `self.metrics`.
self.custom_metric.update_state(x, y, y_pred, sample_weight)
metric_results['custom_metric_name'] = self.custom_metric.result()
return metric_results
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model.call(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end()`. Typically, the
values of the metrics listed in `self.metrics` are returned. Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
| def compute_metrics(self, x, y, y_pred, sample_weight):
"""Update metric states and collect all metrics to be returned.
Subclasses can optionally override this method to provide custom metric
updating and collection logic.
Example:
```python
class MyModel(tf.keras.Sequential):
def compute_metrics(self, x, y, y_pred, sample_weight):
# This super call updates `self.compiled_metrics` and returns
# results for all metrics listed in `self.metrics`.
metric_results = super(MyModel, self).compute_metrics(
x, y, y_pred, sample_weight)
# Note that `self.custom_metric` is not listed in `self.metrics`.
self.custom_metric.update_state(x, y, y_pred, sample_weight)
metric_results['custom_metric_name'] = self.custom_metric.result()
return metric_results
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model.call(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end()`. Typically, the
values of the metrics listed in `self.metrics` are returned. Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
del x # The default implementation does not use `x`.
self.compiled_metrics.update_state(y, y_pred, sample_weight)
return self.get_metrics_result()
| (self, x, y, y_pred, sample_weight) |
725,006 | tf_keras.src.engine.base_layer | compute_output_shape | Computes the output shape of the layer.
This method will cause the layer's state to be built, if that has not
happened before. This requires 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 `tf.TensorShape`,
or structure of shape tuples / `tf.TensorShape` instances
(one per output tensor of the layer).
Shape tuples can include None for free dimensions,
instead of an integer.
Returns:
A `tf.TensorShape` instance
or structure of `tf.TensorShape` instances.
| def compute_output_shape(self, input_shape):
"""Computes the output shape of the layer.
This method will cause the layer's state to be built, if that has not
happened before. This requires 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 `tf.TensorShape`,
or structure of shape tuples / `tf.TensorShape` instances
(one per output tensor of the layer).
Shape tuples can include None for free dimensions,
instead of an integer.
Returns:
A `tf.TensorShape` instance
or structure of `tf.TensorShape` instances.
"""
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)
graph_name = str(self.name) + "_scratch_graph"
with tf.__internal__.FuncGraph(graph_name).as_default():
input_shape = tf_utils.convert_shapes(
input_shape, to_tuples=False
)
def _make_placeholder_like(shape):
ph = backend.placeholder(shape=shape, dtype=self.dtype)
ph._keras_mask = None
return ph
inputs = tf.nest.map_structure(
_make_placeholder_like, 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(
"Please run in eager mode or implement the `compute_output_shape` "
"method on your layer (%s)." % self.__class__.__name__
)
| (self, input_shape) |
725,007 | tf_keras.src.engine.base_layer | compute_output_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.
| @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. "
f"Received: {s}."
)
return s.shape
input_shape = tf.nest.map_structure(
check_type_return_shape, input_signature
)
output_shape = self.compute_output_shape(input_shape)
try:
dtype = self.output.dtype
except AttributeError:
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
)
| (self, input_signature) |
725,009 | tf_keras.src.engine.training | evaluate | Returns the loss value & metrics values for the model in test mode.
Computation is done in batches (see the `batch_size` arg.)
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A `tf.data` dataset. Should return a tuple
of either `(inputs, targets)` or
`(inputs, targets, sample_weights)`.
- A generator or `keras.utils.Sequence` returning `(inputs,
targets)` or `(inputs, targets, sample_weights)`.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given in the `Unpacking
behavior for iterator-like inputs` section of `Model.fit`.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s). It should be consistent with `x`
(you cannot have Numpy inputs and tensor targets, or inversely).
If `x` is a dataset, generator or `keras.utils.Sequence` instance,
`y` should not be specified (since targets will be obtained from
the iterator/dataset).
batch_size: Integer or `None`. Number of samples per batch of
computation. If unspecified, `batch_size` will default to 32. Do
not specify the `batch_size` if your data is in the form of a
dataset, generators, or `keras.utils.Sequence` instances (since
they generate batches).
verbose: `"auto"`, 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = single line.
`"auto"` becomes 1 for most cases, and to 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so `verbose=2` is
recommended when not running interactively (e.g. in a production
environment). Defaults to 'auto'.
sample_weight: Optional Numpy array of weights for the test samples,
used for weighting the loss function. You can either pass a flat
(1D) Numpy array with the same length as the input samples
(1:1 mapping between weights and samples), or in the case of
temporal data, you can pass a 2D array with shape `(samples,
sequence_length)`, to apply a different weight to every
timestep of every sample. This argument is not supported when
`x` is a dataset, instead pass sample weights as the third
element of `x`.
steps: Integer or `None`. Total number of steps (batches of samples)
before declaring the evaluation round finished. Ignored with the
default value of `None`. If x is a `tf.data` dataset and `steps`
is None, 'evaluate' will run until the dataset is exhausted. This
argument is not supported with array inputs.
callbacks: List of `keras.callbacks.Callback` instances. List of
callbacks to apply during evaluation. See
[callbacks](https://www.tensorflow.org/api_docs/python/tf/tf_keras/callbacks).
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the generator
queue. If unspecified, `max_queue_size` will default to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, `workers` will default to
1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
**kwargs: Unused at this time.
See the discussion of `Unpacking behavior for iterator-like inputs` for
`Model.fit`.
Returns:
Scalar test 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 scalar outputs.
Raises:
RuntimeError: If `model.evaluate` is wrapped in a `tf.function`.
| # 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.
# ==============================================================================
"""Training-related part of the TF-Keras engine."""
import copy
import itertools
import json
import warnings
import weakref
import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow.python.distribute import distribute_utils
from tensorflow.python.distribute import input_ops
from tensorflow.python.eager import context
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util.tf_export import keras_export
from tensorflow.tools.docs import doc_controls
from tf_keras.src import backend
from tf_keras.src import callbacks as callbacks_module
from tf_keras.src import optimizers
from tf_keras.src.dtensor import dtensor_api
from tf_keras.src.dtensor import layout_map as layout_map_lib
from tf_keras.src.engine import base_layer
from tf_keras.src.engine import base_layer_utils
from tf_keras.src.engine import compile_utils
from tf_keras.src.engine import data_adapter
from tf_keras.src.engine import input_layer as input_layer_module
from tf_keras.src.engine import training_utils
from tf_keras.src.metrics import base_metric
from tf_keras.src.mixed_precision import loss_scale_optimizer as lso
from tf_keras.src.optimizers import optimizer
from tf_keras.src.optimizers import optimizer_v1
from tf_keras.src.saving import pickle_utils
from tf_keras.src.saving import saving_api
from tf_keras.src.saving import saving_lib
from tf_keras.src.saving import serialization_lib
from tf_keras.src.saving.legacy import serialization
from tf_keras.src.saving.legacy.saved_model import json_utils
from tf_keras.src.saving.legacy.saved_model import model_serialization
from tf_keras.src.utils import generic_utils
from tf_keras.src.utils import io_utils
from tf_keras.src.utils import layer_utils
from tf_keras.src.utils import steps_per_execution_tuning
from tf_keras.src.utils import tf_inspect
from tf_keras.src.utils import tf_utils
from tf_keras.src.utils import traceback_utils
from tf_keras.src.utils import version_utils
from tf_keras.src.utils.mode_keys import ModeKeys
try:
import h5py
except ImportError:
h5py = None
@keras_export("keras.Model", "keras.models.Model")
class Model(base_layer.Layer, version_utils.ModelVersionSelector):
"""A model grouping layers into an object with training/inference features.
Args:
inputs: The input(s) of the model: a `keras.Input` object or a
combination of `keras.Input` objects in a dict, list or tuple.
outputs: The output(s) of the model: a tensor that originated from
`keras.Input` objects or a combination of such tensors in a dict,
list or tuple. See Functional API example below.
name: String, the name of the model.
There are two ways to instantiate a `Model`:
1 - With the "Functional API", where you start from `Input`,
you chain layer calls to specify the model's forward pass,
and finally you create your model from inputs and outputs:
```python
import tensorflow as tf
inputs = tf.keras.Input(shape=(3,))
x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
```
Note: Only dicts, lists, and tuples of input tensors are supported. Nested
inputs are not supported (e.g. lists of list or dicts of dict).
A new Functional API model can also be created by using the
intermediate tensors. This enables you to quickly extract sub-components
of the model.
Example:
```python
inputs = keras.Input(shape=(None, None, 3))
processed = keras.layers.RandomCrop(width=32, height=32)(inputs)
conv = keras.layers.Conv2D(filters=2, kernel_size=3)(processed)
pooling = keras.layers.GlobalAveragePooling2D()(conv)
feature = keras.layers.Dense(10)(pooling)
full_model = keras.Model(inputs, feature)
backbone = keras.Model(processed, conv)
activations = keras.Model(conv, feature)
```
Note that the `backbone` and `activations` models are not
created with `keras.Input` objects, but with the tensors that are originated
from `keras.Input` objects. Under the hood, the layers and weights will
be shared across these models, so that user can train the `full_model`, and
use `backbone` or `activations` to do feature extraction.
The inputs and outputs of the model can be nested structures of tensors as
well, and the created models are standard Functional API models that support
all the existing APIs.
2 - By subclassing the `Model` class: in that case, you should define your
layers in `__init__()` and you should implement the model's forward pass
in `call()`.
```python
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
def call(self, inputs):
x = self.dense1(inputs)
return self.dense2(x)
model = MyModel()
```
If you subclass `Model`, you can optionally have
a `training` argument (boolean) in `call()`, which you can use to specify
a different behavior in training and inference:
```python
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
self.dropout = tf.keras.layers.Dropout(0.5)
def call(self, inputs, training=False):
x = self.dense1(inputs)
if training:
x = self.dropout(x, training=training)
return self.dense2(x)
model = MyModel()
```
Once the model is created, you can config the model with losses and metrics
with `model.compile()`, train the model with `model.fit()`, or use the model
to do prediction with `model.predict()`.
"""
_TF_MODULE_IGNORED_PROPERTIES = frozenset(
itertools.chain(
(
"_train_counter",
"_test_counter",
"_predict_counter",
"_steps_per_execution",
"_compiled_trainable_state",
),
base_layer.Layer._TF_MODULE_IGNORED_PROPERTIES,
)
)
_SCALAR_UPRANKING_ON = False
def __new__(cls, *args, **kwargs):
# Signature detection
if is_functional_model_init_params(args, kwargs) and cls == Model:
# Functional model
from tf_keras.src.engine import functional
return functional.Functional(skip_init=True, *args, **kwargs)
else:
return super(Model, cls).__new__(cls, *args, **kwargs)
@tf.__internal__.tracking.no_automatic_dependency_tracking
@traceback_utils.filter_traceback
def __init__(self, *args, **kwargs):
self._is_model_for_instrumentation = True
# Special case for Subclassed Functional Model, which we couldn't detect
# when __new__ is called. We only realize it is a functional model when
# it calls super.__init__ with input and output tensor.
from tf_keras.src.engine import functional
if is_functional_model_init_params(args, kwargs) and not isinstance(
self, functional.Functional
):
# Filter the kwargs for multiple inheritance.
supported_kwargs = [
"inputs",
"outputs",
"name",
"trainable",
"skip_init",
]
model_kwargs = {
k: kwargs[k] for k in kwargs if k in supported_kwargs
}
other_kwargs = {
k: kwargs[k] for k in kwargs if k not in supported_kwargs
}
inject_functional_model_class(self.__class__)
functional.Functional.__init__(self, *args, **model_kwargs)
# In case there is any multiple inheritance here, we need to call
# the __init__ for any class that appears after the Functional
# class.
clz_to_init = []
found_functional_class = False
for clz in self.__class__.__bases__:
if issubclass(clz, functional.Functional):
found_functional_class = True
continue
if found_functional_class:
clz_to_init.append(clz)
if clz_to_init:
for clz in clz_to_init:
clz.__init__(self, *args, **other_kwargs)
elif other_kwargs:
# In case there are unused kwargs, we should raise an error to
# user, in case they have a typo in the param name.
raise TypeError(
"The following keyword arguments passed to `Model` aren't "
"supported: {}.".format(other_kwargs)
)
return
# The following are implemented as property functions:
# self.trainable_weights
# self.non_trainable_weights
# `inputs` / `outputs` will only appear in kwargs if either are
# misspelled.
generic_utils.validate_kwargs(
kwargs,
{
"trainable",
"dtype",
"dynamic",
"name",
"autocast",
"inputs",
"outputs",
},
)
super().__init__(**kwargs)
# By default, Model is a subclass model, which is not in graph network.
self._is_graph_network = False
self.inputs = None
self.outputs = None
self.input_names = None
self.output_names = None
# stop_training is used by callback to stop training when error happens
self.stop_training = False
self.history = None
# These objects are used in the default `Model.compile`. They are not
# guaranteed to be set after `Model.compile` is called, as users can
# override compile with custom logic.
self.compiled_loss = None
self.compiled_metrics = None
# This is True for Sequential networks and Functional networks.
self._compute_output_and_mask_jointly = False
# Don't reset compilation if already done. This may occur if calling
# `__init__` (or `_init_graph_network`) on an already-compiled model
# such as a Sequential model. Sequential models may need to rebuild
# themselves after compilation.
self._maybe_create_attribute("_is_compiled", False)
self._maybe_create_attribute("optimizer", None)
# Model must be created under scope of DistStrat it will be trained
# with.
if tf.distribute.has_strategy():
self._distribution_strategy = tf.distribute.get_strategy()
else:
self._distribution_strategy = None
self._distribute_reduction_method = None
self._cluster_coordinator = None
# Defaults to value of `tf.config.experimental_functions_run_eagerly`.
self._run_eagerly = None
# Initialize cache attrs.
self._reset_compile_cache()
# Fault-tolerance handler. Set in `ModelCheckpoint`.
self._training_state = None
self._saved_model_inputs_spec = None
self._saved_model_arg_spec = None
self._checkpoint = tf.train.Checkpoint(root=weakref.ref(self))
self._steps_per_execution = None
self._steps_per_execution_tuner = None
self._autotune_steps_per_execution = False
self._layout_map = layout_map_lib.get_current_layout_map()
self._init_batch_counters()
self._base_model_initialized = True
# `jit_compile` starts off with None as default and gets overwritten by
# the value specified in `Model.compile`, and this is effective for
# `fit`, `evaluate`, and `predict`.
self._jit_compile = None
def _create_counter_variable(self, init_value):
"""Helper function for counter variable creation.
For the DTensor use case with layout map, since the variable are not
tracked by model, they can't be visited by the layout map, and need to
be properly initialized as DVariable.
"""
# This function should be removed after we move to the strategy based
# implementation for DTensor.
if self._layout_map is None:
agg = tf.VariableAggregation.ONLY_FIRST_REPLICA
return tf.Variable(init_value, dtype="int64", aggregation=agg)
else:
layout = dtensor_api.Layout.replicated(
mesh=self._layout_map.get_default_mesh(), rank=0
)
return dtensor_api.DVariable(
init_value, dtype="int64", layout=layout
)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _init_batch_counters(self):
# Untracked Variables, used to keep track of mini-batches seen in `fit`,
# `evaluate`, and `predict`.
if not tf.inside_function():
# Creating variables inside tf.function is not allowed, hence
# these would otherwise prevent users from creating TF-Keras layers
# inside tf.function.
# These variables are not connected to outputs so they have no
# effect on graph generation anyway.
self._train_counter = self._create_counter_variable(0)
self._test_counter = self._create_counter_variable(0)
self._predict_counter = self._create_counter_variable(0)
def __setattr__(self, name, value):
if not getattr(self, "_self_setattr_tracking", True):
super().__setattr__(name, value)
return
if all(
isinstance(v, (base_layer.Layer, tf.Variable))
or base_layer_utils.has_weights(v)
for v in tf.nest.flatten(value)
):
try:
self._base_model_initialized
except AttributeError:
raise RuntimeError(
"It looks like you are subclassing `Model` and you "
"forgot to call `super().__init__()`."
" Always start with this line."
)
super().__setattr__(name, value)
def __reduce__(self):
if self.built:
return (
pickle_utils.deserialize_model_from_bytecode,
(pickle_utils.serialize_model_as_bytecode(self),),
)
else:
# SavedModel (and hence serialize_model_as_bytecode) only support
# built models, but if the model is not built,
# it may be possible to serialize as a plain Python object,
# as long as the constituent parts (layers, optimizers, losses,
# etc.) can be serialized as plain Python objects. Thus we call up
# the superclass hierarchy to get an implementation of __reduce__
# that can pickle this Model as a plain Python object.
return super().__reduce__()
def __deepcopy__(self, memo):
if self.built:
new = pickle_utils.deserialize_model_from_bytecode(
pickle_utils.serialize_model_as_bytecode(self)
)
memo[id(self)] = new
else:
# See comment in __reduce__ for explanation
deserializer, serialized, *rest = super().__reduce__()
new = deserializer(*serialized)
memo[id(self)] = new
if rest:
state = copy.deepcopy(rest[0], memo=memo)
new.__setstate__(state)
return new
def __copy__(self):
return self.__deepcopy__({})
@generic_utils.default
def build(self, input_shape):
"""Builds the model based on input shapes received.
This is to be used for subclassed models, which do not know at
instantiation time what their inputs look like.
This method only exists for users who want to call `model.build()` in a
standalone way (as a substitute for calling the model on real data to
build it). It will never be called by the framework (and thus it will
never throw unexpected errors in an unrelated workflow).
Args:
input_shape: Single tuple, `TensorShape` instance, or list/dict of
shapes, where shapes are tuples, integers, or `TensorShape`
instances.
Raises:
ValueError:
1. In case of invalid user-provided data (not of type tuple,
list, `TensorShape`, or dict).
2. If the model requires call arguments that are agnostic
to the input shapes (positional or keyword arg in call
signature).
3. If not all layers were properly built.
4. If float type inputs are not supported within the layers.
In each of these cases, the user should build their model by calling
it on real tensor data.
"""
if self._is_graph_network:
super().build(input_shape)
return
if input_shape is None:
raise ValueError(
"Input shape must be defined when calling `build()` on "
"a `Model` subclass."
)
valid_types = (tuple, list, tf.TensorShape, dict)
if not isinstance(input_shape, valid_types):
raise ValueError(
"Specified input shape is not one of the valid types. "
"Please specify a batch input shape of type tuple or "
"list of input shapes. User provided "
"input type: {}.".format(type(input_shape))
)
if input_shape and not self.inputs:
# We create placeholders for the `None`s in the shape and build the
# model in a Graph. Since tf.Variable is compatible with both eager
# execution and graph building, the variables created after building
# the model in a Graph are still valid when executing eagerly.
if tf.executing_eagerly():
graph = tf.__internal__.FuncGraph("build_graph")
else:
graph = backend.get_graph()
with graph.as_default():
if isinstance(input_shape, list) and all(
d is None or isinstance(d, int) for d in input_shape
):
input_shape = tuple(input_shape)
if isinstance(input_shape, list):
x = [
base_layer_utils.generate_placeholders_from_shape(shape)
for shape in input_shape
]
elif isinstance(input_shape, dict):
x = {
k: base_layer_utils.generate_placeholders_from_shape(
shape
)
for k, shape in input_shape.items()
}
else:
x = base_layer_utils.generate_placeholders_from_shape(
input_shape
)
kwargs = {}
call_signature = self._call_spec.full_argspec
call_args = call_signature.args
# Exclude `self`, `inputs`, and any argument with a default
# value.
if len(call_args) > 2:
if call_signature.defaults:
call_args = call_args[2 : -len(call_signature.defaults)]
else:
call_args = call_args[2:]
for arg in call_args:
if arg == "training":
# Case where `training` is a positional arg with no
# default.
kwargs["training"] = False
else:
# Has invalid call signature with unknown positional
# arguments.
raise ValueError(
"Currently, you cannot build your model if it "
"has positional or keyword arguments that are "
"not inputs to the model, but are required for "
"its `call()` method. Instead, in order to "
"instantiate and build your model, `call()` "
"your model on real tensor data with all "
"expected call arguments. The argument "
"for `call()` can be a single list/tuple that "
"contains multiple inputs."
)
elif len(call_args) < 2:
# Signature without `inputs`.
raise ValueError(
"You can only call `build()` on a model if its "
"`call()` method accepts an `inputs` argument."
)
try:
self.call(x, **kwargs)
except (tf.errors.InvalidArgumentError, TypeError) as e:
raise ValueError(
"You cannot build your model by calling `build` "
"if your layers do not support float type inputs. "
"Instead, in order to instantiate and build your "
"model, call your model on real tensor data (of "
"the correct dtype).\n\nThe actual error from "
f"`call` is: {e}."
)
super().build(input_shape)
@traceback_utils.filter_traceback
def __call__(self, *args, **kwargs):
if self._layout_map is not None and not self.built:
# Note that this method is only overridden for DTensor and layout
# injection purpose.
# Capture the inputs and create graph input as replacement for model
# to initialize its weights first.
copied_args = copy.copy(args)
copied_kwargs = copy.copy(kwargs)
(
inputs,
copied_args,
copied_kwargs,
) = self._call_spec.split_out_first_arg(copied_args, copied_kwargs)
def _convert_to_graph_inputs(x):
if isinstance(x, (tf.Tensor, np.ndarray, float, int)):
x = tf.convert_to_tensor(x)
return input_layer_module.Input(x.shape)
# TODO(scottzhu): maybe better handle mask and training flag.
inputs = tf.nest.map_structure(_convert_to_graph_inputs, inputs)
copied_args = tf.nest.map_structure(
_convert_to_graph_inputs, copied_args
)
copied_kwargs = tf.nest.map_structure(
_convert_to_graph_inputs, copied_kwargs
)
with layout_map_lib.layout_map_scope(self._layout_map):
# We ignore the result here.
super().__call__(inputs, *copied_args, **copied_kwargs)
layout_map_lib._map_subclass_model_variable(self, self._layout_map)
return super().__call__(*args, **kwargs)
@doc_controls.doc_in_current_and_subclasses
def call(self, inputs, training=None, mask=None):
"""Calls the model on new inputs and returns the outputs as tensors.
In this case `call()` just reapplies
all ops in the graph to the new inputs
(e.g. build a new computational graph from the provided inputs).
Note: This method should not be called directly. It is only meant to be
overridden when subclassing `tf.keras.Model`.
To call a model on an input, always use the `__call__()` method,
i.e. `model(inputs)`, which relies on the underlying `call()` method.
Args:
inputs: Input tensor, or dict/list/tuple of input tensors.
training: Boolean or boolean scalar tensor, indicating whether to
run the `Network` in training mode or inference mode.
mask: A mask or list of masks. A mask can be either a boolean tensor
or None (no mask). For more details, check the guide
[here](https://www.tensorflow.org/guide/keras/masking_and_padding).
Returns:
A tensor if there is a single output, or
a list of tensors if there are more than one outputs.
"""
raise NotImplementedError(
"Unimplemented `tf.keras.Model.call()`: if you "
"intend to create a `Model` with the Functional "
"API, please provide `inputs` and `outputs` "
"arguments. Otherwise, subclass `Model` with an "
"overridden `call()` method."
)
@traceback_utils.filter_traceback
def compile(
self,
optimizer="rmsprop",
loss=None,
metrics=None,
loss_weights=None,
weighted_metrics=None,
run_eagerly=None,
steps_per_execution=None,
jit_compile=None,
pss_evaluation_shards=0,
**kwargs,
):
"""Configures the model for training.
Example:
```python
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),
loss=tf.keras.losses.BinaryCrossentropy(),
metrics=[tf.keras.metrics.BinaryAccuracy(),
tf.keras.metrics.FalseNegatives()])
```
Args:
optimizer: String (name of optimizer) or optimizer instance. See
`tf.keras.optimizers`.
loss: Loss function. May be a string (name of loss function), or
a `tf.keras.losses.Loss` instance. See `tf.keras.losses`. A loss
function is any callable with the signature `loss = fn(y_true,
y_pred)`, where `y_true` are the ground truth values, and
`y_pred` are the model's predictions.
`y_true` should have shape
`(batch_size, d0, .. dN)` (except in the case of
sparse loss functions such as
sparse categorical crossentropy which expects integer arrays of
shape `(batch_size, d0, .. dN-1)`).
`y_pred` should have shape `(batch_size, d0, .. dN)`.
The loss function should return a float tensor.
If a custom `Loss` instance is
used and reduction is set to `None`, return value has shape
`(batch_size, d0, .. dN-1)` i.e. per-sample or per-timestep loss
values; otherwise, it is a scalar. If the model has multiple
outputs, you can use a different loss on each output by passing a
dictionary or a list of losses. The loss value that will be
minimized by the model will then be the sum of all individual
losses, unless `loss_weights` is specified.
metrics: List of metrics to be evaluated by the model during
training and testing. Each of this can be a string (name of a
built-in function), function or a `tf.keras.metrics.Metric`
instance. See `tf.keras.metrics`. Typically you will use
`metrics=['accuracy']`.
A function is any callable with the signature `result = fn(y_true,
y_pred)`. To specify different metrics for different outputs of a
multi-output model, you could also pass a dictionary, such as
`metrics={'output_a':'accuracy', 'output_b':['accuracy', 'mse']}`.
You can also pass a list to specify a metric or a list of metrics
for each output, such as
`metrics=[['accuracy'], ['accuracy', 'mse']]`
or `metrics=['accuracy', ['accuracy', 'mse']]`. When you pass the
strings 'accuracy' or 'acc', we convert this to one of
`tf.keras.metrics.BinaryAccuracy`,
`tf.keras.metrics.CategoricalAccuracy`,
`tf.keras.metrics.SparseCategoricalAccuracy` based on the shapes
of the targets and of the model output. We do a similar
conversion for the strings 'crossentropy' and 'ce' as well.
The metrics passed here are evaluated without sample weighting; if
you would like sample weighting to apply, you can specify your
metrics via the `weighted_metrics` argument instead.
loss_weights: Optional list or dictionary specifying scalar
coefficients (Python floats) to weight the loss contributions of
different model outputs. The loss value that will be minimized by
the model will then be the *weighted sum* of all individual
losses, weighted by the `loss_weights` coefficients. If a list,
it is expected to have a 1:1 mapping to the model's outputs. If a
dict, it is expected to map output names (strings) to scalar
coefficients.
weighted_metrics: List of metrics to be evaluated and weighted by
`sample_weight` or `class_weight` during training and testing.
run_eagerly: Bool. If `True`, this `Model`'s logic will not be
wrapped in a `tf.function`. Recommended to leave this as `None`
unless your `Model` cannot be run inside a `tf.function`.
`run_eagerly=True` is not supported when using
`tf.distribute.experimental.ParameterServerStrategy`. Defaults to
`False`.
steps_per_execution: Int or `'auto'`. The number of batches to
run during each `tf.function` call. If set to "auto", keras will
automatically tune `steps_per_execution` during runtime. Running
multiple batches inside a single `tf.function` call can greatly
improve performance on TPUs, when used with distributed strategies
such as `ParameterServerStrategy`, or with small models with a
large Python overhead. At most, one full epoch will be run each
execution. If a number larger than the size of the epoch is
passed, the execution will be truncated to the size of the epoch.
Note that if `steps_per_execution` is set to `N`,
`Callback.on_batch_begin` and `Callback.on_batch_end` methods will
only be called every `N` batches (i.e. before/after each
`tf.function` execution). Defaults to `1`.
jit_compile: If `True`, compile the model training step with XLA.
[XLA](https://www.tensorflow.org/xla) is an optimizing compiler
for machine learning.
`jit_compile` is not enabled for by default.
Note that `jit_compile=True`
may not necessarily work for all models.
For more information on supported operations please refer to the
[XLA documentation](https://www.tensorflow.org/xla).
Also refer to
[known XLA issues](https://www.tensorflow.org/xla/known_issues)
for more details.
pss_evaluation_shards: Integer or 'auto'. Used for
`tf.distribute.ParameterServerStrategy` training only. This arg
sets the number of shards to split the dataset into, to enable an
exact visitation guarantee for evaluation, meaning the model will
be applied to each dataset element exactly once, even if workers
fail. The dataset must be sharded to ensure separate workers do
not process the same data. The number of shards should be at least
the number of workers for good performance. A value of 'auto'
turns on exact evaluation and uses a heuristic for the number of
shards based on the number of workers. 0, meaning no
visitation guarantee is provided. NOTE: Custom implementations of
`Model.test_step` will be ignored when doing exact evaluation.
Defaults to `0`.
**kwargs: Arguments supported for backwards compatibility only.
"""
if jit_compile and not tf_utils.can_jit_compile(warn=True):
jit_compile = False
self._compile_config = serialization_lib.Config(
optimizer=optimizer,
loss=loss,
metrics=metrics,
loss_weights=loss_weights,
weighted_metrics=weighted_metrics,
run_eagerly=run_eagerly,
steps_per_execution=steps_per_execution,
jit_compile=jit_compile,
)
with self.distribute_strategy.scope():
if "experimental_steps_per_execution" in kwargs:
logging.warning(
"The argument `steps_per_execution` is no longer "
"experimental. Pass `steps_per_execution` instead of "
"`experimental_steps_per_execution`."
)
if not steps_per_execution:
steps_per_execution = kwargs.pop(
"experimental_steps_per_execution"
)
# When compiling from an already-serialized model, we do not want to
# reapply some processing steps (e.g. metric renaming for
# multi-output models, which have prefixes added for each
# corresponding output name).
from_serialized = kwargs.pop("from_serialized", False)
self._validate_compile(optimizer, metrics, **kwargs)
self._run_eagerly = run_eagerly
self.optimizer = self._get_optimizer(optimizer)
mesh = None
if self._layout_map is not None:
mesh = self._layout_map.get_default_mesh()
if isinstance(loss, compile_utils.LossesContainer):
self.compiled_loss = loss
else:
self.compiled_loss = compile_utils.LossesContainer(
loss,
loss_weights,
output_names=self.output_names,
mesh=mesh,
)
self.compiled_metrics = compile_utils.MetricsContainer(
metrics,
weighted_metrics,
output_names=self.output_names,
from_serialized=from_serialized,
mesh=mesh,
)
if steps_per_execution == "auto":
if self._steps_per_execution is None:
self._configure_steps_per_execution(1)
self._steps_per_execution_tuner = (
steps_per_execution_tuning.StepsPerExecutionTuner(
self.optimizer, self._steps_per_execution
)
)
self._autotune_steps_per_execution = True
else:
self._configure_steps_per_execution(steps_per_execution or 1)
self._pss_evaluation_shards = self._infer_exact_eval_shards(
pss_evaluation_shards
)
# Initializes attrs that are reset each time `compile` is called.
self._reset_compile_cache()
self._is_compiled = True
self.loss = loss or {}
if (self._run_eagerly or self.dynamic) and jit_compile:
raise ValueError(
"You cannot enable `run_eagerly` and `jit_compile` "
"at the same time."
)
else:
self._jit_compile = jit_compile
def _get_optimizer(self, optimizer):
"""Wraps `optimizer` in `LossScaleOptimizer` if necessary."""
def _get_single_optimizer(opt):
opt = optimizers.get(opt)
if self.dtype_policy.name == "mixed_float16" and not isinstance(
opt, lso.BaseLossScaleOptimizer
):
# Loss scaling is necessary with mixed_float16 for models to
# converge to the same accuracy as with float32.
opt = lso.BaseLossScaleOptimizer(opt)
return opt
return tf.nest.map_structure(_get_single_optimizer, optimizer)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _reset_compile_cache(self):
self.train_function = None
self.test_function = None
self.predict_function = None
# Used to cache the `tf.function`'ed `train_function` to be logged in
# TensorBoard, since the original `train_function` is not necessarily
# a `tf.function` (e.g., with ParameterServerStrategy, the
# `train_function` is a scheduling of the actual training function to a
# remote worker).
self.train_tf_function = None
# Used to cache `trainable` attr of `Layer`s for `fit`.
self._compiled_trainable_state = self._get_trainable_state()
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _configure_steps_per_execution(self, steps_per_execution):
self._steps_per_execution = self._create_counter_variable(
steps_per_execution
)
@property
def _should_compute_mask(self):
return False
@property
def metrics(self):
"""Return metrics added using `compile()` or `add_metric()`.
Note: Metrics passed to `compile()` are available only after a
`keras.Model` has been trained/evaluated on actual data.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> [m.name for m in model.metrics]
[]
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> model.fit(x, y)
>>> [m.name for m in model.metrics]
['loss', 'mae']
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> d = tf.keras.layers.Dense(2, name='out')
>>> output_1 = d(inputs)
>>> output_2 = d(inputs)
>>> model = tf.keras.models.Model(
... inputs=inputs, outputs=[output_1, output_2])
>>> model.add_metric(
... tf.reduce_sum(output_2), name='mean', aggregation='mean')
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
>>> model.fit(x, (y, y))
>>> [m.name for m in model.metrics]
['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',
'out_1_acc', 'mean']
"""
metrics = []
if self._is_compiled:
if self.compiled_loss is not None:
metrics += self.compiled_loss.metrics
if self.compiled_metrics is not None:
metrics += self.compiled_metrics.metrics
for l in self._flatten_layers():
metrics.extend(l._metrics)
return metrics
@property
def metrics_names(self):
"""Returns the model's display labels for all outputs.
Note: `metrics_names` are available only after a `keras.Model` has been
trained/evaluated on actual data.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> model.metrics_names
[]
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> model.fit(x, y)
>>> model.metrics_names
['loss', 'mae']
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> d = tf.keras.layers.Dense(2, name='out')
>>> output_1 = d(inputs)
>>> output_2 = d(inputs)
>>> model = tf.keras.models.Model(
... inputs=inputs, outputs=[output_1, output_2])
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
>>> model.fit(x, (y, y))
>>> model.metrics_names
['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',
'out_1_acc']
"""
# This property includes all output names including `loss` and
# per-output losses for backward compatibility.
return [m.name for m in self.metrics]
@property
def distribute_strategy(self):
"""The `tf.distribute.Strategy` this model was created under."""
return self._distribution_strategy or tf.distribute.get_strategy()
@property
def run_eagerly(self):
"""Settable attribute indicating whether the model should run eagerly.
Running eagerly means that your model will be run step by step,
like Python code. Your model might run slower, but it should become
easier for you to debug it by stepping into individual layer calls.
By default, we will attempt to compile your model to a static graph to
deliver the best execution performance.
Returns:
Boolean, whether the model should run eagerly.
"""
if self.dynamic and self._run_eagerly == False:
# TODO(fchollet): consider using py_func to enable this.
raise ValueError(
"Your model contains layers that can only be "
"successfully run in eager execution (layers "
"constructed with `dynamic=True`). "
"You cannot set `run_eagerly=False`."
)
if self._cluster_coordinator and self._run_eagerly:
raise ValueError(
"When using `Model` with `ParameterServerStrategy`, "
"`run_eagerly` is not supported."
)
# Run eagerly logic, by priority:
# (1) Dynamic models must be run eagerly.
# (2) Explicitly setting run_eagerly causes a Model to be run eagerly.
# (3) Not explicitly setting run_eagerly defaults to TF's global
# setting.
return (
self.dynamic
or self._run_eagerly
or (tf.config.functions_run_eagerly() and self._run_eagerly is None)
)
@run_eagerly.setter
def run_eagerly(self, value):
self._run_eagerly = value
@property
def autotune_steps_per_execution(self):
"""Settable property to enable tuning for steps_per_execution"""
return self._autotune_steps_per_execution
@autotune_steps_per_execution.setter
def autotune_steps_per_execution(self, value):
self._autotune_steps_per_execution = value
if value and self._steps_per_execution_tuner is None:
if self._steps_per_execution is None:
self._configure_steps_per_execution(1)
self._steps_per_execution_tuner = (
steps_per_execution_tuning.StepsPerExecutionTuner(
self.optimizer, self._steps_per_execution
)
)
@property
def steps_per_execution(self):
"""Settable `steps_per_execution variable. Requires a compiled model."""
return self._steps_per_execution
@steps_per_execution.setter
def steps_per_execution(self, value):
if self._steps_per_execution is None:
self._configure_steps_per_execution(value)
else:
self._steps_per_execution.assign(value)
@property
def jit_compile(self):
"""Specify whether to compile the model with XLA.
[XLA](https://www.tensorflow.org/xla) is an optimizing compiler
for machine learning. `jit_compile` is not enabled by default.
Note that `jit_compile=True` may not necessarily work for all models.
For more information on supported operations please refer to the
[XLA documentation](https://www.tensorflow.org/xla). Also refer to
[known XLA issues](https://www.tensorflow.org/xla/known_issues)
for more details.
"""
return self._jit_compile
@jit_compile.setter
def jit_compile(self, value):
# Function remains cached with previous jit_compile settings
if self._jit_compile == value:
# Avoid resetting compiler cache if possible if the value is the
# same
return
# Check if TensorFlow is compiled with XLA before setting the value
if value and not tf_utils.can_jit_compile(warn=True):
self._jit_compile = False
return
self._jit_compile = value
# Setting `jit_compile` should invalidate previously cached functions.
self._reset_compile_cache()
@property
def distribute_reduction_method(self):
"""The method employed to reduce per-replica values during training.
Unless specified, the value "auto" will be assumed, indicating that
the reduction strategy should be chosen based on the current
running environment.
See `reduce_per_replica` function for more details.
"""
return self._distribute_reduction_method or "auto"
@distribute_reduction_method.setter
def distribute_reduction_method(self, value):
self._distribute_reduction_method = value
def _validate_target_and_loss(self, y, loss):
"""Raises error if target or loss is not found.
This method verifies that the target and loss are properly populated
when applicable, or raises errors.
Args:
y: the target for training.
loss: the total loss tensor including loss added via `compile` and
`add_loss`.
"""
# `self.loss` references the loss added via `compile` call. If users
# have provided such, the target must be provided; otherwise it's a user
# error. Note that `self.loss` does not include losses added via
# `add_loss`, and it is a valid use when such loss from `add_loss`
# exists and target does not.
if self.loss and y is None:
raise ValueError(
"Target data is missing. Your model was compiled with "
f"loss={self.loss}, "
"and therefore expects target data to be provided in `fit()`."
)
# For training, there must be compiled loss or regularization loss to
# exist in order to apply the gradients. If one is not found, it means
# no loss was supplied via `compile` or `add_loss`.
elif loss is None:
raise ValueError(
"No loss found. You may have forgotten to provide a `loss` "
"argument in the `compile()` method."
)
def train_step(self, data):
"""The logic for one training step.
This method can be overridden to support custom training logic.
For concrete examples of how to override this method see
[Customizing what happens in fit](
https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit).
This method is called by `Model.make_train_function`.
This method should contain the mathematical logic for one step of
training. This typically includes the forward pass, loss calculation,
backpropagation, and metric updates.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_train_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the
values of the `Model`'s metrics are returned. Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data)
# Run forward pass.
with tf.GradientTape() as tape:
y_pred = self(x, training=True)
loss = self.compute_loss(x, y, y_pred, sample_weight)
self._validate_target_and_loss(y, loss)
# Run backwards pass.
self.optimizer.minimize(loss, self.trainable_variables, tape=tape)
return self.compute_metrics(x, y, y_pred, sample_weight)
def compute_loss(self, x=None, y=None, y_pred=None, sample_weight=None):
"""Compute the total loss, validate it, and return it.
Subclasses can optionally override this method to provide custom loss
computation logic.
Example:
```python
class MyModel(tf.keras.Model):
def __init__(self, *args, **kwargs):
super(MyModel, self).__init__(*args, **kwargs)
self.loss_tracker = tf.keras.metrics.Mean(name='loss')
def compute_loss(self, x, y, y_pred, sample_weight):
loss = tf.reduce_mean(tf.math.squared_difference(y_pred, y))
loss += tf.add_n(self.losses)
self.loss_tracker.update_state(loss)
return loss
def reset_metrics(self):
self.loss_tracker.reset_states()
@property
def metrics(self):
return [self.loss_tracker]
tensors = tf.random.uniform((10, 10)), tf.random.uniform((10,))
dataset = tf.data.Dataset.from_tensor_slices(tensors).repeat().batch(1)
inputs = tf.keras.layers.Input(shape=(10,), name='my_input')
outputs = tf.keras.layers.Dense(10)(inputs)
model = MyModel(inputs, outputs)
model.add_loss(tf.reduce_sum(outputs))
optimizer = tf.keras.optimizers.SGD()
model.compile(optimizer, loss='mse', steps_per_execution=10)
model.fit(dataset, epochs=2, steps_per_epoch=10)
print('My custom loss: ', model.loss_tracker.result().numpy())
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
The total loss as a `tf.Tensor`, or `None` if no loss results (which
is the case when called by `Model.test_step`).
"""
del x # The default implementation does not use `x`.
return self.compiled_loss(
y, y_pred, sample_weight, regularization_losses=self.losses
)
def compute_metrics(self, x, y, y_pred, sample_weight):
"""Update metric states and collect all metrics to be returned.
Subclasses can optionally override this method to provide custom metric
updating and collection logic.
Example:
```python
class MyModel(tf.keras.Sequential):
def compute_metrics(self, x, y, y_pred, sample_weight):
# This super call updates `self.compiled_metrics` and returns
# results for all metrics listed in `self.metrics`.
metric_results = super(MyModel, self).compute_metrics(
x, y, y_pred, sample_weight)
# Note that `self.custom_metric` is not listed in `self.metrics`.
self.custom_metric.update_state(x, y, y_pred, sample_weight)
metric_results['custom_metric_name'] = self.custom_metric.result()
return metric_results
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model.call(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end()`. Typically, the
values of the metrics listed in `self.metrics` are returned. Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
del x # The default implementation does not use `x`.
self.compiled_metrics.update_state(y, y_pred, sample_weight)
return self.get_metrics_result()
def get_metrics_result(self):
"""Returns the model's metrics values as a dict.
If any of the metric result is a dict (containing multiple metrics),
each of them gets added to the top level returned dict of this method.
Returns:
A `dict` containing values of the metrics listed in `self.metrics`.
Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
# Collect metrics to return
return_metrics = {}
for metric in self.metrics:
result = metric.result()
if isinstance(result, dict):
return_metrics.update(result)
else:
return_metrics[metric.name] = result
return return_metrics
def _validate_and_get_metrics_result(self, logs):
"""Returns model metrics as a dict if the keys match with input logs.
When the training / evalution is performed with asynchronous steps, such
as the case with `tf.distribute.ParameterServerStrategy`, the last
scheduled `train / test_step` may not give the latest metrics because it
is not guaranteed to be executed the last. This method gets metrics from
the model directly instead of relying on the return from last step
function.
It logs a warning if the metric results could not be overridden when
used with `tf.distribute.ParameterServerStrategy`.
When the user has custom train / test step functions, the metrics
returned may be different from `Model.metrics`. In those instances,
this function will be no-op and return the logs.
Args:
logs: A `dict` of metrics returned by train / test step function.
Returns:
A `dict` containing values of the metrics listed in `self.metrics`
when logs and model metrics keys match. Otherwise it returns input
`logs`.
"""
PSS_WARN_MSG = "Could not get Model metric results. \
Using the results of last step function could lead to incorrect \
results when used with ParameterServerStrategy"
try:
metric_logs = self.get_metrics_result()
except TypeError:
if self._cluster_coordinator:
logging.warning(PSS_WARN_MSG)
else:
# Verify that train / test step logs passed and metric logs have
# matching keys. Could be different when using custom step functions
if isinstance(logs, dict) and set(logs.keys()) == set(
metric_logs.keys()
):
logs = tf_utils.sync_to_numpy_or_python_type(metric_logs)
elif self._cluster_coordinator:
logging.warning(PSS_WARN_MSG)
return logs
def _aggregate_exact_metrics(self, logs):
# When doing exact evaluation, `logs` is a list of each data shard's
# metric variables, which will be used to update the metrics.
for shard_result in logs:
for metric in self.metrics:
if metric.name not in shard_result.keys():
logging.log_first_n(
logging.WARN,
f"No matching result found for metric {metric.name}. "
"This metric's computed result may be incorrect.",
3,
)
continue
metric_result = shard_result[metric.name]
if len(metric_result) != len(metric.weights):
raise ValueError(
f"Expected {len(metric.weights)} variables in result "
f"for metric {metric.name}, but found "
f"{len(metric_result)}."
)
for weight, val in zip(metric.weights, metric_result):
weight.assign_add(val)
return self.get_metrics_result()
def make_train_function(self, force=False):
"""Creates a function that executes one step of training.
This method can be overridden to support custom training logic.
This method is called by `Model.fit` and `Model.train_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual training
logic to `Model.train_step`.
This function is cached the first time `Model.fit` or
`Model.train_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the train function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_train_batch_end`, such as
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
if self.train_function is not None and not force:
return self.train_function
def step_function(model, iterator):
"""Runs a single training step."""
def run_step(data):
outputs = model.train_step(data)
# Ensure counter is updated only if `train_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._train_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def train_function(iterator):
"""Runs a training execution with a single step."""
return step_function(self, iterator)
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
if self._cluster_coordinator:
self.train_function = (
lambda it: self._cluster_coordinator.schedule(
train_function, args=(it,)
)
)
else:
self.train_function = train_function
# If we're using a coordinator, use the value of
# self._steps_per_execution at the time the function is
# called/scheduled, and not when it is actually executed.
elif self._cluster_coordinator:
def train_function(iterator, steps_per_execution):
"""Runs a training execution with multiple steps."""
for _ in tf.range(steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
self.train_function = lambda it: self._cluster_coordinator.schedule(
train_function, args=(it, self._steps_per_execution.value())
)
else:
def train_function(iterator):
"""Runs a training execution with multiple steps."""
for _ in tf.range(self._steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
self.train_function = train_function
return self.train_function
@traceback_utils.filter_traceback
def fit(
self,
x=None,
y=None,
batch_size=None,
epochs=1,
verbose="auto",
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_batch_size=None,
validation_freq=1,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
):
"""Trains the model for a fixed number of epochs (dataset iterations).
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A `tf.data` dataset. Should return a tuple
of either `(inputs, targets)` or
`(inputs, targets, sample_weights)`.
- A generator or `keras.utils.Sequence` returning `(inputs,
targets)` or `(inputs, targets, sample_weights)`.
- A `tf.keras.utils.experimental.DatasetCreator`, which wraps a
callable that takes a single argument of type
`tf.distribute.InputContext`, and returns a `tf.data.Dataset`.
`DatasetCreator` should be used when users prefer to specify the
per-replica batching and sharding logic for the `Dataset`.
See `tf.keras.utils.experimental.DatasetCreator` doc for more
information.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given below. If these
include `sample_weights` as a third component, note that sample
weighting applies to the `weighted_metrics` argument but not the
`metrics` argument in `compile()`. If using
`tf.distribute.experimental.ParameterServerStrategy`, only
`DatasetCreator` type is supported for `x`.
y: Target data. Like the input data `x`,
it could be either Numpy array(s) or TensorFlow tensor(s).
It should be consistent with `x` (you cannot have Numpy inputs and
tensor targets, or inversely). If `x` is a dataset, generator,
or `keras.utils.Sequence` instance, `y` should
not be specified (since targets will be obtained from `x`).
batch_size: Integer or `None`.
Number of samples per gradient 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).
epochs: Integer. Number of epochs to train the model.
An epoch is an iteration over the entire `x` and `y`
data provided
(unless the `steps_per_epoch` flag is set to
something other than None).
Note that in conjunction with `initial_epoch`,
`epochs` is to be understood as "final epoch".
The model is not trained for a number of iterations
given by `epochs`, but merely until the epoch
of index `epochs` is reached.
verbose: 'auto', 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = one line per epoch.
'auto' becomes 1 for most cases, but 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so verbose=2 is
recommended when not running interactively (eg, in a production
environment). Defaults to 'auto'.
callbacks: List of `keras.callbacks.Callback` instances.
List of callbacks to apply during training.
See `tf.keras.callbacks`. Note
`tf.keras.callbacks.ProgbarLogger` and
`tf.keras.callbacks.History` callbacks are created automatically
and need not be passed into `model.fit`.
`tf.keras.callbacks.ProgbarLogger` is created or not based on
`verbose` argument to `model.fit`.
Callbacks with batch-level calls are currently unsupported with
`tf.distribute.experimental.ParameterServerStrategy`, and users
are advised to implement epoch-level calls instead with an
appropriate `steps_per_epoch` value.
validation_split: Float between 0 and 1.
Fraction of the training data to be used as validation data.
The model will set apart this fraction of the training data,
will not train on it, and will evaluate
the loss and any model metrics
on this data at the end of each epoch.
The validation data is selected from the last samples
in the `x` and `y` data provided, before shuffling. This
argument is not supported when `x` is a dataset, generator or
`keras.utils.Sequence` instance.
If both `validation_data` and `validation_split` are provided,
`validation_data` will override `validation_split`.
`validation_split` is not yet supported with
`tf.distribute.experimental.ParameterServerStrategy`.
validation_data: Data on which to evaluate
the loss and any model metrics at the end of each epoch.
The model will not be trained on this data. Thus, note the fact
that the validation loss of data provided using
`validation_split` or `validation_data` is not affected by
regularization layers like noise and dropout.
`validation_data` will override `validation_split`.
`validation_data` could be:
- A tuple `(x_val, y_val)` of Numpy arrays or tensors.
- A tuple `(x_val, y_val, val_sample_weights)` of NumPy
arrays.
- A `tf.data.Dataset`.
- A Python generator or `keras.utils.Sequence` returning
`(inputs, targets)` or `(inputs, targets, sample_weights)`.
`validation_data` is not yet supported with
`tf.distribute.experimental.ParameterServerStrategy`.
shuffle: Boolean (whether to shuffle the training data
before each epoch) or str (for 'batch'). This argument is
ignored when `x` is a generator or an object of tf.data.Dataset.
'batch' is a special option for dealing
with the limitations of HDF5 data; it shuffles in batch-sized
chunks. Has no effect when `steps_per_epoch` is not `None`.
class_weight: Optional dictionary mapping class indices (integers)
to a weight (float) value, used for weighting the loss function
(during training only).
This can be useful to tell the model to
"pay more attention" to samples from
an under-represented class. When `class_weight` is specified
and targets have a rank of 2 or greater, either `y` must be
one-hot encoded, or an explicit final dimension of `1` must
be included for sparse class labels.
sample_weight: Optional Numpy array of weights for
the training samples, used for weighting the loss function
(during training only). You can either pass a flat (1D)
Numpy array with the same length as the input samples
(1:1 mapping between weights and samples),
or in the case of temporal data,
you can pass a 2D array with shape
`(samples, sequence_length)`,
to apply a different weight to every timestep of every sample.
This argument is not supported when `x` is a dataset, generator,
or `keras.utils.Sequence` instance, instead provide the
sample_weights as the third element of `x`.
Note that sample weighting does not apply to metrics specified
via the `metrics` argument in `compile()`. To apply sample
weighting to your metrics, you can specify them via the
`weighted_metrics` in `compile()` instead.
initial_epoch: Integer.
Epoch at which to start training
(useful for resuming a previous training run).
steps_per_epoch: Integer or `None`.
Total number of steps (batches of samples)
before declaring one epoch finished and starting the
next epoch. 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_per_epoch'
is None, the epoch will run until the input dataset is
exhausted. When passing an infinitely repeating dataset, you
must specify the `steps_per_epoch` argument. If
`steps_per_epoch=-1` the training will run indefinitely with an
infinitely repeating dataset. This argument is not supported
with array inputs.
When using `tf.distribute.experimental.ParameterServerStrategy`:
* `steps_per_epoch=None` is not supported.
validation_steps: Only relevant if `validation_data` is provided and
is a `tf.data` dataset. Total number of steps (batches of
samples) to draw before stopping when performing validation
at the end of every epoch. If 'validation_steps' is None,
validation will run until the `validation_data` dataset is
exhausted. In the case of an infinitely repeated dataset, it
will run into an infinite loop. If 'validation_steps' is
specified and only part of the dataset will be consumed, the
evaluation will start from the beginning of the dataset at each
epoch. This ensures that the same validation samples are used
every time.
validation_batch_size: Integer or `None`.
Number of samples per validation batch.
If unspecified, will default to `batch_size`.
Do not specify the `validation_batch_size` if your data is in
the form of datasets, generators, or `keras.utils.Sequence`
instances (since they generate batches).
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.
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the generator
queue. If unspecified, `max_queue_size` will default to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up
when using process-based threading. If unspecified, `workers`
will default to 1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
Unpacking behavior for iterator-like inputs:
A common pattern is to pass a tf.data.Dataset, generator, or
tf.keras.utils.Sequence to the `x` argument of fit, which will in fact
yield not only features (x) but optionally targets (y) and sample
weights. TF-Keras requires that the output of such iterator-likes be
unambiguous. The iterator should return a tuple of length 1, 2, or 3,
where the optional second and third elements will be used for y and
sample_weight respectively. Any other type provided will be wrapped in
a length one tuple, effectively treating everything as 'x'. When
yielding dicts, they should still adhere to the top-level tuple
structure.
e.g. `({"x0": x0, "x1": x1}, y)`. TF-Keras will not attempt to
separate features, targets, and weights from the keys of a single
dict.
A notable unsupported data type is the namedtuple. The reason is
that it behaves like both an ordered datatype (tuple) and a mapping
datatype (dict). So given a namedtuple of the form:
`namedtuple("example_tuple", ["y", "x"])`
it is ambiguous whether to reverse the order of the elements when
interpreting the value. Even worse is a tuple of the form:
`namedtuple("other_tuple", ["x", "y", "z"])`
where it is unclear if the tuple was intended to be unpacked into x,
y, and sample_weight or passed through as a single element to `x`. As
a result the data processing code will simply raise a ValueError if it
encounters a namedtuple. (Along with instructions to remedy the
issue.)
Returns:
A `History` object. Its `History.history` attribute is
a record of training loss values and metrics values
at successive epochs, as well as validation loss values
and validation metrics values (if applicable).
Raises:
RuntimeError: 1. If the model was never compiled or,
2. If `model.fit` is wrapped in `tf.function`.
ValueError: In case of mismatch between the provided input data
and what the model expects or when the input data is empty.
"""
# Legacy graph support is contained in `training_v1.Model`.
version_utils.disallow_legacy_graph("Model", "fit")
self._assert_compile_was_called()
self._check_call_args("fit")
_disallow_inside_tf_function("fit")
verbose = _get_verbosity(verbose, self.distribute_strategy)
if validation_split and validation_data is None:
# Create the validation data using the training data. Only supported
# for `Tensor` and `NumPy` input.
(
x,
y,
sample_weight,
), validation_data = data_adapter.train_validation_split(
(x, y, sample_weight), validation_split=validation_split
)
if validation_data:
(
val_x,
val_y,
val_sample_weight,
) = data_adapter.unpack_x_y_sample_weight(validation_data)
if self.distribute_strategy._should_use_with_coordinator:
self._cluster_coordinator = (
tf.distribute.experimental.coordinator.ClusterCoordinator(
self.distribute_strategy
)
)
with self.distribute_strategy.scope(), training_utils.RespectCompiledTrainableState( # noqa: E501
self
):
# Creates a `tf.data.Dataset` and handles batch and epoch iteration.
data_handler = data_adapter.get_data_handler(
x=x,
y=y,
sample_weight=sample_weight,
batch_size=batch_size,
steps_per_epoch=steps_per_epoch,
initial_epoch=initial_epoch,
epochs=epochs,
shuffle=shuffle,
class_weight=class_weight,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=epochs,
steps=data_handler.inferred_steps,
)
self.stop_training = False
self.train_function = self.make_train_function()
self._train_counter.assign(0)
callbacks.on_train_begin()
training_logs = None
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
# Handle fault-tolerance for multi-worker.
# TODO(omalleyt): Fix the ordering issues that mean this has to
# happen after `callbacks.on_train_begin`.
steps_per_epoch_inferred = (
steps_per_epoch or data_handler.inferred_steps
)
(
data_handler._initial_epoch,
data_handler._initial_step,
) = self._maybe_load_initial_counters_from_ckpt(
steps_per_epoch_inferred, initial_epoch
)
logs = None
for epoch, iterator in data_handler.enumerate_epochs():
self.reset_metrics()
callbacks.on_epoch_begin(epoch)
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
with tf.profiler.experimental.Trace(
"train",
epoch_num=epoch,
step_num=step,
batch_size=batch_size,
_r=1,
):
callbacks.on_train_batch_begin(step)
tmp_logs = self.train_function(iterator)
if data_handler.should_sync:
context.async_wait()
# No error, now safe to assign to logs.
logs = tmp_logs
end_step = step + data_handler.step_increment
callbacks.on_train_batch_end(end_step, logs)
if self.stop_training:
break
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if logs is None:
raise ValueError(
"Unexpected result of `train_function` "
"(Empty logs). This could be due to issues in input "
"pipeline that resulted in an empty dataset. "
"Otherwise, please use "
"`Model.compile(..., run_eagerly=True)`, or "
"`tf.config.run_functions_eagerly(True)` for more "
"information of where went wrong, or file a "
"issue/bug to `tf.keras`."
)
# Override with model metrics instead of last step logs
logs = self._validate_and_get_metrics_result(logs)
epoch_logs = copy.copy(logs)
# Run validation.
if validation_data and self._should_eval(
epoch, validation_freq
):
if self._pss_evaluation_shards:
self._disallow_exact_eval_with_add_metrics()
# Create data_handler for evaluation and cache it.
if getattr(self, "_eval_data_handler", None) is None:
self._eval_data_handler = data_adapter.get_data_handler(
x=val_x,
y=val_y,
sample_weight=val_sample_weight,
batch_size=validation_batch_size or batch_size,
steps_per_epoch=validation_steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
pss_evaluation_shards=self._pss_evaluation_shards,
)
val_logs = self.evaluate(
x=val_x,
y=val_y,
sample_weight=val_sample_weight,
batch_size=validation_batch_size or batch_size,
steps=validation_steps,
callbacks=callbacks,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
return_dict=True,
_use_cached_eval_dataset=True,
)
val_logs = {
"val_" + name: val for name, val in val_logs.items()
}
epoch_logs.update(val_logs)
callbacks.on_epoch_end(epoch, epoch_logs)
training_logs = epoch_logs
if self.stop_training:
break
if isinstance(self.optimizer, optimizer.Optimizer) and epochs > 0:
self.optimizer.finalize_variable_values(
self.trainable_variables
)
# If eval data_handler exists, delete it after all epochs are done.
if getattr(self, "_eval_data_handler", None) is not None:
del self._eval_data_handler
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_train_end(logs=training_logs)
return self.history
def test_step(self, data):
"""The logic for one evaluation step.
This method can be overridden to support custom evaluation logic.
This method is called by `Model.make_test_function`.
This function should contain the mathematical logic for one step of
evaluation.
This typically includes the forward pass, loss calculation, and metrics
updates.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_test_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the
values of the `Model`'s metrics are returned.
"""
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data)
y_pred = self(x, training=False)
# Updates stateful loss metrics.
self.compute_loss(x, y, y_pred, sample_weight)
return self.compute_metrics(x, y, y_pred, sample_weight)
def _make_test_function_exact(self):
if getattr(self, "_shard_test_function", None):
return self._shard_test_function
def step_function(batch):
def run_step(data):
# TODO(b/272050910): Use sample_weight for weighted metrics.
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(
data
)
y_pred = self(x, training=False)
return x, y, y_pred, sample_weight
if self._jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
outputs = self.distribute_strategy.run(run_step, args=(batch,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
def shard_test_function(dataset, total_shards, shard_idx):
# Copy loss and metric variables to the worker and work with them
# locally. This ensures each shard function is atomic: if a worker
# is preempted, the intermediate progress is discarded and that
# shard is retried. This in turn guarantees exactly-once visitation.
local_unweighted_metrics, local_weighted_metrics = [], []
with tf_utils.with_metric_local_vars_scope():
# TODO(jmullenbach): implement and use a clone for
# `MetricsContainer` and use its `update_state` method directly.
for metric in self.compiled_metrics.unweighted_metrics:
if metric is not None:
local_unweighted_metrics.append(
base_metric.clone_metric(metric)
)
for metric in self.compiled_metrics.weighted_metrics:
if metric is not None:
local_weighted_metrics.append(
base_metric.clone_metric(metric)
)
local_loss = compile_utils.LossesContainer.from_config(
self.compiled_loss.get_config()
)
dataset = input_ops.auto_shard_dataset(
dataset, total_shards, shard_idx
)
iterator = iter(dataset)
with distribute_utils.cache_variable_reads():
for batch in iterator:
x, y, y_pred, sample_weight = step_function(batch)
for weighted_metric in local_weighted_metrics:
weighted_metric.update_state(y, y_pred, sample_weight)
for unweighted_metric in local_unweighted_metrics:
unweighted_metric.update_state(y, y_pred)
local_loss(y, y_pred, sample_weight)
local_metrics = (
local_unweighted_metrics
+ local_weighted_metrics
+ local_loss.metrics
)
outputs = {metric.name: metric.weights for metric in local_metrics}
with tf.control_dependencies(_minimum_control_deps(outputs)):
self._test_counter.assign_add(1)
return outputs
if not self.run_eagerly:
shard_test_function = tf.function(
shard_test_function, reduce_retracing=True
)
self._shard_test_function = (
lambda *args: self._cluster_coordinator.schedule(
shard_test_function,
args=args,
)
)
return self._shard_test_function
def make_test_function(self, force=False):
"""Creates a function that executes one step of evaluation.
This method can be overridden to support custom evaluation logic.
This method is called by `Model.evaluate` and `Model.test_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.test_step`.
This function is cached the first time `Model.evaluate` or
`Model.test_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the test function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_test_batch_end`.
"""
if self.test_function is not None and not force:
return self.test_function
def step_function(model, iterator):
"""Runs a single evaluation step."""
def run_step(data):
outputs = model.test_step(data)
# Ensure counter is updated only if `test_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._test_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def test_function(iterator):
"""Runs a test execution with a single step."""
return step_function(self, iterator)
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
if self._cluster_coordinator:
self.test_function = (
lambda it: self._cluster_coordinator.schedule(
test_function, args=(it,)
)
)
else:
self.test_function = test_function
# If we're using a coordinator, use the value of
# self._steps_per_execution at the time the function is
# called/scheduled, and not when it is actually executed.
elif self._cluster_coordinator:
def test_function(iterator, steps_per_execution):
"""Runs a test execution with multiple steps."""
for _ in tf.range(steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
self.test_function = lambda it: self._cluster_coordinator.schedule(
test_function, args=(it, self._steps_per_execution.value())
)
else:
def test_function(iterator):
"""Runs a test execution with multiple steps."""
for _ in tf.range(self._steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
self.test_function = test_function
return self.test_function
@traceback_utils.filter_traceback
def evaluate(
self,
x=None,
y=None,
batch_size=None,
verbose="auto",
sample_weight=None,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
return_dict=False,
**kwargs,
):
"""Returns the loss value & metrics values for the model in test mode.
Computation is done in batches (see the `batch_size` arg.)
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A `tf.data` dataset. Should return a tuple
of either `(inputs, targets)` or
`(inputs, targets, sample_weights)`.
- A generator or `keras.utils.Sequence` returning `(inputs,
targets)` or `(inputs, targets, sample_weights)`.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given in the `Unpacking
behavior for iterator-like inputs` section of `Model.fit`.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s). It should be consistent with `x`
(you cannot have Numpy inputs and tensor targets, or inversely).
If `x` is a dataset, generator or `keras.utils.Sequence` instance,
`y` should not be specified (since targets will be obtained from
the iterator/dataset).
batch_size: Integer or `None`. Number of samples per batch of
computation. If unspecified, `batch_size` will default to 32. Do
not specify the `batch_size` if your data is in the form of a
dataset, generators, or `keras.utils.Sequence` instances (since
they generate batches).
verbose: `"auto"`, 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = single line.
`"auto"` becomes 1 for most cases, and to 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so `verbose=2` is
recommended when not running interactively (e.g. in a production
environment). Defaults to 'auto'.
sample_weight: Optional Numpy array of weights for the test samples,
used for weighting the loss function. You can either pass a flat
(1D) Numpy array with the same length as the input samples
(1:1 mapping between weights and samples), or in the case of
temporal data, you can pass a 2D array with shape `(samples,
sequence_length)`, to apply a different weight to every
timestep of every sample. This argument is not supported when
`x` is a dataset, instead pass sample weights as the third
element of `x`.
steps: Integer or `None`. Total number of steps (batches of samples)
before declaring the evaluation round finished. Ignored with the
default value of `None`. If x is a `tf.data` dataset and `steps`
is None, 'evaluate' will run until the dataset is exhausted. This
argument is not supported with array inputs.
callbacks: List of `keras.callbacks.Callback` instances. List of
callbacks to apply during evaluation. See
[callbacks](https://www.tensorflow.org/api_docs/python/tf/tf_keras/callbacks).
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the generator
queue. If unspecified, `max_queue_size` will default to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, `workers` will default to
1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
**kwargs: Unused at this time.
See the discussion of `Unpacking behavior for iterator-like inputs` for
`Model.fit`.
Returns:
Scalar test 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 scalar outputs.
Raises:
RuntimeError: If `model.evaluate` is wrapped in a `tf.function`.
"""
version_utils.disallow_legacy_graph("Model", "evaluate")
self._assert_compile_was_called()
self._check_call_args("evaluate")
self._check_sample_weight_warning(x, sample_weight)
_disallow_inside_tf_function("evaluate")
use_cached_eval_dataset = kwargs.pop("_use_cached_eval_dataset", False)
if kwargs:
raise TypeError(f"Invalid keyword arguments: {list(kwargs.keys())}")
if self.distribute_strategy._should_use_with_coordinator:
self._cluster_coordinator = (
tf.distribute.experimental.coordinator.ClusterCoordinator(
self.distribute_strategy
)
)
verbose = _get_verbosity(verbose, self.distribute_strategy)
if self._pss_evaluation_shards:
self._disallow_exact_eval_with_add_metrics()
with self.distribute_strategy.scope():
# Use cached evaluation data only when it's called in `Model.fit`
if (
use_cached_eval_dataset
and getattr(self, "_eval_data_handler", None) is not None
):
data_handler = self._eval_data_handler
else:
# Creates a `tf.data.Dataset` and handles batch and epoch
# iteration.
data_handler = data_adapter.get_data_handler(
x=x,
y=y,
sample_weight=sample_weight,
batch_size=batch_size,
steps_per_epoch=steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
pss_evaluation_shards=self._pss_evaluation_shards,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=1,
steps=data_handler.inferred_steps,
)
# Initialize to prevent errors if 0 epochs are evaluated.
logs = {}
test_function_runner = self._get_test_function_runner(callbacks)
self._test_counter.assign(0)
callbacks.on_test_begin()
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
for (
_,
dataset_or_iterator,
) in data_handler.enumerate_epochs(): # Single epoch.
self.reset_metrics()
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
with tf.profiler.experimental.Trace(
"test", step_num=step, _r=1
):
callbacks.on_test_batch_begin(step)
logs = test_function_runner.run_step(
dataset_or_iterator,
data_handler,
step,
self._pss_evaluation_shards,
)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
# Override with model metrics instead of last step logs
if self._pss_evaluation_shards:
logs = self._aggregate_exact_metrics(logs)
else:
logs = self._validate_and_get_metrics_result(logs)
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_test_end(logs=logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def _disallow_exact_eval_with_add_metrics(self):
metrics_from_add_metric = [
metric
for layer in self._flatten_layers()
for metric in layer._metrics
]
compiled_metrics = self.compiled_metrics.metrics
if any(
[
metric not in compiled_metrics
for metric in metrics_from_add_metric
]
):
raise ValueError(
"Detected that a metric was added to this model "
"via `Model.add_metric`. This is not currently "
"supported when using exact evaluation with "
"`tf.distribute.ParameterServerStrategy`."
)
def _infer_exact_eval_shards(self, pss_evaluation_shards):
if not self.distribute_strategy._should_use_with_coordinator:
return 0
if pss_evaluation_shards == "auto":
# TODO(b/264265138) evaluate and improve this heuristic
return self.distribute_strategy._num_workers * 5
return pss_evaluation_shards
def _get_test_function_runner(self, callbacks):
if (
self._pss_evaluation_shards
and self.distribute_strategy._should_use_with_coordinator
):
self.test_function = self._make_test_function_exact()
test_function_runner = _ExactTestFunction(
self.test_function, callbacks
)
else:
self.test_function = self.make_test_function()
test_function_runner = _TestFunction(self.test_function, callbacks)
return test_function_runner
def predict_step(self, data):
"""The logic for one inference step.
This method can be overridden to support custom inference logic.
This method is called by `Model.make_predict_function`.
This method should contain the mathematical logic for one step of
inference. This typically includes the forward pass.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_predict_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
The result of one inference step, typically the output of calling the
`Model` on data.
"""
x, _, _ = data_adapter.unpack_x_y_sample_weight(data)
return self(x, training=False)
def make_predict_function(self, force=False):
"""Creates a function that executes one step of inference.
This method can be overridden to support custom inference logic.
This method is called by `Model.predict` and `Model.predict_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.predict_step`.
This function is cached the first time `Model.predict` or
`Model.predict_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the predict function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return the outputs of the `Model`.
"""
if self.predict_function is not None and not force:
return self.predict_function
def step_function(model, iterator):
"""Runs a single evaluation step."""
def run_step(data):
outputs = model.predict_step(data)
# Ensure counter is updated only if `test_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._predict_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs, self.distribute_strategy, reduction="concat"
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def predict_function(iterator):
"""Runs an evaluation execution with a single step."""
return step_function(self, iterator)
else:
def predict_function(iterator):
"""Runs an evaluation execution with multiple steps."""
outputs = step_function(self, iterator)
for _ in tf.range(self._steps_per_execution - 1):
tf.autograph.experimental.set_loop_options(
shape_invariants=[
(
outputs,
tf.nest.map_structure(
lambda t: tf_utils.get_tensor_spec(
t, dynamic_batch=True
).shape,
outputs,
),
)
]
)
step_outputs = step_function(self, iterator)
outputs = tf.nest.map_structure(
lambda t1, t2: concat([t1, t2]), outputs, step_outputs
)
return outputs
if not self.run_eagerly:
predict_function = tf.function(
predict_function, reduce_retracing=True
)
self.predict_function = predict_function
return self.predict_function
@traceback_utils.filter_traceback
def predict(
self,
x,
batch_size=None,
verbose="auto",
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
):
"""Generates output predictions for the input samples.
Computation is done in batches. This method is designed for batch
processing of large numbers of inputs. It is not intended for use inside
of loops that iterate over your data and process small numbers of inputs
at a time.
For small numbers of inputs that fit in one batch,
directly use `__call__()` for faster execution, e.g.,
`model(x)`, or `model(x, training=False)` if you have layers such as
`tf.keras.layers.BatchNormalization` that behave differently during
inference. You may pair the individual model call with a `tf.function`
for additional performance inside your inner loop.
If you need access to numpy array values instead of tensors after your
model call, you can use `tensor.numpy()` to get the numpy array value of
an eager tensor.
Also, note the fact that test loss is not affected by
regularization layers like noise and dropout.
Note: See [this FAQ entry](
https://keras.io/getting_started/faq/#whats-the-difference-between-model-methods-predict-and-call)
for more details about the difference between `Model` methods
`predict()` and `__call__()`.
Args:
x: Input samples. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A `tf.data` dataset.
- A generator or `keras.utils.Sequence` instance.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given in the `Unpacking
behavior for iterator-like inputs` section of `Model.fit`.
batch_size: Integer or `None`.
Number of samples per batch.
If unspecified, `batch_size` will default to 32.
Do not specify the `batch_size` if your data is in the
form of dataset, generators, or `keras.utils.Sequence` instances
(since they generate batches).
verbose: `"auto"`, 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = single line.
`"auto"` becomes 1 for most cases, and to 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so `verbose=2` is
recommended when not running interactively (e.g. in a production
environment). Defaults to 'auto'.
steps: Total number of steps (batches of samples)
before declaring the prediction round finished.
Ignored with the default value of `None`. If x is a `tf.data`
dataset and `steps` is None, `predict()` will
run until the input dataset is exhausted.
callbacks: List of `keras.callbacks.Callback` instances.
List of callbacks to apply during prediction.
See [callbacks](
https://www.tensorflow.org/api_docs/python/tf/tf_keras/callbacks).
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the
generator queue. If unspecified, `max_queue_size` will default
to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, `workers` will default
to 1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
See the discussion of `Unpacking behavior for iterator-like inputs` for
`Model.fit`. Note that Model.predict uses the same interpretation rules
as `Model.fit` and `Model.evaluate`, so inputs must be unambiguous for
all three methods.
Returns:
Numpy array(s) of predictions.
Raises:
RuntimeError: If `model.predict` is wrapped in a `tf.function`.
ValueError: In case of mismatch between the provided
input data and the model's expectations,
or in case a stateful model receives a number of samples
that is not a multiple of the batch size.
"""
version_utils.disallow_legacy_graph("Model", "predict")
self._check_call_args("predict")
_disallow_inside_tf_function("predict")
# TODO(yashkatariya): Cache model on the coordinator for faster
# prediction. If running under PSS, then swap it with OneDeviceStrategy
# so that execution will run on the coordinator.
original_pss_strategy = None
if self.distribute_strategy._should_use_with_coordinator:
original_pss_strategy = self.distribute_strategy
self._distribution_strategy = None
# Cluster coordinator is set by `.fit()` and `.evaluate()` which is not
# needed in `.predict()` because all the predictions happen on the
# coordinator/locally.
if self._cluster_coordinator:
self._cluster_coordinator = None
verbose = _get_verbosity(verbose, self.distribute_strategy)
outputs = None
with self.distribute_strategy.scope():
# Creates a `tf.data.Dataset` and handles batch and epoch iteration.
dataset_types = (tf.compat.v1.data.Dataset, tf.data.Dataset)
if (
self._in_multi_worker_mode()
or _is_tpu_multi_host(self.distribute_strategy)
) and isinstance(x, dataset_types):
try:
options = tf.data.Options()
data_option = tf.data.experimental.AutoShardPolicy.DATA
options.experimental_distribute.auto_shard_policy = (
data_option
)
x = x.with_options(options)
except ValueError:
warnings.warn(
"Using Model.predict with MultiWorkerMirroredStrategy "
"or TPUStrategy and AutoShardPolicy.FILE might lead to "
"out-of-order result. Consider setting it to "
"AutoShardPolicy.DATA.",
stacklevel=2,
)
data_handler = data_adapter.get_data_handler(
x=x,
batch_size=batch_size,
steps_per_epoch=steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=1,
steps=data_handler.inferred_steps,
)
self.predict_function = self.make_predict_function()
self._predict_counter.assign(0)
callbacks.on_predict_begin()
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
batch_outputs = None
for _, iterator in data_handler.enumerate_epochs(): # Single epoch.
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
callbacks.on_predict_batch_begin(step)
tmp_batch_outputs = self.predict_function(iterator)
if data_handler.should_sync:
context.async_wait()
batch_outputs = (
tmp_batch_outputs # No error, now safe to assign.
)
if outputs is None:
outputs = tf.nest.map_structure(
lambda batch_output: [batch_output],
batch_outputs,
)
else:
tf.__internal__.nest.map_structure_up_to(
batch_outputs,
lambda output, batch_output: output.append(
batch_output
),
outputs,
batch_outputs,
)
end_step = step + data_handler.step_increment
callbacks.on_predict_batch_end(
end_step, {"outputs": batch_outputs}
)
if batch_outputs is None:
raise ValueError(
"Unexpected result of `predict_function` "
"(Empty batch_outputs). Please use "
"`Model.compile(..., run_eagerly=True)`, or "
"`tf.config.run_functions_eagerly(True)` for more "
"information of where went wrong, or file a "
"issue/bug to `tf.keras`."
)
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_predict_end()
all_outputs = tf.__internal__.nest.map_structure_up_to(
batch_outputs, potentially_ragged_concat, outputs
)
# If originally PSS strategy was used, then replace it back since
# predict is running under `OneDeviceStrategy` after the swap and once
# its done we need to replace it back to PSS again.
if original_pss_strategy is not None:
self._distribution_strategy = original_pss_strategy
return tf_utils.sync_to_numpy_or_python_type(all_outputs)
def reset_metrics(self):
"""Resets the state of all the metrics in the model.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> _ = model.fit(x, y, verbose=0)
>>> assert all(float(m.result()) for m in model.metrics)
>>> model.reset_metrics()
>>> assert all(float(m.result()) == 0 for m in model.metrics)
"""
for m in self.metrics:
m.reset_state()
def train_on_batch(
self,
x,
y=None,
sample_weight=None,
class_weight=None,
reset_metrics=True,
return_dict=False,
):
"""Runs a single gradient update on a single batch of data.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s).
sample_weight: Optional array of the same length as x, containing
weights to apply to the model's loss for each sample. In the case
of temporal data, you can pass a 2D array with shape (samples,
sequence_length), to apply a different weight to every timestep of
every sample.
class_weight: Optional dictionary mapping class indices (integers)
to a weight (float) to apply to the model's loss for the samples
from this class during training. This can be useful to tell the
model to "pay more attention" to samples from an under-represented
class. When `class_weight` is specified and targets have a rank of
2 or greater, either `y` must be one-hot encoded, or an explicit
final dimension of `1` must be included for sparse class labels.
reset_metrics: If `True`, the metrics returned will be only for this
batch. If `False`, the metrics will be statefully accumulated
across batches.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
Returns:
Scalar training 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 scalar outputs.
Raises:
RuntimeError: If `model.train_on_batch` is wrapped in a `tf.function`.
"""
self._assert_compile_was_called()
self._check_call_args("train_on_batch")
_disallow_inside_tf_function("train_on_batch")
if reset_metrics:
self.reset_metrics()
with self.distribute_strategy.scope(), training_utils.RespectCompiledTrainableState( # noqa: E501
self
):
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x, y, sample_weight, class_weight
)
self.train_function = self.make_train_function()
logs = self.train_function(iterator)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def test_on_batch(
self,
x,
y=None,
sample_weight=None,
reset_metrics=True,
return_dict=False,
):
"""Test the model on a single batch of samples.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays (in case the
model has multiple inputs).
- A TensorFlow tensor, or a list of tensors (in case the model has
multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s). It should be consistent with `x`
(you cannot have Numpy inputs and tensor targets, or inversely).
sample_weight: Optional array of the same length as x, containing
weights to apply to the model's loss for each sample. In the case
of temporal data, you can pass a 2D array with shape (samples,
sequence_length), to apply a different weight to every timestep of
every sample.
reset_metrics: If `True`, the metrics returned will be only for this
batch. If `False`, the metrics will be statefully accumulated
across batches.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
Returns:
Scalar test 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 scalar outputs.
Raises:
RuntimeError: If `model.test_on_batch` is wrapped in a
`tf.function`.
"""
self._assert_compile_was_called()
self._check_call_args("test_on_batch")
_disallow_inside_tf_function("test_on_batch")
if reset_metrics:
self.reset_metrics()
with self.distribute_strategy.scope():
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x, y, sample_weight
)
self.test_function = self.make_test_function()
logs = self.test_function(iterator)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def predict_on_batch(self, x):
"""Returns predictions for a single batch of samples.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays (in case the
model has multiple inputs).
- A TensorFlow tensor, or a list of tensors (in case the model has
multiple inputs).
Returns:
Numpy array(s) of predictions.
Raises:
RuntimeError: If `model.predict_on_batch` is wrapped in a
`tf.function`.
"""
self._check_call_args("predict_on_batch")
_disallow_inside_tf_function("predict_on_batch")
with self.distribute_strategy.scope():
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x
)
self.predict_function = self.make_predict_function()
outputs = self.predict_function(iterator)
return tf_utils.sync_to_numpy_or_python_type(outputs)
@doc_controls.do_not_generate_docs
def fit_generator(
self,
generator,
steps_per_epoch=None,
epochs=1,
verbose=1,
callbacks=None,
validation_data=None,
validation_steps=None,
validation_freq=1,
class_weight=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
shuffle=True,
initial_epoch=0,
):
"""Fits the model on data yielded batch-by-batch by a Python generator.
DEPRECATED:
`Model.fit` now supports generators, so there is no longer any need to
use this endpoint.
"""
warnings.warn(
"`Model.fit_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.fit`, which supports generators.",
stacklevel=2,
)
return self.fit(
generator,
steps_per_epoch=steps_per_epoch,
epochs=epochs,
verbose=verbose,
callbacks=callbacks,
validation_data=validation_data,
validation_steps=validation_steps,
validation_freq=validation_freq,
class_weight=class_weight,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
shuffle=shuffle,
initial_epoch=initial_epoch,
)
@doc_controls.do_not_generate_docs
def evaluate_generator(
self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0,
):
"""Evaluates the model on a data generator.
DEPRECATED:
`Model.evaluate` now supports generators, so there is no longer any
need to use this endpoint.
"""
warnings.warn(
"`Model.evaluate_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.evaluate`, which supports generators.",
stacklevel=2,
)
self._check_call_args("evaluate_generator")
return self.evaluate(
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks,
)
@doc_controls.do_not_generate_docs
def predict_generator(
self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0,
):
"""Generates predictions for the input samples from a data generator.
DEPRECATED:
`Model.predict` now supports generators, so there is no longer any
need to use this endpoint.
"""
warnings.warn(
"`Model.predict_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.predict`, which supports generators.",
stacklevel=2,
)
return self.predict(
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks,
)
######################################################################
# Functions below are not training related. They are for model weights
# tracking, save/load, serialization, etc.
######################################################################
@property
def trainable_weights(self):
self._assert_weights_created()
if not self._trainable:
return []
trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
trainable_variables += trackable_obj.trainable_variables
trainable_variables += self._trainable_weights
return self._dedup_weights(trainable_variables)
@property
def non_trainable_weights(self):
self._assert_weights_created()
non_trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
non_trainable_variables += trackable_obj.non_trainable_variables
if not self._trainable:
# Return order is all trainable vars, then all non-trainable vars.
trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
trainable_variables += trackable_obj.trainable_variables
non_trainable_variables = (
trainable_variables
+ self._trainable_weights
+ non_trainable_variables
+ self._non_trainable_weights
)
else:
non_trainable_variables = (
non_trainable_variables + self._non_trainable_weights
)
return self._dedup_weights(non_trainable_variables)
def get_weights(self):
"""Retrieves the weights of the model.
Returns:
A flat list of Numpy arrays.
"""
with self.distribute_strategy.scope():
return super().get_weights()
@traceback_utils.filter_traceback
def save(self, 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.models.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.models.save_model()`.
"""
saving_api.save_model(
self,
filepath=filepath,
overwrite=overwrite,
save_format=save_format,
**kwargs,
)
@traceback_utils.filter_traceback
def save_weights(
self, filepath, overwrite=True, save_format=None, options=None
):
"""Saves all layer weights.
Either saves in HDF5 or in TensorFlow format based on the `save_format`
argument.
When saving in HDF5 format, the weight file has:
- `layer_names` (attribute), a list of strings
(ordered names of model layers).
- For every layer, a `group` named `layer.name`
- For every such layer group, a group attribute `weight_names`,
a list of strings
(ordered names of weights tensor of the layer).
- For every weight in the layer, a dataset
storing the weight value, named after the weight tensor.
When saving in TensorFlow format, all objects referenced by the network
are saved in the same format as `tf.train.Checkpoint`, including any
`Layer` instances or `Optimizer` instances assigned to object
attributes. For networks constructed from inputs and outputs using
`tf.keras.Model(inputs, outputs)`, `Layer` instances used by the network
are tracked/saved automatically. For user-defined classes which inherit
from `tf.keras.Model`, `Layer` instances must be assigned to object
attributes, typically in the constructor. See the documentation of
`tf.train.Checkpoint` and `tf.keras.Model` for details.
While the formats are the same, do not mix `save_weights` and
`tf.train.Checkpoint`. Checkpoints saved by `Model.save_weights` should
be loaded using `Model.load_weights`. Checkpoints saved using
`tf.train.Checkpoint.save` should be restored using the corresponding
`tf.train.Checkpoint.restore`. Prefer `tf.train.Checkpoint` over
`save_weights` for training checkpoints.
The TensorFlow format matches objects and variables by starting at a
root object, `self` for `save_weights`, and greedily matching attribute
names. For `Model.save` this is the `Model`, and for `Checkpoint.save`
this is the `Checkpoint` even if the `Checkpoint` has a model attached.
This means saving a `tf.keras.Model` using `save_weights` and loading
into a `tf.train.Checkpoint` with a `Model` attached (or vice versa)
will not match the `Model`'s variables. See the
[guide to training checkpoints](
https://www.tensorflow.org/guide/checkpoint) for details on
the TensorFlow format.
Args:
filepath: String or PathLike, path to the file to save the weights
to. When saving in TensorFlow format, this is the prefix used
for checkpoint files (multiple files are generated). Note that
the '.h5' suffix causes weights to be saved in HDF5 format.
overwrite: Whether to silently overwrite any existing file at the
target location, or provide the user with a manual prompt.
save_format: Either 'tf' or 'h5'. A `filepath` ending in '.h5' or
'.keras' will default to HDF5 if `save_format` is `None`.
Otherwise, `None` becomes 'tf'. Defaults to `None`.
options: Optional `tf.train.CheckpointOptions` object that specifies
options for saving weights.
Raises:
ImportError: If `h5py` is not available when attempting to save in
HDF5 format.
"""
saving_api.save_weights(
self,
filepath=filepath,
overwrite=overwrite,
save_format=save_format,
options=options,
)
@traceback_utils.filter_traceback
def load_weights(
self, filepath, skip_mismatch=False, by_name=False, options=None
):
"""Loads all layer weights from a saved files.
The saved file could be a SavedModel file, a `.keras` file (v3 saving
format), or a file created via `model.save_weights()`.
By default, weights are loaded based on the network's
topology. This means the architecture should be the same as when the
weights were saved. Note that layers that don't have weights are not
taken into account in the topological ordering, so adding or removing
layers is fine as long as they don't have weights.
**Partial weight loading**
If you have modified your model, for instance by adding a new layer
(with weights) or by changing the shape of the weights of a layer,
you can choose to ignore errors and continue loading
by setting `skip_mismatch=True`. In this case any layer with
mismatching weights will be skipped. A warning will be displayed
for each skipped layer.
**Weight loading by name**
If your weights are saved as a `.h5` file created
via `model.save_weights()`, you can use the argument `by_name=True`.
In this case, weights are loaded into layers only if they share
the same name. This is useful for fine-tuning or transfer-learning
models where some of the layers have changed.
Note that only topological loading (`by_name=False`) is supported when
loading weights from the `.keras` v3 format or from the TensorFlow
SavedModel format.
Args:
filepath: String, path to the weights file to load. For weight files
in TensorFlow format, this is the file prefix (the same as was
passed to `save_weights()`). This can also be a path to a
SavedModel or a `.keras` file (v3 saving format) saved
via `model.save()`.
skip_mismatch: Boolean, whether to skip loading of layers where
there is a mismatch in the number of weights, or a mismatch in
the shape of the weights.
by_name: Boolean, whether to load weights by name or by topological
order. Only topological loading is supported for weight files in
the `.keras` v3 format or in the TensorFlow SavedModel format.
options: Optional `tf.train.CheckpointOptions` object that specifies
options for loading weights (only valid for a SavedModel file).
"""
return saving_api.load_weights(
self,
filepath=filepath,
by_name=by_name,
skip_mismatch=skip_mismatch,
options=options,
)
def _updated_config(self):
"""Util shared between different serialization methods.
Returns:
Model config with TF-Keras version information added.
"""
from tf_keras.src import __version__ as keras_version
config = self.get_config()
model_config = {
"class_name": self.__class__.__name__,
"config": config,
"keras_version": keras_version,
"backend": backend.backend(),
}
return model_config
@generic_utils.default
def get_config(self):
"""Returns the config of the `Model`.
Config is a Python dictionary (serializable) containing the
configuration of an object, which in this case is a `Model`. This allows
the `Model` to be be reinstantiated later (without its trained weights)
from this configuration.
Note that `get_config()` does not guarantee to return a fresh copy of
dict every time it is called. The callers should make a copy of the
returned dict if they want to modify it.
Developers of subclassed `Model` are advised to override this method,
and continue to update the dict from `super(MyModel, self).get_config()`
to provide the proper configuration of this `Model`. The default config
will return config dict for init parameters if they are basic types.
Raises `NotImplementedError` when in cases where a custom
`get_config()` implementation is required for the subclassed model.
Returns:
Python dictionary containing the configuration of this `Model`.
"""
# If sublcass doesn't implement `get_config()` parse from init args
# otherwise default to empty dict
if generic_utils.is_default(self.get_config):
try:
config = base_layer.Layer.get_config(self)
except NotImplementedError:
config = {}
logging.warning(
"Model's `__init__()` arguments contain non-serializable "
"objects. Please implement a `get_config()` method in the "
"subclassed Model for proper saving and loading. "
"Defaulting to empty config."
)
else:
config = {}
return config
@classmethod
def from_config(cls, config, custom_objects=None):
# `from_config` assumes `cls` is either `Functional` or a child class of
# `Functional`. In the case that `cls` is meant to behave like a child
# class of `Functional` but only inherits from the `Model` class, we
# have to call `cls(...)` instead of `Functional.from_config`.
from tf_keras.src.engine import functional
with serialization.SharedObjectLoadingScope():
functional_config_keys = [
"name",
"layers",
"input_layers",
"output_layers",
]
is_functional_config = all(
key in config for key in functional_config_keys
)
argspec = tf_inspect.getfullargspec(cls.__init__)
functional_init_args = tf_inspect.getfullargspec(
functional.Functional.__init__
).args[1:]
revivable_as_functional = (
cls in {functional.Functional, Model}
or argspec.args[1:] == functional_init_args
or (argspec.varargs == "args" and argspec.varkw == "kwargs")
)
if is_functional_config and revivable_as_functional:
# Revive Functional model
# (but not Functional subclasses with a custom __init__)
inputs, outputs, layers = functional.reconstruct_from_config(
config, custom_objects
)
model = cls(
inputs=inputs, outputs=outputs, name=config.get("name")
)
functional.connect_ancillary_layers(model, layers)
else:
# Either the model has a custom __init__, or the config
# does not contain all the information necessary to
# revive a Functional model. This happens when the user creates
# subclassed models where `get_config()` is returning
# insufficient information to be considered a Functional model.
# In this case, we fall back to provide all config into the
# constructor of the class.
try:
model = cls(**config)
except TypeError as e:
raise TypeError(
"Unable to revive model from config. When overriding "
"the `get_config()` method, make sure that the "
"returned config contains all items used as arguments "
f"in the constructor to {cls}, "
"which is the default behavior. "
"You can override this default behavior by defining a "
"`from_config(cls, config)` class method to specify "
"how to create an "
f"instance of {cls.__name__} from its config.\n\n"
f"Received config={config}\n\n"
f"Error encountered during deserialization: {e}"
)
return model
def to_json(self, **kwargs):
"""Returns a JSON string containing the network configuration.
To load a network from a JSON save file, use
`keras.models.model_from_json(json_string, custom_objects={})`.
Args:
**kwargs: Additional keyword arguments to be passed to
*`json.dumps()`.
Returns:
A JSON string.
"""
model_config = self._updated_config()
return json.dumps(
model_config, default=json_utils.get_json_type, **kwargs
)
def to_yaml(self, **kwargs):
"""Returns a yaml string containing the network configuration.
Note: Since TF 2.6, this method is no longer supported and will raise a
RuntimeError.
To load a network from a yaml save file, use
`keras.models.model_from_yaml(yaml_string, custom_objects={})`.
`custom_objects` should be a dictionary mapping
the names of custom losses / layers / etc to the corresponding
functions / classes.
Args:
**kwargs: Additional keyword arguments
to be passed to `yaml.dump()`.
Returns:
A YAML string.
Raises:
RuntimeError: announces that the method poses a security risk
"""
raise RuntimeError(
"Method `model.to_yaml()` has been removed due to security risk of "
"arbitrary code execution. Please use `model.to_json()` instead."
)
def reset_states(self):
for layer in self.layers:
if hasattr(layer, "reset_states") and getattr(
layer, "stateful", False
):
layer.reset_states()
@property
@doc_controls.do_not_generate_docs
def state_updates(self):
"""Deprecated, do NOT use!
Returns the `updates` from all layers that are stateful.
This is useful for separating training updates and
state updates, e.g. when we need to update a layer's internal state
during prediction.
Returns:
A list of update ops.
"""
warnings.warn(
"`Model.state_updates` will be removed in a future version. "
"This property should not be used in TensorFlow 2.0, "
"as `updates` are applied automatically.",
stacklevel=2,
)
state_updates = []
for layer in self.layers:
if getattr(layer, "stateful", False):
if hasattr(layer, "updates"):
state_updates += layer.updates
return state_updates
@property
def weights(self):
"""Returns the list of all layer variables/weights.
Note: This will not track the weights of nested `tf.Modules` that are
not themselves TF-Keras layers.
Returns:
A list of variables.
"""
return self._dedup_weights(self._undeduplicated_weights)
@property
def _undeduplicated_weights(self):
"""Returns the undeduplicated list of all layer variables/weights."""
self._assert_weights_created()
weights = []
for layer in self._self_tracked_trackables:
weights += layer.variables
weights += self._trainable_weights + self._non_trainable_weights
return weights
def summary(
self,
line_length=None,
positions=None,
print_fn=None,
expand_nested=False,
show_trainable=False,
layer_range=None,
):
"""Prints a string summary of the network.
Args:
line_length: Total length of printed lines
(e.g. set this to adapt the display to different
terminal window sizes).
positions: Relative or absolute positions of log elements
in each line. If not provided, becomes
`[0.3, 0.6, 0.70, 1.]`. Defaults to `None`.
print_fn: Print function to use. By default, prints to `stdout`.
If `stdout` doesn't work in your environment, change to `print`.
It will be called on each line of the summary.
You can set it to a custom function
in order to capture the string summary.
expand_nested: Whether to expand the nested models.
Defaults to `False`.
show_trainable: Whether to show if a layer is trainable.
Defaults to `False`.
layer_range: a list or tuple of 2 strings,
which is the starting layer name and ending layer name
(both inclusive) indicating the range of layers to be printed
in summary. It also accepts regex patterns instead of exact
name. In such case, start predicate will be the first element
it matches to `layer_range[0]` and the end predicate will be
the last element it matches to `layer_range[1]`.
By default `None` which considers all layers of model.
Raises:
ValueError: if `summary()` is called before the model is built.
"""
if not self.built:
raise ValueError(
"This model has not yet been built. "
"Build the model first by calling `build()` or by calling "
"the model on a batch of data."
)
layer_utils.print_summary(
self,
line_length=line_length,
positions=positions,
print_fn=print_fn,
expand_nested=expand_nested,
show_trainable=show_trainable,
layer_range=layer_range,
)
@property
def layers(self):
return list(self._flatten_layers(include_self=False, recursive=False))
@layers.setter
def layers(self, _):
raise AttributeError(
"`Model.layers` attribute is reserved and should not be used. "
"Please use another name."
)
def get_layer(self, name=None, index=None):
"""Retrieves a layer based on either its name (unique) or index.
If `name` and `index` are both provided, `index` will take precedence.
Indices are based on order of horizontal graph traversal (bottom-up).
Args:
name: String, name of layer.
index: Integer, index of layer.
Returns:
A layer instance.
"""
# TODO(fchollet): We could build a dictionary based on layer names
# since they are constant, but we have not done that yet.
if index is not None and name is not None:
raise ValueError(
"Provide only a layer name or a layer index. Received: "
f"index={index}, name={name}."
)
if index is not None:
if len(self.layers) <= index:
raise ValueError(
f"Was asked to retrieve layer at index {index}"
f" but model only has {len(self.layers)}"
" layers."
)
else:
return self.layers[index]
if name is not None:
for layer in self.layers:
if layer.name == name:
return layer
raise ValueError(
f"No such layer: {name}. Existing layers are: "
f"{list(layer.name for layer in self.layers)}."
)
raise ValueError(
"Provide either a layer name or layer index at `get_layer`."
)
def get_weight_paths(self):
"""Retrieve all the variables and their paths for the model.
The variable path (string) is a stable key to identify a `tf.Variable`
instance owned by the model. It can be used to specify variable-specific
configurations (e.g. DTensor, quantization) from a global view.
This method returns a dict with weight object paths as keys
and the corresponding `tf.Variable` instances as values.
Note that if the model is a subclassed model and the weights haven't
been initialized, an empty dict will be returned.
Returns:
A dict where keys are variable paths and values are `tf.Variable`
instances.
Example:
```python
class SubclassModel(tf.keras.Model):
def __init__(self, name=None):
super().__init__(name=name)
self.d1 = tf.keras.layers.Dense(10)
self.d2 = tf.keras.layers.Dense(20)
def call(self, inputs):
x = self.d1(inputs)
return self.d2(x)
model = SubclassModel()
model(tf.zeros((10, 10)))
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': model.d1.kernel,
# 'd1.bias': model.d1.bias,
# 'd2.kernel': model.d2.kernel,
# 'd2.bias': model.d2.bias,
# }
# Functional model
inputs = tf.keras.Input((10,), batch_size=10)
x = tf.keras.layers.Dense(20, name='d1')(inputs)
output = tf.keras.layers.Dense(30, name='d2')(x)
model = tf.keras.Model(inputs, output)
d1 = model.layers[1]
d2 = model.layers[2]
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': d1.kernel,
# 'd1.bias': d1.bias,
# 'd2.kernel': d2.kernel,
# 'd2.bias': d2.bias,
# }
```
"""
result = {}
(
descendants,
object_paths_dict,
) = tf.__internal__.tracking.ObjectGraphView(
self
).breadth_first_traversal()
for descendant in descendants:
if isinstance(descendant, tf.Variable):
trackable_references = object_paths_dict[descendant]
object_path = ".".join([t.name for t in trackable_references])
result[object_path] = descendant
return result
def get_compile_config(self):
"""Returns a serialized config with information for compiling the model.
This method returns a config dictionary containing all the information
(optimizer, loss, metrics, etc.) with which the model was compiled.
Returns:
A dict containing information for compiling the model.
"""
if self._is_compiled and hasattr(self, "_compile_config"):
return self._compile_config.serialize()
def compile_from_config(self, config):
"""Compiles the model with the information given in config.
This method uses the information in the config (optimizer, loss,
metrics, etc.) to compile the model.
Args:
config: Dict containing information for compiling the model.
"""
has_overridden_compile = self.__class__.compile != Model.compile
if has_overridden_compile:
logging.warning(
"`compile()` was not called as part of model loading "
"because the model's `compile()` method is custom. "
"All subclassed Models that have `compile()` "
"overridden should also override "
"`get_compile_config()` and `compile_from_config(config)`. "
"Alternatively, you can "
"call `compile()` manually after loading."
)
return
config = saving_lib.deserialize_keras_object(config)
self.compile(**config)
if (
hasattr(self, "optimizer")
# Exempt legacy optimizers.
and isinstance(self.optimizer, optimizer.Optimizer)
and self.built
):
# Create optimizer variables.
self.optimizer.build(self.trainable_variables)
def export(self, filepath):
"""Create a SavedModel artifact for inference (e.g. via TF-Serving).
This method lets you export a model to a lightweight SavedModel artifact
that contains the model's forward pass only (its `call()` method)
and can be served via e.g. TF-Serving. The forward pass is registered
under the name `serve()` (see example below).
The original code of the model (including any custom layers you may
have used) is *no longer* necessary to reload the artifact -- it is
entirely standalone.
Args:
filepath: `str` or `pathlib.Path` object. Path where to save
the artifact.
Example:
```python
# Create the artifact
model.export("path/to/location")
# Later, in a different process / environment...
reloaded_artifact = tf.saved_model.load("path/to/location")
predictions = reloaded_artifact.serve(input_data)
```
If you would like to customize your serving endpoints, you can
use the lower-level `keras.export.ExportArchive` class. The `export()`
method relies on `ExportArchive` internally.
"""
from tf_keras.src.export import export_lib
export_lib.export_model(self, filepath)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _set_save_spec(self, inputs, args=None, kwargs=None):
"""Defines the save spec so that serialization can trace `call()`.
The TensorSpecs of the call function `inputs`, `args`, and `kwargs` are
saved into a tuple of `([inputs] + args, kwargs)`. The input
`TensorSpec` names are updated to match the built `input_names`.
The specs can be retrieved with the `save_spec` property.
Args:
inputs: possibly nested inputs passed into the call function.
args: a list of positional arguments passed into call.
kwargs: a dictionary of keyword arguments passed into call.
"""
if self._saved_model_inputs_spec is not None:
return # Already set.
args = args or []
kwargs = kwargs or {}
input_names = self.input_names
if not input_names:
input_names = compile_utils.create_pseudo_input_names(inputs)
flat_inputs = tf.nest.flatten(inputs)
inputs_spec = []
for name, tensor in zip(input_names, flat_inputs):
inputs_spec.append(
tf_utils.get_tensor_spec(tensor, dynamic_batch=False, name=name)
)
inputs_spec = tf.nest.pack_sequence_as(inputs, inputs_spec)
super()._set_save_spec(inputs_spec, args, kwargs)
# Store the input shapes
if (
self.__class__.__name__ == "Sequential"
and self._build_input_shape is None
):
self._build_input_shape = tf.nest.map_structure(
lambda x: None if x is None else x.shape, inputs_spec
)
def save_spec(self, dynamic_batch=True):
"""Returns the `tf.TensorSpec` of call args as a tuple `(args, kwargs)`.
This value is automatically defined after calling the model for the
first time. Afterwards, you can use it when exporting the model for
serving:
```python
model = tf.keras.Model(...)
@tf.function
def serve(*args, **kwargs):
outputs = model(*args, **kwargs)
# Apply postprocessing steps, or add additional outputs.
...
return outputs
# arg_specs is `[tf.TensorSpec(...), ...]`. kwarg_specs, in this
# example, is an empty dict since functional models do not use keyword
# arguments.
arg_specs, kwarg_specs = model.save_spec()
model.save(path, signatures={
'serving_default': serve.get_concrete_function(*arg_specs,
**kwarg_specs)
})
```
Args:
dynamic_batch: Whether to set the batch sizes of all the returned
`tf.TensorSpec` to `None`. (Note that when defining functional or
Sequential models with `tf.keras.Input([...], batch_size=X)`, the
batch size will always be preserved). Defaults to `True`.
Returns:
If the model inputs are defined, returns a tuple `(args, kwargs)`. All
elements in `args` and `kwargs` are `tf.TensorSpec`.
If the model inputs are not defined, returns `None`.
The model inputs are automatically set when calling the model,
`model.fit`, `model.evaluate` or `model.predict`.
"""
return self._get_save_spec(dynamic_batch, inputs_only=False)
def _assert_weights_created(self):
"""Asserts that all the weights for the model have been created.
For a non-dynamic model, the weights must already be created after the
layer has been called. For a dynamic model, the exact list of weights
can never be known for certain since it may change at any time during
execution.
We run this check right before accessing weights or getting the Numpy
value for the current weights. Otherwise, if the layer has never been
called, the user would just get an empty list, which is misleading.
Raises:
ValueError: if the weights of the network have not yet been created.
"""
if self.dynamic:
return
if (
"build" in self.__class__.__dict__
and self.__class__ != Model
and not self.built
):
# For any model that has customized build() method but hasn't been
# invoked yet, this will cover both sequential and subclass model.
# Also make sure to exclude Model class itself which has build()
# defined.
raise ValueError(
f"Weights for model '{self.name}' have not yet been "
"created. "
"Weights are created when the model is first called on "
"inputs or `build()` is called with an `input_shape`."
)
def _check_call_args(self, method_name):
"""Check that `call()` has only one positional arg."""
# Always allow first arg, regardless of arg name.
fullargspec = self._call_spec.full_argspec
if fullargspec.defaults:
positional_args = fullargspec.args[: -len(fullargspec.defaults)]
else:
positional_args = fullargspec.args
if "training" in positional_args:
positional_args.remove("training")
# self and first arg can be positional.
if len(positional_args) > 2:
extra_args = positional_args[2:]
raise ValueError(
f"Models passed to `{method_name}` can only have `training` "
"and the first argument in `call()` as positional arguments, "
f"found: {extra_args}."
)
def _validate_compile(self, optimizer, metrics, **kwargs):
"""Performs validation checks for the default `compile()`."""
if any(
isinstance(opt, optimizer_v1.Optimizer)
for opt in tf.nest.flatten(optimizer)
):
raise ValueError(
f"`tf.compat.v1.keras` Optimizer ({optimizer}) is "
"not supported when eager execution is enabled. Use a "
"`tf.keras` Optimizer instead, or disable eager "
"execution."
)
kwargs.pop("cloning", None) # Legacy DistStrat argument, never used.
kwargs.pop("experimental_run_tf_function", None) # Always `True`.
distribute_arg = kwargs.pop("distribute", None)
if distribute_arg is not None:
raise ValueError(
"`distribute` argument in compile is not available in TF 2.0. "
"Please create the model under the `strategy.scope()`. "
f"Received: {distribute_arg}."
)
target_tensor_arg = kwargs.pop("target_tensors", None)
if target_tensor_arg is not None:
raise ValueError(
"`target_tensors` argument is not supported when executing "
f"eagerly. Received: {target_tensor_arg}."
)
invalid_kwargs = set(kwargs) - {"sample_weight_mode"}
if invalid_kwargs:
raise TypeError(
"Invalid keyword argument(s) in `compile()`: "
f"{(invalid_kwargs,)}. Valid keyword arguments include "
'"cloning", "experimental_run_tf_function", "distribute",'
' "target_tensors", or "sample_weight_mode".'
)
# Model must be created and compiled with the same DistStrat.
if self.built and tf.distribute.has_strategy():
strategy = tf.distribute.get_strategy()
for v in self.variables:
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Variable ({v}) was not created in the distribution "
f"strategy scope of ({strategy}). It is most likely "
"because some layers, model, or optimizer was being "
"created outside the distribution strategy scope. Try "
"to make sure your code looks similar "
"to the following.\nwith strategy.scope():\n"
" model=_create_model()\n"
" model.compile(...)"
)
# Model metrics must be created in the same distribution strategy scope
# as the model.
strategy = self.distribute_strategy
for metric in tf.nest.flatten(metrics):
for v in getattr(metric, "variables", []):
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Metric ({metric}) passed to `model.compile` was "
"created inside a different distribution strategy "
"scope than the model. All metrics must be created "
"in the same distribution strategy "
f"scope as the model (in this case {strategy}). "
"If you pass in a string identifier for a metric to "
"compile, the metric will automatically be created "
"in the correct distribution strategy scope."
)
# Model metrics must be created in the same distribution strategy scope
# as the model.
for opt in tf.nest.flatten(optimizer):
for v in getattr(opt, "_weights", []):
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Optimizer ({optimizer}) passed to `model.compile` "
"was created inside a different distribution strategy "
"scope than the model. All optimizers must be created "
"in the same distribution strategy scope as the model "
f"(in this case {strategy}). If you pass in a string "
"identifier for an optimizer to compile, the optimizer "
"will automatically be created in the correct "
"distribution strategy scope."
)
def _maybe_load_initial_counters_from_ckpt(
self, steps_per_epoch, initial_epoch
):
"""Maybe load initial epoch from ckpt, considering worker recovery.
Refer to tensorflow/python/tf_keras/distribute/worker_training_state.py
for more information.
Args:
steps_per_epoch: The number of step per epoch.
initial_epoch: The original initial_epoch user passes in `fit()`.
mode: The mode for running `model.fit()`.
Returns:
If the training is recovering from previous failure under multi-worker
training setting, return the (epoch, step) the training is supposed to
continue at. Otherwise, return the `initial_epoch, initial_step` the
user passes in.
"""
initial_step = 0
if self._training_state is not None:
return self._training_state.maybe_load_initial_counters_from_ckpt(
steps_per_epoch, initial_epoch, mode=ModeKeys.TRAIN
)
return (initial_epoch, initial_step)
def _assert_compile_was_called(self):
# Checks whether `compile` has been called. If it has been called,
# then the optimizer is set. This is different from whether the
# model is compiled
# (i.e. whether the model is built and its inputs/outputs are set).
if not self._is_compiled:
raise RuntimeError(
"You must compile your model before "
"training/testing. "
"Use `model.compile(optimizer, loss)`."
)
def _check_sample_weight_warning(self, x, sample_weight):
# Datasets can include sample weight, by returning a tuple with the
# structure of `(x, y, sample_weight)`.
sample_weight_present = sample_weight is not None or (
isinstance(x, tf.data.Dataset)
and isinstance(x.element_spec, tuple)
and len(x.element_spec) == 3
)
if (
sample_weight_present
and self.compiled_metrics._user_weighted_metrics is None
):
logging.warning(
"`evaluate()` received a value for `sample_weight`, but "
"`weighted_metrics` were not provided. Did you mean to pass "
"metrics to `weighted_metrics` in `compile()`? If this is "
"intentional you can pass `weighted_metrics=[]` to `compile()` "
"in order to silence this warning."
)
def _set_inputs(self, inputs, outputs=None, training=None):
"""This method is for compat with Modelv1. Only inputs are needed
here."""
self._set_save_spec(inputs)
@property
def _trackable_saved_model_saver(self):
return model_serialization.ModelSavedModelSaver(self)
def _trackable_children(self, save_type="checkpoint", **kwargs):
if save_type == "savedmodel":
# SavedModel needs to ignore the execution functions.
train_function = self.train_function
test_function = self.test_function
predict_function = self.predict_function
train_tf_function = self.train_tf_function
self.train_function = None
self.test_function = None
self.predict_function = None
self.train_tf_function = None
children = super()._trackable_children(save_type, **kwargs)
if save_type == "savedmodel":
self.train_function = train_function
self.test_function = test_function
self.predict_function = predict_function
self.train_tf_function = train_tf_function
return children
def _should_eval(self, epoch, validation_freq):
epoch = epoch + 1 # one-index the user-facing epoch.
if isinstance(validation_freq, int):
return epoch % validation_freq == 0
elif isinstance(validation_freq, list):
return epoch in validation_freq
else:
raise ValueError(
"Expected `validation_freq` to be a list or int. "
f"Received: validation_freq={validation_freq} of the "
f"type {type(validation_freq)}."
)
######################################################################
# Functions below exist only as v1 / v2 compatibility shims.
######################################################################
def _get_compile_args(self, user_metrics=True):
"""Used for saving or cloning a Model.
Args:
user_metrics: Whether to return user-supplied metrics or `Metric`
objects. If True, returns the user-supplied metrics.
Defaults to `True`.
Returns:
Dictionary of arguments that were used when compiling the model.
"""
self._assert_compile_was_called()
saved_metrics = self.compiled_metrics._user_metrics
saved_weighted_metrics = self.compiled_metrics._user_weighted_metrics
if not user_metrics:
if saved_metrics is not None:
saved_metrics = self.compiled_metrics._metrics
if saved_weighted_metrics is not None:
saved_weighted_metrics = self.compiled_metrics._weighted_metrics
compile_args = {
"optimizer": self.optimizer,
"loss": self.compiled_loss._user_losses,
"metrics": saved_metrics,
"weighted_metrics": saved_weighted_metrics,
"loss_weights": self.compiled_loss._user_loss_weights,
}
return compile_args
def _get_callback_model(self):
return self
def _in_multi_worker_mode(self):
return self.distribute_strategy.extended._in_multi_worker_mode()
@property
def _compile_was_called(self):
return self._is_compiled
| (self, x=None, y=None, batch_size=None, verbose='auto', sample_weight=None, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False, return_dict=False, **kwargs) |
725,010 | tf_keras.src.engine.training | evaluate_generator | Evaluates the model on a data generator.
DEPRECATED:
`Model.evaluate` now supports generators, so there is no longer any
need to use this endpoint.
| @doc_controls.do_not_generate_docs
def evaluate_generator(
self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0,
):
"""Evaluates the model on a data generator.
DEPRECATED:
`Model.evaluate` now supports generators, so there is no longer any
need to use this endpoint.
"""
warnings.warn(
"`Model.evaluate_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.evaluate`, which supports generators.",
stacklevel=2,
)
self._check_call_args("evaluate_generator")
return self.evaluate(
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks,
)
| (self, generator, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False, verbose=0) |
725,011 | tf_keras.src.engine.training | export | Create a SavedModel artifact for inference (e.g. via TF-Serving).
This method lets you export a model to a lightweight SavedModel artifact
that contains the model's forward pass only (its `call()` method)
and can be served via e.g. TF-Serving. The forward pass is registered
under the name `serve()` (see example below).
The original code of the model (including any custom layers you may
have used) is *no longer* necessary to reload the artifact -- it is
entirely standalone.
Args:
filepath: `str` or `pathlib.Path` object. Path where to save
the artifact.
Example:
```python
# Create the artifact
model.export("path/to/location")
# Later, in a different process / environment...
reloaded_artifact = tf.saved_model.load("path/to/location")
predictions = reloaded_artifact.serve(input_data)
```
If you would like to customize your serving endpoints, you can
use the lower-level `keras.export.ExportArchive` class. The `export()`
method relies on `ExportArchive` internally.
| def export(self, filepath):
"""Create a SavedModel artifact for inference (e.g. via TF-Serving).
This method lets you export a model to a lightweight SavedModel artifact
that contains the model's forward pass only (its `call()` method)
and can be served via e.g. TF-Serving. The forward pass is registered
under the name `serve()` (see example below).
The original code of the model (including any custom layers you may
have used) is *no longer* necessary to reload the artifact -- it is
entirely standalone.
Args:
filepath: `str` or `pathlib.Path` object. Path where to save
the artifact.
Example:
```python
# Create the artifact
model.export("path/to/location")
# Later, in a different process / environment...
reloaded_artifact = tf.saved_model.load("path/to/location")
predictions = reloaded_artifact.serve(input_data)
```
If you would like to customize your serving endpoints, you can
use the lower-level `keras.export.ExportArchive` class. The `export()`
method relies on `ExportArchive` internally.
"""
from tf_keras.src.export import export_lib
export_lib.export_model(self, filepath)
| (self, filepath) |
725,013 | tf_keras.src.engine.training | fit | Trains the model for a fixed number of epochs (dataset iterations).
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A `tf.data` dataset. Should return a tuple
of either `(inputs, targets)` or
`(inputs, targets, sample_weights)`.
- A generator or `keras.utils.Sequence` returning `(inputs,
targets)` or `(inputs, targets, sample_weights)`.
- A `tf.keras.utils.experimental.DatasetCreator`, which wraps a
callable that takes a single argument of type
`tf.distribute.InputContext`, and returns a `tf.data.Dataset`.
`DatasetCreator` should be used when users prefer to specify the
per-replica batching and sharding logic for the `Dataset`.
See `tf.keras.utils.experimental.DatasetCreator` doc for more
information.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given below. If these
include `sample_weights` as a third component, note that sample
weighting applies to the `weighted_metrics` argument but not the
`metrics` argument in `compile()`. If using
`tf.distribute.experimental.ParameterServerStrategy`, only
`DatasetCreator` type is supported for `x`.
y: Target data. Like the input data `x`,
it could be either Numpy array(s) or TensorFlow tensor(s).
It should be consistent with `x` (you cannot have Numpy inputs and
tensor targets, or inversely). If `x` is a dataset, generator,
or `keras.utils.Sequence` instance, `y` should
not be specified (since targets will be obtained from `x`).
batch_size: Integer or `None`.
Number of samples per gradient 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).
epochs: Integer. Number of epochs to train the model.
An epoch is an iteration over the entire `x` and `y`
data provided
(unless the `steps_per_epoch` flag is set to
something other than None).
Note that in conjunction with `initial_epoch`,
`epochs` is to be understood as "final epoch".
The model is not trained for a number of iterations
given by `epochs`, but merely until the epoch
of index `epochs` is reached.
verbose: 'auto', 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = one line per epoch.
'auto' becomes 1 for most cases, but 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so verbose=2 is
recommended when not running interactively (eg, in a production
environment). Defaults to 'auto'.
callbacks: List of `keras.callbacks.Callback` instances.
List of callbacks to apply during training.
See `tf.keras.callbacks`. Note
`tf.keras.callbacks.ProgbarLogger` and
`tf.keras.callbacks.History` callbacks are created automatically
and need not be passed into `model.fit`.
`tf.keras.callbacks.ProgbarLogger` is created or not based on
`verbose` argument to `model.fit`.
Callbacks with batch-level calls are currently unsupported with
`tf.distribute.experimental.ParameterServerStrategy`, and users
are advised to implement epoch-level calls instead with an
appropriate `steps_per_epoch` value.
validation_split: Float between 0 and 1.
Fraction of the training data to be used as validation data.
The model will set apart this fraction of the training data,
will not train on it, and will evaluate
the loss and any model metrics
on this data at the end of each epoch.
The validation data is selected from the last samples
in the `x` and `y` data provided, before shuffling. This
argument is not supported when `x` is a dataset, generator or
`keras.utils.Sequence` instance.
If both `validation_data` and `validation_split` are provided,
`validation_data` will override `validation_split`.
`validation_split` is not yet supported with
`tf.distribute.experimental.ParameterServerStrategy`.
validation_data: Data on which to evaluate
the loss and any model metrics at the end of each epoch.
The model will not be trained on this data. Thus, note the fact
that the validation loss of data provided using
`validation_split` or `validation_data` is not affected by
regularization layers like noise and dropout.
`validation_data` will override `validation_split`.
`validation_data` could be:
- A tuple `(x_val, y_val)` of Numpy arrays or tensors.
- A tuple `(x_val, y_val, val_sample_weights)` of NumPy
arrays.
- A `tf.data.Dataset`.
- A Python generator or `keras.utils.Sequence` returning
`(inputs, targets)` or `(inputs, targets, sample_weights)`.
`validation_data` is not yet supported with
`tf.distribute.experimental.ParameterServerStrategy`.
shuffle: Boolean (whether to shuffle the training data
before each epoch) or str (for 'batch'). This argument is
ignored when `x` is a generator or an object of tf.data.Dataset.
'batch' is a special option for dealing
with the limitations of HDF5 data; it shuffles in batch-sized
chunks. Has no effect when `steps_per_epoch` is not `None`.
class_weight: Optional dictionary mapping class indices (integers)
to a weight (float) value, used for weighting the loss function
(during training only).
This can be useful to tell the model to
"pay more attention" to samples from
an under-represented class. When `class_weight` is specified
and targets have a rank of 2 or greater, either `y` must be
one-hot encoded, or an explicit final dimension of `1` must
be included for sparse class labels.
sample_weight: Optional Numpy array of weights for
the training samples, used for weighting the loss function
(during training only). You can either pass a flat (1D)
Numpy array with the same length as the input samples
(1:1 mapping between weights and samples),
or in the case of temporal data,
you can pass a 2D array with shape
`(samples, sequence_length)`,
to apply a different weight to every timestep of every sample.
This argument is not supported when `x` is a dataset, generator,
or `keras.utils.Sequence` instance, instead provide the
sample_weights as the third element of `x`.
Note that sample weighting does not apply to metrics specified
via the `metrics` argument in `compile()`. To apply sample
weighting to your metrics, you can specify them via the
`weighted_metrics` in `compile()` instead.
initial_epoch: Integer.
Epoch at which to start training
(useful for resuming a previous training run).
steps_per_epoch: Integer or `None`.
Total number of steps (batches of samples)
before declaring one epoch finished and starting the
next epoch. 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_per_epoch'
is None, the epoch will run until the input dataset is
exhausted. When passing an infinitely repeating dataset, you
must specify the `steps_per_epoch` argument. If
`steps_per_epoch=-1` the training will run indefinitely with an
infinitely repeating dataset. This argument is not supported
with array inputs.
When using `tf.distribute.experimental.ParameterServerStrategy`:
* `steps_per_epoch=None` is not supported.
validation_steps: Only relevant if `validation_data` is provided and
is a `tf.data` dataset. Total number of steps (batches of
samples) to draw before stopping when performing validation
at the end of every epoch. If 'validation_steps' is None,
validation will run until the `validation_data` dataset is
exhausted. In the case of an infinitely repeated dataset, it
will run into an infinite loop. If 'validation_steps' is
specified and only part of the dataset will be consumed, the
evaluation will start from the beginning of the dataset at each
epoch. This ensures that the same validation samples are used
every time.
validation_batch_size: Integer or `None`.
Number of samples per validation batch.
If unspecified, will default to `batch_size`.
Do not specify the `validation_batch_size` if your data is in
the form of datasets, generators, or `keras.utils.Sequence`
instances (since they generate batches).
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.
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the generator
queue. If unspecified, `max_queue_size` will default to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up
when using process-based threading. If unspecified, `workers`
will default to 1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
Unpacking behavior for iterator-like inputs:
A common pattern is to pass a tf.data.Dataset, generator, or
tf.keras.utils.Sequence to the `x` argument of fit, which will in fact
yield not only features (x) but optionally targets (y) and sample
weights. TF-Keras requires that the output of such iterator-likes be
unambiguous. The iterator should return a tuple of length 1, 2, or 3,
where the optional second and third elements will be used for y and
sample_weight respectively. Any other type provided will be wrapped in
a length one tuple, effectively treating everything as 'x'. When
yielding dicts, they should still adhere to the top-level tuple
structure.
e.g. `({"x0": x0, "x1": x1}, y)`. TF-Keras will not attempt to
separate features, targets, and weights from the keys of a single
dict.
A notable unsupported data type is the namedtuple. The reason is
that it behaves like both an ordered datatype (tuple) and a mapping
datatype (dict). So given a namedtuple of the form:
`namedtuple("example_tuple", ["y", "x"])`
it is ambiguous whether to reverse the order of the elements when
interpreting the value. Even worse is a tuple of the form:
`namedtuple("other_tuple", ["x", "y", "z"])`
where it is unclear if the tuple was intended to be unpacked into x,
y, and sample_weight or passed through as a single element to `x`. As
a result the data processing code will simply raise a ValueError if it
encounters a namedtuple. (Along with instructions to remedy the
issue.)
Returns:
A `History` object. Its `History.history` attribute is
a record of training loss values and metrics values
at successive epochs, as well as validation loss values
and validation metrics values (if applicable).
Raises:
RuntimeError: 1. If the model was never compiled or,
2. If `model.fit` is wrapped in `tf.function`.
ValueError: In case of mismatch between the provided input data
and what the model expects or when the input data is empty.
| # 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.
# ==============================================================================
"""Training-related part of the TF-Keras engine."""
import copy
import itertools
import json
import warnings
import weakref
import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow.python.distribute import distribute_utils
from tensorflow.python.distribute import input_ops
from tensorflow.python.eager import context
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util.tf_export import keras_export
from tensorflow.tools.docs import doc_controls
from tf_keras.src import backend
from tf_keras.src import callbacks as callbacks_module
from tf_keras.src import optimizers
from tf_keras.src.dtensor import dtensor_api
from tf_keras.src.dtensor import layout_map as layout_map_lib
from tf_keras.src.engine import base_layer
from tf_keras.src.engine import base_layer_utils
from tf_keras.src.engine import compile_utils
from tf_keras.src.engine import data_adapter
from tf_keras.src.engine import input_layer as input_layer_module
from tf_keras.src.engine import training_utils
from tf_keras.src.metrics import base_metric
from tf_keras.src.mixed_precision import loss_scale_optimizer as lso
from tf_keras.src.optimizers import optimizer
from tf_keras.src.optimizers import optimizer_v1
from tf_keras.src.saving import pickle_utils
from tf_keras.src.saving import saving_api
from tf_keras.src.saving import saving_lib
from tf_keras.src.saving import serialization_lib
from tf_keras.src.saving.legacy import serialization
from tf_keras.src.saving.legacy.saved_model import json_utils
from tf_keras.src.saving.legacy.saved_model import model_serialization
from tf_keras.src.utils import generic_utils
from tf_keras.src.utils import io_utils
from tf_keras.src.utils import layer_utils
from tf_keras.src.utils import steps_per_execution_tuning
from tf_keras.src.utils import tf_inspect
from tf_keras.src.utils import tf_utils
from tf_keras.src.utils import traceback_utils
from tf_keras.src.utils import version_utils
from tf_keras.src.utils.mode_keys import ModeKeys
try:
import h5py
except ImportError:
h5py = None
@keras_export("keras.Model", "keras.models.Model")
class Model(base_layer.Layer, version_utils.ModelVersionSelector):
"""A model grouping layers into an object with training/inference features.
Args:
inputs: The input(s) of the model: a `keras.Input` object or a
combination of `keras.Input` objects in a dict, list or tuple.
outputs: The output(s) of the model: a tensor that originated from
`keras.Input` objects or a combination of such tensors in a dict,
list or tuple. See Functional API example below.
name: String, the name of the model.
There are two ways to instantiate a `Model`:
1 - With the "Functional API", where you start from `Input`,
you chain layer calls to specify the model's forward pass,
and finally you create your model from inputs and outputs:
```python
import tensorflow as tf
inputs = tf.keras.Input(shape=(3,))
x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
```
Note: Only dicts, lists, and tuples of input tensors are supported. Nested
inputs are not supported (e.g. lists of list or dicts of dict).
A new Functional API model can also be created by using the
intermediate tensors. This enables you to quickly extract sub-components
of the model.
Example:
```python
inputs = keras.Input(shape=(None, None, 3))
processed = keras.layers.RandomCrop(width=32, height=32)(inputs)
conv = keras.layers.Conv2D(filters=2, kernel_size=3)(processed)
pooling = keras.layers.GlobalAveragePooling2D()(conv)
feature = keras.layers.Dense(10)(pooling)
full_model = keras.Model(inputs, feature)
backbone = keras.Model(processed, conv)
activations = keras.Model(conv, feature)
```
Note that the `backbone` and `activations` models are not
created with `keras.Input` objects, but with the tensors that are originated
from `keras.Input` objects. Under the hood, the layers and weights will
be shared across these models, so that user can train the `full_model`, and
use `backbone` or `activations` to do feature extraction.
The inputs and outputs of the model can be nested structures of tensors as
well, and the created models are standard Functional API models that support
all the existing APIs.
2 - By subclassing the `Model` class: in that case, you should define your
layers in `__init__()` and you should implement the model's forward pass
in `call()`.
```python
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
def call(self, inputs):
x = self.dense1(inputs)
return self.dense2(x)
model = MyModel()
```
If you subclass `Model`, you can optionally have
a `training` argument (boolean) in `call()`, which you can use to specify
a different behavior in training and inference:
```python
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
self.dropout = tf.keras.layers.Dropout(0.5)
def call(self, inputs, training=False):
x = self.dense1(inputs)
if training:
x = self.dropout(x, training=training)
return self.dense2(x)
model = MyModel()
```
Once the model is created, you can config the model with losses and metrics
with `model.compile()`, train the model with `model.fit()`, or use the model
to do prediction with `model.predict()`.
"""
_TF_MODULE_IGNORED_PROPERTIES = frozenset(
itertools.chain(
(
"_train_counter",
"_test_counter",
"_predict_counter",
"_steps_per_execution",
"_compiled_trainable_state",
),
base_layer.Layer._TF_MODULE_IGNORED_PROPERTIES,
)
)
_SCALAR_UPRANKING_ON = False
def __new__(cls, *args, **kwargs):
# Signature detection
if is_functional_model_init_params(args, kwargs) and cls == Model:
# Functional model
from tf_keras.src.engine import functional
return functional.Functional(skip_init=True, *args, **kwargs)
else:
return super(Model, cls).__new__(cls, *args, **kwargs)
@tf.__internal__.tracking.no_automatic_dependency_tracking
@traceback_utils.filter_traceback
def __init__(self, *args, **kwargs):
self._is_model_for_instrumentation = True
# Special case for Subclassed Functional Model, which we couldn't detect
# when __new__ is called. We only realize it is a functional model when
# it calls super.__init__ with input and output tensor.
from tf_keras.src.engine import functional
if is_functional_model_init_params(args, kwargs) and not isinstance(
self, functional.Functional
):
# Filter the kwargs for multiple inheritance.
supported_kwargs = [
"inputs",
"outputs",
"name",
"trainable",
"skip_init",
]
model_kwargs = {
k: kwargs[k] for k in kwargs if k in supported_kwargs
}
other_kwargs = {
k: kwargs[k] for k in kwargs if k not in supported_kwargs
}
inject_functional_model_class(self.__class__)
functional.Functional.__init__(self, *args, **model_kwargs)
# In case there is any multiple inheritance here, we need to call
# the __init__ for any class that appears after the Functional
# class.
clz_to_init = []
found_functional_class = False
for clz in self.__class__.__bases__:
if issubclass(clz, functional.Functional):
found_functional_class = True
continue
if found_functional_class:
clz_to_init.append(clz)
if clz_to_init:
for clz in clz_to_init:
clz.__init__(self, *args, **other_kwargs)
elif other_kwargs:
# In case there are unused kwargs, we should raise an error to
# user, in case they have a typo in the param name.
raise TypeError(
"The following keyword arguments passed to `Model` aren't "
"supported: {}.".format(other_kwargs)
)
return
# The following are implemented as property functions:
# self.trainable_weights
# self.non_trainable_weights
# `inputs` / `outputs` will only appear in kwargs if either are
# misspelled.
generic_utils.validate_kwargs(
kwargs,
{
"trainable",
"dtype",
"dynamic",
"name",
"autocast",
"inputs",
"outputs",
},
)
super().__init__(**kwargs)
# By default, Model is a subclass model, which is not in graph network.
self._is_graph_network = False
self.inputs = None
self.outputs = None
self.input_names = None
self.output_names = None
# stop_training is used by callback to stop training when error happens
self.stop_training = False
self.history = None
# These objects are used in the default `Model.compile`. They are not
# guaranteed to be set after `Model.compile` is called, as users can
# override compile with custom logic.
self.compiled_loss = None
self.compiled_metrics = None
# This is True for Sequential networks and Functional networks.
self._compute_output_and_mask_jointly = False
# Don't reset compilation if already done. This may occur if calling
# `__init__` (or `_init_graph_network`) on an already-compiled model
# such as a Sequential model. Sequential models may need to rebuild
# themselves after compilation.
self._maybe_create_attribute("_is_compiled", False)
self._maybe_create_attribute("optimizer", None)
# Model must be created under scope of DistStrat it will be trained
# with.
if tf.distribute.has_strategy():
self._distribution_strategy = tf.distribute.get_strategy()
else:
self._distribution_strategy = None
self._distribute_reduction_method = None
self._cluster_coordinator = None
# Defaults to value of `tf.config.experimental_functions_run_eagerly`.
self._run_eagerly = None
# Initialize cache attrs.
self._reset_compile_cache()
# Fault-tolerance handler. Set in `ModelCheckpoint`.
self._training_state = None
self._saved_model_inputs_spec = None
self._saved_model_arg_spec = None
self._checkpoint = tf.train.Checkpoint(root=weakref.ref(self))
self._steps_per_execution = None
self._steps_per_execution_tuner = None
self._autotune_steps_per_execution = False
self._layout_map = layout_map_lib.get_current_layout_map()
self._init_batch_counters()
self._base_model_initialized = True
# `jit_compile` starts off with None as default and gets overwritten by
# the value specified in `Model.compile`, and this is effective for
# `fit`, `evaluate`, and `predict`.
self._jit_compile = None
def _create_counter_variable(self, init_value):
"""Helper function for counter variable creation.
For the DTensor use case with layout map, since the variable are not
tracked by model, they can't be visited by the layout map, and need to
be properly initialized as DVariable.
"""
# This function should be removed after we move to the strategy based
# implementation for DTensor.
if self._layout_map is None:
agg = tf.VariableAggregation.ONLY_FIRST_REPLICA
return tf.Variable(init_value, dtype="int64", aggregation=agg)
else:
layout = dtensor_api.Layout.replicated(
mesh=self._layout_map.get_default_mesh(), rank=0
)
return dtensor_api.DVariable(
init_value, dtype="int64", layout=layout
)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _init_batch_counters(self):
# Untracked Variables, used to keep track of mini-batches seen in `fit`,
# `evaluate`, and `predict`.
if not tf.inside_function():
# Creating variables inside tf.function is not allowed, hence
# these would otherwise prevent users from creating TF-Keras layers
# inside tf.function.
# These variables are not connected to outputs so they have no
# effect on graph generation anyway.
self._train_counter = self._create_counter_variable(0)
self._test_counter = self._create_counter_variable(0)
self._predict_counter = self._create_counter_variable(0)
def __setattr__(self, name, value):
if not getattr(self, "_self_setattr_tracking", True):
super().__setattr__(name, value)
return
if all(
isinstance(v, (base_layer.Layer, tf.Variable))
or base_layer_utils.has_weights(v)
for v in tf.nest.flatten(value)
):
try:
self._base_model_initialized
except AttributeError:
raise RuntimeError(
"It looks like you are subclassing `Model` and you "
"forgot to call `super().__init__()`."
" Always start with this line."
)
super().__setattr__(name, value)
def __reduce__(self):
if self.built:
return (
pickle_utils.deserialize_model_from_bytecode,
(pickle_utils.serialize_model_as_bytecode(self),),
)
else:
# SavedModel (and hence serialize_model_as_bytecode) only support
# built models, but if the model is not built,
# it may be possible to serialize as a plain Python object,
# as long as the constituent parts (layers, optimizers, losses,
# etc.) can be serialized as plain Python objects. Thus we call up
# the superclass hierarchy to get an implementation of __reduce__
# that can pickle this Model as a plain Python object.
return super().__reduce__()
def __deepcopy__(self, memo):
if self.built:
new = pickle_utils.deserialize_model_from_bytecode(
pickle_utils.serialize_model_as_bytecode(self)
)
memo[id(self)] = new
else:
# See comment in __reduce__ for explanation
deserializer, serialized, *rest = super().__reduce__()
new = deserializer(*serialized)
memo[id(self)] = new
if rest:
state = copy.deepcopy(rest[0], memo=memo)
new.__setstate__(state)
return new
def __copy__(self):
return self.__deepcopy__({})
@generic_utils.default
def build(self, input_shape):
"""Builds the model based on input shapes received.
This is to be used for subclassed models, which do not know at
instantiation time what their inputs look like.
This method only exists for users who want to call `model.build()` in a
standalone way (as a substitute for calling the model on real data to
build it). It will never be called by the framework (and thus it will
never throw unexpected errors in an unrelated workflow).
Args:
input_shape: Single tuple, `TensorShape` instance, or list/dict of
shapes, where shapes are tuples, integers, or `TensorShape`
instances.
Raises:
ValueError:
1. In case of invalid user-provided data (not of type tuple,
list, `TensorShape`, or dict).
2. If the model requires call arguments that are agnostic
to the input shapes (positional or keyword arg in call
signature).
3. If not all layers were properly built.
4. If float type inputs are not supported within the layers.
In each of these cases, the user should build their model by calling
it on real tensor data.
"""
if self._is_graph_network:
super().build(input_shape)
return
if input_shape is None:
raise ValueError(
"Input shape must be defined when calling `build()` on "
"a `Model` subclass."
)
valid_types = (tuple, list, tf.TensorShape, dict)
if not isinstance(input_shape, valid_types):
raise ValueError(
"Specified input shape is not one of the valid types. "
"Please specify a batch input shape of type tuple or "
"list of input shapes. User provided "
"input type: {}.".format(type(input_shape))
)
if input_shape and not self.inputs:
# We create placeholders for the `None`s in the shape and build the
# model in a Graph. Since tf.Variable is compatible with both eager
# execution and graph building, the variables created after building
# the model in a Graph are still valid when executing eagerly.
if tf.executing_eagerly():
graph = tf.__internal__.FuncGraph("build_graph")
else:
graph = backend.get_graph()
with graph.as_default():
if isinstance(input_shape, list) and all(
d is None or isinstance(d, int) for d in input_shape
):
input_shape = tuple(input_shape)
if isinstance(input_shape, list):
x = [
base_layer_utils.generate_placeholders_from_shape(shape)
for shape in input_shape
]
elif isinstance(input_shape, dict):
x = {
k: base_layer_utils.generate_placeholders_from_shape(
shape
)
for k, shape in input_shape.items()
}
else:
x = base_layer_utils.generate_placeholders_from_shape(
input_shape
)
kwargs = {}
call_signature = self._call_spec.full_argspec
call_args = call_signature.args
# Exclude `self`, `inputs`, and any argument with a default
# value.
if len(call_args) > 2:
if call_signature.defaults:
call_args = call_args[2 : -len(call_signature.defaults)]
else:
call_args = call_args[2:]
for arg in call_args:
if arg == "training":
# Case where `training` is a positional arg with no
# default.
kwargs["training"] = False
else:
# Has invalid call signature with unknown positional
# arguments.
raise ValueError(
"Currently, you cannot build your model if it "
"has positional or keyword arguments that are "
"not inputs to the model, but are required for "
"its `call()` method. Instead, in order to "
"instantiate and build your model, `call()` "
"your model on real tensor data with all "
"expected call arguments. The argument "
"for `call()` can be a single list/tuple that "
"contains multiple inputs."
)
elif len(call_args) < 2:
# Signature without `inputs`.
raise ValueError(
"You can only call `build()` on a model if its "
"`call()` method accepts an `inputs` argument."
)
try:
self.call(x, **kwargs)
except (tf.errors.InvalidArgumentError, TypeError) as e:
raise ValueError(
"You cannot build your model by calling `build` "
"if your layers do not support float type inputs. "
"Instead, in order to instantiate and build your "
"model, call your model on real tensor data (of "
"the correct dtype).\n\nThe actual error from "
f"`call` is: {e}."
)
super().build(input_shape)
@traceback_utils.filter_traceback
def __call__(self, *args, **kwargs):
if self._layout_map is not None and not self.built:
# Note that this method is only overridden for DTensor and layout
# injection purpose.
# Capture the inputs and create graph input as replacement for model
# to initialize its weights first.
copied_args = copy.copy(args)
copied_kwargs = copy.copy(kwargs)
(
inputs,
copied_args,
copied_kwargs,
) = self._call_spec.split_out_first_arg(copied_args, copied_kwargs)
def _convert_to_graph_inputs(x):
if isinstance(x, (tf.Tensor, np.ndarray, float, int)):
x = tf.convert_to_tensor(x)
return input_layer_module.Input(x.shape)
# TODO(scottzhu): maybe better handle mask and training flag.
inputs = tf.nest.map_structure(_convert_to_graph_inputs, inputs)
copied_args = tf.nest.map_structure(
_convert_to_graph_inputs, copied_args
)
copied_kwargs = tf.nest.map_structure(
_convert_to_graph_inputs, copied_kwargs
)
with layout_map_lib.layout_map_scope(self._layout_map):
# We ignore the result here.
super().__call__(inputs, *copied_args, **copied_kwargs)
layout_map_lib._map_subclass_model_variable(self, self._layout_map)
return super().__call__(*args, **kwargs)
@doc_controls.doc_in_current_and_subclasses
def call(self, inputs, training=None, mask=None):
"""Calls the model on new inputs and returns the outputs as tensors.
In this case `call()` just reapplies
all ops in the graph to the new inputs
(e.g. build a new computational graph from the provided inputs).
Note: This method should not be called directly. It is only meant to be
overridden when subclassing `tf.keras.Model`.
To call a model on an input, always use the `__call__()` method,
i.e. `model(inputs)`, which relies on the underlying `call()` method.
Args:
inputs: Input tensor, or dict/list/tuple of input tensors.
training: Boolean or boolean scalar tensor, indicating whether to
run the `Network` in training mode or inference mode.
mask: A mask or list of masks. A mask can be either a boolean tensor
or None (no mask). For more details, check the guide
[here](https://www.tensorflow.org/guide/keras/masking_and_padding).
Returns:
A tensor if there is a single output, or
a list of tensors if there are more than one outputs.
"""
raise NotImplementedError(
"Unimplemented `tf.keras.Model.call()`: if you "
"intend to create a `Model` with the Functional "
"API, please provide `inputs` and `outputs` "
"arguments. Otherwise, subclass `Model` with an "
"overridden `call()` method."
)
@traceback_utils.filter_traceback
def compile(
self,
optimizer="rmsprop",
loss=None,
metrics=None,
loss_weights=None,
weighted_metrics=None,
run_eagerly=None,
steps_per_execution=None,
jit_compile=None,
pss_evaluation_shards=0,
**kwargs,
):
"""Configures the model for training.
Example:
```python
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),
loss=tf.keras.losses.BinaryCrossentropy(),
metrics=[tf.keras.metrics.BinaryAccuracy(),
tf.keras.metrics.FalseNegatives()])
```
Args:
optimizer: String (name of optimizer) or optimizer instance. See
`tf.keras.optimizers`.
loss: Loss function. May be a string (name of loss function), or
a `tf.keras.losses.Loss` instance. See `tf.keras.losses`. A loss
function is any callable with the signature `loss = fn(y_true,
y_pred)`, where `y_true` are the ground truth values, and
`y_pred` are the model's predictions.
`y_true` should have shape
`(batch_size, d0, .. dN)` (except in the case of
sparse loss functions such as
sparse categorical crossentropy which expects integer arrays of
shape `(batch_size, d0, .. dN-1)`).
`y_pred` should have shape `(batch_size, d0, .. dN)`.
The loss function should return a float tensor.
If a custom `Loss` instance is
used and reduction is set to `None`, return value has shape
`(batch_size, d0, .. dN-1)` i.e. per-sample or per-timestep loss
values; otherwise, it is a scalar. If the model has multiple
outputs, you can use a different loss on each output by passing a
dictionary or a list of losses. The loss value that will be
minimized by the model will then be the sum of all individual
losses, unless `loss_weights` is specified.
metrics: List of metrics to be evaluated by the model during
training and testing. Each of this can be a string (name of a
built-in function), function or a `tf.keras.metrics.Metric`
instance. See `tf.keras.metrics`. Typically you will use
`metrics=['accuracy']`.
A function is any callable with the signature `result = fn(y_true,
y_pred)`. To specify different metrics for different outputs of a
multi-output model, you could also pass a dictionary, such as
`metrics={'output_a':'accuracy', 'output_b':['accuracy', 'mse']}`.
You can also pass a list to specify a metric or a list of metrics
for each output, such as
`metrics=[['accuracy'], ['accuracy', 'mse']]`
or `metrics=['accuracy', ['accuracy', 'mse']]`. When you pass the
strings 'accuracy' or 'acc', we convert this to one of
`tf.keras.metrics.BinaryAccuracy`,
`tf.keras.metrics.CategoricalAccuracy`,
`tf.keras.metrics.SparseCategoricalAccuracy` based on the shapes
of the targets and of the model output. We do a similar
conversion for the strings 'crossentropy' and 'ce' as well.
The metrics passed here are evaluated without sample weighting; if
you would like sample weighting to apply, you can specify your
metrics via the `weighted_metrics` argument instead.
loss_weights: Optional list or dictionary specifying scalar
coefficients (Python floats) to weight the loss contributions of
different model outputs. The loss value that will be minimized by
the model will then be the *weighted sum* of all individual
losses, weighted by the `loss_weights` coefficients. If a list,
it is expected to have a 1:1 mapping to the model's outputs. If a
dict, it is expected to map output names (strings) to scalar
coefficients.
weighted_metrics: List of metrics to be evaluated and weighted by
`sample_weight` or `class_weight` during training and testing.
run_eagerly: Bool. If `True`, this `Model`'s logic will not be
wrapped in a `tf.function`. Recommended to leave this as `None`
unless your `Model` cannot be run inside a `tf.function`.
`run_eagerly=True` is not supported when using
`tf.distribute.experimental.ParameterServerStrategy`. Defaults to
`False`.
steps_per_execution: Int or `'auto'`. The number of batches to
run during each `tf.function` call. If set to "auto", keras will
automatically tune `steps_per_execution` during runtime. Running
multiple batches inside a single `tf.function` call can greatly
improve performance on TPUs, when used with distributed strategies
such as `ParameterServerStrategy`, or with small models with a
large Python overhead. At most, one full epoch will be run each
execution. If a number larger than the size of the epoch is
passed, the execution will be truncated to the size of the epoch.
Note that if `steps_per_execution` is set to `N`,
`Callback.on_batch_begin` and `Callback.on_batch_end` methods will
only be called every `N` batches (i.e. before/after each
`tf.function` execution). Defaults to `1`.
jit_compile: If `True`, compile the model training step with XLA.
[XLA](https://www.tensorflow.org/xla) is an optimizing compiler
for machine learning.
`jit_compile` is not enabled for by default.
Note that `jit_compile=True`
may not necessarily work for all models.
For more information on supported operations please refer to the
[XLA documentation](https://www.tensorflow.org/xla).
Also refer to
[known XLA issues](https://www.tensorflow.org/xla/known_issues)
for more details.
pss_evaluation_shards: Integer or 'auto'. Used for
`tf.distribute.ParameterServerStrategy` training only. This arg
sets the number of shards to split the dataset into, to enable an
exact visitation guarantee for evaluation, meaning the model will
be applied to each dataset element exactly once, even if workers
fail. The dataset must be sharded to ensure separate workers do
not process the same data. The number of shards should be at least
the number of workers for good performance. A value of 'auto'
turns on exact evaluation and uses a heuristic for the number of
shards based on the number of workers. 0, meaning no
visitation guarantee is provided. NOTE: Custom implementations of
`Model.test_step` will be ignored when doing exact evaluation.
Defaults to `0`.
**kwargs: Arguments supported for backwards compatibility only.
"""
if jit_compile and not tf_utils.can_jit_compile(warn=True):
jit_compile = False
self._compile_config = serialization_lib.Config(
optimizer=optimizer,
loss=loss,
metrics=metrics,
loss_weights=loss_weights,
weighted_metrics=weighted_metrics,
run_eagerly=run_eagerly,
steps_per_execution=steps_per_execution,
jit_compile=jit_compile,
)
with self.distribute_strategy.scope():
if "experimental_steps_per_execution" in kwargs:
logging.warning(
"The argument `steps_per_execution` is no longer "
"experimental. Pass `steps_per_execution` instead of "
"`experimental_steps_per_execution`."
)
if not steps_per_execution:
steps_per_execution = kwargs.pop(
"experimental_steps_per_execution"
)
# When compiling from an already-serialized model, we do not want to
# reapply some processing steps (e.g. metric renaming for
# multi-output models, which have prefixes added for each
# corresponding output name).
from_serialized = kwargs.pop("from_serialized", False)
self._validate_compile(optimizer, metrics, **kwargs)
self._run_eagerly = run_eagerly
self.optimizer = self._get_optimizer(optimizer)
mesh = None
if self._layout_map is not None:
mesh = self._layout_map.get_default_mesh()
if isinstance(loss, compile_utils.LossesContainer):
self.compiled_loss = loss
else:
self.compiled_loss = compile_utils.LossesContainer(
loss,
loss_weights,
output_names=self.output_names,
mesh=mesh,
)
self.compiled_metrics = compile_utils.MetricsContainer(
metrics,
weighted_metrics,
output_names=self.output_names,
from_serialized=from_serialized,
mesh=mesh,
)
if steps_per_execution == "auto":
if self._steps_per_execution is None:
self._configure_steps_per_execution(1)
self._steps_per_execution_tuner = (
steps_per_execution_tuning.StepsPerExecutionTuner(
self.optimizer, self._steps_per_execution
)
)
self._autotune_steps_per_execution = True
else:
self._configure_steps_per_execution(steps_per_execution or 1)
self._pss_evaluation_shards = self._infer_exact_eval_shards(
pss_evaluation_shards
)
# Initializes attrs that are reset each time `compile` is called.
self._reset_compile_cache()
self._is_compiled = True
self.loss = loss or {}
if (self._run_eagerly or self.dynamic) and jit_compile:
raise ValueError(
"You cannot enable `run_eagerly` and `jit_compile` "
"at the same time."
)
else:
self._jit_compile = jit_compile
def _get_optimizer(self, optimizer):
"""Wraps `optimizer` in `LossScaleOptimizer` if necessary."""
def _get_single_optimizer(opt):
opt = optimizers.get(opt)
if self.dtype_policy.name == "mixed_float16" and not isinstance(
opt, lso.BaseLossScaleOptimizer
):
# Loss scaling is necessary with mixed_float16 for models to
# converge to the same accuracy as with float32.
opt = lso.BaseLossScaleOptimizer(opt)
return opt
return tf.nest.map_structure(_get_single_optimizer, optimizer)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _reset_compile_cache(self):
self.train_function = None
self.test_function = None
self.predict_function = None
# Used to cache the `tf.function`'ed `train_function` to be logged in
# TensorBoard, since the original `train_function` is not necessarily
# a `tf.function` (e.g., with ParameterServerStrategy, the
# `train_function` is a scheduling of the actual training function to a
# remote worker).
self.train_tf_function = None
# Used to cache `trainable` attr of `Layer`s for `fit`.
self._compiled_trainable_state = self._get_trainable_state()
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _configure_steps_per_execution(self, steps_per_execution):
self._steps_per_execution = self._create_counter_variable(
steps_per_execution
)
@property
def _should_compute_mask(self):
return False
@property
def metrics(self):
"""Return metrics added using `compile()` or `add_metric()`.
Note: Metrics passed to `compile()` are available only after a
`keras.Model` has been trained/evaluated on actual data.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> [m.name for m in model.metrics]
[]
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> model.fit(x, y)
>>> [m.name for m in model.metrics]
['loss', 'mae']
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> d = tf.keras.layers.Dense(2, name='out')
>>> output_1 = d(inputs)
>>> output_2 = d(inputs)
>>> model = tf.keras.models.Model(
... inputs=inputs, outputs=[output_1, output_2])
>>> model.add_metric(
... tf.reduce_sum(output_2), name='mean', aggregation='mean')
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
>>> model.fit(x, (y, y))
>>> [m.name for m in model.metrics]
['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',
'out_1_acc', 'mean']
"""
metrics = []
if self._is_compiled:
if self.compiled_loss is not None:
metrics += self.compiled_loss.metrics
if self.compiled_metrics is not None:
metrics += self.compiled_metrics.metrics
for l in self._flatten_layers():
metrics.extend(l._metrics)
return metrics
@property
def metrics_names(self):
"""Returns the model's display labels for all outputs.
Note: `metrics_names` are available only after a `keras.Model` has been
trained/evaluated on actual data.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> model.metrics_names
[]
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> model.fit(x, y)
>>> model.metrics_names
['loss', 'mae']
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> d = tf.keras.layers.Dense(2, name='out')
>>> output_1 = d(inputs)
>>> output_2 = d(inputs)
>>> model = tf.keras.models.Model(
... inputs=inputs, outputs=[output_1, output_2])
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
>>> model.fit(x, (y, y))
>>> model.metrics_names
['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',
'out_1_acc']
"""
# This property includes all output names including `loss` and
# per-output losses for backward compatibility.
return [m.name for m in self.metrics]
@property
def distribute_strategy(self):
"""The `tf.distribute.Strategy` this model was created under."""
return self._distribution_strategy or tf.distribute.get_strategy()
@property
def run_eagerly(self):
"""Settable attribute indicating whether the model should run eagerly.
Running eagerly means that your model will be run step by step,
like Python code. Your model might run slower, but it should become
easier for you to debug it by stepping into individual layer calls.
By default, we will attempt to compile your model to a static graph to
deliver the best execution performance.
Returns:
Boolean, whether the model should run eagerly.
"""
if self.dynamic and self._run_eagerly == False:
# TODO(fchollet): consider using py_func to enable this.
raise ValueError(
"Your model contains layers that can only be "
"successfully run in eager execution (layers "
"constructed with `dynamic=True`). "
"You cannot set `run_eagerly=False`."
)
if self._cluster_coordinator and self._run_eagerly:
raise ValueError(
"When using `Model` with `ParameterServerStrategy`, "
"`run_eagerly` is not supported."
)
# Run eagerly logic, by priority:
# (1) Dynamic models must be run eagerly.
# (2) Explicitly setting run_eagerly causes a Model to be run eagerly.
# (3) Not explicitly setting run_eagerly defaults to TF's global
# setting.
return (
self.dynamic
or self._run_eagerly
or (tf.config.functions_run_eagerly() and self._run_eagerly is None)
)
@run_eagerly.setter
def run_eagerly(self, value):
self._run_eagerly = value
@property
def autotune_steps_per_execution(self):
"""Settable property to enable tuning for steps_per_execution"""
return self._autotune_steps_per_execution
@autotune_steps_per_execution.setter
def autotune_steps_per_execution(self, value):
self._autotune_steps_per_execution = value
if value and self._steps_per_execution_tuner is None:
if self._steps_per_execution is None:
self._configure_steps_per_execution(1)
self._steps_per_execution_tuner = (
steps_per_execution_tuning.StepsPerExecutionTuner(
self.optimizer, self._steps_per_execution
)
)
@property
def steps_per_execution(self):
"""Settable `steps_per_execution variable. Requires a compiled model."""
return self._steps_per_execution
@steps_per_execution.setter
def steps_per_execution(self, value):
if self._steps_per_execution is None:
self._configure_steps_per_execution(value)
else:
self._steps_per_execution.assign(value)
@property
def jit_compile(self):
"""Specify whether to compile the model with XLA.
[XLA](https://www.tensorflow.org/xla) is an optimizing compiler
for machine learning. `jit_compile` is not enabled by default.
Note that `jit_compile=True` may not necessarily work for all models.
For more information on supported operations please refer to the
[XLA documentation](https://www.tensorflow.org/xla). Also refer to
[known XLA issues](https://www.tensorflow.org/xla/known_issues)
for more details.
"""
return self._jit_compile
@jit_compile.setter
def jit_compile(self, value):
# Function remains cached with previous jit_compile settings
if self._jit_compile == value:
# Avoid resetting compiler cache if possible if the value is the
# same
return
# Check if TensorFlow is compiled with XLA before setting the value
if value and not tf_utils.can_jit_compile(warn=True):
self._jit_compile = False
return
self._jit_compile = value
# Setting `jit_compile` should invalidate previously cached functions.
self._reset_compile_cache()
@property
def distribute_reduction_method(self):
"""The method employed to reduce per-replica values during training.
Unless specified, the value "auto" will be assumed, indicating that
the reduction strategy should be chosen based on the current
running environment.
See `reduce_per_replica` function for more details.
"""
return self._distribute_reduction_method or "auto"
@distribute_reduction_method.setter
def distribute_reduction_method(self, value):
self._distribute_reduction_method = value
def _validate_target_and_loss(self, y, loss):
"""Raises error if target or loss is not found.
This method verifies that the target and loss are properly populated
when applicable, or raises errors.
Args:
y: the target for training.
loss: the total loss tensor including loss added via `compile` and
`add_loss`.
"""
# `self.loss` references the loss added via `compile` call. If users
# have provided such, the target must be provided; otherwise it's a user
# error. Note that `self.loss` does not include losses added via
# `add_loss`, and it is a valid use when such loss from `add_loss`
# exists and target does not.
if self.loss and y is None:
raise ValueError(
"Target data is missing. Your model was compiled with "
f"loss={self.loss}, "
"and therefore expects target data to be provided in `fit()`."
)
# For training, there must be compiled loss or regularization loss to
# exist in order to apply the gradients. If one is not found, it means
# no loss was supplied via `compile` or `add_loss`.
elif loss is None:
raise ValueError(
"No loss found. You may have forgotten to provide a `loss` "
"argument in the `compile()` method."
)
def train_step(self, data):
"""The logic for one training step.
This method can be overridden to support custom training logic.
For concrete examples of how to override this method see
[Customizing what happens in fit](
https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit).
This method is called by `Model.make_train_function`.
This method should contain the mathematical logic for one step of
training. This typically includes the forward pass, loss calculation,
backpropagation, and metric updates.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_train_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the
values of the `Model`'s metrics are returned. Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data)
# Run forward pass.
with tf.GradientTape() as tape:
y_pred = self(x, training=True)
loss = self.compute_loss(x, y, y_pred, sample_weight)
self._validate_target_and_loss(y, loss)
# Run backwards pass.
self.optimizer.minimize(loss, self.trainable_variables, tape=tape)
return self.compute_metrics(x, y, y_pred, sample_weight)
def compute_loss(self, x=None, y=None, y_pred=None, sample_weight=None):
"""Compute the total loss, validate it, and return it.
Subclasses can optionally override this method to provide custom loss
computation logic.
Example:
```python
class MyModel(tf.keras.Model):
def __init__(self, *args, **kwargs):
super(MyModel, self).__init__(*args, **kwargs)
self.loss_tracker = tf.keras.metrics.Mean(name='loss')
def compute_loss(self, x, y, y_pred, sample_weight):
loss = tf.reduce_mean(tf.math.squared_difference(y_pred, y))
loss += tf.add_n(self.losses)
self.loss_tracker.update_state(loss)
return loss
def reset_metrics(self):
self.loss_tracker.reset_states()
@property
def metrics(self):
return [self.loss_tracker]
tensors = tf.random.uniform((10, 10)), tf.random.uniform((10,))
dataset = tf.data.Dataset.from_tensor_slices(tensors).repeat().batch(1)
inputs = tf.keras.layers.Input(shape=(10,), name='my_input')
outputs = tf.keras.layers.Dense(10)(inputs)
model = MyModel(inputs, outputs)
model.add_loss(tf.reduce_sum(outputs))
optimizer = tf.keras.optimizers.SGD()
model.compile(optimizer, loss='mse', steps_per_execution=10)
model.fit(dataset, epochs=2, steps_per_epoch=10)
print('My custom loss: ', model.loss_tracker.result().numpy())
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
The total loss as a `tf.Tensor`, or `None` if no loss results (which
is the case when called by `Model.test_step`).
"""
del x # The default implementation does not use `x`.
return self.compiled_loss(
y, y_pred, sample_weight, regularization_losses=self.losses
)
def compute_metrics(self, x, y, y_pred, sample_weight):
"""Update metric states and collect all metrics to be returned.
Subclasses can optionally override this method to provide custom metric
updating and collection logic.
Example:
```python
class MyModel(tf.keras.Sequential):
def compute_metrics(self, x, y, y_pred, sample_weight):
# This super call updates `self.compiled_metrics` and returns
# results for all metrics listed in `self.metrics`.
metric_results = super(MyModel, self).compute_metrics(
x, y, y_pred, sample_weight)
# Note that `self.custom_metric` is not listed in `self.metrics`.
self.custom_metric.update_state(x, y, y_pred, sample_weight)
metric_results['custom_metric_name'] = self.custom_metric.result()
return metric_results
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model.call(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end()`. Typically, the
values of the metrics listed in `self.metrics` are returned. Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
del x # The default implementation does not use `x`.
self.compiled_metrics.update_state(y, y_pred, sample_weight)
return self.get_metrics_result()
def get_metrics_result(self):
"""Returns the model's metrics values as a dict.
If any of the metric result is a dict (containing multiple metrics),
each of them gets added to the top level returned dict of this method.
Returns:
A `dict` containing values of the metrics listed in `self.metrics`.
Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
# Collect metrics to return
return_metrics = {}
for metric in self.metrics:
result = metric.result()
if isinstance(result, dict):
return_metrics.update(result)
else:
return_metrics[metric.name] = result
return return_metrics
def _validate_and_get_metrics_result(self, logs):
"""Returns model metrics as a dict if the keys match with input logs.
When the training / evalution is performed with asynchronous steps, such
as the case with `tf.distribute.ParameterServerStrategy`, the last
scheduled `train / test_step` may not give the latest metrics because it
is not guaranteed to be executed the last. This method gets metrics from
the model directly instead of relying on the return from last step
function.
It logs a warning if the metric results could not be overridden when
used with `tf.distribute.ParameterServerStrategy`.
When the user has custom train / test step functions, the metrics
returned may be different from `Model.metrics`. In those instances,
this function will be no-op and return the logs.
Args:
logs: A `dict` of metrics returned by train / test step function.
Returns:
A `dict` containing values of the metrics listed in `self.metrics`
when logs and model metrics keys match. Otherwise it returns input
`logs`.
"""
PSS_WARN_MSG = "Could not get Model metric results. \
Using the results of last step function could lead to incorrect \
results when used with ParameterServerStrategy"
try:
metric_logs = self.get_metrics_result()
except TypeError:
if self._cluster_coordinator:
logging.warning(PSS_WARN_MSG)
else:
# Verify that train / test step logs passed and metric logs have
# matching keys. Could be different when using custom step functions
if isinstance(logs, dict) and set(logs.keys()) == set(
metric_logs.keys()
):
logs = tf_utils.sync_to_numpy_or_python_type(metric_logs)
elif self._cluster_coordinator:
logging.warning(PSS_WARN_MSG)
return logs
def _aggregate_exact_metrics(self, logs):
# When doing exact evaluation, `logs` is a list of each data shard's
# metric variables, which will be used to update the metrics.
for shard_result in logs:
for metric in self.metrics:
if metric.name not in shard_result.keys():
logging.log_first_n(
logging.WARN,
f"No matching result found for metric {metric.name}. "
"This metric's computed result may be incorrect.",
3,
)
continue
metric_result = shard_result[metric.name]
if len(metric_result) != len(metric.weights):
raise ValueError(
f"Expected {len(metric.weights)} variables in result "
f"for metric {metric.name}, but found "
f"{len(metric_result)}."
)
for weight, val in zip(metric.weights, metric_result):
weight.assign_add(val)
return self.get_metrics_result()
def make_train_function(self, force=False):
"""Creates a function that executes one step of training.
This method can be overridden to support custom training logic.
This method is called by `Model.fit` and `Model.train_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual training
logic to `Model.train_step`.
This function is cached the first time `Model.fit` or
`Model.train_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the train function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_train_batch_end`, such as
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
if self.train_function is not None and not force:
return self.train_function
def step_function(model, iterator):
"""Runs a single training step."""
def run_step(data):
outputs = model.train_step(data)
# Ensure counter is updated only if `train_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._train_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def train_function(iterator):
"""Runs a training execution with a single step."""
return step_function(self, iterator)
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
if self._cluster_coordinator:
self.train_function = (
lambda it: self._cluster_coordinator.schedule(
train_function, args=(it,)
)
)
else:
self.train_function = train_function
# If we're using a coordinator, use the value of
# self._steps_per_execution at the time the function is
# called/scheduled, and not when it is actually executed.
elif self._cluster_coordinator:
def train_function(iterator, steps_per_execution):
"""Runs a training execution with multiple steps."""
for _ in tf.range(steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
self.train_function = lambda it: self._cluster_coordinator.schedule(
train_function, args=(it, self._steps_per_execution.value())
)
else:
def train_function(iterator):
"""Runs a training execution with multiple steps."""
for _ in tf.range(self._steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
self.train_function = train_function
return self.train_function
@traceback_utils.filter_traceback
def fit(
self,
x=None,
y=None,
batch_size=None,
epochs=1,
verbose="auto",
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_batch_size=None,
validation_freq=1,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
):
"""Trains the model for a fixed number of epochs (dataset iterations).
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A `tf.data` dataset. Should return a tuple
of either `(inputs, targets)` or
`(inputs, targets, sample_weights)`.
- A generator or `keras.utils.Sequence` returning `(inputs,
targets)` or `(inputs, targets, sample_weights)`.
- A `tf.keras.utils.experimental.DatasetCreator`, which wraps a
callable that takes a single argument of type
`tf.distribute.InputContext`, and returns a `tf.data.Dataset`.
`DatasetCreator` should be used when users prefer to specify the
per-replica batching and sharding logic for the `Dataset`.
See `tf.keras.utils.experimental.DatasetCreator` doc for more
information.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given below. If these
include `sample_weights` as a third component, note that sample
weighting applies to the `weighted_metrics` argument but not the
`metrics` argument in `compile()`. If using
`tf.distribute.experimental.ParameterServerStrategy`, only
`DatasetCreator` type is supported for `x`.
y: Target data. Like the input data `x`,
it could be either Numpy array(s) or TensorFlow tensor(s).
It should be consistent with `x` (you cannot have Numpy inputs and
tensor targets, or inversely). If `x` is a dataset, generator,
or `keras.utils.Sequence` instance, `y` should
not be specified (since targets will be obtained from `x`).
batch_size: Integer or `None`.
Number of samples per gradient 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).
epochs: Integer. Number of epochs to train the model.
An epoch is an iteration over the entire `x` and `y`
data provided
(unless the `steps_per_epoch` flag is set to
something other than None).
Note that in conjunction with `initial_epoch`,
`epochs` is to be understood as "final epoch".
The model is not trained for a number of iterations
given by `epochs`, but merely until the epoch
of index `epochs` is reached.
verbose: 'auto', 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = one line per epoch.
'auto' becomes 1 for most cases, but 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so verbose=2 is
recommended when not running interactively (eg, in a production
environment). Defaults to 'auto'.
callbacks: List of `keras.callbacks.Callback` instances.
List of callbacks to apply during training.
See `tf.keras.callbacks`. Note
`tf.keras.callbacks.ProgbarLogger` and
`tf.keras.callbacks.History` callbacks are created automatically
and need not be passed into `model.fit`.
`tf.keras.callbacks.ProgbarLogger` is created or not based on
`verbose` argument to `model.fit`.
Callbacks with batch-level calls are currently unsupported with
`tf.distribute.experimental.ParameterServerStrategy`, and users
are advised to implement epoch-level calls instead with an
appropriate `steps_per_epoch` value.
validation_split: Float between 0 and 1.
Fraction of the training data to be used as validation data.
The model will set apart this fraction of the training data,
will not train on it, and will evaluate
the loss and any model metrics
on this data at the end of each epoch.
The validation data is selected from the last samples
in the `x` and `y` data provided, before shuffling. This
argument is not supported when `x` is a dataset, generator or
`keras.utils.Sequence` instance.
If both `validation_data` and `validation_split` are provided,
`validation_data` will override `validation_split`.
`validation_split` is not yet supported with
`tf.distribute.experimental.ParameterServerStrategy`.
validation_data: Data on which to evaluate
the loss and any model metrics at the end of each epoch.
The model will not be trained on this data. Thus, note the fact
that the validation loss of data provided using
`validation_split` or `validation_data` is not affected by
regularization layers like noise and dropout.
`validation_data` will override `validation_split`.
`validation_data` could be:
- A tuple `(x_val, y_val)` of Numpy arrays or tensors.
- A tuple `(x_val, y_val, val_sample_weights)` of NumPy
arrays.
- A `tf.data.Dataset`.
- A Python generator or `keras.utils.Sequence` returning
`(inputs, targets)` or `(inputs, targets, sample_weights)`.
`validation_data` is not yet supported with
`tf.distribute.experimental.ParameterServerStrategy`.
shuffle: Boolean (whether to shuffle the training data
before each epoch) or str (for 'batch'). This argument is
ignored when `x` is a generator or an object of tf.data.Dataset.
'batch' is a special option for dealing
with the limitations of HDF5 data; it shuffles in batch-sized
chunks. Has no effect when `steps_per_epoch` is not `None`.
class_weight: Optional dictionary mapping class indices (integers)
to a weight (float) value, used for weighting the loss function
(during training only).
This can be useful to tell the model to
"pay more attention" to samples from
an under-represented class. When `class_weight` is specified
and targets have a rank of 2 or greater, either `y` must be
one-hot encoded, or an explicit final dimension of `1` must
be included for sparse class labels.
sample_weight: Optional Numpy array of weights for
the training samples, used for weighting the loss function
(during training only). You can either pass a flat (1D)
Numpy array with the same length as the input samples
(1:1 mapping between weights and samples),
or in the case of temporal data,
you can pass a 2D array with shape
`(samples, sequence_length)`,
to apply a different weight to every timestep of every sample.
This argument is not supported when `x` is a dataset, generator,
or `keras.utils.Sequence` instance, instead provide the
sample_weights as the third element of `x`.
Note that sample weighting does not apply to metrics specified
via the `metrics` argument in `compile()`. To apply sample
weighting to your metrics, you can specify them via the
`weighted_metrics` in `compile()` instead.
initial_epoch: Integer.
Epoch at which to start training
(useful for resuming a previous training run).
steps_per_epoch: Integer or `None`.
Total number of steps (batches of samples)
before declaring one epoch finished and starting the
next epoch. 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_per_epoch'
is None, the epoch will run until the input dataset is
exhausted. When passing an infinitely repeating dataset, you
must specify the `steps_per_epoch` argument. If
`steps_per_epoch=-1` the training will run indefinitely with an
infinitely repeating dataset. This argument is not supported
with array inputs.
When using `tf.distribute.experimental.ParameterServerStrategy`:
* `steps_per_epoch=None` is not supported.
validation_steps: Only relevant if `validation_data` is provided and
is a `tf.data` dataset. Total number of steps (batches of
samples) to draw before stopping when performing validation
at the end of every epoch. If 'validation_steps' is None,
validation will run until the `validation_data` dataset is
exhausted. In the case of an infinitely repeated dataset, it
will run into an infinite loop. If 'validation_steps' is
specified and only part of the dataset will be consumed, the
evaluation will start from the beginning of the dataset at each
epoch. This ensures that the same validation samples are used
every time.
validation_batch_size: Integer or `None`.
Number of samples per validation batch.
If unspecified, will default to `batch_size`.
Do not specify the `validation_batch_size` if your data is in
the form of datasets, generators, or `keras.utils.Sequence`
instances (since they generate batches).
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.
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the generator
queue. If unspecified, `max_queue_size` will default to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up
when using process-based threading. If unspecified, `workers`
will default to 1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
Unpacking behavior for iterator-like inputs:
A common pattern is to pass a tf.data.Dataset, generator, or
tf.keras.utils.Sequence to the `x` argument of fit, which will in fact
yield not only features (x) but optionally targets (y) and sample
weights. TF-Keras requires that the output of such iterator-likes be
unambiguous. The iterator should return a tuple of length 1, 2, or 3,
where the optional second and third elements will be used for y and
sample_weight respectively. Any other type provided will be wrapped in
a length one tuple, effectively treating everything as 'x'. When
yielding dicts, they should still adhere to the top-level tuple
structure.
e.g. `({"x0": x0, "x1": x1}, y)`. TF-Keras will not attempt to
separate features, targets, and weights from the keys of a single
dict.
A notable unsupported data type is the namedtuple. The reason is
that it behaves like both an ordered datatype (tuple) and a mapping
datatype (dict). So given a namedtuple of the form:
`namedtuple("example_tuple", ["y", "x"])`
it is ambiguous whether to reverse the order of the elements when
interpreting the value. Even worse is a tuple of the form:
`namedtuple("other_tuple", ["x", "y", "z"])`
where it is unclear if the tuple was intended to be unpacked into x,
y, and sample_weight or passed through as a single element to `x`. As
a result the data processing code will simply raise a ValueError if it
encounters a namedtuple. (Along with instructions to remedy the
issue.)
Returns:
A `History` object. Its `History.history` attribute is
a record of training loss values and metrics values
at successive epochs, as well as validation loss values
and validation metrics values (if applicable).
Raises:
RuntimeError: 1. If the model was never compiled or,
2. If `model.fit` is wrapped in `tf.function`.
ValueError: In case of mismatch between the provided input data
and what the model expects or when the input data is empty.
"""
# Legacy graph support is contained in `training_v1.Model`.
version_utils.disallow_legacy_graph("Model", "fit")
self._assert_compile_was_called()
self._check_call_args("fit")
_disallow_inside_tf_function("fit")
verbose = _get_verbosity(verbose, self.distribute_strategy)
if validation_split and validation_data is None:
# Create the validation data using the training data. Only supported
# for `Tensor` and `NumPy` input.
(
x,
y,
sample_weight,
), validation_data = data_adapter.train_validation_split(
(x, y, sample_weight), validation_split=validation_split
)
if validation_data:
(
val_x,
val_y,
val_sample_weight,
) = data_adapter.unpack_x_y_sample_weight(validation_data)
if self.distribute_strategy._should_use_with_coordinator:
self._cluster_coordinator = (
tf.distribute.experimental.coordinator.ClusterCoordinator(
self.distribute_strategy
)
)
with self.distribute_strategy.scope(), training_utils.RespectCompiledTrainableState( # noqa: E501
self
):
# Creates a `tf.data.Dataset` and handles batch and epoch iteration.
data_handler = data_adapter.get_data_handler(
x=x,
y=y,
sample_weight=sample_weight,
batch_size=batch_size,
steps_per_epoch=steps_per_epoch,
initial_epoch=initial_epoch,
epochs=epochs,
shuffle=shuffle,
class_weight=class_weight,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=epochs,
steps=data_handler.inferred_steps,
)
self.stop_training = False
self.train_function = self.make_train_function()
self._train_counter.assign(0)
callbacks.on_train_begin()
training_logs = None
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
# Handle fault-tolerance for multi-worker.
# TODO(omalleyt): Fix the ordering issues that mean this has to
# happen after `callbacks.on_train_begin`.
steps_per_epoch_inferred = (
steps_per_epoch or data_handler.inferred_steps
)
(
data_handler._initial_epoch,
data_handler._initial_step,
) = self._maybe_load_initial_counters_from_ckpt(
steps_per_epoch_inferred, initial_epoch
)
logs = None
for epoch, iterator in data_handler.enumerate_epochs():
self.reset_metrics()
callbacks.on_epoch_begin(epoch)
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
with tf.profiler.experimental.Trace(
"train",
epoch_num=epoch,
step_num=step,
batch_size=batch_size,
_r=1,
):
callbacks.on_train_batch_begin(step)
tmp_logs = self.train_function(iterator)
if data_handler.should_sync:
context.async_wait()
# No error, now safe to assign to logs.
logs = tmp_logs
end_step = step + data_handler.step_increment
callbacks.on_train_batch_end(end_step, logs)
if self.stop_training:
break
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if logs is None:
raise ValueError(
"Unexpected result of `train_function` "
"(Empty logs). This could be due to issues in input "
"pipeline that resulted in an empty dataset. "
"Otherwise, please use "
"`Model.compile(..., run_eagerly=True)`, or "
"`tf.config.run_functions_eagerly(True)` for more "
"information of where went wrong, or file a "
"issue/bug to `tf.keras`."
)
# Override with model metrics instead of last step logs
logs = self._validate_and_get_metrics_result(logs)
epoch_logs = copy.copy(logs)
# Run validation.
if validation_data and self._should_eval(
epoch, validation_freq
):
if self._pss_evaluation_shards:
self._disallow_exact_eval_with_add_metrics()
# Create data_handler for evaluation and cache it.
if getattr(self, "_eval_data_handler", None) is None:
self._eval_data_handler = data_adapter.get_data_handler(
x=val_x,
y=val_y,
sample_weight=val_sample_weight,
batch_size=validation_batch_size or batch_size,
steps_per_epoch=validation_steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
pss_evaluation_shards=self._pss_evaluation_shards,
)
val_logs = self.evaluate(
x=val_x,
y=val_y,
sample_weight=val_sample_weight,
batch_size=validation_batch_size or batch_size,
steps=validation_steps,
callbacks=callbacks,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
return_dict=True,
_use_cached_eval_dataset=True,
)
val_logs = {
"val_" + name: val for name, val in val_logs.items()
}
epoch_logs.update(val_logs)
callbacks.on_epoch_end(epoch, epoch_logs)
training_logs = epoch_logs
if self.stop_training:
break
if isinstance(self.optimizer, optimizer.Optimizer) and epochs > 0:
self.optimizer.finalize_variable_values(
self.trainable_variables
)
# If eval data_handler exists, delete it after all epochs are done.
if getattr(self, "_eval_data_handler", None) is not None:
del self._eval_data_handler
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_train_end(logs=training_logs)
return self.history
def test_step(self, data):
"""The logic for one evaluation step.
This method can be overridden to support custom evaluation logic.
This method is called by `Model.make_test_function`.
This function should contain the mathematical logic for one step of
evaluation.
This typically includes the forward pass, loss calculation, and metrics
updates.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_test_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the
values of the `Model`'s metrics are returned.
"""
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data)
y_pred = self(x, training=False)
# Updates stateful loss metrics.
self.compute_loss(x, y, y_pred, sample_weight)
return self.compute_metrics(x, y, y_pred, sample_weight)
def _make_test_function_exact(self):
if getattr(self, "_shard_test_function", None):
return self._shard_test_function
def step_function(batch):
def run_step(data):
# TODO(b/272050910): Use sample_weight for weighted metrics.
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(
data
)
y_pred = self(x, training=False)
return x, y, y_pred, sample_weight
if self._jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
outputs = self.distribute_strategy.run(run_step, args=(batch,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
def shard_test_function(dataset, total_shards, shard_idx):
# Copy loss and metric variables to the worker and work with them
# locally. This ensures each shard function is atomic: if a worker
# is preempted, the intermediate progress is discarded and that
# shard is retried. This in turn guarantees exactly-once visitation.
local_unweighted_metrics, local_weighted_metrics = [], []
with tf_utils.with_metric_local_vars_scope():
# TODO(jmullenbach): implement and use a clone for
# `MetricsContainer` and use its `update_state` method directly.
for metric in self.compiled_metrics.unweighted_metrics:
if metric is not None:
local_unweighted_metrics.append(
base_metric.clone_metric(metric)
)
for metric in self.compiled_metrics.weighted_metrics:
if metric is not None:
local_weighted_metrics.append(
base_metric.clone_metric(metric)
)
local_loss = compile_utils.LossesContainer.from_config(
self.compiled_loss.get_config()
)
dataset = input_ops.auto_shard_dataset(
dataset, total_shards, shard_idx
)
iterator = iter(dataset)
with distribute_utils.cache_variable_reads():
for batch in iterator:
x, y, y_pred, sample_weight = step_function(batch)
for weighted_metric in local_weighted_metrics:
weighted_metric.update_state(y, y_pred, sample_weight)
for unweighted_metric in local_unweighted_metrics:
unweighted_metric.update_state(y, y_pred)
local_loss(y, y_pred, sample_weight)
local_metrics = (
local_unweighted_metrics
+ local_weighted_metrics
+ local_loss.metrics
)
outputs = {metric.name: metric.weights for metric in local_metrics}
with tf.control_dependencies(_minimum_control_deps(outputs)):
self._test_counter.assign_add(1)
return outputs
if not self.run_eagerly:
shard_test_function = tf.function(
shard_test_function, reduce_retracing=True
)
self._shard_test_function = (
lambda *args: self._cluster_coordinator.schedule(
shard_test_function,
args=args,
)
)
return self._shard_test_function
def make_test_function(self, force=False):
"""Creates a function that executes one step of evaluation.
This method can be overridden to support custom evaluation logic.
This method is called by `Model.evaluate` and `Model.test_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.test_step`.
This function is cached the first time `Model.evaluate` or
`Model.test_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the test function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_test_batch_end`.
"""
if self.test_function is not None and not force:
return self.test_function
def step_function(model, iterator):
"""Runs a single evaluation step."""
def run_step(data):
outputs = model.test_step(data)
# Ensure counter is updated only if `test_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._test_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def test_function(iterator):
"""Runs a test execution with a single step."""
return step_function(self, iterator)
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
if self._cluster_coordinator:
self.test_function = (
lambda it: self._cluster_coordinator.schedule(
test_function, args=(it,)
)
)
else:
self.test_function = test_function
# If we're using a coordinator, use the value of
# self._steps_per_execution at the time the function is
# called/scheduled, and not when it is actually executed.
elif self._cluster_coordinator:
def test_function(iterator, steps_per_execution):
"""Runs a test execution with multiple steps."""
for _ in tf.range(steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
self.test_function = lambda it: self._cluster_coordinator.schedule(
test_function, args=(it, self._steps_per_execution.value())
)
else:
def test_function(iterator):
"""Runs a test execution with multiple steps."""
for _ in tf.range(self._steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
self.test_function = test_function
return self.test_function
@traceback_utils.filter_traceback
def evaluate(
self,
x=None,
y=None,
batch_size=None,
verbose="auto",
sample_weight=None,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
return_dict=False,
**kwargs,
):
"""Returns the loss value & metrics values for the model in test mode.
Computation is done in batches (see the `batch_size` arg.)
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A `tf.data` dataset. Should return a tuple
of either `(inputs, targets)` or
`(inputs, targets, sample_weights)`.
- A generator or `keras.utils.Sequence` returning `(inputs,
targets)` or `(inputs, targets, sample_weights)`.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given in the `Unpacking
behavior for iterator-like inputs` section of `Model.fit`.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s). It should be consistent with `x`
(you cannot have Numpy inputs and tensor targets, or inversely).
If `x` is a dataset, generator or `keras.utils.Sequence` instance,
`y` should not be specified (since targets will be obtained from
the iterator/dataset).
batch_size: Integer or `None`. Number of samples per batch of
computation. If unspecified, `batch_size` will default to 32. Do
not specify the `batch_size` if your data is in the form of a
dataset, generators, or `keras.utils.Sequence` instances (since
they generate batches).
verbose: `"auto"`, 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = single line.
`"auto"` becomes 1 for most cases, and to 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so `verbose=2` is
recommended when not running interactively (e.g. in a production
environment). Defaults to 'auto'.
sample_weight: Optional Numpy array of weights for the test samples,
used for weighting the loss function. You can either pass a flat
(1D) Numpy array with the same length as the input samples
(1:1 mapping between weights and samples), or in the case of
temporal data, you can pass a 2D array with shape `(samples,
sequence_length)`, to apply a different weight to every
timestep of every sample. This argument is not supported when
`x` is a dataset, instead pass sample weights as the third
element of `x`.
steps: Integer or `None`. Total number of steps (batches of samples)
before declaring the evaluation round finished. Ignored with the
default value of `None`. If x is a `tf.data` dataset and `steps`
is None, 'evaluate' will run until the dataset is exhausted. This
argument is not supported with array inputs.
callbacks: List of `keras.callbacks.Callback` instances. List of
callbacks to apply during evaluation. See
[callbacks](https://www.tensorflow.org/api_docs/python/tf/tf_keras/callbacks).
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the generator
queue. If unspecified, `max_queue_size` will default to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, `workers` will default to
1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
**kwargs: Unused at this time.
See the discussion of `Unpacking behavior for iterator-like inputs` for
`Model.fit`.
Returns:
Scalar test 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 scalar outputs.
Raises:
RuntimeError: If `model.evaluate` is wrapped in a `tf.function`.
"""
version_utils.disallow_legacy_graph("Model", "evaluate")
self._assert_compile_was_called()
self._check_call_args("evaluate")
self._check_sample_weight_warning(x, sample_weight)
_disallow_inside_tf_function("evaluate")
use_cached_eval_dataset = kwargs.pop("_use_cached_eval_dataset", False)
if kwargs:
raise TypeError(f"Invalid keyword arguments: {list(kwargs.keys())}")
if self.distribute_strategy._should_use_with_coordinator:
self._cluster_coordinator = (
tf.distribute.experimental.coordinator.ClusterCoordinator(
self.distribute_strategy
)
)
verbose = _get_verbosity(verbose, self.distribute_strategy)
if self._pss_evaluation_shards:
self._disallow_exact_eval_with_add_metrics()
with self.distribute_strategy.scope():
# Use cached evaluation data only when it's called in `Model.fit`
if (
use_cached_eval_dataset
and getattr(self, "_eval_data_handler", None) is not None
):
data_handler = self._eval_data_handler
else:
# Creates a `tf.data.Dataset` and handles batch and epoch
# iteration.
data_handler = data_adapter.get_data_handler(
x=x,
y=y,
sample_weight=sample_weight,
batch_size=batch_size,
steps_per_epoch=steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
pss_evaluation_shards=self._pss_evaluation_shards,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=1,
steps=data_handler.inferred_steps,
)
# Initialize to prevent errors if 0 epochs are evaluated.
logs = {}
test_function_runner = self._get_test_function_runner(callbacks)
self._test_counter.assign(0)
callbacks.on_test_begin()
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
for (
_,
dataset_or_iterator,
) in data_handler.enumerate_epochs(): # Single epoch.
self.reset_metrics()
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
with tf.profiler.experimental.Trace(
"test", step_num=step, _r=1
):
callbacks.on_test_batch_begin(step)
logs = test_function_runner.run_step(
dataset_or_iterator,
data_handler,
step,
self._pss_evaluation_shards,
)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
# Override with model metrics instead of last step logs
if self._pss_evaluation_shards:
logs = self._aggregate_exact_metrics(logs)
else:
logs = self._validate_and_get_metrics_result(logs)
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_test_end(logs=logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def _disallow_exact_eval_with_add_metrics(self):
metrics_from_add_metric = [
metric
for layer in self._flatten_layers()
for metric in layer._metrics
]
compiled_metrics = self.compiled_metrics.metrics
if any(
[
metric not in compiled_metrics
for metric in metrics_from_add_metric
]
):
raise ValueError(
"Detected that a metric was added to this model "
"via `Model.add_metric`. This is not currently "
"supported when using exact evaluation with "
"`tf.distribute.ParameterServerStrategy`."
)
def _infer_exact_eval_shards(self, pss_evaluation_shards):
if not self.distribute_strategy._should_use_with_coordinator:
return 0
if pss_evaluation_shards == "auto":
# TODO(b/264265138) evaluate and improve this heuristic
return self.distribute_strategy._num_workers * 5
return pss_evaluation_shards
def _get_test_function_runner(self, callbacks):
if (
self._pss_evaluation_shards
and self.distribute_strategy._should_use_with_coordinator
):
self.test_function = self._make_test_function_exact()
test_function_runner = _ExactTestFunction(
self.test_function, callbacks
)
else:
self.test_function = self.make_test_function()
test_function_runner = _TestFunction(self.test_function, callbacks)
return test_function_runner
def predict_step(self, data):
"""The logic for one inference step.
This method can be overridden to support custom inference logic.
This method is called by `Model.make_predict_function`.
This method should contain the mathematical logic for one step of
inference. This typically includes the forward pass.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_predict_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
The result of one inference step, typically the output of calling the
`Model` on data.
"""
x, _, _ = data_adapter.unpack_x_y_sample_weight(data)
return self(x, training=False)
def make_predict_function(self, force=False):
"""Creates a function that executes one step of inference.
This method can be overridden to support custom inference logic.
This method is called by `Model.predict` and `Model.predict_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.predict_step`.
This function is cached the first time `Model.predict` or
`Model.predict_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the predict function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return the outputs of the `Model`.
"""
if self.predict_function is not None and not force:
return self.predict_function
def step_function(model, iterator):
"""Runs a single evaluation step."""
def run_step(data):
outputs = model.predict_step(data)
# Ensure counter is updated only if `test_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._predict_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs, self.distribute_strategy, reduction="concat"
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def predict_function(iterator):
"""Runs an evaluation execution with a single step."""
return step_function(self, iterator)
else:
def predict_function(iterator):
"""Runs an evaluation execution with multiple steps."""
outputs = step_function(self, iterator)
for _ in tf.range(self._steps_per_execution - 1):
tf.autograph.experimental.set_loop_options(
shape_invariants=[
(
outputs,
tf.nest.map_structure(
lambda t: tf_utils.get_tensor_spec(
t, dynamic_batch=True
).shape,
outputs,
),
)
]
)
step_outputs = step_function(self, iterator)
outputs = tf.nest.map_structure(
lambda t1, t2: concat([t1, t2]), outputs, step_outputs
)
return outputs
if not self.run_eagerly:
predict_function = tf.function(
predict_function, reduce_retracing=True
)
self.predict_function = predict_function
return self.predict_function
@traceback_utils.filter_traceback
def predict(
self,
x,
batch_size=None,
verbose="auto",
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
):
"""Generates output predictions for the input samples.
Computation is done in batches. This method is designed for batch
processing of large numbers of inputs. It is not intended for use inside
of loops that iterate over your data and process small numbers of inputs
at a time.
For small numbers of inputs that fit in one batch,
directly use `__call__()` for faster execution, e.g.,
`model(x)`, or `model(x, training=False)` if you have layers such as
`tf.keras.layers.BatchNormalization` that behave differently during
inference. You may pair the individual model call with a `tf.function`
for additional performance inside your inner loop.
If you need access to numpy array values instead of tensors after your
model call, you can use `tensor.numpy()` to get the numpy array value of
an eager tensor.
Also, note the fact that test loss is not affected by
regularization layers like noise and dropout.
Note: See [this FAQ entry](
https://keras.io/getting_started/faq/#whats-the-difference-between-model-methods-predict-and-call)
for more details about the difference between `Model` methods
`predict()` and `__call__()`.
Args:
x: Input samples. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A `tf.data` dataset.
- A generator or `keras.utils.Sequence` instance.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given in the `Unpacking
behavior for iterator-like inputs` section of `Model.fit`.
batch_size: Integer or `None`.
Number of samples per batch.
If unspecified, `batch_size` will default to 32.
Do not specify the `batch_size` if your data is in the
form of dataset, generators, or `keras.utils.Sequence` instances
(since they generate batches).
verbose: `"auto"`, 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = single line.
`"auto"` becomes 1 for most cases, and to 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so `verbose=2` is
recommended when not running interactively (e.g. in a production
environment). Defaults to 'auto'.
steps: Total number of steps (batches of samples)
before declaring the prediction round finished.
Ignored with the default value of `None`. If x is a `tf.data`
dataset and `steps` is None, `predict()` will
run until the input dataset is exhausted.
callbacks: List of `keras.callbacks.Callback` instances.
List of callbacks to apply during prediction.
See [callbacks](
https://www.tensorflow.org/api_docs/python/tf/tf_keras/callbacks).
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the
generator queue. If unspecified, `max_queue_size` will default
to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, `workers` will default
to 1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
See the discussion of `Unpacking behavior for iterator-like inputs` for
`Model.fit`. Note that Model.predict uses the same interpretation rules
as `Model.fit` and `Model.evaluate`, so inputs must be unambiguous for
all three methods.
Returns:
Numpy array(s) of predictions.
Raises:
RuntimeError: If `model.predict` is wrapped in a `tf.function`.
ValueError: In case of mismatch between the provided
input data and the model's expectations,
or in case a stateful model receives a number of samples
that is not a multiple of the batch size.
"""
version_utils.disallow_legacy_graph("Model", "predict")
self._check_call_args("predict")
_disallow_inside_tf_function("predict")
# TODO(yashkatariya): Cache model on the coordinator for faster
# prediction. If running under PSS, then swap it with OneDeviceStrategy
# so that execution will run on the coordinator.
original_pss_strategy = None
if self.distribute_strategy._should_use_with_coordinator:
original_pss_strategy = self.distribute_strategy
self._distribution_strategy = None
# Cluster coordinator is set by `.fit()` and `.evaluate()` which is not
# needed in `.predict()` because all the predictions happen on the
# coordinator/locally.
if self._cluster_coordinator:
self._cluster_coordinator = None
verbose = _get_verbosity(verbose, self.distribute_strategy)
outputs = None
with self.distribute_strategy.scope():
# Creates a `tf.data.Dataset` and handles batch and epoch iteration.
dataset_types = (tf.compat.v1.data.Dataset, tf.data.Dataset)
if (
self._in_multi_worker_mode()
or _is_tpu_multi_host(self.distribute_strategy)
) and isinstance(x, dataset_types):
try:
options = tf.data.Options()
data_option = tf.data.experimental.AutoShardPolicy.DATA
options.experimental_distribute.auto_shard_policy = (
data_option
)
x = x.with_options(options)
except ValueError:
warnings.warn(
"Using Model.predict with MultiWorkerMirroredStrategy "
"or TPUStrategy and AutoShardPolicy.FILE might lead to "
"out-of-order result. Consider setting it to "
"AutoShardPolicy.DATA.",
stacklevel=2,
)
data_handler = data_adapter.get_data_handler(
x=x,
batch_size=batch_size,
steps_per_epoch=steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=1,
steps=data_handler.inferred_steps,
)
self.predict_function = self.make_predict_function()
self._predict_counter.assign(0)
callbacks.on_predict_begin()
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
batch_outputs = None
for _, iterator in data_handler.enumerate_epochs(): # Single epoch.
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
callbacks.on_predict_batch_begin(step)
tmp_batch_outputs = self.predict_function(iterator)
if data_handler.should_sync:
context.async_wait()
batch_outputs = (
tmp_batch_outputs # No error, now safe to assign.
)
if outputs is None:
outputs = tf.nest.map_structure(
lambda batch_output: [batch_output],
batch_outputs,
)
else:
tf.__internal__.nest.map_structure_up_to(
batch_outputs,
lambda output, batch_output: output.append(
batch_output
),
outputs,
batch_outputs,
)
end_step = step + data_handler.step_increment
callbacks.on_predict_batch_end(
end_step, {"outputs": batch_outputs}
)
if batch_outputs is None:
raise ValueError(
"Unexpected result of `predict_function` "
"(Empty batch_outputs). Please use "
"`Model.compile(..., run_eagerly=True)`, or "
"`tf.config.run_functions_eagerly(True)` for more "
"information of where went wrong, or file a "
"issue/bug to `tf.keras`."
)
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_predict_end()
all_outputs = tf.__internal__.nest.map_structure_up_to(
batch_outputs, potentially_ragged_concat, outputs
)
# If originally PSS strategy was used, then replace it back since
# predict is running under `OneDeviceStrategy` after the swap and once
# its done we need to replace it back to PSS again.
if original_pss_strategy is not None:
self._distribution_strategy = original_pss_strategy
return tf_utils.sync_to_numpy_or_python_type(all_outputs)
def reset_metrics(self):
"""Resets the state of all the metrics in the model.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> _ = model.fit(x, y, verbose=0)
>>> assert all(float(m.result()) for m in model.metrics)
>>> model.reset_metrics()
>>> assert all(float(m.result()) == 0 for m in model.metrics)
"""
for m in self.metrics:
m.reset_state()
def train_on_batch(
self,
x,
y=None,
sample_weight=None,
class_weight=None,
reset_metrics=True,
return_dict=False,
):
"""Runs a single gradient update on a single batch of data.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s).
sample_weight: Optional array of the same length as x, containing
weights to apply to the model's loss for each sample. In the case
of temporal data, you can pass a 2D array with shape (samples,
sequence_length), to apply a different weight to every timestep of
every sample.
class_weight: Optional dictionary mapping class indices (integers)
to a weight (float) to apply to the model's loss for the samples
from this class during training. This can be useful to tell the
model to "pay more attention" to samples from an under-represented
class. When `class_weight` is specified and targets have a rank of
2 or greater, either `y` must be one-hot encoded, or an explicit
final dimension of `1` must be included for sparse class labels.
reset_metrics: If `True`, the metrics returned will be only for this
batch. If `False`, the metrics will be statefully accumulated
across batches.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
Returns:
Scalar training 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 scalar outputs.
Raises:
RuntimeError: If `model.train_on_batch` is wrapped in a `tf.function`.
"""
self._assert_compile_was_called()
self._check_call_args("train_on_batch")
_disallow_inside_tf_function("train_on_batch")
if reset_metrics:
self.reset_metrics()
with self.distribute_strategy.scope(), training_utils.RespectCompiledTrainableState( # noqa: E501
self
):
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x, y, sample_weight, class_weight
)
self.train_function = self.make_train_function()
logs = self.train_function(iterator)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def test_on_batch(
self,
x,
y=None,
sample_weight=None,
reset_metrics=True,
return_dict=False,
):
"""Test the model on a single batch of samples.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays (in case the
model has multiple inputs).
- A TensorFlow tensor, or a list of tensors (in case the model has
multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s). It should be consistent with `x`
(you cannot have Numpy inputs and tensor targets, or inversely).
sample_weight: Optional array of the same length as x, containing
weights to apply to the model's loss for each sample. In the case
of temporal data, you can pass a 2D array with shape (samples,
sequence_length), to apply a different weight to every timestep of
every sample.
reset_metrics: If `True`, the metrics returned will be only for this
batch. If `False`, the metrics will be statefully accumulated
across batches.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
Returns:
Scalar test 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 scalar outputs.
Raises:
RuntimeError: If `model.test_on_batch` is wrapped in a
`tf.function`.
"""
self._assert_compile_was_called()
self._check_call_args("test_on_batch")
_disallow_inside_tf_function("test_on_batch")
if reset_metrics:
self.reset_metrics()
with self.distribute_strategy.scope():
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x, y, sample_weight
)
self.test_function = self.make_test_function()
logs = self.test_function(iterator)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def predict_on_batch(self, x):
"""Returns predictions for a single batch of samples.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays (in case the
model has multiple inputs).
- A TensorFlow tensor, or a list of tensors (in case the model has
multiple inputs).
Returns:
Numpy array(s) of predictions.
Raises:
RuntimeError: If `model.predict_on_batch` is wrapped in a
`tf.function`.
"""
self._check_call_args("predict_on_batch")
_disallow_inside_tf_function("predict_on_batch")
with self.distribute_strategy.scope():
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x
)
self.predict_function = self.make_predict_function()
outputs = self.predict_function(iterator)
return tf_utils.sync_to_numpy_or_python_type(outputs)
@doc_controls.do_not_generate_docs
def fit_generator(
self,
generator,
steps_per_epoch=None,
epochs=1,
verbose=1,
callbacks=None,
validation_data=None,
validation_steps=None,
validation_freq=1,
class_weight=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
shuffle=True,
initial_epoch=0,
):
"""Fits the model on data yielded batch-by-batch by a Python generator.
DEPRECATED:
`Model.fit` now supports generators, so there is no longer any need to
use this endpoint.
"""
warnings.warn(
"`Model.fit_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.fit`, which supports generators.",
stacklevel=2,
)
return self.fit(
generator,
steps_per_epoch=steps_per_epoch,
epochs=epochs,
verbose=verbose,
callbacks=callbacks,
validation_data=validation_data,
validation_steps=validation_steps,
validation_freq=validation_freq,
class_weight=class_weight,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
shuffle=shuffle,
initial_epoch=initial_epoch,
)
@doc_controls.do_not_generate_docs
def evaluate_generator(
self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0,
):
"""Evaluates the model on a data generator.
DEPRECATED:
`Model.evaluate` now supports generators, so there is no longer any
need to use this endpoint.
"""
warnings.warn(
"`Model.evaluate_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.evaluate`, which supports generators.",
stacklevel=2,
)
self._check_call_args("evaluate_generator")
return self.evaluate(
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks,
)
@doc_controls.do_not_generate_docs
def predict_generator(
self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0,
):
"""Generates predictions for the input samples from a data generator.
DEPRECATED:
`Model.predict` now supports generators, so there is no longer any
need to use this endpoint.
"""
warnings.warn(
"`Model.predict_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.predict`, which supports generators.",
stacklevel=2,
)
return self.predict(
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks,
)
######################################################################
# Functions below are not training related. They are for model weights
# tracking, save/load, serialization, etc.
######################################################################
@property
def trainable_weights(self):
self._assert_weights_created()
if not self._trainable:
return []
trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
trainable_variables += trackable_obj.trainable_variables
trainable_variables += self._trainable_weights
return self._dedup_weights(trainable_variables)
@property
def non_trainable_weights(self):
self._assert_weights_created()
non_trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
non_trainable_variables += trackable_obj.non_trainable_variables
if not self._trainable:
# Return order is all trainable vars, then all non-trainable vars.
trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
trainable_variables += trackable_obj.trainable_variables
non_trainable_variables = (
trainable_variables
+ self._trainable_weights
+ non_trainable_variables
+ self._non_trainable_weights
)
else:
non_trainable_variables = (
non_trainable_variables + self._non_trainable_weights
)
return self._dedup_weights(non_trainable_variables)
def get_weights(self):
"""Retrieves the weights of the model.
Returns:
A flat list of Numpy arrays.
"""
with self.distribute_strategy.scope():
return super().get_weights()
@traceback_utils.filter_traceback
def save(self, 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.models.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.models.save_model()`.
"""
saving_api.save_model(
self,
filepath=filepath,
overwrite=overwrite,
save_format=save_format,
**kwargs,
)
@traceback_utils.filter_traceback
def save_weights(
self, filepath, overwrite=True, save_format=None, options=None
):
"""Saves all layer weights.
Either saves in HDF5 or in TensorFlow format based on the `save_format`
argument.
When saving in HDF5 format, the weight file has:
- `layer_names` (attribute), a list of strings
(ordered names of model layers).
- For every layer, a `group` named `layer.name`
- For every such layer group, a group attribute `weight_names`,
a list of strings
(ordered names of weights tensor of the layer).
- For every weight in the layer, a dataset
storing the weight value, named after the weight tensor.
When saving in TensorFlow format, all objects referenced by the network
are saved in the same format as `tf.train.Checkpoint`, including any
`Layer` instances or `Optimizer` instances assigned to object
attributes. For networks constructed from inputs and outputs using
`tf.keras.Model(inputs, outputs)`, `Layer` instances used by the network
are tracked/saved automatically. For user-defined classes which inherit
from `tf.keras.Model`, `Layer` instances must be assigned to object
attributes, typically in the constructor. See the documentation of
`tf.train.Checkpoint` and `tf.keras.Model` for details.
While the formats are the same, do not mix `save_weights` and
`tf.train.Checkpoint`. Checkpoints saved by `Model.save_weights` should
be loaded using `Model.load_weights`. Checkpoints saved using
`tf.train.Checkpoint.save` should be restored using the corresponding
`tf.train.Checkpoint.restore`. Prefer `tf.train.Checkpoint` over
`save_weights` for training checkpoints.
The TensorFlow format matches objects and variables by starting at a
root object, `self` for `save_weights`, and greedily matching attribute
names. For `Model.save` this is the `Model`, and for `Checkpoint.save`
this is the `Checkpoint` even if the `Checkpoint` has a model attached.
This means saving a `tf.keras.Model` using `save_weights` and loading
into a `tf.train.Checkpoint` with a `Model` attached (or vice versa)
will not match the `Model`'s variables. See the
[guide to training checkpoints](
https://www.tensorflow.org/guide/checkpoint) for details on
the TensorFlow format.
Args:
filepath: String or PathLike, path to the file to save the weights
to. When saving in TensorFlow format, this is the prefix used
for checkpoint files (multiple files are generated). Note that
the '.h5' suffix causes weights to be saved in HDF5 format.
overwrite: Whether to silently overwrite any existing file at the
target location, or provide the user with a manual prompt.
save_format: Either 'tf' or 'h5'. A `filepath` ending in '.h5' or
'.keras' will default to HDF5 if `save_format` is `None`.
Otherwise, `None` becomes 'tf'. Defaults to `None`.
options: Optional `tf.train.CheckpointOptions` object that specifies
options for saving weights.
Raises:
ImportError: If `h5py` is not available when attempting to save in
HDF5 format.
"""
saving_api.save_weights(
self,
filepath=filepath,
overwrite=overwrite,
save_format=save_format,
options=options,
)
@traceback_utils.filter_traceback
def load_weights(
self, filepath, skip_mismatch=False, by_name=False, options=None
):
"""Loads all layer weights from a saved files.
The saved file could be a SavedModel file, a `.keras` file (v3 saving
format), or a file created via `model.save_weights()`.
By default, weights are loaded based on the network's
topology. This means the architecture should be the same as when the
weights were saved. Note that layers that don't have weights are not
taken into account in the topological ordering, so adding or removing
layers is fine as long as they don't have weights.
**Partial weight loading**
If you have modified your model, for instance by adding a new layer
(with weights) or by changing the shape of the weights of a layer,
you can choose to ignore errors and continue loading
by setting `skip_mismatch=True`. In this case any layer with
mismatching weights will be skipped. A warning will be displayed
for each skipped layer.
**Weight loading by name**
If your weights are saved as a `.h5` file created
via `model.save_weights()`, you can use the argument `by_name=True`.
In this case, weights are loaded into layers only if they share
the same name. This is useful for fine-tuning or transfer-learning
models where some of the layers have changed.
Note that only topological loading (`by_name=False`) is supported when
loading weights from the `.keras` v3 format or from the TensorFlow
SavedModel format.
Args:
filepath: String, path to the weights file to load. For weight files
in TensorFlow format, this is the file prefix (the same as was
passed to `save_weights()`). This can also be a path to a
SavedModel or a `.keras` file (v3 saving format) saved
via `model.save()`.
skip_mismatch: Boolean, whether to skip loading of layers where
there is a mismatch in the number of weights, or a mismatch in
the shape of the weights.
by_name: Boolean, whether to load weights by name or by topological
order. Only topological loading is supported for weight files in
the `.keras` v3 format or in the TensorFlow SavedModel format.
options: Optional `tf.train.CheckpointOptions` object that specifies
options for loading weights (only valid for a SavedModel file).
"""
return saving_api.load_weights(
self,
filepath=filepath,
by_name=by_name,
skip_mismatch=skip_mismatch,
options=options,
)
def _updated_config(self):
"""Util shared between different serialization methods.
Returns:
Model config with TF-Keras version information added.
"""
from tf_keras.src import __version__ as keras_version
config = self.get_config()
model_config = {
"class_name": self.__class__.__name__,
"config": config,
"keras_version": keras_version,
"backend": backend.backend(),
}
return model_config
@generic_utils.default
def get_config(self):
"""Returns the config of the `Model`.
Config is a Python dictionary (serializable) containing the
configuration of an object, which in this case is a `Model`. This allows
the `Model` to be be reinstantiated later (without its trained weights)
from this configuration.
Note that `get_config()` does not guarantee to return a fresh copy of
dict every time it is called. The callers should make a copy of the
returned dict if they want to modify it.
Developers of subclassed `Model` are advised to override this method,
and continue to update the dict from `super(MyModel, self).get_config()`
to provide the proper configuration of this `Model`. The default config
will return config dict for init parameters if they are basic types.
Raises `NotImplementedError` when in cases where a custom
`get_config()` implementation is required for the subclassed model.
Returns:
Python dictionary containing the configuration of this `Model`.
"""
# If sublcass doesn't implement `get_config()` parse from init args
# otherwise default to empty dict
if generic_utils.is_default(self.get_config):
try:
config = base_layer.Layer.get_config(self)
except NotImplementedError:
config = {}
logging.warning(
"Model's `__init__()` arguments contain non-serializable "
"objects. Please implement a `get_config()` method in the "
"subclassed Model for proper saving and loading. "
"Defaulting to empty config."
)
else:
config = {}
return config
@classmethod
def from_config(cls, config, custom_objects=None):
# `from_config` assumes `cls` is either `Functional` or a child class of
# `Functional`. In the case that `cls` is meant to behave like a child
# class of `Functional` but only inherits from the `Model` class, we
# have to call `cls(...)` instead of `Functional.from_config`.
from tf_keras.src.engine import functional
with serialization.SharedObjectLoadingScope():
functional_config_keys = [
"name",
"layers",
"input_layers",
"output_layers",
]
is_functional_config = all(
key in config for key in functional_config_keys
)
argspec = tf_inspect.getfullargspec(cls.__init__)
functional_init_args = tf_inspect.getfullargspec(
functional.Functional.__init__
).args[1:]
revivable_as_functional = (
cls in {functional.Functional, Model}
or argspec.args[1:] == functional_init_args
or (argspec.varargs == "args" and argspec.varkw == "kwargs")
)
if is_functional_config and revivable_as_functional:
# Revive Functional model
# (but not Functional subclasses with a custom __init__)
inputs, outputs, layers = functional.reconstruct_from_config(
config, custom_objects
)
model = cls(
inputs=inputs, outputs=outputs, name=config.get("name")
)
functional.connect_ancillary_layers(model, layers)
else:
# Either the model has a custom __init__, or the config
# does not contain all the information necessary to
# revive a Functional model. This happens when the user creates
# subclassed models where `get_config()` is returning
# insufficient information to be considered a Functional model.
# In this case, we fall back to provide all config into the
# constructor of the class.
try:
model = cls(**config)
except TypeError as e:
raise TypeError(
"Unable to revive model from config. When overriding "
"the `get_config()` method, make sure that the "
"returned config contains all items used as arguments "
f"in the constructor to {cls}, "
"which is the default behavior. "
"You can override this default behavior by defining a "
"`from_config(cls, config)` class method to specify "
"how to create an "
f"instance of {cls.__name__} from its config.\n\n"
f"Received config={config}\n\n"
f"Error encountered during deserialization: {e}"
)
return model
def to_json(self, **kwargs):
"""Returns a JSON string containing the network configuration.
To load a network from a JSON save file, use
`keras.models.model_from_json(json_string, custom_objects={})`.
Args:
**kwargs: Additional keyword arguments to be passed to
*`json.dumps()`.
Returns:
A JSON string.
"""
model_config = self._updated_config()
return json.dumps(
model_config, default=json_utils.get_json_type, **kwargs
)
def to_yaml(self, **kwargs):
"""Returns a yaml string containing the network configuration.
Note: Since TF 2.6, this method is no longer supported and will raise a
RuntimeError.
To load a network from a yaml save file, use
`keras.models.model_from_yaml(yaml_string, custom_objects={})`.
`custom_objects` should be a dictionary mapping
the names of custom losses / layers / etc to the corresponding
functions / classes.
Args:
**kwargs: Additional keyword arguments
to be passed to `yaml.dump()`.
Returns:
A YAML string.
Raises:
RuntimeError: announces that the method poses a security risk
"""
raise RuntimeError(
"Method `model.to_yaml()` has been removed due to security risk of "
"arbitrary code execution. Please use `model.to_json()` instead."
)
def reset_states(self):
for layer in self.layers:
if hasattr(layer, "reset_states") and getattr(
layer, "stateful", False
):
layer.reset_states()
@property
@doc_controls.do_not_generate_docs
def state_updates(self):
"""Deprecated, do NOT use!
Returns the `updates` from all layers that are stateful.
This is useful for separating training updates and
state updates, e.g. when we need to update a layer's internal state
during prediction.
Returns:
A list of update ops.
"""
warnings.warn(
"`Model.state_updates` will be removed in a future version. "
"This property should not be used in TensorFlow 2.0, "
"as `updates` are applied automatically.",
stacklevel=2,
)
state_updates = []
for layer in self.layers:
if getattr(layer, "stateful", False):
if hasattr(layer, "updates"):
state_updates += layer.updates
return state_updates
@property
def weights(self):
"""Returns the list of all layer variables/weights.
Note: This will not track the weights of nested `tf.Modules` that are
not themselves TF-Keras layers.
Returns:
A list of variables.
"""
return self._dedup_weights(self._undeduplicated_weights)
@property
def _undeduplicated_weights(self):
"""Returns the undeduplicated list of all layer variables/weights."""
self._assert_weights_created()
weights = []
for layer in self._self_tracked_trackables:
weights += layer.variables
weights += self._trainable_weights + self._non_trainable_weights
return weights
def summary(
self,
line_length=None,
positions=None,
print_fn=None,
expand_nested=False,
show_trainable=False,
layer_range=None,
):
"""Prints a string summary of the network.
Args:
line_length: Total length of printed lines
(e.g. set this to adapt the display to different
terminal window sizes).
positions: Relative or absolute positions of log elements
in each line. If not provided, becomes
`[0.3, 0.6, 0.70, 1.]`. Defaults to `None`.
print_fn: Print function to use. By default, prints to `stdout`.
If `stdout` doesn't work in your environment, change to `print`.
It will be called on each line of the summary.
You can set it to a custom function
in order to capture the string summary.
expand_nested: Whether to expand the nested models.
Defaults to `False`.
show_trainable: Whether to show if a layer is trainable.
Defaults to `False`.
layer_range: a list or tuple of 2 strings,
which is the starting layer name and ending layer name
(both inclusive) indicating the range of layers to be printed
in summary. It also accepts regex patterns instead of exact
name. In such case, start predicate will be the first element
it matches to `layer_range[0]` and the end predicate will be
the last element it matches to `layer_range[1]`.
By default `None` which considers all layers of model.
Raises:
ValueError: if `summary()` is called before the model is built.
"""
if not self.built:
raise ValueError(
"This model has not yet been built. "
"Build the model first by calling `build()` or by calling "
"the model on a batch of data."
)
layer_utils.print_summary(
self,
line_length=line_length,
positions=positions,
print_fn=print_fn,
expand_nested=expand_nested,
show_trainable=show_trainable,
layer_range=layer_range,
)
@property
def layers(self):
return list(self._flatten_layers(include_self=False, recursive=False))
@layers.setter
def layers(self, _):
raise AttributeError(
"`Model.layers` attribute is reserved and should not be used. "
"Please use another name."
)
def get_layer(self, name=None, index=None):
"""Retrieves a layer based on either its name (unique) or index.
If `name` and `index` are both provided, `index` will take precedence.
Indices are based on order of horizontal graph traversal (bottom-up).
Args:
name: String, name of layer.
index: Integer, index of layer.
Returns:
A layer instance.
"""
# TODO(fchollet): We could build a dictionary based on layer names
# since they are constant, but we have not done that yet.
if index is not None and name is not None:
raise ValueError(
"Provide only a layer name or a layer index. Received: "
f"index={index}, name={name}."
)
if index is not None:
if len(self.layers) <= index:
raise ValueError(
f"Was asked to retrieve layer at index {index}"
f" but model only has {len(self.layers)}"
" layers."
)
else:
return self.layers[index]
if name is not None:
for layer in self.layers:
if layer.name == name:
return layer
raise ValueError(
f"No such layer: {name}. Existing layers are: "
f"{list(layer.name for layer in self.layers)}."
)
raise ValueError(
"Provide either a layer name or layer index at `get_layer`."
)
def get_weight_paths(self):
"""Retrieve all the variables and their paths for the model.
The variable path (string) is a stable key to identify a `tf.Variable`
instance owned by the model. It can be used to specify variable-specific
configurations (e.g. DTensor, quantization) from a global view.
This method returns a dict with weight object paths as keys
and the corresponding `tf.Variable` instances as values.
Note that if the model is a subclassed model and the weights haven't
been initialized, an empty dict will be returned.
Returns:
A dict where keys are variable paths and values are `tf.Variable`
instances.
Example:
```python
class SubclassModel(tf.keras.Model):
def __init__(self, name=None):
super().__init__(name=name)
self.d1 = tf.keras.layers.Dense(10)
self.d2 = tf.keras.layers.Dense(20)
def call(self, inputs):
x = self.d1(inputs)
return self.d2(x)
model = SubclassModel()
model(tf.zeros((10, 10)))
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': model.d1.kernel,
# 'd1.bias': model.d1.bias,
# 'd2.kernel': model.d2.kernel,
# 'd2.bias': model.d2.bias,
# }
# Functional model
inputs = tf.keras.Input((10,), batch_size=10)
x = tf.keras.layers.Dense(20, name='d1')(inputs)
output = tf.keras.layers.Dense(30, name='d2')(x)
model = tf.keras.Model(inputs, output)
d1 = model.layers[1]
d2 = model.layers[2]
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': d1.kernel,
# 'd1.bias': d1.bias,
# 'd2.kernel': d2.kernel,
# 'd2.bias': d2.bias,
# }
```
"""
result = {}
(
descendants,
object_paths_dict,
) = tf.__internal__.tracking.ObjectGraphView(
self
).breadth_first_traversal()
for descendant in descendants:
if isinstance(descendant, tf.Variable):
trackable_references = object_paths_dict[descendant]
object_path = ".".join([t.name for t in trackable_references])
result[object_path] = descendant
return result
def get_compile_config(self):
"""Returns a serialized config with information for compiling the model.
This method returns a config dictionary containing all the information
(optimizer, loss, metrics, etc.) with which the model was compiled.
Returns:
A dict containing information for compiling the model.
"""
if self._is_compiled and hasattr(self, "_compile_config"):
return self._compile_config.serialize()
def compile_from_config(self, config):
"""Compiles the model with the information given in config.
This method uses the information in the config (optimizer, loss,
metrics, etc.) to compile the model.
Args:
config: Dict containing information for compiling the model.
"""
has_overridden_compile = self.__class__.compile != Model.compile
if has_overridden_compile:
logging.warning(
"`compile()` was not called as part of model loading "
"because the model's `compile()` method is custom. "
"All subclassed Models that have `compile()` "
"overridden should also override "
"`get_compile_config()` and `compile_from_config(config)`. "
"Alternatively, you can "
"call `compile()` manually after loading."
)
return
config = saving_lib.deserialize_keras_object(config)
self.compile(**config)
if (
hasattr(self, "optimizer")
# Exempt legacy optimizers.
and isinstance(self.optimizer, optimizer.Optimizer)
and self.built
):
# Create optimizer variables.
self.optimizer.build(self.trainable_variables)
def export(self, filepath):
"""Create a SavedModel artifact for inference (e.g. via TF-Serving).
This method lets you export a model to a lightweight SavedModel artifact
that contains the model's forward pass only (its `call()` method)
and can be served via e.g. TF-Serving. The forward pass is registered
under the name `serve()` (see example below).
The original code of the model (including any custom layers you may
have used) is *no longer* necessary to reload the artifact -- it is
entirely standalone.
Args:
filepath: `str` or `pathlib.Path` object. Path where to save
the artifact.
Example:
```python
# Create the artifact
model.export("path/to/location")
# Later, in a different process / environment...
reloaded_artifact = tf.saved_model.load("path/to/location")
predictions = reloaded_artifact.serve(input_data)
```
If you would like to customize your serving endpoints, you can
use the lower-level `keras.export.ExportArchive` class. The `export()`
method relies on `ExportArchive` internally.
"""
from tf_keras.src.export import export_lib
export_lib.export_model(self, filepath)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _set_save_spec(self, inputs, args=None, kwargs=None):
"""Defines the save spec so that serialization can trace `call()`.
The TensorSpecs of the call function `inputs`, `args`, and `kwargs` are
saved into a tuple of `([inputs] + args, kwargs)`. The input
`TensorSpec` names are updated to match the built `input_names`.
The specs can be retrieved with the `save_spec` property.
Args:
inputs: possibly nested inputs passed into the call function.
args: a list of positional arguments passed into call.
kwargs: a dictionary of keyword arguments passed into call.
"""
if self._saved_model_inputs_spec is not None:
return # Already set.
args = args or []
kwargs = kwargs or {}
input_names = self.input_names
if not input_names:
input_names = compile_utils.create_pseudo_input_names(inputs)
flat_inputs = tf.nest.flatten(inputs)
inputs_spec = []
for name, tensor in zip(input_names, flat_inputs):
inputs_spec.append(
tf_utils.get_tensor_spec(tensor, dynamic_batch=False, name=name)
)
inputs_spec = tf.nest.pack_sequence_as(inputs, inputs_spec)
super()._set_save_spec(inputs_spec, args, kwargs)
# Store the input shapes
if (
self.__class__.__name__ == "Sequential"
and self._build_input_shape is None
):
self._build_input_shape = tf.nest.map_structure(
lambda x: None if x is None else x.shape, inputs_spec
)
def save_spec(self, dynamic_batch=True):
"""Returns the `tf.TensorSpec` of call args as a tuple `(args, kwargs)`.
This value is automatically defined after calling the model for the
first time. Afterwards, you can use it when exporting the model for
serving:
```python
model = tf.keras.Model(...)
@tf.function
def serve(*args, **kwargs):
outputs = model(*args, **kwargs)
# Apply postprocessing steps, or add additional outputs.
...
return outputs
# arg_specs is `[tf.TensorSpec(...), ...]`. kwarg_specs, in this
# example, is an empty dict since functional models do not use keyword
# arguments.
arg_specs, kwarg_specs = model.save_spec()
model.save(path, signatures={
'serving_default': serve.get_concrete_function(*arg_specs,
**kwarg_specs)
})
```
Args:
dynamic_batch: Whether to set the batch sizes of all the returned
`tf.TensorSpec` to `None`. (Note that when defining functional or
Sequential models with `tf.keras.Input([...], batch_size=X)`, the
batch size will always be preserved). Defaults to `True`.
Returns:
If the model inputs are defined, returns a tuple `(args, kwargs)`. All
elements in `args` and `kwargs` are `tf.TensorSpec`.
If the model inputs are not defined, returns `None`.
The model inputs are automatically set when calling the model,
`model.fit`, `model.evaluate` or `model.predict`.
"""
return self._get_save_spec(dynamic_batch, inputs_only=False)
def _assert_weights_created(self):
"""Asserts that all the weights for the model have been created.
For a non-dynamic model, the weights must already be created after the
layer has been called. For a dynamic model, the exact list of weights
can never be known for certain since it may change at any time during
execution.
We run this check right before accessing weights or getting the Numpy
value for the current weights. Otherwise, if the layer has never been
called, the user would just get an empty list, which is misleading.
Raises:
ValueError: if the weights of the network have not yet been created.
"""
if self.dynamic:
return
if (
"build" in self.__class__.__dict__
and self.__class__ != Model
and not self.built
):
# For any model that has customized build() method but hasn't been
# invoked yet, this will cover both sequential and subclass model.
# Also make sure to exclude Model class itself which has build()
# defined.
raise ValueError(
f"Weights for model '{self.name}' have not yet been "
"created. "
"Weights are created when the model is first called on "
"inputs or `build()` is called with an `input_shape`."
)
def _check_call_args(self, method_name):
"""Check that `call()` has only one positional arg."""
# Always allow first arg, regardless of arg name.
fullargspec = self._call_spec.full_argspec
if fullargspec.defaults:
positional_args = fullargspec.args[: -len(fullargspec.defaults)]
else:
positional_args = fullargspec.args
if "training" in positional_args:
positional_args.remove("training")
# self and first arg can be positional.
if len(positional_args) > 2:
extra_args = positional_args[2:]
raise ValueError(
f"Models passed to `{method_name}` can only have `training` "
"and the first argument in `call()` as positional arguments, "
f"found: {extra_args}."
)
def _validate_compile(self, optimizer, metrics, **kwargs):
"""Performs validation checks for the default `compile()`."""
if any(
isinstance(opt, optimizer_v1.Optimizer)
for opt in tf.nest.flatten(optimizer)
):
raise ValueError(
f"`tf.compat.v1.keras` Optimizer ({optimizer}) is "
"not supported when eager execution is enabled. Use a "
"`tf.keras` Optimizer instead, or disable eager "
"execution."
)
kwargs.pop("cloning", None) # Legacy DistStrat argument, never used.
kwargs.pop("experimental_run_tf_function", None) # Always `True`.
distribute_arg = kwargs.pop("distribute", None)
if distribute_arg is not None:
raise ValueError(
"`distribute` argument in compile is not available in TF 2.0. "
"Please create the model under the `strategy.scope()`. "
f"Received: {distribute_arg}."
)
target_tensor_arg = kwargs.pop("target_tensors", None)
if target_tensor_arg is not None:
raise ValueError(
"`target_tensors` argument is not supported when executing "
f"eagerly. Received: {target_tensor_arg}."
)
invalid_kwargs = set(kwargs) - {"sample_weight_mode"}
if invalid_kwargs:
raise TypeError(
"Invalid keyword argument(s) in `compile()`: "
f"{(invalid_kwargs,)}. Valid keyword arguments include "
'"cloning", "experimental_run_tf_function", "distribute",'
' "target_tensors", or "sample_weight_mode".'
)
# Model must be created and compiled with the same DistStrat.
if self.built and tf.distribute.has_strategy():
strategy = tf.distribute.get_strategy()
for v in self.variables:
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Variable ({v}) was not created in the distribution "
f"strategy scope of ({strategy}). It is most likely "
"because some layers, model, or optimizer was being "
"created outside the distribution strategy scope. Try "
"to make sure your code looks similar "
"to the following.\nwith strategy.scope():\n"
" model=_create_model()\n"
" model.compile(...)"
)
# Model metrics must be created in the same distribution strategy scope
# as the model.
strategy = self.distribute_strategy
for metric in tf.nest.flatten(metrics):
for v in getattr(metric, "variables", []):
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Metric ({metric}) passed to `model.compile` was "
"created inside a different distribution strategy "
"scope than the model. All metrics must be created "
"in the same distribution strategy "
f"scope as the model (in this case {strategy}). "
"If you pass in a string identifier for a metric to "
"compile, the metric will automatically be created "
"in the correct distribution strategy scope."
)
# Model metrics must be created in the same distribution strategy scope
# as the model.
for opt in tf.nest.flatten(optimizer):
for v in getattr(opt, "_weights", []):
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Optimizer ({optimizer}) passed to `model.compile` "
"was created inside a different distribution strategy "
"scope than the model. All optimizers must be created "
"in the same distribution strategy scope as the model "
f"(in this case {strategy}). If you pass in a string "
"identifier for an optimizer to compile, the optimizer "
"will automatically be created in the correct "
"distribution strategy scope."
)
def _maybe_load_initial_counters_from_ckpt(
self, steps_per_epoch, initial_epoch
):
"""Maybe load initial epoch from ckpt, considering worker recovery.
Refer to tensorflow/python/tf_keras/distribute/worker_training_state.py
for more information.
Args:
steps_per_epoch: The number of step per epoch.
initial_epoch: The original initial_epoch user passes in `fit()`.
mode: The mode for running `model.fit()`.
Returns:
If the training is recovering from previous failure under multi-worker
training setting, return the (epoch, step) the training is supposed to
continue at. Otherwise, return the `initial_epoch, initial_step` the
user passes in.
"""
initial_step = 0
if self._training_state is not None:
return self._training_state.maybe_load_initial_counters_from_ckpt(
steps_per_epoch, initial_epoch, mode=ModeKeys.TRAIN
)
return (initial_epoch, initial_step)
def _assert_compile_was_called(self):
# Checks whether `compile` has been called. If it has been called,
# then the optimizer is set. This is different from whether the
# model is compiled
# (i.e. whether the model is built and its inputs/outputs are set).
if not self._is_compiled:
raise RuntimeError(
"You must compile your model before "
"training/testing. "
"Use `model.compile(optimizer, loss)`."
)
def _check_sample_weight_warning(self, x, sample_weight):
# Datasets can include sample weight, by returning a tuple with the
# structure of `(x, y, sample_weight)`.
sample_weight_present = sample_weight is not None or (
isinstance(x, tf.data.Dataset)
and isinstance(x.element_spec, tuple)
and len(x.element_spec) == 3
)
if (
sample_weight_present
and self.compiled_metrics._user_weighted_metrics is None
):
logging.warning(
"`evaluate()` received a value for `sample_weight`, but "
"`weighted_metrics` were not provided. Did you mean to pass "
"metrics to `weighted_metrics` in `compile()`? If this is "
"intentional you can pass `weighted_metrics=[]` to `compile()` "
"in order to silence this warning."
)
def _set_inputs(self, inputs, outputs=None, training=None):
"""This method is for compat with Modelv1. Only inputs are needed
here."""
self._set_save_spec(inputs)
@property
def _trackable_saved_model_saver(self):
return model_serialization.ModelSavedModelSaver(self)
def _trackable_children(self, save_type="checkpoint", **kwargs):
if save_type == "savedmodel":
# SavedModel needs to ignore the execution functions.
train_function = self.train_function
test_function = self.test_function
predict_function = self.predict_function
train_tf_function = self.train_tf_function
self.train_function = None
self.test_function = None
self.predict_function = None
self.train_tf_function = None
children = super()._trackable_children(save_type, **kwargs)
if save_type == "savedmodel":
self.train_function = train_function
self.test_function = test_function
self.predict_function = predict_function
self.train_tf_function = train_tf_function
return children
def _should_eval(self, epoch, validation_freq):
epoch = epoch + 1 # one-index the user-facing epoch.
if isinstance(validation_freq, int):
return epoch % validation_freq == 0
elif isinstance(validation_freq, list):
return epoch in validation_freq
else:
raise ValueError(
"Expected `validation_freq` to be a list or int. "
f"Received: validation_freq={validation_freq} of the "
f"type {type(validation_freq)}."
)
######################################################################
# Functions below exist only as v1 / v2 compatibility shims.
######################################################################
def _get_compile_args(self, user_metrics=True):
"""Used for saving or cloning a Model.
Args:
user_metrics: Whether to return user-supplied metrics or `Metric`
objects. If True, returns the user-supplied metrics.
Defaults to `True`.
Returns:
Dictionary of arguments that were used when compiling the model.
"""
self._assert_compile_was_called()
saved_metrics = self.compiled_metrics._user_metrics
saved_weighted_metrics = self.compiled_metrics._user_weighted_metrics
if not user_metrics:
if saved_metrics is not None:
saved_metrics = self.compiled_metrics._metrics
if saved_weighted_metrics is not None:
saved_weighted_metrics = self.compiled_metrics._weighted_metrics
compile_args = {
"optimizer": self.optimizer,
"loss": self.compiled_loss._user_losses,
"metrics": saved_metrics,
"weighted_metrics": saved_weighted_metrics,
"loss_weights": self.compiled_loss._user_loss_weights,
}
return compile_args
def _get_callback_model(self):
return self
def _in_multi_worker_mode(self):
return self.distribute_strategy.extended._in_multi_worker_mode()
@property
def _compile_was_called(self):
return self._is_compiled
| (self, x=None, y=None, batch_size=None, epochs=1, verbose='auto', 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_batch_size=None, validation_freq=1, max_queue_size=10, workers=1, use_multiprocessing=False) |
725,014 | tf_keras.src.engine.training | fit_generator | Fits the model on data yielded batch-by-batch by a Python generator.
DEPRECATED:
`Model.fit` now supports generators, so there is no longer any need to
use this endpoint.
| @doc_controls.do_not_generate_docs
def fit_generator(
self,
generator,
steps_per_epoch=None,
epochs=1,
verbose=1,
callbacks=None,
validation_data=None,
validation_steps=None,
validation_freq=1,
class_weight=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
shuffle=True,
initial_epoch=0,
):
"""Fits the model on data yielded batch-by-batch by a Python generator.
DEPRECATED:
`Model.fit` now supports generators, so there is no longer any need to
use this endpoint.
"""
warnings.warn(
"`Model.fit_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.fit`, which supports generators.",
stacklevel=2,
)
return self.fit(
generator,
steps_per_epoch=steps_per_epoch,
epochs=epochs,
verbose=verbose,
callbacks=callbacks,
validation_data=validation_data,
validation_steps=validation_steps,
validation_freq=validation_freq,
class_weight=class_weight,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
shuffle=shuffle,
initial_epoch=initial_epoch,
)
| (self, generator, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None, validation_data=None, validation_steps=None, validation_freq=1, class_weight=None, max_queue_size=10, workers=1, use_multiprocessing=False, shuffle=True, initial_epoch=0) |
725,015 | tf_keras.src.engine.base_layer | get_build_config | Returns a dictionary with the layer's input shape.
This method returns a config dict that can be used by
`build_from_config(config)` to create all states (e.g. Variables and
Lookup tables) needed by the layer.
By default, the config only contains the input shape that the layer
was built with. If you're writing a custom layer that creates state in
an unusual way, you should override this method to make sure this state
is already created when TF-Keras attempts to load its value upon model
loading.
Returns:
A dict containing the input shape associated with the layer.
| def get_build_config(self):
"""Returns a dictionary with the layer's input shape.
This method returns a config dict that can be used by
`build_from_config(config)` to create all states (e.g. Variables and
Lookup tables) needed by the layer.
By default, the config only contains the input shape that the layer
was built with. If you're writing a custom layer that creates state in
an unusual way, you should override this method to make sure this state
is already created when TF-Keras attempts to load its value upon model
loading.
Returns:
A dict containing the input shape associated with the layer.
"""
if self._build_input_shape is not None:
def convert_tensorshapes(x):
if isinstance(x, tf.TensorShape) and x._dims:
return tuple(x.as_list())
return x
return {
"input_shape": tf.nest.map_structure(
convert_tensorshapes, self._build_input_shape
)
}
| (self) |
725,016 | tf_keras.src.engine.training | get_compile_config | Returns a serialized config with information for compiling the model.
This method returns a config dictionary containing all the information
(optimizer, loss, metrics, etc.) with which the model was compiled.
Returns:
A dict containing information for compiling the model.
| def get_compile_config(self):
"""Returns a serialized config with information for compiling the model.
This method returns a config dictionary containing all the information
(optimizer, loss, metrics, etc.) with which the model was compiled.
Returns:
A dict containing information for compiling the model.
"""
if self._is_compiled and hasattr(self, "_compile_config"):
return self._compile_config.serialize()
| (self) |
725,017 | tf_keras.src.engine.training | get_config | Returns the config of the `Model`.
Config is a Python dictionary (serializable) containing the
configuration of an object, which in this case is a `Model`. This allows
the `Model` to be be reinstantiated later (without its trained weights)
from this configuration.
Note that `get_config()` does not guarantee to return a fresh copy of
dict every time it is called. The callers should make a copy of the
returned dict if they want to modify it.
Developers of subclassed `Model` are advised to override this method,
and continue to update the dict from `super(MyModel, self).get_config()`
to provide the proper configuration of this `Model`. The default config
will return config dict for init parameters if they are basic types.
Raises `NotImplementedError` when in cases where a custom
`get_config()` implementation is required for the subclassed model.
Returns:
Python dictionary containing the configuration of this `Model`.
| @generic_utils.default
def get_config(self):
"""Returns the config of the `Model`.
Config is a Python dictionary (serializable) containing the
configuration of an object, which in this case is a `Model`. This allows
the `Model` to be be reinstantiated later (without its trained weights)
from this configuration.
Note that `get_config()` does not guarantee to return a fresh copy of
dict every time it is called. The callers should make a copy of the
returned dict if they want to modify it.
Developers of subclassed `Model` are advised to override this method,
and continue to update the dict from `super(MyModel, self).get_config()`
to provide the proper configuration of this `Model`. The default config
will return config dict for init parameters if they are basic types.
Raises `NotImplementedError` when in cases where a custom
`get_config()` implementation is required for the subclassed model.
Returns:
Python dictionary containing the configuration of this `Model`.
"""
# If sublcass doesn't implement `get_config()` parse from init args
# otherwise default to empty dict
if generic_utils.is_default(self.get_config):
try:
config = base_layer.Layer.get_config(self)
except NotImplementedError:
config = {}
logging.warning(
"Model's `__init__()` arguments contain non-serializable "
"objects. Please implement a `get_config()` method in the "
"subclassed Model for proper saving and loading. "
"Defaulting to empty config."
)
else:
config = {}
return config
| (self) |
725,018 | tf_keras.src.engine.base_layer | get_input_at | 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.
| @doc_controls.do_not_doc_inheritable
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"
)
| (self, node_index) |
725,019 | tf_keras.src.engine.base_layer | get_input_mask_at | 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).
| @doc_controls.do_not_doc_inheritable
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)
| (self, node_index) |
725,020 | tf_keras.src.engine.base_layer | get_input_shape_at | 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.
| @doc_controls.do_not_doc_inheritable
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"
)
| (self, node_index) |
725,021 | tf_keras.src.engine.training | get_layer | Retrieves a layer based on either its name (unique) or index.
If `name` and `index` are both provided, `index` will take precedence.
Indices are based on order of horizontal graph traversal (bottom-up).
Args:
name: String, name of layer.
index: Integer, index of layer.
Returns:
A layer instance.
| def get_layer(self, name=None, index=None):
"""Retrieves a layer based on either its name (unique) or index.
If `name` and `index` are both provided, `index` will take precedence.
Indices are based on order of horizontal graph traversal (bottom-up).
Args:
name: String, name of layer.
index: Integer, index of layer.
Returns:
A layer instance.
"""
# TODO(fchollet): We could build a dictionary based on layer names
# since they are constant, but we have not done that yet.
if index is not None and name is not None:
raise ValueError(
"Provide only a layer name or a layer index. Received: "
f"index={index}, name={name}."
)
if index is not None:
if len(self.layers) <= index:
raise ValueError(
f"Was asked to retrieve layer at index {index}"
f" but model only has {len(self.layers)}"
" layers."
)
else:
return self.layers[index]
if name is not None:
for layer in self.layers:
if layer.name == name:
return layer
raise ValueError(
f"No such layer: {name}. Existing layers are: "
f"{list(layer.name for layer in self.layers)}."
)
raise ValueError(
"Provide either a layer name or layer index at `get_layer`."
)
| (self, name=None, index=None) |
725,022 | tf_keras.src.engine.training | get_metrics_result | Returns the model's metrics values as a dict.
If any of the metric result is a dict (containing multiple metrics),
each of them gets added to the top level returned dict of this method.
Returns:
A `dict` containing values of the metrics listed in `self.metrics`.
Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
| def get_metrics_result(self):
"""Returns the model's metrics values as a dict.
If any of the metric result is a dict (containing multiple metrics),
each of them gets added to the top level returned dict of this method.
Returns:
A `dict` containing values of the metrics listed in `self.metrics`.
Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
# Collect metrics to return
return_metrics = {}
for metric in self.metrics:
result = metric.result()
if isinstance(result, dict):
return_metrics.update(result)
else:
return_metrics[metric.name] = result
return return_metrics
| (self) |
725,023 | tf_keras.src.engine.base_layer | get_output_at | 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.
| @doc_controls.do_not_doc_inheritable
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"
)
| (self, node_index) |
725,024 | tf_keras.src.engine.base_layer | get_output_mask_at | 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).
| @doc_controls.do_not_doc_inheritable
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)
| (self, node_index) |
725,025 | tf_keras.src.engine.base_layer | get_output_shape_at | 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.
| @doc_controls.do_not_doc_inheritable
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"
)
| (self, node_index) |
725,026 | tf_keras.src.engine.training | get_weight_paths | Retrieve all the variables and their paths for the model.
The variable path (string) is a stable key to identify a `tf.Variable`
instance owned by the model. It can be used to specify variable-specific
configurations (e.g. DTensor, quantization) from a global view.
This method returns a dict with weight object paths as keys
and the corresponding `tf.Variable` instances as values.
Note that if the model is a subclassed model and the weights haven't
been initialized, an empty dict will be returned.
Returns:
A dict where keys are variable paths and values are `tf.Variable`
instances.
Example:
```python
class SubclassModel(tf.keras.Model):
def __init__(self, name=None):
super().__init__(name=name)
self.d1 = tf.keras.layers.Dense(10)
self.d2 = tf.keras.layers.Dense(20)
def call(self, inputs):
x = self.d1(inputs)
return self.d2(x)
model = SubclassModel()
model(tf.zeros((10, 10)))
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': model.d1.kernel,
# 'd1.bias': model.d1.bias,
# 'd2.kernel': model.d2.kernel,
# 'd2.bias': model.d2.bias,
# }
# Functional model
inputs = tf.keras.Input((10,), batch_size=10)
x = tf.keras.layers.Dense(20, name='d1')(inputs)
output = tf.keras.layers.Dense(30, name='d2')(x)
model = tf.keras.Model(inputs, output)
d1 = model.layers[1]
d2 = model.layers[2]
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': d1.kernel,
# 'd1.bias': d1.bias,
# 'd2.kernel': d2.kernel,
# 'd2.bias': d2.bias,
# }
```
| def get_weight_paths(self):
"""Retrieve all the variables and their paths for the model.
The variable path (string) is a stable key to identify a `tf.Variable`
instance owned by the model. It can be used to specify variable-specific
configurations (e.g. DTensor, quantization) from a global view.
This method returns a dict with weight object paths as keys
and the corresponding `tf.Variable` instances as values.
Note that if the model is a subclassed model and the weights haven't
been initialized, an empty dict will be returned.
Returns:
A dict where keys are variable paths and values are `tf.Variable`
instances.
Example:
```python
class SubclassModel(tf.keras.Model):
def __init__(self, name=None):
super().__init__(name=name)
self.d1 = tf.keras.layers.Dense(10)
self.d2 = tf.keras.layers.Dense(20)
def call(self, inputs):
x = self.d1(inputs)
return self.d2(x)
model = SubclassModel()
model(tf.zeros((10, 10)))
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': model.d1.kernel,
# 'd1.bias': model.d1.bias,
# 'd2.kernel': model.d2.kernel,
# 'd2.bias': model.d2.bias,
# }
# Functional model
inputs = tf.keras.Input((10,), batch_size=10)
x = tf.keras.layers.Dense(20, name='d1')(inputs)
output = tf.keras.layers.Dense(30, name='d2')(x)
model = tf.keras.Model(inputs, output)
d1 = model.layers[1]
d2 = model.layers[2]
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': d1.kernel,
# 'd1.bias': d1.bias,
# 'd2.kernel': d2.kernel,
# 'd2.bias': d2.bias,
# }
```
"""
result = {}
(
descendants,
object_paths_dict,
) = tf.__internal__.tracking.ObjectGraphView(
self
).breadth_first_traversal()
for descendant in descendants:
if isinstance(descendant, tf.Variable):
trackable_references = object_paths_dict[descendant]
object_path = ".".join([t.name for t in trackable_references])
result[object_path] = descendant
return result
| (self) |
725,027 | tf_keras.src.engine.training | get_weights | Retrieves the weights of the model.
Returns:
A flat list of Numpy arrays.
| def get_weights(self):
"""Retrieves the weights of the model.
Returns:
A flat list of Numpy arrays.
"""
with self.distribute_strategy.scope():
return super().get_weights()
| (self) |
725,028 | tf_keras.src.engine.base_layer | load_own_variables | Loads the state of the layer.
You can override this method to take full control of how the state of
the layer is loaded upon calling `keras.models.load_model()`.
Args:
store: Dict from which the state of the model will be loaded.
| def load_own_variables(self, store):
"""Loads the state of the layer.
You can override this method to take full control of how the state of
the layer is loaded upon calling `keras.models.load_model()`.
Args:
store: Dict from which the state of the model will be loaded.
"""
self._update_trackables()
all_vars = self._trainable_weights + self._non_trainable_weights
if len(store.keys()) != len(all_vars):
raise ValueError(
f"Layer '{self.name}' expected {len(all_vars)} variables, "
"but received "
f"{len(store.keys())} variables during loading. "
f"Expected: {[v.name for v in all_vars]}"
)
for i, v in enumerate(all_vars):
# TODO(rchao): check shapes and raise errors.
v.assign(store[f"{i}"])
| (self, store) |
725,029 | tf_keras.src.engine.training | load_weights | Loads all layer weights from a saved files.
The saved file could be a SavedModel file, a `.keras` file (v3 saving
format), or a file created via `model.save_weights()`.
By default, weights are loaded based on the network's
topology. This means the architecture should be the same as when the
weights were saved. Note that layers that don't have weights are not
taken into account in the topological ordering, so adding or removing
layers is fine as long as they don't have weights.
**Partial weight loading**
If you have modified your model, for instance by adding a new layer
(with weights) or by changing the shape of the weights of a layer,
you can choose to ignore errors and continue loading
by setting `skip_mismatch=True`. In this case any layer with
mismatching weights will be skipped. A warning will be displayed
for each skipped layer.
**Weight loading by name**
If your weights are saved as a `.h5` file created
via `model.save_weights()`, you can use the argument `by_name=True`.
In this case, weights are loaded into layers only if they share
the same name. This is useful for fine-tuning or transfer-learning
models where some of the layers have changed.
Note that only topological loading (`by_name=False`) is supported when
loading weights from the `.keras` v3 format or from the TensorFlow
SavedModel format.
Args:
filepath: String, path to the weights file to load. For weight files
in TensorFlow format, this is the file prefix (the same as was
passed to `save_weights()`). This can also be a path to a
SavedModel or a `.keras` file (v3 saving format) saved
via `model.save()`.
skip_mismatch: Boolean, whether to skip loading of layers where
there is a mismatch in the number of weights, or a mismatch in
the shape of the weights.
by_name: Boolean, whether to load weights by name or by topological
order. Only topological loading is supported for weight files in
the `.keras` v3 format or in the TensorFlow SavedModel format.
options: Optional `tf.train.CheckpointOptions` object that specifies
options for loading weights (only valid for a SavedModel file).
| # 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.
# ==============================================================================
"""Training-related part of the TF-Keras engine."""
import copy
import itertools
import json
import warnings
import weakref
import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow.python.distribute import distribute_utils
from tensorflow.python.distribute import input_ops
from tensorflow.python.eager import context
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util.tf_export import keras_export
from tensorflow.tools.docs import doc_controls
from tf_keras.src import backend
from tf_keras.src import callbacks as callbacks_module
from tf_keras.src import optimizers
from tf_keras.src.dtensor import dtensor_api
from tf_keras.src.dtensor import layout_map as layout_map_lib
from tf_keras.src.engine import base_layer
from tf_keras.src.engine import base_layer_utils
from tf_keras.src.engine import compile_utils
from tf_keras.src.engine import data_adapter
from tf_keras.src.engine import input_layer as input_layer_module
from tf_keras.src.engine import training_utils
from tf_keras.src.metrics import base_metric
from tf_keras.src.mixed_precision import loss_scale_optimizer as lso
from tf_keras.src.optimizers import optimizer
from tf_keras.src.optimizers import optimizer_v1
from tf_keras.src.saving import pickle_utils
from tf_keras.src.saving import saving_api
from tf_keras.src.saving import saving_lib
from tf_keras.src.saving import serialization_lib
from tf_keras.src.saving.legacy import serialization
from tf_keras.src.saving.legacy.saved_model import json_utils
from tf_keras.src.saving.legacy.saved_model import model_serialization
from tf_keras.src.utils import generic_utils
from tf_keras.src.utils import io_utils
from tf_keras.src.utils import layer_utils
from tf_keras.src.utils import steps_per_execution_tuning
from tf_keras.src.utils import tf_inspect
from tf_keras.src.utils import tf_utils
from tf_keras.src.utils import traceback_utils
from tf_keras.src.utils import version_utils
from tf_keras.src.utils.mode_keys import ModeKeys
try:
import h5py
except ImportError:
h5py = None
@keras_export("keras.Model", "keras.models.Model")
class Model(base_layer.Layer, version_utils.ModelVersionSelector):
"""A model grouping layers into an object with training/inference features.
Args:
inputs: The input(s) of the model: a `keras.Input` object or a
combination of `keras.Input` objects in a dict, list or tuple.
outputs: The output(s) of the model: a tensor that originated from
`keras.Input` objects or a combination of such tensors in a dict,
list or tuple. See Functional API example below.
name: String, the name of the model.
There are two ways to instantiate a `Model`:
1 - With the "Functional API", where you start from `Input`,
you chain layer calls to specify the model's forward pass,
and finally you create your model from inputs and outputs:
```python
import tensorflow as tf
inputs = tf.keras.Input(shape=(3,))
x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
```
Note: Only dicts, lists, and tuples of input tensors are supported. Nested
inputs are not supported (e.g. lists of list or dicts of dict).
A new Functional API model can also be created by using the
intermediate tensors. This enables you to quickly extract sub-components
of the model.
Example:
```python
inputs = keras.Input(shape=(None, None, 3))
processed = keras.layers.RandomCrop(width=32, height=32)(inputs)
conv = keras.layers.Conv2D(filters=2, kernel_size=3)(processed)
pooling = keras.layers.GlobalAveragePooling2D()(conv)
feature = keras.layers.Dense(10)(pooling)
full_model = keras.Model(inputs, feature)
backbone = keras.Model(processed, conv)
activations = keras.Model(conv, feature)
```
Note that the `backbone` and `activations` models are not
created with `keras.Input` objects, but with the tensors that are originated
from `keras.Input` objects. Under the hood, the layers and weights will
be shared across these models, so that user can train the `full_model`, and
use `backbone` or `activations` to do feature extraction.
The inputs and outputs of the model can be nested structures of tensors as
well, and the created models are standard Functional API models that support
all the existing APIs.
2 - By subclassing the `Model` class: in that case, you should define your
layers in `__init__()` and you should implement the model's forward pass
in `call()`.
```python
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
def call(self, inputs):
x = self.dense1(inputs)
return self.dense2(x)
model = MyModel()
```
If you subclass `Model`, you can optionally have
a `training` argument (boolean) in `call()`, which you can use to specify
a different behavior in training and inference:
```python
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
self.dropout = tf.keras.layers.Dropout(0.5)
def call(self, inputs, training=False):
x = self.dense1(inputs)
if training:
x = self.dropout(x, training=training)
return self.dense2(x)
model = MyModel()
```
Once the model is created, you can config the model with losses and metrics
with `model.compile()`, train the model with `model.fit()`, or use the model
to do prediction with `model.predict()`.
"""
_TF_MODULE_IGNORED_PROPERTIES = frozenset(
itertools.chain(
(
"_train_counter",
"_test_counter",
"_predict_counter",
"_steps_per_execution",
"_compiled_trainable_state",
),
base_layer.Layer._TF_MODULE_IGNORED_PROPERTIES,
)
)
_SCALAR_UPRANKING_ON = False
def __new__(cls, *args, **kwargs):
# Signature detection
if is_functional_model_init_params(args, kwargs) and cls == Model:
# Functional model
from tf_keras.src.engine import functional
return functional.Functional(skip_init=True, *args, **kwargs)
else:
return super(Model, cls).__new__(cls, *args, **kwargs)
@tf.__internal__.tracking.no_automatic_dependency_tracking
@traceback_utils.filter_traceback
def __init__(self, *args, **kwargs):
self._is_model_for_instrumentation = True
# Special case for Subclassed Functional Model, which we couldn't detect
# when __new__ is called. We only realize it is a functional model when
# it calls super.__init__ with input and output tensor.
from tf_keras.src.engine import functional
if is_functional_model_init_params(args, kwargs) and not isinstance(
self, functional.Functional
):
# Filter the kwargs for multiple inheritance.
supported_kwargs = [
"inputs",
"outputs",
"name",
"trainable",
"skip_init",
]
model_kwargs = {
k: kwargs[k] for k in kwargs if k in supported_kwargs
}
other_kwargs = {
k: kwargs[k] for k in kwargs if k not in supported_kwargs
}
inject_functional_model_class(self.__class__)
functional.Functional.__init__(self, *args, **model_kwargs)
# In case there is any multiple inheritance here, we need to call
# the __init__ for any class that appears after the Functional
# class.
clz_to_init = []
found_functional_class = False
for clz in self.__class__.__bases__:
if issubclass(clz, functional.Functional):
found_functional_class = True
continue
if found_functional_class:
clz_to_init.append(clz)
if clz_to_init:
for clz in clz_to_init:
clz.__init__(self, *args, **other_kwargs)
elif other_kwargs:
# In case there are unused kwargs, we should raise an error to
# user, in case they have a typo in the param name.
raise TypeError(
"The following keyword arguments passed to `Model` aren't "
"supported: {}.".format(other_kwargs)
)
return
# The following are implemented as property functions:
# self.trainable_weights
# self.non_trainable_weights
# `inputs` / `outputs` will only appear in kwargs if either are
# misspelled.
generic_utils.validate_kwargs(
kwargs,
{
"trainable",
"dtype",
"dynamic",
"name",
"autocast",
"inputs",
"outputs",
},
)
super().__init__(**kwargs)
# By default, Model is a subclass model, which is not in graph network.
self._is_graph_network = False
self.inputs = None
self.outputs = None
self.input_names = None
self.output_names = None
# stop_training is used by callback to stop training when error happens
self.stop_training = False
self.history = None
# These objects are used in the default `Model.compile`. They are not
# guaranteed to be set after `Model.compile` is called, as users can
# override compile with custom logic.
self.compiled_loss = None
self.compiled_metrics = None
# This is True for Sequential networks and Functional networks.
self._compute_output_and_mask_jointly = False
# Don't reset compilation if already done. This may occur if calling
# `__init__` (or `_init_graph_network`) on an already-compiled model
# such as a Sequential model. Sequential models may need to rebuild
# themselves after compilation.
self._maybe_create_attribute("_is_compiled", False)
self._maybe_create_attribute("optimizer", None)
# Model must be created under scope of DistStrat it will be trained
# with.
if tf.distribute.has_strategy():
self._distribution_strategy = tf.distribute.get_strategy()
else:
self._distribution_strategy = None
self._distribute_reduction_method = None
self._cluster_coordinator = None
# Defaults to value of `tf.config.experimental_functions_run_eagerly`.
self._run_eagerly = None
# Initialize cache attrs.
self._reset_compile_cache()
# Fault-tolerance handler. Set in `ModelCheckpoint`.
self._training_state = None
self._saved_model_inputs_spec = None
self._saved_model_arg_spec = None
self._checkpoint = tf.train.Checkpoint(root=weakref.ref(self))
self._steps_per_execution = None
self._steps_per_execution_tuner = None
self._autotune_steps_per_execution = False
self._layout_map = layout_map_lib.get_current_layout_map()
self._init_batch_counters()
self._base_model_initialized = True
# `jit_compile` starts off with None as default and gets overwritten by
# the value specified in `Model.compile`, and this is effective for
# `fit`, `evaluate`, and `predict`.
self._jit_compile = None
def _create_counter_variable(self, init_value):
"""Helper function for counter variable creation.
For the DTensor use case with layout map, since the variable are not
tracked by model, they can't be visited by the layout map, and need to
be properly initialized as DVariable.
"""
# This function should be removed after we move to the strategy based
# implementation for DTensor.
if self._layout_map is None:
agg = tf.VariableAggregation.ONLY_FIRST_REPLICA
return tf.Variable(init_value, dtype="int64", aggregation=agg)
else:
layout = dtensor_api.Layout.replicated(
mesh=self._layout_map.get_default_mesh(), rank=0
)
return dtensor_api.DVariable(
init_value, dtype="int64", layout=layout
)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _init_batch_counters(self):
# Untracked Variables, used to keep track of mini-batches seen in `fit`,
# `evaluate`, and `predict`.
if not tf.inside_function():
# Creating variables inside tf.function is not allowed, hence
# these would otherwise prevent users from creating TF-Keras layers
# inside tf.function.
# These variables are not connected to outputs so they have no
# effect on graph generation anyway.
self._train_counter = self._create_counter_variable(0)
self._test_counter = self._create_counter_variable(0)
self._predict_counter = self._create_counter_variable(0)
def __setattr__(self, name, value):
if not getattr(self, "_self_setattr_tracking", True):
super().__setattr__(name, value)
return
if all(
isinstance(v, (base_layer.Layer, tf.Variable))
or base_layer_utils.has_weights(v)
for v in tf.nest.flatten(value)
):
try:
self._base_model_initialized
except AttributeError:
raise RuntimeError(
"It looks like you are subclassing `Model` and you "
"forgot to call `super().__init__()`."
" Always start with this line."
)
super().__setattr__(name, value)
def __reduce__(self):
if self.built:
return (
pickle_utils.deserialize_model_from_bytecode,
(pickle_utils.serialize_model_as_bytecode(self),),
)
else:
# SavedModel (and hence serialize_model_as_bytecode) only support
# built models, but if the model is not built,
# it may be possible to serialize as a plain Python object,
# as long as the constituent parts (layers, optimizers, losses,
# etc.) can be serialized as plain Python objects. Thus we call up
# the superclass hierarchy to get an implementation of __reduce__
# that can pickle this Model as a plain Python object.
return super().__reduce__()
def __deepcopy__(self, memo):
if self.built:
new = pickle_utils.deserialize_model_from_bytecode(
pickle_utils.serialize_model_as_bytecode(self)
)
memo[id(self)] = new
else:
# See comment in __reduce__ for explanation
deserializer, serialized, *rest = super().__reduce__()
new = deserializer(*serialized)
memo[id(self)] = new
if rest:
state = copy.deepcopy(rest[0], memo=memo)
new.__setstate__(state)
return new
def __copy__(self):
return self.__deepcopy__({})
@generic_utils.default
def build(self, input_shape):
"""Builds the model based on input shapes received.
This is to be used for subclassed models, which do not know at
instantiation time what their inputs look like.
This method only exists for users who want to call `model.build()` in a
standalone way (as a substitute for calling the model on real data to
build it). It will never be called by the framework (and thus it will
never throw unexpected errors in an unrelated workflow).
Args:
input_shape: Single tuple, `TensorShape` instance, or list/dict of
shapes, where shapes are tuples, integers, or `TensorShape`
instances.
Raises:
ValueError:
1. In case of invalid user-provided data (not of type tuple,
list, `TensorShape`, or dict).
2. If the model requires call arguments that are agnostic
to the input shapes (positional or keyword arg in call
signature).
3. If not all layers were properly built.
4. If float type inputs are not supported within the layers.
In each of these cases, the user should build their model by calling
it on real tensor data.
"""
if self._is_graph_network:
super().build(input_shape)
return
if input_shape is None:
raise ValueError(
"Input shape must be defined when calling `build()` on "
"a `Model` subclass."
)
valid_types = (tuple, list, tf.TensorShape, dict)
if not isinstance(input_shape, valid_types):
raise ValueError(
"Specified input shape is not one of the valid types. "
"Please specify a batch input shape of type tuple or "
"list of input shapes. User provided "
"input type: {}.".format(type(input_shape))
)
if input_shape and not self.inputs:
# We create placeholders for the `None`s in the shape and build the
# model in a Graph. Since tf.Variable is compatible with both eager
# execution and graph building, the variables created after building
# the model in a Graph are still valid when executing eagerly.
if tf.executing_eagerly():
graph = tf.__internal__.FuncGraph("build_graph")
else:
graph = backend.get_graph()
with graph.as_default():
if isinstance(input_shape, list) and all(
d is None or isinstance(d, int) for d in input_shape
):
input_shape = tuple(input_shape)
if isinstance(input_shape, list):
x = [
base_layer_utils.generate_placeholders_from_shape(shape)
for shape in input_shape
]
elif isinstance(input_shape, dict):
x = {
k: base_layer_utils.generate_placeholders_from_shape(
shape
)
for k, shape in input_shape.items()
}
else:
x = base_layer_utils.generate_placeholders_from_shape(
input_shape
)
kwargs = {}
call_signature = self._call_spec.full_argspec
call_args = call_signature.args
# Exclude `self`, `inputs`, and any argument with a default
# value.
if len(call_args) > 2:
if call_signature.defaults:
call_args = call_args[2 : -len(call_signature.defaults)]
else:
call_args = call_args[2:]
for arg in call_args:
if arg == "training":
# Case where `training` is a positional arg with no
# default.
kwargs["training"] = False
else:
# Has invalid call signature with unknown positional
# arguments.
raise ValueError(
"Currently, you cannot build your model if it "
"has positional or keyword arguments that are "
"not inputs to the model, but are required for "
"its `call()` method. Instead, in order to "
"instantiate and build your model, `call()` "
"your model on real tensor data with all "
"expected call arguments. The argument "
"for `call()` can be a single list/tuple that "
"contains multiple inputs."
)
elif len(call_args) < 2:
# Signature without `inputs`.
raise ValueError(
"You can only call `build()` on a model if its "
"`call()` method accepts an `inputs` argument."
)
try:
self.call(x, **kwargs)
except (tf.errors.InvalidArgumentError, TypeError) as e:
raise ValueError(
"You cannot build your model by calling `build` "
"if your layers do not support float type inputs. "
"Instead, in order to instantiate and build your "
"model, call your model on real tensor data (of "
"the correct dtype).\n\nThe actual error from "
f"`call` is: {e}."
)
super().build(input_shape)
@traceback_utils.filter_traceback
def __call__(self, *args, **kwargs):
if self._layout_map is not None and not self.built:
# Note that this method is only overridden for DTensor and layout
# injection purpose.
# Capture the inputs and create graph input as replacement for model
# to initialize its weights first.
copied_args = copy.copy(args)
copied_kwargs = copy.copy(kwargs)
(
inputs,
copied_args,
copied_kwargs,
) = self._call_spec.split_out_first_arg(copied_args, copied_kwargs)
def _convert_to_graph_inputs(x):
if isinstance(x, (tf.Tensor, np.ndarray, float, int)):
x = tf.convert_to_tensor(x)
return input_layer_module.Input(x.shape)
# TODO(scottzhu): maybe better handle mask and training flag.
inputs = tf.nest.map_structure(_convert_to_graph_inputs, inputs)
copied_args = tf.nest.map_structure(
_convert_to_graph_inputs, copied_args
)
copied_kwargs = tf.nest.map_structure(
_convert_to_graph_inputs, copied_kwargs
)
with layout_map_lib.layout_map_scope(self._layout_map):
# We ignore the result here.
super().__call__(inputs, *copied_args, **copied_kwargs)
layout_map_lib._map_subclass_model_variable(self, self._layout_map)
return super().__call__(*args, **kwargs)
@doc_controls.doc_in_current_and_subclasses
def call(self, inputs, training=None, mask=None):
"""Calls the model on new inputs and returns the outputs as tensors.
In this case `call()` just reapplies
all ops in the graph to the new inputs
(e.g. build a new computational graph from the provided inputs).
Note: This method should not be called directly. It is only meant to be
overridden when subclassing `tf.keras.Model`.
To call a model on an input, always use the `__call__()` method,
i.e. `model(inputs)`, which relies on the underlying `call()` method.
Args:
inputs: Input tensor, or dict/list/tuple of input tensors.
training: Boolean or boolean scalar tensor, indicating whether to
run the `Network` in training mode or inference mode.
mask: A mask or list of masks. A mask can be either a boolean tensor
or None (no mask). For more details, check the guide
[here](https://www.tensorflow.org/guide/keras/masking_and_padding).
Returns:
A tensor if there is a single output, or
a list of tensors if there are more than one outputs.
"""
raise NotImplementedError(
"Unimplemented `tf.keras.Model.call()`: if you "
"intend to create a `Model` with the Functional "
"API, please provide `inputs` and `outputs` "
"arguments. Otherwise, subclass `Model` with an "
"overridden `call()` method."
)
@traceback_utils.filter_traceback
def compile(
self,
optimizer="rmsprop",
loss=None,
metrics=None,
loss_weights=None,
weighted_metrics=None,
run_eagerly=None,
steps_per_execution=None,
jit_compile=None,
pss_evaluation_shards=0,
**kwargs,
):
"""Configures the model for training.
Example:
```python
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),
loss=tf.keras.losses.BinaryCrossentropy(),
metrics=[tf.keras.metrics.BinaryAccuracy(),
tf.keras.metrics.FalseNegatives()])
```
Args:
optimizer: String (name of optimizer) or optimizer instance. See
`tf.keras.optimizers`.
loss: Loss function. May be a string (name of loss function), or
a `tf.keras.losses.Loss` instance. See `tf.keras.losses`. A loss
function is any callable with the signature `loss = fn(y_true,
y_pred)`, where `y_true` are the ground truth values, and
`y_pred` are the model's predictions.
`y_true` should have shape
`(batch_size, d0, .. dN)` (except in the case of
sparse loss functions such as
sparse categorical crossentropy which expects integer arrays of
shape `(batch_size, d0, .. dN-1)`).
`y_pred` should have shape `(batch_size, d0, .. dN)`.
The loss function should return a float tensor.
If a custom `Loss` instance is
used and reduction is set to `None`, return value has shape
`(batch_size, d0, .. dN-1)` i.e. per-sample or per-timestep loss
values; otherwise, it is a scalar. If the model has multiple
outputs, you can use a different loss on each output by passing a
dictionary or a list of losses. The loss value that will be
minimized by the model will then be the sum of all individual
losses, unless `loss_weights` is specified.
metrics: List of metrics to be evaluated by the model during
training and testing. Each of this can be a string (name of a
built-in function), function or a `tf.keras.metrics.Metric`
instance. See `tf.keras.metrics`. Typically you will use
`metrics=['accuracy']`.
A function is any callable with the signature `result = fn(y_true,
y_pred)`. To specify different metrics for different outputs of a
multi-output model, you could also pass a dictionary, such as
`metrics={'output_a':'accuracy', 'output_b':['accuracy', 'mse']}`.
You can also pass a list to specify a metric or a list of metrics
for each output, such as
`metrics=[['accuracy'], ['accuracy', 'mse']]`
or `metrics=['accuracy', ['accuracy', 'mse']]`. When you pass the
strings 'accuracy' or 'acc', we convert this to one of
`tf.keras.metrics.BinaryAccuracy`,
`tf.keras.metrics.CategoricalAccuracy`,
`tf.keras.metrics.SparseCategoricalAccuracy` based on the shapes
of the targets and of the model output. We do a similar
conversion for the strings 'crossentropy' and 'ce' as well.
The metrics passed here are evaluated without sample weighting; if
you would like sample weighting to apply, you can specify your
metrics via the `weighted_metrics` argument instead.
loss_weights: Optional list or dictionary specifying scalar
coefficients (Python floats) to weight the loss contributions of
different model outputs. The loss value that will be minimized by
the model will then be the *weighted sum* of all individual
losses, weighted by the `loss_weights` coefficients. If a list,
it is expected to have a 1:1 mapping to the model's outputs. If a
dict, it is expected to map output names (strings) to scalar
coefficients.
weighted_metrics: List of metrics to be evaluated and weighted by
`sample_weight` or `class_weight` during training and testing.
run_eagerly: Bool. If `True`, this `Model`'s logic will not be
wrapped in a `tf.function`. Recommended to leave this as `None`
unless your `Model` cannot be run inside a `tf.function`.
`run_eagerly=True` is not supported when using
`tf.distribute.experimental.ParameterServerStrategy`. Defaults to
`False`.
steps_per_execution: Int or `'auto'`. The number of batches to
run during each `tf.function` call. If set to "auto", keras will
automatically tune `steps_per_execution` during runtime. Running
multiple batches inside a single `tf.function` call can greatly
improve performance on TPUs, when used with distributed strategies
such as `ParameterServerStrategy`, or with small models with a
large Python overhead. At most, one full epoch will be run each
execution. If a number larger than the size of the epoch is
passed, the execution will be truncated to the size of the epoch.
Note that if `steps_per_execution` is set to `N`,
`Callback.on_batch_begin` and `Callback.on_batch_end` methods will
only be called every `N` batches (i.e. before/after each
`tf.function` execution). Defaults to `1`.
jit_compile: If `True`, compile the model training step with XLA.
[XLA](https://www.tensorflow.org/xla) is an optimizing compiler
for machine learning.
`jit_compile` is not enabled for by default.
Note that `jit_compile=True`
may not necessarily work for all models.
For more information on supported operations please refer to the
[XLA documentation](https://www.tensorflow.org/xla).
Also refer to
[known XLA issues](https://www.tensorflow.org/xla/known_issues)
for more details.
pss_evaluation_shards: Integer or 'auto'. Used for
`tf.distribute.ParameterServerStrategy` training only. This arg
sets the number of shards to split the dataset into, to enable an
exact visitation guarantee for evaluation, meaning the model will
be applied to each dataset element exactly once, even if workers
fail. The dataset must be sharded to ensure separate workers do
not process the same data. The number of shards should be at least
the number of workers for good performance. A value of 'auto'
turns on exact evaluation and uses a heuristic for the number of
shards based on the number of workers. 0, meaning no
visitation guarantee is provided. NOTE: Custom implementations of
`Model.test_step` will be ignored when doing exact evaluation.
Defaults to `0`.
**kwargs: Arguments supported for backwards compatibility only.
"""
if jit_compile and not tf_utils.can_jit_compile(warn=True):
jit_compile = False
self._compile_config = serialization_lib.Config(
optimizer=optimizer,
loss=loss,
metrics=metrics,
loss_weights=loss_weights,
weighted_metrics=weighted_metrics,
run_eagerly=run_eagerly,
steps_per_execution=steps_per_execution,
jit_compile=jit_compile,
)
with self.distribute_strategy.scope():
if "experimental_steps_per_execution" in kwargs:
logging.warning(
"The argument `steps_per_execution` is no longer "
"experimental. Pass `steps_per_execution` instead of "
"`experimental_steps_per_execution`."
)
if not steps_per_execution:
steps_per_execution = kwargs.pop(
"experimental_steps_per_execution"
)
# When compiling from an already-serialized model, we do not want to
# reapply some processing steps (e.g. metric renaming for
# multi-output models, which have prefixes added for each
# corresponding output name).
from_serialized = kwargs.pop("from_serialized", False)
self._validate_compile(optimizer, metrics, **kwargs)
self._run_eagerly = run_eagerly
self.optimizer = self._get_optimizer(optimizer)
mesh = None
if self._layout_map is not None:
mesh = self._layout_map.get_default_mesh()
if isinstance(loss, compile_utils.LossesContainer):
self.compiled_loss = loss
else:
self.compiled_loss = compile_utils.LossesContainer(
loss,
loss_weights,
output_names=self.output_names,
mesh=mesh,
)
self.compiled_metrics = compile_utils.MetricsContainer(
metrics,
weighted_metrics,
output_names=self.output_names,
from_serialized=from_serialized,
mesh=mesh,
)
if steps_per_execution == "auto":
if self._steps_per_execution is None:
self._configure_steps_per_execution(1)
self._steps_per_execution_tuner = (
steps_per_execution_tuning.StepsPerExecutionTuner(
self.optimizer, self._steps_per_execution
)
)
self._autotune_steps_per_execution = True
else:
self._configure_steps_per_execution(steps_per_execution or 1)
self._pss_evaluation_shards = self._infer_exact_eval_shards(
pss_evaluation_shards
)
# Initializes attrs that are reset each time `compile` is called.
self._reset_compile_cache()
self._is_compiled = True
self.loss = loss or {}
if (self._run_eagerly or self.dynamic) and jit_compile:
raise ValueError(
"You cannot enable `run_eagerly` and `jit_compile` "
"at the same time."
)
else:
self._jit_compile = jit_compile
def _get_optimizer(self, optimizer):
"""Wraps `optimizer` in `LossScaleOptimizer` if necessary."""
def _get_single_optimizer(opt):
opt = optimizers.get(opt)
if self.dtype_policy.name == "mixed_float16" and not isinstance(
opt, lso.BaseLossScaleOptimizer
):
# Loss scaling is necessary with mixed_float16 for models to
# converge to the same accuracy as with float32.
opt = lso.BaseLossScaleOptimizer(opt)
return opt
return tf.nest.map_structure(_get_single_optimizer, optimizer)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _reset_compile_cache(self):
self.train_function = None
self.test_function = None
self.predict_function = None
# Used to cache the `tf.function`'ed `train_function` to be logged in
# TensorBoard, since the original `train_function` is not necessarily
# a `tf.function` (e.g., with ParameterServerStrategy, the
# `train_function` is a scheduling of the actual training function to a
# remote worker).
self.train_tf_function = None
# Used to cache `trainable` attr of `Layer`s for `fit`.
self._compiled_trainable_state = self._get_trainable_state()
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _configure_steps_per_execution(self, steps_per_execution):
self._steps_per_execution = self._create_counter_variable(
steps_per_execution
)
@property
def _should_compute_mask(self):
return False
@property
def metrics(self):
"""Return metrics added using `compile()` or `add_metric()`.
Note: Metrics passed to `compile()` are available only after a
`keras.Model` has been trained/evaluated on actual data.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> [m.name for m in model.metrics]
[]
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> model.fit(x, y)
>>> [m.name for m in model.metrics]
['loss', 'mae']
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> d = tf.keras.layers.Dense(2, name='out')
>>> output_1 = d(inputs)
>>> output_2 = d(inputs)
>>> model = tf.keras.models.Model(
... inputs=inputs, outputs=[output_1, output_2])
>>> model.add_metric(
... tf.reduce_sum(output_2), name='mean', aggregation='mean')
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
>>> model.fit(x, (y, y))
>>> [m.name for m in model.metrics]
['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',
'out_1_acc', 'mean']
"""
metrics = []
if self._is_compiled:
if self.compiled_loss is not None:
metrics += self.compiled_loss.metrics
if self.compiled_metrics is not None:
metrics += self.compiled_metrics.metrics
for l in self._flatten_layers():
metrics.extend(l._metrics)
return metrics
@property
def metrics_names(self):
"""Returns the model's display labels for all outputs.
Note: `metrics_names` are available only after a `keras.Model` has been
trained/evaluated on actual data.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> model.metrics_names
[]
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> model.fit(x, y)
>>> model.metrics_names
['loss', 'mae']
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> d = tf.keras.layers.Dense(2, name='out')
>>> output_1 = d(inputs)
>>> output_2 = d(inputs)
>>> model = tf.keras.models.Model(
... inputs=inputs, outputs=[output_1, output_2])
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
>>> model.fit(x, (y, y))
>>> model.metrics_names
['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',
'out_1_acc']
"""
# This property includes all output names including `loss` and
# per-output losses for backward compatibility.
return [m.name for m in self.metrics]
@property
def distribute_strategy(self):
"""The `tf.distribute.Strategy` this model was created under."""
return self._distribution_strategy or tf.distribute.get_strategy()
@property
def run_eagerly(self):
"""Settable attribute indicating whether the model should run eagerly.
Running eagerly means that your model will be run step by step,
like Python code. Your model might run slower, but it should become
easier for you to debug it by stepping into individual layer calls.
By default, we will attempt to compile your model to a static graph to
deliver the best execution performance.
Returns:
Boolean, whether the model should run eagerly.
"""
if self.dynamic and self._run_eagerly == False:
# TODO(fchollet): consider using py_func to enable this.
raise ValueError(
"Your model contains layers that can only be "
"successfully run in eager execution (layers "
"constructed with `dynamic=True`). "
"You cannot set `run_eagerly=False`."
)
if self._cluster_coordinator and self._run_eagerly:
raise ValueError(
"When using `Model` with `ParameterServerStrategy`, "
"`run_eagerly` is not supported."
)
# Run eagerly logic, by priority:
# (1) Dynamic models must be run eagerly.
# (2) Explicitly setting run_eagerly causes a Model to be run eagerly.
# (3) Not explicitly setting run_eagerly defaults to TF's global
# setting.
return (
self.dynamic
or self._run_eagerly
or (tf.config.functions_run_eagerly() and self._run_eagerly is None)
)
@run_eagerly.setter
def run_eagerly(self, value):
self._run_eagerly = value
@property
def autotune_steps_per_execution(self):
"""Settable property to enable tuning for steps_per_execution"""
return self._autotune_steps_per_execution
@autotune_steps_per_execution.setter
def autotune_steps_per_execution(self, value):
self._autotune_steps_per_execution = value
if value and self._steps_per_execution_tuner is None:
if self._steps_per_execution is None:
self._configure_steps_per_execution(1)
self._steps_per_execution_tuner = (
steps_per_execution_tuning.StepsPerExecutionTuner(
self.optimizer, self._steps_per_execution
)
)
@property
def steps_per_execution(self):
"""Settable `steps_per_execution variable. Requires a compiled model."""
return self._steps_per_execution
@steps_per_execution.setter
def steps_per_execution(self, value):
if self._steps_per_execution is None:
self._configure_steps_per_execution(value)
else:
self._steps_per_execution.assign(value)
@property
def jit_compile(self):
"""Specify whether to compile the model with XLA.
[XLA](https://www.tensorflow.org/xla) is an optimizing compiler
for machine learning. `jit_compile` is not enabled by default.
Note that `jit_compile=True` may not necessarily work for all models.
For more information on supported operations please refer to the
[XLA documentation](https://www.tensorflow.org/xla). Also refer to
[known XLA issues](https://www.tensorflow.org/xla/known_issues)
for more details.
"""
return self._jit_compile
@jit_compile.setter
def jit_compile(self, value):
# Function remains cached with previous jit_compile settings
if self._jit_compile == value:
# Avoid resetting compiler cache if possible if the value is the
# same
return
# Check if TensorFlow is compiled with XLA before setting the value
if value and not tf_utils.can_jit_compile(warn=True):
self._jit_compile = False
return
self._jit_compile = value
# Setting `jit_compile` should invalidate previously cached functions.
self._reset_compile_cache()
@property
def distribute_reduction_method(self):
"""The method employed to reduce per-replica values during training.
Unless specified, the value "auto" will be assumed, indicating that
the reduction strategy should be chosen based on the current
running environment.
See `reduce_per_replica` function for more details.
"""
return self._distribute_reduction_method or "auto"
@distribute_reduction_method.setter
def distribute_reduction_method(self, value):
self._distribute_reduction_method = value
def _validate_target_and_loss(self, y, loss):
"""Raises error if target or loss is not found.
This method verifies that the target and loss are properly populated
when applicable, or raises errors.
Args:
y: the target for training.
loss: the total loss tensor including loss added via `compile` and
`add_loss`.
"""
# `self.loss` references the loss added via `compile` call. If users
# have provided such, the target must be provided; otherwise it's a user
# error. Note that `self.loss` does not include losses added via
# `add_loss`, and it is a valid use when such loss from `add_loss`
# exists and target does not.
if self.loss and y is None:
raise ValueError(
"Target data is missing. Your model was compiled with "
f"loss={self.loss}, "
"and therefore expects target data to be provided in `fit()`."
)
# For training, there must be compiled loss or regularization loss to
# exist in order to apply the gradients. If one is not found, it means
# no loss was supplied via `compile` or `add_loss`.
elif loss is None:
raise ValueError(
"No loss found. You may have forgotten to provide a `loss` "
"argument in the `compile()` method."
)
def train_step(self, data):
"""The logic for one training step.
This method can be overridden to support custom training logic.
For concrete examples of how to override this method see
[Customizing what happens in fit](
https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit).
This method is called by `Model.make_train_function`.
This method should contain the mathematical logic for one step of
training. This typically includes the forward pass, loss calculation,
backpropagation, and metric updates.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_train_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the
values of the `Model`'s metrics are returned. Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data)
# Run forward pass.
with tf.GradientTape() as tape:
y_pred = self(x, training=True)
loss = self.compute_loss(x, y, y_pred, sample_weight)
self._validate_target_and_loss(y, loss)
# Run backwards pass.
self.optimizer.minimize(loss, self.trainable_variables, tape=tape)
return self.compute_metrics(x, y, y_pred, sample_weight)
def compute_loss(self, x=None, y=None, y_pred=None, sample_weight=None):
"""Compute the total loss, validate it, and return it.
Subclasses can optionally override this method to provide custom loss
computation logic.
Example:
```python
class MyModel(tf.keras.Model):
def __init__(self, *args, **kwargs):
super(MyModel, self).__init__(*args, **kwargs)
self.loss_tracker = tf.keras.metrics.Mean(name='loss')
def compute_loss(self, x, y, y_pred, sample_weight):
loss = tf.reduce_mean(tf.math.squared_difference(y_pred, y))
loss += tf.add_n(self.losses)
self.loss_tracker.update_state(loss)
return loss
def reset_metrics(self):
self.loss_tracker.reset_states()
@property
def metrics(self):
return [self.loss_tracker]
tensors = tf.random.uniform((10, 10)), tf.random.uniform((10,))
dataset = tf.data.Dataset.from_tensor_slices(tensors).repeat().batch(1)
inputs = tf.keras.layers.Input(shape=(10,), name='my_input')
outputs = tf.keras.layers.Dense(10)(inputs)
model = MyModel(inputs, outputs)
model.add_loss(tf.reduce_sum(outputs))
optimizer = tf.keras.optimizers.SGD()
model.compile(optimizer, loss='mse', steps_per_execution=10)
model.fit(dataset, epochs=2, steps_per_epoch=10)
print('My custom loss: ', model.loss_tracker.result().numpy())
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
The total loss as a `tf.Tensor`, or `None` if no loss results (which
is the case when called by `Model.test_step`).
"""
del x # The default implementation does not use `x`.
return self.compiled_loss(
y, y_pred, sample_weight, regularization_losses=self.losses
)
def compute_metrics(self, x, y, y_pred, sample_weight):
"""Update metric states and collect all metrics to be returned.
Subclasses can optionally override this method to provide custom metric
updating and collection logic.
Example:
```python
class MyModel(tf.keras.Sequential):
def compute_metrics(self, x, y, y_pred, sample_weight):
# This super call updates `self.compiled_metrics` and returns
# results for all metrics listed in `self.metrics`.
metric_results = super(MyModel, self).compute_metrics(
x, y, y_pred, sample_weight)
# Note that `self.custom_metric` is not listed in `self.metrics`.
self.custom_metric.update_state(x, y, y_pred, sample_weight)
metric_results['custom_metric_name'] = self.custom_metric.result()
return metric_results
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model.call(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end()`. Typically, the
values of the metrics listed in `self.metrics` are returned. Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
del x # The default implementation does not use `x`.
self.compiled_metrics.update_state(y, y_pred, sample_weight)
return self.get_metrics_result()
def get_metrics_result(self):
"""Returns the model's metrics values as a dict.
If any of the metric result is a dict (containing multiple metrics),
each of them gets added to the top level returned dict of this method.
Returns:
A `dict` containing values of the metrics listed in `self.metrics`.
Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
# Collect metrics to return
return_metrics = {}
for metric in self.metrics:
result = metric.result()
if isinstance(result, dict):
return_metrics.update(result)
else:
return_metrics[metric.name] = result
return return_metrics
def _validate_and_get_metrics_result(self, logs):
"""Returns model metrics as a dict if the keys match with input logs.
When the training / evalution is performed with asynchronous steps, such
as the case with `tf.distribute.ParameterServerStrategy`, the last
scheduled `train / test_step` may not give the latest metrics because it
is not guaranteed to be executed the last. This method gets metrics from
the model directly instead of relying on the return from last step
function.
It logs a warning if the metric results could not be overridden when
used with `tf.distribute.ParameterServerStrategy`.
When the user has custom train / test step functions, the metrics
returned may be different from `Model.metrics`. In those instances,
this function will be no-op and return the logs.
Args:
logs: A `dict` of metrics returned by train / test step function.
Returns:
A `dict` containing values of the metrics listed in `self.metrics`
when logs and model metrics keys match. Otherwise it returns input
`logs`.
"""
PSS_WARN_MSG = "Could not get Model metric results. \
Using the results of last step function could lead to incorrect \
results when used with ParameterServerStrategy"
try:
metric_logs = self.get_metrics_result()
except TypeError:
if self._cluster_coordinator:
logging.warning(PSS_WARN_MSG)
else:
# Verify that train / test step logs passed and metric logs have
# matching keys. Could be different when using custom step functions
if isinstance(logs, dict) and set(logs.keys()) == set(
metric_logs.keys()
):
logs = tf_utils.sync_to_numpy_or_python_type(metric_logs)
elif self._cluster_coordinator:
logging.warning(PSS_WARN_MSG)
return logs
def _aggregate_exact_metrics(self, logs):
# When doing exact evaluation, `logs` is a list of each data shard's
# metric variables, which will be used to update the metrics.
for shard_result in logs:
for metric in self.metrics:
if metric.name not in shard_result.keys():
logging.log_first_n(
logging.WARN,
f"No matching result found for metric {metric.name}. "
"This metric's computed result may be incorrect.",
3,
)
continue
metric_result = shard_result[metric.name]
if len(metric_result) != len(metric.weights):
raise ValueError(
f"Expected {len(metric.weights)} variables in result "
f"for metric {metric.name}, but found "
f"{len(metric_result)}."
)
for weight, val in zip(metric.weights, metric_result):
weight.assign_add(val)
return self.get_metrics_result()
def make_train_function(self, force=False):
"""Creates a function that executes one step of training.
This method can be overridden to support custom training logic.
This method is called by `Model.fit` and `Model.train_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual training
logic to `Model.train_step`.
This function is cached the first time `Model.fit` or
`Model.train_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the train function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_train_batch_end`, such as
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
if self.train_function is not None and not force:
return self.train_function
def step_function(model, iterator):
"""Runs a single training step."""
def run_step(data):
outputs = model.train_step(data)
# Ensure counter is updated only if `train_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._train_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def train_function(iterator):
"""Runs a training execution with a single step."""
return step_function(self, iterator)
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
if self._cluster_coordinator:
self.train_function = (
lambda it: self._cluster_coordinator.schedule(
train_function, args=(it,)
)
)
else:
self.train_function = train_function
# If we're using a coordinator, use the value of
# self._steps_per_execution at the time the function is
# called/scheduled, and not when it is actually executed.
elif self._cluster_coordinator:
def train_function(iterator, steps_per_execution):
"""Runs a training execution with multiple steps."""
for _ in tf.range(steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
self.train_function = lambda it: self._cluster_coordinator.schedule(
train_function, args=(it, self._steps_per_execution.value())
)
else:
def train_function(iterator):
"""Runs a training execution with multiple steps."""
for _ in tf.range(self._steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
self.train_function = train_function
return self.train_function
@traceback_utils.filter_traceback
def fit(
self,
x=None,
y=None,
batch_size=None,
epochs=1,
verbose="auto",
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_batch_size=None,
validation_freq=1,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
):
"""Trains the model for a fixed number of epochs (dataset iterations).
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A `tf.data` dataset. Should return a tuple
of either `(inputs, targets)` or
`(inputs, targets, sample_weights)`.
- A generator or `keras.utils.Sequence` returning `(inputs,
targets)` or `(inputs, targets, sample_weights)`.
- A `tf.keras.utils.experimental.DatasetCreator`, which wraps a
callable that takes a single argument of type
`tf.distribute.InputContext`, and returns a `tf.data.Dataset`.
`DatasetCreator` should be used when users prefer to specify the
per-replica batching and sharding logic for the `Dataset`.
See `tf.keras.utils.experimental.DatasetCreator` doc for more
information.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given below. If these
include `sample_weights` as a third component, note that sample
weighting applies to the `weighted_metrics` argument but not the
`metrics` argument in `compile()`. If using
`tf.distribute.experimental.ParameterServerStrategy`, only
`DatasetCreator` type is supported for `x`.
y: Target data. Like the input data `x`,
it could be either Numpy array(s) or TensorFlow tensor(s).
It should be consistent with `x` (you cannot have Numpy inputs and
tensor targets, or inversely). If `x` is a dataset, generator,
or `keras.utils.Sequence` instance, `y` should
not be specified (since targets will be obtained from `x`).
batch_size: Integer or `None`.
Number of samples per gradient 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).
epochs: Integer. Number of epochs to train the model.
An epoch is an iteration over the entire `x` and `y`
data provided
(unless the `steps_per_epoch` flag is set to
something other than None).
Note that in conjunction with `initial_epoch`,
`epochs` is to be understood as "final epoch".
The model is not trained for a number of iterations
given by `epochs`, but merely until the epoch
of index `epochs` is reached.
verbose: 'auto', 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = one line per epoch.
'auto' becomes 1 for most cases, but 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so verbose=2 is
recommended when not running interactively (eg, in a production
environment). Defaults to 'auto'.
callbacks: List of `keras.callbacks.Callback` instances.
List of callbacks to apply during training.
See `tf.keras.callbacks`. Note
`tf.keras.callbacks.ProgbarLogger` and
`tf.keras.callbacks.History` callbacks are created automatically
and need not be passed into `model.fit`.
`tf.keras.callbacks.ProgbarLogger` is created or not based on
`verbose` argument to `model.fit`.
Callbacks with batch-level calls are currently unsupported with
`tf.distribute.experimental.ParameterServerStrategy`, and users
are advised to implement epoch-level calls instead with an
appropriate `steps_per_epoch` value.
validation_split: Float between 0 and 1.
Fraction of the training data to be used as validation data.
The model will set apart this fraction of the training data,
will not train on it, and will evaluate
the loss and any model metrics
on this data at the end of each epoch.
The validation data is selected from the last samples
in the `x` and `y` data provided, before shuffling. This
argument is not supported when `x` is a dataset, generator or
`keras.utils.Sequence` instance.
If both `validation_data` and `validation_split` are provided,
`validation_data` will override `validation_split`.
`validation_split` is not yet supported with
`tf.distribute.experimental.ParameterServerStrategy`.
validation_data: Data on which to evaluate
the loss and any model metrics at the end of each epoch.
The model will not be trained on this data. Thus, note the fact
that the validation loss of data provided using
`validation_split` or `validation_data` is not affected by
regularization layers like noise and dropout.
`validation_data` will override `validation_split`.
`validation_data` could be:
- A tuple `(x_val, y_val)` of Numpy arrays or tensors.
- A tuple `(x_val, y_val, val_sample_weights)` of NumPy
arrays.
- A `tf.data.Dataset`.
- A Python generator or `keras.utils.Sequence` returning
`(inputs, targets)` or `(inputs, targets, sample_weights)`.
`validation_data` is not yet supported with
`tf.distribute.experimental.ParameterServerStrategy`.
shuffle: Boolean (whether to shuffle the training data
before each epoch) or str (for 'batch'). This argument is
ignored when `x` is a generator or an object of tf.data.Dataset.
'batch' is a special option for dealing
with the limitations of HDF5 data; it shuffles in batch-sized
chunks. Has no effect when `steps_per_epoch` is not `None`.
class_weight: Optional dictionary mapping class indices (integers)
to a weight (float) value, used for weighting the loss function
(during training only).
This can be useful to tell the model to
"pay more attention" to samples from
an under-represented class. When `class_weight` is specified
and targets have a rank of 2 or greater, either `y` must be
one-hot encoded, or an explicit final dimension of `1` must
be included for sparse class labels.
sample_weight: Optional Numpy array of weights for
the training samples, used for weighting the loss function
(during training only). You can either pass a flat (1D)
Numpy array with the same length as the input samples
(1:1 mapping between weights and samples),
or in the case of temporal data,
you can pass a 2D array with shape
`(samples, sequence_length)`,
to apply a different weight to every timestep of every sample.
This argument is not supported when `x` is a dataset, generator,
or `keras.utils.Sequence` instance, instead provide the
sample_weights as the third element of `x`.
Note that sample weighting does not apply to metrics specified
via the `metrics` argument in `compile()`. To apply sample
weighting to your metrics, you can specify them via the
`weighted_metrics` in `compile()` instead.
initial_epoch: Integer.
Epoch at which to start training
(useful for resuming a previous training run).
steps_per_epoch: Integer or `None`.
Total number of steps (batches of samples)
before declaring one epoch finished and starting the
next epoch. 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_per_epoch'
is None, the epoch will run until the input dataset is
exhausted. When passing an infinitely repeating dataset, you
must specify the `steps_per_epoch` argument. If
`steps_per_epoch=-1` the training will run indefinitely with an
infinitely repeating dataset. This argument is not supported
with array inputs.
When using `tf.distribute.experimental.ParameterServerStrategy`:
* `steps_per_epoch=None` is not supported.
validation_steps: Only relevant if `validation_data` is provided and
is a `tf.data` dataset. Total number of steps (batches of
samples) to draw before stopping when performing validation
at the end of every epoch. If 'validation_steps' is None,
validation will run until the `validation_data` dataset is
exhausted. In the case of an infinitely repeated dataset, it
will run into an infinite loop. If 'validation_steps' is
specified and only part of the dataset will be consumed, the
evaluation will start from the beginning of the dataset at each
epoch. This ensures that the same validation samples are used
every time.
validation_batch_size: Integer or `None`.
Number of samples per validation batch.
If unspecified, will default to `batch_size`.
Do not specify the `validation_batch_size` if your data is in
the form of datasets, generators, or `keras.utils.Sequence`
instances (since they generate batches).
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.
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the generator
queue. If unspecified, `max_queue_size` will default to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up
when using process-based threading. If unspecified, `workers`
will default to 1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
Unpacking behavior for iterator-like inputs:
A common pattern is to pass a tf.data.Dataset, generator, or
tf.keras.utils.Sequence to the `x` argument of fit, which will in fact
yield not only features (x) but optionally targets (y) and sample
weights. TF-Keras requires that the output of such iterator-likes be
unambiguous. The iterator should return a tuple of length 1, 2, or 3,
where the optional second and third elements will be used for y and
sample_weight respectively. Any other type provided will be wrapped in
a length one tuple, effectively treating everything as 'x'. When
yielding dicts, they should still adhere to the top-level tuple
structure.
e.g. `({"x0": x0, "x1": x1}, y)`. TF-Keras will not attempt to
separate features, targets, and weights from the keys of a single
dict.
A notable unsupported data type is the namedtuple. The reason is
that it behaves like both an ordered datatype (tuple) and a mapping
datatype (dict). So given a namedtuple of the form:
`namedtuple("example_tuple", ["y", "x"])`
it is ambiguous whether to reverse the order of the elements when
interpreting the value. Even worse is a tuple of the form:
`namedtuple("other_tuple", ["x", "y", "z"])`
where it is unclear if the tuple was intended to be unpacked into x,
y, and sample_weight or passed through as a single element to `x`. As
a result the data processing code will simply raise a ValueError if it
encounters a namedtuple. (Along with instructions to remedy the
issue.)
Returns:
A `History` object. Its `History.history` attribute is
a record of training loss values and metrics values
at successive epochs, as well as validation loss values
and validation metrics values (if applicable).
Raises:
RuntimeError: 1. If the model was never compiled or,
2. If `model.fit` is wrapped in `tf.function`.
ValueError: In case of mismatch between the provided input data
and what the model expects or when the input data is empty.
"""
# Legacy graph support is contained in `training_v1.Model`.
version_utils.disallow_legacy_graph("Model", "fit")
self._assert_compile_was_called()
self._check_call_args("fit")
_disallow_inside_tf_function("fit")
verbose = _get_verbosity(verbose, self.distribute_strategy)
if validation_split and validation_data is None:
# Create the validation data using the training data. Only supported
# for `Tensor` and `NumPy` input.
(
x,
y,
sample_weight,
), validation_data = data_adapter.train_validation_split(
(x, y, sample_weight), validation_split=validation_split
)
if validation_data:
(
val_x,
val_y,
val_sample_weight,
) = data_adapter.unpack_x_y_sample_weight(validation_data)
if self.distribute_strategy._should_use_with_coordinator:
self._cluster_coordinator = (
tf.distribute.experimental.coordinator.ClusterCoordinator(
self.distribute_strategy
)
)
with self.distribute_strategy.scope(), training_utils.RespectCompiledTrainableState( # noqa: E501
self
):
# Creates a `tf.data.Dataset` and handles batch and epoch iteration.
data_handler = data_adapter.get_data_handler(
x=x,
y=y,
sample_weight=sample_weight,
batch_size=batch_size,
steps_per_epoch=steps_per_epoch,
initial_epoch=initial_epoch,
epochs=epochs,
shuffle=shuffle,
class_weight=class_weight,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=epochs,
steps=data_handler.inferred_steps,
)
self.stop_training = False
self.train_function = self.make_train_function()
self._train_counter.assign(0)
callbacks.on_train_begin()
training_logs = None
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
# Handle fault-tolerance for multi-worker.
# TODO(omalleyt): Fix the ordering issues that mean this has to
# happen after `callbacks.on_train_begin`.
steps_per_epoch_inferred = (
steps_per_epoch or data_handler.inferred_steps
)
(
data_handler._initial_epoch,
data_handler._initial_step,
) = self._maybe_load_initial_counters_from_ckpt(
steps_per_epoch_inferred, initial_epoch
)
logs = None
for epoch, iterator in data_handler.enumerate_epochs():
self.reset_metrics()
callbacks.on_epoch_begin(epoch)
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
with tf.profiler.experimental.Trace(
"train",
epoch_num=epoch,
step_num=step,
batch_size=batch_size,
_r=1,
):
callbacks.on_train_batch_begin(step)
tmp_logs = self.train_function(iterator)
if data_handler.should_sync:
context.async_wait()
# No error, now safe to assign to logs.
logs = tmp_logs
end_step = step + data_handler.step_increment
callbacks.on_train_batch_end(end_step, logs)
if self.stop_training:
break
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if logs is None:
raise ValueError(
"Unexpected result of `train_function` "
"(Empty logs). This could be due to issues in input "
"pipeline that resulted in an empty dataset. "
"Otherwise, please use "
"`Model.compile(..., run_eagerly=True)`, or "
"`tf.config.run_functions_eagerly(True)` for more "
"information of where went wrong, or file a "
"issue/bug to `tf.keras`."
)
# Override with model metrics instead of last step logs
logs = self._validate_and_get_metrics_result(logs)
epoch_logs = copy.copy(logs)
# Run validation.
if validation_data and self._should_eval(
epoch, validation_freq
):
if self._pss_evaluation_shards:
self._disallow_exact_eval_with_add_metrics()
# Create data_handler for evaluation and cache it.
if getattr(self, "_eval_data_handler", None) is None:
self._eval_data_handler = data_adapter.get_data_handler(
x=val_x,
y=val_y,
sample_weight=val_sample_weight,
batch_size=validation_batch_size or batch_size,
steps_per_epoch=validation_steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
pss_evaluation_shards=self._pss_evaluation_shards,
)
val_logs = self.evaluate(
x=val_x,
y=val_y,
sample_weight=val_sample_weight,
batch_size=validation_batch_size or batch_size,
steps=validation_steps,
callbacks=callbacks,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
return_dict=True,
_use_cached_eval_dataset=True,
)
val_logs = {
"val_" + name: val for name, val in val_logs.items()
}
epoch_logs.update(val_logs)
callbacks.on_epoch_end(epoch, epoch_logs)
training_logs = epoch_logs
if self.stop_training:
break
if isinstance(self.optimizer, optimizer.Optimizer) and epochs > 0:
self.optimizer.finalize_variable_values(
self.trainable_variables
)
# If eval data_handler exists, delete it after all epochs are done.
if getattr(self, "_eval_data_handler", None) is not None:
del self._eval_data_handler
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_train_end(logs=training_logs)
return self.history
def test_step(self, data):
"""The logic for one evaluation step.
This method can be overridden to support custom evaluation logic.
This method is called by `Model.make_test_function`.
This function should contain the mathematical logic for one step of
evaluation.
This typically includes the forward pass, loss calculation, and metrics
updates.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_test_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the
values of the `Model`'s metrics are returned.
"""
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data)
y_pred = self(x, training=False)
# Updates stateful loss metrics.
self.compute_loss(x, y, y_pred, sample_weight)
return self.compute_metrics(x, y, y_pred, sample_weight)
def _make_test_function_exact(self):
if getattr(self, "_shard_test_function", None):
return self._shard_test_function
def step_function(batch):
def run_step(data):
# TODO(b/272050910): Use sample_weight for weighted metrics.
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(
data
)
y_pred = self(x, training=False)
return x, y, y_pred, sample_weight
if self._jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
outputs = self.distribute_strategy.run(run_step, args=(batch,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
def shard_test_function(dataset, total_shards, shard_idx):
# Copy loss and metric variables to the worker and work with them
# locally. This ensures each shard function is atomic: if a worker
# is preempted, the intermediate progress is discarded and that
# shard is retried. This in turn guarantees exactly-once visitation.
local_unweighted_metrics, local_weighted_metrics = [], []
with tf_utils.with_metric_local_vars_scope():
# TODO(jmullenbach): implement and use a clone for
# `MetricsContainer` and use its `update_state` method directly.
for metric in self.compiled_metrics.unweighted_metrics:
if metric is not None:
local_unweighted_metrics.append(
base_metric.clone_metric(metric)
)
for metric in self.compiled_metrics.weighted_metrics:
if metric is not None:
local_weighted_metrics.append(
base_metric.clone_metric(metric)
)
local_loss = compile_utils.LossesContainer.from_config(
self.compiled_loss.get_config()
)
dataset = input_ops.auto_shard_dataset(
dataset, total_shards, shard_idx
)
iterator = iter(dataset)
with distribute_utils.cache_variable_reads():
for batch in iterator:
x, y, y_pred, sample_weight = step_function(batch)
for weighted_metric in local_weighted_metrics:
weighted_metric.update_state(y, y_pred, sample_weight)
for unweighted_metric in local_unweighted_metrics:
unweighted_metric.update_state(y, y_pred)
local_loss(y, y_pred, sample_weight)
local_metrics = (
local_unweighted_metrics
+ local_weighted_metrics
+ local_loss.metrics
)
outputs = {metric.name: metric.weights for metric in local_metrics}
with tf.control_dependencies(_minimum_control_deps(outputs)):
self._test_counter.assign_add(1)
return outputs
if not self.run_eagerly:
shard_test_function = tf.function(
shard_test_function, reduce_retracing=True
)
self._shard_test_function = (
lambda *args: self._cluster_coordinator.schedule(
shard_test_function,
args=args,
)
)
return self._shard_test_function
def make_test_function(self, force=False):
"""Creates a function that executes one step of evaluation.
This method can be overridden to support custom evaluation logic.
This method is called by `Model.evaluate` and `Model.test_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.test_step`.
This function is cached the first time `Model.evaluate` or
`Model.test_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the test function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_test_batch_end`.
"""
if self.test_function is not None and not force:
return self.test_function
def step_function(model, iterator):
"""Runs a single evaluation step."""
def run_step(data):
outputs = model.test_step(data)
# Ensure counter is updated only if `test_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._test_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def test_function(iterator):
"""Runs a test execution with a single step."""
return step_function(self, iterator)
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
if self._cluster_coordinator:
self.test_function = (
lambda it: self._cluster_coordinator.schedule(
test_function, args=(it,)
)
)
else:
self.test_function = test_function
# If we're using a coordinator, use the value of
# self._steps_per_execution at the time the function is
# called/scheduled, and not when it is actually executed.
elif self._cluster_coordinator:
def test_function(iterator, steps_per_execution):
"""Runs a test execution with multiple steps."""
for _ in tf.range(steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
self.test_function = lambda it: self._cluster_coordinator.schedule(
test_function, args=(it, self._steps_per_execution.value())
)
else:
def test_function(iterator):
"""Runs a test execution with multiple steps."""
for _ in tf.range(self._steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
self.test_function = test_function
return self.test_function
@traceback_utils.filter_traceback
def evaluate(
self,
x=None,
y=None,
batch_size=None,
verbose="auto",
sample_weight=None,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
return_dict=False,
**kwargs,
):
"""Returns the loss value & metrics values for the model in test mode.
Computation is done in batches (see the `batch_size` arg.)
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A `tf.data` dataset. Should return a tuple
of either `(inputs, targets)` or
`(inputs, targets, sample_weights)`.
- A generator or `keras.utils.Sequence` returning `(inputs,
targets)` or `(inputs, targets, sample_weights)`.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given in the `Unpacking
behavior for iterator-like inputs` section of `Model.fit`.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s). It should be consistent with `x`
(you cannot have Numpy inputs and tensor targets, or inversely).
If `x` is a dataset, generator or `keras.utils.Sequence` instance,
`y` should not be specified (since targets will be obtained from
the iterator/dataset).
batch_size: Integer or `None`. Number of samples per batch of
computation. If unspecified, `batch_size` will default to 32. Do
not specify the `batch_size` if your data is in the form of a
dataset, generators, or `keras.utils.Sequence` instances (since
they generate batches).
verbose: `"auto"`, 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = single line.
`"auto"` becomes 1 for most cases, and to 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so `verbose=2` is
recommended when not running interactively (e.g. in a production
environment). Defaults to 'auto'.
sample_weight: Optional Numpy array of weights for the test samples,
used for weighting the loss function. You can either pass a flat
(1D) Numpy array with the same length as the input samples
(1:1 mapping between weights and samples), or in the case of
temporal data, you can pass a 2D array with shape `(samples,
sequence_length)`, to apply a different weight to every
timestep of every sample. This argument is not supported when
`x` is a dataset, instead pass sample weights as the third
element of `x`.
steps: Integer or `None`. Total number of steps (batches of samples)
before declaring the evaluation round finished. Ignored with the
default value of `None`. If x is a `tf.data` dataset and `steps`
is None, 'evaluate' will run until the dataset is exhausted. This
argument is not supported with array inputs.
callbacks: List of `keras.callbacks.Callback` instances. List of
callbacks to apply during evaluation. See
[callbacks](https://www.tensorflow.org/api_docs/python/tf/tf_keras/callbacks).
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the generator
queue. If unspecified, `max_queue_size` will default to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, `workers` will default to
1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
**kwargs: Unused at this time.
See the discussion of `Unpacking behavior for iterator-like inputs` for
`Model.fit`.
Returns:
Scalar test 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 scalar outputs.
Raises:
RuntimeError: If `model.evaluate` is wrapped in a `tf.function`.
"""
version_utils.disallow_legacy_graph("Model", "evaluate")
self._assert_compile_was_called()
self._check_call_args("evaluate")
self._check_sample_weight_warning(x, sample_weight)
_disallow_inside_tf_function("evaluate")
use_cached_eval_dataset = kwargs.pop("_use_cached_eval_dataset", False)
if kwargs:
raise TypeError(f"Invalid keyword arguments: {list(kwargs.keys())}")
if self.distribute_strategy._should_use_with_coordinator:
self._cluster_coordinator = (
tf.distribute.experimental.coordinator.ClusterCoordinator(
self.distribute_strategy
)
)
verbose = _get_verbosity(verbose, self.distribute_strategy)
if self._pss_evaluation_shards:
self._disallow_exact_eval_with_add_metrics()
with self.distribute_strategy.scope():
# Use cached evaluation data only when it's called in `Model.fit`
if (
use_cached_eval_dataset
and getattr(self, "_eval_data_handler", None) is not None
):
data_handler = self._eval_data_handler
else:
# Creates a `tf.data.Dataset` and handles batch and epoch
# iteration.
data_handler = data_adapter.get_data_handler(
x=x,
y=y,
sample_weight=sample_weight,
batch_size=batch_size,
steps_per_epoch=steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
pss_evaluation_shards=self._pss_evaluation_shards,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=1,
steps=data_handler.inferred_steps,
)
# Initialize to prevent errors if 0 epochs are evaluated.
logs = {}
test_function_runner = self._get_test_function_runner(callbacks)
self._test_counter.assign(0)
callbacks.on_test_begin()
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
for (
_,
dataset_or_iterator,
) in data_handler.enumerate_epochs(): # Single epoch.
self.reset_metrics()
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
with tf.profiler.experimental.Trace(
"test", step_num=step, _r=1
):
callbacks.on_test_batch_begin(step)
logs = test_function_runner.run_step(
dataset_or_iterator,
data_handler,
step,
self._pss_evaluation_shards,
)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
# Override with model metrics instead of last step logs
if self._pss_evaluation_shards:
logs = self._aggregate_exact_metrics(logs)
else:
logs = self._validate_and_get_metrics_result(logs)
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_test_end(logs=logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def _disallow_exact_eval_with_add_metrics(self):
metrics_from_add_metric = [
metric
for layer in self._flatten_layers()
for metric in layer._metrics
]
compiled_metrics = self.compiled_metrics.metrics
if any(
[
metric not in compiled_metrics
for metric in metrics_from_add_metric
]
):
raise ValueError(
"Detected that a metric was added to this model "
"via `Model.add_metric`. This is not currently "
"supported when using exact evaluation with "
"`tf.distribute.ParameterServerStrategy`."
)
def _infer_exact_eval_shards(self, pss_evaluation_shards):
if not self.distribute_strategy._should_use_with_coordinator:
return 0
if pss_evaluation_shards == "auto":
# TODO(b/264265138) evaluate and improve this heuristic
return self.distribute_strategy._num_workers * 5
return pss_evaluation_shards
def _get_test_function_runner(self, callbacks):
if (
self._pss_evaluation_shards
and self.distribute_strategy._should_use_with_coordinator
):
self.test_function = self._make_test_function_exact()
test_function_runner = _ExactTestFunction(
self.test_function, callbacks
)
else:
self.test_function = self.make_test_function()
test_function_runner = _TestFunction(self.test_function, callbacks)
return test_function_runner
def predict_step(self, data):
"""The logic for one inference step.
This method can be overridden to support custom inference logic.
This method is called by `Model.make_predict_function`.
This method should contain the mathematical logic for one step of
inference. This typically includes the forward pass.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_predict_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
The result of one inference step, typically the output of calling the
`Model` on data.
"""
x, _, _ = data_adapter.unpack_x_y_sample_weight(data)
return self(x, training=False)
def make_predict_function(self, force=False):
"""Creates a function that executes one step of inference.
This method can be overridden to support custom inference logic.
This method is called by `Model.predict` and `Model.predict_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.predict_step`.
This function is cached the first time `Model.predict` or
`Model.predict_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the predict function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return the outputs of the `Model`.
"""
if self.predict_function is not None and not force:
return self.predict_function
def step_function(model, iterator):
"""Runs a single evaluation step."""
def run_step(data):
outputs = model.predict_step(data)
# Ensure counter is updated only if `test_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._predict_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs, self.distribute_strategy, reduction="concat"
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def predict_function(iterator):
"""Runs an evaluation execution with a single step."""
return step_function(self, iterator)
else:
def predict_function(iterator):
"""Runs an evaluation execution with multiple steps."""
outputs = step_function(self, iterator)
for _ in tf.range(self._steps_per_execution - 1):
tf.autograph.experimental.set_loop_options(
shape_invariants=[
(
outputs,
tf.nest.map_structure(
lambda t: tf_utils.get_tensor_spec(
t, dynamic_batch=True
).shape,
outputs,
),
)
]
)
step_outputs = step_function(self, iterator)
outputs = tf.nest.map_structure(
lambda t1, t2: concat([t1, t2]), outputs, step_outputs
)
return outputs
if not self.run_eagerly:
predict_function = tf.function(
predict_function, reduce_retracing=True
)
self.predict_function = predict_function
return self.predict_function
@traceback_utils.filter_traceback
def predict(
self,
x,
batch_size=None,
verbose="auto",
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
):
"""Generates output predictions for the input samples.
Computation is done in batches. This method is designed for batch
processing of large numbers of inputs. It is not intended for use inside
of loops that iterate over your data and process small numbers of inputs
at a time.
For small numbers of inputs that fit in one batch,
directly use `__call__()` for faster execution, e.g.,
`model(x)`, or `model(x, training=False)` if you have layers such as
`tf.keras.layers.BatchNormalization` that behave differently during
inference. You may pair the individual model call with a `tf.function`
for additional performance inside your inner loop.
If you need access to numpy array values instead of tensors after your
model call, you can use `tensor.numpy()` to get the numpy array value of
an eager tensor.
Also, note the fact that test loss is not affected by
regularization layers like noise and dropout.
Note: See [this FAQ entry](
https://keras.io/getting_started/faq/#whats-the-difference-between-model-methods-predict-and-call)
for more details about the difference between `Model` methods
`predict()` and `__call__()`.
Args:
x: Input samples. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A `tf.data` dataset.
- A generator or `keras.utils.Sequence` instance.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given in the `Unpacking
behavior for iterator-like inputs` section of `Model.fit`.
batch_size: Integer or `None`.
Number of samples per batch.
If unspecified, `batch_size` will default to 32.
Do not specify the `batch_size` if your data is in the
form of dataset, generators, or `keras.utils.Sequence` instances
(since they generate batches).
verbose: `"auto"`, 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = single line.
`"auto"` becomes 1 for most cases, and to 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so `verbose=2` is
recommended when not running interactively (e.g. in a production
environment). Defaults to 'auto'.
steps: Total number of steps (batches of samples)
before declaring the prediction round finished.
Ignored with the default value of `None`. If x is a `tf.data`
dataset and `steps` is None, `predict()` will
run until the input dataset is exhausted.
callbacks: List of `keras.callbacks.Callback` instances.
List of callbacks to apply during prediction.
See [callbacks](
https://www.tensorflow.org/api_docs/python/tf/tf_keras/callbacks).
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the
generator queue. If unspecified, `max_queue_size` will default
to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, `workers` will default
to 1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
See the discussion of `Unpacking behavior for iterator-like inputs` for
`Model.fit`. Note that Model.predict uses the same interpretation rules
as `Model.fit` and `Model.evaluate`, so inputs must be unambiguous for
all three methods.
Returns:
Numpy array(s) of predictions.
Raises:
RuntimeError: If `model.predict` is wrapped in a `tf.function`.
ValueError: In case of mismatch between the provided
input data and the model's expectations,
or in case a stateful model receives a number of samples
that is not a multiple of the batch size.
"""
version_utils.disallow_legacy_graph("Model", "predict")
self._check_call_args("predict")
_disallow_inside_tf_function("predict")
# TODO(yashkatariya): Cache model on the coordinator for faster
# prediction. If running under PSS, then swap it with OneDeviceStrategy
# so that execution will run on the coordinator.
original_pss_strategy = None
if self.distribute_strategy._should_use_with_coordinator:
original_pss_strategy = self.distribute_strategy
self._distribution_strategy = None
# Cluster coordinator is set by `.fit()` and `.evaluate()` which is not
# needed in `.predict()` because all the predictions happen on the
# coordinator/locally.
if self._cluster_coordinator:
self._cluster_coordinator = None
verbose = _get_verbosity(verbose, self.distribute_strategy)
outputs = None
with self.distribute_strategy.scope():
# Creates a `tf.data.Dataset` and handles batch and epoch iteration.
dataset_types = (tf.compat.v1.data.Dataset, tf.data.Dataset)
if (
self._in_multi_worker_mode()
or _is_tpu_multi_host(self.distribute_strategy)
) and isinstance(x, dataset_types):
try:
options = tf.data.Options()
data_option = tf.data.experimental.AutoShardPolicy.DATA
options.experimental_distribute.auto_shard_policy = (
data_option
)
x = x.with_options(options)
except ValueError:
warnings.warn(
"Using Model.predict with MultiWorkerMirroredStrategy "
"or TPUStrategy and AutoShardPolicy.FILE might lead to "
"out-of-order result. Consider setting it to "
"AutoShardPolicy.DATA.",
stacklevel=2,
)
data_handler = data_adapter.get_data_handler(
x=x,
batch_size=batch_size,
steps_per_epoch=steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=1,
steps=data_handler.inferred_steps,
)
self.predict_function = self.make_predict_function()
self._predict_counter.assign(0)
callbacks.on_predict_begin()
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
batch_outputs = None
for _, iterator in data_handler.enumerate_epochs(): # Single epoch.
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
callbacks.on_predict_batch_begin(step)
tmp_batch_outputs = self.predict_function(iterator)
if data_handler.should_sync:
context.async_wait()
batch_outputs = (
tmp_batch_outputs # No error, now safe to assign.
)
if outputs is None:
outputs = tf.nest.map_structure(
lambda batch_output: [batch_output],
batch_outputs,
)
else:
tf.__internal__.nest.map_structure_up_to(
batch_outputs,
lambda output, batch_output: output.append(
batch_output
),
outputs,
batch_outputs,
)
end_step = step + data_handler.step_increment
callbacks.on_predict_batch_end(
end_step, {"outputs": batch_outputs}
)
if batch_outputs is None:
raise ValueError(
"Unexpected result of `predict_function` "
"(Empty batch_outputs). Please use "
"`Model.compile(..., run_eagerly=True)`, or "
"`tf.config.run_functions_eagerly(True)` for more "
"information of where went wrong, or file a "
"issue/bug to `tf.keras`."
)
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_predict_end()
all_outputs = tf.__internal__.nest.map_structure_up_to(
batch_outputs, potentially_ragged_concat, outputs
)
# If originally PSS strategy was used, then replace it back since
# predict is running under `OneDeviceStrategy` after the swap and once
# its done we need to replace it back to PSS again.
if original_pss_strategy is not None:
self._distribution_strategy = original_pss_strategy
return tf_utils.sync_to_numpy_or_python_type(all_outputs)
def reset_metrics(self):
"""Resets the state of all the metrics in the model.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> _ = model.fit(x, y, verbose=0)
>>> assert all(float(m.result()) for m in model.metrics)
>>> model.reset_metrics()
>>> assert all(float(m.result()) == 0 for m in model.metrics)
"""
for m in self.metrics:
m.reset_state()
def train_on_batch(
self,
x,
y=None,
sample_weight=None,
class_weight=None,
reset_metrics=True,
return_dict=False,
):
"""Runs a single gradient update on a single batch of data.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s).
sample_weight: Optional array of the same length as x, containing
weights to apply to the model's loss for each sample. In the case
of temporal data, you can pass a 2D array with shape (samples,
sequence_length), to apply a different weight to every timestep of
every sample.
class_weight: Optional dictionary mapping class indices (integers)
to a weight (float) to apply to the model's loss for the samples
from this class during training. This can be useful to tell the
model to "pay more attention" to samples from an under-represented
class. When `class_weight` is specified and targets have a rank of
2 or greater, either `y` must be one-hot encoded, or an explicit
final dimension of `1` must be included for sparse class labels.
reset_metrics: If `True`, the metrics returned will be only for this
batch. If `False`, the metrics will be statefully accumulated
across batches.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
Returns:
Scalar training 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 scalar outputs.
Raises:
RuntimeError: If `model.train_on_batch` is wrapped in a `tf.function`.
"""
self._assert_compile_was_called()
self._check_call_args("train_on_batch")
_disallow_inside_tf_function("train_on_batch")
if reset_metrics:
self.reset_metrics()
with self.distribute_strategy.scope(), training_utils.RespectCompiledTrainableState( # noqa: E501
self
):
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x, y, sample_weight, class_weight
)
self.train_function = self.make_train_function()
logs = self.train_function(iterator)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def test_on_batch(
self,
x,
y=None,
sample_weight=None,
reset_metrics=True,
return_dict=False,
):
"""Test the model on a single batch of samples.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays (in case the
model has multiple inputs).
- A TensorFlow tensor, or a list of tensors (in case the model has
multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s). It should be consistent with `x`
(you cannot have Numpy inputs and tensor targets, or inversely).
sample_weight: Optional array of the same length as x, containing
weights to apply to the model's loss for each sample. In the case
of temporal data, you can pass a 2D array with shape (samples,
sequence_length), to apply a different weight to every timestep of
every sample.
reset_metrics: If `True`, the metrics returned will be only for this
batch. If `False`, the metrics will be statefully accumulated
across batches.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
Returns:
Scalar test 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 scalar outputs.
Raises:
RuntimeError: If `model.test_on_batch` is wrapped in a
`tf.function`.
"""
self._assert_compile_was_called()
self._check_call_args("test_on_batch")
_disallow_inside_tf_function("test_on_batch")
if reset_metrics:
self.reset_metrics()
with self.distribute_strategy.scope():
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x, y, sample_weight
)
self.test_function = self.make_test_function()
logs = self.test_function(iterator)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def predict_on_batch(self, x):
"""Returns predictions for a single batch of samples.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays (in case the
model has multiple inputs).
- A TensorFlow tensor, or a list of tensors (in case the model has
multiple inputs).
Returns:
Numpy array(s) of predictions.
Raises:
RuntimeError: If `model.predict_on_batch` is wrapped in a
`tf.function`.
"""
self._check_call_args("predict_on_batch")
_disallow_inside_tf_function("predict_on_batch")
with self.distribute_strategy.scope():
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x
)
self.predict_function = self.make_predict_function()
outputs = self.predict_function(iterator)
return tf_utils.sync_to_numpy_or_python_type(outputs)
@doc_controls.do_not_generate_docs
def fit_generator(
self,
generator,
steps_per_epoch=None,
epochs=1,
verbose=1,
callbacks=None,
validation_data=None,
validation_steps=None,
validation_freq=1,
class_weight=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
shuffle=True,
initial_epoch=0,
):
"""Fits the model on data yielded batch-by-batch by a Python generator.
DEPRECATED:
`Model.fit` now supports generators, so there is no longer any need to
use this endpoint.
"""
warnings.warn(
"`Model.fit_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.fit`, which supports generators.",
stacklevel=2,
)
return self.fit(
generator,
steps_per_epoch=steps_per_epoch,
epochs=epochs,
verbose=verbose,
callbacks=callbacks,
validation_data=validation_data,
validation_steps=validation_steps,
validation_freq=validation_freq,
class_weight=class_weight,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
shuffle=shuffle,
initial_epoch=initial_epoch,
)
@doc_controls.do_not_generate_docs
def evaluate_generator(
self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0,
):
"""Evaluates the model on a data generator.
DEPRECATED:
`Model.evaluate` now supports generators, so there is no longer any
need to use this endpoint.
"""
warnings.warn(
"`Model.evaluate_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.evaluate`, which supports generators.",
stacklevel=2,
)
self._check_call_args("evaluate_generator")
return self.evaluate(
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks,
)
@doc_controls.do_not_generate_docs
def predict_generator(
self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0,
):
"""Generates predictions for the input samples from a data generator.
DEPRECATED:
`Model.predict` now supports generators, so there is no longer any
need to use this endpoint.
"""
warnings.warn(
"`Model.predict_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.predict`, which supports generators.",
stacklevel=2,
)
return self.predict(
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks,
)
######################################################################
# Functions below are not training related. They are for model weights
# tracking, save/load, serialization, etc.
######################################################################
@property
def trainable_weights(self):
self._assert_weights_created()
if not self._trainable:
return []
trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
trainable_variables += trackable_obj.trainable_variables
trainable_variables += self._trainable_weights
return self._dedup_weights(trainable_variables)
@property
def non_trainable_weights(self):
self._assert_weights_created()
non_trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
non_trainable_variables += trackable_obj.non_trainable_variables
if not self._trainable:
# Return order is all trainable vars, then all non-trainable vars.
trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
trainable_variables += trackable_obj.trainable_variables
non_trainable_variables = (
trainable_variables
+ self._trainable_weights
+ non_trainable_variables
+ self._non_trainable_weights
)
else:
non_trainable_variables = (
non_trainable_variables + self._non_trainable_weights
)
return self._dedup_weights(non_trainable_variables)
def get_weights(self):
"""Retrieves the weights of the model.
Returns:
A flat list of Numpy arrays.
"""
with self.distribute_strategy.scope():
return super().get_weights()
@traceback_utils.filter_traceback
def save(self, 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.models.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.models.save_model()`.
"""
saving_api.save_model(
self,
filepath=filepath,
overwrite=overwrite,
save_format=save_format,
**kwargs,
)
@traceback_utils.filter_traceback
def save_weights(
self, filepath, overwrite=True, save_format=None, options=None
):
"""Saves all layer weights.
Either saves in HDF5 or in TensorFlow format based on the `save_format`
argument.
When saving in HDF5 format, the weight file has:
- `layer_names` (attribute), a list of strings
(ordered names of model layers).
- For every layer, a `group` named `layer.name`
- For every such layer group, a group attribute `weight_names`,
a list of strings
(ordered names of weights tensor of the layer).
- For every weight in the layer, a dataset
storing the weight value, named after the weight tensor.
When saving in TensorFlow format, all objects referenced by the network
are saved in the same format as `tf.train.Checkpoint`, including any
`Layer` instances or `Optimizer` instances assigned to object
attributes. For networks constructed from inputs and outputs using
`tf.keras.Model(inputs, outputs)`, `Layer` instances used by the network
are tracked/saved automatically. For user-defined classes which inherit
from `tf.keras.Model`, `Layer` instances must be assigned to object
attributes, typically in the constructor. See the documentation of
`tf.train.Checkpoint` and `tf.keras.Model` for details.
While the formats are the same, do not mix `save_weights` and
`tf.train.Checkpoint`. Checkpoints saved by `Model.save_weights` should
be loaded using `Model.load_weights`. Checkpoints saved using
`tf.train.Checkpoint.save` should be restored using the corresponding
`tf.train.Checkpoint.restore`. Prefer `tf.train.Checkpoint` over
`save_weights` for training checkpoints.
The TensorFlow format matches objects and variables by starting at a
root object, `self` for `save_weights`, and greedily matching attribute
names. For `Model.save` this is the `Model`, and for `Checkpoint.save`
this is the `Checkpoint` even if the `Checkpoint` has a model attached.
This means saving a `tf.keras.Model` using `save_weights` and loading
into a `tf.train.Checkpoint` with a `Model` attached (or vice versa)
will not match the `Model`'s variables. See the
[guide to training checkpoints](
https://www.tensorflow.org/guide/checkpoint) for details on
the TensorFlow format.
Args:
filepath: String or PathLike, path to the file to save the weights
to. When saving in TensorFlow format, this is the prefix used
for checkpoint files (multiple files are generated). Note that
the '.h5' suffix causes weights to be saved in HDF5 format.
overwrite: Whether to silently overwrite any existing file at the
target location, or provide the user with a manual prompt.
save_format: Either 'tf' or 'h5'. A `filepath` ending in '.h5' or
'.keras' will default to HDF5 if `save_format` is `None`.
Otherwise, `None` becomes 'tf'. Defaults to `None`.
options: Optional `tf.train.CheckpointOptions` object that specifies
options for saving weights.
Raises:
ImportError: If `h5py` is not available when attempting to save in
HDF5 format.
"""
saving_api.save_weights(
self,
filepath=filepath,
overwrite=overwrite,
save_format=save_format,
options=options,
)
@traceback_utils.filter_traceback
def load_weights(
self, filepath, skip_mismatch=False, by_name=False, options=None
):
"""Loads all layer weights from a saved files.
The saved file could be a SavedModel file, a `.keras` file (v3 saving
format), or a file created via `model.save_weights()`.
By default, weights are loaded based on the network's
topology. This means the architecture should be the same as when the
weights were saved. Note that layers that don't have weights are not
taken into account in the topological ordering, so adding or removing
layers is fine as long as they don't have weights.
**Partial weight loading**
If you have modified your model, for instance by adding a new layer
(with weights) or by changing the shape of the weights of a layer,
you can choose to ignore errors and continue loading
by setting `skip_mismatch=True`. In this case any layer with
mismatching weights will be skipped. A warning will be displayed
for each skipped layer.
**Weight loading by name**
If your weights are saved as a `.h5` file created
via `model.save_weights()`, you can use the argument `by_name=True`.
In this case, weights are loaded into layers only if they share
the same name. This is useful for fine-tuning or transfer-learning
models where some of the layers have changed.
Note that only topological loading (`by_name=False`) is supported when
loading weights from the `.keras` v3 format or from the TensorFlow
SavedModel format.
Args:
filepath: String, path to the weights file to load. For weight files
in TensorFlow format, this is the file prefix (the same as was
passed to `save_weights()`). This can also be a path to a
SavedModel or a `.keras` file (v3 saving format) saved
via `model.save()`.
skip_mismatch: Boolean, whether to skip loading of layers where
there is a mismatch in the number of weights, or a mismatch in
the shape of the weights.
by_name: Boolean, whether to load weights by name or by topological
order. Only topological loading is supported for weight files in
the `.keras` v3 format or in the TensorFlow SavedModel format.
options: Optional `tf.train.CheckpointOptions` object that specifies
options for loading weights (only valid for a SavedModel file).
"""
return saving_api.load_weights(
self,
filepath=filepath,
by_name=by_name,
skip_mismatch=skip_mismatch,
options=options,
)
def _updated_config(self):
"""Util shared between different serialization methods.
Returns:
Model config with TF-Keras version information added.
"""
from tf_keras.src import __version__ as keras_version
config = self.get_config()
model_config = {
"class_name": self.__class__.__name__,
"config": config,
"keras_version": keras_version,
"backend": backend.backend(),
}
return model_config
@generic_utils.default
def get_config(self):
"""Returns the config of the `Model`.
Config is a Python dictionary (serializable) containing the
configuration of an object, which in this case is a `Model`. This allows
the `Model` to be be reinstantiated later (without its trained weights)
from this configuration.
Note that `get_config()` does not guarantee to return a fresh copy of
dict every time it is called. The callers should make a copy of the
returned dict if they want to modify it.
Developers of subclassed `Model` are advised to override this method,
and continue to update the dict from `super(MyModel, self).get_config()`
to provide the proper configuration of this `Model`. The default config
will return config dict for init parameters if they are basic types.
Raises `NotImplementedError` when in cases where a custom
`get_config()` implementation is required for the subclassed model.
Returns:
Python dictionary containing the configuration of this `Model`.
"""
# If sublcass doesn't implement `get_config()` parse from init args
# otherwise default to empty dict
if generic_utils.is_default(self.get_config):
try:
config = base_layer.Layer.get_config(self)
except NotImplementedError:
config = {}
logging.warning(
"Model's `__init__()` arguments contain non-serializable "
"objects. Please implement a `get_config()` method in the "
"subclassed Model for proper saving and loading. "
"Defaulting to empty config."
)
else:
config = {}
return config
@classmethod
def from_config(cls, config, custom_objects=None):
# `from_config` assumes `cls` is either `Functional` or a child class of
# `Functional`. In the case that `cls` is meant to behave like a child
# class of `Functional` but only inherits from the `Model` class, we
# have to call `cls(...)` instead of `Functional.from_config`.
from tf_keras.src.engine import functional
with serialization.SharedObjectLoadingScope():
functional_config_keys = [
"name",
"layers",
"input_layers",
"output_layers",
]
is_functional_config = all(
key in config for key in functional_config_keys
)
argspec = tf_inspect.getfullargspec(cls.__init__)
functional_init_args = tf_inspect.getfullargspec(
functional.Functional.__init__
).args[1:]
revivable_as_functional = (
cls in {functional.Functional, Model}
or argspec.args[1:] == functional_init_args
or (argspec.varargs == "args" and argspec.varkw == "kwargs")
)
if is_functional_config and revivable_as_functional:
# Revive Functional model
# (but not Functional subclasses with a custom __init__)
inputs, outputs, layers = functional.reconstruct_from_config(
config, custom_objects
)
model = cls(
inputs=inputs, outputs=outputs, name=config.get("name")
)
functional.connect_ancillary_layers(model, layers)
else:
# Either the model has a custom __init__, or the config
# does not contain all the information necessary to
# revive a Functional model. This happens when the user creates
# subclassed models where `get_config()` is returning
# insufficient information to be considered a Functional model.
# In this case, we fall back to provide all config into the
# constructor of the class.
try:
model = cls(**config)
except TypeError as e:
raise TypeError(
"Unable to revive model from config. When overriding "
"the `get_config()` method, make sure that the "
"returned config contains all items used as arguments "
f"in the constructor to {cls}, "
"which is the default behavior. "
"You can override this default behavior by defining a "
"`from_config(cls, config)` class method to specify "
"how to create an "
f"instance of {cls.__name__} from its config.\n\n"
f"Received config={config}\n\n"
f"Error encountered during deserialization: {e}"
)
return model
def to_json(self, **kwargs):
"""Returns a JSON string containing the network configuration.
To load a network from a JSON save file, use
`keras.models.model_from_json(json_string, custom_objects={})`.
Args:
**kwargs: Additional keyword arguments to be passed to
*`json.dumps()`.
Returns:
A JSON string.
"""
model_config = self._updated_config()
return json.dumps(
model_config, default=json_utils.get_json_type, **kwargs
)
def to_yaml(self, **kwargs):
"""Returns a yaml string containing the network configuration.
Note: Since TF 2.6, this method is no longer supported and will raise a
RuntimeError.
To load a network from a yaml save file, use
`keras.models.model_from_yaml(yaml_string, custom_objects={})`.
`custom_objects` should be a dictionary mapping
the names of custom losses / layers / etc to the corresponding
functions / classes.
Args:
**kwargs: Additional keyword arguments
to be passed to `yaml.dump()`.
Returns:
A YAML string.
Raises:
RuntimeError: announces that the method poses a security risk
"""
raise RuntimeError(
"Method `model.to_yaml()` has been removed due to security risk of "
"arbitrary code execution. Please use `model.to_json()` instead."
)
def reset_states(self):
for layer in self.layers:
if hasattr(layer, "reset_states") and getattr(
layer, "stateful", False
):
layer.reset_states()
@property
@doc_controls.do_not_generate_docs
def state_updates(self):
"""Deprecated, do NOT use!
Returns the `updates` from all layers that are stateful.
This is useful for separating training updates and
state updates, e.g. when we need to update a layer's internal state
during prediction.
Returns:
A list of update ops.
"""
warnings.warn(
"`Model.state_updates` will be removed in a future version. "
"This property should not be used in TensorFlow 2.0, "
"as `updates` are applied automatically.",
stacklevel=2,
)
state_updates = []
for layer in self.layers:
if getattr(layer, "stateful", False):
if hasattr(layer, "updates"):
state_updates += layer.updates
return state_updates
@property
def weights(self):
"""Returns the list of all layer variables/weights.
Note: This will not track the weights of nested `tf.Modules` that are
not themselves TF-Keras layers.
Returns:
A list of variables.
"""
return self._dedup_weights(self._undeduplicated_weights)
@property
def _undeduplicated_weights(self):
"""Returns the undeduplicated list of all layer variables/weights."""
self._assert_weights_created()
weights = []
for layer in self._self_tracked_trackables:
weights += layer.variables
weights += self._trainable_weights + self._non_trainable_weights
return weights
def summary(
self,
line_length=None,
positions=None,
print_fn=None,
expand_nested=False,
show_trainable=False,
layer_range=None,
):
"""Prints a string summary of the network.
Args:
line_length: Total length of printed lines
(e.g. set this to adapt the display to different
terminal window sizes).
positions: Relative or absolute positions of log elements
in each line. If not provided, becomes
`[0.3, 0.6, 0.70, 1.]`. Defaults to `None`.
print_fn: Print function to use. By default, prints to `stdout`.
If `stdout` doesn't work in your environment, change to `print`.
It will be called on each line of the summary.
You can set it to a custom function
in order to capture the string summary.
expand_nested: Whether to expand the nested models.
Defaults to `False`.
show_trainable: Whether to show if a layer is trainable.
Defaults to `False`.
layer_range: a list or tuple of 2 strings,
which is the starting layer name and ending layer name
(both inclusive) indicating the range of layers to be printed
in summary. It also accepts regex patterns instead of exact
name. In such case, start predicate will be the first element
it matches to `layer_range[0]` and the end predicate will be
the last element it matches to `layer_range[1]`.
By default `None` which considers all layers of model.
Raises:
ValueError: if `summary()` is called before the model is built.
"""
if not self.built:
raise ValueError(
"This model has not yet been built. "
"Build the model first by calling `build()` or by calling "
"the model on a batch of data."
)
layer_utils.print_summary(
self,
line_length=line_length,
positions=positions,
print_fn=print_fn,
expand_nested=expand_nested,
show_trainable=show_trainable,
layer_range=layer_range,
)
@property
def layers(self):
return list(self._flatten_layers(include_self=False, recursive=False))
@layers.setter
def layers(self, _):
raise AttributeError(
"`Model.layers` attribute is reserved and should not be used. "
"Please use another name."
)
def get_layer(self, name=None, index=None):
"""Retrieves a layer based on either its name (unique) or index.
If `name` and `index` are both provided, `index` will take precedence.
Indices are based on order of horizontal graph traversal (bottom-up).
Args:
name: String, name of layer.
index: Integer, index of layer.
Returns:
A layer instance.
"""
# TODO(fchollet): We could build a dictionary based on layer names
# since they are constant, but we have not done that yet.
if index is not None and name is not None:
raise ValueError(
"Provide only a layer name or a layer index. Received: "
f"index={index}, name={name}."
)
if index is not None:
if len(self.layers) <= index:
raise ValueError(
f"Was asked to retrieve layer at index {index}"
f" but model only has {len(self.layers)}"
" layers."
)
else:
return self.layers[index]
if name is not None:
for layer in self.layers:
if layer.name == name:
return layer
raise ValueError(
f"No such layer: {name}. Existing layers are: "
f"{list(layer.name for layer in self.layers)}."
)
raise ValueError(
"Provide either a layer name or layer index at `get_layer`."
)
def get_weight_paths(self):
"""Retrieve all the variables and their paths for the model.
The variable path (string) is a stable key to identify a `tf.Variable`
instance owned by the model. It can be used to specify variable-specific
configurations (e.g. DTensor, quantization) from a global view.
This method returns a dict with weight object paths as keys
and the corresponding `tf.Variable` instances as values.
Note that if the model is a subclassed model and the weights haven't
been initialized, an empty dict will be returned.
Returns:
A dict where keys are variable paths and values are `tf.Variable`
instances.
Example:
```python
class SubclassModel(tf.keras.Model):
def __init__(self, name=None):
super().__init__(name=name)
self.d1 = tf.keras.layers.Dense(10)
self.d2 = tf.keras.layers.Dense(20)
def call(self, inputs):
x = self.d1(inputs)
return self.d2(x)
model = SubclassModel()
model(tf.zeros((10, 10)))
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': model.d1.kernel,
# 'd1.bias': model.d1.bias,
# 'd2.kernel': model.d2.kernel,
# 'd2.bias': model.d2.bias,
# }
# Functional model
inputs = tf.keras.Input((10,), batch_size=10)
x = tf.keras.layers.Dense(20, name='d1')(inputs)
output = tf.keras.layers.Dense(30, name='d2')(x)
model = tf.keras.Model(inputs, output)
d1 = model.layers[1]
d2 = model.layers[2]
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': d1.kernel,
# 'd1.bias': d1.bias,
# 'd2.kernel': d2.kernel,
# 'd2.bias': d2.bias,
# }
```
"""
result = {}
(
descendants,
object_paths_dict,
) = tf.__internal__.tracking.ObjectGraphView(
self
).breadth_first_traversal()
for descendant in descendants:
if isinstance(descendant, tf.Variable):
trackable_references = object_paths_dict[descendant]
object_path = ".".join([t.name for t in trackable_references])
result[object_path] = descendant
return result
def get_compile_config(self):
"""Returns a serialized config with information for compiling the model.
This method returns a config dictionary containing all the information
(optimizer, loss, metrics, etc.) with which the model was compiled.
Returns:
A dict containing information for compiling the model.
"""
if self._is_compiled and hasattr(self, "_compile_config"):
return self._compile_config.serialize()
def compile_from_config(self, config):
"""Compiles the model with the information given in config.
This method uses the information in the config (optimizer, loss,
metrics, etc.) to compile the model.
Args:
config: Dict containing information for compiling the model.
"""
has_overridden_compile = self.__class__.compile != Model.compile
if has_overridden_compile:
logging.warning(
"`compile()` was not called as part of model loading "
"because the model's `compile()` method is custom. "
"All subclassed Models that have `compile()` "
"overridden should also override "
"`get_compile_config()` and `compile_from_config(config)`. "
"Alternatively, you can "
"call `compile()` manually after loading."
)
return
config = saving_lib.deserialize_keras_object(config)
self.compile(**config)
if (
hasattr(self, "optimizer")
# Exempt legacy optimizers.
and isinstance(self.optimizer, optimizer.Optimizer)
and self.built
):
# Create optimizer variables.
self.optimizer.build(self.trainable_variables)
def export(self, filepath):
"""Create a SavedModel artifact for inference (e.g. via TF-Serving).
This method lets you export a model to a lightweight SavedModel artifact
that contains the model's forward pass only (its `call()` method)
and can be served via e.g. TF-Serving. The forward pass is registered
under the name `serve()` (see example below).
The original code of the model (including any custom layers you may
have used) is *no longer* necessary to reload the artifact -- it is
entirely standalone.
Args:
filepath: `str` or `pathlib.Path` object. Path where to save
the artifact.
Example:
```python
# Create the artifact
model.export("path/to/location")
# Later, in a different process / environment...
reloaded_artifact = tf.saved_model.load("path/to/location")
predictions = reloaded_artifact.serve(input_data)
```
If you would like to customize your serving endpoints, you can
use the lower-level `keras.export.ExportArchive` class. The `export()`
method relies on `ExportArchive` internally.
"""
from tf_keras.src.export import export_lib
export_lib.export_model(self, filepath)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _set_save_spec(self, inputs, args=None, kwargs=None):
"""Defines the save spec so that serialization can trace `call()`.
The TensorSpecs of the call function `inputs`, `args`, and `kwargs` are
saved into a tuple of `([inputs] + args, kwargs)`. The input
`TensorSpec` names are updated to match the built `input_names`.
The specs can be retrieved with the `save_spec` property.
Args:
inputs: possibly nested inputs passed into the call function.
args: a list of positional arguments passed into call.
kwargs: a dictionary of keyword arguments passed into call.
"""
if self._saved_model_inputs_spec is not None:
return # Already set.
args = args or []
kwargs = kwargs or {}
input_names = self.input_names
if not input_names:
input_names = compile_utils.create_pseudo_input_names(inputs)
flat_inputs = tf.nest.flatten(inputs)
inputs_spec = []
for name, tensor in zip(input_names, flat_inputs):
inputs_spec.append(
tf_utils.get_tensor_spec(tensor, dynamic_batch=False, name=name)
)
inputs_spec = tf.nest.pack_sequence_as(inputs, inputs_spec)
super()._set_save_spec(inputs_spec, args, kwargs)
# Store the input shapes
if (
self.__class__.__name__ == "Sequential"
and self._build_input_shape is None
):
self._build_input_shape = tf.nest.map_structure(
lambda x: None if x is None else x.shape, inputs_spec
)
def save_spec(self, dynamic_batch=True):
"""Returns the `tf.TensorSpec` of call args as a tuple `(args, kwargs)`.
This value is automatically defined after calling the model for the
first time. Afterwards, you can use it when exporting the model for
serving:
```python
model = tf.keras.Model(...)
@tf.function
def serve(*args, **kwargs):
outputs = model(*args, **kwargs)
# Apply postprocessing steps, or add additional outputs.
...
return outputs
# arg_specs is `[tf.TensorSpec(...), ...]`. kwarg_specs, in this
# example, is an empty dict since functional models do not use keyword
# arguments.
arg_specs, kwarg_specs = model.save_spec()
model.save(path, signatures={
'serving_default': serve.get_concrete_function(*arg_specs,
**kwarg_specs)
})
```
Args:
dynamic_batch: Whether to set the batch sizes of all the returned
`tf.TensorSpec` to `None`. (Note that when defining functional or
Sequential models with `tf.keras.Input([...], batch_size=X)`, the
batch size will always be preserved). Defaults to `True`.
Returns:
If the model inputs are defined, returns a tuple `(args, kwargs)`. All
elements in `args` and `kwargs` are `tf.TensorSpec`.
If the model inputs are not defined, returns `None`.
The model inputs are automatically set when calling the model,
`model.fit`, `model.evaluate` or `model.predict`.
"""
return self._get_save_spec(dynamic_batch, inputs_only=False)
def _assert_weights_created(self):
"""Asserts that all the weights for the model have been created.
For a non-dynamic model, the weights must already be created after the
layer has been called. For a dynamic model, the exact list of weights
can never be known for certain since it may change at any time during
execution.
We run this check right before accessing weights or getting the Numpy
value for the current weights. Otherwise, if the layer has never been
called, the user would just get an empty list, which is misleading.
Raises:
ValueError: if the weights of the network have not yet been created.
"""
if self.dynamic:
return
if (
"build" in self.__class__.__dict__
and self.__class__ != Model
and not self.built
):
# For any model that has customized build() method but hasn't been
# invoked yet, this will cover both sequential and subclass model.
# Also make sure to exclude Model class itself which has build()
# defined.
raise ValueError(
f"Weights for model '{self.name}' have not yet been "
"created. "
"Weights are created when the model is first called on "
"inputs or `build()` is called with an `input_shape`."
)
def _check_call_args(self, method_name):
"""Check that `call()` has only one positional arg."""
# Always allow first arg, regardless of arg name.
fullargspec = self._call_spec.full_argspec
if fullargspec.defaults:
positional_args = fullargspec.args[: -len(fullargspec.defaults)]
else:
positional_args = fullargspec.args
if "training" in positional_args:
positional_args.remove("training")
# self and first arg can be positional.
if len(positional_args) > 2:
extra_args = positional_args[2:]
raise ValueError(
f"Models passed to `{method_name}` can only have `training` "
"and the first argument in `call()` as positional arguments, "
f"found: {extra_args}."
)
def _validate_compile(self, optimizer, metrics, **kwargs):
"""Performs validation checks for the default `compile()`."""
if any(
isinstance(opt, optimizer_v1.Optimizer)
for opt in tf.nest.flatten(optimizer)
):
raise ValueError(
f"`tf.compat.v1.keras` Optimizer ({optimizer}) is "
"not supported when eager execution is enabled. Use a "
"`tf.keras` Optimizer instead, or disable eager "
"execution."
)
kwargs.pop("cloning", None) # Legacy DistStrat argument, never used.
kwargs.pop("experimental_run_tf_function", None) # Always `True`.
distribute_arg = kwargs.pop("distribute", None)
if distribute_arg is not None:
raise ValueError(
"`distribute` argument in compile is not available in TF 2.0. "
"Please create the model under the `strategy.scope()`. "
f"Received: {distribute_arg}."
)
target_tensor_arg = kwargs.pop("target_tensors", None)
if target_tensor_arg is not None:
raise ValueError(
"`target_tensors` argument is not supported when executing "
f"eagerly. Received: {target_tensor_arg}."
)
invalid_kwargs = set(kwargs) - {"sample_weight_mode"}
if invalid_kwargs:
raise TypeError(
"Invalid keyword argument(s) in `compile()`: "
f"{(invalid_kwargs,)}. Valid keyword arguments include "
'"cloning", "experimental_run_tf_function", "distribute",'
' "target_tensors", or "sample_weight_mode".'
)
# Model must be created and compiled with the same DistStrat.
if self.built and tf.distribute.has_strategy():
strategy = tf.distribute.get_strategy()
for v in self.variables:
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Variable ({v}) was not created in the distribution "
f"strategy scope of ({strategy}). It is most likely "
"because some layers, model, or optimizer was being "
"created outside the distribution strategy scope. Try "
"to make sure your code looks similar "
"to the following.\nwith strategy.scope():\n"
" model=_create_model()\n"
" model.compile(...)"
)
# Model metrics must be created in the same distribution strategy scope
# as the model.
strategy = self.distribute_strategy
for metric in tf.nest.flatten(metrics):
for v in getattr(metric, "variables", []):
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Metric ({metric}) passed to `model.compile` was "
"created inside a different distribution strategy "
"scope than the model. All metrics must be created "
"in the same distribution strategy "
f"scope as the model (in this case {strategy}). "
"If you pass in a string identifier for a metric to "
"compile, the metric will automatically be created "
"in the correct distribution strategy scope."
)
# Model metrics must be created in the same distribution strategy scope
# as the model.
for opt in tf.nest.flatten(optimizer):
for v in getattr(opt, "_weights", []):
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Optimizer ({optimizer}) passed to `model.compile` "
"was created inside a different distribution strategy "
"scope than the model. All optimizers must be created "
"in the same distribution strategy scope as the model "
f"(in this case {strategy}). If you pass in a string "
"identifier for an optimizer to compile, the optimizer "
"will automatically be created in the correct "
"distribution strategy scope."
)
def _maybe_load_initial_counters_from_ckpt(
self, steps_per_epoch, initial_epoch
):
"""Maybe load initial epoch from ckpt, considering worker recovery.
Refer to tensorflow/python/tf_keras/distribute/worker_training_state.py
for more information.
Args:
steps_per_epoch: The number of step per epoch.
initial_epoch: The original initial_epoch user passes in `fit()`.
mode: The mode for running `model.fit()`.
Returns:
If the training is recovering from previous failure under multi-worker
training setting, return the (epoch, step) the training is supposed to
continue at. Otherwise, return the `initial_epoch, initial_step` the
user passes in.
"""
initial_step = 0
if self._training_state is not None:
return self._training_state.maybe_load_initial_counters_from_ckpt(
steps_per_epoch, initial_epoch, mode=ModeKeys.TRAIN
)
return (initial_epoch, initial_step)
def _assert_compile_was_called(self):
# Checks whether `compile` has been called. If it has been called,
# then the optimizer is set. This is different from whether the
# model is compiled
# (i.e. whether the model is built and its inputs/outputs are set).
if not self._is_compiled:
raise RuntimeError(
"You must compile your model before "
"training/testing. "
"Use `model.compile(optimizer, loss)`."
)
def _check_sample_weight_warning(self, x, sample_weight):
# Datasets can include sample weight, by returning a tuple with the
# structure of `(x, y, sample_weight)`.
sample_weight_present = sample_weight is not None or (
isinstance(x, tf.data.Dataset)
and isinstance(x.element_spec, tuple)
and len(x.element_spec) == 3
)
if (
sample_weight_present
and self.compiled_metrics._user_weighted_metrics is None
):
logging.warning(
"`evaluate()` received a value for `sample_weight`, but "
"`weighted_metrics` were not provided. Did you mean to pass "
"metrics to `weighted_metrics` in `compile()`? If this is "
"intentional you can pass `weighted_metrics=[]` to `compile()` "
"in order to silence this warning."
)
def _set_inputs(self, inputs, outputs=None, training=None):
"""This method is for compat with Modelv1. Only inputs are needed
here."""
self._set_save_spec(inputs)
@property
def _trackable_saved_model_saver(self):
return model_serialization.ModelSavedModelSaver(self)
def _trackable_children(self, save_type="checkpoint", **kwargs):
if save_type == "savedmodel":
# SavedModel needs to ignore the execution functions.
train_function = self.train_function
test_function = self.test_function
predict_function = self.predict_function
train_tf_function = self.train_tf_function
self.train_function = None
self.test_function = None
self.predict_function = None
self.train_tf_function = None
children = super()._trackable_children(save_type, **kwargs)
if save_type == "savedmodel":
self.train_function = train_function
self.test_function = test_function
self.predict_function = predict_function
self.train_tf_function = train_tf_function
return children
def _should_eval(self, epoch, validation_freq):
epoch = epoch + 1 # one-index the user-facing epoch.
if isinstance(validation_freq, int):
return epoch % validation_freq == 0
elif isinstance(validation_freq, list):
return epoch in validation_freq
else:
raise ValueError(
"Expected `validation_freq` to be a list or int. "
f"Received: validation_freq={validation_freq} of the "
f"type {type(validation_freq)}."
)
######################################################################
# Functions below exist only as v1 / v2 compatibility shims.
######################################################################
def _get_compile_args(self, user_metrics=True):
"""Used for saving or cloning a Model.
Args:
user_metrics: Whether to return user-supplied metrics or `Metric`
objects. If True, returns the user-supplied metrics.
Defaults to `True`.
Returns:
Dictionary of arguments that were used when compiling the model.
"""
self._assert_compile_was_called()
saved_metrics = self.compiled_metrics._user_metrics
saved_weighted_metrics = self.compiled_metrics._user_weighted_metrics
if not user_metrics:
if saved_metrics is not None:
saved_metrics = self.compiled_metrics._metrics
if saved_weighted_metrics is not None:
saved_weighted_metrics = self.compiled_metrics._weighted_metrics
compile_args = {
"optimizer": self.optimizer,
"loss": self.compiled_loss._user_losses,
"metrics": saved_metrics,
"weighted_metrics": saved_weighted_metrics,
"loss_weights": self.compiled_loss._user_loss_weights,
}
return compile_args
def _get_callback_model(self):
return self
def _in_multi_worker_mode(self):
return self.distribute_strategy.extended._in_multi_worker_mode()
@property
def _compile_was_called(self):
return self._is_compiled
| (self, filepath, skip_mismatch=False, by_name=False, options=None) |
725,030 | tf_keras.src.engine.training | make_predict_function | Creates a function that executes one step of inference.
This method can be overridden to support custom inference logic.
This method is called by `Model.predict` and `Model.predict_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.predict_step`.
This function is cached the first time `Model.predict` or
`Model.predict_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the predict function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return the outputs of the `Model`.
| def make_predict_function(self, force=False):
"""Creates a function that executes one step of inference.
This method can be overridden to support custom inference logic.
This method is called by `Model.predict` and `Model.predict_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.predict_step`.
This function is cached the first time `Model.predict` or
`Model.predict_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the predict function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return the outputs of the `Model`.
"""
if self.predict_function is not None and not force:
return self.predict_function
def step_function(model, iterator):
"""Runs a single evaluation step."""
def run_step(data):
outputs = model.predict_step(data)
# Ensure counter is updated only if `test_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._predict_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs, self.distribute_strategy, reduction="concat"
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def predict_function(iterator):
"""Runs an evaluation execution with a single step."""
return step_function(self, iterator)
else:
def predict_function(iterator):
"""Runs an evaluation execution with multiple steps."""
outputs = step_function(self, iterator)
for _ in tf.range(self._steps_per_execution - 1):
tf.autograph.experimental.set_loop_options(
shape_invariants=[
(
outputs,
tf.nest.map_structure(
lambda t: tf_utils.get_tensor_spec(
t, dynamic_batch=True
).shape,
outputs,
),
)
]
)
step_outputs = step_function(self, iterator)
outputs = tf.nest.map_structure(
lambda t1, t2: concat([t1, t2]), outputs, step_outputs
)
return outputs
if not self.run_eagerly:
predict_function = tf.function(
predict_function, reduce_retracing=True
)
self.predict_function = predict_function
return self.predict_function
| (self, force=False) |
725,031 | tf_keras.src.engine.training | make_test_function | Creates a function that executes one step of evaluation.
This method can be overridden to support custom evaluation logic.
This method is called by `Model.evaluate` and `Model.test_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.test_step`.
This function is cached the first time `Model.evaluate` or
`Model.test_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the test function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_test_batch_end`.
| def make_test_function(self, force=False):
"""Creates a function that executes one step of evaluation.
This method can be overridden to support custom evaluation logic.
This method is called by `Model.evaluate` and `Model.test_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.test_step`.
This function is cached the first time `Model.evaluate` or
`Model.test_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the test function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_test_batch_end`.
"""
if self.test_function is not None and not force:
return self.test_function
def step_function(model, iterator):
"""Runs a single evaluation step."""
def run_step(data):
outputs = model.test_step(data)
# Ensure counter is updated only if `test_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._test_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def test_function(iterator):
"""Runs a test execution with a single step."""
return step_function(self, iterator)
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
if self._cluster_coordinator:
self.test_function = (
lambda it: self._cluster_coordinator.schedule(
test_function, args=(it,)
)
)
else:
self.test_function = test_function
# If we're using a coordinator, use the value of
# self._steps_per_execution at the time the function is
# called/scheduled, and not when it is actually executed.
elif self._cluster_coordinator:
def test_function(iterator, steps_per_execution):
"""Runs a test execution with multiple steps."""
for _ in tf.range(steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
self.test_function = lambda it: self._cluster_coordinator.schedule(
test_function, args=(it, self._steps_per_execution.value())
)
else:
def test_function(iterator):
"""Runs a test execution with multiple steps."""
for _ in tf.range(self._steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
self.test_function = test_function
return self.test_function
| (self, force=False) |
725,032 | tf_keras.src.engine.training | make_train_function | Creates a function that executes one step of training.
This method can be overridden to support custom training logic.
This method is called by `Model.fit` and `Model.train_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual training
logic to `Model.train_step`.
This function is cached the first time `Model.fit` or
`Model.train_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the train function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_train_batch_end`, such as
`{'loss': 0.2, 'accuracy': 0.7}`.
| def make_train_function(self, force=False):
"""Creates a function that executes one step of training.
This method can be overridden to support custom training logic.
This method is called by `Model.fit` and `Model.train_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual training
logic to `Model.train_step`.
This function is cached the first time `Model.fit` or
`Model.train_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the train function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_train_batch_end`, such as
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
if self.train_function is not None and not force:
return self.train_function
def step_function(model, iterator):
"""Runs a single training step."""
def run_step(data):
outputs = model.train_step(data)
# Ensure counter is updated only if `train_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._train_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def train_function(iterator):
"""Runs a training execution with a single step."""
return step_function(self, iterator)
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
if self._cluster_coordinator:
self.train_function = (
lambda it: self._cluster_coordinator.schedule(
train_function, args=(it,)
)
)
else:
self.train_function = train_function
# If we're using a coordinator, use the value of
# self._steps_per_execution at the time the function is
# called/scheduled, and not when it is actually executed.
elif self._cluster_coordinator:
def train_function(iterator, steps_per_execution):
"""Runs a training execution with multiple steps."""
for _ in tf.range(steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
self.train_function = lambda it: self._cluster_coordinator.schedule(
train_function, args=(it, self._steps_per_execution.value())
)
else:
def train_function(iterator):
"""Runs a training execution with multiple steps."""
for _ in tf.range(self._steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
self.train_function = train_function
return self.train_function
| (self, force=False) |
725,033 | tf_keras.src.engine.training | predict | Generates output predictions for the input samples.
Computation is done in batches. This method is designed for batch
processing of large numbers of inputs. It is not intended for use inside
of loops that iterate over your data and process small numbers of inputs
at a time.
For small numbers of inputs that fit in one batch,
directly use `__call__()` for faster execution, e.g.,
`model(x)`, or `model(x, training=False)` if you have layers such as
`tf.keras.layers.BatchNormalization` that behave differently during
inference. You may pair the individual model call with a `tf.function`
for additional performance inside your inner loop.
If you need access to numpy array values instead of tensors after your
model call, you can use `tensor.numpy()` to get the numpy array value of
an eager tensor.
Also, note the fact that test loss is not affected by
regularization layers like noise and dropout.
Note: See [this FAQ entry](
https://keras.io/getting_started/faq/#whats-the-difference-between-model-methods-predict-and-call)
for more details about the difference between `Model` methods
`predict()` and `__call__()`.
Args:
x: Input samples. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A `tf.data` dataset.
- A generator or `keras.utils.Sequence` instance.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given in the `Unpacking
behavior for iterator-like inputs` section of `Model.fit`.
batch_size: Integer or `None`.
Number of samples per batch.
If unspecified, `batch_size` will default to 32.
Do not specify the `batch_size` if your data is in the
form of dataset, generators, or `keras.utils.Sequence` instances
(since they generate batches).
verbose: `"auto"`, 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = single line.
`"auto"` becomes 1 for most cases, and to 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so `verbose=2` is
recommended when not running interactively (e.g. in a production
environment). Defaults to 'auto'.
steps: Total number of steps (batches of samples)
before declaring the prediction round finished.
Ignored with the default value of `None`. If x is a `tf.data`
dataset and `steps` is None, `predict()` will
run until the input dataset is exhausted.
callbacks: List of `keras.callbacks.Callback` instances.
List of callbacks to apply during prediction.
See [callbacks](
https://www.tensorflow.org/api_docs/python/tf/tf_keras/callbacks).
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the
generator queue. If unspecified, `max_queue_size` will default
to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, `workers` will default
to 1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
See the discussion of `Unpacking behavior for iterator-like inputs` for
`Model.fit`. Note that Model.predict uses the same interpretation rules
as `Model.fit` and `Model.evaluate`, so inputs must be unambiguous for
all three methods.
Returns:
Numpy array(s) of predictions.
Raises:
RuntimeError: If `model.predict` is wrapped in a `tf.function`.
ValueError: In case of mismatch between the provided
input data and the model's expectations,
or in case a stateful model receives a number of samples
that is not a multiple of the batch size.
| # 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.
# ==============================================================================
"""Training-related part of the TF-Keras engine."""
import copy
import itertools
import json
import warnings
import weakref
import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow.python.distribute import distribute_utils
from tensorflow.python.distribute import input_ops
from tensorflow.python.eager import context
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util.tf_export import keras_export
from tensorflow.tools.docs import doc_controls
from tf_keras.src import backend
from tf_keras.src import callbacks as callbacks_module
from tf_keras.src import optimizers
from tf_keras.src.dtensor import dtensor_api
from tf_keras.src.dtensor import layout_map as layout_map_lib
from tf_keras.src.engine import base_layer
from tf_keras.src.engine import base_layer_utils
from tf_keras.src.engine import compile_utils
from tf_keras.src.engine import data_adapter
from tf_keras.src.engine import input_layer as input_layer_module
from tf_keras.src.engine import training_utils
from tf_keras.src.metrics import base_metric
from tf_keras.src.mixed_precision import loss_scale_optimizer as lso
from tf_keras.src.optimizers import optimizer
from tf_keras.src.optimizers import optimizer_v1
from tf_keras.src.saving import pickle_utils
from tf_keras.src.saving import saving_api
from tf_keras.src.saving import saving_lib
from tf_keras.src.saving import serialization_lib
from tf_keras.src.saving.legacy import serialization
from tf_keras.src.saving.legacy.saved_model import json_utils
from tf_keras.src.saving.legacy.saved_model import model_serialization
from tf_keras.src.utils import generic_utils
from tf_keras.src.utils import io_utils
from tf_keras.src.utils import layer_utils
from tf_keras.src.utils import steps_per_execution_tuning
from tf_keras.src.utils import tf_inspect
from tf_keras.src.utils import tf_utils
from tf_keras.src.utils import traceback_utils
from tf_keras.src.utils import version_utils
from tf_keras.src.utils.mode_keys import ModeKeys
try:
import h5py
except ImportError:
h5py = None
@keras_export("keras.Model", "keras.models.Model")
class Model(base_layer.Layer, version_utils.ModelVersionSelector):
"""A model grouping layers into an object with training/inference features.
Args:
inputs: The input(s) of the model: a `keras.Input` object or a
combination of `keras.Input` objects in a dict, list or tuple.
outputs: The output(s) of the model: a tensor that originated from
`keras.Input` objects or a combination of such tensors in a dict,
list or tuple. See Functional API example below.
name: String, the name of the model.
There are two ways to instantiate a `Model`:
1 - With the "Functional API", where you start from `Input`,
you chain layer calls to specify the model's forward pass,
and finally you create your model from inputs and outputs:
```python
import tensorflow as tf
inputs = tf.keras.Input(shape=(3,))
x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)
outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
```
Note: Only dicts, lists, and tuples of input tensors are supported. Nested
inputs are not supported (e.g. lists of list or dicts of dict).
A new Functional API model can also be created by using the
intermediate tensors. This enables you to quickly extract sub-components
of the model.
Example:
```python
inputs = keras.Input(shape=(None, None, 3))
processed = keras.layers.RandomCrop(width=32, height=32)(inputs)
conv = keras.layers.Conv2D(filters=2, kernel_size=3)(processed)
pooling = keras.layers.GlobalAveragePooling2D()(conv)
feature = keras.layers.Dense(10)(pooling)
full_model = keras.Model(inputs, feature)
backbone = keras.Model(processed, conv)
activations = keras.Model(conv, feature)
```
Note that the `backbone` and `activations` models are not
created with `keras.Input` objects, but with the tensors that are originated
from `keras.Input` objects. Under the hood, the layers and weights will
be shared across these models, so that user can train the `full_model`, and
use `backbone` or `activations` to do feature extraction.
The inputs and outputs of the model can be nested structures of tensors as
well, and the created models are standard Functional API models that support
all the existing APIs.
2 - By subclassing the `Model` class: in that case, you should define your
layers in `__init__()` and you should implement the model's forward pass
in `call()`.
```python
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
def call(self, inputs):
x = self.dense1(inputs)
return self.dense2(x)
model = MyModel()
```
If you subclass `Model`, you can optionally have
a `training` argument (boolean) in `call()`, which you can use to specify
a different behavior in training and inference:
```python
import tensorflow as tf
class MyModel(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
self.dropout = tf.keras.layers.Dropout(0.5)
def call(self, inputs, training=False):
x = self.dense1(inputs)
if training:
x = self.dropout(x, training=training)
return self.dense2(x)
model = MyModel()
```
Once the model is created, you can config the model with losses and metrics
with `model.compile()`, train the model with `model.fit()`, or use the model
to do prediction with `model.predict()`.
"""
_TF_MODULE_IGNORED_PROPERTIES = frozenset(
itertools.chain(
(
"_train_counter",
"_test_counter",
"_predict_counter",
"_steps_per_execution",
"_compiled_trainable_state",
),
base_layer.Layer._TF_MODULE_IGNORED_PROPERTIES,
)
)
_SCALAR_UPRANKING_ON = False
def __new__(cls, *args, **kwargs):
# Signature detection
if is_functional_model_init_params(args, kwargs) and cls == Model:
# Functional model
from tf_keras.src.engine import functional
return functional.Functional(skip_init=True, *args, **kwargs)
else:
return super(Model, cls).__new__(cls, *args, **kwargs)
@tf.__internal__.tracking.no_automatic_dependency_tracking
@traceback_utils.filter_traceback
def __init__(self, *args, **kwargs):
self._is_model_for_instrumentation = True
# Special case for Subclassed Functional Model, which we couldn't detect
# when __new__ is called. We only realize it is a functional model when
# it calls super.__init__ with input and output tensor.
from tf_keras.src.engine import functional
if is_functional_model_init_params(args, kwargs) and not isinstance(
self, functional.Functional
):
# Filter the kwargs for multiple inheritance.
supported_kwargs = [
"inputs",
"outputs",
"name",
"trainable",
"skip_init",
]
model_kwargs = {
k: kwargs[k] for k in kwargs if k in supported_kwargs
}
other_kwargs = {
k: kwargs[k] for k in kwargs if k not in supported_kwargs
}
inject_functional_model_class(self.__class__)
functional.Functional.__init__(self, *args, **model_kwargs)
# In case there is any multiple inheritance here, we need to call
# the __init__ for any class that appears after the Functional
# class.
clz_to_init = []
found_functional_class = False
for clz in self.__class__.__bases__:
if issubclass(clz, functional.Functional):
found_functional_class = True
continue
if found_functional_class:
clz_to_init.append(clz)
if clz_to_init:
for clz in clz_to_init:
clz.__init__(self, *args, **other_kwargs)
elif other_kwargs:
# In case there are unused kwargs, we should raise an error to
# user, in case they have a typo in the param name.
raise TypeError(
"The following keyword arguments passed to `Model` aren't "
"supported: {}.".format(other_kwargs)
)
return
# The following are implemented as property functions:
# self.trainable_weights
# self.non_trainable_weights
# `inputs` / `outputs` will only appear in kwargs if either are
# misspelled.
generic_utils.validate_kwargs(
kwargs,
{
"trainable",
"dtype",
"dynamic",
"name",
"autocast",
"inputs",
"outputs",
},
)
super().__init__(**kwargs)
# By default, Model is a subclass model, which is not in graph network.
self._is_graph_network = False
self.inputs = None
self.outputs = None
self.input_names = None
self.output_names = None
# stop_training is used by callback to stop training when error happens
self.stop_training = False
self.history = None
# These objects are used in the default `Model.compile`. They are not
# guaranteed to be set after `Model.compile` is called, as users can
# override compile with custom logic.
self.compiled_loss = None
self.compiled_metrics = None
# This is True for Sequential networks and Functional networks.
self._compute_output_and_mask_jointly = False
# Don't reset compilation if already done. This may occur if calling
# `__init__` (or `_init_graph_network`) on an already-compiled model
# such as a Sequential model. Sequential models may need to rebuild
# themselves after compilation.
self._maybe_create_attribute("_is_compiled", False)
self._maybe_create_attribute("optimizer", None)
# Model must be created under scope of DistStrat it will be trained
# with.
if tf.distribute.has_strategy():
self._distribution_strategy = tf.distribute.get_strategy()
else:
self._distribution_strategy = None
self._distribute_reduction_method = None
self._cluster_coordinator = None
# Defaults to value of `tf.config.experimental_functions_run_eagerly`.
self._run_eagerly = None
# Initialize cache attrs.
self._reset_compile_cache()
# Fault-tolerance handler. Set in `ModelCheckpoint`.
self._training_state = None
self._saved_model_inputs_spec = None
self._saved_model_arg_spec = None
self._checkpoint = tf.train.Checkpoint(root=weakref.ref(self))
self._steps_per_execution = None
self._steps_per_execution_tuner = None
self._autotune_steps_per_execution = False
self._layout_map = layout_map_lib.get_current_layout_map()
self._init_batch_counters()
self._base_model_initialized = True
# `jit_compile` starts off with None as default and gets overwritten by
# the value specified in `Model.compile`, and this is effective for
# `fit`, `evaluate`, and `predict`.
self._jit_compile = None
def _create_counter_variable(self, init_value):
"""Helper function for counter variable creation.
For the DTensor use case with layout map, since the variable are not
tracked by model, they can't be visited by the layout map, and need to
be properly initialized as DVariable.
"""
# This function should be removed after we move to the strategy based
# implementation for DTensor.
if self._layout_map is None:
agg = tf.VariableAggregation.ONLY_FIRST_REPLICA
return tf.Variable(init_value, dtype="int64", aggregation=agg)
else:
layout = dtensor_api.Layout.replicated(
mesh=self._layout_map.get_default_mesh(), rank=0
)
return dtensor_api.DVariable(
init_value, dtype="int64", layout=layout
)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _init_batch_counters(self):
# Untracked Variables, used to keep track of mini-batches seen in `fit`,
# `evaluate`, and `predict`.
if not tf.inside_function():
# Creating variables inside tf.function is not allowed, hence
# these would otherwise prevent users from creating TF-Keras layers
# inside tf.function.
# These variables are not connected to outputs so they have no
# effect on graph generation anyway.
self._train_counter = self._create_counter_variable(0)
self._test_counter = self._create_counter_variable(0)
self._predict_counter = self._create_counter_variable(0)
def __setattr__(self, name, value):
if not getattr(self, "_self_setattr_tracking", True):
super().__setattr__(name, value)
return
if all(
isinstance(v, (base_layer.Layer, tf.Variable))
or base_layer_utils.has_weights(v)
for v in tf.nest.flatten(value)
):
try:
self._base_model_initialized
except AttributeError:
raise RuntimeError(
"It looks like you are subclassing `Model` and you "
"forgot to call `super().__init__()`."
" Always start with this line."
)
super().__setattr__(name, value)
def __reduce__(self):
if self.built:
return (
pickle_utils.deserialize_model_from_bytecode,
(pickle_utils.serialize_model_as_bytecode(self),),
)
else:
# SavedModel (and hence serialize_model_as_bytecode) only support
# built models, but if the model is not built,
# it may be possible to serialize as a plain Python object,
# as long as the constituent parts (layers, optimizers, losses,
# etc.) can be serialized as plain Python objects. Thus we call up
# the superclass hierarchy to get an implementation of __reduce__
# that can pickle this Model as a plain Python object.
return super().__reduce__()
def __deepcopy__(self, memo):
if self.built:
new = pickle_utils.deserialize_model_from_bytecode(
pickle_utils.serialize_model_as_bytecode(self)
)
memo[id(self)] = new
else:
# See comment in __reduce__ for explanation
deserializer, serialized, *rest = super().__reduce__()
new = deserializer(*serialized)
memo[id(self)] = new
if rest:
state = copy.deepcopy(rest[0], memo=memo)
new.__setstate__(state)
return new
def __copy__(self):
return self.__deepcopy__({})
@generic_utils.default
def build(self, input_shape):
"""Builds the model based on input shapes received.
This is to be used for subclassed models, which do not know at
instantiation time what their inputs look like.
This method only exists for users who want to call `model.build()` in a
standalone way (as a substitute for calling the model on real data to
build it). It will never be called by the framework (and thus it will
never throw unexpected errors in an unrelated workflow).
Args:
input_shape: Single tuple, `TensorShape` instance, or list/dict of
shapes, where shapes are tuples, integers, or `TensorShape`
instances.
Raises:
ValueError:
1. In case of invalid user-provided data (not of type tuple,
list, `TensorShape`, or dict).
2. If the model requires call arguments that are agnostic
to the input shapes (positional or keyword arg in call
signature).
3. If not all layers were properly built.
4. If float type inputs are not supported within the layers.
In each of these cases, the user should build their model by calling
it on real tensor data.
"""
if self._is_graph_network:
super().build(input_shape)
return
if input_shape is None:
raise ValueError(
"Input shape must be defined when calling `build()` on "
"a `Model` subclass."
)
valid_types = (tuple, list, tf.TensorShape, dict)
if not isinstance(input_shape, valid_types):
raise ValueError(
"Specified input shape is not one of the valid types. "
"Please specify a batch input shape of type tuple or "
"list of input shapes. User provided "
"input type: {}.".format(type(input_shape))
)
if input_shape and not self.inputs:
# We create placeholders for the `None`s in the shape and build the
# model in a Graph. Since tf.Variable is compatible with both eager
# execution and graph building, the variables created after building
# the model in a Graph are still valid when executing eagerly.
if tf.executing_eagerly():
graph = tf.__internal__.FuncGraph("build_graph")
else:
graph = backend.get_graph()
with graph.as_default():
if isinstance(input_shape, list) and all(
d is None or isinstance(d, int) for d in input_shape
):
input_shape = tuple(input_shape)
if isinstance(input_shape, list):
x = [
base_layer_utils.generate_placeholders_from_shape(shape)
for shape in input_shape
]
elif isinstance(input_shape, dict):
x = {
k: base_layer_utils.generate_placeholders_from_shape(
shape
)
for k, shape in input_shape.items()
}
else:
x = base_layer_utils.generate_placeholders_from_shape(
input_shape
)
kwargs = {}
call_signature = self._call_spec.full_argspec
call_args = call_signature.args
# Exclude `self`, `inputs`, and any argument with a default
# value.
if len(call_args) > 2:
if call_signature.defaults:
call_args = call_args[2 : -len(call_signature.defaults)]
else:
call_args = call_args[2:]
for arg in call_args:
if arg == "training":
# Case where `training` is a positional arg with no
# default.
kwargs["training"] = False
else:
# Has invalid call signature with unknown positional
# arguments.
raise ValueError(
"Currently, you cannot build your model if it "
"has positional or keyword arguments that are "
"not inputs to the model, but are required for "
"its `call()` method. Instead, in order to "
"instantiate and build your model, `call()` "
"your model on real tensor data with all "
"expected call arguments. The argument "
"for `call()` can be a single list/tuple that "
"contains multiple inputs."
)
elif len(call_args) < 2:
# Signature without `inputs`.
raise ValueError(
"You can only call `build()` on a model if its "
"`call()` method accepts an `inputs` argument."
)
try:
self.call(x, **kwargs)
except (tf.errors.InvalidArgumentError, TypeError) as e:
raise ValueError(
"You cannot build your model by calling `build` "
"if your layers do not support float type inputs. "
"Instead, in order to instantiate and build your "
"model, call your model on real tensor data (of "
"the correct dtype).\n\nThe actual error from "
f"`call` is: {e}."
)
super().build(input_shape)
@traceback_utils.filter_traceback
def __call__(self, *args, **kwargs):
if self._layout_map is not None and not self.built:
# Note that this method is only overridden for DTensor and layout
# injection purpose.
# Capture the inputs and create graph input as replacement for model
# to initialize its weights first.
copied_args = copy.copy(args)
copied_kwargs = copy.copy(kwargs)
(
inputs,
copied_args,
copied_kwargs,
) = self._call_spec.split_out_first_arg(copied_args, copied_kwargs)
def _convert_to_graph_inputs(x):
if isinstance(x, (tf.Tensor, np.ndarray, float, int)):
x = tf.convert_to_tensor(x)
return input_layer_module.Input(x.shape)
# TODO(scottzhu): maybe better handle mask and training flag.
inputs = tf.nest.map_structure(_convert_to_graph_inputs, inputs)
copied_args = tf.nest.map_structure(
_convert_to_graph_inputs, copied_args
)
copied_kwargs = tf.nest.map_structure(
_convert_to_graph_inputs, copied_kwargs
)
with layout_map_lib.layout_map_scope(self._layout_map):
# We ignore the result here.
super().__call__(inputs, *copied_args, **copied_kwargs)
layout_map_lib._map_subclass_model_variable(self, self._layout_map)
return super().__call__(*args, **kwargs)
@doc_controls.doc_in_current_and_subclasses
def call(self, inputs, training=None, mask=None):
"""Calls the model on new inputs and returns the outputs as tensors.
In this case `call()` just reapplies
all ops in the graph to the new inputs
(e.g. build a new computational graph from the provided inputs).
Note: This method should not be called directly. It is only meant to be
overridden when subclassing `tf.keras.Model`.
To call a model on an input, always use the `__call__()` method,
i.e. `model(inputs)`, which relies on the underlying `call()` method.
Args:
inputs: Input tensor, or dict/list/tuple of input tensors.
training: Boolean or boolean scalar tensor, indicating whether to
run the `Network` in training mode or inference mode.
mask: A mask or list of masks. A mask can be either a boolean tensor
or None (no mask). For more details, check the guide
[here](https://www.tensorflow.org/guide/keras/masking_and_padding).
Returns:
A tensor if there is a single output, or
a list of tensors if there are more than one outputs.
"""
raise NotImplementedError(
"Unimplemented `tf.keras.Model.call()`: if you "
"intend to create a `Model` with the Functional "
"API, please provide `inputs` and `outputs` "
"arguments. Otherwise, subclass `Model` with an "
"overridden `call()` method."
)
@traceback_utils.filter_traceback
def compile(
self,
optimizer="rmsprop",
loss=None,
metrics=None,
loss_weights=None,
weighted_metrics=None,
run_eagerly=None,
steps_per_execution=None,
jit_compile=None,
pss_evaluation_shards=0,
**kwargs,
):
"""Configures the model for training.
Example:
```python
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-3),
loss=tf.keras.losses.BinaryCrossentropy(),
metrics=[tf.keras.metrics.BinaryAccuracy(),
tf.keras.metrics.FalseNegatives()])
```
Args:
optimizer: String (name of optimizer) or optimizer instance. See
`tf.keras.optimizers`.
loss: Loss function. May be a string (name of loss function), or
a `tf.keras.losses.Loss` instance. See `tf.keras.losses`. A loss
function is any callable with the signature `loss = fn(y_true,
y_pred)`, where `y_true` are the ground truth values, and
`y_pred` are the model's predictions.
`y_true` should have shape
`(batch_size, d0, .. dN)` (except in the case of
sparse loss functions such as
sparse categorical crossentropy which expects integer arrays of
shape `(batch_size, d0, .. dN-1)`).
`y_pred` should have shape `(batch_size, d0, .. dN)`.
The loss function should return a float tensor.
If a custom `Loss` instance is
used and reduction is set to `None`, return value has shape
`(batch_size, d0, .. dN-1)` i.e. per-sample or per-timestep loss
values; otherwise, it is a scalar. If the model has multiple
outputs, you can use a different loss on each output by passing a
dictionary or a list of losses. The loss value that will be
minimized by the model will then be the sum of all individual
losses, unless `loss_weights` is specified.
metrics: List of metrics to be evaluated by the model during
training and testing. Each of this can be a string (name of a
built-in function), function or a `tf.keras.metrics.Metric`
instance. See `tf.keras.metrics`. Typically you will use
`metrics=['accuracy']`.
A function is any callable with the signature `result = fn(y_true,
y_pred)`. To specify different metrics for different outputs of a
multi-output model, you could also pass a dictionary, such as
`metrics={'output_a':'accuracy', 'output_b':['accuracy', 'mse']}`.
You can also pass a list to specify a metric or a list of metrics
for each output, such as
`metrics=[['accuracy'], ['accuracy', 'mse']]`
or `metrics=['accuracy', ['accuracy', 'mse']]`. When you pass the
strings 'accuracy' or 'acc', we convert this to one of
`tf.keras.metrics.BinaryAccuracy`,
`tf.keras.metrics.CategoricalAccuracy`,
`tf.keras.metrics.SparseCategoricalAccuracy` based on the shapes
of the targets and of the model output. We do a similar
conversion for the strings 'crossentropy' and 'ce' as well.
The metrics passed here are evaluated without sample weighting; if
you would like sample weighting to apply, you can specify your
metrics via the `weighted_metrics` argument instead.
loss_weights: Optional list or dictionary specifying scalar
coefficients (Python floats) to weight the loss contributions of
different model outputs. The loss value that will be minimized by
the model will then be the *weighted sum* of all individual
losses, weighted by the `loss_weights` coefficients. If a list,
it is expected to have a 1:1 mapping to the model's outputs. If a
dict, it is expected to map output names (strings) to scalar
coefficients.
weighted_metrics: List of metrics to be evaluated and weighted by
`sample_weight` or `class_weight` during training and testing.
run_eagerly: Bool. If `True`, this `Model`'s logic will not be
wrapped in a `tf.function`. Recommended to leave this as `None`
unless your `Model` cannot be run inside a `tf.function`.
`run_eagerly=True` is not supported when using
`tf.distribute.experimental.ParameterServerStrategy`. Defaults to
`False`.
steps_per_execution: Int or `'auto'`. The number of batches to
run during each `tf.function` call. If set to "auto", keras will
automatically tune `steps_per_execution` during runtime. Running
multiple batches inside a single `tf.function` call can greatly
improve performance on TPUs, when used with distributed strategies
such as `ParameterServerStrategy`, or with small models with a
large Python overhead. At most, one full epoch will be run each
execution. If a number larger than the size of the epoch is
passed, the execution will be truncated to the size of the epoch.
Note that if `steps_per_execution` is set to `N`,
`Callback.on_batch_begin` and `Callback.on_batch_end` methods will
only be called every `N` batches (i.e. before/after each
`tf.function` execution). Defaults to `1`.
jit_compile: If `True`, compile the model training step with XLA.
[XLA](https://www.tensorflow.org/xla) is an optimizing compiler
for machine learning.
`jit_compile` is not enabled for by default.
Note that `jit_compile=True`
may not necessarily work for all models.
For more information on supported operations please refer to the
[XLA documentation](https://www.tensorflow.org/xla).
Also refer to
[known XLA issues](https://www.tensorflow.org/xla/known_issues)
for more details.
pss_evaluation_shards: Integer or 'auto'. Used for
`tf.distribute.ParameterServerStrategy` training only. This arg
sets the number of shards to split the dataset into, to enable an
exact visitation guarantee for evaluation, meaning the model will
be applied to each dataset element exactly once, even if workers
fail. The dataset must be sharded to ensure separate workers do
not process the same data. The number of shards should be at least
the number of workers for good performance. A value of 'auto'
turns on exact evaluation and uses a heuristic for the number of
shards based on the number of workers. 0, meaning no
visitation guarantee is provided. NOTE: Custom implementations of
`Model.test_step` will be ignored when doing exact evaluation.
Defaults to `0`.
**kwargs: Arguments supported for backwards compatibility only.
"""
if jit_compile and not tf_utils.can_jit_compile(warn=True):
jit_compile = False
self._compile_config = serialization_lib.Config(
optimizer=optimizer,
loss=loss,
metrics=metrics,
loss_weights=loss_weights,
weighted_metrics=weighted_metrics,
run_eagerly=run_eagerly,
steps_per_execution=steps_per_execution,
jit_compile=jit_compile,
)
with self.distribute_strategy.scope():
if "experimental_steps_per_execution" in kwargs:
logging.warning(
"The argument `steps_per_execution` is no longer "
"experimental. Pass `steps_per_execution` instead of "
"`experimental_steps_per_execution`."
)
if not steps_per_execution:
steps_per_execution = kwargs.pop(
"experimental_steps_per_execution"
)
# When compiling from an already-serialized model, we do not want to
# reapply some processing steps (e.g. metric renaming for
# multi-output models, which have prefixes added for each
# corresponding output name).
from_serialized = kwargs.pop("from_serialized", False)
self._validate_compile(optimizer, metrics, **kwargs)
self._run_eagerly = run_eagerly
self.optimizer = self._get_optimizer(optimizer)
mesh = None
if self._layout_map is not None:
mesh = self._layout_map.get_default_mesh()
if isinstance(loss, compile_utils.LossesContainer):
self.compiled_loss = loss
else:
self.compiled_loss = compile_utils.LossesContainer(
loss,
loss_weights,
output_names=self.output_names,
mesh=mesh,
)
self.compiled_metrics = compile_utils.MetricsContainer(
metrics,
weighted_metrics,
output_names=self.output_names,
from_serialized=from_serialized,
mesh=mesh,
)
if steps_per_execution == "auto":
if self._steps_per_execution is None:
self._configure_steps_per_execution(1)
self._steps_per_execution_tuner = (
steps_per_execution_tuning.StepsPerExecutionTuner(
self.optimizer, self._steps_per_execution
)
)
self._autotune_steps_per_execution = True
else:
self._configure_steps_per_execution(steps_per_execution or 1)
self._pss_evaluation_shards = self._infer_exact_eval_shards(
pss_evaluation_shards
)
# Initializes attrs that are reset each time `compile` is called.
self._reset_compile_cache()
self._is_compiled = True
self.loss = loss or {}
if (self._run_eagerly or self.dynamic) and jit_compile:
raise ValueError(
"You cannot enable `run_eagerly` and `jit_compile` "
"at the same time."
)
else:
self._jit_compile = jit_compile
def _get_optimizer(self, optimizer):
"""Wraps `optimizer` in `LossScaleOptimizer` if necessary."""
def _get_single_optimizer(opt):
opt = optimizers.get(opt)
if self.dtype_policy.name == "mixed_float16" and not isinstance(
opt, lso.BaseLossScaleOptimizer
):
# Loss scaling is necessary with mixed_float16 for models to
# converge to the same accuracy as with float32.
opt = lso.BaseLossScaleOptimizer(opt)
return opt
return tf.nest.map_structure(_get_single_optimizer, optimizer)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _reset_compile_cache(self):
self.train_function = None
self.test_function = None
self.predict_function = None
# Used to cache the `tf.function`'ed `train_function` to be logged in
# TensorBoard, since the original `train_function` is not necessarily
# a `tf.function` (e.g., with ParameterServerStrategy, the
# `train_function` is a scheduling of the actual training function to a
# remote worker).
self.train_tf_function = None
# Used to cache `trainable` attr of `Layer`s for `fit`.
self._compiled_trainable_state = self._get_trainable_state()
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _configure_steps_per_execution(self, steps_per_execution):
self._steps_per_execution = self._create_counter_variable(
steps_per_execution
)
@property
def _should_compute_mask(self):
return False
@property
def metrics(self):
"""Return metrics added using `compile()` or `add_metric()`.
Note: Metrics passed to `compile()` are available only after a
`keras.Model` has been trained/evaluated on actual data.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> [m.name for m in model.metrics]
[]
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> model.fit(x, y)
>>> [m.name for m in model.metrics]
['loss', 'mae']
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> d = tf.keras.layers.Dense(2, name='out')
>>> output_1 = d(inputs)
>>> output_2 = d(inputs)
>>> model = tf.keras.models.Model(
... inputs=inputs, outputs=[output_1, output_2])
>>> model.add_metric(
... tf.reduce_sum(output_2), name='mean', aggregation='mean')
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
>>> model.fit(x, (y, y))
>>> [m.name for m in model.metrics]
['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',
'out_1_acc', 'mean']
"""
metrics = []
if self._is_compiled:
if self.compiled_loss is not None:
metrics += self.compiled_loss.metrics
if self.compiled_metrics is not None:
metrics += self.compiled_metrics.metrics
for l in self._flatten_layers():
metrics.extend(l._metrics)
return metrics
@property
def metrics_names(self):
"""Returns the model's display labels for all outputs.
Note: `metrics_names` are available only after a `keras.Model` has been
trained/evaluated on actual data.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> model.metrics_names
[]
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> model.fit(x, y)
>>> model.metrics_names
['loss', 'mae']
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> d = tf.keras.layers.Dense(2, name='out')
>>> output_1 = d(inputs)
>>> output_2 = d(inputs)
>>> model = tf.keras.models.Model(
... inputs=inputs, outputs=[output_1, output_2])
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
>>> model.fit(x, (y, y))
>>> model.metrics_names
['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',
'out_1_acc']
"""
# This property includes all output names including `loss` and
# per-output losses for backward compatibility.
return [m.name for m in self.metrics]
@property
def distribute_strategy(self):
"""The `tf.distribute.Strategy` this model was created under."""
return self._distribution_strategy or tf.distribute.get_strategy()
@property
def run_eagerly(self):
"""Settable attribute indicating whether the model should run eagerly.
Running eagerly means that your model will be run step by step,
like Python code. Your model might run slower, but it should become
easier for you to debug it by stepping into individual layer calls.
By default, we will attempt to compile your model to a static graph to
deliver the best execution performance.
Returns:
Boolean, whether the model should run eagerly.
"""
if self.dynamic and self._run_eagerly == False:
# TODO(fchollet): consider using py_func to enable this.
raise ValueError(
"Your model contains layers that can only be "
"successfully run in eager execution (layers "
"constructed with `dynamic=True`). "
"You cannot set `run_eagerly=False`."
)
if self._cluster_coordinator and self._run_eagerly:
raise ValueError(
"When using `Model` with `ParameterServerStrategy`, "
"`run_eagerly` is not supported."
)
# Run eagerly logic, by priority:
# (1) Dynamic models must be run eagerly.
# (2) Explicitly setting run_eagerly causes a Model to be run eagerly.
# (3) Not explicitly setting run_eagerly defaults to TF's global
# setting.
return (
self.dynamic
or self._run_eagerly
or (tf.config.functions_run_eagerly() and self._run_eagerly is None)
)
@run_eagerly.setter
def run_eagerly(self, value):
self._run_eagerly = value
@property
def autotune_steps_per_execution(self):
"""Settable property to enable tuning for steps_per_execution"""
return self._autotune_steps_per_execution
@autotune_steps_per_execution.setter
def autotune_steps_per_execution(self, value):
self._autotune_steps_per_execution = value
if value and self._steps_per_execution_tuner is None:
if self._steps_per_execution is None:
self._configure_steps_per_execution(1)
self._steps_per_execution_tuner = (
steps_per_execution_tuning.StepsPerExecutionTuner(
self.optimizer, self._steps_per_execution
)
)
@property
def steps_per_execution(self):
"""Settable `steps_per_execution variable. Requires a compiled model."""
return self._steps_per_execution
@steps_per_execution.setter
def steps_per_execution(self, value):
if self._steps_per_execution is None:
self._configure_steps_per_execution(value)
else:
self._steps_per_execution.assign(value)
@property
def jit_compile(self):
"""Specify whether to compile the model with XLA.
[XLA](https://www.tensorflow.org/xla) is an optimizing compiler
for machine learning. `jit_compile` is not enabled by default.
Note that `jit_compile=True` may not necessarily work for all models.
For more information on supported operations please refer to the
[XLA documentation](https://www.tensorflow.org/xla). Also refer to
[known XLA issues](https://www.tensorflow.org/xla/known_issues)
for more details.
"""
return self._jit_compile
@jit_compile.setter
def jit_compile(self, value):
# Function remains cached with previous jit_compile settings
if self._jit_compile == value:
# Avoid resetting compiler cache if possible if the value is the
# same
return
# Check if TensorFlow is compiled with XLA before setting the value
if value and not tf_utils.can_jit_compile(warn=True):
self._jit_compile = False
return
self._jit_compile = value
# Setting `jit_compile` should invalidate previously cached functions.
self._reset_compile_cache()
@property
def distribute_reduction_method(self):
"""The method employed to reduce per-replica values during training.
Unless specified, the value "auto" will be assumed, indicating that
the reduction strategy should be chosen based on the current
running environment.
See `reduce_per_replica` function for more details.
"""
return self._distribute_reduction_method or "auto"
@distribute_reduction_method.setter
def distribute_reduction_method(self, value):
self._distribute_reduction_method = value
def _validate_target_and_loss(self, y, loss):
"""Raises error if target or loss is not found.
This method verifies that the target and loss are properly populated
when applicable, or raises errors.
Args:
y: the target for training.
loss: the total loss tensor including loss added via `compile` and
`add_loss`.
"""
# `self.loss` references the loss added via `compile` call. If users
# have provided such, the target must be provided; otherwise it's a user
# error. Note that `self.loss` does not include losses added via
# `add_loss`, and it is a valid use when such loss from `add_loss`
# exists and target does not.
if self.loss and y is None:
raise ValueError(
"Target data is missing. Your model was compiled with "
f"loss={self.loss}, "
"and therefore expects target data to be provided in `fit()`."
)
# For training, there must be compiled loss or regularization loss to
# exist in order to apply the gradients. If one is not found, it means
# no loss was supplied via `compile` or `add_loss`.
elif loss is None:
raise ValueError(
"No loss found. You may have forgotten to provide a `loss` "
"argument in the `compile()` method."
)
def train_step(self, data):
"""The logic for one training step.
This method can be overridden to support custom training logic.
For concrete examples of how to override this method see
[Customizing what happens in fit](
https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit).
This method is called by `Model.make_train_function`.
This method should contain the mathematical logic for one step of
training. This typically includes the forward pass, loss calculation,
backpropagation, and metric updates.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_train_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the
values of the `Model`'s metrics are returned. Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data)
# Run forward pass.
with tf.GradientTape() as tape:
y_pred = self(x, training=True)
loss = self.compute_loss(x, y, y_pred, sample_weight)
self._validate_target_and_loss(y, loss)
# Run backwards pass.
self.optimizer.minimize(loss, self.trainable_variables, tape=tape)
return self.compute_metrics(x, y, y_pred, sample_weight)
def compute_loss(self, x=None, y=None, y_pred=None, sample_weight=None):
"""Compute the total loss, validate it, and return it.
Subclasses can optionally override this method to provide custom loss
computation logic.
Example:
```python
class MyModel(tf.keras.Model):
def __init__(self, *args, **kwargs):
super(MyModel, self).__init__(*args, **kwargs)
self.loss_tracker = tf.keras.metrics.Mean(name='loss')
def compute_loss(self, x, y, y_pred, sample_weight):
loss = tf.reduce_mean(tf.math.squared_difference(y_pred, y))
loss += tf.add_n(self.losses)
self.loss_tracker.update_state(loss)
return loss
def reset_metrics(self):
self.loss_tracker.reset_states()
@property
def metrics(self):
return [self.loss_tracker]
tensors = tf.random.uniform((10, 10)), tf.random.uniform((10,))
dataset = tf.data.Dataset.from_tensor_slices(tensors).repeat().batch(1)
inputs = tf.keras.layers.Input(shape=(10,), name='my_input')
outputs = tf.keras.layers.Dense(10)(inputs)
model = MyModel(inputs, outputs)
model.add_loss(tf.reduce_sum(outputs))
optimizer = tf.keras.optimizers.SGD()
model.compile(optimizer, loss='mse', steps_per_execution=10)
model.fit(dataset, epochs=2, steps_per_epoch=10)
print('My custom loss: ', model.loss_tracker.result().numpy())
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
The total loss as a `tf.Tensor`, or `None` if no loss results (which
is the case when called by `Model.test_step`).
"""
del x # The default implementation does not use `x`.
return self.compiled_loss(
y, y_pred, sample_weight, regularization_losses=self.losses
)
def compute_metrics(self, x, y, y_pred, sample_weight):
"""Update metric states and collect all metrics to be returned.
Subclasses can optionally override this method to provide custom metric
updating and collection logic.
Example:
```python
class MyModel(tf.keras.Sequential):
def compute_metrics(self, x, y, y_pred, sample_weight):
# This super call updates `self.compiled_metrics` and returns
# results for all metrics listed in `self.metrics`.
metric_results = super(MyModel, self).compute_metrics(
x, y, y_pred, sample_weight)
# Note that `self.custom_metric` is not listed in `self.metrics`.
self.custom_metric.update_state(x, y, y_pred, sample_weight)
metric_results['custom_metric_name'] = self.custom_metric.result()
return metric_results
```
Args:
x: Input data.
y: Target data.
y_pred: Predictions returned by the model (output of `model.call(x)`)
sample_weight: Sample weights for weighting the loss function.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end()`. Typically, the
values of the metrics listed in `self.metrics` are returned. Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
del x # The default implementation does not use `x`.
self.compiled_metrics.update_state(y, y_pred, sample_weight)
return self.get_metrics_result()
def get_metrics_result(self):
"""Returns the model's metrics values as a dict.
If any of the metric result is a dict (containing multiple metrics),
each of them gets added to the top level returned dict of this method.
Returns:
A `dict` containing values of the metrics listed in `self.metrics`.
Example:
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
# Collect metrics to return
return_metrics = {}
for metric in self.metrics:
result = metric.result()
if isinstance(result, dict):
return_metrics.update(result)
else:
return_metrics[metric.name] = result
return return_metrics
def _validate_and_get_metrics_result(self, logs):
"""Returns model metrics as a dict if the keys match with input logs.
When the training / evalution is performed with asynchronous steps, such
as the case with `tf.distribute.ParameterServerStrategy`, the last
scheduled `train / test_step` may not give the latest metrics because it
is not guaranteed to be executed the last. This method gets metrics from
the model directly instead of relying on the return from last step
function.
It logs a warning if the metric results could not be overridden when
used with `tf.distribute.ParameterServerStrategy`.
When the user has custom train / test step functions, the metrics
returned may be different from `Model.metrics`. In those instances,
this function will be no-op and return the logs.
Args:
logs: A `dict` of metrics returned by train / test step function.
Returns:
A `dict` containing values of the metrics listed in `self.metrics`
when logs and model metrics keys match. Otherwise it returns input
`logs`.
"""
PSS_WARN_MSG = "Could not get Model metric results. \
Using the results of last step function could lead to incorrect \
results when used with ParameterServerStrategy"
try:
metric_logs = self.get_metrics_result()
except TypeError:
if self._cluster_coordinator:
logging.warning(PSS_WARN_MSG)
else:
# Verify that train / test step logs passed and metric logs have
# matching keys. Could be different when using custom step functions
if isinstance(logs, dict) and set(logs.keys()) == set(
metric_logs.keys()
):
logs = tf_utils.sync_to_numpy_or_python_type(metric_logs)
elif self._cluster_coordinator:
logging.warning(PSS_WARN_MSG)
return logs
def _aggregate_exact_metrics(self, logs):
# When doing exact evaluation, `logs` is a list of each data shard's
# metric variables, which will be used to update the metrics.
for shard_result in logs:
for metric in self.metrics:
if metric.name not in shard_result.keys():
logging.log_first_n(
logging.WARN,
f"No matching result found for metric {metric.name}. "
"This metric's computed result may be incorrect.",
3,
)
continue
metric_result = shard_result[metric.name]
if len(metric_result) != len(metric.weights):
raise ValueError(
f"Expected {len(metric.weights)} variables in result "
f"for metric {metric.name}, but found "
f"{len(metric_result)}."
)
for weight, val in zip(metric.weights, metric_result):
weight.assign_add(val)
return self.get_metrics_result()
def make_train_function(self, force=False):
"""Creates a function that executes one step of training.
This method can be overridden to support custom training logic.
This method is called by `Model.fit` and `Model.train_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual training
logic to `Model.train_step`.
This function is cached the first time `Model.fit` or
`Model.train_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the train function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_train_batch_end`, such as
`{'loss': 0.2, 'accuracy': 0.7}`.
"""
if self.train_function is not None and not force:
return self.train_function
def step_function(model, iterator):
"""Runs a single training step."""
def run_step(data):
outputs = model.train_step(data)
# Ensure counter is updated only if `train_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._train_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def train_function(iterator):
"""Runs a training execution with a single step."""
return step_function(self, iterator)
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
if self._cluster_coordinator:
self.train_function = (
lambda it: self._cluster_coordinator.schedule(
train_function, args=(it,)
)
)
else:
self.train_function = train_function
# If we're using a coordinator, use the value of
# self._steps_per_execution at the time the function is
# called/scheduled, and not when it is actually executed.
elif self._cluster_coordinator:
def train_function(iterator, steps_per_execution):
"""Runs a training execution with multiple steps."""
for _ in tf.range(steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
self.train_function = lambda it: self._cluster_coordinator.schedule(
train_function, args=(it, self._steps_per_execution.value())
)
else:
def train_function(iterator):
"""Runs a training execution with multiple steps."""
for _ in tf.range(self._steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
train_function = tf.function(
train_function, reduce_retracing=True
)
self.train_tf_function = train_function
self.train_function = train_function
return self.train_function
@traceback_utils.filter_traceback
def fit(
self,
x=None,
y=None,
batch_size=None,
epochs=1,
verbose="auto",
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_batch_size=None,
validation_freq=1,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
):
"""Trains the model for a fixed number of epochs (dataset iterations).
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A `tf.data` dataset. Should return a tuple
of either `(inputs, targets)` or
`(inputs, targets, sample_weights)`.
- A generator or `keras.utils.Sequence` returning `(inputs,
targets)` or `(inputs, targets, sample_weights)`.
- A `tf.keras.utils.experimental.DatasetCreator`, which wraps a
callable that takes a single argument of type
`tf.distribute.InputContext`, and returns a `tf.data.Dataset`.
`DatasetCreator` should be used when users prefer to specify the
per-replica batching and sharding logic for the `Dataset`.
See `tf.keras.utils.experimental.DatasetCreator` doc for more
information.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given below. If these
include `sample_weights` as a third component, note that sample
weighting applies to the `weighted_metrics` argument but not the
`metrics` argument in `compile()`. If using
`tf.distribute.experimental.ParameterServerStrategy`, only
`DatasetCreator` type is supported for `x`.
y: Target data. Like the input data `x`,
it could be either Numpy array(s) or TensorFlow tensor(s).
It should be consistent with `x` (you cannot have Numpy inputs and
tensor targets, or inversely). If `x` is a dataset, generator,
or `keras.utils.Sequence` instance, `y` should
not be specified (since targets will be obtained from `x`).
batch_size: Integer or `None`.
Number of samples per gradient 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).
epochs: Integer. Number of epochs to train the model.
An epoch is an iteration over the entire `x` and `y`
data provided
(unless the `steps_per_epoch` flag is set to
something other than None).
Note that in conjunction with `initial_epoch`,
`epochs` is to be understood as "final epoch".
The model is not trained for a number of iterations
given by `epochs`, but merely until the epoch
of index `epochs` is reached.
verbose: 'auto', 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = one line per epoch.
'auto' becomes 1 for most cases, but 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so verbose=2 is
recommended when not running interactively (eg, in a production
environment). Defaults to 'auto'.
callbacks: List of `keras.callbacks.Callback` instances.
List of callbacks to apply during training.
See `tf.keras.callbacks`. Note
`tf.keras.callbacks.ProgbarLogger` and
`tf.keras.callbacks.History` callbacks are created automatically
and need not be passed into `model.fit`.
`tf.keras.callbacks.ProgbarLogger` is created or not based on
`verbose` argument to `model.fit`.
Callbacks with batch-level calls are currently unsupported with
`tf.distribute.experimental.ParameterServerStrategy`, and users
are advised to implement epoch-level calls instead with an
appropriate `steps_per_epoch` value.
validation_split: Float between 0 and 1.
Fraction of the training data to be used as validation data.
The model will set apart this fraction of the training data,
will not train on it, and will evaluate
the loss and any model metrics
on this data at the end of each epoch.
The validation data is selected from the last samples
in the `x` and `y` data provided, before shuffling. This
argument is not supported when `x` is a dataset, generator or
`keras.utils.Sequence` instance.
If both `validation_data` and `validation_split` are provided,
`validation_data` will override `validation_split`.
`validation_split` is not yet supported with
`tf.distribute.experimental.ParameterServerStrategy`.
validation_data: Data on which to evaluate
the loss and any model metrics at the end of each epoch.
The model will not be trained on this data. Thus, note the fact
that the validation loss of data provided using
`validation_split` or `validation_data` is not affected by
regularization layers like noise and dropout.
`validation_data` will override `validation_split`.
`validation_data` could be:
- A tuple `(x_val, y_val)` of Numpy arrays or tensors.
- A tuple `(x_val, y_val, val_sample_weights)` of NumPy
arrays.
- A `tf.data.Dataset`.
- A Python generator or `keras.utils.Sequence` returning
`(inputs, targets)` or `(inputs, targets, sample_weights)`.
`validation_data` is not yet supported with
`tf.distribute.experimental.ParameterServerStrategy`.
shuffle: Boolean (whether to shuffle the training data
before each epoch) or str (for 'batch'). This argument is
ignored when `x` is a generator or an object of tf.data.Dataset.
'batch' is a special option for dealing
with the limitations of HDF5 data; it shuffles in batch-sized
chunks. Has no effect when `steps_per_epoch` is not `None`.
class_weight: Optional dictionary mapping class indices (integers)
to a weight (float) value, used for weighting the loss function
(during training only).
This can be useful to tell the model to
"pay more attention" to samples from
an under-represented class. When `class_weight` is specified
and targets have a rank of 2 or greater, either `y` must be
one-hot encoded, or an explicit final dimension of `1` must
be included for sparse class labels.
sample_weight: Optional Numpy array of weights for
the training samples, used for weighting the loss function
(during training only). You can either pass a flat (1D)
Numpy array with the same length as the input samples
(1:1 mapping between weights and samples),
or in the case of temporal data,
you can pass a 2D array with shape
`(samples, sequence_length)`,
to apply a different weight to every timestep of every sample.
This argument is not supported when `x` is a dataset, generator,
or `keras.utils.Sequence` instance, instead provide the
sample_weights as the third element of `x`.
Note that sample weighting does not apply to metrics specified
via the `metrics` argument in `compile()`. To apply sample
weighting to your metrics, you can specify them via the
`weighted_metrics` in `compile()` instead.
initial_epoch: Integer.
Epoch at which to start training
(useful for resuming a previous training run).
steps_per_epoch: Integer or `None`.
Total number of steps (batches of samples)
before declaring one epoch finished and starting the
next epoch. 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_per_epoch'
is None, the epoch will run until the input dataset is
exhausted. When passing an infinitely repeating dataset, you
must specify the `steps_per_epoch` argument. If
`steps_per_epoch=-1` the training will run indefinitely with an
infinitely repeating dataset. This argument is not supported
with array inputs.
When using `tf.distribute.experimental.ParameterServerStrategy`:
* `steps_per_epoch=None` is not supported.
validation_steps: Only relevant if `validation_data` is provided and
is a `tf.data` dataset. Total number of steps (batches of
samples) to draw before stopping when performing validation
at the end of every epoch. If 'validation_steps' is None,
validation will run until the `validation_data` dataset is
exhausted. In the case of an infinitely repeated dataset, it
will run into an infinite loop. If 'validation_steps' is
specified and only part of the dataset will be consumed, the
evaluation will start from the beginning of the dataset at each
epoch. This ensures that the same validation samples are used
every time.
validation_batch_size: Integer or `None`.
Number of samples per validation batch.
If unspecified, will default to `batch_size`.
Do not specify the `validation_batch_size` if your data is in
the form of datasets, generators, or `keras.utils.Sequence`
instances (since they generate batches).
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.
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the generator
queue. If unspecified, `max_queue_size` will default to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up
when using process-based threading. If unspecified, `workers`
will default to 1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
Unpacking behavior for iterator-like inputs:
A common pattern is to pass a tf.data.Dataset, generator, or
tf.keras.utils.Sequence to the `x` argument of fit, which will in fact
yield not only features (x) but optionally targets (y) and sample
weights. TF-Keras requires that the output of such iterator-likes be
unambiguous. The iterator should return a tuple of length 1, 2, or 3,
where the optional second and third elements will be used for y and
sample_weight respectively. Any other type provided will be wrapped in
a length one tuple, effectively treating everything as 'x'. When
yielding dicts, they should still adhere to the top-level tuple
structure.
e.g. `({"x0": x0, "x1": x1}, y)`. TF-Keras will not attempt to
separate features, targets, and weights from the keys of a single
dict.
A notable unsupported data type is the namedtuple. The reason is
that it behaves like both an ordered datatype (tuple) and a mapping
datatype (dict). So given a namedtuple of the form:
`namedtuple("example_tuple", ["y", "x"])`
it is ambiguous whether to reverse the order of the elements when
interpreting the value. Even worse is a tuple of the form:
`namedtuple("other_tuple", ["x", "y", "z"])`
where it is unclear if the tuple was intended to be unpacked into x,
y, and sample_weight or passed through as a single element to `x`. As
a result the data processing code will simply raise a ValueError if it
encounters a namedtuple. (Along with instructions to remedy the
issue.)
Returns:
A `History` object. Its `History.history` attribute is
a record of training loss values and metrics values
at successive epochs, as well as validation loss values
and validation metrics values (if applicable).
Raises:
RuntimeError: 1. If the model was never compiled or,
2. If `model.fit` is wrapped in `tf.function`.
ValueError: In case of mismatch between the provided input data
and what the model expects or when the input data is empty.
"""
# Legacy graph support is contained in `training_v1.Model`.
version_utils.disallow_legacy_graph("Model", "fit")
self._assert_compile_was_called()
self._check_call_args("fit")
_disallow_inside_tf_function("fit")
verbose = _get_verbosity(verbose, self.distribute_strategy)
if validation_split and validation_data is None:
# Create the validation data using the training data. Only supported
# for `Tensor` and `NumPy` input.
(
x,
y,
sample_weight,
), validation_data = data_adapter.train_validation_split(
(x, y, sample_weight), validation_split=validation_split
)
if validation_data:
(
val_x,
val_y,
val_sample_weight,
) = data_adapter.unpack_x_y_sample_weight(validation_data)
if self.distribute_strategy._should_use_with_coordinator:
self._cluster_coordinator = (
tf.distribute.experimental.coordinator.ClusterCoordinator(
self.distribute_strategy
)
)
with self.distribute_strategy.scope(), training_utils.RespectCompiledTrainableState( # noqa: E501
self
):
# Creates a `tf.data.Dataset` and handles batch and epoch iteration.
data_handler = data_adapter.get_data_handler(
x=x,
y=y,
sample_weight=sample_weight,
batch_size=batch_size,
steps_per_epoch=steps_per_epoch,
initial_epoch=initial_epoch,
epochs=epochs,
shuffle=shuffle,
class_weight=class_weight,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=epochs,
steps=data_handler.inferred_steps,
)
self.stop_training = False
self.train_function = self.make_train_function()
self._train_counter.assign(0)
callbacks.on_train_begin()
training_logs = None
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
# Handle fault-tolerance for multi-worker.
# TODO(omalleyt): Fix the ordering issues that mean this has to
# happen after `callbacks.on_train_begin`.
steps_per_epoch_inferred = (
steps_per_epoch or data_handler.inferred_steps
)
(
data_handler._initial_epoch,
data_handler._initial_step,
) = self._maybe_load_initial_counters_from_ckpt(
steps_per_epoch_inferred, initial_epoch
)
logs = None
for epoch, iterator in data_handler.enumerate_epochs():
self.reset_metrics()
callbacks.on_epoch_begin(epoch)
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
with tf.profiler.experimental.Trace(
"train",
epoch_num=epoch,
step_num=step,
batch_size=batch_size,
_r=1,
):
callbacks.on_train_batch_begin(step)
tmp_logs = self.train_function(iterator)
if data_handler.should_sync:
context.async_wait()
# No error, now safe to assign to logs.
logs = tmp_logs
end_step = step + data_handler.step_increment
callbacks.on_train_batch_end(end_step, logs)
if self.stop_training:
break
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if logs is None:
raise ValueError(
"Unexpected result of `train_function` "
"(Empty logs). This could be due to issues in input "
"pipeline that resulted in an empty dataset. "
"Otherwise, please use "
"`Model.compile(..., run_eagerly=True)`, or "
"`tf.config.run_functions_eagerly(True)` for more "
"information of where went wrong, or file a "
"issue/bug to `tf.keras`."
)
# Override with model metrics instead of last step logs
logs = self._validate_and_get_metrics_result(logs)
epoch_logs = copy.copy(logs)
# Run validation.
if validation_data and self._should_eval(
epoch, validation_freq
):
if self._pss_evaluation_shards:
self._disallow_exact_eval_with_add_metrics()
# Create data_handler for evaluation and cache it.
if getattr(self, "_eval_data_handler", None) is None:
self._eval_data_handler = data_adapter.get_data_handler(
x=val_x,
y=val_y,
sample_weight=val_sample_weight,
batch_size=validation_batch_size or batch_size,
steps_per_epoch=validation_steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
pss_evaluation_shards=self._pss_evaluation_shards,
)
val_logs = self.evaluate(
x=val_x,
y=val_y,
sample_weight=val_sample_weight,
batch_size=validation_batch_size or batch_size,
steps=validation_steps,
callbacks=callbacks,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
return_dict=True,
_use_cached_eval_dataset=True,
)
val_logs = {
"val_" + name: val for name, val in val_logs.items()
}
epoch_logs.update(val_logs)
callbacks.on_epoch_end(epoch, epoch_logs)
training_logs = epoch_logs
if self.stop_training:
break
if isinstance(self.optimizer, optimizer.Optimizer) and epochs > 0:
self.optimizer.finalize_variable_values(
self.trainable_variables
)
# If eval data_handler exists, delete it after all epochs are done.
if getattr(self, "_eval_data_handler", None) is not None:
del self._eval_data_handler
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_train_end(logs=training_logs)
return self.history
def test_step(self, data):
"""The logic for one evaluation step.
This method can be overridden to support custom evaluation logic.
This method is called by `Model.make_test_function`.
This function should contain the mathematical logic for one step of
evaluation.
This typically includes the forward pass, loss calculation, and metrics
updates.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_test_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
A `dict` containing values that will be passed to
`tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the
values of the `Model`'s metrics are returned.
"""
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data)
y_pred = self(x, training=False)
# Updates stateful loss metrics.
self.compute_loss(x, y, y_pred, sample_weight)
return self.compute_metrics(x, y, y_pred, sample_weight)
def _make_test_function_exact(self):
if getattr(self, "_shard_test_function", None):
return self._shard_test_function
def step_function(batch):
def run_step(data):
# TODO(b/272050910): Use sample_weight for weighted metrics.
x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(
data
)
y_pred = self(x, training=False)
return x, y, y_pred, sample_weight
if self._jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
outputs = self.distribute_strategy.run(run_step, args=(batch,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
def shard_test_function(dataset, total_shards, shard_idx):
# Copy loss and metric variables to the worker and work with them
# locally. This ensures each shard function is atomic: if a worker
# is preempted, the intermediate progress is discarded and that
# shard is retried. This in turn guarantees exactly-once visitation.
local_unweighted_metrics, local_weighted_metrics = [], []
with tf_utils.with_metric_local_vars_scope():
# TODO(jmullenbach): implement and use a clone for
# `MetricsContainer` and use its `update_state` method directly.
for metric in self.compiled_metrics.unweighted_metrics:
if metric is not None:
local_unweighted_metrics.append(
base_metric.clone_metric(metric)
)
for metric in self.compiled_metrics.weighted_metrics:
if metric is not None:
local_weighted_metrics.append(
base_metric.clone_metric(metric)
)
local_loss = compile_utils.LossesContainer.from_config(
self.compiled_loss.get_config()
)
dataset = input_ops.auto_shard_dataset(
dataset, total_shards, shard_idx
)
iterator = iter(dataset)
with distribute_utils.cache_variable_reads():
for batch in iterator:
x, y, y_pred, sample_weight = step_function(batch)
for weighted_metric in local_weighted_metrics:
weighted_metric.update_state(y, y_pred, sample_weight)
for unweighted_metric in local_unweighted_metrics:
unweighted_metric.update_state(y, y_pred)
local_loss(y, y_pred, sample_weight)
local_metrics = (
local_unweighted_metrics
+ local_weighted_metrics
+ local_loss.metrics
)
outputs = {metric.name: metric.weights for metric in local_metrics}
with tf.control_dependencies(_minimum_control_deps(outputs)):
self._test_counter.assign_add(1)
return outputs
if not self.run_eagerly:
shard_test_function = tf.function(
shard_test_function, reduce_retracing=True
)
self._shard_test_function = (
lambda *args: self._cluster_coordinator.schedule(
shard_test_function,
args=args,
)
)
return self._shard_test_function
def make_test_function(self, force=False):
"""Creates a function that executes one step of evaluation.
This method can be overridden to support custom evaluation logic.
This method is called by `Model.evaluate` and `Model.test_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.test_step`.
This function is cached the first time `Model.evaluate` or
`Model.test_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the test function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return a `dict` containing values that will
be passed to `tf.keras.Callbacks.on_test_batch_end`.
"""
if self.test_function is not None and not force:
return self.test_function
def step_function(model, iterator):
"""Runs a single evaluation step."""
def run_step(data):
outputs = model.test_step(data)
# Ensure counter is updated only if `test_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._test_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs,
self.distribute_strategy,
reduction=self.distribute_reduction_method,
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def test_function(iterator):
"""Runs a test execution with a single step."""
return step_function(self, iterator)
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
if self._cluster_coordinator:
self.test_function = (
lambda it: self._cluster_coordinator.schedule(
test_function, args=(it,)
)
)
else:
self.test_function = test_function
# If we're using a coordinator, use the value of
# self._steps_per_execution at the time the function is
# called/scheduled, and not when it is actually executed.
elif self._cluster_coordinator:
def test_function(iterator, steps_per_execution):
"""Runs a test execution with multiple steps."""
for _ in tf.range(steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
self.test_function = lambda it: self._cluster_coordinator.schedule(
test_function, args=(it, self._steps_per_execution.value())
)
else:
def test_function(iterator):
"""Runs a test execution with multiple steps."""
for _ in tf.range(self._steps_per_execution):
outputs = step_function(self, iterator)
return outputs
if not self.run_eagerly:
test_function = tf.function(
test_function, reduce_retracing=True
)
self.test_function = test_function
return self.test_function
@traceback_utils.filter_traceback
def evaluate(
self,
x=None,
y=None,
batch_size=None,
verbose="auto",
sample_weight=None,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
return_dict=False,
**kwargs,
):
"""Returns the loss value & metrics values for the model in test mode.
Computation is done in batches (see the `batch_size` arg.)
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A `tf.data` dataset. Should return a tuple
of either `(inputs, targets)` or
`(inputs, targets, sample_weights)`.
- A generator or `keras.utils.Sequence` returning `(inputs,
targets)` or `(inputs, targets, sample_weights)`.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given in the `Unpacking
behavior for iterator-like inputs` section of `Model.fit`.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s). It should be consistent with `x`
(you cannot have Numpy inputs and tensor targets, or inversely).
If `x` is a dataset, generator or `keras.utils.Sequence` instance,
`y` should not be specified (since targets will be obtained from
the iterator/dataset).
batch_size: Integer or `None`. Number of samples per batch of
computation. If unspecified, `batch_size` will default to 32. Do
not specify the `batch_size` if your data is in the form of a
dataset, generators, or `keras.utils.Sequence` instances (since
they generate batches).
verbose: `"auto"`, 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = single line.
`"auto"` becomes 1 for most cases, and to 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so `verbose=2` is
recommended when not running interactively (e.g. in a production
environment). Defaults to 'auto'.
sample_weight: Optional Numpy array of weights for the test samples,
used for weighting the loss function. You can either pass a flat
(1D) Numpy array with the same length as the input samples
(1:1 mapping between weights and samples), or in the case of
temporal data, you can pass a 2D array with shape `(samples,
sequence_length)`, to apply a different weight to every
timestep of every sample. This argument is not supported when
`x` is a dataset, instead pass sample weights as the third
element of `x`.
steps: Integer or `None`. Total number of steps (batches of samples)
before declaring the evaluation round finished. Ignored with the
default value of `None`. If x is a `tf.data` dataset and `steps`
is None, 'evaluate' will run until the dataset is exhausted. This
argument is not supported with array inputs.
callbacks: List of `keras.callbacks.Callback` instances. List of
callbacks to apply during evaluation. See
[callbacks](https://www.tensorflow.org/api_docs/python/tf/tf_keras/callbacks).
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the generator
queue. If unspecified, `max_queue_size` will default to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, `workers` will default to
1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
**kwargs: Unused at this time.
See the discussion of `Unpacking behavior for iterator-like inputs` for
`Model.fit`.
Returns:
Scalar test 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 scalar outputs.
Raises:
RuntimeError: If `model.evaluate` is wrapped in a `tf.function`.
"""
version_utils.disallow_legacy_graph("Model", "evaluate")
self._assert_compile_was_called()
self._check_call_args("evaluate")
self._check_sample_weight_warning(x, sample_weight)
_disallow_inside_tf_function("evaluate")
use_cached_eval_dataset = kwargs.pop("_use_cached_eval_dataset", False)
if kwargs:
raise TypeError(f"Invalid keyword arguments: {list(kwargs.keys())}")
if self.distribute_strategy._should_use_with_coordinator:
self._cluster_coordinator = (
tf.distribute.experimental.coordinator.ClusterCoordinator(
self.distribute_strategy
)
)
verbose = _get_verbosity(verbose, self.distribute_strategy)
if self._pss_evaluation_shards:
self._disallow_exact_eval_with_add_metrics()
with self.distribute_strategy.scope():
# Use cached evaluation data only when it's called in `Model.fit`
if (
use_cached_eval_dataset
and getattr(self, "_eval_data_handler", None) is not None
):
data_handler = self._eval_data_handler
else:
# Creates a `tf.data.Dataset` and handles batch and epoch
# iteration.
data_handler = data_adapter.get_data_handler(
x=x,
y=y,
sample_weight=sample_weight,
batch_size=batch_size,
steps_per_epoch=steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
pss_evaluation_shards=self._pss_evaluation_shards,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=1,
steps=data_handler.inferred_steps,
)
# Initialize to prevent errors if 0 epochs are evaluated.
logs = {}
test_function_runner = self._get_test_function_runner(callbacks)
self._test_counter.assign(0)
callbacks.on_test_begin()
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
for (
_,
dataset_or_iterator,
) in data_handler.enumerate_epochs(): # Single epoch.
self.reset_metrics()
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
with tf.profiler.experimental.Trace(
"test", step_num=step, _r=1
):
callbacks.on_test_batch_begin(step)
logs = test_function_runner.run_step(
dataset_or_iterator,
data_handler,
step,
self._pss_evaluation_shards,
)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
# Override with model metrics instead of last step logs
if self._pss_evaluation_shards:
logs = self._aggregate_exact_metrics(logs)
else:
logs = self._validate_and_get_metrics_result(logs)
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_test_end(logs=logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def _disallow_exact_eval_with_add_metrics(self):
metrics_from_add_metric = [
metric
for layer in self._flatten_layers()
for metric in layer._metrics
]
compiled_metrics = self.compiled_metrics.metrics
if any(
[
metric not in compiled_metrics
for metric in metrics_from_add_metric
]
):
raise ValueError(
"Detected that a metric was added to this model "
"via `Model.add_metric`. This is not currently "
"supported when using exact evaluation with "
"`tf.distribute.ParameterServerStrategy`."
)
def _infer_exact_eval_shards(self, pss_evaluation_shards):
if not self.distribute_strategy._should_use_with_coordinator:
return 0
if pss_evaluation_shards == "auto":
# TODO(b/264265138) evaluate and improve this heuristic
return self.distribute_strategy._num_workers * 5
return pss_evaluation_shards
def _get_test_function_runner(self, callbacks):
if (
self._pss_evaluation_shards
and self.distribute_strategy._should_use_with_coordinator
):
self.test_function = self._make_test_function_exact()
test_function_runner = _ExactTestFunction(
self.test_function, callbacks
)
else:
self.test_function = self.make_test_function()
test_function_runner = _TestFunction(self.test_function, callbacks)
return test_function_runner
def predict_step(self, data):
"""The logic for one inference step.
This method can be overridden to support custom inference logic.
This method is called by `Model.make_predict_function`.
This method should contain the mathematical logic for one step of
inference. This typically includes the forward pass.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_predict_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
The result of one inference step, typically the output of calling the
`Model` on data.
"""
x, _, _ = data_adapter.unpack_x_y_sample_weight(data)
return self(x, training=False)
def make_predict_function(self, force=False):
"""Creates a function that executes one step of inference.
This method can be overridden to support custom inference logic.
This method is called by `Model.predict` and `Model.predict_on_batch`.
Typically, this method directly controls `tf.function` and
`tf.distribute.Strategy` settings, and delegates the actual evaluation
logic to `Model.predict_step`.
This function is cached the first time `Model.predict` or
`Model.predict_on_batch` is called. The cache is cleared whenever
`Model.compile` is called. You can skip the cache and generate again the
function with `force=True`.
Args:
force: Whether to regenerate the predict function and skip the cached
function if available.
Returns:
Function. The function created by this method should accept a
`tf.data.Iterator`, and return the outputs of the `Model`.
"""
if self.predict_function is not None and not force:
return self.predict_function
def step_function(model, iterator):
"""Runs a single evaluation step."""
def run_step(data):
outputs = model.predict_step(data)
# Ensure counter is updated only if `test_step` succeeds.
with tf.control_dependencies(_minimum_control_deps(outputs)):
model._predict_counter.assign_add(1)
return outputs
if self.jit_compile:
run_step = tf.function(
run_step, jit_compile=True, reduce_retracing=True
)
data = next(iterator)
outputs = model.distribute_strategy.run(run_step, args=(data,))
outputs = reduce_per_replica(
outputs, self.distribute_strategy, reduction="concat"
)
return outputs
# Special case if steps_per_execution is one.
if (
self._steps_per_execution is None
or self._steps_per_execution.numpy().item() == 1
and not self.autotune_steps_per_execution
):
def predict_function(iterator):
"""Runs an evaluation execution with a single step."""
return step_function(self, iterator)
else:
def predict_function(iterator):
"""Runs an evaluation execution with multiple steps."""
outputs = step_function(self, iterator)
for _ in tf.range(self._steps_per_execution - 1):
tf.autograph.experimental.set_loop_options(
shape_invariants=[
(
outputs,
tf.nest.map_structure(
lambda t: tf_utils.get_tensor_spec(
t, dynamic_batch=True
).shape,
outputs,
),
)
]
)
step_outputs = step_function(self, iterator)
outputs = tf.nest.map_structure(
lambda t1, t2: concat([t1, t2]), outputs, step_outputs
)
return outputs
if not self.run_eagerly:
predict_function = tf.function(
predict_function, reduce_retracing=True
)
self.predict_function = predict_function
return self.predict_function
@traceback_utils.filter_traceback
def predict(
self,
x,
batch_size=None,
verbose="auto",
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
):
"""Generates output predictions for the input samples.
Computation is done in batches. This method is designed for batch
processing of large numbers of inputs. It is not intended for use inside
of loops that iterate over your data and process small numbers of inputs
at a time.
For small numbers of inputs that fit in one batch,
directly use `__call__()` for faster execution, e.g.,
`model(x)`, or `model(x, training=False)` if you have layers such as
`tf.keras.layers.BatchNormalization` that behave differently during
inference. You may pair the individual model call with a `tf.function`
for additional performance inside your inner loop.
If you need access to numpy array values instead of tensors after your
model call, you can use `tensor.numpy()` to get the numpy array value of
an eager tensor.
Also, note the fact that test loss is not affected by
regularization layers like noise and dropout.
Note: See [this FAQ entry](
https://keras.io/getting_started/faq/#whats-the-difference-between-model-methods-predict-and-call)
for more details about the difference between `Model` methods
`predict()` and `__call__()`.
Args:
x: Input samples. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A `tf.data` dataset.
- A generator or `keras.utils.Sequence` instance.
A more detailed description of unpacking behavior for iterator
types (Dataset, generator, Sequence) is given in the `Unpacking
behavior for iterator-like inputs` section of `Model.fit`.
batch_size: Integer or `None`.
Number of samples per batch.
If unspecified, `batch_size` will default to 32.
Do not specify the `batch_size` if your data is in the
form of dataset, generators, or `keras.utils.Sequence` instances
(since they generate batches).
verbose: `"auto"`, 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = single line.
`"auto"` becomes 1 for most cases, and to 2 when used with
`ParameterServerStrategy`. Note that the progress bar is not
particularly useful when logged to a file, so `verbose=2` is
recommended when not running interactively (e.g. in a production
environment). Defaults to 'auto'.
steps: Total number of steps (batches of samples)
before declaring the prediction round finished.
Ignored with the default value of `None`. If x is a `tf.data`
dataset and `steps` is None, `predict()` will
run until the input dataset is exhausted.
callbacks: List of `keras.callbacks.Callback` instances.
List of callbacks to apply during prediction.
See [callbacks](
https://www.tensorflow.org/api_docs/python/tf/tf_keras/callbacks).
max_queue_size: Integer. Used for generator or
`keras.utils.Sequence` input only. Maximum size for the
generator queue. If unspecified, `max_queue_size` will default
to 10.
workers: Integer. Used for generator or `keras.utils.Sequence` input
only. Maximum number of processes to spin up when using
process-based threading. If unspecified, `workers` will default
to 1.
use_multiprocessing: Boolean. Used for generator or
`keras.utils.Sequence` input only. If `True`, use process-based
threading. If unspecified, `use_multiprocessing` will default to
`False`. Note that because this implementation relies on
multiprocessing, you should not pass non-pickleable arguments to
the generator as they can't be passed easily to children
processes.
See the discussion of `Unpacking behavior for iterator-like inputs` for
`Model.fit`. Note that Model.predict uses the same interpretation rules
as `Model.fit` and `Model.evaluate`, so inputs must be unambiguous for
all three methods.
Returns:
Numpy array(s) of predictions.
Raises:
RuntimeError: If `model.predict` is wrapped in a `tf.function`.
ValueError: In case of mismatch between the provided
input data and the model's expectations,
or in case a stateful model receives a number of samples
that is not a multiple of the batch size.
"""
version_utils.disallow_legacy_graph("Model", "predict")
self._check_call_args("predict")
_disallow_inside_tf_function("predict")
# TODO(yashkatariya): Cache model on the coordinator for faster
# prediction. If running under PSS, then swap it with OneDeviceStrategy
# so that execution will run on the coordinator.
original_pss_strategy = None
if self.distribute_strategy._should_use_with_coordinator:
original_pss_strategy = self.distribute_strategy
self._distribution_strategy = None
# Cluster coordinator is set by `.fit()` and `.evaluate()` which is not
# needed in `.predict()` because all the predictions happen on the
# coordinator/locally.
if self._cluster_coordinator:
self._cluster_coordinator = None
verbose = _get_verbosity(verbose, self.distribute_strategy)
outputs = None
with self.distribute_strategy.scope():
# Creates a `tf.data.Dataset` and handles batch and epoch iteration.
dataset_types = (tf.compat.v1.data.Dataset, tf.data.Dataset)
if (
self._in_multi_worker_mode()
or _is_tpu_multi_host(self.distribute_strategy)
) and isinstance(x, dataset_types):
try:
options = tf.data.Options()
data_option = tf.data.experimental.AutoShardPolicy.DATA
options.experimental_distribute.auto_shard_policy = (
data_option
)
x = x.with_options(options)
except ValueError:
warnings.warn(
"Using Model.predict with MultiWorkerMirroredStrategy "
"or TPUStrategy and AutoShardPolicy.FILE might lead to "
"out-of-order result. Consider setting it to "
"AutoShardPolicy.DATA.",
stacklevel=2,
)
data_handler = data_adapter.get_data_handler(
x=x,
batch_size=batch_size,
steps_per_epoch=steps,
initial_epoch=0,
epochs=1,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
model=self,
steps_per_execution=self._steps_per_execution,
)
# Container that configures and calls `tf.keras.Callback`s.
if not isinstance(callbacks, callbacks_module.CallbackList):
callbacks = callbacks_module.CallbackList(
callbacks,
add_history=True,
add_progbar=verbose != 0,
model=self,
verbose=verbose,
epochs=1,
steps=data_handler.inferred_steps,
)
self.predict_function = self.make_predict_function()
self._predict_counter.assign(0)
callbacks.on_predict_begin()
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.start()
batch_outputs = None
for _, iterator in data_handler.enumerate_epochs(): # Single epoch.
with data_handler.catch_stop_iteration():
for step in data_handler.steps():
callbacks.on_predict_batch_begin(step)
tmp_batch_outputs = self.predict_function(iterator)
if data_handler.should_sync:
context.async_wait()
batch_outputs = (
tmp_batch_outputs # No error, now safe to assign.
)
if outputs is None:
outputs = tf.nest.map_structure(
lambda batch_output: [batch_output],
batch_outputs,
)
else:
tf.__internal__.nest.map_structure_up_to(
batch_outputs,
lambda output, batch_output: output.append(
batch_output
),
outputs,
batch_outputs,
)
end_step = step + data_handler.step_increment
callbacks.on_predict_batch_end(
end_step, {"outputs": batch_outputs}
)
if batch_outputs is None:
raise ValueError(
"Unexpected result of `predict_function` "
"(Empty batch_outputs). Please use "
"`Model.compile(..., run_eagerly=True)`, or "
"`tf.config.run_functions_eagerly(True)` for more "
"information of where went wrong, or file a "
"issue/bug to `tf.keras`."
)
if self.autotune_steps_per_execution:
self._steps_per_execution_tuner.stop()
callbacks.on_predict_end()
all_outputs = tf.__internal__.nest.map_structure_up_to(
batch_outputs, potentially_ragged_concat, outputs
)
# If originally PSS strategy was used, then replace it back since
# predict is running under `OneDeviceStrategy` after the swap and once
# its done we need to replace it back to PSS again.
if original_pss_strategy is not None:
self._distribution_strategy = original_pss_strategy
return tf_utils.sync_to_numpy_or_python_type(all_outputs)
def reset_metrics(self):
"""Resets the state of all the metrics in the model.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,))
>>> outputs = tf.keras.layers.Dense(2)(inputs)
>>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
>>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> x = np.random.random((2, 3))
>>> y = np.random.randint(0, 2, (2, 2))
>>> _ = model.fit(x, y, verbose=0)
>>> assert all(float(m.result()) for m in model.metrics)
>>> model.reset_metrics()
>>> assert all(float(m.result()) == 0 for m in model.metrics)
"""
for m in self.metrics:
m.reset_state()
def train_on_batch(
self,
x,
y=None,
sample_weight=None,
class_weight=None,
reset_metrics=True,
return_dict=False,
):
"""Runs a single gradient update on a single batch of data.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s).
sample_weight: Optional array of the same length as x, containing
weights to apply to the model's loss for each sample. In the case
of temporal data, you can pass a 2D array with shape (samples,
sequence_length), to apply a different weight to every timestep of
every sample.
class_weight: Optional dictionary mapping class indices (integers)
to a weight (float) to apply to the model's loss for the samples
from this class during training. This can be useful to tell the
model to "pay more attention" to samples from an under-represented
class. When `class_weight` is specified and targets have a rank of
2 or greater, either `y` must be one-hot encoded, or an explicit
final dimension of `1` must be included for sparse class labels.
reset_metrics: If `True`, the metrics returned will be only for this
batch. If `False`, the metrics will be statefully accumulated
across batches.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
Returns:
Scalar training 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 scalar outputs.
Raises:
RuntimeError: If `model.train_on_batch` is wrapped in a `tf.function`.
"""
self._assert_compile_was_called()
self._check_call_args("train_on_batch")
_disallow_inside_tf_function("train_on_batch")
if reset_metrics:
self.reset_metrics()
with self.distribute_strategy.scope(), training_utils.RespectCompiledTrainableState( # noqa: E501
self
):
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x, y, sample_weight, class_weight
)
self.train_function = self.make_train_function()
logs = self.train_function(iterator)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def test_on_batch(
self,
x,
y=None,
sample_weight=None,
reset_metrics=True,
return_dict=False,
):
"""Test the model on a single batch of samples.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays (in case the
model has multiple inputs).
- A TensorFlow tensor, or a list of tensors (in case the model has
multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
y: Target data. Like the input data `x`, it could be either Numpy
array(s) or TensorFlow tensor(s). It should be consistent with `x`
(you cannot have Numpy inputs and tensor targets, or inversely).
sample_weight: Optional array of the same length as x, containing
weights to apply to the model's loss for each sample. In the case
of temporal data, you can pass a 2D array with shape (samples,
sequence_length), to apply a different weight to every timestep of
every sample.
reset_metrics: If `True`, the metrics returned will be only for this
batch. If `False`, the metrics will be statefully accumulated
across batches.
return_dict: If `True`, loss and metric results are returned as a
dict, with each key being the name of the metric. If `False`, they
are returned as a list.
Returns:
Scalar test 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 scalar outputs.
Raises:
RuntimeError: If `model.test_on_batch` is wrapped in a
`tf.function`.
"""
self._assert_compile_was_called()
self._check_call_args("test_on_batch")
_disallow_inside_tf_function("test_on_batch")
if reset_metrics:
self.reset_metrics()
with self.distribute_strategy.scope():
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x, y, sample_weight
)
self.test_function = self.make_test_function()
logs = self.test_function(iterator)
logs = tf_utils.sync_to_numpy_or_python_type(logs)
if return_dict:
return logs
else:
return flatten_metrics_in_order(logs, self.metrics_names)
def predict_on_batch(self, x):
"""Returns predictions for a single batch of samples.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays (in case the
model has multiple inputs).
- A TensorFlow tensor, or a list of tensors (in case the model has
multiple inputs).
Returns:
Numpy array(s) of predictions.
Raises:
RuntimeError: If `model.predict_on_batch` is wrapped in a
`tf.function`.
"""
self._check_call_args("predict_on_batch")
_disallow_inside_tf_function("predict_on_batch")
with self.distribute_strategy.scope():
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x
)
self.predict_function = self.make_predict_function()
outputs = self.predict_function(iterator)
return tf_utils.sync_to_numpy_or_python_type(outputs)
@doc_controls.do_not_generate_docs
def fit_generator(
self,
generator,
steps_per_epoch=None,
epochs=1,
verbose=1,
callbacks=None,
validation_data=None,
validation_steps=None,
validation_freq=1,
class_weight=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
shuffle=True,
initial_epoch=0,
):
"""Fits the model on data yielded batch-by-batch by a Python generator.
DEPRECATED:
`Model.fit` now supports generators, so there is no longer any need to
use this endpoint.
"""
warnings.warn(
"`Model.fit_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.fit`, which supports generators.",
stacklevel=2,
)
return self.fit(
generator,
steps_per_epoch=steps_per_epoch,
epochs=epochs,
verbose=verbose,
callbacks=callbacks,
validation_data=validation_data,
validation_steps=validation_steps,
validation_freq=validation_freq,
class_weight=class_weight,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
shuffle=shuffle,
initial_epoch=initial_epoch,
)
@doc_controls.do_not_generate_docs
def evaluate_generator(
self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0,
):
"""Evaluates the model on a data generator.
DEPRECATED:
`Model.evaluate` now supports generators, so there is no longer any
need to use this endpoint.
"""
warnings.warn(
"`Model.evaluate_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.evaluate`, which supports generators.",
stacklevel=2,
)
self._check_call_args("evaluate_generator")
return self.evaluate(
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks,
)
@doc_controls.do_not_generate_docs
def predict_generator(
self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0,
):
"""Generates predictions for the input samples from a data generator.
DEPRECATED:
`Model.predict` now supports generators, so there is no longer any
need to use this endpoint.
"""
warnings.warn(
"`Model.predict_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.predict`, which supports generators.",
stacklevel=2,
)
return self.predict(
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks,
)
######################################################################
# Functions below are not training related. They are for model weights
# tracking, save/load, serialization, etc.
######################################################################
@property
def trainable_weights(self):
self._assert_weights_created()
if not self._trainable:
return []
trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
trainable_variables += trackable_obj.trainable_variables
trainable_variables += self._trainable_weights
return self._dedup_weights(trainable_variables)
@property
def non_trainable_weights(self):
self._assert_weights_created()
non_trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
non_trainable_variables += trackable_obj.non_trainable_variables
if not self._trainable:
# Return order is all trainable vars, then all non-trainable vars.
trainable_variables = []
for trackable_obj in self._self_tracked_trackables:
trainable_variables += trackable_obj.trainable_variables
non_trainable_variables = (
trainable_variables
+ self._trainable_weights
+ non_trainable_variables
+ self._non_trainable_weights
)
else:
non_trainable_variables = (
non_trainable_variables + self._non_trainable_weights
)
return self._dedup_weights(non_trainable_variables)
def get_weights(self):
"""Retrieves the weights of the model.
Returns:
A flat list of Numpy arrays.
"""
with self.distribute_strategy.scope():
return super().get_weights()
@traceback_utils.filter_traceback
def save(self, 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.models.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.models.save_model()`.
"""
saving_api.save_model(
self,
filepath=filepath,
overwrite=overwrite,
save_format=save_format,
**kwargs,
)
@traceback_utils.filter_traceback
def save_weights(
self, filepath, overwrite=True, save_format=None, options=None
):
"""Saves all layer weights.
Either saves in HDF5 or in TensorFlow format based on the `save_format`
argument.
When saving in HDF5 format, the weight file has:
- `layer_names` (attribute), a list of strings
(ordered names of model layers).
- For every layer, a `group` named `layer.name`
- For every such layer group, a group attribute `weight_names`,
a list of strings
(ordered names of weights tensor of the layer).
- For every weight in the layer, a dataset
storing the weight value, named after the weight tensor.
When saving in TensorFlow format, all objects referenced by the network
are saved in the same format as `tf.train.Checkpoint`, including any
`Layer` instances or `Optimizer` instances assigned to object
attributes. For networks constructed from inputs and outputs using
`tf.keras.Model(inputs, outputs)`, `Layer` instances used by the network
are tracked/saved automatically. For user-defined classes which inherit
from `tf.keras.Model`, `Layer` instances must be assigned to object
attributes, typically in the constructor. See the documentation of
`tf.train.Checkpoint` and `tf.keras.Model` for details.
While the formats are the same, do not mix `save_weights` and
`tf.train.Checkpoint`. Checkpoints saved by `Model.save_weights` should
be loaded using `Model.load_weights`. Checkpoints saved using
`tf.train.Checkpoint.save` should be restored using the corresponding
`tf.train.Checkpoint.restore`. Prefer `tf.train.Checkpoint` over
`save_weights` for training checkpoints.
The TensorFlow format matches objects and variables by starting at a
root object, `self` for `save_weights`, and greedily matching attribute
names. For `Model.save` this is the `Model`, and for `Checkpoint.save`
this is the `Checkpoint` even if the `Checkpoint` has a model attached.
This means saving a `tf.keras.Model` using `save_weights` and loading
into a `tf.train.Checkpoint` with a `Model` attached (or vice versa)
will not match the `Model`'s variables. See the
[guide to training checkpoints](
https://www.tensorflow.org/guide/checkpoint) for details on
the TensorFlow format.
Args:
filepath: String or PathLike, path to the file to save the weights
to. When saving in TensorFlow format, this is the prefix used
for checkpoint files (multiple files are generated). Note that
the '.h5' suffix causes weights to be saved in HDF5 format.
overwrite: Whether to silently overwrite any existing file at the
target location, or provide the user with a manual prompt.
save_format: Either 'tf' or 'h5'. A `filepath` ending in '.h5' or
'.keras' will default to HDF5 if `save_format` is `None`.
Otherwise, `None` becomes 'tf'. Defaults to `None`.
options: Optional `tf.train.CheckpointOptions` object that specifies
options for saving weights.
Raises:
ImportError: If `h5py` is not available when attempting to save in
HDF5 format.
"""
saving_api.save_weights(
self,
filepath=filepath,
overwrite=overwrite,
save_format=save_format,
options=options,
)
@traceback_utils.filter_traceback
def load_weights(
self, filepath, skip_mismatch=False, by_name=False, options=None
):
"""Loads all layer weights from a saved files.
The saved file could be a SavedModel file, a `.keras` file (v3 saving
format), or a file created via `model.save_weights()`.
By default, weights are loaded based on the network's
topology. This means the architecture should be the same as when the
weights were saved. Note that layers that don't have weights are not
taken into account in the topological ordering, so adding or removing
layers is fine as long as they don't have weights.
**Partial weight loading**
If you have modified your model, for instance by adding a new layer
(with weights) or by changing the shape of the weights of a layer,
you can choose to ignore errors and continue loading
by setting `skip_mismatch=True`. In this case any layer with
mismatching weights will be skipped. A warning will be displayed
for each skipped layer.
**Weight loading by name**
If your weights are saved as a `.h5` file created
via `model.save_weights()`, you can use the argument `by_name=True`.
In this case, weights are loaded into layers only if they share
the same name. This is useful for fine-tuning or transfer-learning
models where some of the layers have changed.
Note that only topological loading (`by_name=False`) is supported when
loading weights from the `.keras` v3 format or from the TensorFlow
SavedModel format.
Args:
filepath: String, path to the weights file to load. For weight files
in TensorFlow format, this is the file prefix (the same as was
passed to `save_weights()`). This can also be a path to a
SavedModel or a `.keras` file (v3 saving format) saved
via `model.save()`.
skip_mismatch: Boolean, whether to skip loading of layers where
there is a mismatch in the number of weights, or a mismatch in
the shape of the weights.
by_name: Boolean, whether to load weights by name or by topological
order. Only topological loading is supported for weight files in
the `.keras` v3 format or in the TensorFlow SavedModel format.
options: Optional `tf.train.CheckpointOptions` object that specifies
options for loading weights (only valid for a SavedModel file).
"""
return saving_api.load_weights(
self,
filepath=filepath,
by_name=by_name,
skip_mismatch=skip_mismatch,
options=options,
)
def _updated_config(self):
"""Util shared between different serialization methods.
Returns:
Model config with TF-Keras version information added.
"""
from tf_keras.src import __version__ as keras_version
config = self.get_config()
model_config = {
"class_name": self.__class__.__name__,
"config": config,
"keras_version": keras_version,
"backend": backend.backend(),
}
return model_config
@generic_utils.default
def get_config(self):
"""Returns the config of the `Model`.
Config is a Python dictionary (serializable) containing the
configuration of an object, which in this case is a `Model`. This allows
the `Model` to be be reinstantiated later (without its trained weights)
from this configuration.
Note that `get_config()` does not guarantee to return a fresh copy of
dict every time it is called. The callers should make a copy of the
returned dict if they want to modify it.
Developers of subclassed `Model` are advised to override this method,
and continue to update the dict from `super(MyModel, self).get_config()`
to provide the proper configuration of this `Model`. The default config
will return config dict for init parameters if they are basic types.
Raises `NotImplementedError` when in cases where a custom
`get_config()` implementation is required for the subclassed model.
Returns:
Python dictionary containing the configuration of this `Model`.
"""
# If sublcass doesn't implement `get_config()` parse from init args
# otherwise default to empty dict
if generic_utils.is_default(self.get_config):
try:
config = base_layer.Layer.get_config(self)
except NotImplementedError:
config = {}
logging.warning(
"Model's `__init__()` arguments contain non-serializable "
"objects. Please implement a `get_config()` method in the "
"subclassed Model for proper saving and loading. "
"Defaulting to empty config."
)
else:
config = {}
return config
@classmethod
def from_config(cls, config, custom_objects=None):
# `from_config` assumes `cls` is either `Functional` or a child class of
# `Functional`. In the case that `cls` is meant to behave like a child
# class of `Functional` but only inherits from the `Model` class, we
# have to call `cls(...)` instead of `Functional.from_config`.
from tf_keras.src.engine import functional
with serialization.SharedObjectLoadingScope():
functional_config_keys = [
"name",
"layers",
"input_layers",
"output_layers",
]
is_functional_config = all(
key in config for key in functional_config_keys
)
argspec = tf_inspect.getfullargspec(cls.__init__)
functional_init_args = tf_inspect.getfullargspec(
functional.Functional.__init__
).args[1:]
revivable_as_functional = (
cls in {functional.Functional, Model}
or argspec.args[1:] == functional_init_args
or (argspec.varargs == "args" and argspec.varkw == "kwargs")
)
if is_functional_config and revivable_as_functional:
# Revive Functional model
# (but not Functional subclasses with a custom __init__)
inputs, outputs, layers = functional.reconstruct_from_config(
config, custom_objects
)
model = cls(
inputs=inputs, outputs=outputs, name=config.get("name")
)
functional.connect_ancillary_layers(model, layers)
else:
# Either the model has a custom __init__, or the config
# does not contain all the information necessary to
# revive a Functional model. This happens when the user creates
# subclassed models where `get_config()` is returning
# insufficient information to be considered a Functional model.
# In this case, we fall back to provide all config into the
# constructor of the class.
try:
model = cls(**config)
except TypeError as e:
raise TypeError(
"Unable to revive model from config. When overriding "
"the `get_config()` method, make sure that the "
"returned config contains all items used as arguments "
f"in the constructor to {cls}, "
"which is the default behavior. "
"You can override this default behavior by defining a "
"`from_config(cls, config)` class method to specify "
"how to create an "
f"instance of {cls.__name__} from its config.\n\n"
f"Received config={config}\n\n"
f"Error encountered during deserialization: {e}"
)
return model
def to_json(self, **kwargs):
"""Returns a JSON string containing the network configuration.
To load a network from a JSON save file, use
`keras.models.model_from_json(json_string, custom_objects={})`.
Args:
**kwargs: Additional keyword arguments to be passed to
*`json.dumps()`.
Returns:
A JSON string.
"""
model_config = self._updated_config()
return json.dumps(
model_config, default=json_utils.get_json_type, **kwargs
)
def to_yaml(self, **kwargs):
"""Returns a yaml string containing the network configuration.
Note: Since TF 2.6, this method is no longer supported and will raise a
RuntimeError.
To load a network from a yaml save file, use
`keras.models.model_from_yaml(yaml_string, custom_objects={})`.
`custom_objects` should be a dictionary mapping
the names of custom losses / layers / etc to the corresponding
functions / classes.
Args:
**kwargs: Additional keyword arguments
to be passed to `yaml.dump()`.
Returns:
A YAML string.
Raises:
RuntimeError: announces that the method poses a security risk
"""
raise RuntimeError(
"Method `model.to_yaml()` has been removed due to security risk of "
"arbitrary code execution. Please use `model.to_json()` instead."
)
def reset_states(self):
for layer in self.layers:
if hasattr(layer, "reset_states") and getattr(
layer, "stateful", False
):
layer.reset_states()
@property
@doc_controls.do_not_generate_docs
def state_updates(self):
"""Deprecated, do NOT use!
Returns the `updates` from all layers that are stateful.
This is useful for separating training updates and
state updates, e.g. when we need to update a layer's internal state
during prediction.
Returns:
A list of update ops.
"""
warnings.warn(
"`Model.state_updates` will be removed in a future version. "
"This property should not be used in TensorFlow 2.0, "
"as `updates` are applied automatically.",
stacklevel=2,
)
state_updates = []
for layer in self.layers:
if getattr(layer, "stateful", False):
if hasattr(layer, "updates"):
state_updates += layer.updates
return state_updates
@property
def weights(self):
"""Returns the list of all layer variables/weights.
Note: This will not track the weights of nested `tf.Modules` that are
not themselves TF-Keras layers.
Returns:
A list of variables.
"""
return self._dedup_weights(self._undeduplicated_weights)
@property
def _undeduplicated_weights(self):
"""Returns the undeduplicated list of all layer variables/weights."""
self._assert_weights_created()
weights = []
for layer in self._self_tracked_trackables:
weights += layer.variables
weights += self._trainable_weights + self._non_trainable_weights
return weights
def summary(
self,
line_length=None,
positions=None,
print_fn=None,
expand_nested=False,
show_trainable=False,
layer_range=None,
):
"""Prints a string summary of the network.
Args:
line_length: Total length of printed lines
(e.g. set this to adapt the display to different
terminal window sizes).
positions: Relative or absolute positions of log elements
in each line. If not provided, becomes
`[0.3, 0.6, 0.70, 1.]`. Defaults to `None`.
print_fn: Print function to use. By default, prints to `stdout`.
If `stdout` doesn't work in your environment, change to `print`.
It will be called on each line of the summary.
You can set it to a custom function
in order to capture the string summary.
expand_nested: Whether to expand the nested models.
Defaults to `False`.
show_trainable: Whether to show if a layer is trainable.
Defaults to `False`.
layer_range: a list or tuple of 2 strings,
which is the starting layer name and ending layer name
(both inclusive) indicating the range of layers to be printed
in summary. It also accepts regex patterns instead of exact
name. In such case, start predicate will be the first element
it matches to `layer_range[0]` and the end predicate will be
the last element it matches to `layer_range[1]`.
By default `None` which considers all layers of model.
Raises:
ValueError: if `summary()` is called before the model is built.
"""
if not self.built:
raise ValueError(
"This model has not yet been built. "
"Build the model first by calling `build()` or by calling "
"the model on a batch of data."
)
layer_utils.print_summary(
self,
line_length=line_length,
positions=positions,
print_fn=print_fn,
expand_nested=expand_nested,
show_trainable=show_trainable,
layer_range=layer_range,
)
@property
def layers(self):
return list(self._flatten_layers(include_self=False, recursive=False))
@layers.setter
def layers(self, _):
raise AttributeError(
"`Model.layers` attribute is reserved and should not be used. "
"Please use another name."
)
def get_layer(self, name=None, index=None):
"""Retrieves a layer based on either its name (unique) or index.
If `name` and `index` are both provided, `index` will take precedence.
Indices are based on order of horizontal graph traversal (bottom-up).
Args:
name: String, name of layer.
index: Integer, index of layer.
Returns:
A layer instance.
"""
# TODO(fchollet): We could build a dictionary based on layer names
# since they are constant, but we have not done that yet.
if index is not None and name is not None:
raise ValueError(
"Provide only a layer name or a layer index. Received: "
f"index={index}, name={name}."
)
if index is not None:
if len(self.layers) <= index:
raise ValueError(
f"Was asked to retrieve layer at index {index}"
f" but model only has {len(self.layers)}"
" layers."
)
else:
return self.layers[index]
if name is not None:
for layer in self.layers:
if layer.name == name:
return layer
raise ValueError(
f"No such layer: {name}. Existing layers are: "
f"{list(layer.name for layer in self.layers)}."
)
raise ValueError(
"Provide either a layer name or layer index at `get_layer`."
)
def get_weight_paths(self):
"""Retrieve all the variables and their paths for the model.
The variable path (string) is a stable key to identify a `tf.Variable`
instance owned by the model. It can be used to specify variable-specific
configurations (e.g. DTensor, quantization) from a global view.
This method returns a dict with weight object paths as keys
and the corresponding `tf.Variable` instances as values.
Note that if the model is a subclassed model and the weights haven't
been initialized, an empty dict will be returned.
Returns:
A dict where keys are variable paths and values are `tf.Variable`
instances.
Example:
```python
class SubclassModel(tf.keras.Model):
def __init__(self, name=None):
super().__init__(name=name)
self.d1 = tf.keras.layers.Dense(10)
self.d2 = tf.keras.layers.Dense(20)
def call(self, inputs):
x = self.d1(inputs)
return self.d2(x)
model = SubclassModel()
model(tf.zeros((10, 10)))
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': model.d1.kernel,
# 'd1.bias': model.d1.bias,
# 'd2.kernel': model.d2.kernel,
# 'd2.bias': model.d2.bias,
# }
# Functional model
inputs = tf.keras.Input((10,), batch_size=10)
x = tf.keras.layers.Dense(20, name='d1')(inputs)
output = tf.keras.layers.Dense(30, name='d2')(x)
model = tf.keras.Model(inputs, output)
d1 = model.layers[1]
d2 = model.layers[2]
weight_paths = model.get_weight_paths()
# weight_paths:
# {
# 'd1.kernel': d1.kernel,
# 'd1.bias': d1.bias,
# 'd2.kernel': d2.kernel,
# 'd2.bias': d2.bias,
# }
```
"""
result = {}
(
descendants,
object_paths_dict,
) = tf.__internal__.tracking.ObjectGraphView(
self
).breadth_first_traversal()
for descendant in descendants:
if isinstance(descendant, tf.Variable):
trackable_references = object_paths_dict[descendant]
object_path = ".".join([t.name for t in trackable_references])
result[object_path] = descendant
return result
def get_compile_config(self):
"""Returns a serialized config with information for compiling the model.
This method returns a config dictionary containing all the information
(optimizer, loss, metrics, etc.) with which the model was compiled.
Returns:
A dict containing information for compiling the model.
"""
if self._is_compiled and hasattr(self, "_compile_config"):
return self._compile_config.serialize()
def compile_from_config(self, config):
"""Compiles the model with the information given in config.
This method uses the information in the config (optimizer, loss,
metrics, etc.) to compile the model.
Args:
config: Dict containing information for compiling the model.
"""
has_overridden_compile = self.__class__.compile != Model.compile
if has_overridden_compile:
logging.warning(
"`compile()` was not called as part of model loading "
"because the model's `compile()` method is custom. "
"All subclassed Models that have `compile()` "
"overridden should also override "
"`get_compile_config()` and `compile_from_config(config)`. "
"Alternatively, you can "
"call `compile()` manually after loading."
)
return
config = saving_lib.deserialize_keras_object(config)
self.compile(**config)
if (
hasattr(self, "optimizer")
# Exempt legacy optimizers.
and isinstance(self.optimizer, optimizer.Optimizer)
and self.built
):
# Create optimizer variables.
self.optimizer.build(self.trainable_variables)
def export(self, filepath):
"""Create a SavedModel artifact for inference (e.g. via TF-Serving).
This method lets you export a model to a lightweight SavedModel artifact
that contains the model's forward pass only (its `call()` method)
and can be served via e.g. TF-Serving. The forward pass is registered
under the name `serve()` (see example below).
The original code of the model (including any custom layers you may
have used) is *no longer* necessary to reload the artifact -- it is
entirely standalone.
Args:
filepath: `str` or `pathlib.Path` object. Path where to save
the artifact.
Example:
```python
# Create the artifact
model.export("path/to/location")
# Later, in a different process / environment...
reloaded_artifact = tf.saved_model.load("path/to/location")
predictions = reloaded_artifact.serve(input_data)
```
If you would like to customize your serving endpoints, you can
use the lower-level `keras.export.ExportArchive` class. The `export()`
method relies on `ExportArchive` internally.
"""
from tf_keras.src.export import export_lib
export_lib.export_model(self, filepath)
@tf.__internal__.tracking.no_automatic_dependency_tracking
def _set_save_spec(self, inputs, args=None, kwargs=None):
"""Defines the save spec so that serialization can trace `call()`.
The TensorSpecs of the call function `inputs`, `args`, and `kwargs` are
saved into a tuple of `([inputs] + args, kwargs)`. The input
`TensorSpec` names are updated to match the built `input_names`.
The specs can be retrieved with the `save_spec` property.
Args:
inputs: possibly nested inputs passed into the call function.
args: a list of positional arguments passed into call.
kwargs: a dictionary of keyword arguments passed into call.
"""
if self._saved_model_inputs_spec is not None:
return # Already set.
args = args or []
kwargs = kwargs or {}
input_names = self.input_names
if not input_names:
input_names = compile_utils.create_pseudo_input_names(inputs)
flat_inputs = tf.nest.flatten(inputs)
inputs_spec = []
for name, tensor in zip(input_names, flat_inputs):
inputs_spec.append(
tf_utils.get_tensor_spec(tensor, dynamic_batch=False, name=name)
)
inputs_spec = tf.nest.pack_sequence_as(inputs, inputs_spec)
super()._set_save_spec(inputs_spec, args, kwargs)
# Store the input shapes
if (
self.__class__.__name__ == "Sequential"
and self._build_input_shape is None
):
self._build_input_shape = tf.nest.map_structure(
lambda x: None if x is None else x.shape, inputs_spec
)
def save_spec(self, dynamic_batch=True):
"""Returns the `tf.TensorSpec` of call args as a tuple `(args, kwargs)`.
This value is automatically defined after calling the model for the
first time. Afterwards, you can use it when exporting the model for
serving:
```python
model = tf.keras.Model(...)
@tf.function
def serve(*args, **kwargs):
outputs = model(*args, **kwargs)
# Apply postprocessing steps, or add additional outputs.
...
return outputs
# arg_specs is `[tf.TensorSpec(...), ...]`. kwarg_specs, in this
# example, is an empty dict since functional models do not use keyword
# arguments.
arg_specs, kwarg_specs = model.save_spec()
model.save(path, signatures={
'serving_default': serve.get_concrete_function(*arg_specs,
**kwarg_specs)
})
```
Args:
dynamic_batch: Whether to set the batch sizes of all the returned
`tf.TensorSpec` to `None`. (Note that when defining functional or
Sequential models with `tf.keras.Input([...], batch_size=X)`, the
batch size will always be preserved). Defaults to `True`.
Returns:
If the model inputs are defined, returns a tuple `(args, kwargs)`. All
elements in `args` and `kwargs` are `tf.TensorSpec`.
If the model inputs are not defined, returns `None`.
The model inputs are automatically set when calling the model,
`model.fit`, `model.evaluate` or `model.predict`.
"""
return self._get_save_spec(dynamic_batch, inputs_only=False)
def _assert_weights_created(self):
"""Asserts that all the weights for the model have been created.
For a non-dynamic model, the weights must already be created after the
layer has been called. For a dynamic model, the exact list of weights
can never be known for certain since it may change at any time during
execution.
We run this check right before accessing weights or getting the Numpy
value for the current weights. Otherwise, if the layer has never been
called, the user would just get an empty list, which is misleading.
Raises:
ValueError: if the weights of the network have not yet been created.
"""
if self.dynamic:
return
if (
"build" in self.__class__.__dict__
and self.__class__ != Model
and not self.built
):
# For any model that has customized build() method but hasn't been
# invoked yet, this will cover both sequential and subclass model.
# Also make sure to exclude Model class itself which has build()
# defined.
raise ValueError(
f"Weights for model '{self.name}' have not yet been "
"created. "
"Weights are created when the model is first called on "
"inputs or `build()` is called with an `input_shape`."
)
def _check_call_args(self, method_name):
"""Check that `call()` has only one positional arg."""
# Always allow first arg, regardless of arg name.
fullargspec = self._call_spec.full_argspec
if fullargspec.defaults:
positional_args = fullargspec.args[: -len(fullargspec.defaults)]
else:
positional_args = fullargspec.args
if "training" in positional_args:
positional_args.remove("training")
# self and first arg can be positional.
if len(positional_args) > 2:
extra_args = positional_args[2:]
raise ValueError(
f"Models passed to `{method_name}` can only have `training` "
"and the first argument in `call()` as positional arguments, "
f"found: {extra_args}."
)
def _validate_compile(self, optimizer, metrics, **kwargs):
"""Performs validation checks for the default `compile()`."""
if any(
isinstance(opt, optimizer_v1.Optimizer)
for opt in tf.nest.flatten(optimizer)
):
raise ValueError(
f"`tf.compat.v1.keras` Optimizer ({optimizer}) is "
"not supported when eager execution is enabled. Use a "
"`tf.keras` Optimizer instead, or disable eager "
"execution."
)
kwargs.pop("cloning", None) # Legacy DistStrat argument, never used.
kwargs.pop("experimental_run_tf_function", None) # Always `True`.
distribute_arg = kwargs.pop("distribute", None)
if distribute_arg is not None:
raise ValueError(
"`distribute` argument in compile is not available in TF 2.0. "
"Please create the model under the `strategy.scope()`. "
f"Received: {distribute_arg}."
)
target_tensor_arg = kwargs.pop("target_tensors", None)
if target_tensor_arg is not None:
raise ValueError(
"`target_tensors` argument is not supported when executing "
f"eagerly. Received: {target_tensor_arg}."
)
invalid_kwargs = set(kwargs) - {"sample_weight_mode"}
if invalid_kwargs:
raise TypeError(
"Invalid keyword argument(s) in `compile()`: "
f"{(invalid_kwargs,)}. Valid keyword arguments include "
'"cloning", "experimental_run_tf_function", "distribute",'
' "target_tensors", or "sample_weight_mode".'
)
# Model must be created and compiled with the same DistStrat.
if self.built and tf.distribute.has_strategy():
strategy = tf.distribute.get_strategy()
for v in self.variables:
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Variable ({v}) was not created in the distribution "
f"strategy scope of ({strategy}). It is most likely "
"because some layers, model, or optimizer was being "
"created outside the distribution strategy scope. Try "
"to make sure your code looks similar "
"to the following.\nwith strategy.scope():\n"
" model=_create_model()\n"
" model.compile(...)"
)
# Model metrics must be created in the same distribution strategy scope
# as the model.
strategy = self.distribute_strategy
for metric in tf.nest.flatten(metrics):
for v in getattr(metric, "variables", []):
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Metric ({metric}) passed to `model.compile` was "
"created inside a different distribution strategy "
"scope than the model. All metrics must be created "
"in the same distribution strategy "
f"scope as the model (in this case {strategy}). "
"If you pass in a string identifier for a metric to "
"compile, the metric will automatically be created "
"in the correct distribution strategy scope."
)
# Model metrics must be created in the same distribution strategy scope
# as the model.
for opt in tf.nest.flatten(optimizer):
for v in getattr(opt, "_weights", []):
if not strategy.extended.variable_created_in_scope(v):
raise ValueError(
f"Optimizer ({optimizer}) passed to `model.compile` "
"was created inside a different distribution strategy "
"scope than the model. All optimizers must be created "
"in the same distribution strategy scope as the model "
f"(in this case {strategy}). If you pass in a string "
"identifier for an optimizer to compile, the optimizer "
"will automatically be created in the correct "
"distribution strategy scope."
)
def _maybe_load_initial_counters_from_ckpt(
self, steps_per_epoch, initial_epoch
):
"""Maybe load initial epoch from ckpt, considering worker recovery.
Refer to tensorflow/python/tf_keras/distribute/worker_training_state.py
for more information.
Args:
steps_per_epoch: The number of step per epoch.
initial_epoch: The original initial_epoch user passes in `fit()`.
mode: The mode for running `model.fit()`.
Returns:
If the training is recovering from previous failure under multi-worker
training setting, return the (epoch, step) the training is supposed to
continue at. Otherwise, return the `initial_epoch, initial_step` the
user passes in.
"""
initial_step = 0
if self._training_state is not None:
return self._training_state.maybe_load_initial_counters_from_ckpt(
steps_per_epoch, initial_epoch, mode=ModeKeys.TRAIN
)
return (initial_epoch, initial_step)
def _assert_compile_was_called(self):
# Checks whether `compile` has been called. If it has been called,
# then the optimizer is set. This is different from whether the
# model is compiled
# (i.e. whether the model is built and its inputs/outputs are set).
if not self._is_compiled:
raise RuntimeError(
"You must compile your model before "
"training/testing. "
"Use `model.compile(optimizer, loss)`."
)
def _check_sample_weight_warning(self, x, sample_weight):
# Datasets can include sample weight, by returning a tuple with the
# structure of `(x, y, sample_weight)`.
sample_weight_present = sample_weight is not None or (
isinstance(x, tf.data.Dataset)
and isinstance(x.element_spec, tuple)
and len(x.element_spec) == 3
)
if (
sample_weight_present
and self.compiled_metrics._user_weighted_metrics is None
):
logging.warning(
"`evaluate()` received a value for `sample_weight`, but "
"`weighted_metrics` were not provided. Did you mean to pass "
"metrics to `weighted_metrics` in `compile()`? If this is "
"intentional you can pass `weighted_metrics=[]` to `compile()` "
"in order to silence this warning."
)
def _set_inputs(self, inputs, outputs=None, training=None):
"""This method is for compat with Modelv1. Only inputs are needed
here."""
self._set_save_spec(inputs)
@property
def _trackable_saved_model_saver(self):
return model_serialization.ModelSavedModelSaver(self)
def _trackable_children(self, save_type="checkpoint", **kwargs):
if save_type == "savedmodel":
# SavedModel needs to ignore the execution functions.
train_function = self.train_function
test_function = self.test_function
predict_function = self.predict_function
train_tf_function = self.train_tf_function
self.train_function = None
self.test_function = None
self.predict_function = None
self.train_tf_function = None
children = super()._trackable_children(save_type, **kwargs)
if save_type == "savedmodel":
self.train_function = train_function
self.test_function = test_function
self.predict_function = predict_function
self.train_tf_function = train_tf_function
return children
def _should_eval(self, epoch, validation_freq):
epoch = epoch + 1 # one-index the user-facing epoch.
if isinstance(validation_freq, int):
return epoch % validation_freq == 0
elif isinstance(validation_freq, list):
return epoch in validation_freq
else:
raise ValueError(
"Expected `validation_freq` to be a list or int. "
f"Received: validation_freq={validation_freq} of the "
f"type {type(validation_freq)}."
)
######################################################################
# Functions below exist only as v1 / v2 compatibility shims.
######################################################################
def _get_compile_args(self, user_metrics=True):
"""Used for saving or cloning a Model.
Args:
user_metrics: Whether to return user-supplied metrics or `Metric`
objects. If True, returns the user-supplied metrics.
Defaults to `True`.
Returns:
Dictionary of arguments that were used when compiling the model.
"""
self._assert_compile_was_called()
saved_metrics = self.compiled_metrics._user_metrics
saved_weighted_metrics = self.compiled_metrics._user_weighted_metrics
if not user_metrics:
if saved_metrics is not None:
saved_metrics = self.compiled_metrics._metrics
if saved_weighted_metrics is not None:
saved_weighted_metrics = self.compiled_metrics._weighted_metrics
compile_args = {
"optimizer": self.optimizer,
"loss": self.compiled_loss._user_losses,
"metrics": saved_metrics,
"weighted_metrics": saved_weighted_metrics,
"loss_weights": self.compiled_loss._user_loss_weights,
}
return compile_args
def _get_callback_model(self):
return self
def _in_multi_worker_mode(self):
return self.distribute_strategy.extended._in_multi_worker_mode()
@property
def _compile_was_called(self):
return self._is_compiled
| (self, x, batch_size=None, verbose='auto', steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False) |
725,034 | tf_keras.src.engine.training | predict_generator | Generates predictions for the input samples from a data generator.
DEPRECATED:
`Model.predict` now supports generators, so there is no longer any
need to use this endpoint.
| @doc_controls.do_not_generate_docs
def predict_generator(
self,
generator,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
verbose=0,
):
"""Generates predictions for the input samples from a data generator.
DEPRECATED:
`Model.predict` now supports generators, so there is no longer any
need to use this endpoint.
"""
warnings.warn(
"`Model.predict_generator` is deprecated and "
"will be removed in a future version. "
"Please use `Model.predict`, which supports generators.",
stacklevel=2,
)
return self.predict(
generator,
steps=steps,
max_queue_size=max_queue_size,
workers=workers,
use_multiprocessing=use_multiprocessing,
verbose=verbose,
callbacks=callbacks,
)
| (self, generator, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False, verbose=0) |
725,035 | tf_keras.src.engine.training | predict_on_batch | Returns predictions for a single batch of samples.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays (in case the
model has multiple inputs).
- A TensorFlow tensor, or a list of tensors (in case the model has
multiple inputs).
Returns:
Numpy array(s) of predictions.
Raises:
RuntimeError: If `model.predict_on_batch` is wrapped in a
`tf.function`.
| def predict_on_batch(self, x):
"""Returns predictions for a single batch of samples.
Args:
x: Input data. It could be:
- A Numpy array (or array-like), or a list of arrays (in case the
model has multiple inputs).
- A TensorFlow tensor, or a list of tensors (in case the model has
multiple inputs).
Returns:
Numpy array(s) of predictions.
Raises:
RuntimeError: If `model.predict_on_batch` is wrapped in a
`tf.function`.
"""
self._check_call_args("predict_on_batch")
_disallow_inside_tf_function("predict_on_batch")
with self.distribute_strategy.scope():
iterator = data_adapter.single_batch_iterator(
self.distribute_strategy, x
)
self.predict_function = self.make_predict_function()
outputs = self.predict_function(iterator)
return tf_utils.sync_to_numpy_or_python_type(outputs)
| (self, x) |
725,036 | tf_keras.src.engine.training | predict_step | The logic for one inference step.
This method can be overridden to support custom inference logic.
This method is called by `Model.make_predict_function`.
This method should contain the mathematical logic for one step of
inference. This typically includes the forward pass.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_predict_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
The result of one inference step, typically the output of calling the
`Model` on data.
| def predict_step(self, data):
"""The logic for one inference step.
This method can be overridden to support custom inference logic.
This method is called by `Model.make_predict_function`.
This method should contain the mathematical logic for one step of
inference. This typically includes the forward pass.
Configuration details for *how* this logic is run (e.g. `tf.function`
and `tf.distribute.Strategy` settings), should be left to
`Model.make_predict_function`, which can also be overridden.
Args:
data: A nested structure of `Tensor`s.
Returns:
The result of one inference step, typically the output of calling the
`Model` on data.
"""
x, _, _ = data_adapter.unpack_x_y_sample_weight(data)
return self(x, training=False)
| (self, data) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.