Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

run_embedding.py 9.3 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
  1. # coding=utf-8
  2. # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
  3. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """ Returning embedding of input text """
  17. import logging
  18. import os
  19. import sys
  20. from dataclasses import dataclass, field
  21. from typing import Dict, List, Optional, Tuple
  22. from torch.utils.data.dataloader import DataLoader
  23. import numpy as np
  24. import torch
  25. from torch import nn
  26. import h5py
  27. import pdb
  28. from tqdm import tqdm
  29. from transformers import (
  30. AutoConfig,
  31. AutoTokenizer,
  32. AutoModel,
  33. HfArgumentParser,
  34. set_seed,
  35. )
  36. from utils_embedding import EmbeddingDataset, data_collator
  37. logger = logging.getLogger(__name__)
  38. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
  39. @dataclass
  40. class ModelArguments:
  41. """
  42. Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
  43. """
  44. model_name_or_path: str = field(
  45. metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
  46. )
  47. config_name: Optional[str] = field(
  48. default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
  49. )
  50. tokenizer_name: Optional[str] = field(
  51. default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
  52. )
  53. use_fast: bool = field(default=False, metadata={"help": "Set this flag to use fast tokenization."})
  54. # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
  55. # or just modify its tokenizer_config.json.
  56. cache_dir: Optional[str] = field(
  57. default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
  58. )
  59. @dataclass
  60. class DataArguments:
  61. """
  62. Arguments pertaining to what data we are going to input our model for training and eval.
  63. """
  64. data_path: str = field(
  65. metadata={"help": "The input data path in .txt format."}
  66. )
  67. output_path: str = field(
  68. metadata={"help": "The file name of embedding output (.h5)"}
  69. )
  70. @dataclass
  71. class EmbeddingArguments:
  72. """
  73. Arguments pertaining to what data we are going to input our model for training and eval.
  74. """
  75. pooling: str = field(
  76. default='none',
  77. metadata={"help": "Pooling method: none, first, mean, sum (default:none)"}
  78. )
  79. batch_size: int = field(
  80. default=32,
  81. metadata={"help": "Batch size to embed in batch"}
  82. )
  83. max_seq_length: int = field(
  84. default=128,
  85. metadata={
  86. "help": "The maximum total input sequence length after tokenization. Sequences longer "
  87. "than this will be truncated, sequences shorter will be padded."
  88. },
  89. )
  90. class Embedder:
  91. """
  92. Embedder is a simple but feature-complete training and eval loop for PyTorch,
  93. optimized for Transformers.
  94. """
  95. model: AutoModel
  96. args: EmbeddingArguments
  97. embed_dataset: EmbeddingDataset
  98. output_path: str
  99. def __init__(
  100. self,
  101. model: AutoModel,
  102. args: EmbeddingArguments,
  103. embed_dataset: EmbeddingDataset=None,
  104. output_path: str=""
  105. ):
  106. """
  107. Embedder is a simple but feature-complete training and eval loop for PyTorch,
  108. optimized for Transformers.
  109. """
  110. self.model = model.to(device)
  111. self.args = args
  112. self.embed_dataset = embed_dataset
  113. self.output_path = output_path
  114. def get_embed_dataloader(self) -> DataLoader:
  115. if self.embed_dataset is None:
  116. raise ValueError("Embedder: embedding requires a embed_dataset.")
  117. data_loader = DataLoader(
  118. self.embed_dataset,
  119. batch_size=self.args.batch_size,
  120. collate_fn=data_collator
  121. )
  122. return data_loader
  123. def num_examples(self, dataloader: DataLoader) -> int:
  124. """
  125. Helper to get num of examples from a DataLoader, by accessing its Dataset.
  126. """
  127. return len(dataloader.dataset)
  128. def embed(self) -> Tuple:
  129. """
  130. Run prediction and return predictions and potential metrics.
  131. Depending on the dataset and your use case, your test dataset may contain labels.
  132. In that case, this method will also return metrics, like in evaluate().
  133. """
  134. embed_dataloader = self.get_embed_dataloader()
  135. return self._embedding_loop(embed_dataloader)
  136. def _embedding_loop(
  137. self, dataloader: DataLoader
  138. ) -> Tuple:
  139. """
  140. Prediction/evaluation loop, shared by `evaluate()` and `predict()`.
  141. Works both with or without labels.
  142. """
  143. model = self.model
  144. batch_size = dataloader.batch_size
  145. logger.info("***** Running embedding *****")
  146. logger.info(" Num examples = %d", self.num_examples(dataloader))
  147. logger.info(" Batch size = %d", batch_size)
  148. model.eval()
  149. # prepare for hdf5 file stream
  150. f = h5py.File(self.output_path, 'w')
  151. for inputs in tqdm(dataloader, desc='embedding'):
  152. for k, v in inputs.items():
  153. if isinstance(v, torch.Tensor):
  154. inputs[k] = v.to(device)
  155. metadata = inputs['metadata']
  156. del inputs['metadata']
  157. with torch.no_grad():
  158. outputs = model(**inputs)
  159. last_hidden_states = outputs[0].detach()
  160. # batch process (fast)
  161. embeddings = []
  162. if self.args.pooling == 'first':
  163. embeddings = last_hidden_states[:,0,:]
  164. elif self.args.pooling == 'sum' or self.args.pooling == 'mean':
  165. # masking [CLS] and [SEP]
  166. attention_mask = inputs['attention_mask'].detach()
  167. attention_mask = torch.nn.functional.pad(attention_mask[:,2:],(1,1)) # 2 means [CLS] and [SEP]
  168. # extract the hidden state where there's no masking
  169. attention_mask = attention_mask.unsqueeze(-1).expand(last_hidden_states.shape)
  170. sub_embeddings = (attention_mask.to(torch.float)*last_hidden_states)
  171. # summation
  172. embeddings = sub_embeddings.sum(dim=1)
  173. # mean
  174. if self.args.pooling == 'mean':
  175. attention_mask = attention_mask[:,:,0].sum(dim=-1).unsqueeze(1)
  176. embeddings = embeddings/attention_mask.to(torch.float)
  177. elif self.args.pooling == 'none':
  178. for embed, attention_mask in zip(last_hidden_states, inputs['attention_mask']):
  179. token_embed = embed[0:attention_mask.sum()]
  180. embeddings.append(token_embed)
  181. # save into hdf5 file
  182. for embedding, each_metadata in zip(embeddings,metadata):
  183. text_id=u"{}".format(each_metadata['text'])
  184. dg = f.get(text_id) or f.create_group(text_id)
  185. if not dg.get('embedding'):
  186. dg.create_dataset('embedding', data=embedding.cpu())
  187. # close hdf5 file stream
  188. f.close()
  189. def main():
  190. # We now keep distinct sets of args, for a cleaner separation of concerns.
  191. parser = HfArgumentParser((ModelArguments, DataArguments, EmbeddingArguments))
  192. model_args, data_args, embed_args = parser.parse_args_into_dataclasses()
  193. # Setup logging
  194. logging.basicConfig(
  195. format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
  196. datefmt="%m/%d/%Y %H:%M:%S",
  197. level=logging.INFO,
  198. )
  199. # argument check
  200. if embed_args.pooling not in ['none', 'first', 'mean', 'sum']:
  201. logging.warn('pooling should be none, first, mean, or sum')
  202. return
  203. # Load pretrained model and tokenizer
  204. config = AutoConfig.from_pretrained(
  205. model_args.config_name if model_args.config_name else model_args.model_name_or_path,
  206. )
  207. tokenizer = AutoTokenizer.from_pretrained(
  208. model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
  209. use_fast=model_args.use_fast,
  210. )
  211. model = AutoModel.from_pretrained(
  212. model_args.model_name_or_path,
  213. from_tf=bool(".ckpt" in model_args.model_name_or_path),
  214. config=config,
  215. cache_dir=model_args.cache_dir,
  216. )
  217. # Get datasets
  218. embed_dataset = EmbeddingDataset(
  219. data_path=data_args.data_path,
  220. tokenizer=tokenizer,
  221. max_seq_length=embed_args.max_seq_length,
  222. )
  223. # Initialize our Embedder
  224. embedder = Embedder(
  225. model=model,
  226. args=embed_args,
  227. embed_dataset=embed_dataset,
  228. output_path=data_args.output_path
  229. )
  230. # run embed and save it to hdf5
  231. embedder.embed()
  232. print("done")
  233. def _mp_fn(index):
  234. # For xla_spawn (TPUs)
  235. main()
  236. if __name__ == "__main__":
  237. main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...