(N=15)
| 1214 | |
| 1215 | |
| 1216 | def test_DPAttention(N=15): |
| 1217 | from numpy_ml.neural_nets.layers import DotProductAttention |
| 1218 | |
| 1219 | N = np.inf if N is None else N |
| 1220 | |
| 1221 | np.random.seed(12345) |
| 1222 | |
| 1223 | i = 1 |
| 1224 | while i < N + 1: |
| 1225 | n_ex = np.random.randint(1, 10) |
| 1226 | d_k = np.random.randint(1, 100) |
| 1227 | d_v = np.random.randint(1, 100) |
| 1228 | |
| 1229 | Q = random_tensor((n_ex, d_k), standardize=True) |
| 1230 | K = random_tensor((n_ex, d_k), standardize=True) |
| 1231 | V = random_tensor((n_ex, d_v), standardize=True) |
| 1232 | |
| 1233 | # initialize DotProductAttention layer |
| 1234 | mine = DotProductAttention(scale=True, dropout_p=0) |
| 1235 | |
| 1236 | # forward prop |
| 1237 | y_pred = mine.forward(Q, K, V) |
| 1238 | |
| 1239 | # backprop |
| 1240 | dLdy = np.ones_like(y_pred) |
| 1241 | dLdQ, dLdK, dLdV = mine.backward(dLdy) |
| 1242 | |
| 1243 | # get gold standard gradients |
| 1244 | gold_mod = TorchSDPAttentionLayer() |
| 1245 | golds = gold_mod.extract_grads(Q, K, V) |
| 1246 | |
| 1247 | params = [ |
| 1248 | (mine.X[0][0], "Q"), |
| 1249 | (mine.X[0][1], "K"), |
| 1250 | (mine.X[0][2], "V"), |
| 1251 | (y_pred, "Y"), |
| 1252 | (dLdV, "dLdV"), |
| 1253 | (dLdK, "dLdK"), |
| 1254 | (dLdQ, "dLdQ"), |
| 1255 | ] |
| 1256 | |
| 1257 | print("\nTrial {}".format(i)) |
| 1258 | print("n_ex={} d_k={} d_v={}".format(n_ex, d_k, d_v)) |
| 1259 | for ix, (mine, label) in enumerate(params): |
| 1260 | assert_almost_equal( |
| 1261 | mine, golds[label], err_msg=err_fmt(params, golds, ix), decimal=4 |
| 1262 | ) |
| 1263 | print("\tPASSED {}".format(label)) |
| 1264 | i += 1 |
| 1265 | |
| 1266 | |
| 1267 | def test_Conv1D(N=15): |
nothing calls this directly
no test coverage detected