Coverage Report

Created: 2026-08-31 06:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/sentencepiece/build/root/include/sentencepiece_trainer.h
Line
Count
Source
1
// Copyright 2018 Google Inc.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.!
14
15
#ifndef SENTENCEPIECE_TRAINER_H_
16
#define SENTENCEPIECE_TRAINER_H_
17
18
#include <functional>
19
#include <string>
20
#include <unordered_map>
21
#include <utility>
22
#include <vector>
23
24
#include "absl/status/status.h"
25
#include "absl/strings/string_view.h"
26
#include "absl/types/span.h"
27
#include "sentencepiece_processor.h"
28
29
namespace sentencepiece {
30
31
class TrainerSpec;
32
class NormalizerSpec;
33
class ModelProto;
34
35
namespace normalizer {
36
class Normalizer;
37
}  // namespace normalizer
38
39
// Iterator over the training sentences.
40
// Training sentences are loaded sequentially as follows:
41
//
42
// for (; !it.done(); it.Next()) {
43
//    const std::string &s = it.value();
44
// }
45
// ABSL_RETURN_IF_ERROR(it.status());
46
//
47
class SentenceIterator {
48
 public:
49
  virtual ~SentenceIterator() = default;
50
  // Returns true if iteration finishes (including error case).
51
  // Uses SentenceIterator::status() method to know whether
52
  // all sentences are loaded successfully.
53
  [[nodiscard]] virtual bool done() const = 0;
54
  virtual void Next() = 0;
55
  [[nodiscard]] virtual const std::string& value() const = 0;
56
  virtual absl::Status status() const = 0;
57
};
58
59
// Container for C++ objects passed to Trainer.
60
struct TrainerComponents {
61
  SentenceIterator* sentence_iterator = nullptr;
62
  using Pretokenizer =
63
      std::function<std::vector<std::string>(absl::string_view)>;
64
  Pretokenizer pretokenizer = nullptr;
65
  bool allow_inconsistent_pretokenization = false;
66
67
  TrainerComponents();
68
  ~TrainerComponents();
69
  TrainerComponents(const TrainerComponents& other);
70
  TrainerComponents(TrainerComponents&& other) noexcept;
71
  TrainerComponents& operator=(const TrainerComponents& other);
72
  TrainerComponents& operator=(TrainerComponents&& other) noexcept;
73
74
  // Accessors for spec Protobuf messages (Pimpl)
75
  TrainerSpec* mutable_trainer_spec();
76
  const TrainerSpec& trainer_spec() const;
77
78
  NormalizerSpec* mutable_normalizer_spec();
79
  const NormalizerSpec& normalizer_spec() const;
80
81
  NormalizerSpec* mutable_denormalizer_spec();
82
  const NormalizerSpec& denormalizer_spec() const;
83
84
 private:
85
  struct Impl;
86
  std::unique_ptr<Impl> impl_;
87
};
88
89
class SentencePieceTrainer {
90
 public:
91
  // Trains SentencePiece model with `components`.
92
  static absl::Status Train(const TrainerComponents& components,
93
                            std::string* serialized_model_proto = nullptr);
94
95
  // Trains SentencePiece model with command-line string in `args` and
96
  // `components`.
97
  static absl::Status Train(absl::string_view args,
98
                            const TrainerComponents& components,
99
                            std::string* serialized_model_proto = nullptr);
100
101
  // Trains SentencePiece model with `kwargs` map and `components`.
102
  static absl::Status Train(
103
      const std::unordered_map<std::string, std::string>& kwargs,
104
      const TrainerComponents& components,
105
      std::string* serialized_model_proto = nullptr);
106
107
  // Trains SentencePiece model with `trainer_spec`.
108
  // Default `normalizer_spec` is used.
109
  // When `sentence_iterator` is passed, load sentences from the iterator.
110
  [[deprecated("Use Train(const TrainerComponents&, ...) instead.")]]
111
  static absl::Status Train(const TrainerSpec& trainer_spec,
112
                            SentenceIterator* sentence_iterator = nullptr,
113
                            std::string* serialized_model_proto = nullptr);
114
115
  // Trains SentencePiece model with `trainer_spec` and
116
  // `normalizer_spec`.
117
  // When `sentence_iterator` is passed, load sentences from the iterator.
118
  [[deprecated("Use Train(const TrainerComponents&, ...) instead.")]]
119
  static absl::Status Train(const TrainerSpec& trainer_spec,
120
                            const NormalizerSpec& normalizer_spec,
121
                            SentenceIterator* sentence_iterator = nullptr,
122
                            std::string* serialized_model_proto = nullptr);
123
124
  // Trains SentencePiece model with `trainer_spec`, `normalizer_spec`
125
  // and `denormalizer_spec`.
126
  // When `sentence_iterator` is passed, load sentences from the iterator.
127
  [[deprecated("Use Train(const TrainerComponents&, ...) instead.")]]
128
  static absl::Status Train(const TrainerSpec& trainer_spec,
129
                            const NormalizerSpec& normalizer_spec,
130
                            const NormalizerSpec& denormalizer_spec,
131
                            SentenceIterator* sentence_iterator = nullptr,
132
                            std::string* serialized_model_proto = nullptr);
133
  // Trains SentencePiece model with command-line string in `args`,
134
  // e.g.,
135
  // '--input=data --model_prefix=m --vocab_size=8192 model_type=unigram'
136
  // When `sentence_iterator` is passed, load sentences from the iterator.
137
  [[deprecated(
138
      "Use Train(absl::string_view, const TrainerComponents&, ...) instead.")]]
139
  static absl::Status Train(absl::string_view args,
140
                            SentenceIterator* sentence_iterator = nullptr,
141
                            std::string* serialized_model_proto = nullptr);
142
143
  // Trains SentencePiece model with mapin `kwargs`.
144
  // e.g., {{"input", "data"}, {"model_prefix, "m"}, {"vocab_size", "8192"}...}
145
  [[deprecated(
146
      "Use Train(const std::unordered_map<std::string, std::string>&, const "
147
      "TrainerComponents&, ...) instead.")]]
148
  static absl::Status Train(
149
      const std::unordered_map<std::string, std::string>& kwargs,
150
      SentenceIterator* sentence_iterator = nullptr,
151
      std::string* serialized_model_proto = nullptr);
152
153
  // The same as above, but passes the list of sentences.
154
  [[deprecated(
155
      "Use Train(absl::string_view, const TrainerComponents&, ...) instead.")]]
156
  static absl::Status Train(absl::string_view args,
157
                            const std::vector<std::string>& sentences,
158
                            std::string* serialized_model_proto = nullptr);
159
160
  // The same as above, but passes the list of sentences.
161
  [[deprecated(
162
      "Use Train(const std::unordered_map<std::string, std::string>&, const "
163
      "TrainerComponents&, ...) instead.")]]
164
  static absl::Status Train(
165
      const std::unordered_map<std::string, std::string>& kwargs,
166
      const std::vector<std::string>& sentences,
167
      std::string* serialized_model_proto = nullptr);
168
169
  // Handy function to make a normalizer spec from the pre-compiled
170
  // normalization name. Do not use this method in production as it crashes
171
  // When `name` is invalid. Useful for unittesting.
172
  static NormalizerSpec GetNormalizerSpec(absl::string_view name);
173
174
  // Populates necessary fields (precompiled_charmap) from
175
  // `NormalizerSpec::name` or `NormalizerSpec::normalization_rule_tsv`.
176
  static absl::Status PopulateNormalizerSpec(NormalizerSpec* normalizer_spec,
177
                                             bool is_denormalizer = false);
178
179
  // Overrides `trainer_spec`, `normalizer_spec`, `denormalizer_spec` with the
180
  // std::unordered_map in `kwargs`.
181
  static absl::Status MergeSpecsFromArgs(
182
      const std::unordered_map<std::string, std::string>& kwargs,
183
      TrainerSpec* trainer_spec, NormalizerSpec* normalizer_spec,
184
      NormalizerSpec* denormalizer_spec);
185
186
  static absl::Status MergeSpecsFromArgs(
187
      const std::unordered_map<std::string, std::string>& kwargs,
188
      TrainerComponents* components);
189
190
  // Overrides `trainer_spec`, `normalizer_spec`, `denormalizer_spec` with the
191
  // command line flags in `args`.
192
  static absl::Status MergeSpecsFromArgs(absl::string_view args,
193
                                         TrainerSpec* trainer_spec,
194
                                         NormalizerSpec* normalizer_spec,
195
                                         NormalizerSpec* denormalizer_spec);
196
197
  static absl::Status MergeSpecsFromArgs(absl::string_view args,
198
                                         TrainerComponents* components);
199
200
  // Helper function to set `field_name=value` in `message`.
201
  // When `field_name` is repeated, multiple values can be passed
202
  // with comma-separated values. `field_name` must not be a nested message.
203
  // The body of these functions are automatically generated with
204
  // data/gen_spec_parser.pl
205
  static absl::Status SetProtoField(absl::string_view name,
206
                                    absl::string_view value,
207
                                    TrainerSpec* message);
208
209
  static absl::Status SetProtoField(absl::string_view name,
210
                                    absl::string_view value,
211
                                    NormalizerSpec* message);
212
213
  // Populates model type from string representation, e.g., "bpe".
214
  // Supported model: "unigram", "bpe", "word", "char".
215
  static absl::Status PopulateModelTypeFromString(absl::string_view type,
216
                                                  TrainerSpec* trainer_spec);
217
218
 private:
219
0
  SentencePieceTrainer() {}
220
  ~SentencePieceTrainer() = default;
221
};
222
223
class SentencePieceNormalizer {
224
 public:
225
  SentencePieceNormalizer();
226
  virtual ~SentencePieceNormalizer();
227
228
  virtual absl::Status Load(std::unique_ptr<ModelProto> model_proto);
229
  virtual absl::Status Load(std::unique_ptr<NormalizerSpec> normalizer_spec);
230
231
  virtual absl::Status Load(absl::string_view filename);
232
233
  virtual absl::Status LoadFromSerializedProto(absl::string_view serialized);
234
  virtual absl::Status LoadFromSerializedNormalizerSpec(
235
      absl::string_view serialized);
236
237
  virtual absl::Status LoadFromRuleTSV(absl::string_view filename);
238
239
  virtual absl::Status LoadFromRuleName(absl::string_view name);
240
241
  virtual absl::Status LoadFromMap(
242
      absl::Span<const std::pair<std::string, std::string>> norm_map);
243
244
  virtual absl::Status Decompile(
245
      std::vector<std::pair<std::string, std::string>>* norm_map) const;
246
247
  virtual absl::Status Normalize(absl::string_view input,
248
                                 std::string* normalized) const;
249
250
  virtual absl::Status Normalize(absl::string_view input,
251
                                 std::string* normalized,
252
                                 std::vector<size_t>* norm_to_orig) const;
253
254
  [[nodiscard]] virtual std::string Normalize(absl::string_view input) const;
255
256
  [[nodiscard]] virtual NormalizerSpec* mutable_normalizer_spec();
257
258
  [[nodiscard]] virtual std::string serialized_model_proto() const;
259
260
  [[nodiscard]] virtual std::string serialized_normalizer_spec() const;
261
262
 private:
263
  std::unique_ptr<normalizer::Normalizer> normalizer_;
264
  std::unique_ptr<NormalizerSpec> normalizer_spec_;
265
};
266
267
// Converts the utf8 byte spans into Unicode char span.
268
void ConvertToUnicodeAlignment(absl::string_view orig, absl::string_view norm,
269
                               std::vector<size_t>* norm_to_orig);
270
271
// Sets data dir including the pre-compiled normalization data.
272
// The implementation is found in util.cc
273
void SetDataDir(absl::string_view data_dir);
274
275
}  // namespace sentencepiece
276
277
#endif  // SENTENCEPIECE_TRAINER_H_