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.

embedding.py 5.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. from typing import Optional
  10. import numpy as np
  11. from ..functional.nn import embedding as embedding_func
  12. from ..tensor import Parameter
  13. from . import init
  14. from .module import Module
  15. class Embedding(Module):
  16. r"""A simple lookup table that stores embeddings of a fixed dictionary and size.
  17. This module is often used to store word embeddings and retrieve them using indices.
  18. The input to the module is a list of indices, and the output is the corresponding word embeddings.
  19. The indices should less than num_embeddings.
  20. Args:
  21. num_embeddings: size of embedding dictionary.
  22. embedding_dim: size of each embedding vector.
  23. padding_idx: should be set to None, not supportted now.
  24. max_norm: should be set to None, not supportted now.
  25. norm_type: should be set to None, not supportted now.
  26. initial_weight: the learnable weights of the module of shape (num_embeddings, embedding_dim).
  27. Examples:
  28. .. testcode::
  29. import numpy as np
  30. import megengine as mge
  31. import megengine.module as M
  32. weight = mge.tensor(np.array([(1.2,2.3,3.4,4.5,5.6)], dtype=np.float32))
  33. data = mge.tensor(np.array([(0,0)], dtype=np.int32))
  34. embedding = M.Embedding(1, 5, initial_weight=weight)
  35. output = embedding(data)
  36. with np.printoptions(precision=6):
  37. print(output.numpy())
  38. Outputs:
  39. .. testoutput::
  40. [[[1.2 2.3 3.4 4.5 5.6]
  41. [1.2 2.3 3.4 4.5 5.6]]]
  42. """
  43. def __init__(
  44. self,
  45. num_embeddings: int,
  46. embedding_dim: int,
  47. padding_idx: Optional[int] = None,
  48. max_norm: Optional[float] = None,
  49. norm_type: Optional[float] = None,
  50. initial_weight: Parameter = None,
  51. freeze: bool = False,
  52. **kwargs
  53. ):
  54. super().__init__(**kwargs)
  55. if padding_idx is not None:
  56. raise ValueError("Not support padding index now.")
  57. if max_norm is not None or norm_type is not None:
  58. raise ValueError("Not support weight normalize now.")
  59. self.padding_idx = padding_idx
  60. self.max_norm = max_norm
  61. self.norm_type = norm_type
  62. self.num_embeddings = num_embeddings
  63. self.embedding_dim = embedding_dim
  64. self.freeze = freeze
  65. if initial_weight is None:
  66. self.weight = Parameter(
  67. np.random.uniform(
  68. size=(self.num_embeddings, self.embedding_dim)
  69. ).astype(np.float32)
  70. )
  71. self.reset_parameters()
  72. else:
  73. if initial_weight.numpy().shape != (num_embeddings, embedding_dim):
  74. raise ValueError(
  75. "The weight shape should match num_embeddings and embedding_dim"
  76. )
  77. self.weight = Parameter(initial_weight.numpy())
  78. def reset_parameters(self) -> None:
  79. init.normal_(self.weight)
  80. def forward(self, inputs):
  81. if self.freeze:
  82. weight = self.weight.detach()
  83. else:
  84. weight = self.weight
  85. return embedding_func(inputs, weight)
  86. @classmethod
  87. def from_pretrained(
  88. cls,
  89. embeddings: Parameter,
  90. freeze: Optional[bool] = True,
  91. padding_idx: Optional[int] = None,
  92. max_norm: Optional[float] = None,
  93. norm_type: Optional[float] = None,
  94. ):
  95. r"""Creates Embedding instance from given 2-dimensional FloatTensor.
  96. Args:
  97. embeddings: tensor contained weight for the embedding.
  98. freeze: if ``True``, the weight does not get updated during the learning process. Default: True.
  99. padding_idx: should be set to None, not support Now.
  100. max_norm: should be set to None, not support Now.
  101. norm_type: should be set to None, not support Now.
  102. Examples:
  103. .. testcode::
  104. import numpy as np
  105. import megengine as mge
  106. import megengine.module as M
  107. weight = mge.tensor(np.array([(1.2,2.3,3.4,4.5,5.6)], dtype=np.float32))
  108. data = mge.tensor(np.array([(0,0)], dtype=np.int32))
  109. embedding = M.Embedding.from_pretrained(weight, freeze=False)
  110. output = embedding(data)
  111. print(output.numpy())
  112. Outputs:
  113. .. testoutput::
  114. [[[1.2 2.3 3.4 4.5 5.6]
  115. [1.2 2.3 3.4 4.5 5.6]]]
  116. """
  117. embeddings_shape = embeddings.shape
  118. embeddings_dim = len(embeddings_shape)
  119. if embeddings_dim != 2:
  120. raise ValueError("Embeddings parameter is expected to be 2-dimensional")
  121. rows = embeddings_shape[0]
  122. cols = embeddings_shape[1]
  123. embedding = cls(
  124. num_embeddings=rows,
  125. embedding_dim=cols,
  126. initial_weight=embeddings,
  127. padding_idx=padding_idx,
  128. max_norm=max_norm,
  129. norm_type=norm_type,
  130. freeze=freeze,
  131. )
  132. return embedding