臨界區。
用法
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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。