-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
NmtPreprocessBuildJob.cs
449 lines (415 loc) · 16.7 KB
/
NmtPreprocessBuildJob.cs
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
namespace SIL.Machine.AspNetCore.Services;
public class NmtPreprocessBuildJob : HangfireBuildJob<IReadOnlyList<Corpus>>
{
private static readonly JsonWriterOptions PretranslateWriterOptions = new() { Indented = true };
private readonly ISharedFileService _sharedFileService;
private readonly ICorpusService _corpusService;
private readonly ILanguageTagService _languageTagService;
private int _seed = 1234;
private Random _random;
public NmtPreprocessBuildJob(
IPlatformService platformService,
IRepository<TranslationEngine> engines,
IDistributedReaderWriterLockFactory lockFactory,
ILogger<NmtPreprocessBuildJob> logger,
IBuildJobService buildJobService,
ISharedFileService sharedFileService,
ICorpusService corpusService,
ILanguageTagService languageTagService
)
: base(platformService, engines, lockFactory, buildJobService, logger)
{
_sharedFileService = sharedFileService;
_corpusService = corpusService;
_languageTagService = languageTagService;
_random = new Random(_seed);
}
internal int Seed
{
get => _seed;
set
{
if (_seed != value)
{
_seed = value;
_random = new Random(_seed);
}
}
}
protected override async Task DoWorkAsync(
string engineId,
string buildId,
IReadOnlyList<Corpus> data,
string? buildOptions,
IDistributedReaderWriterLock @lock,
CancellationToken cancellationToken
)
{
(int trainCount, int pretranslateCount) = await WriteDataFilesAsync(
buildId,
data,
buildOptions,
cancellationToken
);
// Log summary of build data
JsonObject buildPreprocessSummary =
new()
{
{ "Event", "BuildPreprocess" },
{ "EngineId", engineId },
{ "BuildId", buildId },
{ "NumTrainRows", trainCount },
{ "NumPretranslateRows", pretranslateCount }
};
TranslationEngine? engine = await Engines.GetAsync(e => e.EngineId == engineId, cancellationToken);
if (engine is null)
throw new OperationCanceledException($"Engine {engineId} does not exist. Build canceled.");
bool sourceTagInFlores200 = _languageTagService.ConvertToFlores200Code(
engine.SourceLanguage,
out string srcLang
);
buildPreprocessSummary.Add("SourceLanguageResolved", srcLang);
bool targetTagInFlores200 = _languageTagService.ConvertToFlores200Code(
engine.TargetLanguage,
out string trgLang
);
buildPreprocessSummary.Add("TargetLanguageResolved", trgLang);
Logger.LogInformation("{summary}", buildPreprocessSummary.ToJsonString());
if (trainCount == 0 && (!sourceTagInFlores200 || !targetTagInFlores200))
{
throw new InvalidOperationException(
$"Neither language code in build {buildId} are known to the base model, and the data specified for training was empty. Build canceled."
);
}
await using (await @lock.WriterLockAsync(cancellationToken: cancellationToken))
{
bool canceling = !await BuildJobService.StartBuildJobAsync(
BuildJobType.Gpu,
TranslationEngineType.Nmt,
engineId,
buildId,
NmtBuildStages.Train,
buildOptions: buildOptions,
cancellationToken: cancellationToken
);
if (canceling)
throw new OperationCanceledException();
}
}
private async Task<(int TrainCount, int PretranslateCount)> WriteDataFilesAsync(
string buildId,
IReadOnlyList<Corpus> corpora,
string? buildOptions,
CancellationToken cancellationToken
)
{
JsonObject? buildOptionsObject = null;
if (buildOptions is not null)
{
buildOptionsObject = JsonSerializer.Deserialize<JsonObject>(buildOptions);
}
await using StreamWriter sourceTrainWriter =
new(await _sharedFileService.OpenWriteAsync($"builds/{buildId}/train.src.txt", cancellationToken));
await using StreamWriter targetTrainWriter =
new(await _sharedFileService.OpenWriteAsync($"builds/{buildId}/train.trg.txt", cancellationToken));
await using Stream pretranslateStream = await _sharedFileService.OpenWriteAsync(
$"builds/{buildId}/pretranslate.src.json",
cancellationToken
);
await using Utf8JsonWriter pretranslateWriter = new(pretranslateStream, PretranslateWriterOptions);
int trainCount = 0;
int pretranslateCount = 0;
pretranslateWriter.WriteStartArray();
foreach (Corpus corpus in corpora)
{
ITextCorpus[] sourceTextCorpora = _corpusService.CreateTextCorpora(corpus.SourceFiles).ToArray();
ITextCorpus targetTextCorpus =
_corpusService.CreateTextCorpora(corpus.TargetFiles).FirstOrDefault() ?? new DictionaryTextCorpus();
if (sourceTextCorpora.Length == 0)
continue;
int skipCount = 0;
foreach (Row?[] rows in AlignTrainCorpus(corpus, sourceTextCorpora, targetTextCorpus))
{
if (skipCount > 0)
{
skipCount--;
continue;
}
Row[] trainRows = rows.Where(r => IsIncluded(r, corpus.TrainOnChapters)).Cast<Row>().ToArray();
if (trainRows.Length > 0)
{
Row row = trainRows[0];
if (rows.Length > 1)
{
Row[] nonEmptyRows = trainRows.Where(r => r.SourceSegment.Length > 0).ToArray();
if (nonEmptyRows.Length > 0)
row = nonEmptyRows[_random.Next(nonEmptyRows.Length)];
}
await sourceTrainWriter.WriteAsync($"{row.SourceSegment}\n");
await targetTrainWriter.WriteAsync($"{row.TargetSegment}\n");
skipCount = row.RowCount - 1;
if (row.SourceSegment.Length > 0 && row.TargetSegment.Length > 0)
trainCount++;
}
}
if ((bool?)buildOptionsObject?["use_key_terms"] ?? true)
{
ITextCorpus? sourceTermCorpus = _corpusService.CreateTermCorpora(corpus.SourceFiles).FirstOrDefault();
ITextCorpus? targetTermCorpus = _corpusService.CreateTermCorpora(corpus.TargetFiles).FirstOrDefault();
if (sourceTermCorpus is not null && targetTermCorpus is not null)
{
IParallelTextCorpus parallelKeyTermsCorpus = sourceTermCorpus.AlignRows(targetTermCorpus);
foreach (ParallelTextRow row in parallelKeyTermsCorpus)
{
await sourceTrainWriter.WriteAsync($"{row.SourceText}\n");
await targetTrainWriter.WriteAsync($"{row.TargetText}\n");
trainCount++;
}
}
}
foreach (Row row in AlignPretranslateCorpus(corpus, sourceTextCorpora[0], targetTextCorpus))
{
if (
IsIncluded(row, corpus.PretranslateChapters)
&& row.SourceSegment.Length > 0
&& (row.TargetSegment.Length == 0 || !IsInTrain(row, corpus))
)
{
pretranslateWriter.WriteStartObject();
pretranslateWriter.WriteString("corpusId", corpus.Id);
pretranslateWriter.WriteString("textId", row.TextId);
pretranslateWriter.WriteStartArray("refs");
foreach (object rowRef in row.Refs)
pretranslateWriter.WriteStringValue(rowRef.ToString());
pretranslateWriter.WriteEndArray();
pretranslateWriter.WriteString("translation", row.SourceSegment);
pretranslateWriter.WriteEndObject();
pretranslateCount++;
}
}
}
pretranslateWriter.WriteEndArray();
return (trainCount, pretranslateCount);
}
protected override async Task CleanupAsync(
string engineId,
string buildId,
IReadOnlyList<Corpus> data,
IDistributedReaderWriterLock @lock,
JobCompletionStatus completionStatus
)
{
if (completionStatus is JobCompletionStatus.Canceled)
{
try
{
await _sharedFileService.DeleteAsync($"builds/{buildId}/");
}
catch (Exception e)
{
Logger.LogWarning(e, "Unable to to delete job data for build {BuildId}.", buildId);
}
}
}
private static bool IsInTrain(Row row, Corpus corpus)
{
if (corpus.TrainOnChapters is not null)
{
if (row.Refs.Any(r => IsInChapters(corpus.TrainOnChapters, r)))
return true;
}
return corpus.TrainOnAll || corpus.TrainOnTextIds.Contains(row.TextId);
}
private static bool IsIncluded(Row? row, IReadOnlyDictionary<string, HashSet<int>>? chapters)
{
if (row is null)
return false;
if (chapters is not null)
return row.Refs.Any(r => IsInChapters(chapters, r));
return true;
}
private static bool IsInChapters(IReadOnlyDictionary<string, HashSet<int>> bookChapters, object rowRef)
{
if (rowRef is not ScriptureRef sr)
return false;
return bookChapters.TryGetValue(sr.Book, out HashSet<int>? chapters)
&& (chapters.Contains(sr.ChapterNum) || chapters.Count == 0);
}
private static IEnumerable<Row?[]> AlignTrainCorpus(
Corpus corpus,
IReadOnlyList<ITextCorpus> srcCorpora,
ITextCorpus trgCorpus
)
{
if (!corpus.TrainOnAll)
{
IEnumerable<string> textIds = corpus.TrainOnChapters is not null
? corpus.TrainOnChapters.Keys
: corpus.TrainOnTextIds;
srcCorpora = srcCorpora.Select(sc => sc.FilterTexts(textIds)).ToArray();
trgCorpus = trgCorpus.FilterTexts(textIds);
}
if (trgCorpus.IsScripture())
{
return srcCorpora
.Select(sc => AlignScripture(sc, trgCorpus))
.ZipMany(rows => rows.ToArray())
// filter out every list that only contains completely empty rows
.Where(rows => rows.Any(r => r is null || r.SourceSegment.Length > 0 || r.TargetSegment.Length > 0));
}
IEnumerable<Row[]> sourceOnlyRows = srcCorpora
.Select(sc => sc.AlignRows(trgCorpus, allSourceRows: true))
.ZipMany(rows =>
rows.Where(r => r.TargetSegment.Count == 0)
.Select(r => new Row(r.TextId, r.Refs, r.SourceText, r.TargetText, 1))
.ToArray()
);
IEnumerable<Row[]> targetRows = srcCorpora
.Select(sc => sc.AlignRows(trgCorpus, allTargetRows: true))
.ZipMany(rows =>
rows.Where(r => r.TargetSegment.Count > 0)
.Select(r => new Row(r.TextId, r.Refs, r.SourceText, r.TargetText, 1))
.ToArray()
);
return sourceOnlyRows
.Concat(targetRows)
// filter out every list that only contains completely empty rows
.Where(rows => rows.Any(r => r.SourceSegment.Length > 0 || r.TargetSegment.Length > 0));
}
private static IEnumerable<Row?> AlignScripture(ITextCorpus srcCorpus, ITextCorpus trgCorpus)
{
int rowCount = 0;
StringBuilder srcSegBuffer = new();
StringBuilder trgSegBuffer = new();
HashSet<VerseRef> vrefs = [];
foreach (
(VerseRef vref, string srcSegment, string trgSegment) in srcCorpus
.ExtractScripture()
.Select(r => (r.CorpusVerseRef, r.Text))
.Zip(
trgCorpus.ExtractScripture().Select(r => r.Text),
(s, t) => (VerseRef: s.CorpusVerseRef, SourceSegment: s.Text, TargetSegment: t)
)
)
{
if (srcSegment == "<range>" && trgSegment == "<range>")
{
vrefs.UnionWith(vref.AllVerses());
rowCount++;
}
else if (srcSegment == "<range>")
{
vrefs.UnionWith(vref.AllVerses());
if (trgSegment.Length > 0)
{
if (trgSegBuffer.Length > 0)
trgSegBuffer.Append(' ');
trgSegBuffer.Append(trgSegment);
}
rowCount++;
}
else if (trgSegment == "<range>")
{
vrefs.UnionWith(vref.AllVerses());
if (srcSegment.Length > 0)
{
if (srcSegBuffer.Length > 0)
srcSegBuffer.Append(' ');
srcSegBuffer.Append(srcSegment);
}
rowCount++;
}
else
{
if (rowCount > 0)
{
yield return new(
vrefs.First().Book,
vrefs.Order().Select(v => new ScriptureRef(v)).Cast<object>().ToArray(),
srcSegBuffer.ToString(),
trgSegBuffer.ToString(),
rowCount
);
for (int i = 0; i < rowCount - 1; i++)
yield return null;
srcSegBuffer.Clear();
trgSegBuffer.Clear();
vrefs.Clear();
rowCount = 0;
}
vrefs.UnionWith(vref.AllVerses());
srcSegBuffer.Append(srcSegment);
trgSegBuffer.Append(trgSegment);
rowCount++;
}
}
if (rowCount > 0)
{
yield return new(
vrefs.First().Book,
vrefs.Order().Select(v => new ScriptureRef(v)).Cast<object>().ToArray(),
srcSegBuffer.ToString(),
trgSegBuffer.ToString(),
rowCount
);
for (int i = 0; i < rowCount - 1; i++)
yield return null;
}
}
private static IEnumerable<Row> AlignPretranslateCorpus(Corpus corpus, ITextCorpus srcCorpus, ITextCorpus trgCorpus)
{
if (!corpus.PretranslateAll)
{
IEnumerable<string> textIds = corpus.PretranslateChapters is not null
? corpus.PretranslateChapters.Keys
: corpus.PretranslateTextIds;
srcCorpus = srcCorpus.FilterTexts(textIds);
trgCorpus = trgCorpus.FilterTexts(textIds);
}
int rowCount = 0;
StringBuilder srcSegBuffer = new();
StringBuilder trgSegBuffer = new();
List<object> refs = [];
string textId = "";
foreach (ParallelTextRow row in srcCorpus.AlignRows(trgCorpus, allSourceRows: true))
{
if (!row.IsTargetRangeStart && row.IsTargetInRange)
{
refs.AddRange(row.Refs);
if (row.SourceText.Length > 0)
{
if (srcSegBuffer.Length > 0)
srcSegBuffer.Append(' ');
srcSegBuffer.Append(row.SourceText);
}
rowCount++;
}
else
{
if (rowCount > 0)
{
yield return new(textId, refs, srcSegBuffer.ToString(), trgSegBuffer.ToString(), 1);
textId = "";
srcSegBuffer.Clear();
trgSegBuffer.Clear();
refs.Clear();
rowCount = 0;
}
textId = row.TextId;
refs.AddRange(row.Refs);
srcSegBuffer.Append(row.SourceText);
trgSegBuffer.Append(row.TargetText);
rowCount++;
}
}
if (rowCount > 0)
yield return new(textId, refs, srcSegBuffer.ToString(), trgSegBuffer.ToString(), 1);
}
private record Row(
string TextId,
IReadOnlyList<object> Refs,
string SourceSegment,
string TargetSegment,
int RowCount
);
}