临界区。
用法
tf.CriticalSection(
name=None, shared_name=None, critical_section_def=None, import_scope=None
)
属性
-
name
CriticalSection
对象是图中的资源,它按顺序执行子图。一个可能希望以独占方式运行的子图的常见示例是由以下函数给出的示例:
v = resource_variable_ops.ResourceVariable(0.0, name="v")
def count():
value = v.read_value()
with tf.control_dependencies([value]):
with tf.control_dependencies([v.assign_add(1)]):
return tf.identity(value)
这里,v
的快照在 value
中被捕获;然后更新v
。返回快照值。
如果多个工作人员或线程都并行执行 count
,则无法保证在任何线程的 count
计算中的任何时候对变量 v
的访问都是原子的。事实上,即使实现一个原子计数器来保证用户将看到每个值 0, 1, ...,
目前也是不可能的。
解决方案是确保对底层资源 v
的任何访问仅通过关键部分进行处理:
cs = CriticalSection()
f1 = cs.execute(count)
f2 = cs.execute(count)
output = f1 + f2
session.run(output)
函数f1
和f2
将连续执行,对v
的更新将是原子的。
注意
所有资源对象,包括临界区和在该临界区执行的函数的任何捕获变量,都将位于同一设备(主机和 cpu/gpu)。
在同一资源上使用多个临界区时,无法保证对这些资源的独占访问。默认情况下不允许此行为(但请参阅 kwarg exclusive_resource_access
)。
例如,在两个单独的临界区中运行相同的函数将无法确保串行执行:
v = tf.compat.v1.get_variable("v", initializer=0.0, use_resource=True)
def accumulate(up):
x = v.read_value()
with tf.control_dependencies([x]):
with tf.control_dependencies([v.assign_add(up)]):
return tf.identity(x)
ex1 = CriticalSection().execute(
accumulate, 1.0, exclusive_resource_access=False)
ex2 = CriticalSection().execute(
accumulate, 1.0, exclusive_resource_access=False)
bad_sum = ex1 + ex2
sess.run(v.initializer)
sess.run(bad_sum) # May return 0.0
相关用法
- Python tf.CriticalSection.execute用法及代码示例
- Python tf.compat.v1.distributions.Multinomial.stddev用法及代码示例
- Python tf.compat.v1.distribute.MirroredStrategy.experimental_distribute_dataset用法及代码示例
- Python tf.compat.v1.data.TFRecordDataset.interleave用法及代码示例
- Python tf.summary.scalar用法及代码示例
- Python tf.linalg.LinearOperatorFullMatrix.matvec用法及代码示例
- Python tf.linalg.LinearOperatorToeplitz.solve用法及代码示例
- Python tf.raw_ops.TPUReplicatedInput用法及代码示例
- Python tf.raw_ops.Bitcast用法及代码示例
- Python tf.compat.v1.distributions.Bernoulli.cross_entropy用法及代码示例
- Python tf.compat.v1.Variable.eval用法及代码示例
- Python tf.compat.v1.train.FtrlOptimizer.compute_gradients用法及代码示例
- Python tf.distribute.OneDeviceStrategy.experimental_distribute_values_from_function用法及代码示例
- Python tf.math.special.fresnel_cos用法及代码示例
- Python tf.keras.applications.inception_resnet_v2.preprocess_input用法及代码示例
- Python tf.compat.v1.layers.conv3d用法及代码示例
- Python tf.Variable.__lt__用法及代码示例
- Python tf.keras.metrics.Mean.merge_state用法及代码示例
- Python tf.keras.layers.InputLayer用法及代码示例
- Python tf.compat.v1.strings.length用法及代码示例
注:本文由纯净天空筛选整理自tensorflow.org大神的英文原创作品 tf.CriticalSection。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。