:param d_model: dimension of the model :param height: height of the positions :param width: width of the positions :return: d_model*height*width position matrix from https://github.com/wzlxjtu/PositionalEncoding2D
(d_model, height, width)
| 32 | return emb |
| 33 | |
| 34 | def positionalencoding2d(d_model, height, width): |
| 35 | """ |
| 36 | :param d_model: dimension of the model |
| 37 | :param height: height of the positions |
| 38 | :param width: width of the positions |
| 39 | :return: d_model*height*width position matrix |
| 40 | from https://github.com/wzlxjtu/PositionalEncoding2D |
| 41 | """ |
| 42 | if d_model % 4 != 0: |
| 43 | raise ValueError("Cannot use sin/cos positional encoding with " |
| 44 | "odd dimension (got dim={:d})".format(d_model)) |
| 45 | pe = torch.zeros(d_model, height, width) |
| 46 | # Each dimension use half of d_model |
| 47 | d_model = int(d_model / 2) |
| 48 | div_term = torch.exp(torch.arange(0., d_model, 2) * |
| 49 | -(math.log(10000.0) / d_model)) |
| 50 | pos_w = torch.arange(0., width).unsqueeze(1) |
| 51 | pos_h = torch.arange(0., height).unsqueeze(1) |
| 52 | pe[0:d_model:2, :, :] = torch.sin(pos_w * div_term).transpose(0, 1).unsqueeze(1).repeat(1, height, 1) |
| 53 | pe[1:d_model:2, :, :] = torch.cos(pos_w * div_term).transpose(0, 1).unsqueeze(1).repeat(1, height, 1) |
| 54 | pe[d_model::2, :, :] = torch.sin(pos_h * div_term).transpose(0, 1).unsqueeze(2).repeat(1, 1, width) |
| 55 | pe[d_model + 1::2, :, :] = torch.cos(pos_h * div_term).transpose(0, 1).unsqueeze(2).repeat(1, 1, width) |
| 56 | return pe |
| 57 | |
| 58 | def nonlinearity(x): |
| 59 | # swish |