(N=15)
| 1604 | |
| 1605 | |
| 1606 | def test_MultiHeadedAttentionModule(N=15): |
| 1607 | from numpy_ml.neural_nets.modules import MultiHeadedAttentionModule |
| 1608 | |
| 1609 | N = np.inf if N is None else N |
| 1610 | np.random.seed(12345) |
| 1611 | |
| 1612 | i = 1 |
| 1613 | while i < N + 1: |
| 1614 | n_ex = np.random.randint(1, 10) |
| 1615 | latent_dim = np.random.randint(1, 20) |
| 1616 | n_heads = np.random.randint(2, 10) |
| 1617 | d_k = d_v = n_heads * latent_dim |
| 1618 | |
| 1619 | Q = random_tensor((n_ex, d_k), standardize=True) |
| 1620 | K = random_tensor((n_ex, d_k), standardize=True) |
| 1621 | V = random_tensor((n_ex, d_v), standardize=True) |
| 1622 | |
| 1623 | mine = MultiHeadedAttentionModule(n_heads=n_heads, dropout_p=0) |
| 1624 | |
| 1625 | # forward prop |
| 1626 | y_pred = mine.forward(Q, K, V) |
| 1627 | |
| 1628 | # backprop |
| 1629 | dLdy = np.ones_like(y_pred) |
| 1630 | dLdQ, dLdK, dLdV = mine.backward(dLdy) |
| 1631 | |
| 1632 | # get gold standard gradients |
| 1633 | params = mine.parameters |
| 1634 | hparams = mine.hyperparameters |
| 1635 | gold_mod = TorchMultiHeadedAttentionModule(params, hparams) |
| 1636 | golds = gold_mod.extract_grads(Q, K, V) |
| 1637 | |
| 1638 | dv = mine.derived_variables |
| 1639 | params = mine.parameters["components"] |
| 1640 | grads = mine.gradients["components"] |
| 1641 | params = [ |
| 1642 | (Q, "Q"), |
| 1643 | (K, "K"), |
| 1644 | (V, "V"), |
| 1645 | (mine.n_heads, "n_heads"), |
| 1646 | (mine.latent_dim, "latent_dim"), |
| 1647 | (params["O"]["W"], "O_W"), |
| 1648 | (params["K"]["W"], "K_W"), |
| 1649 | (params["V"]["W"], "V_W"), |
| 1650 | (params["Q"]["W"], "Q_W"), |
| 1651 | (params["O"]["b"], "O_b"), |
| 1652 | (params["K"]["b"], "K_b"), |
| 1653 | (params["V"]["b"], "V_b"), |
| 1654 | (params["Q"]["b"], "Q_b"), |
| 1655 | (dv["Q_proj"], "Q_proj"), |
| 1656 | (dv["K_proj"], "K_proj"), |
| 1657 | (dv["V_proj"], "V_proj"), |
| 1658 | (dv["attention_weights"][0], "weights"), |
| 1659 | (dv["attention_out"], "attn_out"), |
| 1660 | (y_pred, "Y"), |
| 1661 | (dLdy, "dLdy"), |
| 1662 | (dv["dQ_proj"], "dQ_proj"), |
| 1663 | (dv["dK_proj"], "dK_proj"), |
nothing calls this directly
no test coverage detected