ctranslate2 4.7.0__cp314-cp314-macosx_11_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,455 @@
1
+ import argparse
2
+ import copy
3
+ import os
4
+
5
+ from typing import Optional, Union
6
+
7
+ from ctranslate2.converters import utils
8
+ from ctranslate2.converters.converter import Converter
9
+ from ctranslate2.specs import common_spec, transformer_spec
10
+
11
+ _SUPPORTED_ACTIVATIONS = {
12
+ "gelu": common_spec.Activation.GELUTanh,
13
+ "relu": common_spec.Activation.RELU,
14
+ "swish": common_spec.Activation.SWISH,
15
+ }
16
+
17
+
18
+ class OpenNMTTFConverter(Converter):
19
+ """Converts OpenNMT-tf models."""
20
+
21
+ @classmethod
22
+ def from_config(
23
+ cls,
24
+ config: Union[str, dict],
25
+ auto_config: bool = False,
26
+ checkpoint_path: Optional[str] = None,
27
+ model: Optional[str] = None,
28
+ ):
29
+ """Creates the converter from the configuration.
30
+
31
+ Arguments:
32
+ config: Path to the YAML configuration, or a dictionary with the loaded configuration.
33
+ auto_config: Whether the model automatic configuration values should be used.
34
+ checkpoint_path: Path to the checkpoint or checkpoint directory to load. If not set,
35
+ the latest checkpoint from the model directory is loaded.
36
+ model: If the model instance cannot be resolved from the model directory, this argument
37
+ can be set to either the name of the model in the catalog or the path to the model
38
+ configuration.
39
+
40
+ Returns:
41
+ A :class:`ctranslate2.converters.OpenNMTTFConverter` instance.
42
+ """
43
+ from opennmt import config as config_util
44
+ from opennmt.utils.checkpoint import Checkpoint
45
+
46
+ if isinstance(config, str):
47
+ config = config_util.load_config([config])
48
+ else:
49
+ config = copy.deepcopy(config)
50
+
51
+ if model is None:
52
+ model = config_util.load_model(config["model_dir"])
53
+ elif os.path.exists(model):
54
+ model = config_util.load_model_from_file(model)
55
+ else:
56
+ model = config_util.load_model_from_catalog(model)
57
+
58
+ if auto_config:
59
+ config_util.merge_config(config, model.auto_config())
60
+
61
+ data_config = config_util.try_prefix_paths(config["model_dir"], config["data"])
62
+ model.initialize(data_config)
63
+
64
+ checkpoint = Checkpoint.from_config(config, model)
65
+ checkpoint_path = checkpoint.restore(checkpoint_path=checkpoint_path)
66
+ if checkpoint_path is None:
67
+ raise RuntimeError("No checkpoint was restored")
68
+
69
+ model.create_variables()
70
+ return cls(model)
71
+
72
+ def __init__(self, model):
73
+ """Initializes the converter.
74
+
75
+ Arguments:
76
+ model: An initialized and fully-built ``opennmt.models.Model`` instance.
77
+ """
78
+ self._model = model
79
+
80
+ def _load(self):
81
+ import opennmt
82
+
83
+ if isinstance(self._model, opennmt.models.LanguageModel):
84
+ spec_builder = TransformerDecoderSpecBuilder()
85
+ else:
86
+ spec_builder = TransformerSpecBuilder()
87
+
88
+ return spec_builder(self._model)
89
+
90
+
91
+ class TransformerSpecBuilder:
92
+ def __call__(self, model):
93
+ import opennmt
94
+
95
+ check = utils.ConfigurationChecker()
96
+ check(
97
+ isinstance(model, opennmt.models.Transformer),
98
+ "Only Transformer models are supported",
99
+ )
100
+ check.validate()
101
+
102
+ check(
103
+ isinstance(model.encoder, opennmt.encoders.SelfAttentionEncoder),
104
+ "Parallel encoders are not supported",
105
+ )
106
+ check(
107
+ isinstance(
108
+ model.features_inputter,
109
+ (opennmt.inputters.WordEmbedder, opennmt.inputters.ParallelInputter),
110
+ ),
111
+ "Source inputter must be a WordEmbedder or a ParallelInputter",
112
+ )
113
+ check.validate()
114
+
115
+ mha = model.encoder.layers[0].self_attention.layer
116
+ ffn = model.encoder.layers[0].ffn.layer
117
+ with_relative_position = mha.maximum_relative_position is not None
118
+ activation_name = ffn.inner.activation.__name__
119
+
120
+ check(
121
+ activation_name in _SUPPORTED_ACTIVATIONS,
122
+ "Activation %s is not supported (supported activations are: %s)"
123
+ % (activation_name, ", ".join(_SUPPORTED_ACTIVATIONS.keys())),
124
+ )
125
+ check(
126
+ with_relative_position != bool(model.encoder.position_encoder),
127
+ "Relative position representation and position encoding cannot be both enabled "
128
+ "or both disabled",
129
+ )
130
+ check(
131
+ model.decoder.attention_reduction
132
+ != opennmt.layers.MultiHeadAttentionReduction.AVERAGE_ALL_LAYERS,
133
+ "Averaging all multi-head attention matrices is not supported",
134
+ )
135
+
136
+ source_inputters = _get_inputters(model.features_inputter)
137
+ target_inputters = _get_inputters(model.labels_inputter)
138
+ num_source_embeddings = len(source_inputters)
139
+ if num_source_embeddings == 1:
140
+ embeddings_merge = common_spec.EmbeddingsMerge.CONCAT
141
+ else:
142
+ reducer = model.features_inputter.reducer
143
+ embeddings_merge = None
144
+ if reducer is not None:
145
+ if isinstance(reducer, opennmt.layers.ConcatReducer):
146
+ embeddings_merge = common_spec.EmbeddingsMerge.CONCAT
147
+ elif isinstance(reducer, opennmt.layers.SumReducer):
148
+ embeddings_merge = common_spec.EmbeddingsMerge.ADD
149
+
150
+ check(
151
+ all(
152
+ isinstance(inputter, opennmt.inputters.WordEmbedder)
153
+ for inputter in source_inputters
154
+ ),
155
+ "All source inputters must WordEmbedders",
156
+ )
157
+ check(
158
+ embeddings_merge is not None,
159
+ "Unsupported embeddings reducer %s" % reducer,
160
+ )
161
+
162
+ alignment_layer = -1
163
+ alignment_heads = 1
164
+ if (
165
+ model.decoder.attention_reduction
166
+ == opennmt.layers.MultiHeadAttentionReduction.AVERAGE_LAST_LAYER
167
+ ):
168
+ alignment_heads = 0
169
+
170
+ check.validate()
171
+
172
+ encoder_spec = transformer_spec.TransformerEncoderSpec(
173
+ len(model.encoder.layers),
174
+ model.encoder.layers[0].self_attention.layer.num_heads,
175
+ pre_norm=model.encoder.layer_norm is not None,
176
+ activation=_SUPPORTED_ACTIVATIONS[activation_name],
177
+ num_source_embeddings=num_source_embeddings,
178
+ embeddings_merge=embeddings_merge,
179
+ relative_position=with_relative_position,
180
+ )
181
+
182
+ decoder_spec = transformer_spec.TransformerDecoderSpec(
183
+ len(model.decoder.layers),
184
+ model.decoder.layers[0].self_attention.layer.num_heads,
185
+ pre_norm=model.decoder.layer_norm is not None,
186
+ activation=_SUPPORTED_ACTIVATIONS[activation_name],
187
+ relative_position=with_relative_position,
188
+ alignment_layer=alignment_layer,
189
+ alignment_heads=alignment_heads,
190
+ )
191
+
192
+ spec = transformer_spec.TransformerSpec(encoder_spec, decoder_spec)
193
+
194
+ spec.config.add_source_bos = bool(source_inputters[0].mark_start)
195
+ spec.config.add_source_eos = bool(source_inputters[0].mark_end)
196
+ for inputter in source_inputters:
197
+ spec.register_source_vocabulary(_load_vocab(inputter.vocabulary_file))
198
+ for inputter in target_inputters:
199
+ spec.register_target_vocabulary(_load_vocab(inputter.vocabulary_file))
200
+
201
+ self.set_transformer_encoder(
202
+ spec.encoder,
203
+ model.encoder,
204
+ model.features_inputter,
205
+ )
206
+ self.set_transformer_decoder(
207
+ spec.decoder,
208
+ model.decoder,
209
+ model.labels_inputter,
210
+ )
211
+
212
+ return spec
213
+
214
+ def set_transformer_encoder(self, spec, module, inputter):
215
+ for embedding_spec, inputter in zip(spec.embeddings, _get_inputters(inputter)):
216
+ self.set_embeddings(embedding_spec, inputter)
217
+ if module.position_encoder is not None:
218
+ self.set_position_encodings(
219
+ spec.position_encodings,
220
+ module.position_encoder,
221
+ )
222
+
223
+ for layer_spec, layer in zip(spec.layer, module.layers):
224
+ self.set_multi_head_attention(
225
+ layer_spec.self_attention,
226
+ layer.self_attention,
227
+ self_attention=True,
228
+ )
229
+
230
+ self.set_ffn(layer_spec.ffn, layer.ffn)
231
+
232
+ if module.layer_norm is not None:
233
+ self.set_layer_norm(spec.layer_norm, module.layer_norm)
234
+
235
+ def set_transformer_decoder(self, spec, module, inputter):
236
+ self.set_embeddings(spec.embeddings, inputter)
237
+ if module.position_encoder is not None:
238
+ self.set_position_encodings(
239
+ spec.position_encodings,
240
+ module.position_encoder,
241
+ )
242
+
243
+ for layer_spec, layer in zip(spec.layer, module.layers):
244
+ self.set_multi_head_attention(
245
+ layer_spec.self_attention,
246
+ layer.self_attention,
247
+ self_attention=True,
248
+ )
249
+
250
+ if layer.attention:
251
+ self.set_multi_head_attention(
252
+ layer_spec.attention,
253
+ layer.attention[0],
254
+ self_attention=False,
255
+ )
256
+
257
+ self.set_ffn(layer_spec.ffn, layer.ffn)
258
+
259
+ if module.layer_norm is not None:
260
+ self.set_layer_norm(spec.layer_norm, module.layer_norm)
261
+
262
+ self.set_linear(spec.projection, module.output_layer)
263
+
264
+ def set_ffn(self, spec, module):
265
+ self.set_linear(spec.linear_0, module.layer.inner)
266
+ self.set_linear(spec.linear_1, module.layer.outer)
267
+ self.set_layer_norm_from_wrapper(spec.layer_norm, module)
268
+
269
+ def set_multi_head_attention(self, spec, module, self_attention=False):
270
+ split_layers = [common_spec.LinearSpec() for _ in range(3)]
271
+ self.set_linear(split_layers[0], module.layer.linear_queries)
272
+ self.set_linear(split_layers[1], module.layer.linear_keys)
273
+ self.set_linear(split_layers[2], module.layer.linear_values)
274
+
275
+ if self_attention:
276
+ utils.fuse_linear(spec.linear[0], split_layers)
277
+ if module.layer.maximum_relative_position is not None:
278
+ spec.relative_position_keys = (
279
+ module.layer.relative_position_keys.numpy()
280
+ )
281
+ spec.relative_position_values = (
282
+ module.layer.relative_position_values.numpy()
283
+ )
284
+ else:
285
+ utils.fuse_linear(spec.linear[0], split_layers[:1])
286
+ utils.fuse_linear(spec.linear[1], split_layers[1:])
287
+
288
+ self.set_linear(spec.linear[-1], module.layer.linear_output)
289
+ self.set_layer_norm_from_wrapper(spec.layer_norm, module)
290
+
291
+ def set_layer_norm_from_wrapper(self, spec, module):
292
+ self.set_layer_norm(
293
+ spec,
294
+ (
295
+ module.output_layer_norm
296
+ if module.input_layer_norm is None
297
+ else module.input_layer_norm
298
+ ),
299
+ )
300
+
301
+ def set_layer_norm(self, spec, module):
302
+ spec.gamma = module.gamma.numpy()
303
+ spec.beta = module.beta.numpy()
304
+
305
+ def set_linear(self, spec, module):
306
+ spec.weight = module.kernel.numpy()
307
+ if not module.transpose:
308
+ spec.weight = spec.weight.transpose()
309
+ if module.bias is not None:
310
+ spec.bias = module.bias.numpy()
311
+
312
+ def set_embeddings(self, spec, module):
313
+ spec.weight = module.embedding.numpy()
314
+
315
+ def set_position_encodings(self, spec, module):
316
+ import opennmt
317
+
318
+ if isinstance(module, opennmt.layers.PositionEmbedder):
319
+ spec.encodings = module.embedding.numpy()[1:]
320
+
321
+
322
+ class TransformerDecoderSpecBuilder(TransformerSpecBuilder):
323
+ def __call__(self, model):
324
+ import opennmt
325
+
326
+ check = utils.ConfigurationChecker()
327
+ check(
328
+ isinstance(model.decoder, opennmt.decoders.SelfAttentionDecoder),
329
+ "Only self-attention decoders are supported",
330
+ )
331
+ check.validate()
332
+
333
+ mha = model.decoder.layers[0].self_attention.layer
334
+ ffn = model.decoder.layers[0].ffn.layer
335
+ activation_name = ffn.inner.activation.__name__
336
+
337
+ check(
338
+ activation_name in _SUPPORTED_ACTIVATIONS,
339
+ "Activation %s is not supported (supported activations are: %s)"
340
+ % (activation_name, ", ".join(_SUPPORTED_ACTIVATIONS.keys())),
341
+ )
342
+ check.validate()
343
+
344
+ spec = transformer_spec.TransformerDecoderModelSpec.from_config(
345
+ len(model.decoder.layers),
346
+ mha.num_heads,
347
+ pre_norm=model.decoder.layer_norm is not None,
348
+ activation=_SUPPORTED_ACTIVATIONS[activation_name],
349
+ )
350
+
351
+ spec.register_vocabulary(_load_vocab(model.features_inputter.vocabulary_file))
352
+ self.set_transformer_decoder(
353
+ spec.decoder,
354
+ model.decoder,
355
+ model.features_inputter,
356
+ )
357
+
358
+ return spec
359
+
360
+
361
+ def _get_inputters(inputter):
362
+ import opennmt
363
+
364
+ return (
365
+ inputter.inputters
366
+ if isinstance(inputter, opennmt.inputters.MultiInputter)
367
+ else [inputter]
368
+ )
369
+
370
+
371
+ def _load_vocab(vocab, unk_token="<unk>"):
372
+ import opennmt
373
+
374
+ if isinstance(vocab, opennmt.data.Vocab):
375
+ tokens = list(vocab.words)
376
+ elif isinstance(vocab, list):
377
+ tokens = list(vocab)
378
+ elif isinstance(vocab, str):
379
+ tokens = opennmt.data.Vocab.from_file(vocab).words
380
+ else:
381
+ raise TypeError("Invalid vocabulary type")
382
+
383
+ if unk_token not in tokens:
384
+ tokens.append(unk_token)
385
+ return tokens
386
+
387
+
388
+ def main():
389
+ parser = argparse.ArgumentParser(
390
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter
391
+ )
392
+ parser.add_argument("--config", help="Path to the YAML configuration.")
393
+ parser.add_argument(
394
+ "--auto_config",
395
+ action="store_true",
396
+ help="Use the model automatic configuration values.",
397
+ )
398
+ parser.add_argument(
399
+ "--model_path",
400
+ help=(
401
+ "Path to the checkpoint or checkpoint directory to load. If not set, "
402
+ "the latest checkpoint from the model directory is loaded."
403
+ ),
404
+ )
405
+ parser.add_argument(
406
+ "--model_type",
407
+ help=(
408
+ "If the model instance cannot be resolved from the model directory, "
409
+ "this argument can be set to either the name of the model in the catalog "
410
+ "or the path to the model configuration."
411
+ ),
412
+ )
413
+ parser.add_argument(
414
+ "--src_vocab",
415
+ help="Path to the source vocabulary (required if no configuration is set).",
416
+ )
417
+ parser.add_argument(
418
+ "--tgt_vocab",
419
+ help="Path to the target vocabulary (required if no configuration is set).",
420
+ )
421
+ Converter.declare_arguments(parser)
422
+ args = parser.parse_args()
423
+
424
+ config = args.config
425
+ if not config:
426
+ if not args.model_path or not args.src_vocab or not args.tgt_vocab:
427
+ raise ValueError(
428
+ "Options --model_path, --src_vocab, --tgt_vocab are required "
429
+ "when a configuration is not set"
430
+ )
431
+
432
+ model_dir = (
433
+ args.model_path
434
+ if os.path.isdir(args.model_path)
435
+ else os.path.dirname(args.model_path)
436
+ )
437
+ config = {
438
+ "model_dir": model_dir,
439
+ "data": {
440
+ "source_vocabulary": args.src_vocab,
441
+ "target_vocabulary": args.tgt_vocab,
442
+ },
443
+ }
444
+
445
+ converter = OpenNMTTFConverter.from_config(
446
+ config,
447
+ auto_config=args.auto_config,
448
+ checkpoint_path=args.model_path,
449
+ model=args.model_type,
450
+ )
451
+ converter.convert_from_args(args)
452
+
453
+
454
+ if __name__ == "__main__":
455
+ main()
@@ -0,0 +1,44 @@
1
+ import argparse
2
+ import os
3
+
4
+ import yaml
5
+
6
+ from ctranslate2.converters.marian import MarianConverter
7
+
8
+
9
+ class OpusMTConverter(MarianConverter):
10
+ """Converts models trained with OPUS-MT."""
11
+
12
+ def __init__(self, model_dir: str):
13
+ """Initializes the OPUS-MT converter.
14
+
15
+ Arguments:
16
+ model_dir: Path the OPUS-MT model directory.
17
+ """
18
+ with open(
19
+ os.path.join(model_dir, "decoder.yml"), encoding="utf-8"
20
+ ) as decoder_file:
21
+ decoder_config = yaml.safe_load(decoder_file)
22
+
23
+ model_path = os.path.join(model_dir, decoder_config["models"][0])
24
+ vocab_paths = [
25
+ os.path.join(model_dir, path) for path in decoder_config["vocabs"]
26
+ ]
27
+ super().__init__(model_path, vocab_paths)
28
+
29
+
30
+ def main():
31
+ parser = argparse.ArgumentParser(
32
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter
33
+ )
34
+ parser.add_argument(
35
+ "--model_dir", required=True, help="Path to the OPUS-MT model directory."
36
+ )
37
+ OpusMTConverter.declare_arguments(parser)
38
+ args = parser.parse_args()
39
+ converter = OpusMTConverter(args.model_dir)
40
+ converter.convert_from_args(args)
41
+
42
+
43
+ if __name__ == "__main__":
44
+ main()