Descripción basic del contenido
- Efectos de encender la nueva promoción de tipo
- Tipo de promoción más consistente y predecible
- Riesgo reducido de reducción de bits
- tf.tensor Métodos matemáticos dunder
- tf.variable Ops en el lugar
- tf. Conversiones implícitas constitales
- Matriz de tf-numpay
- Inferencia de tipo de entrada
- API de soporte de tébittensor
A continuación se muestra una lista no exhaustiva de cambios que resultan de activar la promoción del nuevo tipo.
- Resultados de promoción más consistentes y predecibles.
- Riesgo reducido de reducción de bits.
tf.Tensor
Los métodos matemáticos de dunder usan una nueva promoción de tipo.tf.fixed
puede regresarWeakTensor
.tf.fixed
permite conversiones implícitas cuando una entrada de tensor con un dtype diferente deldtype
Arg se pasa.tf.Variable
operaciones en el lugar (assign
,assign-add
,assign-sub
) Permitir conversiones implícitas.tnp.array(1)
ytnp.array(1.0)
Devuelve el Tiérdete de 32 bits.WeakTensor
S se creará y se utilizará para las API unarias y binarias de soporte débil.
Resultados de promoción más consistentes y predecibles
El uso de un sistema basado en la pink permite que el nuevo tipo de promoción produzca resultados de promoción de tipo consistentes y predecibles.
Promoción de tipo antiguo
Cambiar el orden de las operaciones produce resultados inconsistentes utilizando la promoción de tipo antiguo.
# Setup
tnp.experimental_enable_numpy_behavior(dtype_conversion_mode="legacy")
a = np.array(1, dtype=np.int8)
b = tf.fixed(1)
c = np.array(1, dtype=np.float16)
# (a + b) + c throws an InvalidArgumentError.
attempt:
tf.add(tf.add(a, b), c)
besides tf.errors.InvalidArgumentError as e:
print(f'{sort(e)}: {e}') # InvalidArgumentError
: can't compute AddV2 as enter #1(zero-based) was anticipated to be a int8 tensor however is a int32 tensor [Op:AddV2] title:
# (b + a) + c returns an i32 end result.
tf.add(tf.add(b, a), c) #
Promoción de nuevo tipo
La nueva promoción de tipo produce resultados consistentes independientemente del orden.
tnp.experimental_enable_numpy_behavior(dtype_conversion_mode="all")
a = np.array(1, dtype=np.int8)
b = tf.fixed(1)
c = np.array(1, dtype=np.float16)
WARNING:tensorflow:UserWarning: enabling the brand new sort promotion should occur in the beginning of this system. Please guarantee no TF APIs have been used but.
# (a + b) + c returns a f16 end result.
tf.add(tf.add(a, b), c) #
# (b + a) + c additionally returns a f16 end result.
tf.add(tf.add(b, a), c) #
Riesgo reducido de reducción de bits
Promoción de tipo antiguo
La promoción de tipo anterior a menudo resultó en resultados de 64 bits.
tnp.experimental_enable_numpy_behavior(dtype_conversion_mode="legacy")
np.array(3.2, np.float16) + tf.fixed(1, tf.int8) + tf.fixed(50) #
Promoción de nuevo tipo
La promoción de nuevo tipo devuelve los resultados con un número mínimo de bits necesarios.
tnp.experimental_enable_numpy_behavior(dtype_conversion_mode="all")
WARNING:tensorflow:UserWarning: enabling the brand new sort promotion should occur in the beginning of this system. Please guarantee no TF APIs have been used but.
np.array(3.2, np.float16) + tf.fixed(1, tf.int8) + tf.fixed(50) #
tf.tensor Métodos matemáticos dunder
Todo tf.Tensor
Los métodos matemáticos de Dunder seguirán la nueva promoción de tipo.
-tf.fixed(5) #
tf.fixed(5, tf.int16) - tf.fixed(1, tf.float32) #
tf.variable Ops en el lugar
Se permitirán conversiones implícitas en tf.Variable
operaciones en el lugar.
Nota: No se permitirá cualquier promoción que resulte en un dtype que sea diferente del dtype authentic de la variable. Esto es porque tf.Variable
no puede cambiar su dtype.
tnp.experimental_enable_numpy_behavior(dtype_conversion_mode="all")
a = tf.Variable(10, tf.int32)
a.assign_add(tf.fixed(5, tf.int16)) #
WARNING:tensorflow:UserWarning: enabling the brand new sort promotion should occur in the beginning of this system. Please guarantee no TF APIs have been used but.
tf. Conversiones implícitas constitales
En la promoción de tipo antiguo, tf.fixed
requirió un tensor de entrada para tener el mismo dtype que el argumento dtype. Sin embargo, en la nueva promoción de tipo, convertimos implícitamente el tensor en el dtype especificado.
tnp.experimental_enable_numpy_behavior(dtype_conversion_mode="all")
a = tf.fixed(10, tf.int16)
tf.fixed(a, tf.float32) #
WARNING:tensorflow:UserWarning: enabling the brand new sort promotion should occur in the beginning of this system. Please guarantee no TF APIs have been used but.
Matriz de tf-numpy
tnp.array
predeterminado a i32*
y f32*
Para entradas de Python usando la nueva promoción de tipo.
tnp.array(1) #
tnp.array(1.0) #
Inferencia de tipo de entrada
Así es como se infieren los diferentes tipos de entradas en la promoción del nuevo tipo.
tf.Tensor
: Desdetf.Tensor
Tiene una propiedad dtype, no hacemos más inferencia.- Tipos numpy: esto incluye tipos como
np.array(1)
,np.int16(1)
ynp.float
. Dado que las entradas numpy también tienen una propiedad Dtype, tomamos la propiedad DTYPE como el tipo de inferencia de resultados. Tenga en cuenta que Numpy predeterminado esi64
yf64
. - Python Scalars/Nested Tipos: esto incluye tipos como
1
,[1, 2, 3]
y(1.0, 2.0)
.- Pitón
int
se infiere comoi32*
. - Pitón
float
se infiere comof32*
. - Pitón
complicated
se infiere comoc128*
.
- Pitón
- Si la entrada no cae en ninguna de las categorías anteriores, pero tiene una propiedad Dtype, tomamos la propiedad DTYPE como el tipo de inferencia de resultados.
Lectura adicional
La nueva promoción de tipo se parece mucho a la promoción de tipo de Jax-Numpy. Si desea saber más detalles sobre la nueva promoción de tipo y las opciones de diseño, consulte los recursos a continuación.
API de soporte de tébittensor
A continuación se muestra una lista de API que admite WeakTensor
.
Para un OP unario, esto significa que si se pasa una entrada sin tipo especificado por el usuario, devolverá un WeakTensor
.
Para un OP binario, seguirá la tabla de promoción aquí. Puede o no devolver un WeakTensor
dependiendo del resultado de la promoción de las dos entradas.
Nota: Todas las operaciones matemáticas (+
, -
, *
…) son compatibles.
tf.bitwise.invert
tf.clip_by_value
tf.debugging.check_numerics
tf.expand_dims
tf.id
tf.picture.adjust_brightness
tf.picture.adjust_gamma
tf.picture.extract_patches
tf.picture.random_brightness
tf.picture.stateless_random_brightness
tf.linalg.diag
tf.linalg.diag_part
tf.linalg.matmul
tf.linalg.matrix_transpose
tf.linalg.tensor_diag_part
tf.linalg.hint
tf.math.abs
tf.math.acos
tf.math.acosh
tf.math.add
tf.math.angle
tf.math.asin
tf.math.asinh
tf.math.atan
tf.math.atanh
tf.math.ceil
tf.math.conj
tf.math.cos
tf.math.cosh
tf.math.digamma
tf.math.divide_no_nan
tf.math.divide
tf.math.erf
tf.math.erfc
tf.math.erfcinv
tf.math.erfinv
tf.math.exp
tf.math.expm1
tf.math.flooring
tf.math.floordiv
tf.math.floormod
tf.math.imag
tf.math.lgamma
tf.math.log1p
tf.math.log_sigmoid
tf.math.log
tf.math.multiply_no_nan
tf.math.multiply
tf.math.ndtri
tf.math.unfavourable
tf.math.pow
tf.math.actual
tf.math.actual
tf.math.reciprocal_no_nan
tf.math.reciprocal
tf.math.reduce_euclidean_norm
tf.math.reduce_logsumexp
tf.math.reduce_max
tf.math.reduce_mean
tf.math.reduce_min
tf.math.reduce_prod
tf.math.reduce_std
tf.math.reduce_sum
tf.math.reduce_variance
tf.math.rint
tf.math.spherical
tf.math.rsqrt
tf.math.scalar_mul
tf.math.sigmoid
tf.math.signal
tf.math.sin
tf.math.sinh
tf.math.softplus
tf.math.particular.bessel_i0
tf.math.particular.bessel_i0e
tf.math.particular.bessel_i1
tf.math.particular.bessel_i1e
tf.math.particular.bessel_j0
tf.math.particular.bessel_j1
tf.math.particular.bessel_k0
tf.math.particular.bessel_k0e
tf.math.particular.bessel_k1
tf.math.particular.bessel_k1e
tf.math.particular.bessel_y0
tf.math.particular.bessel_y1
tf.math.particular.dawsn
tf.math.particular.expint
tf.math.particular.fresnel_cos
tf.math.particular.fresnel_sin
tf.math.particular.spence
tf.math.sqrt
tf.math.sq.
tf.math.subtract
tf.math.tan
tf.math.tanh
tf.nn.depth_to_space
tf.nn.elu
tf.nn.gelu
tf.nn.leaky_relu
tf.nn.log_softmax
tf.nn.relu6
tf.nn.relu
tf.nn.selu
tf.nn.softsign
tf.nn.space_to_depth
tf.nn.swish
tf.ones_like
tf.realdiv
tf.reshape
tf.squeeze
tf.stop_gradient
tf.transpose
tf.truncatediv
tf.truncatemod
tf.zeros_like
tf.experimental.numpy.abs
tf.experimental.numpy.absolute
tf.experimental.numpy.amax
tf.experimental.numpy.amin
tf.experimental.numpy.angle
tf.experimental.numpy.arange
tf.experimental.numpy.arccos
tf.experimental.numpy.arccosh
tf.experimental.numpy.arcsin
tf.experimental.numpy.arcsinh
tf.experimental.numpy.arctan
tf.experimental.numpy.arctanh
tf.experimental.numpy.round
tf.experimental.numpy.array
tf.experimental.numpy.asanyarray
tf.experimental.numpy.asarray
tf.experimental.numpy.ascontiguousarray
tf.experimental.numpy.common
tf.experimental.numpy.bitwise_not
tf.experimental.numpy.cbrt
tf.experimental.numpy.ceil
tf.experimental.numpy.conj
tf.experimental.numpy.conjugate
tf.experimental.numpy.copy
tf.experimental.numpy.cos
tf.experimental.numpy.cosh
tf.experimental.numpy.cumprod
tf.experimental.numpy.cumsum
tf.experimental.numpy.deg2rad
tf.experimental.numpy.diag
tf.experimental.numpy.diagflat
tf.experimental.numpy.diagonal
tf.experimental.numpy.diff
tf.experimental.numpy.empty_like
tf.experimental.numpy.exp2
tf.experimental.numpy.exp
tf.experimental.numpy.expand_dims
tf.experimental.numpy.expm1
tf.experimental.numpy.fabs
tf.experimental.numpy.repair
tf.experimental.numpy.flatten
tf.experimental.numpy.flip
tf.experimental.numpy.fliplr
tf.experimental.numpy.flipud
tf.experimental.numpy.flooring
tf.experimental.numpy.full_like
tf.experimental.numpy.imag
tf.experimental.numpy.log10
tf.experimental.numpy.log1p
tf.experimental.numpy.log2
tf.experimental.numpy.log
tf.experimental.numpy.max
tf.experimental.numpy.imply
tf.experimental.numpy.min
tf.experimental.numpy.moveaxis
tf.experimental.numpy.nanmean
tf.experimental.numpy.unfavourable
tf.experimental.numpy.ones_like
tf.experimental.numpy.constructive
tf.experimental.numpy.prod
tf.experimental.numpy.rad2deg
tf.experimental.numpy.ravel
tf.experimental.numpy.actual
tf.experimental.numpy.reciprocal
tf.experimental.numpy.repeat
tf.experimental.numpy.reshape
tf.experimental.numpy.rot90
tf.experimental.numpy.spherical
tf.experimental.numpy.signbit
tf.experimental.numpy.sin
tf.experimental.numpy.sinc
tf.experimental.numpy.sinh
tf.experimental.numpy.type
tf.experimental.numpy.sqrt
tf.experimental.numpy.sq.
tf.experimental.numpy.squeeze
tf.experimental.numpy.std
tf.experimental.numpy.sum
tf.experimental.numpy.swapaxes
tf.experimental.numpy.tan
tf.experimental.numpy.tanh
tf.experimental.numpy.hint
tf.experimental.numpy.transpose
tf.experimental.numpy.triu
tf.experimental.numpy.vander
tf.experimental.numpy.var
tf.experimental.numpy.zeros_like
Publicado originalmente en el