You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

AttentionTest.cs 8.6 kB

3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. using Microsoft.VisualStudio.TestTools.UnitTesting;
  2. using Tensorflow.Keras.Layers;
  3. using Tensorflow.Keras.Utils;
  4. using Tensorflow.NumPy;
  5. using static Tensorflow.Binding;
  6. using static Tensorflow.KerasApi;
  7. namespace Tensorflow.Keras.UnitTest.Layers
  8. {
  9. [TestClass]
  10. public class AttentionTest : EagerModeTestBase
  11. {
  12. #region BaseDenseAttention
  13. [TestMethod]
  14. public void test_multi_dim_with_mask()
  15. {
  16. // Scores tensor of shape [1, 1, 3]
  17. var scores = np.array(new[, ,] { { { 1f, 0f, 1f } } }, dtype: np.float32);
  18. // Value tensor of shape [1, 3, 1]
  19. var v = np.array(new[, ,] { { { 1.6f }, { 0.7f }, { -0.8f } } }, dtype: np.float32);
  20. // Scores mask tensor of shape [1, 1, 3]
  21. var scores_mask = np.array(new[, ,] { { { true, true, false } } }, dtype: np.@bool);
  22. var _tup_1 = new BaseDenseAttention(new())._apply_scores(scores: scores, value: v, scores_mask: scores_mask);
  23. var actual = _tup_1.Item1;
  24. var actual_scores = _tup_1.Item2;
  25. // Expected softmax scores = softmax(scores) with zeros in positions where
  26. // v_mask == False.
  27. // => softmax_scores000 = exp(1)/(exp(1) + exp(0)) = 0.73105857863
  28. // softmax_scores001 = exp(0)/(exp(1) + exp(0)) = 0.26894142137
  29. // softmax_scores002 = 0
  30. var expected_scores = np.array(new[, ,] { { { 0.73105857863f, 0.26894142137f, 0f } } }, dtype: np.float32);
  31. Assert.AreEqual(expected_scores, actual_scores.numpy());
  32. // Expected tensor of shape [1, 1, 1].
  33. // expected000 = 0.73105857863 * 1.6 + 0.26894142137 * 0.7 - 0 * 0.8
  34. // = 1.35795272077
  35. //Actually the output is 1.3579528
  36. var expected = np.array(new[, ,] { { { 1.3579528f } } }, dtype: np.float32);
  37. Assert.AreEqual(expected, actual.numpy());
  38. }
  39. [TestMethod]
  40. public void test_one_dim_batch_size_two()
  41. {
  42. // Scores tensor of shape [2, 1, 1]
  43. var scores = np.array(new[, ,] { { { 1.1f } }, { { 2.1f } } }, dtype: np.float32);
  44. // Value tensor of shape [2, 1, 1]
  45. var v = np.array(new[, ,] { { { 1.6f } }, { { 2.6f } } }, dtype: np.float32);
  46. // Scpres mask tensor of shape [2, 1, 1]
  47. var scores_mask = np.array(new[, ,] { { { true } }, { { true } } }, dtype: np.@bool);
  48. var _tup_1 = new BaseDenseAttention(new())._apply_scores(scores: scores, value: v, scores_mask: scores_mask);
  49. var actual = _tup_1.Item1;
  50. var actual_scores = _tup_1.Item2;
  51. // Expected softmax_scores = [[[1]], [[1]]]
  52. var expected_scores = np.array(new[, ,] { { { 1f } }, { { 1f } } }, dtype: np.float32);
  53. Assert.AreEqual(expected_scores, actual_scores.numpy());
  54. // Expected tensor of shape [2, 1, 1].
  55. // expected000 = softmax_scores[0, 0] * 1.6 = 1.6
  56. // expected100 = softmax_scores[1, 0] * 2.6 = 2.6
  57. var expected = np.array(new[, ,] { { { 1.6f } }, { { 2.6f } } }, dtype: np.float32);
  58. Assert.AreEqual(expected, actual.numpy());
  59. }
  60. #endregion
  61. // ------------------------------------------------------------------
  62. #region Attention
  63. [TestMethod]
  64. public void test_calculate_scores_multi_dim()
  65. {
  66. // Query tensor of shape [1, 2, 4]
  67. var q = np.array(new[, ,] { {
  68. { 1f, 1.1f, 1.2f, 1.3f },
  69. { 2f, 2.1f, 2.2f, 2.3f }
  70. } }, dtype: np.float32);
  71. // Key tensor of shape [1, 3, 4]
  72. var k = np.array(new[, ,] { {
  73. { 1.5f, 1.6f, 1.7f, 1.8f },
  74. { 2.5f, 2.6f, 2.7f, 2.8f },
  75. { 3.5f, 3.6f, 3.7f, 3.8f }
  76. } }, dtype: np.float32);
  77. var attention_layer = (Attention)keras.layers.Attention();
  78. //attention_layer.build(((1, 2, 4), (1, 3, 4)));
  79. var actual = attention_layer._calculate_scores(query: q, key: k);
  80. // Expected tensor of shape [1, 2, 3].
  81. // expected000 = 1.*1.5+1.1*1.6+1.2*1.7+1.3*1.8 = 7.64
  82. // expected001 = 1.*2.5+1.1*2.6+1.2*2.7+1.3*2.8 = 12.24
  83. // expected002 = 1.*3.5+1.1*3.6+1.2*3.7+1.3*3.8 = 16.84
  84. // expected010 = 2.*1.5+2.1*1.6+2.2*1.7+2.3*1.8 = 14.24
  85. // expected011 = 2.*2.5+2.1*2.6+2.2*2.7+2.3*2.8 = 22.84
  86. // expected012 = 2.*3.5+2.1*3.6+2.2*3.7+2.3*3.8 = 31.44
  87. // Actually the output000 is 7.6400003, the output012 is 31.439999
  88. var expected = np.array(new[, ,] { {
  89. { 7.6400003f, 12.24f, 16.84f },
  90. { 14.24f, 22.84f, 31.439999f }
  91. } }, dtype: np.float32);
  92. Assert.IsTrue(expected == actual.numpy());
  93. }
  94. [TestMethod]
  95. [Ignore]
  96. public void test_calculate_scores_multi_dim_concat()
  97. {
  98. // Query tensor of shape [1, 2, 4]
  99. var q = np.array(new[, ,] { {
  100. { 1f, 1.1f, 1.2f, 1.3f },
  101. { 2f, 2.1f, 2.2f, 2.3f }
  102. } }, dtype: np.float32);
  103. // Key tensor of shape [1, 3, 4]
  104. var k = np.array(new[, ,] { {
  105. { 1.5f, 1.6f, 1.7f, 1.8f },
  106. { 2.5f, 2.6f, 2.7f, 2.8f },
  107. { 3.5f, 3.6f, 3.7f, 3.8f }
  108. } }, dtype: np.float32);
  109. var attention_layer = (Attention)keras.layers.Attention(score_mode: "concat");
  110. //attention_layer.concat_score_weight = 1;
  111. attention_layer.concat_score_weight = base_layer_utils.make_variable(new VariableArgs()
  112. {
  113. Name = "concat_score_weight",
  114. Shape = (1),
  115. DType = TF_DataType.TF_FLOAT,
  116. Getter = base_layer_utils.make_variable,
  117. Overwrite = true,
  118. Initializer = tf.ones_initializer,
  119. Synchronization = VariableSynchronization.Auto,
  120. Aggregation = VariableAggregation.None,
  121. Trainable = true
  122. });
  123. //attention_layer.build(((1, 2, 4), (1, 3, 4)));
  124. //var actual = keras.backend.get_value(attention_layer._calculate_scores(query: q, key: k));
  125. var actual = attention_layer._calculate_scores(query: q, key: k);
  126. // pylint:disable=line-too-long
  127. // expected000 = tanh(1.+1.5) + tanh(1.1+1.6) + tanh(1.2+1.7) + tanh(1.3+1.8) = 3.96753427840
  128. // expected001 = tanh(1.+2.5) + tanh(1.1+2.6) + tanh(1.2+2.7) + tanh(1.3+2.8) = 3.99558784825
  129. // expected002 = tanh(1.+3.5) + tanh(1.1+3.6) + tanh(1.2+3.7) + tanh(1.3+3.8) = 3.99940254147
  130. // expected010 = tanh(2.+1.5) + tanh(2.1+1.6) + tanh(2.2+1.7) + tanh(2.3+1.8) = 3.99558784825
  131. // expected011 = tanh(2.+2.5) + tanh(2.1+2.6) + tanh(2.2+2.7) + tanh(2.3+2.8) = 3.99940254147
  132. // expected012 = tanh(2.+3.5) + tanh(2.1+3.6) + tanh(2.2+3.7) + tanh(2.3+3.8) = 3.99991913657
  133. //Actually the output012 is 3.9999194
  134. var expected = np.array(new[, ,] { {
  135. { 3.96753427840f, 3.99558784825f, 3.99940254147f },
  136. { 3.99558784825f, 3.99940254147f, 3.9999194f }
  137. } }, dtype: np.float32);
  138. Assert.AreEqual(expected, actual.numpy());
  139. }
  140. #endregion
  141. // ------------------------------------------------------------------
  142. #region MultiHeadAttention
  143. [TestMethod]
  144. public void test_masked_attention()
  145. {
  146. var batch_size = 3;
  147. var query = keras.Input(shape: (4, 8));
  148. var value = keras.Input(shape: (2, 8));
  149. var mask_tensor = keras.Input(shape: (4, 2));
  150. var attention_layer = keras.layers.MultiHeadAttention(num_heads: 2, key_dim: 2);
  151. attention_layer.Apply(new Tensor[] { query, value, mask_tensor });
  152. var from_data = 10 * np.random.randn(batch_size, 4, 8);
  153. var to_data = 10 * np.random.randn(batch_size, 2, 8);
  154. var mask_data = np.random.randint(2, size: (batch_size, 4, 2));
  155. var masked_output_data = attention_layer.Apply(new[] { from_data, to_data, mask_data });
  156. var null_mask_data = np.ones((batch_size, 4, 2));
  157. var unmasked_output_data = attention_layer.Apply(new[] { from_data, to_data, null_mask_data });
  158. Assert.AreNotEqual(masked_output_data, unmasked_output_data);
  159. }
  160. #endregion
  161. }
  162. }