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.
- ctranslate2/.dylibs/libctranslate2.4.7.0.dylib +0 -0
- ctranslate2/__init__.py +66 -0
- ctranslate2/_ext.cpython-314-darwin.so +0 -0
- ctranslate2/converters/__init__.py +8 -0
- ctranslate2/converters/converter.py +109 -0
- ctranslate2/converters/eole_ct2.py +353 -0
- ctranslate2/converters/fairseq.py +347 -0
- ctranslate2/converters/marian.py +315 -0
- ctranslate2/converters/openai_gpt2.py +95 -0
- ctranslate2/converters/opennmt_py.py +361 -0
- ctranslate2/converters/opennmt_tf.py +455 -0
- ctranslate2/converters/opus_mt.py +44 -0
- ctranslate2/converters/transformers.py +3721 -0
- ctranslate2/converters/utils.py +127 -0
- ctranslate2/extensions.py +589 -0
- ctranslate2/logging.py +45 -0
- ctranslate2/models/__init__.py +18 -0
- ctranslate2/specs/__init__.py +18 -0
- ctranslate2/specs/attention_spec.py +98 -0
- ctranslate2/specs/common_spec.py +66 -0
- ctranslate2/specs/model_spec.py +767 -0
- ctranslate2/specs/transformer_spec.py +797 -0
- ctranslate2/specs/wav2vec2_spec.py +72 -0
- ctranslate2/specs/wav2vec2bert_spec.py +97 -0
- ctranslate2/specs/whisper_spec.py +77 -0
- ctranslate2/version.py +3 -0
- ctranslate2-4.7.0.dist-info/METADATA +180 -0
- ctranslate2-4.7.0.dist-info/RECORD +31 -0
- ctranslate2-4.7.0.dist-info/WHEEL +6 -0
- ctranslate2-4.7.0.dist-info/entry_points.txt +8 -0
- ctranslate2-4.7.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,767 @@
|
|
|
1
|
+
"""Specifications declare the expected variables layout of CTranslate2 models
|
|
2
|
+
that do not load a computation graph. The model converter should make sure that
|
|
3
|
+
each required variable of the specification is set.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import abc
|
|
7
|
+
import ctypes
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import shutil
|
|
11
|
+
import struct
|
|
12
|
+
|
|
13
|
+
from typing import Dict, List, Optional
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
import torch
|
|
19
|
+
|
|
20
|
+
torch_is_available = True
|
|
21
|
+
except ImportError:
|
|
22
|
+
torch_is_available = False
|
|
23
|
+
|
|
24
|
+
OPTIONAL = "__optional"
|
|
25
|
+
CURRENT_BINARY_VERSION = 6
|
|
26
|
+
|
|
27
|
+
ACCEPTED_MODEL_TYPES = (
|
|
28
|
+
"int8",
|
|
29
|
+
"int8_float32",
|
|
30
|
+
"int8_float16",
|
|
31
|
+
"int8_bfloat16",
|
|
32
|
+
"int16",
|
|
33
|
+
"float16",
|
|
34
|
+
"bfloat16",
|
|
35
|
+
"float32",
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
SKIP_CREATING_ALIAS = ("rotary_scaling_long_factor", "rotary_scaling_short_factor")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _join_scope(scope, name):
|
|
42
|
+
if not scope:
|
|
43
|
+
return name
|
|
44
|
+
return "%s/%s" % (scope, name)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _split_scope(scope):
|
|
48
|
+
return scope.split("/")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _parent_scope(scope):
|
|
52
|
+
keys = _split_scope(scope)
|
|
53
|
+
scope, attr = keys[:-1], keys[-1]
|
|
54
|
+
return "/".join(scope), attr
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def visit_spec(spec, fn, scope=""):
|
|
58
|
+
"""Recursively visits a layer spec."""
|
|
59
|
+
for name, value in list(spec.__dict__.items()):
|
|
60
|
+
if name.startswith("_"):
|
|
61
|
+
continue
|
|
62
|
+
if isinstance(value, list):
|
|
63
|
+
for i, elem in enumerate(value):
|
|
64
|
+
visit_spec(elem, fn, scope=_join_scope(scope, "%s_%d" % (name, i)))
|
|
65
|
+
elif isinstance(value, LayerSpec):
|
|
66
|
+
visit_spec(value, fn, scope=_join_scope(scope, name))
|
|
67
|
+
else:
|
|
68
|
+
fn(spec, _join_scope(scope, name), value)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def index_spec(spec, index):
|
|
72
|
+
if not index:
|
|
73
|
+
return spec
|
|
74
|
+
keys = _split_scope(index)
|
|
75
|
+
for key in keys:
|
|
76
|
+
try:
|
|
77
|
+
spec = getattr(spec, key)
|
|
78
|
+
except AttributeError:
|
|
79
|
+
attr, index = key.rsplit("_", 1)
|
|
80
|
+
spec = getattr(spec, attr)[int(index)]
|
|
81
|
+
return spec
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class FrozenMeta(type):
|
|
85
|
+
def __call__(self, *args, **kwargs):
|
|
86
|
+
instance = super().__call__(*args, **kwargs)
|
|
87
|
+
instance._frozen = True
|
|
88
|
+
return instance
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class FrozenAttr:
|
|
92
|
+
def __setattr__(self, key, value):
|
|
93
|
+
if hasattr(self, "_frozen") and not hasattr(self, key):
|
|
94
|
+
raise AttributeError("Attribute %s does not exist" % key)
|
|
95
|
+
super().__setattr__(key, value)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class LayerSpec(FrozenAttr, metaclass=FrozenMeta):
|
|
99
|
+
"""A layer specification declares the weights that should be set by the converters."""
|
|
100
|
+
|
|
101
|
+
def validate(self) -> None:
|
|
102
|
+
"""Verify that the required weights are set.
|
|
103
|
+
|
|
104
|
+
Raises:
|
|
105
|
+
ValueError: If a required weight is not set in the specification.
|
|
106
|
+
"""
|
|
107
|
+
unset_attributes = []
|
|
108
|
+
|
|
109
|
+
def _check(spec, name, value):
|
|
110
|
+
if value is None:
|
|
111
|
+
unset_attributes.append(name)
|
|
112
|
+
return
|
|
113
|
+
|
|
114
|
+
if isinstance(value, np.ndarray):
|
|
115
|
+
# float64 is not a supported type.
|
|
116
|
+
if value.dtype == np.float64:
|
|
117
|
+
value = value.astype(np.float32)
|
|
118
|
+
elif isinstance(value, float):
|
|
119
|
+
value = np.dtype("float32").type(value)
|
|
120
|
+
elif isinstance(value, bool):
|
|
121
|
+
# Convert bool to an integer type.
|
|
122
|
+
value = np.dtype("int8").type(value)
|
|
123
|
+
elif isinstance(value, str):
|
|
124
|
+
if value != OPTIONAL:
|
|
125
|
+
value = np.frombuffer(value.encode("utf-8"), dtype=np.int8)
|
|
126
|
+
|
|
127
|
+
if isinstance(value, np.ndarray) or isinstance(value, np.generic):
|
|
128
|
+
value = NumpyVariable(value)
|
|
129
|
+
elif torch_is_available and isinstance(value, torch.Tensor):
|
|
130
|
+
value = PyTorchVariable(value)
|
|
131
|
+
|
|
132
|
+
attr_name = _split_scope(name)[-1]
|
|
133
|
+
setattr(spec, attr_name, value)
|
|
134
|
+
|
|
135
|
+
self._visit(_check)
|
|
136
|
+
|
|
137
|
+
if unset_attributes:
|
|
138
|
+
raise ValueError(
|
|
139
|
+
"Some required model attributes are not set:\n\n%s"
|
|
140
|
+
% "\n".join(unset_attributes)
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
def variables(
|
|
144
|
+
self,
|
|
145
|
+
prefix: str = "",
|
|
146
|
+
ordered: bool = False,
|
|
147
|
+
) -> Dict[str, np.ndarray]:
|
|
148
|
+
"""Recursively returns the weights from this layer and its children.
|
|
149
|
+
|
|
150
|
+
Arguments:
|
|
151
|
+
prefix: Prefix to prepend to all variable names.
|
|
152
|
+
ordered: If set, an ordered list is returned instead.
|
|
153
|
+
|
|
154
|
+
Returns:
|
|
155
|
+
Dictionary mapping variables name to value.
|
|
156
|
+
"""
|
|
157
|
+
var = {}
|
|
158
|
+
|
|
159
|
+
def _register_var(spec, name, value):
|
|
160
|
+
if isinstance(value, str) and value == OPTIONAL:
|
|
161
|
+
return
|
|
162
|
+
var[_join_scope(prefix, name)] = value
|
|
163
|
+
|
|
164
|
+
self._visit(_register_var)
|
|
165
|
+
if ordered:
|
|
166
|
+
return list(sorted(var.items(), key=lambda x: x[0]))
|
|
167
|
+
return var
|
|
168
|
+
|
|
169
|
+
def _alias_variables(self):
|
|
170
|
+
"""Find duplicate variables in spec and create aliases."""
|
|
171
|
+
# When a variable is duplicated, keep the version that comes first in
|
|
172
|
+
# the alphabetical order and alias the others.
|
|
173
|
+
variables = self.variables(ordered=True)
|
|
174
|
+
for name, value in reversed(variables):
|
|
175
|
+
for other_name, other_value in variables:
|
|
176
|
+
if name == other_name:
|
|
177
|
+
break
|
|
178
|
+
# Because variables can be transformed on load (e.g. transposed),
|
|
179
|
+
# we use an element-wise equality check.
|
|
180
|
+
scope, attr_name = _parent_scope(name)
|
|
181
|
+
if (
|
|
182
|
+
not value.is_scalar()
|
|
183
|
+
and value.equal(other_value)
|
|
184
|
+
and attr_name not in SKIP_CREATING_ALIAS
|
|
185
|
+
):
|
|
186
|
+
# Replace variable value by the alias name.
|
|
187
|
+
spec = index_spec(self, scope)
|
|
188
|
+
setattr(spec, attr_name, other_name)
|
|
189
|
+
break
|
|
190
|
+
|
|
191
|
+
def _quantize(self, quantization):
|
|
192
|
+
"""Possibly quantizes the variable of the layer."""
|
|
193
|
+
if quantization is not None and quantization not in ACCEPTED_MODEL_TYPES:
|
|
194
|
+
raise ValueError(
|
|
195
|
+
"%s is not a valid quantization type. Accepted types are: %s"
|
|
196
|
+
% (quantization, ", ".join(ACCEPTED_MODEL_TYPES))
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
def _quantize(spec, name, value):
|
|
200
|
+
if not isinstance(value, Variable) or value.is_scalar():
|
|
201
|
+
return
|
|
202
|
+
|
|
203
|
+
key = _split_scope(name)[-1]
|
|
204
|
+
scale = None
|
|
205
|
+
is_quantizable = hasattr(spec, "%s_scale" % key)
|
|
206
|
+
is_convertible = value.dtype in ("float32", "float16", "bfloat16")
|
|
207
|
+
|
|
208
|
+
if is_quantizable:
|
|
209
|
+
if quantization == "int16":
|
|
210
|
+
value = value.to("float32").numpy()
|
|
211
|
+
# Represent the value with 10 bits so the multiplication is 20 bits
|
|
212
|
+
# and 12 bits are left for accumulation.
|
|
213
|
+
scale = np.float32(2**10 / np.amax(np.absolute(value)))
|
|
214
|
+
value *= scale
|
|
215
|
+
value = np.rint(value)
|
|
216
|
+
value = np.clip(
|
|
217
|
+
value, np.iinfo(np.int16).min, np.iinfo(np.int16).max
|
|
218
|
+
)
|
|
219
|
+
value = value.astype(np.int16)
|
|
220
|
+
scale = NumpyVariable(scale)
|
|
221
|
+
value = NumpyVariable(value)
|
|
222
|
+
elif quantization in (
|
|
223
|
+
"int8",
|
|
224
|
+
"int8_float32",
|
|
225
|
+
"int8_float16",
|
|
226
|
+
"int8_bfloat16",
|
|
227
|
+
):
|
|
228
|
+
value = value.to("float32").numpy()
|
|
229
|
+
# For conv1d layer we need to reshape to 2D before calculating scale
|
|
230
|
+
old_shape = None
|
|
231
|
+
if len(value.shape) == 3:
|
|
232
|
+
old_shape = value.shape
|
|
233
|
+
value = value.reshape(value.shape[0], -1)
|
|
234
|
+
amax = np.amax(np.absolute(value), axis=1)
|
|
235
|
+
amax[amax == 0] = 127.0
|
|
236
|
+
scale = 127.0 / amax
|
|
237
|
+
value *= np.expand_dims(scale, 1)
|
|
238
|
+
value = np.rint(value)
|
|
239
|
+
value = value.astype(np.int8)
|
|
240
|
+
# reshape back to old shape
|
|
241
|
+
if old_shape:
|
|
242
|
+
value = value.reshape(old_shape)
|
|
243
|
+
scale = NumpyVariable(scale)
|
|
244
|
+
value = NumpyVariable(value)
|
|
245
|
+
elif quantization in ("float16", "bfloat16", "float32"):
|
|
246
|
+
value = value.to(quantization)
|
|
247
|
+
|
|
248
|
+
elif is_convertible:
|
|
249
|
+
if quantization in ("float16", "int8_float16"):
|
|
250
|
+
value = value.to("float16")
|
|
251
|
+
elif quantization in ("bfloat16", "int8_bfloat16"):
|
|
252
|
+
value = value.to("bfloat16")
|
|
253
|
+
elif quantization in ("float32", "int16", "int8_float32"):
|
|
254
|
+
value = value.to("float32")
|
|
255
|
+
|
|
256
|
+
setattr(spec, key, value)
|
|
257
|
+
if scale is not None:
|
|
258
|
+
setattr(spec, "%s_scale" % key, scale)
|
|
259
|
+
|
|
260
|
+
self._visit(_quantize)
|
|
261
|
+
|
|
262
|
+
def optimize(self, quantization: Optional[str] = None) -> None:
|
|
263
|
+
"""Recursively applies some optimizations to this layer:
|
|
264
|
+
|
|
265
|
+
* Alias variables with the same shape and value.
|
|
266
|
+
* Quantize weights.
|
|
267
|
+
|
|
268
|
+
Arguments:
|
|
269
|
+
quantization: Weight quantization scheme (possible values are: int8, int8_float32,
|
|
270
|
+
int8_float16, int8_bfloat16, int16, float16, bfloat16, float32).
|
|
271
|
+
"""
|
|
272
|
+
self._alias_variables()
|
|
273
|
+
self._quantize(quantization)
|
|
274
|
+
|
|
275
|
+
def _visit(self, fn):
|
|
276
|
+
"""Recursively visits this layer and its children."""
|
|
277
|
+
visit_spec(self, fn)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _dtype_to_type_id(object_dtype):
|
|
281
|
+
# Order should match the DataType enum in include/ctranslate2/types.h
|
|
282
|
+
dtypes = ("float32", "int8", "int16", "int32", "float16", "bfloat16")
|
|
283
|
+
try:
|
|
284
|
+
return dtypes.index(object_dtype)
|
|
285
|
+
except ValueError:
|
|
286
|
+
raise ValueError(
|
|
287
|
+
"%s is not in list of supported dtypes: %s"
|
|
288
|
+
% (object_dtype, ", ".join(dtypes))
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
class ModelConfig(FrozenAttr, metaclass=FrozenMeta):
|
|
293
|
+
"""Base class for model configurations."""
|
|
294
|
+
|
|
295
|
+
def __init__(self, **kwargs):
|
|
296
|
+
"""Initializes the configuration with a set of parameters."""
|
|
297
|
+
for key, value in kwargs.items():
|
|
298
|
+
setattr(self, key, value)
|
|
299
|
+
|
|
300
|
+
def to_dict(self):
|
|
301
|
+
"""Returns the configuration as a dictionary."""
|
|
302
|
+
return {
|
|
303
|
+
key: value
|
|
304
|
+
for key, value in self.__dict__.items()
|
|
305
|
+
if not key.startswith("_")
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
def add_attribute(self, key, value):
|
|
309
|
+
self.__dict__[key] = value
|
|
310
|
+
|
|
311
|
+
def save_as_json(self, path):
|
|
312
|
+
"""Saves the configuration as a JSON file."""
|
|
313
|
+
with open(path, "w", encoding="utf-8") as config_file:
|
|
314
|
+
json.dump(
|
|
315
|
+
self.to_dict(),
|
|
316
|
+
config_file,
|
|
317
|
+
indent=2,
|
|
318
|
+
sort_keys=True,
|
|
319
|
+
)
|
|
320
|
+
config_file.write("\n")
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
class ModelSpec(LayerSpec):
|
|
324
|
+
"""The top level layer specification."""
|
|
325
|
+
|
|
326
|
+
def __init__(self):
|
|
327
|
+
"""Initializes the model specification."""
|
|
328
|
+
self._config = self.get_default_config()
|
|
329
|
+
self._files = {}
|
|
330
|
+
|
|
331
|
+
@property
|
|
332
|
+
def name(self):
|
|
333
|
+
"""The name of the model specification."""
|
|
334
|
+
raise NotImplementedError()
|
|
335
|
+
|
|
336
|
+
@property
|
|
337
|
+
def revision(self):
|
|
338
|
+
"""The model specification revision.
|
|
339
|
+
|
|
340
|
+
This value is incremented each time the weights layout of the model is
|
|
341
|
+
changed (e.g. a weight is renamed).
|
|
342
|
+
"""
|
|
343
|
+
return 1
|
|
344
|
+
|
|
345
|
+
@property
|
|
346
|
+
def config(self):
|
|
347
|
+
"""The model configuration."""
|
|
348
|
+
return self._config
|
|
349
|
+
|
|
350
|
+
def get_default_config(self):
|
|
351
|
+
"""Returns the default configuration used by this model."""
|
|
352
|
+
return None
|
|
353
|
+
|
|
354
|
+
def register_file(self, path: str, filename: Optional[str] = None) -> None:
|
|
355
|
+
"""Registers a file to be saved in the model directory."""
|
|
356
|
+
if not os.path.isfile(path):
|
|
357
|
+
raise ValueError("File %s does not exist" % path)
|
|
358
|
+
if filename is None:
|
|
359
|
+
filename = os.path.basename(path)
|
|
360
|
+
if filename in self._files:
|
|
361
|
+
raise ValueError("A file with name %s was already registered" % filename)
|
|
362
|
+
self._files[filename] = path
|
|
363
|
+
|
|
364
|
+
def save(self, output_dir: str) -> None:
|
|
365
|
+
"""Saves this model on disk.
|
|
366
|
+
|
|
367
|
+
Arguments:
|
|
368
|
+
output_dir: Output directory where the model is saved.
|
|
369
|
+
"""
|
|
370
|
+
self._serialize(os.path.join(output_dir, "model.bin"))
|
|
371
|
+
if self._config is not None:
|
|
372
|
+
self._config.save_as_json(os.path.join(output_dir, "config.json"))
|
|
373
|
+
|
|
374
|
+
for filename, path in self._files.items():
|
|
375
|
+
destination = os.path.join(output_dir, filename)
|
|
376
|
+
if os.path.exists(destination):
|
|
377
|
+
raise RuntimeError(
|
|
378
|
+
"File %s already exists in the model directory" % destination
|
|
379
|
+
)
|
|
380
|
+
shutil.copy(path, destination)
|
|
381
|
+
|
|
382
|
+
def _serialize(self, path):
|
|
383
|
+
"""Serializes the model variables."""
|
|
384
|
+
variables = []
|
|
385
|
+
aliases = []
|
|
386
|
+
for variable in self.variables(ordered=True):
|
|
387
|
+
if isinstance(variable[1], str):
|
|
388
|
+
aliases.append(variable)
|
|
389
|
+
else:
|
|
390
|
+
variables.append(variable)
|
|
391
|
+
|
|
392
|
+
with open(path, "wb") as model:
|
|
393
|
+
|
|
394
|
+
def _write_string(string):
|
|
395
|
+
model.write(struct.pack("H", len(string) + 1))
|
|
396
|
+
model.write(string.encode("utf-8"))
|
|
397
|
+
model.write(struct.pack("B", 0))
|
|
398
|
+
|
|
399
|
+
model.write(struct.pack("I", CURRENT_BINARY_VERSION))
|
|
400
|
+
_write_string(self.name)
|
|
401
|
+
model.write(struct.pack("I", self.revision))
|
|
402
|
+
model.write(struct.pack("I", len(variables)))
|
|
403
|
+
for name, value in variables:
|
|
404
|
+
_write_string(name)
|
|
405
|
+
model.write(struct.pack("B", len(value.shape)))
|
|
406
|
+
for dim in value.shape:
|
|
407
|
+
model.write(struct.pack("I", dim))
|
|
408
|
+
model.write(struct.pack("B", _dtype_to_type_id(value.dtype)))
|
|
409
|
+
model.write(struct.pack("I", value.num_bytes()))
|
|
410
|
+
model.write(value.to_bytes())
|
|
411
|
+
model.write(struct.pack("I", len(aliases)))
|
|
412
|
+
for alias, variable_name in aliases:
|
|
413
|
+
_write_string(alias)
|
|
414
|
+
_write_string(variable_name)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _flatten_vocabularies(vocabularies):
|
|
418
|
+
for name, vocabulary in vocabularies.items():
|
|
419
|
+
if len(vocabulary) == 1:
|
|
420
|
+
yield name, vocabulary[0]
|
|
421
|
+
else:
|
|
422
|
+
for i, vocab in enumerate(vocabulary):
|
|
423
|
+
yield "%s_%d" % (name, i + 1), vocab
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
class SequenceToSequenceModelConfig(ModelConfig):
|
|
427
|
+
"""Configuration for sequence-to-sequence models."""
|
|
428
|
+
|
|
429
|
+
def __init__(
|
|
430
|
+
self,
|
|
431
|
+
unk_token: str = "<unk>",
|
|
432
|
+
bos_token: str = "<s>",
|
|
433
|
+
eos_token: str = "</s>",
|
|
434
|
+
decoder_start_token: Optional[str] = "<s>",
|
|
435
|
+
add_source_bos: bool = False,
|
|
436
|
+
add_source_eos: bool = False,
|
|
437
|
+
**kwargs,
|
|
438
|
+
):
|
|
439
|
+
"""Initializes the configuration for sequence-to-sequence models.
|
|
440
|
+
|
|
441
|
+
Args:
|
|
442
|
+
unk_token: The unknown token.
|
|
443
|
+
bos_token: The start of sentence token.
|
|
444
|
+
eos_token: The end of sentence token.
|
|
445
|
+
decoder_start_token: The decoder start token. If ``None``, the token should
|
|
446
|
+
be passed by the user in the target prefix.
|
|
447
|
+
add_source_bos: If ``True``, ``bos_token`` will be automatically added to
|
|
448
|
+
the source input.
|
|
449
|
+
add_source_eos: If ``True``, ``eos_token`` will be automatically added to
|
|
450
|
+
the source input.
|
|
451
|
+
**kwargs: Additional configuration.
|
|
452
|
+
"""
|
|
453
|
+
super().__init__(
|
|
454
|
+
unk_token=unk_token,
|
|
455
|
+
bos_token=bos_token,
|
|
456
|
+
eos_token=eos_token,
|
|
457
|
+
decoder_start_token=decoder_start_token,
|
|
458
|
+
add_source_bos=add_source_bos,
|
|
459
|
+
add_source_eos=add_source_eos,
|
|
460
|
+
**kwargs,
|
|
461
|
+
)
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
class SequenceToSequenceModelSpec(ModelSpec):
|
|
465
|
+
"""Base specification for sequence to sequence models."""
|
|
466
|
+
|
|
467
|
+
def __init__(self):
|
|
468
|
+
"""Initializes a sequence to sequence model specification."""
|
|
469
|
+
super().__init__()
|
|
470
|
+
self._vocabularies = {
|
|
471
|
+
"source": [],
|
|
472
|
+
"target": [],
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
def get_default_config(self):
|
|
476
|
+
return SequenceToSequenceModelConfig()
|
|
477
|
+
|
|
478
|
+
@abc.abstractmethod
|
|
479
|
+
def get_source_vocabulary_size(self):
|
|
480
|
+
"""Returns the source vocabulary size expected by the model."""
|
|
481
|
+
raise NotImplementedError()
|
|
482
|
+
|
|
483
|
+
@abc.abstractmethod
|
|
484
|
+
def get_target_vocabulary_size(self):
|
|
485
|
+
"""Returns the target vocabulary size expected by the model."""
|
|
486
|
+
raise NotImplementedError()
|
|
487
|
+
|
|
488
|
+
def register_source_vocabulary(self, tokens: List[str]) -> None:
|
|
489
|
+
"""Registers a source vocabulary of tokens.
|
|
490
|
+
|
|
491
|
+
Arguments:
|
|
492
|
+
tokens: List of source tokens.
|
|
493
|
+
"""
|
|
494
|
+
self._vocabularies["source"].append(tokens)
|
|
495
|
+
|
|
496
|
+
def register_target_vocabulary(self, tokens: List[str]) -> None:
|
|
497
|
+
"""Registers a target vocabulary of tokens.
|
|
498
|
+
|
|
499
|
+
Arguments:
|
|
500
|
+
tokens: List of target tokens.
|
|
501
|
+
"""
|
|
502
|
+
self._vocabularies["target"].append(tokens)
|
|
503
|
+
|
|
504
|
+
def register_vocabulary_mapping(self, path: str) -> None:
|
|
505
|
+
"""Registers a vocabulary mapping file.
|
|
506
|
+
|
|
507
|
+
Arguments:
|
|
508
|
+
path: Path to the vocabulary mapping file.
|
|
509
|
+
"""
|
|
510
|
+
self.register_file(path, "vmap.txt")
|
|
511
|
+
|
|
512
|
+
def validate(self) -> None:
|
|
513
|
+
super().validate()
|
|
514
|
+
|
|
515
|
+
# Check that vocabularies are registered and have the correct size.
|
|
516
|
+
vocabulary_sizes = {
|
|
517
|
+
"source": self.get_source_vocabulary_size(),
|
|
518
|
+
"target": self.get_target_vocabulary_size(),
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
for name, sizes in vocabulary_sizes.items():
|
|
522
|
+
if not isinstance(sizes, list):
|
|
523
|
+
sizes = [sizes]
|
|
524
|
+
vocabularies = self._vocabularies[name]
|
|
525
|
+
if len(vocabularies) != len(sizes):
|
|
526
|
+
raise ValueError(
|
|
527
|
+
"Incorrect number of %s vocabularies: %d registered, but expected %d"
|
|
528
|
+
% (name, len(vocabularies), len(sizes))
|
|
529
|
+
)
|
|
530
|
+
for i, (vocabulary, expected_size) in enumerate(zip(vocabularies, sizes)):
|
|
531
|
+
if len(vocabulary) != expected_size:
|
|
532
|
+
raise ValueError(
|
|
533
|
+
"%s vocabulary %d has size %d but the model expected a vocabulary "
|
|
534
|
+
"of size %d"
|
|
535
|
+
% (name.capitalize(), i, len(vocabulary), expected_size)
|
|
536
|
+
)
|
|
537
|
+
|
|
538
|
+
def save(self, output_dir: str) -> None:
|
|
539
|
+
# Save the vocabularies.
|
|
540
|
+
vocabularies = dict(_flatten_vocabularies(self._vocabularies))
|
|
541
|
+
all_vocabularies = list(vocabularies.values())
|
|
542
|
+
if all(vocabulary == all_vocabularies[0] for vocabulary in all_vocabularies):
|
|
543
|
+
vocabularies = {"shared": all_vocabularies[0]}
|
|
544
|
+
|
|
545
|
+
for name, tokens in vocabularies.items():
|
|
546
|
+
_save_vocabulary(output_dir, "%s_vocabulary" % name, tokens)
|
|
547
|
+
|
|
548
|
+
# Save the rest of the model.
|
|
549
|
+
super().save(output_dir)
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
class LanguageModelConfig(ModelConfig):
|
|
553
|
+
"""Configuration for language models."""
|
|
554
|
+
|
|
555
|
+
def __init__(
|
|
556
|
+
self,
|
|
557
|
+
unk_token: str = "<unk>",
|
|
558
|
+
bos_token: str = "<s>",
|
|
559
|
+
eos_token: str = "</s>",
|
|
560
|
+
**kwargs,
|
|
561
|
+
):
|
|
562
|
+
"""Initializes the configuration for language models.
|
|
563
|
+
|
|
564
|
+
Args:
|
|
565
|
+
unk_token: The unknown token.
|
|
566
|
+
bos_token: The start of sentence token.
|
|
567
|
+
eos_token: The end of sentence token.
|
|
568
|
+
**kwargs: Additional configuration.
|
|
569
|
+
"""
|
|
570
|
+
super().__init__(
|
|
571
|
+
unk_token=unk_token,
|
|
572
|
+
bos_token=bos_token,
|
|
573
|
+
eos_token=eos_token,
|
|
574
|
+
**kwargs,
|
|
575
|
+
)
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
class LanguageModelSpec(ModelSpec):
|
|
579
|
+
"""Base specification for language models."""
|
|
580
|
+
|
|
581
|
+
def __init__(self):
|
|
582
|
+
"""Initializes a language model specification."""
|
|
583
|
+
super().__init__()
|
|
584
|
+
self._vocabulary = []
|
|
585
|
+
|
|
586
|
+
def get_default_config(self):
|
|
587
|
+
return LanguageModelConfig()
|
|
588
|
+
|
|
589
|
+
@abc.abstractmethod
|
|
590
|
+
def get_vocabulary_size(self):
|
|
591
|
+
"""Returns the vocabulary size expected by the model."""
|
|
592
|
+
raise NotImplementedError()
|
|
593
|
+
|
|
594
|
+
def register_vocabulary(self, tokens: List[str]) -> None:
|
|
595
|
+
"""Registers the vocabulary of tokens.
|
|
596
|
+
|
|
597
|
+
Arguments:
|
|
598
|
+
tokens: List of tokens.
|
|
599
|
+
"""
|
|
600
|
+
self._vocabulary = list(tokens)
|
|
601
|
+
|
|
602
|
+
def validate(self) -> None:
|
|
603
|
+
super().validate()
|
|
604
|
+
|
|
605
|
+
expected_vocabulary_size = self.get_vocabulary_size()
|
|
606
|
+
if len(self._vocabulary) != expected_vocabulary_size:
|
|
607
|
+
raise ValueError(
|
|
608
|
+
"Vocabulary has size %d but the model expected a vocabulary of size %d"
|
|
609
|
+
% (len(self._vocabulary), expected_vocabulary_size)
|
|
610
|
+
)
|
|
611
|
+
|
|
612
|
+
def save(self, output_dir: str) -> None:
|
|
613
|
+
# Save the vocabulary.
|
|
614
|
+
_save_vocabulary(output_dir, "vocabulary", self._vocabulary)
|
|
615
|
+
|
|
616
|
+
# Save the rest of the model.
|
|
617
|
+
super().save(output_dir)
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def _save_vocabulary(output_dir, name, tokens):
|
|
621
|
+
vocabulary_path = os.path.join(output_dir, "%s.json" % name)
|
|
622
|
+
|
|
623
|
+
with open(vocabulary_path, "w", encoding="utf-8") as vocabulary_file:
|
|
624
|
+
json.dump(tokens, vocabulary_file, indent=2)
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
class Variable(abc.ABC):
|
|
628
|
+
"""Abstract base class for model variables."""
|
|
629
|
+
|
|
630
|
+
@property
|
|
631
|
+
@abc.abstractmethod
|
|
632
|
+
def shape(self) -> List[int]:
|
|
633
|
+
raise NotImplementedError()
|
|
634
|
+
|
|
635
|
+
def is_scalar(self) -> bool:
|
|
636
|
+
return len(self.shape) == 0
|
|
637
|
+
|
|
638
|
+
@property
|
|
639
|
+
@abc.abstractmethod
|
|
640
|
+
def dtype(self) -> str:
|
|
641
|
+
raise NotImplementedError()
|
|
642
|
+
|
|
643
|
+
def to(self, dtype: str) -> "Variable":
|
|
644
|
+
if dtype == self.dtype:
|
|
645
|
+
return self
|
|
646
|
+
return self._to(dtype)
|
|
647
|
+
|
|
648
|
+
@abc.abstractmethod
|
|
649
|
+
def numpy(self) -> np.ndarray:
|
|
650
|
+
raise NotImplementedError()
|
|
651
|
+
|
|
652
|
+
def equal(self, other) -> bool:
|
|
653
|
+
return type(self) is type(other) and self._equal(other)
|
|
654
|
+
|
|
655
|
+
@abc.abstractmethod
|
|
656
|
+
def num_bytes(self) -> int:
|
|
657
|
+
raise NotImplementedError()
|
|
658
|
+
|
|
659
|
+
@abc.abstractmethod
|
|
660
|
+
def to_bytes(self) -> bytes:
|
|
661
|
+
raise NotImplementedError()
|
|
662
|
+
|
|
663
|
+
@abc.abstractmethod
|
|
664
|
+
def _to(self, dtype: str) -> "Variable":
|
|
665
|
+
raise NotImplementedError()
|
|
666
|
+
|
|
667
|
+
@abc.abstractmethod
|
|
668
|
+
def _equal(self, other) -> bool:
|
|
669
|
+
raise NotImplementedError()
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
class NumpyVariable(Variable):
|
|
673
|
+
"""Model variable as a Numpy array."""
|
|
674
|
+
|
|
675
|
+
def __init__(self, array):
|
|
676
|
+
self.array = array
|
|
677
|
+
|
|
678
|
+
@property
|
|
679
|
+
def shape(self) -> List[int]:
|
|
680
|
+
return self.array.shape
|
|
681
|
+
|
|
682
|
+
@property
|
|
683
|
+
def dtype(self) -> str:
|
|
684
|
+
return self.array.dtype.name
|
|
685
|
+
|
|
686
|
+
def numpy(self) -> np.ndarray:
|
|
687
|
+
return self.array
|
|
688
|
+
|
|
689
|
+
def num_bytes(self) -> int:
|
|
690
|
+
return self.array.nbytes
|
|
691
|
+
|
|
692
|
+
def to_bytes(self) -> bytes:
|
|
693
|
+
return self.array.tobytes()
|
|
694
|
+
|
|
695
|
+
def _to(self, dtype: str) -> Variable:
|
|
696
|
+
if dtype == "bfloat16":
|
|
697
|
+
if not torch_is_available:
|
|
698
|
+
raise RuntimeError(
|
|
699
|
+
"Converting to bfloat16 requires torch to be installed"
|
|
700
|
+
)
|
|
701
|
+
return PyTorchVariable.from_numpy(self.array).to(dtype)
|
|
702
|
+
|
|
703
|
+
dtype = np.dtype(dtype)
|
|
704
|
+
self.array = self.array.astype(dtype)
|
|
705
|
+
return self
|
|
706
|
+
|
|
707
|
+
def _equal(self, other) -> bool:
|
|
708
|
+
a = self.array
|
|
709
|
+
b = other.array
|
|
710
|
+
return a is b or (
|
|
711
|
+
a.dtype == b.dtype
|
|
712
|
+
and a.shape == b.shape
|
|
713
|
+
and a.flat[0] == b.flat[0]
|
|
714
|
+
and np.array_equal(a, b)
|
|
715
|
+
)
|
|
716
|
+
|
|
717
|
+
|
|
718
|
+
class PyTorchVariable(Variable):
|
|
719
|
+
"""Model variable as a PyTorch tensor."""
|
|
720
|
+
|
|
721
|
+
def __init__(self, tensor):
|
|
722
|
+
if isinstance(tensor, torch.nn.Parameter):
|
|
723
|
+
tensor = tensor.data
|
|
724
|
+
|
|
725
|
+
self.tensor = tensor.contiguous()
|
|
726
|
+
|
|
727
|
+
@classmethod
|
|
728
|
+
def from_numpy(cls, array):
|
|
729
|
+
tensor = torch.from_numpy(array)
|
|
730
|
+
return cls(tensor)
|
|
731
|
+
|
|
732
|
+
@property
|
|
733
|
+
def shape(self) -> List[int]:
|
|
734
|
+
return list(self.tensor.shape)
|
|
735
|
+
|
|
736
|
+
@property
|
|
737
|
+
def dtype(self) -> str:
|
|
738
|
+
return str(self.tensor.dtype).replace("torch.", "")
|
|
739
|
+
|
|
740
|
+
def numpy(self) -> np.ndarray:
|
|
741
|
+
return self.tensor.detach().numpy()
|
|
742
|
+
|
|
743
|
+
def num_bytes(self) -> int:
|
|
744
|
+
return self.tensor.numel() * self.tensor.element_size()
|
|
745
|
+
|
|
746
|
+
def to_bytes(self) -> bytes:
|
|
747
|
+
max_size = 2**31 - 1
|
|
748
|
+
num_bytes = self.num_bytes()
|
|
749
|
+
output = b""
|
|
750
|
+
offset = 0
|
|
751
|
+
while num_bytes > 0:
|
|
752
|
+
chunk_size = max_size if num_bytes > max_size else num_bytes
|
|
753
|
+
chunk = ctypes.string_at(self.tensor.data_ptr() + offset, chunk_size)
|
|
754
|
+
output += chunk
|
|
755
|
+
offset += chunk_size
|
|
756
|
+
num_bytes -= chunk_size
|
|
757
|
+
return output
|
|
758
|
+
|
|
759
|
+
def _to(self, dtype: str) -> Variable:
|
|
760
|
+
dtype = getattr(torch, dtype)
|
|
761
|
+
self.tensor = self.tensor.to(dtype)
|
|
762
|
+
return self
|
|
763
|
+
|
|
764
|
+
def _equal(self, other) -> bool:
|
|
765
|
+
a = self.tensor
|
|
766
|
+
b = other.tensor
|
|
767
|
+
return a is b or (a.dtype == b.dtype and torch.equal(a, b))
|