applied-ai-018 commited on
Commit
16037bc
·
verified ·
1 Parent(s): 4b6852c

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. cc-multilingual-main/cc_net/third_party/kenlm/build/lib/libkenlm_builder.a +3 -0
  3. cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/CMakeLists.txt +40 -0
  4. cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/arpa_io.cc +77 -0
  5. cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/arpa_io.hh +99 -0
  6. cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/count_io.hh +89 -0
  7. cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/filter_main.cc +253 -0
  8. cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/format.hh +250 -0
  9. cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/phrase.cc +292 -0
  10. cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/phrase.hh +168 -0
  11. cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/phrase_table_vocab_main.cc +165 -0
  12. cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/thread.hh +167 -0
  13. cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/vocab.cc +53 -0
  14. cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/vocab.hh +133 -0
  15. cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/CMakeLists.txt +60 -0
  16. cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/backoff_matrix.hh +29 -0
  17. cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/backoff_reunification_test.cc +158 -0
  18. cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/bounded_sequence_encoding_test.cc +97 -0
  19. cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/interpolate_main.cc +124 -0
  20. cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/normalize.hh +35 -0
  21. cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/normalize_test.cc +86 -0
  22. cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/split_worker.cc +40 -0
  23. cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/tune_instances_test.cc +138 -0
  24. cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/tune_weights.cc +33 -0
  25. cc-multilingual-main/cc_net/third_party/kenlm/python/_kenlm.pxd +63 -0
  26. cc-multilingual-main/cc_net/third_party/kenlm/python/example.py +43 -0
  27. cc-multilingual-main/cc_net/third_party/kenlm/python/kenlm.cpp +0 -0
  28. cc-multilingual-main/cc_net/third_party/kenlm/python/score_sentence.cc +30 -0
  29. cc-multilingual-main/cc_net/third_party/kenlm/python/score_sentence.hh +13 -0
  30. cc-multilingual-main/cc_net/third_party/kenlm/util/bit_packing.cc +40 -0
  31. cc-multilingual-main/cc_net/third_party/kenlm/util/bit_packing.hh +191 -0
  32. cc-multilingual-main/cc_net/third_party/kenlm/util/bit_packing_test.cc +59 -0
  33. cc-multilingual-main/cc_net/third_party/kenlm/util/cat_compressed_main.cc +47 -0
  34. cc-multilingual-main/cc_net/third_party/kenlm/util/ersatz_progress.cc +47 -0
  35. cc-multilingual-main/cc_net/third_party/kenlm/util/exception.cc +104 -0
  36. cc-multilingual-main/cc_net/third_party/kenlm/util/exception.hh +159 -0
  37. cc-multilingual-main/cc_net/third_party/kenlm/util/fake_ostream.hh +111 -0
  38. cc-multilingual-main/cc_net/third_party/kenlm/util/file.cc +621 -0
  39. cc-multilingual-main/cc_net/third_party/kenlm/util/file.hh +169 -0
  40. cc-multilingual-main/cc_net/third_party/kenlm/util/file_piece.cc +367 -0
  41. cc-multilingual-main/cc_net/third_party/kenlm/util/file_stream.hh +97 -0
  42. cc-multilingual-main/cc_net/third_party/kenlm/util/fixed_array.hh +206 -0
  43. cc-multilingual-main/cc_net/third_party/kenlm/util/float_to_string.hh +25 -0
  44. cc-multilingual-main/cc_net/third_party/kenlm/util/getopt.hh +33 -0
  45. cc-multilingual-main/cc_net/third_party/kenlm/util/integer_to_string.hh +66 -0
  46. cc-multilingual-main/cc_net/third_party/kenlm/util/integer_to_string_test.cc +81 -0
  47. cc-multilingual-main/cc_net/third_party/kenlm/util/joint_sort.hh +146 -0
  48. cc-multilingual-main/cc_net/third_party/kenlm/util/joint_sort_test.cc +62 -0
  49. cc-multilingual-main/cc_net/third_party/kenlm/util/mmap.cc +405 -0
  50. cc-multilingual-main/cc_net/third_party/kenlm/util/mmap.hh +239 -0
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
60
  cc-multilingual-main/cc_net/third_party/kenlm/build/lib/libkenlm.a filter=lfs diff=lfs merge=lfs -text
 
 
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
60
  cc-multilingual-main/cc_net/third_party/kenlm/build/lib/libkenlm.a filter=lfs diff=lfs merge=lfs -text
61
+ cc-multilingual-main/cc_net/third_party/kenlm/build/lib/libkenlm_builder.a filter=lfs diff=lfs merge=lfs -text
cc-multilingual-main/cc_net/third_party/kenlm/build/lib/libkenlm_builder.a ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9863b8fa839e23d2977f597d936852952987aadf49ad0289258b757826af770a
3
+ size 1124178
cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/CMakeLists.txt ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This CMake file was created by Lane Schwartz <[email protected]>
2
+
3
+ # Explicitly list the source files for this subdirectory
4
+ #
5
+ # If you add any source files to this subdirectory
6
+ # that should be included in the kenlm library,
7
+ # (this excludes any unit test files)
8
+ # you should add them to the following list:
9
+ #
10
+ # In order to set correct paths to these files
11
+ # in case this variable is referenced by CMake files in the parent directory,
12
+ # we prefix all files with ${CMAKE_CURRENT_SOURCE_DIR}.
13
+ #
14
+ set(KENLM_FILTER_SOURCE
15
+ ${CMAKE_CURRENT_SOURCE_DIR}/arpa_io.cc
16
+ ${CMAKE_CURRENT_SOURCE_DIR}/phrase.cc
17
+ ${CMAKE_CURRENT_SOURCE_DIR}/vocab.cc
18
+ )
19
+
20
+ # Group these objects together for later use.
21
+ #
22
+ # Given add_library(foo OBJECT ${my_foo_sources}),
23
+ # refer to these objects as $<TARGET_OBJECTS:foo>
24
+ #
25
+ add_library(kenlm_filter ${KENLM_FILTER_SOURCE})
26
+ target_link_libraries(kenlm_filter PUBLIC kenlm_util)
27
+ # Since headers are relative to `include/kenlm` at install time, not just `include`
28
+ target_include_directories(kenlm_filter PUBLIC $<INSTALL_INTERFACE:include/kenlm>)
29
+
30
+ AddExes(EXES filter phrase_table_vocab
31
+ LIBRARIES kenlm_filter kenlm)
32
+
33
+ install(
34
+ TARGETS kenlm_filter
35
+ EXPORT kenlmTargets
36
+ RUNTIME DESTINATION bin
37
+ LIBRARY DESTINATION lib
38
+ ARCHIVE DESTINATION lib
39
+ INCLUDES DESTINATION include
40
+ )
cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/arpa_io.cc ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "arpa_io.hh"
2
+ #include "../../util/file_piece.hh"
3
+ #include "../../util/string_stream.hh"
4
+
5
+ #include <iostream>
6
+ #include <ostream>
7
+ #include <string>
8
+ #include <vector>
9
+
10
+ #include <cctype>
11
+ #include <cerrno>
12
+ #include <cstring>
13
+
14
+ namespace lm {
15
+
16
+ ARPAInputException::ARPAInputException(const StringPiece &message) throw() {
17
+ *this << message;
18
+ }
19
+
20
+ ARPAInputException::ARPAInputException(const StringPiece &message, const StringPiece &line) throw() {
21
+ *this << message << " in line " << line;
22
+ }
23
+
24
+ ARPAInputException::~ARPAInputException() throw() {}
25
+
26
+ // Seeking is the responsibility of the caller.
27
+ template <class Stream> void WriteCounts(Stream &out, const std::vector<uint64_t> &number) {
28
+ out << "\n\\data\\\n";
29
+ for (unsigned int i = 0; i < number.size(); ++i) {
30
+ out << "ngram " << i+1 << "=" << number[i] << '\n';
31
+ }
32
+ out << '\n';
33
+ }
34
+
35
+ size_t SizeNeededForCounts(const std::vector<uint64_t> &number) {
36
+ util::StringStream stream;
37
+ WriteCounts(stream, number);
38
+ return stream.str().size();
39
+ }
40
+
41
+ bool IsEntirelyWhiteSpace(const StringPiece &line) {
42
+ for (size_t i = 0; i < static_cast<size_t>(line.size()); ++i) {
43
+ if (!isspace(line.data()[i])) return false;
44
+ }
45
+ return true;
46
+ }
47
+
48
+ ARPAOutput::ARPAOutput(const char *name, size_t buffer_size)
49
+ : file_backing_(util::CreateOrThrow(name)), file_(file_backing_.get(), buffer_size) {}
50
+
51
+ void ARPAOutput::ReserveForCounts(std::streampos reserve) {
52
+ for (std::streampos i = 0; i < reserve; i += std::streampos(1)) {
53
+ file_ << '\n';
54
+ }
55
+ }
56
+
57
+ void ARPAOutput::BeginLength(unsigned int length) {
58
+ file_ << '\\' << length << "-grams:" << '\n';
59
+ fast_counter_ = 0;
60
+ }
61
+
62
+ void ARPAOutput::EndLength(unsigned int length) {
63
+ file_ << '\n';
64
+ if (length > counts_.size()) {
65
+ counts_.resize(length);
66
+ }
67
+ counts_[length - 1] = fast_counter_;
68
+ }
69
+
70
+ void ARPAOutput::Finish() {
71
+ file_ << "\\end\\\n";
72
+ file_.seekp(0);
73
+ WriteCounts(file_, counts_);
74
+ file_.flush();
75
+ }
76
+
77
+ } // namespace lm
cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/arpa_io.hh ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef LM_FILTER_ARPA_IO_H
2
+ #define LM_FILTER_ARPA_IO_H
3
+ /* Input and output for ARPA format language model files.
4
+ */
5
+ #include "../read_arpa.hh"
6
+ #include "../../util/exception.hh"
7
+ #include "../../util/file_stream.hh"
8
+ #include "../../util/string_piece.hh"
9
+ #include "../../util/tokenize_piece.hh"
10
+
11
+ #include <boost/noncopyable.hpp>
12
+ #include <boost/scoped_array.hpp>
13
+
14
+ #include <fstream>
15
+ #include <string>
16
+ #include <vector>
17
+
18
+ #include <cstring>
19
+ #include <stdint.h>
20
+
21
+ namespace util { class FilePiece; }
22
+
23
+ namespace lm {
24
+
25
+ class ARPAInputException : public util::Exception {
26
+ public:
27
+ explicit ARPAInputException(const StringPiece &message) throw();
28
+ explicit ARPAInputException(const StringPiece &message, const StringPiece &line) throw();
29
+ virtual ~ARPAInputException() throw();
30
+ };
31
+
32
+ // Handling for the counts of n-grams at the beginning of ARPA files.
33
+ size_t SizeNeededForCounts(const std::vector<uint64_t> &number);
34
+
35
+ /* Writes an ARPA file. This has to be seekable so the counts can be written
36
+ * at the end. Hence, I just have it own a std::fstream instead of accepting
37
+ * a separately held std::ostream. TODO: use the fast one from estimation.
38
+ */
39
+ class ARPAOutput : boost::noncopyable {
40
+ public:
41
+ explicit ARPAOutput(const char *name, size_t buffer_size = 65536);
42
+
43
+ void ReserveForCounts(std::streampos reserve);
44
+
45
+ void BeginLength(unsigned int length);
46
+
47
+ void AddNGram(const StringPiece &line) {
48
+ file_ << line << '\n';
49
+ ++fast_counter_;
50
+ }
51
+
52
+ void AddNGram(const StringPiece &ngram, const StringPiece &line) {
53
+ AddNGram(line);
54
+ }
55
+
56
+ template <class Iterator> void AddNGram(const Iterator &begin, const Iterator &end, const StringPiece &line) {
57
+ AddNGram(line);
58
+ }
59
+
60
+ void EndLength(unsigned int length);
61
+
62
+ void Finish();
63
+
64
+ private:
65
+ util::scoped_fd file_backing_;
66
+ util::FileStream file_;
67
+ uint64_t fast_counter_;
68
+ std::vector<uint64_t> counts_;
69
+ };
70
+
71
+
72
+ template <class Output> void ReadNGrams(util::FilePiece &in, unsigned int length, uint64_t number, Output &out) {
73
+ ReadNGramHeader(in, length);
74
+ out.BeginLength(length);
75
+ for (uint64_t i = 0; i < number; ++i) {
76
+ StringPiece line = in.ReadLine();
77
+ util::TokenIter<util::SingleCharacter> tabber(line, '\t');
78
+ if (!tabber) throw ARPAInputException("blank line", line);
79
+ if (!++tabber) throw ARPAInputException("no tab", line);
80
+
81
+ out.AddNGram(*tabber, line);
82
+ }
83
+ out.EndLength(length);
84
+ }
85
+
86
+ template <class Output> void ReadARPA(util::FilePiece &in_lm, Output &out) {
87
+ std::vector<uint64_t> number;
88
+ ReadARPACounts(in_lm, number);
89
+ out.ReserveForCounts(SizeNeededForCounts(number));
90
+ for (unsigned int i = 0; i < number.size(); ++i) {
91
+ ReadNGrams(in_lm, i + 1, number[i], out);
92
+ }
93
+ ReadEnd(in_lm);
94
+ out.Finish();
95
+ }
96
+
97
+ } // namespace lm
98
+
99
+ #endif // LM_FILTER_ARPA_IO_H
cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/count_io.hh ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef LM_FILTER_COUNT_IO_H
2
+ #define LM_FILTER_COUNT_IO_H
3
+
4
+ #include <fstream>
5
+ #include <iostream>
6
+ #include <string>
7
+
8
+ #include "../../util/file_stream.hh"
9
+ #include "../../util/file.hh"
10
+ #include "../../util/file_piece.hh"
11
+
12
+ namespace lm {
13
+
14
+ class CountOutput : boost::noncopyable {
15
+ public:
16
+ explicit CountOutput(const char *name) : file_(util::CreateOrThrow(name)) {}
17
+
18
+ void AddNGram(const StringPiece &line) {
19
+ file_ << line << '\n';
20
+ }
21
+
22
+ template <class Iterator> void AddNGram(const Iterator &begin, const Iterator &end, const StringPiece &line) {
23
+ AddNGram(line);
24
+ }
25
+
26
+ void AddNGram(const StringPiece &ngram, const StringPiece &line) {
27
+ AddNGram(line);
28
+ }
29
+
30
+ private:
31
+ util::FileStream file_;
32
+ };
33
+
34
+ class CountBatch {
35
+ public:
36
+ explicit CountBatch(std::streamsize initial_read)
37
+ : initial_read_(initial_read) {
38
+ buffer_.reserve(initial_read);
39
+ }
40
+
41
+ void Read(std::istream &in) {
42
+ buffer_.resize(initial_read_);
43
+ in.read(&*buffer_.begin(), initial_read_);
44
+ buffer_.resize(in.gcount());
45
+ char got;
46
+ while (in.get(got) && got != '\n')
47
+ buffer_.push_back(got);
48
+ }
49
+
50
+ template <class Output> void Send(Output &out) {
51
+ for (util::TokenIter<util::SingleCharacter> line(StringPiece(&*buffer_.begin(), buffer_.size()), '\n'); line; ++line) {
52
+ util::TokenIter<util::SingleCharacter> tabber(*line, '\t');
53
+ if (!tabber) {
54
+ std::cerr << "Warning: empty n-gram count line being removed\n";
55
+ continue;
56
+ }
57
+ util::TokenIter<util::SingleCharacter, true> words(*tabber, ' ');
58
+ if (!words) {
59
+ std::cerr << "Line has a tab but no words.\n";
60
+ continue;
61
+ }
62
+ out.AddNGram(words, util::TokenIter<util::SingleCharacter, true>::end(), *line);
63
+ }
64
+ }
65
+
66
+ private:
67
+ std::streamsize initial_read_;
68
+
69
+ // This could have been a std::string but that's less happy with raw writes.
70
+ std::vector<char> buffer_;
71
+ };
72
+
73
+ template <class Output> void ReadCount(util::FilePiece &in_file, Output &out) {
74
+ try {
75
+ while (true) {
76
+ StringPiece line = in_file.ReadLine();
77
+ util::TokenIter<util::SingleCharacter> tabber(line, '\t');
78
+ if (!tabber) {
79
+ std::cerr << "Warning: empty n-gram count line being removed\n";
80
+ continue;
81
+ }
82
+ out.AddNGram(*tabber, line);
83
+ }
84
+ } catch (const util::EndOfFileException &) {}
85
+ }
86
+
87
+ } // namespace lm
88
+
89
+ #endif // LM_FILTER_COUNT_IO_H
cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/filter_main.cc ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "arpa_io.hh"
2
+ #include "format.hh"
3
+ #include "phrase.hh"
4
+ #ifndef NTHREAD
5
+ #include "thread.hh"
6
+ #endif
7
+ #include "vocab.hh"
8
+ #include "wrapper.hh"
9
+ #include "../../util/exception.hh"
10
+ #include "../../util/file_piece.hh"
11
+
12
+ #include <boost/ptr_container/ptr_vector.hpp>
13
+
14
+ #include <cstring>
15
+ #include <fstream>
16
+ #include <iostream>
17
+ #include <memory>
18
+
19
+ namespace lm {
20
+ namespace {
21
+
22
+ void DisplayHelp(const char *name) {
23
+ std::cerr
24
+ << "Usage: " << name << " mode [context] [phrase] [raw|arpa] [threads:m] [batch_size:m] (vocab|model):input_file output_file\n\n"
25
+ "copy mode just copies, but makes the format nicer for e.g. irstlm's broken\n"
26
+ " parser.\n"
27
+ "single mode treats the entire input as a single sentence.\n"
28
+ "multiple mode filters to multiple sentences in parallel. Each sentence is on\n"
29
+ " a separate line. A separate file is created for each sentence by appending\n"
30
+ " the 0-indexed line number to the output file name.\n"
31
+ "union mode produces one filtered model that is the union of models created by\n"
32
+ " multiple mode.\n\n"
33
+ "context means only the context (all but last word) has to pass the filter, but\n"
34
+ " the entire n-gram is output.\n\n"
35
+ "phrase means that the vocabulary is actually tab-delimited phrases and that the\n"
36
+ " phrases can generate the n-gram when assembled in arbitrary order and\n"
37
+ " clipped. Currently works with multiple or union mode.\n\n"
38
+ "The file format is set by [raw|arpa] with default arpa:\n"
39
+ "raw means space-separated tokens, optionally followed by a tab and arbitrary\n"
40
+ " text. This is useful for ngram count files.\n"
41
+ "arpa means the ARPA file format for n-gram language models.\n\n"
42
+ #ifndef NTHREAD
43
+ "threads:m sets m threads (default: conccurrency detected by boost)\n"
44
+ "batch_size:m sets the batch size for threading. Expect memory usage from this\n"
45
+ " of 2*threads*batch_size n-grams.\n\n"
46
+ #else
47
+ "This binary was compiled with -DNTHREAD, disabling threading. If you wanted\n"
48
+ " threading, compile without this flag against Boost >=1.42.0.\n\n"
49
+ #endif
50
+ "There are two inputs: vocabulary and model. Either may be given as a file\n"
51
+ " while the other is on stdin. Specify the type given as a file using\n"
52
+ " vocab: or model: before the file name. \n\n"
53
+ "For ARPA format, the output must be seekable. For raw format, it can be a\n"
54
+ " stream i.e. /dev/stdout\n";
55
+ }
56
+
57
+ typedef enum {MODE_COPY, MODE_SINGLE, MODE_MULTIPLE, MODE_UNION, MODE_UNSET} FilterMode;
58
+ typedef enum {FORMAT_ARPA, FORMAT_COUNT} Format;
59
+
60
+ struct Config {
61
+ Config() :
62
+ #ifndef NTHREAD
63
+ batch_size(25000),
64
+ threads(boost::thread::hardware_concurrency()),
65
+ #endif
66
+ phrase(false),
67
+ context(false),
68
+ format(FORMAT_ARPA)
69
+ {
70
+ #ifndef NTHREAD
71
+ if (!threads) threads = 1;
72
+ #endif
73
+ }
74
+
75
+ #ifndef NTHREAD
76
+ size_t batch_size;
77
+ size_t threads;
78
+ #endif
79
+ bool phrase;
80
+ bool context;
81
+ FilterMode mode;
82
+ Format format;
83
+ };
84
+
85
+ template <class Format, class Filter, class OutputBuffer, class Output> void RunThreadedFilter(const Config &config, util::FilePiece &in_lm, Filter &filter, Output &output) {
86
+ #ifndef NTHREAD
87
+ if (config.threads == 1) {
88
+ #endif
89
+ Format::RunFilter(in_lm, filter, output);
90
+ #ifndef NTHREAD
91
+ } else {
92
+ typedef Controller<Filter, OutputBuffer, Output> Threaded;
93
+ Threaded threading(config.batch_size, config.threads * 2, config.threads, filter, output);
94
+ Format::RunFilter(in_lm, threading, output);
95
+ }
96
+ #endif
97
+ }
98
+
99
+ template <class Format, class Filter, class OutputBuffer, class Output> void RunContextFilter(const Config &config, util::FilePiece &in_lm, Filter filter, Output &output) {
100
+ if (config.context) {
101
+ ContextFilter<Filter> context_filter(filter);
102
+ RunThreadedFilter<Format, ContextFilter<Filter>, OutputBuffer, Output>(config, in_lm, context_filter, output);
103
+ } else {
104
+ RunThreadedFilter<Format, Filter, OutputBuffer, Output>(config, in_lm, filter, output);
105
+ }
106
+ }
107
+
108
+ template <class Format, class Binary> void DispatchBinaryFilter(const Config &config, util::FilePiece &in_lm, const Binary &binary, typename Format::Output &out) {
109
+ typedef BinaryFilter<Binary> Filter;
110
+ RunContextFilter<Format, Filter, BinaryOutputBuffer, typename Format::Output>(config, in_lm, Filter(binary), out);
111
+ }
112
+
113
+ template <class Format> void DispatchFilterModes(const Config &config, std::istream &in_vocab, util::FilePiece &in_lm, const char *out_name) {
114
+ if (config.mode == MODE_MULTIPLE) {
115
+ if (config.phrase) {
116
+ typedef phrase::Multiple Filter;
117
+ phrase::Substrings substrings;
118
+ typename Format::Multiple out(out_name, phrase::ReadMultiple(in_vocab, substrings));
119
+ RunContextFilter<Format, Filter, MultipleOutputBuffer, typename Format::Multiple>(config, in_lm, Filter(substrings), out);
120
+ } else {
121
+ typedef vocab::Multiple Filter;
122
+ boost::unordered_map<std::string, std::vector<unsigned int> > words;
123
+ typename Format::Multiple out(out_name, vocab::ReadMultiple(in_vocab, words));
124
+ RunContextFilter<Format, Filter, MultipleOutputBuffer, typename Format::Multiple>(config, in_lm, Filter(words), out);
125
+ }
126
+ return;
127
+ }
128
+
129
+ typename Format::Output out(out_name);
130
+
131
+ if (config.mode == MODE_COPY) {
132
+ Format::Copy(in_lm, out);
133
+ return;
134
+ }
135
+
136
+ if (config.mode == MODE_SINGLE) {
137
+ vocab::Single::Words words;
138
+ vocab::ReadSingle(in_vocab, words);
139
+ DispatchBinaryFilter<Format, vocab::Single>(config, in_lm, vocab::Single(words), out);
140
+ return;
141
+ }
142
+
143
+ if (config.mode == MODE_UNION) {
144
+ if (config.phrase) {
145
+ phrase::Substrings substrings;
146
+ phrase::ReadMultiple(in_vocab, substrings);
147
+ DispatchBinaryFilter<Format, phrase::Union>(config, in_lm, phrase::Union(substrings), out);
148
+ } else {
149
+ vocab::Union::Words words;
150
+ vocab::ReadMultiple(in_vocab, words);
151
+ DispatchBinaryFilter<Format, vocab::Union>(config, in_lm, vocab::Union(words), out);
152
+ }
153
+ return;
154
+ }
155
+ }
156
+
157
+ } // namespace
158
+ } // namespace lm
159
+
160
+ int main(int argc, char *argv[]) {
161
+ try {
162
+ if (argc < 4) {
163
+ lm::DisplayHelp(argv[0]);
164
+ return 1;
165
+ }
166
+
167
+ // I used to have boost::program_options, but some users didn't want to compile boost.
168
+ lm::Config config;
169
+ config.mode = lm::MODE_UNSET;
170
+ for (int i = 1; i < argc - 2; ++i) {
171
+ const char *str = argv[i];
172
+ if (!std::strcmp(str, "copy")) {
173
+ config.mode = lm::MODE_COPY;
174
+ } else if (!std::strcmp(str, "single")) {
175
+ config.mode = lm::MODE_SINGLE;
176
+ } else if (!std::strcmp(str, "multiple")) {
177
+ config.mode = lm::MODE_MULTIPLE;
178
+ } else if (!std::strcmp(str, "union")) {
179
+ config.mode = lm::MODE_UNION;
180
+ } else if (!std::strcmp(str, "phrase")) {
181
+ config.phrase = true;
182
+ } else if (!std::strcmp(str, "context")) {
183
+ config.context = true;
184
+ } else if (!std::strcmp(str, "arpa")) {
185
+ config.format = lm::FORMAT_ARPA;
186
+ } else if (!std::strcmp(str, "raw")) {
187
+ config.format = lm::FORMAT_COUNT;
188
+ #ifndef NTHREAD
189
+ } else if (!std::strncmp(str, "threads:", 8)) {
190
+ config.threads = boost::lexical_cast<size_t>(str + 8);
191
+ if (!config.threads) {
192
+ std::cerr << "Specify at least one thread." << std::endl;
193
+ return 1;
194
+ }
195
+ } else if (!std::strncmp(str, "batch_size:", 11)) {
196
+ config.batch_size = boost::lexical_cast<size_t>(str + 11);
197
+ if (config.batch_size < 5000) {
198
+ std::cerr << "Batch size must be at least one and should probably be >= 5000" << std::endl;
199
+ if (!config.batch_size) return 1;
200
+ }
201
+ #endif
202
+ } else {
203
+ lm::DisplayHelp(argv[0]);
204
+ return 1;
205
+ }
206
+ }
207
+
208
+ if (config.mode == lm::MODE_UNSET) {
209
+ lm::DisplayHelp(argv[0]);
210
+ return 1;
211
+ }
212
+
213
+ if (config.phrase && config.mode != lm::MODE_UNION && config.mode != lm::MODE_MULTIPLE) {
214
+ std::cerr << "Phrase constraint currently only works in multiple or union mode. If you really need it for single, put everything on one line and use union." << std::endl;
215
+ return 1;
216
+ }
217
+
218
+ bool cmd_is_model = true;
219
+ const char *cmd_input = argv[argc - 2];
220
+ if (!strncmp(cmd_input, "vocab:", 6)) {
221
+ cmd_is_model = false;
222
+ cmd_input += 6;
223
+ } else if (!strncmp(cmd_input, "model:", 6)) {
224
+ cmd_input += 6;
225
+ } else if (strchr(cmd_input, ':')) {
226
+ std::cerr << "Specify vocab: or model: before the input file name, not " << cmd_input << std::endl;
227
+ return 1;
228
+ } else {
229
+ std::cerr << "Assuming that " << cmd_input << " is a model file" << std::endl;
230
+ }
231
+ std::ifstream cmd_file;
232
+ std::istream *vocab;
233
+ if (cmd_is_model) {
234
+ vocab = &std::cin;
235
+ } else {
236
+ cmd_file.open(cmd_input, std::ios::in);
237
+ UTIL_THROW_IF(!cmd_file, util::ErrnoException, "Failed to open " << cmd_input);
238
+ vocab = &cmd_file;
239
+ }
240
+
241
+ util::FilePiece model(cmd_is_model ? util::OpenReadOrThrow(cmd_input) : 0, cmd_is_model ? cmd_input : NULL, &std::cerr);
242
+
243
+ if (config.format == lm::FORMAT_ARPA) {
244
+ lm::DispatchFilterModes<lm::ARPAFormat>(config, *vocab, model, argv[argc - 1]);
245
+ } else if (config.format == lm::FORMAT_COUNT) {
246
+ lm::DispatchFilterModes<lm::CountFormat>(config, *vocab, model, argv[argc - 1]);
247
+ }
248
+ return 0;
249
+ } catch (const std::exception &e) {
250
+ std::cerr << e.what() << std::endl;
251
+ return 1;
252
+ }
253
+ }
cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/format.hh ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef LM_FILTER_FORMAT_H
2
+ #define LM_FILTER_FORMAT_H
3
+
4
+ #include "arpa_io.hh"
5
+ #include "count_io.hh"
6
+
7
+ #include <boost/lexical_cast.hpp>
8
+ #include <boost/ptr_container/ptr_vector.hpp>
9
+
10
+ #include <iosfwd>
11
+
12
+ namespace lm {
13
+
14
+ template <class Single> class MultipleOutput {
15
+ private:
16
+ typedef boost::ptr_vector<Single> Singles;
17
+ typedef typename Singles::iterator SinglesIterator;
18
+
19
+ public:
20
+ MultipleOutput(const char *prefix, size_t number) {
21
+ files_.reserve(number);
22
+ std::string tmp;
23
+ for (unsigned int i = 0; i < number; ++i) {
24
+ tmp = prefix;
25
+ tmp += boost::lexical_cast<std::string>(i);
26
+ files_.push_back(new Single(tmp.c_str()));
27
+ }
28
+ }
29
+
30
+ void AddNGram(const StringPiece &line) {
31
+ for (SinglesIterator i = files_.begin(); i != files_.end(); ++i)
32
+ i->AddNGram(line);
33
+ }
34
+
35
+ template <class Iterator> void AddNGram(const Iterator &begin, const Iterator &end, const StringPiece &line) {
36
+ for (SinglesIterator i = files_.begin(); i != files_.end(); ++i)
37
+ i->AddNGram(begin, end, line);
38
+ }
39
+
40
+ void SingleAddNGram(size_t offset, const StringPiece &line) {
41
+ files_[offset].AddNGram(line);
42
+ }
43
+
44
+ template <class Iterator> void SingleAddNGram(size_t offset, const Iterator &begin, const Iterator &end, const StringPiece &line) {
45
+ files_[offset].AddNGram(begin, end, line);
46
+ }
47
+
48
+ protected:
49
+ Singles files_;
50
+ };
51
+
52
+ class MultipleARPAOutput : public MultipleOutput<ARPAOutput> {
53
+ public:
54
+ MultipleARPAOutput(const char *prefix, size_t number) : MultipleOutput<ARPAOutput>(prefix, number) {}
55
+
56
+ void ReserveForCounts(std::streampos reserve) {
57
+ for (boost::ptr_vector<ARPAOutput>::iterator i = files_.begin(); i != files_.end(); ++i)
58
+ i->ReserveForCounts(reserve);
59
+ }
60
+
61
+ void BeginLength(unsigned int length) {
62
+ for (boost::ptr_vector<ARPAOutput>::iterator i = files_.begin(); i != files_.end(); ++i)
63
+ i->BeginLength(length);
64
+ }
65
+
66
+ void EndLength(unsigned int length) {
67
+ for (boost::ptr_vector<ARPAOutput>::iterator i = files_.begin(); i != files_.end(); ++i)
68
+ i->EndLength(length);
69
+ }
70
+
71
+ void Finish() {
72
+ for (boost::ptr_vector<ARPAOutput>::iterator i = files_.begin(); i != files_.end(); ++i)
73
+ i->Finish();
74
+ }
75
+ };
76
+
77
+ template <class Filter, class Output> class DispatchInput {
78
+ public:
79
+ DispatchInput(Filter &filter, Output &output) : filter_(filter), output_(output) {}
80
+
81
+ /* template <class Iterator> void AddNGram(const Iterator &begin, const Iterator &end, const StringPiece &line) {
82
+ filter_.AddNGram(begin, end, line, output_);
83
+ }*/
84
+
85
+ void AddNGram(const StringPiece &ngram, const StringPiece &line) {
86
+ filter_.AddNGram(ngram, line, output_);
87
+ }
88
+
89
+ protected:
90
+ Filter &filter_;
91
+ Output &output_;
92
+ };
93
+
94
+ template <class Filter, class Output> class DispatchARPAInput : public DispatchInput<Filter, Output> {
95
+ private:
96
+ typedef DispatchInput<Filter, Output> B;
97
+
98
+ public:
99
+ DispatchARPAInput(Filter &filter, Output &output) : B(filter, output) {}
100
+
101
+ void ReserveForCounts(std::streampos reserve) { B::output_.ReserveForCounts(reserve); }
102
+ void BeginLength(unsigned int length) { B::output_.BeginLength(length); }
103
+
104
+ void EndLength(unsigned int length) {
105
+ B::filter_.Flush();
106
+ B::output_.EndLength(length);
107
+ }
108
+ void Finish() { B::output_.Finish(); }
109
+ };
110
+
111
+ struct ARPAFormat {
112
+ typedef ARPAOutput Output;
113
+ typedef MultipleARPAOutput Multiple;
114
+ static void Copy(util::FilePiece &in, Output &out) {
115
+ ReadARPA(in, out);
116
+ }
117
+ template <class Filter, class Out> static void RunFilter(util::FilePiece &in, Filter &filter, Out &output) {
118
+ DispatchARPAInput<Filter, Out> dispatcher(filter, output);
119
+ ReadARPA(in, dispatcher);
120
+ }
121
+ };
122
+
123
+ struct CountFormat {
124
+ typedef CountOutput Output;
125
+ typedef MultipleOutput<Output> Multiple;
126
+ static void Copy(util::FilePiece &in, Output &out) {
127
+ ReadCount(in, out);
128
+ }
129
+ template <class Filter, class Out> static void RunFilter(util::FilePiece &in, Filter &filter, Out &output) {
130
+ DispatchInput<Filter, Out> dispatcher(filter, output);
131
+ ReadCount(in, dispatcher);
132
+ }
133
+ };
134
+
135
+ /* For multithreading, the buffer classes hold batches of filter inputs and
136
+ * outputs in memory. The strings get reused a lot, so keep them around
137
+ * instead of clearing each time.
138
+ */
139
+ class InputBuffer {
140
+ public:
141
+ InputBuffer() : actual_(0) {}
142
+
143
+ void Reserve(size_t size) { lines_.reserve(size); }
144
+
145
+ template <class Output> void AddNGram(const StringPiece &ngram, const StringPiece &line, Output &output) {
146
+ if (lines_.size() == actual_) lines_.resize(lines_.size() + 1);
147
+ // TODO avoid this copy.
148
+ std::string &copied = lines_[actual_].line;
149
+ copied.assign(line.data(), line.size());
150
+ lines_[actual_].ngram.set(copied.data() + (ngram.data() - line.data()), ngram.size());
151
+ ++actual_;
152
+ }
153
+
154
+ template <class Filter, class Output> void CallFilter(Filter &filter, Output &output) const {
155
+ for (std::vector<Line>::const_iterator i = lines_.begin(); i != lines_.begin() + actual_; ++i) {
156
+ filter.AddNGram(i->ngram, i->line, output);
157
+ }
158
+ }
159
+
160
+ void Clear() { actual_ = 0; }
161
+ bool Empty() { return actual_ == 0; }
162
+ size_t Size() { return actual_; }
163
+
164
+ private:
165
+ struct Line {
166
+ std::string line;
167
+ StringPiece ngram;
168
+ };
169
+
170
+ size_t actual_;
171
+
172
+ std::vector<Line> lines_;
173
+ };
174
+
175
+ class BinaryOutputBuffer {
176
+ public:
177
+ BinaryOutputBuffer() {}
178
+
179
+ void Reserve(size_t size) {
180
+ lines_.reserve(size);
181
+ }
182
+
183
+ void AddNGram(const StringPiece &line) {
184
+ lines_.push_back(line);
185
+ }
186
+
187
+ template <class Output> void Flush(Output &output) {
188
+ for (std::vector<StringPiece>::const_iterator i = lines_.begin(); i != lines_.end(); ++i) {
189
+ output.AddNGram(*i);
190
+ }
191
+ lines_.clear();
192
+ }
193
+
194
+ private:
195
+ std::vector<StringPiece> lines_;
196
+ };
197
+
198
+ class MultipleOutputBuffer {
199
+ public:
200
+ MultipleOutputBuffer() : last_(NULL) {}
201
+
202
+ void Reserve(size_t size) {
203
+ annotated_.reserve(size);
204
+ }
205
+
206
+ void AddNGram(const StringPiece &line) {
207
+ annotated_.resize(annotated_.size() + 1);
208
+ annotated_.back().line = line;
209
+ }
210
+
211
+ void SingleAddNGram(size_t offset, const StringPiece &line) {
212
+ if ((line.data() == last_.data()) && (line.length() == last_.length())) {
213
+ annotated_.back().systems.push_back(offset);
214
+ } else {
215
+ annotated_.resize(annotated_.size() + 1);
216
+ annotated_.back().systems.push_back(offset);
217
+ annotated_.back().line = line;
218
+ last_ = line;
219
+ }
220
+ }
221
+
222
+ template <class Output> void Flush(Output &output) {
223
+ for (std::vector<Annotated>::const_iterator i = annotated_.begin(); i != annotated_.end(); ++i) {
224
+ if (i->systems.empty()) {
225
+ output.AddNGram(i->line);
226
+ } else {
227
+ for (std::vector<size_t>::const_iterator j = i->systems.begin(); j != i->systems.end(); ++j) {
228
+ output.SingleAddNGram(*j, i->line);
229
+ }
230
+ }
231
+ }
232
+ annotated_.clear();
233
+ }
234
+
235
+ private:
236
+ struct Annotated {
237
+ // If this is empty, send to all systems.
238
+ // A filter should never send to all systems and send to a single one.
239
+ std::vector<size_t> systems;
240
+ StringPiece line;
241
+ };
242
+
243
+ StringPiece last_;
244
+
245
+ std::vector<Annotated> annotated_;
246
+ };
247
+
248
+ } // namespace lm
249
+
250
+ #endif // LM_FILTER_FORMAT_H
cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/phrase.cc ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "phrase.hh"
2
+
3
+ #include "format.hh"
4
+
5
+ #include <algorithm>
6
+ #include <functional>
7
+ #include <iostream>
8
+ #include <queue>
9
+ #include <string>
10
+ #include <vector>
11
+
12
+ #include <cctype>
13
+
14
+ namespace lm {
15
+ namespace phrase {
16
+
17
+ unsigned int ReadMultiple(std::istream &in, Substrings &out) {
18
+ bool sentence_content = false;
19
+ unsigned int sentence_id = 0;
20
+ std::vector<Hash> phrase;
21
+ std::string word;
22
+ while (in) {
23
+ char c;
24
+ // Gather a word.
25
+ while (!isspace(c = in.get()) && in) word += c;
26
+ // Treat EOF like a newline.
27
+ if (!in) c = '\n';
28
+ // Add the word to the phrase.
29
+ if (!word.empty()) {
30
+ phrase.push_back(util::MurmurHashNative(word.data(), word.size()));
31
+ word.clear();
32
+ }
33
+ if (c == ' ') continue;
34
+ // It's more than just a space. Close out the phrase.
35
+ if (!phrase.empty()) {
36
+ sentence_content = true;
37
+ out.AddPhrase(sentence_id, phrase.begin(), phrase.end());
38
+ phrase.clear();
39
+ }
40
+ if (c == '\t' || c == '\v') continue;
41
+ // It's more than a space or tab: a newline.
42
+ if (sentence_content) {
43
+ ++sentence_id;
44
+ sentence_content = false;
45
+ }
46
+ }
47
+ if (!in.eof()) in.exceptions(std::istream::failbit | std::istream::badbit);
48
+ return sentence_id + sentence_content;
49
+ }
50
+
51
+ namespace {
52
+ typedef unsigned int Sentence;
53
+ typedef std::vector<Sentence> Sentences;
54
+ } // namespace
55
+
56
+ namespace detail {
57
+
58
+ const StringPiece kEndSentence("</s>");
59
+
60
+ class Arc {
61
+ public:
62
+ Arc() {}
63
+
64
+ // For arcs from one vertex to another.
65
+ void SetPhrase(detail::Vertex &from, detail::Vertex &to, const Sentences &intersect) {
66
+ Set(to, intersect);
67
+ from_ = &from;
68
+ }
69
+
70
+ /* For arcs from before the n-gram begins to somewhere in the n-gram (right
71
+ * aligned). These have no from_ vertex; it implictly matches every
72
+ * sentence. This also handles when the n-gram is a substring of a phrase.
73
+ */
74
+ void SetRight(detail::Vertex &to, const Sentences &complete) {
75
+ Set(to, complete);
76
+ from_ = NULL;
77
+ }
78
+
79
+ Sentence Current() const {
80
+ return *current_;
81
+ }
82
+
83
+ bool Empty() const {
84
+ return current_ == last_;
85
+ }
86
+
87
+ /* When this function returns:
88
+ * If Empty() then there's nothing left from this intersection.
89
+ *
90
+ * If Current() == to then to is part of the intersection.
91
+ *
92
+ * Otherwise, Current() > to. In this case, to is not part of the
93
+ * intersection and neither is anything < Current(). To determine if
94
+ * any value >= Current() is in the intersection, call LowerBound again
95
+ * with the value.
96
+ */
97
+ void LowerBound(const Sentence to);
98
+
99
+ private:
100
+ void Set(detail::Vertex &to, const Sentences &sentences);
101
+
102
+ const Sentence *current_;
103
+ const Sentence *last_;
104
+ detail::Vertex *from_;
105
+ };
106
+
107
+ struct ArcGreater : public std::binary_function<const Arc *, const Arc *, bool> {
108
+ bool operator()(const Arc *first, const Arc *second) const {
109
+ return first->Current() > second->Current();
110
+ }
111
+ };
112
+
113
+ class Vertex {
114
+ public:
115
+ Vertex() : current_(0) {}
116
+
117
+ Sentence Current() const {
118
+ return current_;
119
+ }
120
+
121
+ bool Empty() const {
122
+ return incoming_.empty();
123
+ }
124
+
125
+ void LowerBound(const Sentence to);
126
+
127
+ private:
128
+ friend class Arc;
129
+
130
+ void AddIncoming(Arc *arc) {
131
+ if (!arc->Empty()) incoming_.push(arc);
132
+ }
133
+
134
+ unsigned int current_;
135
+ std::priority_queue<Arc*, std::vector<Arc*>, ArcGreater> incoming_;
136
+ };
137
+
138
+ void Arc::LowerBound(const Sentence to) {
139
+ current_ = std::lower_bound(current_, last_, to);
140
+ // If *current_ > to, don't advance from_. The intervening values of
141
+ // from_ may be useful for another one of its outgoing arcs.
142
+ if (!from_ || Empty() || (Current() > to)) return;
143
+ assert(Current() == to);
144
+ from_->LowerBound(to);
145
+ if (from_->Empty()) {
146
+ current_ = last_;
147
+ return;
148
+ }
149
+ assert(from_->Current() >= to);
150
+ if (from_->Current() > to) {
151
+ current_ = std::lower_bound(current_ + 1, last_, from_->Current());
152
+ }
153
+ }
154
+
155
+ void Arc::Set(Vertex &to, const Sentences &sentences) {
156
+ current_ = &*sentences.begin();
157
+ last_ = &*sentences.end();
158
+ to.AddIncoming(this);
159
+ }
160
+
161
+ void Vertex::LowerBound(const Sentence to) {
162
+ if (Empty()) return;
163
+ // Union lower bound.
164
+ while (true) {
165
+ Arc *top = incoming_.top();
166
+ if (top->Current() > to) {
167
+ current_ = top->Current();
168
+ return;
169
+ }
170
+ // If top->Current() == to, we still need to verify that's an actual
171
+ // element and not just a bound.
172
+ incoming_.pop();
173
+ top->LowerBound(to);
174
+ if (!top->Empty()) {
175
+ incoming_.push(top);
176
+ if (top->Current() == to) {
177
+ current_ = to;
178
+ return;
179
+ }
180
+ } else if (Empty()) {
181
+ return;
182
+ }
183
+ }
184
+ }
185
+
186
+ } // namespace detail
187
+
188
+ namespace {
189
+
190
+ void BuildGraph(const Substrings &phrase, const std::vector<Hash> &hashes, detail::Vertex *const vertices, detail::Arc *free_arc) {
191
+ using detail::Vertex;
192
+ using detail::Arc;
193
+ assert(!hashes.empty());
194
+
195
+ const Hash *const first_word = &*hashes.begin();
196
+ const Hash *const last_word = &*hashes.end() - 1;
197
+
198
+ Hash hash = 0;
199
+ const Sentences *found;
200
+ // Phrases starting at or before the first word in the n-gram.
201
+ {
202
+ Vertex *vertex = vertices;
203
+ for (const Hash *word = first_word; ; ++word, ++vertex) {
204
+ hash = util::MurmurHashNative(&hash, sizeof(uint64_t), *word);
205
+ // Now hash is [hashes.begin(), word].
206
+ if (word == last_word) {
207
+ if (phrase.FindSubstring(hash, found))
208
+ (free_arc++)->SetRight(*vertex, *found);
209
+ break;
210
+ }
211
+ if (!phrase.FindRight(hash, found)) break;
212
+ (free_arc++)->SetRight(*vertex, *found);
213
+ }
214
+ }
215
+
216
+ // Phrases starting at the second or later word in the n-gram.
217
+ Vertex *vertex_from = vertices;
218
+ for (const Hash *word_from = first_word + 1; word_from != &*hashes.end(); ++word_from, ++vertex_from) {
219
+ hash = 0;
220
+ Vertex *vertex_to = vertex_from + 1;
221
+ for (const Hash *word_to = word_from; ; ++word_to, ++vertex_to) {
222
+ // Notice that word_to and vertex_to have the same index.
223
+ hash = util::MurmurHashNative(&hash, sizeof(uint64_t), *word_to);
224
+ // Now hash covers [word_from, word_to].
225
+ if (word_to == last_word) {
226
+ if (phrase.FindLeft(hash, found))
227
+ (free_arc++)->SetPhrase(*vertex_from, *vertex_to, *found);
228
+ break;
229
+ }
230
+ if (!phrase.FindPhrase(hash, found)) break;
231
+ (free_arc++)->SetPhrase(*vertex_from, *vertex_to, *found);
232
+ }
233
+ }
234
+ }
235
+
236
+ } // namespace
237
+
238
+ namespace detail {
239
+
240
+ // Here instead of header due to forward declaration.
241
+ ConditionCommon::ConditionCommon(const Substrings &substrings) : substrings_(substrings) {}
242
+
243
+ // Rest of the variables are temporaries anyway
244
+ ConditionCommon::ConditionCommon(const ConditionCommon &from) : substrings_(from.substrings_) {}
245
+
246
+ ConditionCommon::~ConditionCommon() {}
247
+
248
+ detail::Vertex &ConditionCommon::MakeGraph() {
249
+ assert(!hashes_.empty());
250
+ vertices_.clear();
251
+ vertices_.resize(hashes_.size());
252
+ arcs_.clear();
253
+ // One for every substring.
254
+ arcs_.resize(((hashes_.size() + 1) * hashes_.size()) / 2);
255
+ BuildGraph(substrings_, hashes_, &*vertices_.begin(), &*arcs_.begin());
256
+ return vertices_[hashes_.size() - 1];
257
+ }
258
+
259
+ } // namespace detail
260
+
261
+ bool Union::Evaluate() {
262
+ detail::Vertex &last_vertex = MakeGraph();
263
+ unsigned int lower = 0;
264
+ while (true) {
265
+ last_vertex.LowerBound(lower);
266
+ if (last_vertex.Empty()) return false;
267
+ if (last_vertex.Current() == lower) return true;
268
+ lower = last_vertex.Current();
269
+ }
270
+ }
271
+
272
+ template <class Output> void Multiple::Evaluate(const StringPiece &line, Output &output) {
273
+ detail::Vertex &last_vertex = MakeGraph();
274
+ unsigned int lower = 0;
275
+ while (true) {
276
+ last_vertex.LowerBound(lower);
277
+ if (last_vertex.Empty()) return;
278
+ if (last_vertex.Current() == lower) {
279
+ output.SingleAddNGram(lower, line);
280
+ ++lower;
281
+ } else {
282
+ lower = last_vertex.Current();
283
+ }
284
+ }
285
+ }
286
+
287
+ template void Multiple::Evaluate<CountFormat::Multiple>(const StringPiece &line, CountFormat::Multiple &output);
288
+ template void Multiple::Evaluate<ARPAFormat::Multiple>(const StringPiece &line, ARPAFormat::Multiple &output);
289
+ template void Multiple::Evaluate<MultipleOutputBuffer>(const StringPiece &line, MultipleOutputBuffer &output);
290
+
291
+ } // namespace phrase
292
+ } // namespace lm
cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/phrase.hh ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef LM_FILTER_PHRASE_H
2
+ #define LM_FILTER_PHRASE_H
3
+
4
+ #include "../../util/murmur_hash.hh"
5
+ #include "../../util/string_piece.hh"
6
+ #include "../../util/tokenize_piece.hh"
7
+
8
+ #include <boost/unordered_map.hpp>
9
+
10
+ #include <iosfwd>
11
+ #include <vector>
12
+
13
+ #define LM_FILTER_PHRASE_METHOD(caps, lower) \
14
+ bool Find##caps(Hash key, const std::vector<unsigned int> *&out) const {\
15
+ Table::const_iterator i(table_.find(key));\
16
+ if (i==table_.end()) return false; \
17
+ out = &i->second.lower; \
18
+ return true; \
19
+ }
20
+
21
+ namespace lm {
22
+ namespace phrase {
23
+
24
+ typedef uint64_t Hash;
25
+
26
+ class Substrings {
27
+ private:
28
+ /* This is the value in a hash table where the key is a string. It indicates
29
+ * four sets of sentences:
30
+ * substring is sentences with a phrase containing the key as a substring.
31
+ * left is sentencess with a phrase that begins with the key (left aligned).
32
+ * right is sentences with a phrase that ends with the key (right aligned).
33
+ * phrase is sentences where the key is a phrase.
34
+ * Each set is encoded as a vector of sentence ids in increasing order.
35
+ */
36
+ struct SentenceRelation {
37
+ std::vector<unsigned int> substring, left, right, phrase;
38
+ };
39
+ /* Most of the CPU is hash table lookups, so let's not complicate it with
40
+ * vector equality comparisons. If a collision happens, the SentenceRelation
41
+ * structure will contain the union of sentence ids over the colliding strings.
42
+ * In that case, the filter will be slightly more permissive.
43
+ * The key here is the same as boost's hash of std::vector<std::string>.
44
+ */
45
+ typedef boost::unordered_map<Hash, SentenceRelation> Table;
46
+
47
+ public:
48
+ Substrings() {}
49
+
50
+ /* If the string isn't a substring of any phrase, return NULL. Otherwise,
51
+ * return a pointer to std::vector<unsigned int> listing sentences with
52
+ * matching phrases. This set may be empty for Left, Right, or Phrase.
53
+ * Example: const std::vector<unsigned int> *FindSubstring(Hash key)
54
+ */
55
+ LM_FILTER_PHRASE_METHOD(Substring, substring)
56
+ LM_FILTER_PHRASE_METHOD(Left, left)
57
+ LM_FILTER_PHRASE_METHOD(Right, right)
58
+ LM_FILTER_PHRASE_METHOD(Phrase, phrase)
59
+
60
+ #pragma GCC diagnostic ignored "-Wuninitialized" // end != finish so there's always an initialization
61
+ // sentence_id must be non-decreasing. Iterators are over words in the phrase.
62
+ template <class Iterator> void AddPhrase(unsigned int sentence_id, const Iterator &begin, const Iterator &end) {
63
+ // Iterate over all substrings.
64
+ for (Iterator start = begin; start != end; ++start) {
65
+ Hash hash = 0;
66
+ SentenceRelation *relation;
67
+ for (Iterator finish = start; finish != end; ++finish) {
68
+ hash = util::MurmurHashNative(&hash, sizeof(uint64_t), *finish);
69
+ // Now hash is of [start, finish].
70
+ relation = &table_[hash];
71
+ AppendSentence(relation->substring, sentence_id);
72
+ if (start == begin) AppendSentence(relation->left, sentence_id);
73
+ }
74
+ AppendSentence(relation->right, sentence_id);
75
+ if (start == begin) AppendSentence(relation->phrase, sentence_id);
76
+ }
77
+ }
78
+
79
+ private:
80
+ void AppendSentence(std::vector<unsigned int> &vec, unsigned int sentence_id) {
81
+ if (vec.empty() || vec.back() != sentence_id) vec.push_back(sentence_id);
82
+ }
83
+
84
+ Table table_;
85
+ };
86
+
87
+ // Read a file with one sentence per line containing tab-delimited phrases of
88
+ // space-separated words.
89
+ unsigned int ReadMultiple(std::istream &in, Substrings &out);
90
+
91
+ namespace detail {
92
+ extern const StringPiece kEndSentence;
93
+
94
+ template <class Iterator> void MakeHashes(Iterator i, const Iterator &end, std::vector<Hash> &hashes) {
95
+ hashes.clear();
96
+ if (i == end) return;
97
+ // TODO: check strict phrase boundaries after <s> and before </s>. For now, just skip tags.
98
+ if ((i->data()[0] == '<') && (i->data()[i->size() - 1] == '>')) {
99
+ ++i;
100
+ }
101
+ for (; i != end && (*i != kEndSentence); ++i) {
102
+ hashes.push_back(util::MurmurHashNative(i->data(), i->size()));
103
+ }
104
+ }
105
+
106
+ class Vertex;
107
+ class Arc;
108
+
109
+ class ConditionCommon {
110
+ protected:
111
+ ConditionCommon(const Substrings &substrings);
112
+ ConditionCommon(const ConditionCommon &from);
113
+
114
+ ~ConditionCommon();
115
+
116
+ detail::Vertex &MakeGraph();
117
+
118
+ // Temporaries in PassNGram and Evaluate to avoid reallocation.
119
+ std::vector<Hash> hashes_;
120
+
121
+ private:
122
+ std::vector<detail::Vertex> vertices_;
123
+ std::vector<detail::Arc> arcs_;
124
+
125
+ const Substrings &substrings_;
126
+ };
127
+
128
+ } // namespace detail
129
+
130
+ class Union : public detail::ConditionCommon {
131
+ public:
132
+ explicit Union(const Substrings &substrings) : detail::ConditionCommon(substrings) {}
133
+
134
+ template <class Iterator> bool PassNGram(const Iterator &begin, const Iterator &end) {
135
+ detail::MakeHashes(begin, end, hashes_);
136
+ return hashes_.empty() || Evaluate();
137
+ }
138
+
139
+ private:
140
+ bool Evaluate();
141
+ };
142
+
143
+ class Multiple : public detail::ConditionCommon {
144
+ public:
145
+ explicit Multiple(const Substrings &substrings) : detail::ConditionCommon(substrings) {}
146
+
147
+ template <class Iterator, class Output> void AddNGram(const Iterator &begin, const Iterator &end, const StringPiece &line, Output &output) {
148
+ detail::MakeHashes(begin, end, hashes_);
149
+ if (hashes_.empty()) {
150
+ output.AddNGram(line);
151
+ } else {
152
+ Evaluate(line, output);
153
+ }
154
+ }
155
+
156
+ template <class Output> void AddNGram(const StringPiece &ngram, const StringPiece &line, Output &output) {
157
+ AddNGram(util::TokenIter<util::SingleCharacter, true>(ngram, ' '), util::TokenIter<util::SingleCharacter, true>::end(), line, output);
158
+ }
159
+
160
+ void Flush() const {}
161
+
162
+ private:
163
+ template <class Output> void Evaluate(const StringPiece &line, Output &output);
164
+ };
165
+
166
+ } // namespace phrase
167
+ } // namespace lm
168
+ #endif // LM_FILTER_PHRASE_H
cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/phrase_table_vocab_main.cc ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "../../util/file_stream.hh"
2
+ #include "../../util/file_piece.hh"
3
+ #include "../../util/murmur_hash.hh"
4
+ #include "../../util/pool.hh"
5
+ #include "../../util/string_piece.hh"
6
+ #include "../../util/string_piece_hash.hh"
7
+ #include "../../util/tokenize_piece.hh"
8
+
9
+ #include <boost/unordered_map.hpp>
10
+ #include <boost/unordered_set.hpp>
11
+
12
+ #include <cstddef>
13
+ #include <vector>
14
+
15
+ namespace {
16
+
17
+ struct MutablePiece {
18
+ mutable StringPiece behind;
19
+ bool operator==(const MutablePiece &other) const {
20
+ return behind == other.behind;
21
+ }
22
+ };
23
+
24
+ std::size_t hash_value(const MutablePiece &m) {
25
+ return hash_value(m.behind);
26
+ }
27
+
28
+ class InternString {
29
+ public:
30
+ const char *Add(StringPiece str) {
31
+ MutablePiece mut;
32
+ mut.behind = str;
33
+ std::pair<boost::unordered_set<MutablePiece>::iterator, bool> res(strs_.insert(mut));
34
+ if (res.second) {
35
+ void *mem = backing_.Allocate(str.size() + 1);
36
+ memcpy(mem, str.data(), str.size());
37
+ static_cast<char*>(mem)[str.size()] = 0;
38
+ res.first->behind = StringPiece(static_cast<char*>(mem), str.size());
39
+ }
40
+ return res.first->behind.data();
41
+ }
42
+
43
+ private:
44
+ util::Pool backing_;
45
+ boost::unordered_set<MutablePiece> strs_;
46
+ };
47
+
48
+ class TargetWords {
49
+ public:
50
+ void Introduce(StringPiece source) {
51
+ vocab_.resize(vocab_.size() + 1);
52
+ std::vector<unsigned int> temp(1, vocab_.size() - 1);
53
+ Add(temp, source);
54
+ }
55
+
56
+ void Add(const std::vector<unsigned int> &sentences, StringPiece target) {
57
+ if (sentences.empty()) return;
58
+ interns_.clear();
59
+ for (util::TokenIter<util::SingleCharacter, true> i(target, ' '); i; ++i) {
60
+ interns_.push_back(intern_.Add(*i));
61
+ }
62
+ for (std::vector<unsigned int>::const_iterator i(sentences.begin()); i != sentences.end(); ++i) {
63
+ boost::unordered_set<const char *> &vocab = vocab_[*i];
64
+ for (std::vector<const char *>::const_iterator j = interns_.begin(); j != interns_.end(); ++j) {
65
+ vocab.insert(*j);
66
+ }
67
+ }
68
+ }
69
+
70
+ void Print() const {
71
+ util::FileStream out(1);
72
+ for (std::vector<boost::unordered_set<const char *> >::const_iterator i = vocab_.begin(); i != vocab_.end(); ++i) {
73
+ for (boost::unordered_set<const char *>::const_iterator j = i->begin(); j != i->end(); ++j) {
74
+ out << *j << ' ';
75
+ }
76
+ out << '\n';
77
+ }
78
+ }
79
+
80
+ private:
81
+ InternString intern_;
82
+
83
+ std::vector<boost::unordered_set<const char *> > vocab_;
84
+
85
+ // Temporary in Add.
86
+ std::vector<const char *> interns_;
87
+ };
88
+
89
+ class Input {
90
+ public:
91
+ explicit Input(std::size_t max_length)
92
+ : max_length_(max_length), sentence_id_(0), empty_() {}
93
+
94
+ void AddSentence(StringPiece sentence, TargetWords &targets) {
95
+ canonical_.clear();
96
+ starts_.clear();
97
+ starts_.push_back(0);
98
+ for (util::TokenIter<util::AnyCharacter, true> i(sentence, StringPiece("\0 \t", 3)); i; ++i) {
99
+ canonical_.append(i->data(), i->size());
100
+ canonical_ += ' ';
101
+ starts_.push_back(canonical_.size());
102
+ }
103
+ targets.Introduce(canonical_);
104
+ for (std::size_t i = 0; i < starts_.size() - 1; ++i) {
105
+ std::size_t subtract = starts_[i];
106
+ const char *start = &canonical_[subtract];
107
+ for (std::size_t j = i + 1; j < std::min(starts_.size(), i + max_length_ + 1); ++j) {
108
+ map_[util::MurmurHash64A(start, &canonical_[starts_[j]] - start - 1)].push_back(sentence_id_);
109
+ }
110
+ }
111
+ ++sentence_id_;
112
+ }
113
+
114
+ // Assumes single space-delimited phrase with no space at the beginning or end.
115
+ const std::vector<unsigned int> &Matches(StringPiece phrase) const {
116
+ Map::const_iterator i = map_.find(util::MurmurHash64A(phrase.data(), phrase.size()));
117
+ return i == map_.end() ? empty_ : i->second;
118
+ }
119
+
120
+ private:
121
+ const std::size_t max_length_;
122
+
123
+ // hash of phrase is the key, array of sentences is the value.
124
+ typedef boost::unordered_map<uint64_t, std::vector<unsigned int> > Map;
125
+ Map map_;
126
+
127
+ std::size_t sentence_id_;
128
+
129
+ // Temporaries in AddSentence.
130
+ std::string canonical_;
131
+ std::vector<std::size_t> starts_;
132
+
133
+ const std::vector<unsigned int> empty_;
134
+ };
135
+
136
+ } // namespace
137
+
138
+ int main(int argc, char *argv[]) {
139
+ if (argc != 2) {
140
+ std::cerr << "Expected source text on the command line" << std::endl;
141
+ return 1;
142
+ }
143
+ Input input(7);
144
+ TargetWords targets;
145
+ try {
146
+ util::FilePiece inputs(argv[1], &std::cerr);
147
+ while (true)
148
+ input.AddSentence(inputs.ReadLine(), targets);
149
+ } catch (const util::EndOfFileException &e) {}
150
+
151
+ util::FilePiece table(0, NULL, &std::cerr);
152
+ StringPiece line;
153
+ const StringPiece pipes("|||");
154
+ while (true) {
155
+ try {
156
+ line = table.ReadLine();
157
+ } catch (const util::EndOfFileException &e) { break; }
158
+ util::TokenIter<util::MultiCharacter> it(line, pipes);
159
+ StringPiece source(*it);
160
+ if (!source.empty() && source[source.size() - 1] == ' ')
161
+ source.remove_suffix(1);
162
+ targets.Add(input.Matches(source), *++it);
163
+ }
164
+ targets.Print();
165
+ }
cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/thread.hh ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef LM_FILTER_THREAD_H
2
+ #define LM_FILTER_THREAD_H
3
+
4
+ #include "../../util/thread_pool.hh"
5
+
6
+ #include <boost/utility/in_place_factory.hpp>
7
+
8
+ #include <deque>
9
+ #include <stack>
10
+
11
+ namespace lm {
12
+
13
+ template <class OutputBuffer> class ThreadBatch {
14
+ public:
15
+ ThreadBatch() {}
16
+
17
+ void Reserve(size_t size) {
18
+ input_.Reserve(size);
19
+ output_.Reserve(size);
20
+ }
21
+
22
+ // File reading thread.
23
+ InputBuffer &Fill(uint64_t sequence) {
24
+ sequence_ = sequence;
25
+ // Why wait until now to clear instead of after output? free in the same
26
+ // thread as allocated.
27
+ input_.Clear();
28
+ return input_;
29
+ }
30
+
31
+ // Filter worker thread.
32
+ template <class Filter> void CallFilter(Filter &filter) {
33
+ input_.CallFilter(filter, output_);
34
+ }
35
+
36
+ uint64_t Sequence() const { return sequence_; }
37
+
38
+ // File writing thread.
39
+ template <class RealOutput> void Flush(RealOutput &output) {
40
+ output_.Flush(output);
41
+ }
42
+
43
+ private:
44
+ InputBuffer input_;
45
+ OutputBuffer output_;
46
+
47
+ uint64_t sequence_;
48
+ };
49
+
50
+ template <class Batch, class Filter> class FilterWorker {
51
+ public:
52
+ typedef Batch *Request;
53
+
54
+ FilterWorker(const Filter &filter, util::PCQueue<Request> &done) : filter_(filter), done_(done) {}
55
+
56
+ void operator()(Request request) {
57
+ request->CallFilter(filter_);
58
+ done_.Produce(request);
59
+ }
60
+
61
+ private:
62
+ Filter filter_;
63
+
64
+ util::PCQueue<Request> &done_;
65
+ };
66
+
67
+ // There should only be one OutputWorker.
68
+ template <class Batch, class Output> class OutputWorker {
69
+ public:
70
+ typedef Batch *Request;
71
+
72
+ OutputWorker(Output &output, util::PCQueue<Request> &done) : output_(output), done_(done), base_sequence_(0) {}
73
+
74
+ void operator()(Request request) {
75
+ assert(request->Sequence() >= base_sequence_);
76
+ // Assemble the output in order.
77
+ uint64_t pos = request->Sequence() - base_sequence_;
78
+ if (pos >= ordering_.size()) {
79
+ ordering_.resize(pos + 1, NULL);
80
+ }
81
+ ordering_[pos] = request;
82
+ while (!ordering_.empty() && ordering_.front()) {
83
+ ordering_.front()->Flush(output_);
84
+ done_.Produce(ordering_.front());
85
+ ordering_.pop_front();
86
+ ++base_sequence_;
87
+ }
88
+ }
89
+
90
+ private:
91
+ Output &output_;
92
+
93
+ util::PCQueue<Request> &done_;
94
+
95
+ std::deque<Request> ordering_;
96
+
97
+ uint64_t base_sequence_;
98
+ };
99
+
100
+ template <class Filter, class OutputBuffer, class RealOutput> class Controller : boost::noncopyable {
101
+ private:
102
+ typedef ThreadBatch<OutputBuffer> Batch;
103
+
104
+ public:
105
+ Controller(size_t batch_size, size_t queue, size_t workers, const Filter &filter, RealOutput &output)
106
+ : batch_size_(batch_size), queue_size_(queue),
107
+ batches_(queue),
108
+ to_read_(queue),
109
+ output_(queue, 1, boost::in_place(boost::ref(output), boost::ref(to_read_)), NULL),
110
+ filter_(queue, workers, boost::in_place(boost::ref(filter), boost::ref(output_.In())), NULL),
111
+ sequence_(0) {
112
+ for (size_t i = 0; i < queue; ++i) {
113
+ batches_[i].Reserve(batch_size);
114
+ local_read_.push(&batches_[i]);
115
+ }
116
+ NewInput();
117
+ }
118
+
119
+ void AddNGram(const StringPiece &ngram, const StringPiece &line, RealOutput &output) {
120
+ input_->AddNGram(ngram, line, output);
121
+ if (input_->Size() == batch_size_) {
122
+ FlushInput();
123
+ NewInput();
124
+ }
125
+ }
126
+
127
+ void Flush() {
128
+ FlushInput();
129
+ while (local_read_.size() < queue_size_) {
130
+ MoveRead();
131
+ }
132
+ NewInput();
133
+ }
134
+
135
+ private:
136
+ void FlushInput() {
137
+ if (input_->Empty()) return;
138
+ filter_.Produce(local_read_.top());
139
+ local_read_.pop();
140
+ if (local_read_.empty()) MoveRead();
141
+ }
142
+
143
+ void NewInput() {
144
+ input_ = &local_read_.top()->Fill(sequence_++);
145
+ }
146
+
147
+ void MoveRead() {
148
+ local_read_.push(to_read_.Consume());
149
+ }
150
+
151
+ const size_t batch_size_;
152
+ const size_t queue_size_;
153
+
154
+ std::vector<Batch> batches_;
155
+
156
+ util::PCQueue<Batch*> to_read_;
157
+ std::stack<Batch*> local_read_;
158
+ util::ThreadPool<OutputWorker<Batch, RealOutput> > output_;
159
+ util::ThreadPool<FilterWorker<Batch, Filter> > filter_;
160
+
161
+ uint64_t sequence_;
162
+ InputBuffer *input_;
163
+ };
164
+
165
+ } // namespace lm
166
+
167
+ #endif // LM_FILTER_THREAD_H
cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/vocab.cc ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "vocab.hh"
2
+
3
+ #include <istream>
4
+ #include <iostream>
5
+
6
+ #include <cctype>
7
+
8
+ namespace lm {
9
+ namespace vocab {
10
+
11
+ void ReadSingle(std::istream &in, boost::unordered_set<std::string> &out) {
12
+ in.exceptions(std::istream::badbit);
13
+ std::string word;
14
+ while (in >> word) {
15
+ out.insert(word);
16
+ }
17
+ }
18
+
19
+ namespace {
20
+ bool IsLineEnd(std::istream &in) {
21
+ int got;
22
+ do {
23
+ got = in.get();
24
+ if (!in) return true;
25
+ if (got == '\n') return true;
26
+ } while (isspace(got));
27
+ in.unget();
28
+ return false;
29
+ }
30
+ }// namespace
31
+
32
+ // Read space separated words in enter separated lines. These lines can be
33
+ // very long, so don't read an entire line at a time.
34
+ unsigned int ReadMultiple(std::istream &in, boost::unordered_map<std::string, std::vector<unsigned int> > &out) {
35
+ in.exceptions(std::istream::badbit);
36
+ unsigned int sentence = 0;
37
+ bool used_id = false;
38
+ std::string word;
39
+ while (in >> word) {
40
+ used_id = true;
41
+ std::vector<unsigned int> &posting = out[word];
42
+ if (posting.empty() || (posting.back() != sentence))
43
+ posting.push_back(sentence);
44
+ if (IsLineEnd(in)) {
45
+ ++sentence;
46
+ used_id = false;
47
+ }
48
+ }
49
+ return sentence + used_id;
50
+ }
51
+
52
+ } // namespace vocab
53
+ } // namespace lm
cc-multilingual-main/cc_net/third_party/kenlm/lm/filter/vocab.hh ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef LM_FILTER_VOCAB_H
2
+ #define LM_FILTER_VOCAB_H
3
+
4
+ // Vocabulary-based filters for language models.
5
+
6
+ #include "../../util/multi_intersection.hh"
7
+ #include "../../util/string_piece.hh"
8
+ #include "../../util/string_piece_hash.hh"
9
+ #include "../../util/tokenize_piece.hh"
10
+
11
+ #include <boost/noncopyable.hpp>
12
+ #include <boost/range/iterator_range.hpp>
13
+ #include <boost/unordered/unordered_map.hpp>
14
+ #include <boost/unordered/unordered_set.hpp>
15
+
16
+ #include <string>
17
+ #include <vector>
18
+
19
+ namespace lm {
20
+ namespace vocab {
21
+
22
+ void ReadSingle(std::istream &in, boost::unordered_set<std::string> &out);
23
+
24
+ // Read one sentence vocabulary per line. Return the number of sentences.
25
+ unsigned int ReadMultiple(std::istream &in, boost::unordered_map<std::string, std::vector<unsigned int> > &out);
26
+
27
+ /* Is this a special tag like <s> or <UNK>? This actually includes anything
28
+ * surrounded with < and >, which most tokenizers separate for real words, so
29
+ * this should not catch real words as it looks at a single token.
30
+ */
31
+ inline bool IsTag(const StringPiece &value) {
32
+ // The parser should never give an empty string.
33
+ assert(!value.empty());
34
+ return (value.data()[0] == '<' && value.data()[value.size() - 1] == '>');
35
+ }
36
+
37
+ class Single {
38
+ public:
39
+ typedef boost::unordered_set<std::string> Words;
40
+
41
+ explicit Single(const Words &vocab) : vocab_(vocab) {}
42
+
43
+ template <class Iterator> bool PassNGram(const Iterator &begin, const Iterator &end) {
44
+ for (Iterator i = begin; i != end; ++i) {
45
+ if (IsTag(*i)) continue;
46
+ if (FindStringPiece(vocab_, *i) == vocab_.end()) return false;
47
+ }
48
+ return true;
49
+ }
50
+
51
+ private:
52
+ const Words &vocab_;
53
+ };
54
+
55
+ class Union {
56
+ public:
57
+ typedef boost::unordered_map<std::string, std::vector<unsigned int> > Words;
58
+
59
+ explicit Union(const Words &vocabs) : vocabs_(vocabs) {}
60
+
61
+ template <class Iterator> bool PassNGram(const Iterator &begin, const Iterator &end) {
62
+ sets_.clear();
63
+
64
+ for (Iterator i(begin); i != end; ++i) {
65
+ if (IsTag(*i)) continue;
66
+ Words::const_iterator found(FindStringPiece(vocabs_, *i));
67
+ if (vocabs_.end() == found) return false;
68
+ sets_.push_back(boost::iterator_range<const unsigned int*>(&*found->second.begin(), &*found->second.end()));
69
+ }
70
+ return (sets_.empty() || util::FirstIntersection(sets_));
71
+ }
72
+
73
+ private:
74
+ const Words &vocabs_;
75
+
76
+ std::vector<boost::iterator_range<const unsigned int*> > sets_;
77
+ };
78
+
79
+ class Multiple {
80
+ public:
81
+ typedef boost::unordered_map<std::string, std::vector<unsigned int> > Words;
82
+
83
+ Multiple(const Words &vocabs) : vocabs_(vocabs) {}
84
+
85
+ private:
86
+ // Callback from AllIntersection that does AddNGram.
87
+ template <class Output> class Callback {
88
+ public:
89
+ Callback(Output &out, const StringPiece &line) : out_(out), line_(line) {}
90
+
91
+ void operator()(unsigned int index) {
92
+ out_.SingleAddNGram(index, line_);
93
+ }
94
+
95
+ private:
96
+ Output &out_;
97
+ const StringPiece &line_;
98
+ };
99
+
100
+ public:
101
+ template <class Iterator, class Output> void AddNGram(const Iterator &begin, const Iterator &end, const StringPiece &line, Output &output) {
102
+ sets_.clear();
103
+ for (Iterator i(begin); i != end; ++i) {
104
+ if (IsTag(*i)) continue;
105
+ Words::const_iterator found(FindStringPiece(vocabs_, *i));
106
+ if (vocabs_.end() == found) return;
107
+ sets_.push_back(boost::iterator_range<const unsigned int*>(&*found->second.begin(), &*found->second.end()));
108
+ }
109
+ if (sets_.empty()) {
110
+ output.AddNGram(line);
111
+ return;
112
+ }
113
+
114
+ Callback<Output> cb(output, line);
115
+ util::AllIntersection(sets_, cb);
116
+ }
117
+
118
+ template <class Output> void AddNGram(const StringPiece &ngram, const StringPiece &line, Output &output) {
119
+ AddNGram(util::TokenIter<util::SingleCharacter, true>(ngram, ' '), util::TokenIter<util::SingleCharacter, true>::end(), line, output);
120
+ }
121
+
122
+ void Flush() const {}
123
+
124
+ private:
125
+ const Words &vocabs_;
126
+
127
+ std::vector<boost::iterator_range<const unsigned int*> > sets_;
128
+ };
129
+
130
+ } // namespace vocab
131
+ } // namespace lm
132
+
133
+ #endif // LM_FILTER_VOCAB_H
cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/CMakeLists.txt ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Eigen3 less than 3.1.0 has a race condition: http://eigen.tuxfamily.org/bz/show_bug.cgi?id=466
2
+
3
+ if(ENABLE_INTERPOLATE)
4
+ find_package(Eigen3 3.1.0 CONFIG REQUIRED)
5
+ include_directories(${EIGEN3_INCLUDE_DIR})
6
+
7
+ set(KENLM_INTERPOLATE_SOURCE
8
+ backoff_reunification.cc
9
+ bounded_sequence_encoding.cc
10
+ merge_probabilities.cc
11
+ merge_vocab.cc
12
+ normalize.cc
13
+ pipeline.cc
14
+ split_worker.cc
15
+ tune_derivatives.cc
16
+ tune_instances.cc
17
+ tune_weights.cc
18
+ universal_vocab.cc)
19
+
20
+ add_library(kenlm_interpolate ${KENLM_INTERPOLATE_SOURCE})
21
+ target_link_libraries(kenlm_interpolate PUBLIC kenlm Eigen3::Eigen)
22
+ # Since headers are relative to `include/kenlm` at install time, not just `include`
23
+ target_include_directories(kenlm_interpolate PUBLIC $<INSTALL_INTERFACE:include/kenlm>)
24
+
25
+
26
+ find_package(OpenMP)
27
+ if (OPENMP_CXX_FOUND)
28
+ target_link_libraries(kenlm_interpolate PUBLIC OpenMP::OpenMP_CXX)
29
+ endif()
30
+
31
+
32
+ set(KENLM_INTERPOLATE_EXES
33
+ interpolate
34
+ streaming_example)
35
+
36
+ set(KENLM_INTERPOLATE_LIBS
37
+ kenlm_interpolate)
38
+
39
+ AddExes(EXES ${KENLM_INTERPOLATE_EXES}
40
+ LIBRARIES ${KENLM_INTERPOLATE_LIBS})
41
+
42
+ install(
43
+ TARGETS kenlm_interpolate
44
+ EXPORT kenlmTargets
45
+ RUNTIME DESTINATION bin
46
+ LIBRARY DESTINATION lib
47
+ ARCHIVE DESTINATION lib
48
+ INCLUDES DESTINATION include
49
+ )
50
+
51
+ if(BUILD_TESTING)
52
+ AddTests(TESTS backoff_reunification_test bounded_sequence_encoding_test merge_vocab_test normalize_test tune_derivatives_test
53
+ LIBRARIES ${KENLM_INTERPOLATE_LIBS} Threads::Threads)
54
+
55
+ # tune_instances_test needs an extra command line parameter
56
+ KenLMAddTest(TEST tune_instances_test
57
+ LIBRARIES ${KENLM_INTERPOLATE_LIBS}
58
+ TEST_ARGS -- ${CMAKE_CURRENT_SOURCE_DIR}/../common/test_data)
59
+ endif()
60
+ endif()
cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/backoff_matrix.hh ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef LM_INTERPOLATE_BACKOFF_MATRIX_H
2
+ #define LM_INTERPOLATE_BACKOFF_MATRIX_H
3
+
4
+ #include <cstddef>
5
+ #include <vector>
6
+
7
+ namespace lm { namespace interpolate {
8
+
9
+ class BackoffMatrix {
10
+ public:
11
+ BackoffMatrix(std::size_t num_models, std::size_t max_order)
12
+ : max_order_(max_order), backing_(num_models * max_order) {}
13
+
14
+ float &Backoff(std::size_t model, std::size_t order_minus_1) {
15
+ return backing_[model * max_order_ + order_minus_1];
16
+ }
17
+
18
+ float Backoff(std::size_t model, std::size_t order_minus_1) const {
19
+ return backing_[model * max_order_ + order_minus_1];
20
+ }
21
+
22
+ private:
23
+ const std::size_t max_order_;
24
+ std::vector<float> backing_;
25
+ };
26
+
27
+ }} // namespaces
28
+
29
+ #endif // LM_INTERPOLATE_BACKOFF_MATRIX_H
cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/backoff_reunification_test.cc ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "backoff_reunification.hh"
2
+ #include "../common/ngram_stream.hh"
3
+
4
+ #define BOOST_TEST_MODULE InterpolateBackoffReunificationTest
5
+ #include <boost/test/unit_test.hpp>
6
+
7
+ namespace lm {
8
+ namespace interpolate {
9
+
10
+ namespace {
11
+
12
+ // none of this input actually makes sense, all we care about is making
13
+ // sure the merging works
14
+ template <uint8_t N>
15
+ struct Gram {
16
+ WordIndex ids[N];
17
+ float prob;
18
+ float boff;
19
+ };
20
+
21
+ template <uint8_t N>
22
+ struct Grams {
23
+ const static Gram<N> grams[];
24
+ };
25
+
26
+ template <>
27
+ const Gram<1> Grams<1>::grams[]
28
+ = {{{0}, -0.1f, -0.1f}, {{1}, -0.4f, -0.2f}, {{2}, -0.5f, -0.1f}};
29
+
30
+ template <>
31
+ const Gram<2> Grams<2>::grams[] = {{{0, 0}, -0.05f, -0.05f},
32
+ {{1, 0}, -0.05f, -0.02f},
33
+ {{1, 1}, -0.2f, -0.04f},
34
+ {{2, 2}, -0.2f, -0.01f}};
35
+
36
+ template <>
37
+ const Gram<3> Grams<3>::grams[] = {{{0, 0, 0}, -0.001f, -0.005f},
38
+ {{1, 0, 0}, -0.001f, -0.002f},
39
+ {{2, 0, 0}, -0.001f, -0.003f},
40
+ {{0, 1, 0}, -0.1f, -0.008f},
41
+ {{1, 1, 0}, -0.1f, -0.09f},
42
+ {{1, 1, 1}, -0.2f, -0.08f}};
43
+
44
+ template <uint8_t N>
45
+ class WriteInput {
46
+ public:
47
+ void Run(const util::stream::ChainPosition &position) {
48
+ lm::NGramStream<float> output(position);
49
+
50
+ for (std::size_t i = 0; i < sizeof(Grams<N>::grams) / sizeof(Gram<N>);
51
+ ++i, ++output) {
52
+ std::copy(Grams<N>::grams[i].ids, Grams<N>::grams[i].ids + N,
53
+ output->begin());
54
+ output->Value() = Grams<N>::grams[i].prob;
55
+ }
56
+ output.Poison();
57
+ }
58
+ };
59
+
60
+ template <uint8_t N>
61
+ class WriteBackoffs {
62
+ public:
63
+ void Run(const util::stream::ChainPosition &position) {
64
+ util::stream::Stream output(position);
65
+
66
+ for (std::size_t i = 0; i < sizeof(Grams<N>::grams) / sizeof(Gram<N>);
67
+ ++i, ++output) {
68
+ *reinterpret_cast<float *>(output.Get()) = Grams<N>::grams[i].boff;
69
+ }
70
+ output.Poison();
71
+ }
72
+ };
73
+
74
+ template <uint8_t N>
75
+ class CheckOutput {
76
+ public:
77
+ void Run(const util::stream::ChainPosition &position) {
78
+ lm::NGramStream<ProbBackoff> stream(position);
79
+
80
+ std::size_t i = 0;
81
+ for (; stream; ++stream, ++i) {
82
+ std::stringstream ss;
83
+ for (WordIndex *idx = stream->begin(); idx != stream->end(); ++idx)
84
+ ss << "(" << *idx << ")";
85
+
86
+ BOOST_CHECK(std::equal(stream->begin(), stream->end(), Grams<N>::grams[i].ids));
87
+ //"Mismatched id in CheckOutput<" << (int)N << ">: " << ss.str();
88
+
89
+ BOOST_CHECK_EQUAL(stream->Value().prob, Grams<N>::grams[i].prob);
90
+ /* "Mismatched probability in CheckOutput<"
91
+ << (int)N << ">, got " << stream->Value().prob
92
+ << ", expected " << Grams<N>::grams[i].prob;*/
93
+
94
+ BOOST_CHECK_EQUAL(stream->Value().backoff, Grams<N>::grams[i].boff);
95
+ /* "Mismatched backoff in CheckOutput<"
96
+ << (int)N << ">, got " << stream->Value().backoff
97
+ << ", expected " << Grams<N>::grams[i].boff);*/
98
+ }
99
+ BOOST_CHECK_EQUAL(i , sizeof(Grams<N>::grams) / sizeof(Gram<N>));
100
+ /* "Did not get correct number of "
101
+ << (int)N << "-grams: expected "
102
+ << sizeof(Grams<N>::grams) / sizeof(Gram<N>)
103
+ << ", got " << i;*/
104
+ }
105
+ };
106
+ }
107
+
108
+ BOOST_AUTO_TEST_CASE(BackoffReunificationTest) {
109
+ util::stream::ChainConfig config;
110
+ config.total_memory = 100;
111
+ config.block_count = 1;
112
+
113
+ util::stream::Chains prob_chains(3);
114
+ config.entry_size = NGram<float>::TotalSize(1);
115
+ prob_chains.push_back(config);
116
+ prob_chains.back() >> WriteInput<1>();
117
+
118
+ config.entry_size = NGram<float>::TotalSize(2);
119
+ prob_chains.push_back(config);
120
+ prob_chains.back() >> WriteInput<2>();
121
+
122
+ config.entry_size = NGram<float>::TotalSize(3);
123
+ prob_chains.push_back(config);
124
+ prob_chains.back() >> WriteInput<3>();
125
+
126
+ util::stream::Chains boff_chains(3);
127
+ config.entry_size = sizeof(float);
128
+ boff_chains.push_back(config);
129
+ boff_chains.back() >> WriteBackoffs<1>();
130
+
131
+ boff_chains.push_back(config);
132
+ boff_chains.back() >> WriteBackoffs<2>();
133
+
134
+ boff_chains.push_back(config);
135
+ boff_chains.back() >> WriteBackoffs<3>();
136
+
137
+ util::stream::ChainPositions prob_pos(prob_chains);
138
+ util::stream::ChainPositions boff_pos(boff_chains);
139
+
140
+ util::stream::Chains output_chains(3);
141
+ for (std::size_t i = 0; i < 3; ++i) {
142
+ config.entry_size = NGram<ProbBackoff>::TotalSize(i + 1);
143
+ output_chains.push_back(config);
144
+ }
145
+
146
+ ReunifyBackoff(prob_pos, boff_pos, output_chains);
147
+
148
+ output_chains[0] >> CheckOutput<1>();
149
+ output_chains[1] >> CheckOutput<2>();
150
+ output_chains[2] >> CheckOutput<3>();
151
+
152
+ prob_chains >> util::stream::kRecycle;
153
+ boff_chains >> util::stream::kRecycle;
154
+
155
+ output_chains.Wait();
156
+ }
157
+ }
158
+ }
cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/bounded_sequence_encoding_test.cc ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "bounded_sequence_encoding.hh"
2
+
3
+ #include "../../util/scoped.hh"
4
+
5
+ #define BOOST_TEST_MODULE BoundedSequenceEncodingTest
6
+ #include <boost/test/unit_test.hpp>
7
+
8
+ namespace lm {
9
+ namespace interpolate {
10
+ namespace {
11
+
12
+ BOOST_AUTO_TEST_CASE(Simple) {
13
+ unsigned char bounds[] = {2};
14
+ BoundedSequenceEncoding enc(bounds, bounds + 1);
15
+ util::scoped_malloc backing(util::MallocOrThrow(enc.EncodedLength()));
16
+ unsigned char input = 1;
17
+ enc.Encode(&input, backing.get());
18
+ unsigned char output;
19
+ enc.Decode(backing.get(), &output);
20
+ BOOST_CHECK_EQUAL(1, output);
21
+ }
22
+
23
+ void ExhaustiveTest(unsigned char *bound_begin, unsigned char *bound_end) {
24
+ BoundedSequenceEncoding enc(bound_begin, bound_end);
25
+ util::scoped_malloc backing(util::MallocOrThrow(enc.EncodedLength()));
26
+ std::vector<unsigned char> values(bound_end - bound_begin),
27
+ out(bound_end - bound_begin);
28
+ while (true) {
29
+ enc.Encode(&values[0], backing.get());
30
+ enc.Decode(backing.get(), &out[0]);
31
+ for (std::size_t i = 0; i != values.size(); ++i) {
32
+ BOOST_CHECK_EQUAL(values[i], out[i]);
33
+ }
34
+ for (std::size_t i = 0;; ++i) {
35
+ if (i == values.size()) return;
36
+ ++values[i];
37
+ if (values[i] < bound_begin[i]) break;
38
+ values[i] = 0;
39
+ }
40
+ }
41
+ }
42
+
43
+ void CheckEncodeDecode(unsigned char *bounds, unsigned char *input,
44
+ unsigned char *output, std::size_t len) {
45
+ BoundedSequenceEncoding encoder(bounds, bounds + len);
46
+ util::scoped_malloc backing(util::MallocOrThrow(encoder.EncodedLength()));
47
+
48
+ encoder.Encode(input, backing.get());
49
+ encoder.Decode(backing.get(), output);
50
+
51
+ for (std::size_t i = 0; i < len; ++i) {
52
+ BOOST_CHECK_EQUAL(input[i], output[i]);
53
+ }
54
+ }
55
+
56
+ BOOST_AUTO_TEST_CASE(Exhaustive) {
57
+ unsigned char bounds[] = {5, 2, 3, 9, 7, 20, 8};
58
+ ExhaustiveTest(bounds, bounds + sizeof(bounds) / sizeof(unsigned char));
59
+ }
60
+
61
+ BOOST_AUTO_TEST_CASE(LessThan64) {
62
+ unsigned char bounds[] = {255, 255, 255, 255, 255, 255, 255, 3};
63
+ unsigned char input[] = {172, 183, 254, 187, 96, 87, 65, 2};
64
+ unsigned char output[] = {0, 0, 0, 0, 0, 0, 0, 0};
65
+
66
+ std::size_t len = sizeof(bounds) / sizeof(unsigned char);
67
+ assert(sizeof(input) / sizeof(unsigned char) == len);
68
+ assert(sizeof(output) / sizeof(unsigned char) == len);
69
+
70
+ CheckEncodeDecode(bounds, input, output, len);
71
+ }
72
+
73
+ BOOST_AUTO_TEST_CASE(Exactly64) {
74
+ unsigned char bounds[] = {255, 255, 255, 255, 255, 255, 255, 255};
75
+ unsigned char input[] = {172, 183, 254, 187, 96, 87, 65, 16};
76
+ unsigned char output[] = {0, 0, 0, 0, 0, 0, 0, 0};
77
+
78
+ std::size_t len = sizeof(bounds) / sizeof(unsigned char);
79
+ assert(sizeof(input) / sizeof(unsigned char) == len);
80
+ assert(sizeof(output) / sizeof(unsigned char) == len);
81
+
82
+ CheckEncodeDecode(bounds, input, output, len);
83
+ }
84
+
85
+ BOOST_AUTO_TEST_CASE(MoreThan64) {
86
+ unsigned char bounds[] = {255, 255, 255, 255, 255, 255, 255, 255, 255};
87
+ unsigned char input[] = {172, 183, 254, 187, 96, 87, 65, 16, 137};
88
+ unsigned char output[] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
89
+
90
+ std::size_t len = sizeof(bounds) / sizeof(unsigned char);
91
+ assert(sizeof(input) / sizeof(unsigned char) == len);
92
+ assert(sizeof(output) / sizeof(unsigned char) == len);
93
+
94
+ CheckEncodeDecode(bounds, input, output, len);
95
+ }
96
+
97
+ }}} // namespaces
cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/interpolate_main.cc ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "../common/model_buffer.hh"
2
+ #include "../common/size_option.hh"
3
+ #include "pipeline.hh"
4
+ #include "tune_instances.hh"
5
+ #include "tune_weights.hh"
6
+ #include "../../util/fixed_array.hh"
7
+ #include "../../util/usage.hh"
8
+
9
+ #pragma GCC diagnostic push
10
+ #pragma GCC diagnostic ignored "-Wpragmas" // Older gcc doesn't have "-Wunused-local-typedefs" and complains.
11
+ #pragma GCC diagnostic ignored "-Wunused-local-typedefs"
12
+ #include <Eigen/Core>
13
+ #pragma GCC diagnostic pop
14
+
15
+ #include <boost/program_options.hpp>
16
+
17
+ #include <iostream>
18
+ #include <vector>
19
+
20
+ namespace {
21
+ void MungeWeightArgs(int argc, char *argv[], std::vector<const char *> &munged_args) {
22
+ // Boost program options doesn't -w 0.2 -0.1 because it thinks -0.1 is an
23
+ // option. There appears to be no standard way to fix this without breaking
24
+ // single-dash arguments. So here's a hack: put a -w before every number
25
+ // if it's within the scope of a weight argument.
26
+ munged_args.push_back(argv[0]);
27
+ char **inside_weights = NULL;
28
+ for (char **i = argv + 1; i < argv + argc; ++i) {
29
+ StringPiece arg(*i);
30
+ if (starts_with(arg, "-w") || starts_with(arg, "--w")) {
31
+ inside_weights = i;
32
+ } else if (inside_weights && arg.size() >= 2 && arg[0] == '-' && ((arg[1] >= '0' && arg[1] <= '9') || arg[1] == '.')) {
33
+ // If a negative number appears right after -w, don't add another -w.
34
+ // And do stay inside weights.
35
+ if (inside_weights + 1 != i) {
36
+ munged_args.push_back("-w");
37
+ }
38
+ } else if (starts_with(arg, "-")) {
39
+ inside_weights = NULL;
40
+ }
41
+ munged_args.push_back(*i);
42
+ }
43
+ }
44
+ } // namespace
45
+
46
+ int main(int argc, char *argv[]) {
47
+ try {
48
+ Eigen::initParallel();
49
+ lm::interpolate::Config pipe_config;
50
+ lm::interpolate::InstancesConfig instances_config;
51
+ std::vector<std::string> input_models;
52
+ std::string tuning_file;
53
+
54
+ namespace po = boost::program_options;
55
+ po::options_description options("Log-linear interpolation options");
56
+ options.add_options()
57
+ ("help,h", po::bool_switch(), "Show this help message")
58
+ ("model,m", po::value<std::vector<std::string> >(&input_models)->multitoken()->required(), "Models to interpolate, which must be in KenLM intermediate format. The intermediate format can be generated using the --intermediate argument to lmplz.")
59
+ ("weight,w", po::value<std::vector<float> >(&pipe_config.lambdas)->multitoken(), "Interpolation weights")
60
+ ("tuning,t", po::value<std::string>(&tuning_file), "File to tune on: a text file with one sentence per line")
61
+ ("just_tune", po::bool_switch(), "Tune and print weights then quit")
62
+ ("temp_prefix,T", po::value<std::string>(&pipe_config.sort.temp_prefix)->default_value("/tmp/lm"), "Temporary file prefix")
63
+ ("memory,S", lm::SizeOption(pipe_config.sort.total_memory, util::GuessPhysicalMemory() ? "50%" : "1G"), "Sorting memory: this is a very rough guide")
64
+ ("sort_block", lm::SizeOption(pipe_config.sort.buffer_size, "64M"), "Block size");
65
+ po::variables_map vm;
66
+
67
+ std::vector<const char *> munged_args;
68
+ MungeWeightArgs(argc, argv, munged_args);
69
+
70
+ po::store(po::parse_command_line((int)munged_args.size(), &*munged_args.begin(), options), vm);
71
+ if (argc == 1 || vm["help"].as<bool>()) {
72
+ std::cerr << "Interpolate multiple models\n" << options << std::endl;
73
+ return 1;
74
+ }
75
+ po::notify(vm);
76
+ instances_config.sort = pipe_config.sort;
77
+ instances_config.model_read_chain_mem = instances_config.sort.buffer_size;
78
+ instances_config.extension_write_chain_mem = instances_config.sort.total_memory;
79
+ instances_config.lazy_memory = instances_config.sort.total_memory;
80
+
81
+ if (pipe_config.lambdas.empty() && tuning_file.empty()) {
82
+ std::cerr << "Provide a tuning file with -t xor weights with -w." << std::endl;
83
+ return 1;
84
+ }
85
+ if (!pipe_config.lambdas.empty() && !tuning_file.empty()) {
86
+ std::cerr << "Provide weights xor a tuning file, not both." << std::endl;
87
+ return 1;
88
+ }
89
+
90
+ if (!tuning_file.empty()) {
91
+ // Tune weights
92
+ std::vector<StringPiece> model_names;
93
+ for (std::vector<std::string>::const_iterator i = input_models.begin(); i != input_models.end(); ++i) {
94
+ model_names.push_back(*i);
95
+ }
96
+ lm::interpolate::TuneWeights(util::OpenReadOrThrow(tuning_file.c_str()), model_names, instances_config, pipe_config.lambdas);
97
+
98
+ std::cerr << "Final weights:";
99
+ std::ostream &to = vm["just_tune"].as<bool>() ? std::cout : std::cerr;
100
+ for (std::vector<float>::const_iterator i = pipe_config.lambdas.begin(); i != pipe_config.lambdas.end(); ++i) {
101
+ to << ' ' << *i;
102
+ }
103
+ to << std::endl;
104
+ }
105
+ if (vm["just_tune"].as<bool>()) {
106
+ return 0;
107
+ }
108
+
109
+ if (pipe_config.lambdas.size() != input_models.size()) {
110
+ std::cerr << "Number of models (" << input_models.size() << ") should match the number of weights (" << pipe_config.lambdas.size() << ")." << std::endl;
111
+ return 1;
112
+ }
113
+
114
+ util::FixedArray<lm::ModelBuffer> models(input_models.size());
115
+ for (std::size_t i = 0; i < input_models.size(); ++i) {
116
+ models.push_back(input_models[i]);
117
+ }
118
+ lm::interpolate::Pipeline(models, pipe_config, 1);
119
+ } catch (const std::exception &e) {
120
+ std::cerr << e.what() <<std::endl;
121
+ return 1;
122
+ }
123
+ return 0;
124
+ }
cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/normalize.hh ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef LM_INTERPOLATE_NORMALIZE_H
2
+ #define LM_INTERPOLATE_NORMALIZE_H
3
+
4
+ #include "../../util/fixed_array.hh"
5
+
6
+ /* Pass 2:
7
+ * - Multiply backoff weights by the backed off probabilities from pass 1.
8
+ * - Compute the normalization factor Z.
9
+ * - Send Z to the next highest order.
10
+ * - Rewind and divide by Z.
11
+ */
12
+
13
+ namespace util { namespace stream {
14
+ class ChainPositions;
15
+ class Chains;
16
+ }} // namespaces
17
+
18
+ namespace lm { namespace interpolate {
19
+
20
+ struct InterpolateInfo;
21
+
22
+ void Normalize(
23
+ const InterpolateInfo &info,
24
+ // Input full models for backoffs. Assumes that renumbering has been done. Suffix order.
25
+ util::FixedArray<util::stream::ChainPositions> &models_by_order,
26
+ // Input PartialProbGamma from MergeProbabilities. Context order.
27
+ util::stream::Chains &merged_probabilities,
28
+ // Output NGram<float> with normalized probabilities. Context order.
29
+ util::stream::Chains &probabilities_out,
30
+ // Output bare floats with backoffs. Note backoffs.size() == order - 1. Suffix order.
31
+ util::stream::Chains &backoffs_out);
32
+
33
+ }} // namespaces
34
+
35
+ #endif // LM_INTERPOLATE_NORMALIZE_H
cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/normalize_test.cc ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "normalize.hh"
2
+
3
+ #include "interpolate_info.hh"
4
+ #include "merge_probabilities.hh"
5
+ #include "../common/ngram_stream.hh"
6
+ #include "../../util/stream/chain.hh"
7
+ #include "../../util/stream/multi_stream.hh"
8
+
9
+ #define BOOST_TEST_MODULE NormalizeTest
10
+ #include <boost/test/unit_test.hpp>
11
+
12
+ namespace lm { namespace interpolate { namespace {
13
+
14
+ // log without backoff
15
+ const float kInputs[] = {-0.3, 1.2, -9.8, 4.0, -7.0, 0.0};
16
+
17
+ class WriteInput {
18
+ public:
19
+ WriteInput() {}
20
+ void Run(const util::stream::ChainPosition &to) {
21
+ util::stream::Stream out(to);
22
+ for (WordIndex i = 0; i < sizeof(kInputs) / sizeof(float); ++i, ++out) {
23
+ memcpy(out.Get(), &i, sizeof(WordIndex));
24
+ memcpy((uint8_t*)out.Get() + sizeof(WordIndex), &kInputs[i], sizeof(float));
25
+ }
26
+ out.Poison();
27
+ }
28
+ };
29
+
30
+ void CheckOutput(const util::stream::ChainPosition &from) {
31
+ NGramStream<float> in(from);
32
+ float sum = 0.0;
33
+ for (WordIndex i = 0; i < sizeof(kInputs) / sizeof(float) - 1 /* <s> at the end */; ++i) {
34
+ sum += pow(10.0, kInputs[i]);
35
+ }
36
+ sum = log10(sum);
37
+ BOOST_REQUIRE(in);
38
+ BOOST_CHECK_CLOSE(kInputs[0] - sum, in->Value(), 0.0001);
39
+ BOOST_REQUIRE(++in);
40
+ BOOST_CHECK_CLOSE(kInputs[1] - sum, in->Value(), 0.0001);
41
+ BOOST_REQUIRE(++in);
42
+ BOOST_CHECK_CLOSE(kInputs[2] - sum, in->Value(), 0.0001);
43
+ BOOST_REQUIRE(++in);
44
+ BOOST_CHECK_CLOSE(kInputs[3] - sum, in->Value(), 0.0001);
45
+ BOOST_REQUIRE(++in);
46
+ BOOST_CHECK_CLOSE(kInputs[4] - sum, in->Value(), 0.0001);
47
+ BOOST_REQUIRE(++in);
48
+ BOOST_CHECK_CLOSE(kInputs[5] - sum, in->Value(), 0.0001);
49
+ BOOST_CHECK(!++in);
50
+ }
51
+
52
+ BOOST_AUTO_TEST_CASE(Unigrams) {
53
+ InterpolateInfo info;
54
+ info.lambdas.push_back(2.0);
55
+ info.lambdas.push_back(-0.1);
56
+ info.orders.push_back(1);
57
+ info.orders.push_back(1);
58
+
59
+ BOOST_CHECK_EQUAL(0, MakeEncoder(info, 1).EncodedLength());
60
+
61
+ // No backoffs.
62
+ util::stream::Chains blank(0);
63
+ util::FixedArray<util::stream::ChainPositions> models_by_order(2);
64
+ models_by_order.push_back(blank);
65
+ models_by_order.push_back(blank);
66
+
67
+ util::stream::Chains merged_probabilities(1);
68
+ util::stream::Chains probabilities_out(1);
69
+ util::stream::Chains backoffs_out(0);
70
+
71
+ merged_probabilities.push_back(util::stream::ChainConfig(sizeof(WordIndex) + sizeof(float) + sizeof(float), 2, 24));
72
+ probabilities_out.push_back(util::stream::ChainConfig(sizeof(WordIndex) + sizeof(float), 2, 100));
73
+
74
+ merged_probabilities[0] >> WriteInput();
75
+ Normalize(info, models_by_order, merged_probabilities, probabilities_out, backoffs_out);
76
+
77
+ util::stream::ChainPosition checker(probabilities_out[0].Add());
78
+
79
+ merged_probabilities >> util::stream::kRecycle;
80
+ probabilities_out >> util::stream::kRecycle;
81
+
82
+ CheckOutput(checker);
83
+ probabilities_out.Wait();
84
+ }
85
+
86
+ }}} // namespaces
cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/split_worker.cc ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "split_worker.hh"
2
+ #include "../common/ngram.hh"
3
+
4
+ namespace lm {
5
+ namespace interpolate {
6
+
7
+ SplitWorker::SplitWorker(std::size_t order, util::stream::Chain &backoff_chain,
8
+ util::stream::Chain &sort_chain)
9
+ : order_(order) {
10
+ backoff_chain >> backoff_input_;
11
+ sort_chain >> sort_input_;
12
+ }
13
+
14
+ void SplitWorker::Run(const util::stream::ChainPosition &position) {
15
+ // input: ngram record (id, prob, and backoff)
16
+ // output: a float to the backoff_input stream
17
+ // an ngram id and a float to the sort_input stream
18
+ for (util::stream::Stream stream(position); stream; ++stream) {
19
+ NGram<ProbBackoff> ngram(stream.Get(), order_);
20
+
21
+ // write id and prob to the sort stream
22
+ float prob = ngram.Value().prob;
23
+ lm::WordIndex *out = reinterpret_cast<lm::WordIndex *>(sort_input_.Get());
24
+ for (const lm::WordIndex *it = ngram.begin(); it != ngram.end(); ++it) {
25
+ *out++ = *it;
26
+ }
27
+ *reinterpret_cast<float *>(out) = prob;
28
+ ++sort_input_;
29
+
30
+ // write backoff to the backoff output stream
31
+ float boff = ngram.Value().backoff;
32
+ *reinterpret_cast<float *>(backoff_input_.Get()) = boff;
33
+ ++backoff_input_;
34
+ }
35
+ sort_input_.Poison();
36
+ backoff_input_.Poison();
37
+ }
38
+
39
+ }
40
+ }
cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/tune_instances_test.cc ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "tune_instances.hh"
2
+
3
+ #include "../../util/file.hh"
4
+ #include "../../util/file_stream.hh"
5
+ #include "../../util/stream/chain.hh"
6
+ #include "../../util/stream/config.hh"
7
+ #include "../../util/stream/typed_stream.hh"
8
+ #include "../../util/string_piece.hh"
9
+
10
+ #define BOOST_TEST_MODULE InstanceTest
11
+ #include <boost/test/unit_test.hpp>
12
+
13
+ #include <vector>
14
+
15
+ #include <math.h>
16
+
17
+ namespace lm { namespace interpolate { namespace {
18
+
19
+ BOOST_AUTO_TEST_CASE(Toy) {
20
+ util::scoped_fd test_input(util::MakeTemp("temporary"));
21
+ util::FileStream(test_input.get()) << "c\n";
22
+
23
+ std::string dir("../common/test_data");
24
+ if (boost::unit_test::framework::master_test_suite().argc == 2) {
25
+ dir = boost::unit_test::framework::master_test_suite().argv[1];
26
+ }
27
+
28
+ #if BYTE_ORDER == LITTLE_ENDIAN
29
+ std::string endian = "little";
30
+ #elif BYTE_ORDER == BIG_ENDIAN
31
+ std::string endian = "big";
32
+ #else
33
+ #error "Unsupported byte order."
34
+ #endif
35
+ dir += "/" + endian + "endian/";
36
+
37
+ std::vector<StringPiece> model_names;
38
+ std::string full0 = dir + "toy0";
39
+ std::string full1 = dir + "toy1";
40
+ model_names.push_back(full0);
41
+ model_names.push_back(full1);
42
+
43
+ // Tiny buffer sizes.
44
+ InstancesConfig config;
45
+ config.model_read_chain_mem = 100;
46
+ config.extension_write_chain_mem = 100;
47
+ config.lazy_memory = 100;
48
+ config.sort.temp_prefix = "temporary";
49
+ config.sort.buffer_size = 100;
50
+ config.sort.total_memory = 1024;
51
+
52
+ util::SeekOrThrow(test_input.get(), 0);
53
+
54
+ Instances inst(test_input.release(), model_names, config);
55
+
56
+ BOOST_CHECK_EQUAL(1, inst.BOS());
57
+ const Matrix &ln_unigrams = inst.LNUnigrams();
58
+
59
+ // <unk>=0
60
+ BOOST_CHECK_CLOSE(-0.90309 * M_LN10, ln_unigrams(0, 0), 0.001);
61
+ BOOST_CHECK_CLOSE(-1 * M_LN10, ln_unigrams(0, 1), 0.001);
62
+ // <s>=1 doesn't matter as long as it doesn't cause NaNs.
63
+ BOOST_CHECK(!isnan(ln_unigrams(1, 0)));
64
+ BOOST_CHECK(!isnan(ln_unigrams(1, 1)));
65
+ // a = 2
66
+ BOOST_CHECK_CLOSE(-0.46943438 * M_LN10, ln_unigrams(2, 0), 0.001);
67
+ BOOST_CHECK_CLOSE(-0.6146491 * M_LN10, ln_unigrams(2, 1), 0.001);
68
+ // </s> = 3
69
+ BOOST_CHECK_CLOSE(-0.5720968 * M_LN10, ln_unigrams(3, 0), 0.001);
70
+ BOOST_CHECK_CLOSE(-0.6146491 * M_LN10, ln_unigrams(3, 1), 0.001);
71
+ // c = 4
72
+ BOOST_CHECK_CLOSE(-0.90309 * M_LN10, ln_unigrams(4, 0), 0.001); // <unk>
73
+ BOOST_CHECK_CLOSE(-0.7659168 * M_LN10, ln_unigrams(4, 1), 0.001);
74
+ // too lazy to do b = 5.
75
+
76
+ // Two instances:
77
+ // <s> predicts c
78
+ // <s> c predicts </s>
79
+ BOOST_REQUIRE_EQUAL(2, inst.NumInstances());
80
+ BOOST_CHECK_CLOSE(-0.30103 * M_LN10, inst.LNBackoffs(0)(0), 0.001);
81
+ BOOST_CHECK_CLOSE(-0.30103 * M_LN10, inst.LNBackoffs(0)(1), 0.001);
82
+
83
+
84
+ // Backoffs of <s> c
85
+ BOOST_CHECK_CLOSE(0.0, inst.LNBackoffs(1)(0), 0.001);
86
+ BOOST_CHECK_CLOSE((-0.30103 - 0.30103) * M_LN10, inst.LNBackoffs(1)(1), 0.001);
87
+
88
+ util::stream::Chain extensions(util::stream::ChainConfig(inst.ReadExtensionsEntrySize(), 2, 300));
89
+ inst.ReadExtensions(extensions);
90
+ util::stream::TypedStream<Extension> stream(extensions.Add());
91
+ extensions >> util::stream::kRecycle;
92
+
93
+ // The extensions are (in order of instance, vocab id, and model as they should be sorted):
94
+ // <s> a from both models 0 and 1 (so two instances)
95
+ // <s> c from model 1
96
+ // <s> b from model 0
97
+ // c </s> from model 1
98
+ // Magic probabilities come from querying the models directly.
99
+
100
+ // <s> a from model 0
101
+ BOOST_REQUIRE(stream);
102
+ BOOST_CHECK_EQUAL(0, stream->instance);
103
+ BOOST_CHECK_EQUAL(2 /* a */, stream->word);
104
+ BOOST_CHECK_EQUAL(0, stream->model);
105
+ BOOST_CHECK_CLOSE(-0.37712017 * M_LN10, stream->ln_prob, 0.001);
106
+
107
+ // <s> a from model 1
108
+ BOOST_REQUIRE(++stream);
109
+ BOOST_CHECK_EQUAL(0, stream->instance);
110
+ BOOST_CHECK_EQUAL(2 /* a */, stream->word);
111
+ BOOST_CHECK_EQUAL(1, stream->model);
112
+ BOOST_CHECK_CLOSE(-0.4301247 * M_LN10, stream->ln_prob, 0.001);
113
+
114
+ // <s> c from model 1
115
+ BOOST_REQUIRE(++stream);
116
+ BOOST_CHECK_EQUAL(0, stream->instance);
117
+ BOOST_CHECK_EQUAL(4 /* c */, stream->word);
118
+ BOOST_CHECK_EQUAL(1, stream->model);
119
+ BOOST_CHECK_CLOSE(-0.4740302 * M_LN10, stream->ln_prob, 0.001);
120
+
121
+ // <s> b from model 0
122
+ BOOST_REQUIRE(++stream);
123
+ BOOST_CHECK_EQUAL(0, stream->instance);
124
+ BOOST_CHECK_EQUAL(5 /* b */, stream->word);
125
+ BOOST_CHECK_EQUAL(0, stream->model);
126
+ BOOST_CHECK_CLOSE(-0.41574955 * M_LN10, stream->ln_prob, 0.001);
127
+
128
+ // c </s> from model 1
129
+ BOOST_REQUIRE(++stream);
130
+ BOOST_CHECK_EQUAL(1, stream->instance);
131
+ BOOST_CHECK_EQUAL(3 /* </s> */, stream->word);
132
+ BOOST_CHECK_EQUAL(1, stream->model);
133
+ BOOST_CHECK_CLOSE(-0.09113217 * M_LN10, stream->ln_prob, 0.001);
134
+
135
+ BOOST_CHECK(!++stream);
136
+ }
137
+
138
+ }}} // namespaces
cc-multilingual-main/cc_net/third_party/kenlm/lm/interpolate/tune_weights.cc ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "tune_weights.hh"
2
+
3
+ #include "tune_derivatives.hh"
4
+ #include "tune_instances.hh"
5
+
6
+ #pragma GCC diagnostic push
7
+ #pragma GCC diagnostic ignored "-Wpragmas" // Older gcc doesn't have "-Wunused-local-typedefs" and complains.
8
+ #pragma GCC diagnostic ignored "-Wunused-local-typedefs"
9
+ #include <Eigen/Dense>
10
+ #pragma GCC diagnostic pop
11
+ #include <boost/program_options.hpp>
12
+
13
+ #include <iostream>
14
+
15
+ namespace lm { namespace interpolate {
16
+ void TuneWeights(int tune_file, const std::vector<StringPiece> &model_names, const InstancesConfig &config, std::vector<float> &weights_out) {
17
+ Instances instances(tune_file, model_names, config);
18
+ Vector weights = Vector::Constant(model_names.size(), 1.0 / model_names.size());
19
+ Vector gradient;
20
+ Matrix hessian;
21
+ for (std::size_t iteration = 0; iteration < 10 /*TODO fancy stopping criteria */; ++iteration) {
22
+ std::cerr << "Iteration " << iteration << ": weights =";
23
+ for (Vector::Index i = 0; i < weights.rows(); ++i) {
24
+ std::cerr << ' ' << weights(i);
25
+ }
26
+ std::cerr << std::endl;
27
+ std::cerr << "Perplexity = " << Derivatives(instances, weights, gradient, hessian) << std::endl;
28
+ // TODO: 1.0 step size was too big and it kept getting unstable. More math.
29
+ weights -= 0.7 * hessian.inverse() * gradient;
30
+ }
31
+ weights_out.assign(weights.data(), weights.data() + weights.size());
32
+ }
33
+ }} // namespaces
cc-multilingual-main/cc_net/third_party/kenlm/python/_kenlm.pxd ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from libcpp cimport bool
2
+
3
+ cdef extern from "lm/word_index.hh" namespace "lm":
4
+ ctypedef unsigned WordIndex
5
+
6
+ cdef extern from "lm/return.hh" namespace "lm":
7
+ cdef struct FullScoreReturn:
8
+ float prob
9
+ unsigned char ngram_length
10
+
11
+ cdef extern from "lm/state.hh" namespace "lm::ngram":
12
+ cdef cppclass State :
13
+ int Compare(const State &other) const
14
+
15
+ int hash_value(const State &state)
16
+
17
+ cdef extern from "lm/virtual_interface.hh" namespace "lm::base":
18
+ cdef cppclass Vocabulary:
19
+ WordIndex Index(char*)
20
+ WordIndex BeginSentence()
21
+ WordIndex EndSentence()
22
+ WordIndex NotFound()
23
+
24
+ ctypedef Vocabulary const_Vocabulary "const lm::base::Vocabulary"
25
+
26
+ cdef cppclass Model:
27
+ void BeginSentenceWrite(void *)
28
+ void NullContextWrite(void *)
29
+ unsigned int Order()
30
+ const_Vocabulary& BaseVocabulary()
31
+ float BaseScore(void *in_state, WordIndex new_word, void *out_state)
32
+ FullScoreReturn BaseFullScore(void *in_state, WordIndex new_word, void *out_state)
33
+
34
+ cdef extern from "util/mmap.hh" namespace "util":
35
+ cdef enum LoadMethod:
36
+ LAZY
37
+ POPULATE_OR_LAZY
38
+ POPULATE_OR_READ
39
+ READ
40
+ PARALLEL_READ
41
+
42
+ cdef extern from "lm/config.hh" namespace "lm::ngram::Config":
43
+ cdef enum ARPALoadComplain:
44
+ ALL
45
+ EXPENSIVE
46
+ NONE
47
+
48
+ cdef extern from "lm/config.hh" namespace "lm::ngram":
49
+ cdef cppclass Config:
50
+ Config()
51
+ float probing_multiplier
52
+ LoadMethod load_method
53
+ bool show_progress
54
+ ARPALoadComplain arpa_complain
55
+ float unknown_missing_logprob
56
+
57
+ cdef extern from "lm/model.hh" namespace "lm::ngram":
58
+ cdef Model *LoadVirtual(char *, Config &config) except +
59
+ #default constructor
60
+ cdef Model *LoadVirtual(char *) except +
61
+
62
+ cdef extern from "python/score_sentence.hh" namespace "lm::base":
63
+ cdef float ScoreSentence(const Model *model, const char *sentence)
cc-multilingual-main/cc_net/third_party/kenlm/python/example.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ import os
3
+ import kenlm
4
+
5
+ LM = os.path.join(os.path.dirname(__file__), '..', 'lm', 'test.arpa')
6
+ model = kenlm.LanguageModel(LM)
7
+ print('{0}-gram model'.format(model.order))
8
+
9
+ sentence = 'language modeling is fun .'
10
+ print(sentence)
11
+ print(model.score(sentence))
12
+
13
+ # Check that total full score = direct score
14
+ def score(s):
15
+ return sum(prob for prob, _, _ in model.full_scores(s))
16
+
17
+ assert (abs(score(sentence) - model.score(sentence)) < 1e-3)
18
+
19
+ # Show scores and n-gram matches
20
+ words = ['<s>'] + sentence.split() + ['</s>']
21
+ for i, (prob, length, oov) in enumerate(model.full_scores(sentence)):
22
+ print('{0} {1}: {2}'.format(prob, length, ' '.join(words[i+2-length:i+2])))
23
+ if oov:
24
+ print('\t"{0}" is an OOV'.format(words[i+1]))
25
+
26
+ # Find out-of-vocabulary words
27
+ for w in words:
28
+ if not w in model:
29
+ print('"{0}" is an OOV'.format(w))
30
+
31
+ #Stateful query
32
+ state = kenlm.State()
33
+ state2 = kenlm.State()
34
+ #Use <s> as context. If you don't want <s>, use model.NullContextWrite(state).
35
+ model.BeginSentenceWrite(state)
36
+ accum = 0.0
37
+ accum += model.BaseScore(state, "a", state2)
38
+ accum += model.BaseScore(state2, "sentence", state)
39
+ #score defaults to bos = True and eos = True. Here we'll check without the end
40
+ #of sentence marker.
41
+ assert (abs(accum - model.score("a sentence", eos = False)) < 1e-3)
42
+ accum += model.BaseScore(state, "</s>", state2)
43
+ assert (abs(accum - model.score("a sentence")) < 1e-3)
cc-multilingual-main/cc_net/third_party/kenlm/python/kenlm.cpp ADDED
The diff for this file is too large to render. See raw diff
 
cc-multilingual-main/cc_net/third_party/kenlm/python/score_sentence.cc ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "lm/state.hh"
2
+ #include "lm/virtual_interface.hh"
3
+ #include "util/tokenize_piece.hh"
4
+
5
+ #include <algorithm>
6
+ #include <utility>
7
+
8
+ namespace lm {
9
+ namespace base {
10
+
11
+ float ScoreSentence(const base::Model *model, const char *sentence) {
12
+ // TODO: reduce virtual dispatch to one per sentence?
13
+ const base::Vocabulary &vocab = model->BaseVocabulary();
14
+ // We know it's going to be a KenLM State.
15
+ lm::ngram::State state_vec[2];
16
+ lm::ngram::State *state = &state_vec[0];
17
+ lm::ngram::State *state2 = &state_vec[1];
18
+ model->BeginSentenceWrite(state);
19
+ float ret = 0.0;
20
+ for (util::TokenIter<util::BoolCharacter, true> i(sentence, util::kSpaces); i; ++i) {
21
+ lm::WordIndex index = vocab.Index(*i);
22
+ ret += model->BaseScore(state, index, state2);
23
+ std::swap(state, state2);
24
+ }
25
+ ret += model->BaseScore(state, vocab.EndSentence(), state2);
26
+ return ret;
27
+ }
28
+
29
+ } // namespace base
30
+ } // namespace lm
cc-multilingual-main/cc_net/third_party/kenlm/python/score_sentence.hh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Score an entire sentence splitting on whitespace. This should not be needed
2
+ // for C++ users (who should do it themselves), but it's faster for python users.
3
+ #pragma once
4
+
5
+ namespace lm {
6
+ namespace base {
7
+
8
+ class Model;
9
+
10
+ float ScoreSentence(const Model *model, const char *sentence);
11
+
12
+ } // namespace base
13
+ } // namespace lm
cc-multilingual-main/cc_net/third_party/kenlm/util/bit_packing.cc ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "bit_packing.hh"
2
+ #include "exception.hh"
3
+
4
+ #include <cstring>
5
+
6
+ namespace util {
7
+
8
+ namespace {
9
+ template <bool> struct StaticCheck {};
10
+ template <> struct StaticCheck<true> { typedef bool StaticAssertionPassed; };
11
+
12
+ // If your float isn't 4 bytes, we're hosed.
13
+ typedef StaticCheck<sizeof(float) == 4>::StaticAssertionPassed FloatSize;
14
+
15
+ } // namespace
16
+
17
+ uint8_t RequiredBits(uint64_t max_value) {
18
+ if (!max_value) return 0;
19
+ uint8_t ret = 1;
20
+ while (max_value >>= 1) ++ret;
21
+ return ret;
22
+ }
23
+
24
+ void BitPackingSanity() {
25
+ const FloatEnc neg1 = { -1.0 }, pos1 = { 1.0 };
26
+ if ((neg1.i ^ pos1.i) != 0x80000000) UTIL_THROW(Exception, "Sign bit is not 0x80000000");
27
+ char mem[57+8];
28
+ memset(mem, 0, sizeof(mem));
29
+ const uint64_t test57 = 0x123456789abcdefULL;
30
+ for (uint64_t b = 0; b < 57 * 8; b += 57) {
31
+ WriteInt57(mem, b, 57, test57);
32
+ }
33
+ for (uint64_t b = 0; b < 57 * 8; b += 57) {
34
+ if (test57 != ReadInt57(mem, b, 57, (1ULL << 57) - 1))
35
+ UTIL_THROW(Exception, "The bit packing routines are failing for your architecture. Please send a bug report with your architecture, operating system, and compiler.");
36
+ }
37
+ // TODO: more checks.
38
+ }
39
+
40
+ } // namespace util
cc-multilingual-main/cc_net/third_party/kenlm/util/bit_packing.hh ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef UTIL_BIT_PACKING_H
2
+ #define UTIL_BIT_PACKING_H
3
+
4
+ /* Bit-level packing routines
5
+ *
6
+ * WARNING WARNING WARNING:
7
+ * The write functions assume that memory is zero initially. This makes them
8
+ * faster and is the appropriate case for mmapped language model construction.
9
+ * These routines assume that unaligned access to uint64_t is fast. This is
10
+ * the case on x86_64. I'm not sure how fast unaligned 64-bit access is on
11
+ * x86 but my target audience is large language models for which 64-bit is
12
+ * necessary.
13
+ *
14
+ * Call the BitPackingSanity function to sanity check. Calling once suffices,
15
+ * but it may be called multiple times when that's inconvenient.
16
+ *
17
+ * ARM and MinGW ports contributed by Hideo Okuma and Tomoyuki Yoshimura at
18
+ * NICT.
19
+ */
20
+
21
+ #include <cassert>
22
+ #ifdef __APPLE__
23
+ #include <architecture/byte_order.h>
24
+ #elif __linux__
25
+ #include <endian.h>
26
+ #elif !defined(_WIN32) && !defined(_WIN64)
27
+ #include <arpa/nameser_compat.h>
28
+ #endif
29
+
30
+ #include <stdint.h>
31
+ #include <cstring>
32
+
33
+ namespace util {
34
+
35
+ // Fun fact: __BYTE_ORDER is wrong on Solaris Sparc, but the version without __ is correct.
36
+ #if BYTE_ORDER == LITTLE_ENDIAN
37
+ inline uint8_t BitPackShift(uint8_t bit, uint8_t /*length*/) {
38
+ return bit;
39
+ }
40
+ inline uint8_t BitPackShift32(uint8_t bit, uint8_t /*length*/) {
41
+ return bit;
42
+ }
43
+ #elif BYTE_ORDER == BIG_ENDIAN
44
+ inline uint8_t BitPackShift(uint8_t bit, uint8_t length) {
45
+ return 64 - length - bit;
46
+ }
47
+ inline uint8_t BitPackShift32(uint8_t bit, uint8_t length) {
48
+ return 32 - length - bit;
49
+ }
50
+ #else
51
+ #error "Bit packing code isn't written for your byte order."
52
+ #endif
53
+
54
+ inline uint64_t ReadOff(const void *base, uint64_t bit_off) {
55
+ #if defined(__arm) || defined(__arm__)
56
+ const uint8_t *base_off = reinterpret_cast<const uint8_t*>(base) + (bit_off >> 3);
57
+ uint64_t value64;
58
+ memcpy(&value64, base_off, sizeof(value64));
59
+ return value64;
60
+ #else
61
+ return *reinterpret_cast<const uint64_t*>(reinterpret_cast<const uint8_t*>(base) + (bit_off >> 3));
62
+ #endif
63
+ }
64
+
65
+ /* Pack integers up to 57 bits using their least significant digits.
66
+ * The length is specified using mask:
67
+ * Assumes mask == (1 << length) - 1 where length <= 57.
68
+ */
69
+ inline uint64_t ReadInt57(const void *base, uint64_t bit_off, uint8_t length, uint64_t mask) {
70
+ return (ReadOff(base, bit_off) >> BitPackShift(bit_off & 7, length)) & mask;
71
+ }
72
+ /* Assumes value < (1 << length) and length <= 57.
73
+ * Assumes the memory is zero initially.
74
+ */
75
+ inline void WriteInt57(void *base, uint64_t bit_off, uint8_t length, uint64_t value) {
76
+ #if defined(__arm) || defined(__arm__)
77
+ uint8_t *base_off = reinterpret_cast<uint8_t*>(base) + (bit_off >> 3);
78
+ uint64_t value64;
79
+ memcpy(&value64, base_off, sizeof(value64));
80
+ value64 |= (value << BitPackShift(bit_off & 7, length));
81
+ memcpy(base_off, &value64, sizeof(value64));
82
+ #else
83
+ *reinterpret_cast<uint64_t*>(reinterpret_cast<uint8_t*>(base) + (bit_off >> 3)) |=
84
+ (value << BitPackShift(bit_off & 7, length));
85
+ #endif
86
+ }
87
+
88
+ /* Same caveats as above, but for a 25 bit limit. */
89
+ inline uint32_t ReadInt25(const void *base, uint64_t bit_off, uint8_t length, uint32_t mask) {
90
+ #if defined(__arm) || defined(__arm__)
91
+ const uint8_t *base_off = reinterpret_cast<const uint8_t*>(base) + (bit_off >> 3);
92
+ uint32_t value32;
93
+ memcpy(&value32, base_off, sizeof(value32));
94
+ return (value32 >> BitPackShift32(bit_off & 7, length)) & mask;
95
+ #else
96
+ return (*reinterpret_cast<const uint32_t*>(reinterpret_cast<const uint8_t*>(base) + (bit_off >> 3)) >> BitPackShift32(bit_off & 7, length)) & mask;
97
+ #endif
98
+ }
99
+
100
+ inline void WriteInt25(void *base, uint64_t bit_off, uint8_t length, uint32_t value) {
101
+ #if defined(__arm) || defined(__arm__)
102
+ uint8_t *base_off = reinterpret_cast<uint8_t*>(base) + (bit_off >> 3);
103
+ uint32_t value32;
104
+ memcpy(&value32, base_off, sizeof(value32));
105
+ value32 |= (value << BitPackShift32(bit_off & 7, length));
106
+ memcpy(base_off, &value32, sizeof(value32));
107
+ #else
108
+ *reinterpret_cast<uint32_t*>(reinterpret_cast<uint8_t*>(base) + (bit_off >> 3)) |=
109
+ (value << BitPackShift32(bit_off & 7, length));
110
+ #endif
111
+ }
112
+
113
+ typedef union { float f; uint32_t i; } FloatEnc;
114
+
115
+ inline float ReadFloat32(const void *base, uint64_t bit_off) {
116
+ FloatEnc encoded;
117
+ encoded.i = static_cast<uint32_t>(ReadOff(base, bit_off) >> BitPackShift(bit_off & 7, 32));
118
+ return encoded.f;
119
+ }
120
+ inline void WriteFloat32(void *base, uint64_t bit_off, float value) {
121
+ FloatEnc encoded;
122
+ encoded.f = value;
123
+ WriteInt57(base, bit_off, 32, encoded.i);
124
+ }
125
+
126
+ const uint32_t kSignBit = 0x80000000;
127
+
128
+ inline void SetSign(float &to) {
129
+ FloatEnc enc;
130
+ enc.f = to;
131
+ enc.i |= kSignBit;
132
+ to = enc.f;
133
+ }
134
+
135
+ inline void UnsetSign(float &to) {
136
+ FloatEnc enc;
137
+ enc.f = to;
138
+ enc.i &= ~kSignBit;
139
+ to = enc.f;
140
+ }
141
+
142
+ inline float ReadNonPositiveFloat31(const void *base, uint64_t bit_off) {
143
+ FloatEnc encoded;
144
+ encoded.i = static_cast<uint32_t>(ReadOff(base, bit_off) >> BitPackShift(bit_off & 7, 31));
145
+ // Sign bit set means negative.
146
+ encoded.i |= kSignBit;
147
+ return encoded.f;
148
+ }
149
+ inline void WriteNonPositiveFloat31(void *base, uint64_t bit_off, float value) {
150
+ FloatEnc encoded;
151
+ encoded.f = value;
152
+ encoded.i &= ~kSignBit;
153
+ WriteInt57(base, bit_off, 31, encoded.i);
154
+ }
155
+
156
+ void BitPackingSanity();
157
+
158
+ // Return bits required to store integers upto max_value. Not the most
159
+ // efficient implementation, but this is only called a few times to size tries.
160
+ uint8_t RequiredBits(uint64_t max_value);
161
+
162
+ struct BitsMask {
163
+ static BitsMask ByMax(uint64_t max_value) {
164
+ BitsMask ret;
165
+ ret.FromMax(max_value);
166
+ return ret;
167
+ }
168
+ static BitsMask ByBits(uint8_t bits) {
169
+ BitsMask ret;
170
+ ret.bits = bits;
171
+ ret.mask = (1ULL << bits) - 1;
172
+ return ret;
173
+ }
174
+ void FromMax(uint64_t max_value) {
175
+ bits = RequiredBits(max_value);
176
+ mask = (1ULL << bits) - 1;
177
+ }
178
+ uint8_t bits;
179
+ uint64_t mask;
180
+ };
181
+
182
+ struct BitAddress {
183
+ BitAddress(void *in_base, uint64_t in_offset) : base(in_base), offset(in_offset) {}
184
+
185
+ void *base;
186
+ uint64_t offset;
187
+ };
188
+
189
+ } // namespace util
190
+
191
+ #endif // UTIL_BIT_PACKING_H
cc-multilingual-main/cc_net/third_party/kenlm/util/bit_packing_test.cc ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "bit_packing.hh"
2
+
3
+ #define BOOST_TEST_MODULE BitPackingTest
4
+ #include <boost/test/unit_test.hpp>
5
+
6
+ #include <cstring>
7
+
8
+ namespace util {
9
+ namespace {
10
+
11
+ const uint64_t test57 = 0x123456789abcdefULL;
12
+ const uint32_t test25 = 0x1234567;
13
+
14
+ BOOST_AUTO_TEST_CASE(ZeroBit57) {
15
+ char mem[16];
16
+ memset(mem, 0, sizeof(mem));
17
+ WriteInt57(mem, 0, 57, test57);
18
+ BOOST_CHECK_EQUAL(test57, ReadInt57(mem, 0, 57, (1ULL << 57) - 1));
19
+ }
20
+
21
+ BOOST_AUTO_TEST_CASE(EachBit57) {
22
+ char mem[16];
23
+ for (uint8_t b = 0; b < 8; ++b) {
24
+ memset(mem, 0, sizeof(mem));
25
+ WriteInt57(mem, b, 57, test57);
26
+ BOOST_CHECK_EQUAL(test57, ReadInt57(mem, b, 57, (1ULL << 57) - 1));
27
+ }
28
+ }
29
+
30
+ BOOST_AUTO_TEST_CASE(Consecutive57) {
31
+ char mem[57+8];
32
+ memset(mem, 0, sizeof(mem));
33
+ for (uint64_t b = 0; b < 57 * 8; b += 57) {
34
+ WriteInt57(mem, b, 57, test57);
35
+ BOOST_CHECK_EQUAL(test57, ReadInt57(mem, b, 57, (1ULL << 57) - 1));
36
+ }
37
+ for (uint64_t b = 0; b < 57 * 8; b += 57) {
38
+ BOOST_CHECK_EQUAL(test57, ReadInt57(mem, b, 57, (1ULL << 57) - 1));
39
+ }
40
+ }
41
+
42
+ BOOST_AUTO_TEST_CASE(Consecutive25) {
43
+ char mem[25+8];
44
+ memset(mem, 0, sizeof(mem));
45
+ for (uint64_t b = 0; b < 25 * 8; b += 25) {
46
+ WriteInt25(mem, b, 25, test25);
47
+ BOOST_CHECK_EQUAL(test25, ReadInt25(mem, b, 25, (1ULL << 25) - 1));
48
+ }
49
+ for (uint64_t b = 0; b < 25 * 8; b += 25) {
50
+ BOOST_CHECK_EQUAL(test25, ReadInt25(mem, b, 25, (1ULL << 25) - 1));
51
+ }
52
+ }
53
+
54
+ BOOST_AUTO_TEST_CASE(Sanity) {
55
+ BitPackingSanity();
56
+ }
57
+
58
+ } // namespace
59
+ } // namespace util
cc-multilingual-main/cc_net/third_party/kenlm/util/cat_compressed_main.cc ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Like cat but interprets compressed files.
2
+ #include "file.hh"
3
+ #include "read_compressed.hh"
4
+
5
+ #include <cstring>
6
+ #include <iostream>
7
+
8
+ namespace {
9
+ const std::size_t kBufSize = 16384;
10
+ void Copy(util::ReadCompressed &from, int to) {
11
+ util::scoped_malloc buffer(util::MallocOrThrow(kBufSize));
12
+ while (std::size_t amount = from.Read(buffer.get(), kBufSize)) {
13
+ util::WriteOrThrow(to, buffer.get(), amount);
14
+ }
15
+ }
16
+ } // namespace
17
+
18
+ int main(int argc, char *argv[]) {
19
+ // Lane Schwartz likes -h and --help
20
+ for (int i = 1; i < argc; ++i) {
21
+ char *arg = argv[i];
22
+ if (!strcmp(arg, "--")) break;
23
+ if (!strcmp(arg, "-h") || !strcmp(arg, "--help")) {
24
+ std::cerr <<
25
+ "A cat implementation that interprets compressed files.\n"
26
+ "Usage: " << argv[0] << " [file1] [file2] ...\n"
27
+ "If no file is provided, then stdin is read.\n";
28
+ return 1;
29
+ }
30
+ }
31
+
32
+ try {
33
+ if (argc == 1) {
34
+ util::ReadCompressed in(0);
35
+ Copy(in, 1);
36
+ } else {
37
+ for (int i = 1; i < argc; ++i) {
38
+ util::ReadCompressed in(util::OpenReadOrThrow(argv[i]));
39
+ Copy(in, 1);
40
+ }
41
+ }
42
+ } catch (const std::exception &e) {
43
+ std::cerr << e.what() << std::endl;
44
+ return 2;
45
+ }
46
+ return 0;
47
+ }
cc-multilingual-main/cc_net/third_party/kenlm/util/ersatz_progress.cc ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "ersatz_progress.hh"
2
+
3
+ #include <algorithm>
4
+ #include <ostream>
5
+ #include <limits>
6
+ #include <string>
7
+
8
+ namespace util {
9
+
10
+ namespace { const unsigned char kWidth = 100; }
11
+
12
+ const char kProgressBanner[] = "----5---10---15---20---25---30---35---40---45---50---55---60---65---70---75---80---85---90---95--100\n";
13
+
14
+ ErsatzProgress::ErsatzProgress() : current_(0), next_(std::numeric_limits<uint64_t>::max()), complete_(next_), out_(NULL) {}
15
+
16
+ ErsatzProgress::~ErsatzProgress() {
17
+ if (out_) Finished();
18
+ }
19
+
20
+ ErsatzProgress::ErsatzProgress(uint64_t complete, std::ostream *to, const std::string &message)
21
+ : current_(0), next_(complete / kWidth), complete_(complete), stones_written_(0), out_(to) {
22
+ if (!out_) {
23
+ next_ = std::numeric_limits<uint64_t>::max();
24
+ return;
25
+ }
26
+ if (!message.empty()) *out_ << message << '\n';
27
+ *out_ << kProgressBanner;
28
+ }
29
+
30
+ void ErsatzProgress::Milestone() {
31
+ if (!out_) { current_ = 0; return; }
32
+ if (!complete_) return;
33
+ unsigned char stone = std::min(static_cast<uint64_t>(kWidth), (current_ * kWidth) / complete_);
34
+
35
+ for (; stones_written_ < stone; ++stones_written_) {
36
+ (*out_) << '*';
37
+ }
38
+ if (stone == kWidth) {
39
+ (*out_) << std::endl;
40
+ next_ = std::numeric_limits<uint64_t>::max();
41
+ out_ = NULL;
42
+ } else {
43
+ next_ = std::max(next_, ((stone + 1) * complete_ + kWidth - 1) / kWidth);
44
+ }
45
+ }
46
+
47
+ } // namespace util
cc-multilingual-main/cc_net/third_party/kenlm/util/exception.cc ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "exception.hh"
2
+
3
+ #ifdef __GXX_RTTI
4
+ #include <typeinfo>
5
+ #endif
6
+
7
+ #include <cerrno>
8
+ #include <cstring>
9
+
10
+ #if defined(_WIN32) || defined(_WIN64)
11
+ #include <windows.h>
12
+ #include <io.h>
13
+ #endif
14
+
15
+ namespace util {
16
+
17
+ Exception::Exception() throw() {}
18
+ Exception::~Exception() throw() {}
19
+
20
+ void Exception::SetLocation(const char *file, unsigned int line, const char *func, const char *child_name, const char *condition) {
21
+ /* The child class might have set some text, but we want this to come first.
22
+ * Another option would be passing this information to the constructor, but
23
+ * then child classes would have to accept constructor arguments and pass
24
+ * them down.
25
+ */
26
+ std::string old_text;
27
+ what_.swap(old_text);
28
+ what_ << file << ':' << line;
29
+ if (func) what_ << " in " << func << " threw ";
30
+ if (child_name) {
31
+ what_ << child_name;
32
+ } else {
33
+ #ifdef __GXX_RTTI
34
+ what_ << typeid(this).name();
35
+ #else
36
+ what_ << "an exception";
37
+ #endif
38
+ }
39
+ if (condition) {
40
+ what_ << " because `" << condition << '\'';
41
+ }
42
+ what_ << ".\n";
43
+ what_ << old_text;
44
+ }
45
+
46
+ namespace {
47
+
48
+ #ifdef __GNUC__
49
+ const char *HandleStrerror(int ret, const char *buf) __attribute__ ((unused));
50
+ const char *HandleStrerror(const char *ret, const char * /*buf*/) __attribute__ ((unused));
51
+ #endif
52
+ // At least one of these functions will not be called.
53
+ #ifdef __clang__
54
+ #pragma clang diagnostic push
55
+ #pragma clang diagnostic ignored "-Wunused-function"
56
+ #endif
57
+ // The XOPEN version.
58
+ const char *HandleStrerror(int ret, const char *buf) {
59
+ if (!ret) return buf;
60
+ return NULL;
61
+ }
62
+
63
+ // The GNU version.
64
+ const char *HandleStrerror(const char *ret, const char * /*buf*/) {
65
+ return ret;
66
+ }
67
+ #ifdef __clang__
68
+ #pragma clang diagnostic pop
69
+ #endif
70
+ } // namespace
71
+
72
+ ErrnoException::ErrnoException() throw() : errno_(errno) {
73
+ char buf[200];
74
+ buf[0] = 0;
75
+ #if defined(sun) || defined(_WIN32) || defined(_WIN64)
76
+ const char *add = strerror(errno);
77
+ #else
78
+ const char *add = HandleStrerror(strerror_r(errno, buf, 200), buf);
79
+ #endif
80
+
81
+ if (add) {
82
+ *this << add << ' ';
83
+ }
84
+ }
85
+
86
+ ErrnoException::~ErrnoException() throw() {}
87
+
88
+ OverflowException::OverflowException() throw() {}
89
+ OverflowException::~OverflowException() throw() {}
90
+
91
+ #if defined(_WIN32) || defined(_WIN64)
92
+ WindowsException::WindowsException() throw() {
93
+ unsigned int last_error = GetLastError();
94
+ char error_msg[256] = "";
95
+ if (!FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, last_error, LANG_NEUTRAL, error_msg, sizeof(error_msg), NULL)) {
96
+ *this << "Windows error " << GetLastError() << " while formatting Windows error " << last_error << ". ";
97
+ } else {
98
+ *this << "Windows error " << last_error << ": " << error_msg;
99
+ }
100
+ }
101
+ WindowsException::~WindowsException() throw() {}
102
+ #endif
103
+
104
+ } // namespace util
cc-multilingual-main/cc_net/third_party/kenlm/util/exception.hh ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef UTIL_EXCEPTION_H
2
+ #define UTIL_EXCEPTION_H
3
+
4
+ #include "string_stream.hh"
5
+
6
+ #include <exception>
7
+ #include <limits>
8
+ #include <string>
9
+ #include <stdint.h>
10
+
11
+ namespace util {
12
+
13
+ template <class Except, class Data> typename Except::template ExceptionTag<Except&>::Identity operator<<(Except &e, const Data &data);
14
+
15
+ class Exception : public std::exception {
16
+ public:
17
+ Exception() throw();
18
+ virtual ~Exception() throw();
19
+
20
+ const char *what() const throw() { return what_.str().c_str(); }
21
+
22
+ // For use by the UTIL_THROW macros.
23
+ void SetLocation(
24
+ const char *file,
25
+ unsigned int line,
26
+ const char *func,
27
+ const char *child_name,
28
+ const char *condition);
29
+
30
+ private:
31
+ template <class Except, class Data> friend typename Except::template ExceptionTag<Except&>::Identity operator<<(Except &e, const Data &data);
32
+
33
+ // This helps restrict operator<< defined below.
34
+ template <class T> struct ExceptionTag {
35
+ typedef T Identity;
36
+ };
37
+
38
+ StringStream what_;
39
+ };
40
+
41
+ /* This implements the normal operator<< for Exception and all its children.
42
+ * SFINAE means it only applies to Exception. Think of this as an ersatz
43
+ * boost::enable_if.
44
+ */
45
+ template <class Except, class Data> typename Except::template ExceptionTag<Except&>::Identity operator<<(Except &e, const Data &data) {
46
+ e.what_ << data;
47
+ return e;
48
+ }
49
+
50
+ #ifdef __GNUC__
51
+ #define UTIL_FUNC_NAME __PRETTY_FUNCTION__
52
+ #else
53
+ #ifdef _WIN32
54
+ #define UTIL_FUNC_NAME __FUNCTION__
55
+ #else
56
+ #define UTIL_FUNC_NAME NULL
57
+ #endif
58
+ #endif
59
+
60
+ /* Create an instance of Exception, add the message Modify, and throw it.
61
+ * Modify is appended to the what() message and can contain << for ostream
62
+ * operations.
63
+ *
64
+ * do .. while kludge to swallow trailing ; character
65
+ * http://gcc.gnu.org/onlinedocs/cpp/Swallowing-the-Semicolon.html .
66
+ * Arg can be a constructor argument to the exception.
67
+ */
68
+ #define UTIL_THROW_BACKEND(Condition, Exception, Arg, Modify) do { \
69
+ Exception UTIL_e Arg; \
70
+ UTIL_e.SetLocation(__FILE__, __LINE__, UTIL_FUNC_NAME, #Exception, Condition); \
71
+ UTIL_e << Modify; \
72
+ throw UTIL_e; \
73
+ } while (0)
74
+
75
+ #define UTIL_THROW_ARG(Exception, Arg, Modify) \
76
+ UTIL_THROW_BACKEND(NULL, Exception, Arg, Modify)
77
+
78
+ #define UTIL_THROW(Exception, Modify) \
79
+ UTIL_THROW_BACKEND(NULL, Exception, , Modify);
80
+
81
+ #define UTIL_THROW2(Modify) \
82
+ UTIL_THROW_BACKEND(NULL, util::Exception, , Modify);
83
+
84
+ #if __GNUC__ >= 3
85
+ #define UTIL_UNLIKELY(x) __builtin_expect (!!(x), 0)
86
+ #else
87
+ #define UTIL_UNLIKELY(x) (x)
88
+ #endif
89
+
90
+ #if __GNUC__ >= 3
91
+ #define UTIL_LIKELY(x) __builtin_expect (!!(x), 1)
92
+ #else
93
+ #define UTIL_LIKELY(x) (x)
94
+ #endif
95
+
96
+ #define UTIL_THROW_IF_ARG(Condition, Exception, Arg, Modify) do { \
97
+ if (UTIL_UNLIKELY(Condition)) { \
98
+ UTIL_THROW_BACKEND(#Condition, Exception, Arg, Modify); \
99
+ } \
100
+ } while (0)
101
+
102
+ #define UTIL_THROW_IF(Condition, Exception, Modify) \
103
+ UTIL_THROW_IF_ARG(Condition, Exception, , Modify)
104
+
105
+ #define UTIL_THROW_IF2(Condition, Modify) \
106
+ UTIL_THROW_IF_ARG(Condition, util::Exception, , Modify)
107
+
108
+ // Exception that records errno and adds it to the message.
109
+ class ErrnoException : public Exception {
110
+ public:
111
+ ErrnoException() throw();
112
+
113
+ virtual ~ErrnoException() throw();
114
+
115
+ int Error() const throw() { return errno_; }
116
+
117
+ private:
118
+ int errno_;
119
+ };
120
+
121
+ // file wasn't there, or couldn't be open for some reason
122
+ class FileOpenException : public Exception {
123
+ public:
124
+ FileOpenException() throw() {}
125
+ ~FileOpenException() throw() {}
126
+ };
127
+
128
+ // Utilities for overflow checking.
129
+ class OverflowException : public Exception {
130
+ public:
131
+ OverflowException() throw();
132
+ ~OverflowException() throw();
133
+ };
134
+
135
+ template <unsigned len> inline std::size_t CheckOverflowInternal(uint64_t value) {
136
+ UTIL_THROW_IF(value > static_cast<uint64_t>(std::numeric_limits<std::size_t>::max()), OverflowException, "Integer overflow detected. This model is too big for 32-bit code.");
137
+ return static_cast<std::size_t>(value);
138
+ }
139
+
140
+ template <> inline std::size_t CheckOverflowInternal<8>(uint64_t value) {
141
+ return value;
142
+ }
143
+
144
+ inline std::size_t CheckOverflow(uint64_t value) {
145
+ return CheckOverflowInternal<sizeof(std::size_t)>(value);
146
+ }
147
+
148
+ #if defined(_WIN32) || defined(_WIN64)
149
+ /* Thrown for Windows specific operations. */
150
+ class WindowsException : public Exception {
151
+ public:
152
+ WindowsException() throw();
153
+ ~WindowsException() throw();
154
+ };
155
+ #endif
156
+
157
+ } // namespace util
158
+
159
+ #endif // UTIL_EXCEPTION_H
cc-multilingual-main/cc_net/third_party/kenlm/util/fake_ostream.hh ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef UTIL_FAKE_OSTREAM_H
2
+ #define UTIL_FAKE_OSTREAM_H
3
+
4
+ #include "float_to_string.hh"
5
+ #include "integer_to_string.hh"
6
+ #include "string_piece.hh"
7
+
8
+ #include <cassert>
9
+ #include <limits>
10
+
11
+ #include <stdint.h>
12
+
13
+ namespace util {
14
+
15
+ /* Like std::ostream but without being incredibly slow.
16
+ * Supports most of the built-in types except for long double.
17
+ *
18
+ * The FakeOStream class is intended to be inherited from. The inherting class
19
+ * should provide:
20
+ * public:
21
+ * Derived &flush();
22
+ * Derived &write(const void *data, std::size_t length);
23
+ *
24
+ * private: or protected:
25
+ * friend class FakeOStream;
26
+ * char *Ensure(std::size_t amount);
27
+ * void AdvanceTo(char *to);
28
+ *
29
+ * The Ensure function makes enough space for an in-place write and returns
30
+ * where to write. The AdvanceTo function happens after the write, saying how
31
+ * much was actually written.
32
+ *
33
+ * Precondition:
34
+ * amount <= kToStringMaxBytes for in-place writes.
35
+ */
36
+ template <class Derived> class FakeOStream {
37
+ public:
38
+ FakeOStream() {}
39
+
40
+ // This also covers std::string and char*
41
+ Derived &operator<<(StringPiece str) {
42
+ return C().write(str.data(), str.size());
43
+ }
44
+
45
+ // Handle integers by size and signedness.
46
+ private:
47
+ template <class Arg> struct EnableIfKludge {
48
+ typedef Derived type;
49
+ };
50
+ template <class From, unsigned Length = sizeof(From), bool Signed = std::numeric_limits<From>::is_signed, bool IsInteger = std::numeric_limits<From>::is_integer> struct Coerce {};
51
+
52
+ template <class From> struct Coerce<From, 2, false, true> { typedef uint16_t To; };
53
+ template <class From> struct Coerce<From, 4, false, true> { typedef uint32_t To; };
54
+ template <class From> struct Coerce<From, 8, false, true> { typedef uint64_t To; };
55
+
56
+ template <class From> struct Coerce<From, 2, true, true> { typedef int16_t To; };
57
+ template <class From> struct Coerce<From, 4, true, true> { typedef int32_t To; };
58
+ template <class From> struct Coerce<From, 8, true, true> { typedef int64_t To; };
59
+ public:
60
+ template <class From> typename EnableIfKludge<typename Coerce<From>::To>::type &operator<<(const From value) {
61
+ return CallToString(static_cast<typename Coerce<From>::To>(value));
62
+ }
63
+
64
+ // Character types that get copied as bytes instead of displayed as integers.
65
+ Derived &operator<<(char val) { return put(val); }
66
+ Derived &operator<<(signed char val) { return put(static_cast<char>(val)); }
67
+ Derived &operator<<(unsigned char val) { return put(static_cast<char>(val)); }
68
+
69
+ Derived &operator<<(bool val) { return put(val + '0'); }
70
+ // enums will fall back to int but are not caught by the template.
71
+ Derived &operator<<(int val) { return CallToString(static_cast<typename Coerce<int>::To>(val)); }
72
+
73
+ Derived &operator<<(float val) { return CallToString(val); }
74
+ Derived &operator<<(double val) { return CallToString(val); }
75
+
76
+ // This is here to catch all the other pointer types.
77
+ Derived &operator<<(const void *value) { return CallToString(value); }
78
+ // This is here because the above line also catches const char*.
79
+ Derived &operator<<(const char *value) { return *this << StringPiece(value); }
80
+ Derived &operator<<(char *value) { return *this << StringPiece(value); }
81
+
82
+ Derived &put(char val) {
83
+ char *c = C().Ensure(1);
84
+ *c = val;
85
+ C().AdvanceTo(++c);
86
+ return C();
87
+ }
88
+
89
+ char widen(char val) const { return val; }
90
+
91
+ private:
92
+ // References to derived class for convenience.
93
+ Derived &C() {
94
+ return *static_cast<Derived*>(this);
95
+ }
96
+
97
+ const Derived &C() const {
98
+ return *static_cast<const Derived*>(this);
99
+ }
100
+
101
+ // This is separate to prevent an infinite loop if the compiler considers
102
+ // types the same (i.e. gcc std::size_t and uint64_t or uint32_t).
103
+ template <class T> Derived &CallToString(const T value) {
104
+ C().AdvanceTo(ToString(value, C().Ensure(ToStringBuf<T>::kBytes)));
105
+ return C();
106
+ }
107
+ };
108
+
109
+ } // namespace
110
+
111
+ #endif // UTIL_FAKE_OSTREAM_H
cc-multilingual-main/cc_net/third_party/kenlm/util/file.cc ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #define _LARGEFILE64_SOURCE
2
+ #define _FILE_OFFSET_BITS 64
3
+
4
+ #include "file.hh"
5
+
6
+ #include "exception.hh"
7
+
8
+ #include <algorithm>
9
+ #include <cstdlib>
10
+ #include <cstdio>
11
+ #include <iostream>
12
+ #include <limits>
13
+ #include <stdexcept>
14
+ #include <sstream>
15
+
16
+ #include <cassert>
17
+ #include <cerrno>
18
+ #include <climits>
19
+ #include <sys/types.h>
20
+ #include <sys/stat.h>
21
+ #include <fcntl.h>
22
+ #include <stdint.h>
23
+
24
+ #if defined(__MINGW32__)
25
+ #include <windows.h>
26
+ #include <unistd.h>
27
+ #warning "The file functions on MinGW have not been tested for file sizes above 2^31 - 1. Please read https://stackoverflow.com/questions/12539488/determine-64-bit-file-size-in-c-on-mingw-32-bit and fix"
28
+ #elif defined(_WIN32) || defined(_WIN64)
29
+ #include <windows.h>
30
+ #include <io.h>
31
+ #else
32
+ #include <unistd.h>
33
+ #endif
34
+
35
+ namespace util {
36
+
37
+ scoped_fd::~scoped_fd() {
38
+ if (fd_ != -1 && close(fd_)) {
39
+ std::cerr << "Could not close file " << fd_ << std::endl;
40
+ std::abort();
41
+ }
42
+ }
43
+
44
+ void scoped_FILE_closer::Close(std::FILE *file) {
45
+ if (file && std::fclose(file)) {
46
+ std::cerr << "Could not close file " << file << std::endl;
47
+ std::abort();
48
+ }
49
+ }
50
+
51
+ // Note that ErrnoException records errno before NameFromFD is called.
52
+ FDException::FDException(int fd) throw() : fd_(fd), name_guess_(NameFromFD(fd)) {
53
+ *this << "in " << name_guess_ << ' ';
54
+ }
55
+
56
+ FDException::~FDException() throw() {}
57
+
58
+ EndOfFileException::EndOfFileException() throw() {
59
+ *this << "End of file";
60
+ }
61
+ EndOfFileException::~EndOfFileException() throw() {}
62
+
63
+ bool InputFileIsStdin(StringPiece path) {
64
+ return path == "-" || path == "/dev/stdin";
65
+ }
66
+
67
+ bool OutputFileIsStdout(StringPiece path) {
68
+ return path == "-" || path == "/dev/stdout";
69
+ }
70
+
71
+ int OpenReadOrThrow(const char *name) {
72
+ int ret;
73
+ #if defined(_WIN32) || defined(_WIN64)
74
+ UTIL_THROW_IF(-1 == (ret = _open(name, _O_BINARY | _O_RDONLY)), ErrnoException, "while opening " << name);
75
+ #else
76
+ UTIL_THROW_IF(-1 == (ret = open(name, O_RDONLY)), ErrnoException, "while opening " << name);
77
+ #endif
78
+ return ret;
79
+ }
80
+
81
+ int CreateOrThrow(const char *name) {
82
+ int ret;
83
+ #if defined(_WIN32) || defined(_WIN64)
84
+ UTIL_THROW_IF(-1 == (ret = _open(name, _O_CREAT | _O_TRUNC | _O_RDWR | _O_BINARY, _S_IREAD | _S_IWRITE)), ErrnoException, "while creating " << name);
85
+ #else
86
+ UTIL_THROW_IF(-1 == (ret = open(name, O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)), ErrnoException, "while creating " << name);
87
+ #endif
88
+ return ret;
89
+ }
90
+
91
+ uint64_t SizeFile(int fd) {
92
+ #if defined __MINGW32__
93
+ struct stat sb;
94
+ // Does this handle 64-bit?
95
+ int ret = fstat(fd, &sb);
96
+ if (ret == -1 || (!sb.st_size && !S_ISREG(sb.st_mode))) return kBadSize;
97
+ return sb.st_size;
98
+ #elif defined(_WIN32) || defined(_WIN64)
99
+ __int64 ret = _filelengthi64(fd);
100
+ return (ret == -1) ? kBadSize : ret;
101
+ #else // Not windows.
102
+
103
+ #ifdef OS_ANDROID
104
+ struct stat64 sb;
105
+ int ret = fstat64(fd, &sb);
106
+ #else
107
+ struct stat sb;
108
+ int ret = fstat(fd, &sb);
109
+ #endif
110
+ if (ret == -1 || (!sb.st_size && !S_ISREG(sb.st_mode))) return kBadSize;
111
+ return sb.st_size;
112
+ #endif
113
+ }
114
+
115
+ uint64_t SizeOrThrow(int fd) {
116
+ uint64_t ret = SizeFile(fd);
117
+ UTIL_THROW_IF_ARG(ret == kBadSize, FDException, (fd), "Failed to size");
118
+ return ret;
119
+ }
120
+
121
+ void ResizeOrThrow(int fd, uint64_t to) {
122
+ #if defined __MINGW32__
123
+ // Does this handle 64-bit?
124
+ int ret = ftruncate
125
+ #elif defined(_WIN32) || defined(_WIN64)
126
+ errno_t ret = _chsize_s
127
+ #elif defined(OS_ANDROID)
128
+ int ret = ftruncate64
129
+ #else
130
+ int ret = ftruncate
131
+ #endif
132
+ (fd, to);
133
+ UTIL_THROW_IF_ARG(ret, FDException, (fd), "while resizing to " << to << " bytes");
134
+ }
135
+
136
+ void HolePunch(int fd, uint64_t offset, uint64_t size) {
137
+ #if defined(__linux__) && defined(FALLOC_FL_PUNCH_HOLE) && defined(FALLOC_FL_KEEP_SIZE)
138
+ UTIL_THROW_IF_ARG(-1 == fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, offset, size), FDException, (fd), "in punching a hole at " << offset << " for " << size << " bytes.");
139
+ #else
140
+ UTIL_THROW(UnsupportedOSException, "fallocate hole punching requires Linux and glibc >= 2.18");
141
+ #endif
142
+ }
143
+
144
+ namespace {
145
+ std::size_t GuardLarge(std::size_t size) {
146
+ // The following operating systems have broken read/write/pread/pwrite that
147
+ // only supports up to 2^31.
148
+ // OS X man pages claim to support 64-bit, but Kareem M. Darwish had problems
149
+ // building with larger files, so APPLE is also here.
150
+ #if defined(_WIN32) || defined(_WIN64) || defined(__APPLE__) || defined(OS_ANDROID) || defined(__MINGW32__)
151
+ return size < INT_MAX ? size : INT_MAX;
152
+ #else
153
+ return size;
154
+ #endif
155
+ }
156
+ }
157
+
158
+ #if defined(_WIN32) || defined(_WIN64)
159
+ namespace {
160
+ const std::size_t kMaxDWORD = static_cast<std::size_t>(4294967295UL);
161
+ } // namespace
162
+ #endif
163
+
164
+ std::size_t PartialRead(int fd, void *to, std::size_t amount) {
165
+ #if defined(_WIN32) || defined(_WIN64)
166
+ DWORD ret;
167
+ HANDLE file_handle = reinterpret_cast<HANDLE>(_get_osfhandle(fd));
168
+ DWORD larger_size = static_cast<DWORD>(std::min<std::size_t>(kMaxDWORD, amount));
169
+ DWORD smaller_size = 28672; // Received reports that 31346 worked but higher values did not. This rounds down to the nearest multiple of 4096, the page size.
170
+ if (!ReadFile(file_handle, to, larger_size, &ret, NULL))
171
+ {
172
+ DWORD last_error = GetLastError();
173
+ if (last_error != ERROR_NOT_ENOUGH_MEMORY || !ReadFile(file_handle, to, smaller_size, &ret, NULL)) {
174
+ UTIL_THROW(WindowsException, "Windows error in ReadFile.");
175
+ }
176
+ }
177
+ #else
178
+ errno = 0;
179
+ ssize_t ret;
180
+ do {
181
+ ret = read(fd, to, GuardLarge(amount));
182
+ } while (ret == -1 && errno == EINTR);
183
+ UTIL_THROW_IF_ARG(ret < 0, FDException, (fd), "while reading " << amount << " bytes");
184
+ #endif
185
+ return static_cast<std::size_t>(ret);
186
+ }
187
+
188
+ void ReadOrThrow(int fd, void *to_void, std::size_t amount) {
189
+ uint8_t *to = static_cast<uint8_t*>(to_void);
190
+ while (amount) {
191
+ std::size_t ret = PartialRead(fd, to, amount);
192
+ UTIL_THROW_IF(ret == 0, EndOfFileException, " in " << NameFromFD(fd) << " but there should be " << amount << " more bytes to read.");
193
+ amount -= ret;
194
+ to += ret;
195
+ }
196
+ }
197
+
198
+ std::size_t ReadOrEOF(int fd, void *to_void, std::size_t amount) {
199
+ uint8_t *to = static_cast<uint8_t*>(to_void);
200
+ std::size_t remaining = amount;
201
+ while (remaining) {
202
+ std::size_t ret = PartialRead(fd, to, remaining);
203
+ if (!ret) return amount - remaining;
204
+ remaining -= ret;
205
+ to += ret;
206
+ }
207
+ return amount;
208
+ }
209
+
210
+ void WriteOrThrow(int fd, const void *data_void, std::size_t size) {
211
+ const uint8_t *data = static_cast<const uint8_t*>(data_void);
212
+ while (size) {
213
+ #if defined(_WIN32) || defined(_WIN64)
214
+ int ret;
215
+ #else
216
+ ssize_t ret;
217
+ #endif
218
+ errno = 0;
219
+ do {
220
+ ret =
221
+ #if defined(_WIN32) || defined(_WIN64)
222
+ _write
223
+ #else
224
+ write
225
+ #endif
226
+ (fd, data, GuardLarge(size));
227
+ } while (ret == -1 && errno == EINTR);
228
+ UTIL_THROW_IF_ARG(ret < 1, FDException, (fd), "while writing " << size << " bytes");
229
+ data += ret;
230
+ size -= ret;
231
+ }
232
+ }
233
+
234
+ void WriteOrThrow(FILE *to, const void *data, std::size_t size) {
235
+ if (!size) return;
236
+ UTIL_THROW_IF(1 != std::fwrite(data, size, 1, to), ErrnoException, "Short write; requested size " << size);
237
+ }
238
+
239
+ void ErsatzPRead(int fd, void *to_void, std::size_t size, uint64_t off) {
240
+ uint8_t *to = static_cast<uint8_t*>(to_void);
241
+ while (size) {
242
+ #if defined(_WIN32) || defined(_WIN64)
243
+ /* BROKEN: changes file pointer. Even if you save it and change it back, it won't be safe to use concurrently with write() or read() which lmplz does. */
244
+ // size_t might be 64-bit. DWORD is always 32.
245
+ DWORD reading = static_cast<DWORD>(std::min<std::size_t>(kMaxDWORD, size));
246
+ DWORD ret;
247
+ OVERLAPPED overlapped;
248
+ memset(&overlapped, 0, sizeof(OVERLAPPED));
249
+ overlapped.Offset = static_cast<DWORD>(off);
250
+ overlapped.OffsetHigh = static_cast<DWORD>(off >> 32);
251
+ UTIL_THROW_IF(!ReadFile((HANDLE)_get_osfhandle(fd), to, reading, &ret, &overlapped), WindowsException, "ReadFile failed for offset " << off);
252
+ #else
253
+ ssize_t ret;
254
+ errno = 0;
255
+ ret =
256
+ #ifdef OS_ANDROID
257
+ pread64
258
+ #else
259
+ pread
260
+ #endif
261
+ (fd, to, GuardLarge(size), off);
262
+ if (ret <= 0) {
263
+ if (ret == -1 && errno == EINTR) continue;
264
+ UTIL_THROW_IF(ret == 0, EndOfFileException, " for reading " << size << " bytes at " << off << " from " << NameFromFD(fd));
265
+ UTIL_THROW_ARG(FDException, (fd), "while reading " << size << " bytes at offset " << off);
266
+ }
267
+ #endif
268
+ size -= ret;
269
+ off += ret;
270
+ to += ret;
271
+ }
272
+ }
273
+
274
+ void ErsatzPWrite(int fd, const void *from_void, std::size_t size, uint64_t off) {
275
+ const uint8_t *from = static_cast<const uint8_t*>(from_void);
276
+ while(size) {
277
+ #if defined(_WIN32) || defined(_WIN64)
278
+ /* Changes file pointer. Even if you save it and change it back, it won't be safe to use concurrently with write() or read() */
279
+ // size_t might be 64-bit. DWORD is always 32.
280
+ DWORD writing = static_cast<DWORD>(std::min<std::size_t>(kMaxDWORD, size));
281
+ DWORD ret;
282
+ OVERLAPPED overlapped;
283
+ memset(&overlapped, 0, sizeof(OVERLAPPED));
284
+ overlapped.Offset = static_cast<DWORD>(off);
285
+ overlapped.OffsetHigh = static_cast<DWORD>(off >> 32);
286
+ UTIL_THROW_IF(!WriteFile((HANDLE)_get_osfhandle(fd), from, writing, &ret, &overlapped), Exception, "WriteFile failed for offset " << off);
287
+ #else
288
+ ssize_t ret;
289
+ errno = 0;
290
+ ret =
291
+ #ifdef OS_ANDROID
292
+ pwrite64
293
+ #else
294
+ pwrite
295
+ #endif
296
+ (fd, from, GuardLarge(size), off);
297
+ if (ret <= 0) {
298
+ if (ret == -1 && errno == EINTR) continue;
299
+ UTIL_THROW_IF(ret == 0, EndOfFileException, " for writing " << size << " bytes at " << off << " from " << NameFromFD(fd));
300
+ UTIL_THROW_ARG(FDException, (fd), "while writing " << size << " bytes at offset " << off);
301
+ }
302
+ #endif
303
+ size -= ret;
304
+ off += ret;
305
+ from += ret;
306
+ }
307
+ }
308
+
309
+
310
+ void FSyncOrThrow(int fd) {
311
+ // Apparently windows doesn't have fsync?
312
+ #if !defined(_WIN32) && !defined(_WIN64)
313
+ UTIL_THROW_IF_ARG(-1 == fsync(fd), FDException, (fd), "while syncing");
314
+ #endif
315
+ }
316
+
317
+ namespace {
318
+
319
+ // Static assert for 64-bit off_t size.
320
+ #if !defined(_WIN32) && !defined(_WIN64) && !defined(OS_ANDROID)
321
+ template <unsigned> struct CheckOffT;
322
+ template <> struct CheckOffT<8> {
323
+ struct True {};
324
+ };
325
+ // If there's a compiler error on the next line, then off_t isn't 64 bit. And
326
+ // that makes me a sad panda.
327
+ typedef CheckOffT<sizeof(off_t)>::True IgnoredType;
328
+ #endif
329
+
330
+ // Can't we all just get along?
331
+ uint64_t InternalSeek(int fd, int64_t off, int whence) {
332
+ #if defined __MINGW32__
333
+ // Does this handle 64-bit?
334
+ typedef off_t Offset;
335
+ Offset ret = lseek(fd, off, whence);
336
+ #elif defined(_WIN32) || defined(_WIN64)
337
+ typedef __int64 Offset;
338
+ Offset ret = _lseeki64(fd, off, whence);
339
+ #elif defined(OS_ANDROID)
340
+ typedef off64_t Offset;
341
+ Offset ret = lseek64(fd, off, whence);
342
+ #else
343
+ typedef off_t Offset;
344
+ Offset ret = lseek(fd, off, whence);
345
+ #endif
346
+ UTIL_THROW_IF_ARG((Offset)-1 == ret, FDException, (fd), "while seeking to " << off << " whence " << whence);
347
+ return (uint64_t)ret;
348
+ }
349
+ } // namespace
350
+
351
+ uint64_t SeekOrThrow(int fd, uint64_t off) {
352
+ return InternalSeek(fd, off, SEEK_SET);
353
+ }
354
+
355
+ uint64_t AdvanceOrThrow(int fd, int64_t off) {
356
+ return InternalSeek(fd, off, SEEK_CUR);
357
+ }
358
+
359
+ uint64_t SeekEnd(int fd) {
360
+ return InternalSeek(fd, 0, SEEK_END);
361
+ }
362
+
363
+ std::FILE *FDOpenOrThrow(scoped_fd &file) {
364
+ std::FILE *ret = fdopen(file.get(), "r+b");
365
+ UTIL_THROW_IF_ARG(!ret, FDException, (file.get()), "Could not fdopen for write");
366
+ file.release();
367
+ return ret;
368
+ }
369
+
370
+ std::FILE *FDOpenReadOrThrow(scoped_fd &file) {
371
+ std::FILE *ret = fdopen(file.get(), "rb");
372
+ UTIL_THROW_IF_ARG(!ret, FDException, (file.get()), "Could not fdopen for read");
373
+ file.release();
374
+ return ret;
375
+ }
376
+
377
+ // Sigh. Windows temporary file creation is full of race conditions.
378
+ #if defined(_WIN32) || defined(_WIN64)
379
+ /* mkstemp extracted from libc/sysdeps/posix/tempname.c. Copyright
380
+ (C) 1991-1999, 2000, 2001, 2006 Free Software Foundation, Inc.
381
+
382
+ The GNU C Library is free software; you can redistribute it and/or
383
+ modify it under the terms of the GNU Lesser General Public
384
+ License as published by the Free Software Foundation; either
385
+ version 2.1 of the License, or (at your option) any later version. */
386
+
387
+ /* This has been modified from the original version to rename the function and
388
+ * set the Windows temporary flag. */
389
+
390
+ static const char letters[] =
391
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
392
+
393
+ /* Generate a temporary file name based on TMPL. TMPL must match the
394
+ rules for mk[s]temp (i.e. end in "XXXXXX"). The name constructed
395
+ does not exist at the time of the call to mkstemp. TMPL is
396
+ overwritten with the result. */
397
+ int
398
+ mkstemp_and_unlink(char *tmpl)
399
+ {
400
+ int len;
401
+ char *XXXXXX;
402
+ static unsigned long long value;
403
+ unsigned long long random_time_bits;
404
+ unsigned int count;
405
+ int fd = -1;
406
+ int save_errno = errno;
407
+
408
+ /* A lower bound on the number of temporary files to attempt to
409
+ generate. The maximum total number of temporary file names that
410
+ can exist for a given template is 62**6. It should never be
411
+ necessary to try all these combinations. Instead if a reasonable
412
+ number of names is tried (we define reasonable as 62**3) fail to
413
+ give the system administrator the chance to remove the problems. */
414
+ #define ATTEMPTS_MIN (62 * 62 * 62)
415
+
416
+ /* The number of times to attempt to generate a temporary file. To
417
+ conform to POSIX, this must be no smaller than TMP_MAX. */
418
+ #if ATTEMPTS_MIN < TMP_MAX
419
+ unsigned int attempts = TMP_MAX;
420
+ #else
421
+ unsigned int attempts = ATTEMPTS_MIN;
422
+ #endif
423
+
424
+ len = strlen (tmpl);
425
+ if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
426
+ {
427
+ errno = EINVAL;
428
+ return -1;
429
+ }
430
+
431
+ /* This is where the Xs start. */
432
+ XXXXXX = &tmpl[len - 6];
433
+
434
+ /* Get some more or less random data. */
435
+ {
436
+ SYSTEMTIME stNow;
437
+ FILETIME ftNow;
438
+
439
+ // get system time
440
+ GetSystemTime(&stNow);
441
+ stNow.wMilliseconds = 500;
442
+ if (!SystemTimeToFileTime(&stNow, &ftNow))
443
+ {
444
+ errno = -1;
445
+ return -1;
446
+ }
447
+
448
+ random_time_bits = (((unsigned long long)ftNow.dwHighDateTime << 32)
449
+ | (unsigned long long)ftNow.dwLowDateTime);
450
+ }
451
+ value += random_time_bits ^ (unsigned long long)GetCurrentThreadId ();
452
+
453
+ for (count = 0; count < attempts; value += 7777, ++count)
454
+ {
455
+ unsigned long long v = value;
456
+
457
+ /* Fill in the random bits. */
458
+ XXXXXX[0] = letters[v % 62];
459
+ v /= 62;
460
+ XXXXXX[1] = letters[v % 62];
461
+ v /= 62;
462
+ XXXXXX[2] = letters[v % 62];
463
+ v /= 62;
464
+ XXXXXX[3] = letters[v % 62];
465
+ v /= 62;
466
+ XXXXXX[4] = letters[v % 62];
467
+ v /= 62;
468
+ XXXXXX[5] = letters[v % 62];
469
+
470
+ /* Modified for windows and to unlink */
471
+ // fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL, _S_IREAD | _S_IWRITE);
472
+ int flags = _O_RDWR | _O_CREAT | _O_EXCL | _O_BINARY;
473
+ flags |= _O_TEMPORARY;
474
+ fd = _open (tmpl, flags, _S_IREAD | _S_IWRITE);
475
+ if (fd >= 0)
476
+ {
477
+ errno = save_errno;
478
+ return fd;
479
+ }
480
+ else if (errno != EEXIST)
481
+ return -1;
482
+ }
483
+
484
+ /* We got out of the loop because we ran out of combinations to try. */
485
+ errno = EEXIST;
486
+ return -1;
487
+ }
488
+ #else
489
+ int
490
+ mkstemp_and_unlink(char *tmpl) {
491
+ int ret = mkstemp(tmpl);
492
+ if (ret != -1) {
493
+ UTIL_THROW_IF(unlink(tmpl), ErrnoException, "while deleting " << tmpl);
494
+ }
495
+ return ret;
496
+ }
497
+ #endif
498
+
499
+ // If it's a directory, add a /. This lets users say -T /tmp without creating
500
+ // /tmpAAAAAA
501
+ void NormalizeTempPrefix(std::string &base) {
502
+ if (base.empty()) return;
503
+ if (base[base.size() - 1] == '/') return;
504
+ struct stat sb;
505
+ // It's fine for it to not exist.
506
+ if (-1 == stat(base.c_str(), &sb)) return;
507
+ if (
508
+ #if defined(_WIN32) || defined(_WIN64)
509
+ sb.st_mode & _S_IFDIR
510
+ #else
511
+ S_ISDIR(sb.st_mode)
512
+ #endif
513
+ ) base += '/';
514
+ }
515
+
516
+ int MakeTemp(const StringPiece &base) {
517
+ std::string name(base.data(), base.size());
518
+ name += "XXXXXX";
519
+ name.push_back(0);
520
+ int ret;
521
+ UTIL_THROW_IF(-1 == (ret = mkstemp_and_unlink(&name[0])), ErrnoException, "while making a temporary based on " << base);
522
+ return ret;
523
+ }
524
+
525
+ std::FILE *FMakeTemp(const StringPiece &base) {
526
+ util::scoped_fd file(MakeTemp(base));
527
+ return FDOpenOrThrow(file);
528
+ }
529
+
530
+ std::string DefaultTempDirectory() {
531
+ #if defined(_WIN32) || defined(_WIN64)
532
+ char dir_buffer[1000];
533
+ if (GetTempPath(1000, dir_buffer) == 0)
534
+ throw std::runtime_error("Could not read temporary directory.");
535
+ std::string ret(dir_buffer);
536
+ NormalizeTempPrefix(ret);
537
+ return ret;
538
+ #else
539
+ // POSIX says to try these environment variables, in this order:
540
+ const char *const vars[] = {"TMPDIR", "TMP", "TEMPDIR", "TEMP", 0};
541
+ for (int i=0; vars[i]; ++i) {
542
+ char *val =
543
+ #if defined(_GNU_SOURCE) && defined(__GLIBC_PREREQ)
544
+ #if __GLIBC_PREREQ(2,17)
545
+ secure_getenv
546
+ #else // __GLIBC_PREREQ
547
+ getenv
548
+ #endif // __GLIBC_PREREQ
549
+ #else // _GNU_SOURCE
550
+ getenv
551
+ #endif
552
+ (vars[i]);
553
+ // Environment variable is set and nonempty. Use it.
554
+ if (val && *val) {
555
+ std::string ret(val);
556
+ NormalizeTempPrefix(ret);
557
+ return ret;
558
+ }
559
+ }
560
+ // No environment variables set. Default to /tmp.
561
+ return "/tmp/";
562
+ #endif
563
+ }
564
+
565
+ int DupOrThrow(int fd) {
566
+ int ret = dup(fd);
567
+ UTIL_THROW_IF_ARG(ret == -1, FDException, (fd), "in duplicating the file descriptor");
568
+ return ret;
569
+ }
570
+
571
+ namespace {
572
+ // Try to name things but be willing to fail too.
573
+ bool TryName(int fd, std::string &out) {
574
+ #if defined(_WIN32) || defined(_WIN64)
575
+ return false;
576
+ #else
577
+ std::string name("/proc/self/fd/");
578
+ std::ostringstream convert;
579
+ convert << fd;
580
+ name += convert.str();
581
+
582
+ struct stat sb;
583
+ if (-1 == lstat(name.c_str(), &sb))
584
+ return false;
585
+ out.resize(sb.st_size + 1);
586
+ // lstat gave us a size, but I've seen it grow, possibly due to symlinks on top of symlinks.
587
+ while (true) {
588
+ ssize_t ret = readlink(name.c_str(), &out[0], out.size());
589
+ if (-1 == ret)
590
+ return false;
591
+ if ((size_t)ret < out.size()) {
592
+ out.resize(ret);
593
+ break;
594
+ }
595
+ // Exponential growth.
596
+ out.resize(out.size() * 2);
597
+ }
598
+ // Don't use the non-file names.
599
+ if (!out.empty() && out[0] != '/')
600
+ return false;
601
+ return true;
602
+ #endif
603
+ }
604
+ } // namespace
605
+
606
+ std::string NameFromFD(int fd) {
607
+ std::string ret;
608
+ if (TryName(fd, ret)) return ret;
609
+ switch (fd) {
610
+ case 0: return "stdin";
611
+ case 1: return "stdout";
612
+ case 2: return "stderr";
613
+ }
614
+ ret = "fd ";
615
+ std::ostringstream convert;
616
+ convert << fd;
617
+ ret += convert.str();
618
+ return ret;
619
+ }
620
+
621
+ } // namespace util
cc-multilingual-main/cc_net/third_party/kenlm/util/file.hh ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef UTIL_FILE_H
2
+ #define UTIL_FILE_H
3
+
4
+ #include "exception.hh"
5
+ #include "scoped.hh"
6
+ #include "string_piece.hh"
7
+
8
+ #include <cstddef>
9
+ #include <cstdio>
10
+ #include <string>
11
+ #include <stdint.h>
12
+
13
+ namespace util {
14
+
15
+ class scoped_fd {
16
+ public:
17
+ scoped_fd() : fd_(-1) {}
18
+
19
+ explicit scoped_fd(int fd) : fd_(fd) {}
20
+
21
+ ~scoped_fd();
22
+
23
+ #if __cplusplus >= 201103L
24
+ scoped_fd(scoped_fd &&from) noexcept : fd_(from.fd_) {
25
+ from.fd_ = -1;
26
+ }
27
+ #endif
28
+
29
+ void reset(int to = -1) {
30
+ scoped_fd other(fd_);
31
+ fd_ = to;
32
+ }
33
+
34
+ int get() const { return fd_; }
35
+
36
+ int operator*() const { return fd_; }
37
+
38
+ int release() {
39
+ int ret = fd_;
40
+ fd_ = -1;
41
+ return ret;
42
+ }
43
+
44
+ private:
45
+ int fd_;
46
+
47
+ scoped_fd(const scoped_fd &);
48
+ scoped_fd &operator=(const scoped_fd &);
49
+ };
50
+
51
+ struct scoped_FILE_closer {
52
+ static void Close(std::FILE *file);
53
+ };
54
+ typedef scoped<std::FILE, scoped_FILE_closer> scoped_FILE;
55
+
56
+ /* Thrown for any operation where the fd is known. */
57
+ class FDException : public ErrnoException {
58
+ public:
59
+ explicit FDException(int fd) throw();
60
+
61
+ virtual ~FDException() throw();
62
+
63
+ // This may no longer be valid if the exception was thrown past open.
64
+ int FD() const { return fd_; }
65
+
66
+ // Guess from NameFromFD.
67
+ const std::string &NameGuess() const { return name_guess_; }
68
+
69
+ private:
70
+ int fd_;
71
+
72
+ std::string name_guess_;
73
+ };
74
+
75
+ // End of file reached.
76
+ class EndOfFileException : public Exception {
77
+ public:
78
+ EndOfFileException() throw();
79
+ ~EndOfFileException() throw();
80
+ };
81
+
82
+ class UnsupportedOSException : public Exception {};
83
+
84
+ // Open for read only.
85
+ int OpenReadOrThrow(const char *name);
86
+ // Create file if it doesn't exist, truncate if it does. Opened for write.
87
+ int CreateOrThrow(const char *name);
88
+
89
+ /** Does the given input file path denote standard input?
90
+ *
91
+ * Returns true if, and only if, path is either "-" or "/dev/stdin".
92
+ *
93
+ * Opening standard input as a file may need some special treatment for
94
+ * portability. There's a convention that a dash ("-") in place of an input
95
+ * file path denotes standard input, but opening "/dev/stdin" may need to be
96
+ * special as well.
97
+ */
98
+ bool InputPathIsStdin(StringPiece path);
99
+
100
+ /** Does the given output file path denote standard output?
101
+ *
102
+ * Returns true if, and only if, path is either "-" or "/dev/stdout".
103
+ *
104
+ * Opening standard output as a file may need some special treatment for
105
+ * portability. There's a convention that a dash ("-") in place of an output
106
+ * file path denotes standard output, but opening "/dev/stdout" may need to be
107
+ * special as well.
108
+ */
109
+ bool OutputPathIsStdout(StringPiece path);
110
+
111
+ // Return value for SizeFile when it can't size properly.
112
+ const uint64_t kBadSize = (uint64_t)-1;
113
+ uint64_t SizeFile(int fd);
114
+ uint64_t SizeOrThrow(int fd);
115
+
116
+ void ResizeOrThrow(int fd, uint64_t to);
117
+
118
+ // It bothers me that fallocate has offset before size while pread has size
119
+ // before offset. But best to follow the call.
120
+ void HolePunch(int fd, uint64_t offset, uint64_t size);
121
+
122
+ std::size_t PartialRead(int fd, void *to, std::size_t size);
123
+ void ReadOrThrow(int fd, void *to, std::size_t size);
124
+ std::size_t ReadOrEOF(int fd, void *to_void, std::size_t size);
125
+
126
+ void WriteOrThrow(int fd, const void *data_void, std::size_t size);
127
+ void WriteOrThrow(FILE *to, const void *data, std::size_t size);
128
+
129
+ /* These call pread/pwrite in a loop. However, on Windows they call ReadFile/
130
+ * WriteFile which changes the file pointer. So it's safe to call ErsatzPRead
131
+ * and ErsatzPWrite concurrently (or any combination thereof). But it changes
132
+ * the file pointer on windows, so it's not safe to call concurrently with
133
+ * anything that uses the implicit file pointer e.g. the Read/Write functions
134
+ * above.
135
+ */
136
+ void ErsatzPRead(int fd, void *to, std::size_t size, uint64_t off);
137
+ void ErsatzPWrite(int fd, const void *data_void, std::size_t size, uint64_t off);
138
+
139
+ void FSyncOrThrow(int fd);
140
+
141
+ // Seeking: returns offset
142
+ uint64_t SeekOrThrow(int fd, uint64_t off);
143
+ uint64_t AdvanceOrThrow(int fd, int64_t off);
144
+ uint64_t SeekEnd(int fd);
145
+
146
+ std::FILE *FDOpenOrThrow(scoped_fd &file);
147
+ std::FILE *FDOpenReadOrThrow(scoped_fd &file);
148
+
149
+ // Temporary files
150
+ // Append a / if base is a directory.
151
+ void NormalizeTempPrefix(std::string &base);
152
+ int MakeTemp(const StringPiece &prefix);
153
+ std::FILE *FMakeTemp(const StringPiece &prefix);
154
+
155
+ // Where should we put temporary files? Handles all the windows/POSIX defaults fun.
156
+ std::string DefaultTempDirectory();
157
+
158
+ // dup an fd.
159
+ int DupOrThrow(int fd);
160
+
161
+ /* Attempt get file name from fd. This won't always work (i.e. on Windows or
162
+ * a pipe). The file might have been renamed. It's intended for diagnostics
163
+ * and logging only.
164
+ */
165
+ std::string NameFromFD(int fd);
166
+
167
+ } // namespace util
168
+
169
+ #endif // UTIL_FILE_H
cc-multilingual-main/cc_net/third_party/kenlm/util/file_piece.cc ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "file_piece.hh"
2
+
3
+ #include "double-conversion/double-conversion.h"
4
+ #include "exception.hh"
5
+ #include "file.hh"
6
+ #include "mmap.hh"
7
+
8
+ #if defined(_WIN32) || defined(_WIN64)
9
+ #include <io.h>
10
+ #else
11
+ #include <unistd.h>
12
+ #endif
13
+
14
+ #include <algorithm>
15
+ #include <cassert>
16
+ #include <cerrno>
17
+ #include <cmath>
18
+ #include <cstdlib>
19
+ #include <iostream>
20
+ #include <limits>
21
+ #include <string>
22
+
23
+ #include <fcntl.h>
24
+ #include <sys/types.h>
25
+ #include <sys/stat.h>
26
+
27
+ #if defined(_WIN32) || defined(_WIN64)
28
+ #include <math.h>
29
+ #endif
30
+
31
+ namespace util {
32
+
33
+ namespace { const uint64_t kPageSize = SizePage(); }
34
+
35
+ ParseNumberException::ParseNumberException(StringPiece value) throw() {
36
+ *this << "Could not parse \"" << value << "\" into a ";
37
+ }
38
+
39
+ LineIterator &LineIterator::operator++() {
40
+ if (!backing_->ReadLineOrEOF(line_, delim_))
41
+ backing_ = NULL;
42
+ return *this;
43
+ }
44
+
45
+ FilePiece::FilePiece(const char *name, std::ostream *show_progress, std::size_t min_buffer) :
46
+ file_(OpenReadOrThrow(name)), total_size_(SizeFile(file_.get())),
47
+ progress_(total_size_, total_size_ == kBadSize ? NULL : show_progress, std::string("Reading ") + name) {
48
+ Initialize(name, show_progress, min_buffer);
49
+ }
50
+
51
+ namespace {
52
+ std::string NamePossiblyFind(int fd, const char *name) {
53
+ if (name) return name;
54
+ return NameFromFD(fd);
55
+ }
56
+ } // namespace
57
+
58
+ FilePiece::FilePiece(int fd, const char *name, std::ostream *show_progress, std::size_t min_buffer) :
59
+ file_(fd), total_size_(SizeFile(file_.get())),
60
+ progress_(total_size_, total_size_ == kBadSize ? NULL : show_progress, std::string("Reading ") + NamePossiblyFind(fd, name)) {
61
+ Initialize(NamePossiblyFind(fd, name).c_str(), show_progress, min_buffer);
62
+ }
63
+
64
+ FilePiece::FilePiece(std::istream &stream, const char * /*name*/, std::size_t min_buffer) :
65
+ total_size_(kBadSize) {
66
+ InitializeNoRead("istream", min_buffer);
67
+
68
+ fallback_to_read_ = true;
69
+ HugeMalloc(default_map_size_, false, data_);
70
+ position_ = data_.begin();
71
+ position_end_ = position_;
72
+
73
+ fell_back_.Reset(stream);
74
+ }
75
+
76
+ StringPiece FilePiece::ReadLine(char delim, bool strip_cr) {
77
+ std::size_t skip = 0;
78
+ while (true) {
79
+ const char *i = std::find(position_ + skip, position_end_, delim);
80
+ if (UTIL_LIKELY(i != position_end_)) {
81
+ // End of line.
82
+ // Take 1 byte off the end if it's an unwanted carriage return.
83
+ const std::size_t subtract_cr = (
84
+ (strip_cr && i > position_ && *(i - 1) == '\r') ?
85
+ 1 : 0);
86
+ StringPiece ret(position_, i - position_ - subtract_cr);
87
+ position_ = i + 1;
88
+ return ret;
89
+ }
90
+ if (at_end_) {
91
+ if (position_ == position_end_) {
92
+ Shift();
93
+ }
94
+ return Consume(position_end_);
95
+ }
96
+ skip = position_end_ - position_;
97
+ Shift();
98
+ }
99
+ }
100
+
101
+ bool FilePiece::ReadLineOrEOF(StringPiece &to, char delim, bool strip_cr) {
102
+ try {
103
+ to = ReadLine(delim, strip_cr);
104
+ } catch (const util::EndOfFileException &e) { return false; }
105
+ return true;
106
+ }
107
+
108
+ float FilePiece::ReadFloat() {
109
+ return ReadNumber<float>();
110
+ }
111
+ double FilePiece::ReadDouble() {
112
+ return ReadNumber<double>();
113
+ }
114
+ long int FilePiece::ReadLong() {
115
+ return ReadNumber<long int>();
116
+ }
117
+ unsigned long int FilePiece::ReadULong() {
118
+ return ReadNumber<unsigned long int>();
119
+ }
120
+
121
+ // Factored out so that istream can call this.
122
+ void FilePiece::InitializeNoRead(const char *name, std::size_t min_buffer) {
123
+ file_name_ = name;
124
+
125
+ default_map_size_ = kPageSize * std::max<std::size_t>((min_buffer / kPageSize + 1), 2);
126
+ position_ = NULL;
127
+ position_end_ = NULL;
128
+ mapped_offset_ = 0;
129
+ at_end_ = false;
130
+ }
131
+
132
+ void FilePiece::Initialize(const char *name, std::ostream *show_progress, std::size_t min_buffer) {
133
+ InitializeNoRead(name, min_buffer);
134
+ uint64_t current_offset;
135
+ bool valid_current_offset;
136
+ try {
137
+ current_offset = AdvanceOrThrow(file_.get(), 0);
138
+ valid_current_offset = true;
139
+ } catch (const FDException &) {
140
+ current_offset = 0;
141
+ valid_current_offset = false;
142
+ }
143
+
144
+ // So the assertion in TransitionToRead passes
145
+ fallback_to_read_ = false;
146
+ if (total_size_ == kBadSize || !valid_current_offset) {
147
+ if (show_progress)
148
+ *show_progress << "File " << name << " isn't normal. Using slower read() instead of mmap(). No progress bar." << std::endl;
149
+ TransitionToRead();
150
+ } else {
151
+ mapped_offset_ = current_offset;
152
+ }
153
+ Shift();
154
+ // gzip detect.
155
+ if ((position_end_ >= position_ + ReadCompressed::kMagicSize) && ReadCompressed::DetectCompressedMagic(position_)) {
156
+ if (!fallback_to_read_) {
157
+ at_end_ = false;
158
+ TransitionToRead();
159
+ }
160
+ }
161
+ }
162
+
163
+ namespace {
164
+
165
+ static const double_conversion::StringToDoubleConverter kConverter(
166
+ double_conversion::StringToDoubleConverter::ALLOW_TRAILING_JUNK | double_conversion::StringToDoubleConverter::ALLOW_LEADING_SPACES,
167
+ std::numeric_limits<double>::quiet_NaN(),
168
+ std::numeric_limits<double>::quiet_NaN(),
169
+ "inf",
170
+ "NaN");
171
+
172
+ StringPiece FirstToken(StringPiece str) {
173
+ const char *i;
174
+ for (i = str.data(); i != str.data() + str.size(); ++i) {
175
+ if (kSpaces[(unsigned char)*i]) break;
176
+ }
177
+ return StringPiece(str.data(), i - str.data());
178
+ }
179
+
180
+ // std::isnan is technically C++11 not C++98. But in practice this is a problem for visual studio.
181
+ template <class T> inline int CrossPlatformIsNaN(T value) {
182
+ #if defined(_WIN32) || defined(_WIN64)
183
+ return isnan(value);
184
+ #else
185
+ return std::isnan(value);
186
+ #endif
187
+ }
188
+
189
+ const char *ParseNumber(StringPiece str, float &out) {
190
+ int count;
191
+ out = kConverter.StringToFloat(str.data(), str.size(), &count);
192
+ UTIL_THROW_IF_ARG(CrossPlatformIsNaN(out) && str != "NaN" && str != "nan", ParseNumberException, (FirstToken(str)), "float");
193
+ return str.data() + count;
194
+ }
195
+ const char *ParseNumber(StringPiece str, double &out) {
196
+ int count;
197
+ out = kConverter.StringToDouble(str.data(), str.size(), &count);
198
+ UTIL_THROW_IF_ARG(CrossPlatformIsNaN(out) && str != "NaN" && str != "nan", ParseNumberException, (FirstToken(str)), "double");
199
+ return str.data() + count;
200
+ }
201
+ const char *ParseNumber(StringPiece str, long int &out) {
202
+ char *end;
203
+ errno = 0;
204
+ out = strtol(str.data(), &end, 10);
205
+ UTIL_THROW_IF_ARG(errno || (end == str.data()), ParseNumberException, (FirstToken(str)), "long int");
206
+ return end;
207
+ }
208
+ const char *ParseNumber(StringPiece str, unsigned long int &out) {
209
+ char *end;
210
+ errno = 0;
211
+ out = strtoul(str.data(), &end, 10);
212
+ UTIL_THROW_IF_ARG(errno || (end == str.data()), ParseNumberException, (FirstToken(str)), "unsigned long int");
213
+ return end;
214
+ }
215
+ } // namespace
216
+
217
+ template <class T> T FilePiece::ReadNumber() {
218
+ SkipSpaces();
219
+ while (last_space_ < position_) {
220
+ if (UTIL_UNLIKELY(at_end_)) {
221
+ // Hallucinate a null off the end of the file.
222
+ std::string buffer(position_, position_end_);
223
+ T ret;
224
+ // Has to be null-terminated.
225
+ const char *begin = buffer.c_str();
226
+ const char *end = ParseNumber(StringPiece(begin, buffer.size()), ret);
227
+ position_ += end - begin;
228
+ return ret;
229
+ }
230
+ Shift();
231
+ }
232
+ T ret;
233
+ position_ = ParseNumber(StringPiece(position_, last_space_ - position_), ret);
234
+ return ret;
235
+ }
236
+
237
+ const char *FilePiece::FindDelimiterOrEOF(const bool *delim) {
238
+ std::size_t skip = 0;
239
+ while (true) {
240
+ for (const char *i = position_ + skip; i < position_end_; ++i) {
241
+ if (delim[static_cast<unsigned char>(*i)]) return i;
242
+ }
243
+ if (at_end_) {
244
+ if (position_ == position_end_) Shift();
245
+ return position_end_;
246
+ }
247
+ skip = position_end_ - position_;
248
+ Shift();
249
+ }
250
+ }
251
+
252
+ void FilePiece::Shift() {
253
+ if (at_end_) {
254
+ progress_.Finished();
255
+ throw EndOfFileException();
256
+ }
257
+ uint64_t desired_begin = position_ - data_.begin() + mapped_offset_;
258
+
259
+ if (!fallback_to_read_) MMapShift(desired_begin);
260
+ // Notice an mmap failure might set the fallback.
261
+ if (fallback_to_read_) ReadShift();
262
+
263
+ for (last_space_ = position_end_ - 1; last_space_ >= position_; --last_space_) {
264
+ if (kSpaces[static_cast<unsigned char>(*last_space_)]) break;
265
+ }
266
+ }
267
+
268
+ void FilePiece::UpdateProgress() {
269
+ if (!fallback_to_read_)
270
+ progress_.Set(position_ - data_.begin() + mapped_offset_);
271
+ }
272
+
273
+ void FilePiece::MMapShift(uint64_t desired_begin) {
274
+ // Use mmap.
275
+ uint64_t ignore = desired_begin % kPageSize;
276
+ // Duplicate request for Shift means give more data.
277
+ if (position_ == data_.begin() + ignore && position_) {
278
+ default_map_size_ *= 2;
279
+ }
280
+ // Local version so that in case of failure it doesn't overwrite the class variable.
281
+ uint64_t mapped_offset = desired_begin - ignore;
282
+
283
+ uint64_t mapped_size;
284
+ if (default_map_size_ >= static_cast<std::size_t>(total_size_ - mapped_offset)) {
285
+ at_end_ = true;
286
+ mapped_size = total_size_ - mapped_offset;
287
+ } else {
288
+ mapped_size = default_map_size_;
289
+ }
290
+
291
+ // Forcibly clear the existing mmap first.
292
+ data_.reset();
293
+ try {
294
+ MapRead(POPULATE_OR_LAZY, *file_, mapped_offset, mapped_size, data_);
295
+ } catch (const util::ErrnoException &) {
296
+ if (desired_begin) {
297
+ SeekOrThrow(*file_, desired_begin);
298
+ }
299
+ // The mmap was scheduled to end the file, but now we're going to read it.
300
+ at_end_ = false;
301
+ TransitionToRead();
302
+ return;
303
+ }
304
+ mapped_offset_ = mapped_offset;
305
+ position_ = data_.begin() + ignore;
306
+ position_end_ = data_.begin() + mapped_size;
307
+
308
+ progress_.Set(desired_begin);
309
+ }
310
+
311
+ void FilePiece::TransitionToRead() {
312
+ assert(!fallback_to_read_);
313
+ fallback_to_read_ = true;
314
+ data_.reset();
315
+ HugeMalloc(default_map_size_, false, data_);
316
+ position_ = data_.begin();
317
+ position_end_ = position_;
318
+
319
+ try {
320
+ fell_back_.Reset(file_.release());
321
+ } catch (util::Exception &e) {
322
+ e << " in file " << file_name_;
323
+ throw;
324
+ }
325
+ }
326
+
327
+ void FilePiece::ReadShift() {
328
+ assert(fallback_to_read_);
329
+ // Bytes [data_.begin(), position_) have been consumed.
330
+ // Bytes [position_, position_end_) have been read into the buffer.
331
+
332
+ // Start at the beginning of the buffer if there's nothing useful in it.
333
+ if (position_ == position_end_) {
334
+ mapped_offset_ += (position_end_ - data_.begin());
335
+ position_ = data_.begin();
336
+ position_end_ = position_;
337
+ }
338
+
339
+ std::size_t already_read = position_end_ - data_.begin();
340
+
341
+ if (already_read == default_map_size_) {
342
+ if (position_ == data_.begin()) {
343
+ // Buffer too small.
344
+ std::size_t valid_length = position_end_ - position_;
345
+ default_map_size_ *= 2;
346
+ HugeRealloc(default_map_size_, false, data_);
347
+ position_ = data_.begin();
348
+ position_end_ = position_ + valid_length;
349
+ } else {
350
+ std::size_t moving = position_end_ - position_;
351
+ memmove(data_.get(), position_, moving);
352
+ position_ = data_.begin();
353
+ position_end_ = position_ + moving;
354
+ already_read = moving;
355
+ }
356
+ }
357
+
358
+ std::size_t read_return = fell_back_.Read(static_cast<uint8_t*>(data_.get()) + already_read, default_map_size_ - already_read);
359
+ progress_.Set(fell_back_.RawAmount());
360
+
361
+ if (read_return == 0) {
362
+ at_end_ = true;
363
+ }
364
+ position_end_ += read_return;
365
+ }
366
+
367
+ } // namespace util
cc-multilingual-main/cc_net/third_party/kenlm/util/file_stream.hh ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Like std::ofstream but without being incredibly slow. Backed by a raw fd.
2
+ * Supports most of the built-in types except for long double.
3
+ */
4
+ #ifndef UTIL_FILE_STREAM_H
5
+ #define UTIL_FILE_STREAM_H
6
+
7
+ #include "fake_ostream.hh"
8
+ #include "file.hh"
9
+ #include "scoped.hh"
10
+
11
+ #include <cassert>
12
+ #include <cstring>
13
+
14
+ #include <stdint.h>
15
+
16
+ namespace util {
17
+
18
+ class FileStream : public FakeOStream<FileStream> {
19
+ public:
20
+ explicit FileStream(int out = -1, std::size_t buffer_size = 8192)
21
+ : buf_(util::MallocOrThrow(std::max<std::size_t>(buffer_size, kToStringMaxBytes))),
22
+ current_(static_cast<char*>(buf_.get())),
23
+ end_(current_ + std::max<std::size_t>(buffer_size, kToStringMaxBytes)),
24
+ fd_(out) {}
25
+
26
+ #if __cplusplus >= 201103L
27
+ FileStream(FileStream &&from) noexcept : buf_(from.buf_.release()), current_(from.current_), end_(from.end_), fd_(from.fd_) {
28
+ from.end_ = reinterpret_cast<char*>(from.buf_.get());
29
+ from.current_ = from.end_;
30
+ }
31
+ #endif
32
+
33
+ ~FileStream() {
34
+ flush();
35
+ }
36
+
37
+ void SetFD(int to) {
38
+ flush();
39
+ fd_ = to;
40
+ }
41
+
42
+ FileStream &flush() {
43
+ if (current_ != buf_.get()) {
44
+ util::WriteOrThrow(fd_, buf_.get(), current_ - (char*)buf_.get());
45
+ current_ = static_cast<char*>(buf_.get());
46
+ }
47
+ return *this;
48
+ }
49
+
50
+ // For writes of arbitrary size.
51
+ FileStream &write(const void *data, std::size_t length) {
52
+ if (UTIL_LIKELY(current_ + length <= end_)) {
53
+ std::memcpy(current_, data, length);
54
+ current_ += length;
55
+ return *this;
56
+ }
57
+ flush();
58
+ if (current_ + length <= end_) {
59
+ std::memcpy(current_, data, length);
60
+ current_ += length;
61
+ } else {
62
+ util::WriteOrThrow(fd_, data, length);
63
+ }
64
+ return *this;
65
+ }
66
+
67
+ FileStream &seekp(uint64_t to) {
68
+ flush();
69
+ util::SeekOrThrow(fd_, to);
70
+ return *this;
71
+ }
72
+
73
+ protected:
74
+ friend class FakeOStream<FileStream>;
75
+ // For writes directly to buffer guaranteed to have amount < buffer size.
76
+ char *Ensure(std::size_t amount) {
77
+ if (UTIL_UNLIKELY(current_ + amount > end_)) {
78
+ flush();
79
+ assert(current_ + amount <= end_);
80
+ }
81
+ return current_;
82
+ }
83
+
84
+ void AdvanceTo(char *to) {
85
+ current_ = to;
86
+ assert(current_ <= end_);
87
+ }
88
+
89
+ private:
90
+ util::scoped_malloc buf_;
91
+ char *current_, *end_;
92
+ int fd_;
93
+ };
94
+
95
+ } // namespace
96
+
97
+ #endif
cc-multilingual-main/cc_net/third_party/kenlm/util/fixed_array.hh ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef UTIL_FIXED_ARRAY_H
2
+ #define UTIL_FIXED_ARRAY_H
3
+
4
+ #include "scoped.hh"
5
+
6
+ #include <cstddef>
7
+
8
+ #include <cassert>
9
+ #include <cstdlib>
10
+
11
+ namespace util {
12
+
13
+ /**
14
+ * Defines an array with fixed maximum size.
15
+ *
16
+ * Ever want an array of things but they don't have a default constructor or
17
+ * are non-copyable? FixedArray allows constructing one at a time.
18
+ */
19
+ template <class T> class FixedArray {
20
+ public:
21
+ /** Initialize with a given size bound but do not construct the objects. */
22
+ explicit FixedArray(std::size_t limit) {
23
+ Init(limit);
24
+ }
25
+
26
+ /**
27
+ * Constructs an instance, but does not initialize it.
28
+ *
29
+ * Any objects constructed in this manner must be subsequently @ref FixedArray::Init() "initialized" prior to use.
30
+ *
31
+ * @see FixedArray::Init()
32
+ */
33
+ FixedArray()
34
+ : newed_end_(NULL)
35
+ #ifndef NDEBUG
36
+ , allocated_end_(NULL)
37
+ #endif
38
+ {}
39
+
40
+ /**
41
+ * Initialize with a given size bound but do not construct the objects.
42
+ *
43
+ * This method is responsible for allocating memory.
44
+ * Objects stored in this array will be constructed in a location within this allocated memory.
45
+ */
46
+ void Init(std::size_t count) {
47
+ assert(!block_.get());
48
+ block_.reset(malloc(sizeof(T) * count));
49
+ if (!block_.get()) throw std::bad_alloc();
50
+ newed_end_ = begin();
51
+ #ifndef NDEBUG
52
+ allocated_end_ = begin() + count;
53
+ #endif
54
+ }
55
+
56
+ /**
57
+ * Constructs a copy of the provided array.
58
+ *
59
+ * @param from Array whose elements should be copied into this newly-constructed data structure.
60
+ */
61
+ FixedArray(const FixedArray &from) {
62
+ std::size_t size = from.newed_end_ - static_cast<const T*>(from.block_.get());
63
+ Init(size);
64
+ for (std::size_t i = 0; i < size; ++i) {
65
+ push_back(from[i]);
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Frees the memory held by this object.
71
+ */
72
+ ~FixedArray() { clear(); }
73
+
74
+ #if __cplusplus >= 201103L
75
+ FixedArray(FixedArray &&from)
76
+ : block_(std::move(from.block_)),
77
+ newed_end_(from.newed_end_)
78
+ # ifndef NDEBUG
79
+ , allocated_end_(from.allocated_end_)
80
+ # endif // NDEBUG
81
+ {
82
+ from.newed_end_ = NULL;
83
+ # ifndef NDEBUG
84
+ from.allocated_end_ = NULL;
85
+ # endif // NDEBUG
86
+ }
87
+ #endif // C++11
88
+
89
+ /** Gets a pointer to the first object currently stored in this data structure. */
90
+ T *begin() { return static_cast<T*>(block_.get()); }
91
+
92
+ /** Gets a const pointer to the last object currently stored in this data structure. */
93
+ const T *begin() const { return static_cast<const T*>(block_.get()); }
94
+
95
+ /** Gets a pointer to the last object currently stored in this data structure. */
96
+ T *end() { return newed_end_; }
97
+
98
+ /** Gets a const pointer to the last object currently stored in this data structure. */
99
+ const T *end() const { return newed_end_; }
100
+
101
+ /** Gets a reference to the last object currently stored in this data structure. */
102
+ T &back() { return *(end() - 1); }
103
+
104
+ /** Gets a const reference to the last object currently stored in this data structure. */
105
+ const T &back() const { return *(end() - 1); }
106
+
107
+ /** Gets the number of objects currently stored in this data structure. */
108
+ std::size_t size() const { return end() - begin(); }
109
+
110
+ /** Returns true if there are no objects currently stored in this data structure. */
111
+ bool empty() const { return begin() == end(); }
112
+
113
+ /**
114
+ * Gets a reference to the object with index i currently stored in this data structure.
115
+ *
116
+ * @param i Index of the object to reference
117
+ */
118
+ T &operator[](std::size_t i) {
119
+ assert(i < size());
120
+ return begin()[i];
121
+ }
122
+
123
+ /**
124
+ * Gets a const reference to the object with index i currently stored in this data structure.
125
+ *
126
+ * @param i Index of the object to reference
127
+ */
128
+ const T &operator[](std::size_t i) const {
129
+ assert(i < size());
130
+ return begin()[i];
131
+ }
132
+
133
+ /**
134
+ * Constructs a new object using the provided parameter,
135
+ * and stores it in this data structure.
136
+ *
137
+ * The memory backing the constructed object is managed by this data structure.
138
+ * I miss C++11 variadic templates.
139
+ */
140
+ #if __cplusplus >= 201103L
141
+ template <typename... Construct> T *emplace_back(Construct&&... construct) {
142
+ T *ret = end();
143
+ new (end()) T(construct...);
144
+ Constructed();
145
+ return ret;
146
+ }
147
+ template <typename... Construct> T *push_back(Construct&&... construct) {
148
+ T *ret = end();
149
+ new (end()) T(construct...);
150
+ Constructed();
151
+ return ret;
152
+ }
153
+ #else
154
+ void push_back() {
155
+ new (end()) T();
156
+ Constructed();
157
+ }
158
+ template <class C> void push_back(const C &c) {
159
+ new (end()) T(c);
160
+ Constructed();
161
+ }
162
+ template <class C> void push_back(C &c) {
163
+ new (end()) T(c);
164
+ Constructed();
165
+ }
166
+ template <class C, class D> void push_back(const C &c, const D &d) {
167
+ new (end()) T(c, d);
168
+ Constructed();
169
+ }
170
+ #endif
171
+
172
+ void pop_back() {
173
+ back().~T();
174
+ --newed_end_;
175
+ }
176
+
177
+ /**
178
+ * Removes all elements from this array.
179
+ */
180
+ void clear() {
181
+ while (newed_end_ != begin())
182
+ pop_back();
183
+ }
184
+
185
+ protected:
186
+ // Always call Constructed after successful completion of new.
187
+ void Constructed() {
188
+ ++newed_end_;
189
+ #ifndef NDEBUG
190
+ assert(newed_end_ <= allocated_end_);
191
+ #endif
192
+ }
193
+
194
+ private:
195
+ util::scoped_malloc block_;
196
+
197
+ T *newed_end_;
198
+
199
+ #ifndef NDEBUG
200
+ T *allocated_end_;
201
+ #endif
202
+ };
203
+
204
+ } // namespace util
205
+
206
+ #endif // UTIL_FIXED_ARRAY_H
cc-multilingual-main/cc_net/third_party/kenlm/util/float_to_string.hh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef UTIL_FLOAT_TO_STRING_H
2
+ #define UTIL_FLOAT_TO_STRING_H
3
+
4
+ // Just for ToStringBuf
5
+ #include "integer_to_string.hh"
6
+
7
+ namespace util {
8
+
9
+ template <> struct ToStringBuf<double> {
10
+ // DoubleToStringConverter::kBase10MaximalLength + 1 for null paranoia.
11
+ static const unsigned kBytes = 19;
12
+ };
13
+
14
+ // Single wasn't documented in double conversion, so be conservative and
15
+ // say the same as double.
16
+ template <> struct ToStringBuf<float> {
17
+ static const unsigned kBytes = 19;
18
+ };
19
+
20
+ char *ToString(double value, char *to);
21
+ char *ToString(float value, char *to);
22
+
23
+ } // namespace util
24
+
25
+ #endif // UTIL_FLOAT_TO_STRING_H
cc-multilingual-main/cc_net/third_party/kenlm/util/getopt.hh ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ POSIX getopt for Windows
3
+
4
+ AT&T Public License
5
+
6
+ Code given out at the 1985 UNIFORUM conference in Dallas.
7
+ */
8
+
9
+ #ifdef __GNUC__
10
+ #include <getopt.h>
11
+ #endif
12
+ #ifndef __GNUC__
13
+
14
+ #ifndef UTIL_GETOPT_H
15
+ #define UTIL_GETOPT_H
16
+
17
+ #ifdef __cplusplus
18
+ extern "C" {
19
+ #endif
20
+
21
+ extern int opterr;
22
+ extern int optind;
23
+ extern int optopt;
24
+ extern char *optarg;
25
+ extern int getopt(int argc, char **argv, char *opts);
26
+
27
+ #ifdef __cplusplus
28
+ }
29
+ #endif
30
+
31
+ #endif /* UTIL_GETOPT_H */
32
+ #endif /* __GNUC__ */
33
+
cc-multilingual-main/cc_net/third_party/kenlm/util/integer_to_string.hh ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef UTIL_INTEGER_TO_STRING_H
2
+ #define UTIL_INTEGER_TO_STRING_H
3
+ #include <cstddef>
4
+ #include <stdint.h>
5
+
6
+ namespace util {
7
+
8
+ /* These functions convert integers to strings and return the end pointer.
9
+ */
10
+ char *ToString(uint32_t value, char *to);
11
+ char *ToString(uint64_t value, char *to);
12
+
13
+ // Implemented as wrappers to above
14
+ char *ToString(int32_t value, char *to);
15
+ char *ToString(int64_t value, char *to);
16
+
17
+ // Calls the 32-bit versions for now.
18
+ char *ToString(uint16_t value, char *to);
19
+ char *ToString(int16_t value, char *to);
20
+
21
+ char *ToString(const void *value, char *to);
22
+
23
+ inline char *ToString(bool value, char *to) {
24
+ *to++ = '0' + value;
25
+ return to;
26
+ }
27
+
28
+ // How many bytes to reserve in the buffer for these strings:
29
+ // g++ 4.9.1 doesn't work with this:
30
+ // static const std::size_t kBytes = 5;
31
+ // So use enum.
32
+ template <class T> struct ToStringBuf;
33
+ template <> struct ToStringBuf<bool> {
34
+ enum { kBytes = 1 };
35
+ };
36
+ template <> struct ToStringBuf<uint16_t> {
37
+ enum { kBytes = 5 };
38
+ };
39
+ template <> struct ToStringBuf<int16_t> {
40
+ enum { kBytes = 6 };
41
+ };
42
+ template <> struct ToStringBuf<uint32_t> {
43
+ enum { kBytes = 10 };
44
+ };
45
+ template <> struct ToStringBuf<int32_t> {
46
+ enum { kBytes = 11 };
47
+ };
48
+ template <> struct ToStringBuf<uint64_t> {
49
+ enum { kBytes = 20 };
50
+ };
51
+ template <> struct ToStringBuf<int64_t> {
52
+ // Not a typo. 2^63 has 19 digits.
53
+ enum { kBytes = 20 };
54
+ };
55
+
56
+ template <> struct ToStringBuf<const void*> {
57
+ // Either 18 on 64-bit or 10 on 32-bit.
58
+ enum { kBytes = sizeof(const void*) * 2 + 2 };
59
+ };
60
+
61
+ // Maximum over this and float.
62
+ enum { kToStringMaxBytes = 20 };
63
+
64
+ } // namespace util
65
+
66
+ #endif // UTIL_INTEGER_TO_STRING_H
cc-multilingual-main/cc_net/third_party/kenlm/util/integer_to_string_test.cc ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #define BOOST_LEXICAL_CAST_ASSUME_C_LOCALE
2
+ #include "integer_to_string.hh"
3
+ #include "string_piece.hh"
4
+
5
+ #define BOOST_TEST_MODULE IntegerToStringTest
6
+ #include <boost/test/unit_test.hpp>
7
+ #include <boost/lexical_cast.hpp>
8
+
9
+ #include <limits>
10
+
11
+ namespace util {
12
+ namespace {
13
+
14
+ template <class T> void TestValue(const T value) {
15
+ char buf[ToStringBuf<T>::kBytes];
16
+ StringPiece result(buf, ToString(value, buf) - buf);
17
+ BOOST_REQUIRE_GE(static_cast<std::size_t>(ToStringBuf<T>::kBytes), result.size());
18
+ if (value) {
19
+ BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(value), result);
20
+ } else {
21
+ // Platforms can do void * as 0x0 or 0.
22
+ BOOST_CHECK(result == "0x0" || result == "0");
23
+ }
24
+ }
25
+
26
+ template <class T> void TestCorners() {
27
+ TestValue(std::numeric_limits<T>::min());
28
+ TestValue(std::numeric_limits<T>::max());
29
+ TestValue((T)0);
30
+ TestValue((T)-1);
31
+ TestValue((T)1);
32
+ }
33
+
34
+ BOOST_AUTO_TEST_CASE(Corners) {
35
+ TestCorners<uint16_t>();
36
+ TestCorners<uint32_t>();
37
+ TestCorners<uint64_t>();
38
+ TestCorners<int16_t>();
39
+ TestCorners<int32_t>();
40
+ TestCorners<int64_t>();
41
+ TestCorners<const void*>();
42
+ }
43
+
44
+ template <class T> void TestAll() {
45
+ for (T i = std::numeric_limits<T>::min(); i < std::numeric_limits<T>::max(); ++i) {
46
+ TestValue(i);
47
+ }
48
+ TestValue(std::numeric_limits<T>::max());
49
+ }
50
+
51
+ BOOST_AUTO_TEST_CASE(Short) {
52
+ TestAll<uint16_t>();
53
+ TestAll<int16_t>();
54
+ }
55
+
56
+ template <class T> void Test10s() {
57
+ for (T i = 1; i < std::numeric_limits<T>::max() / 10; i *= 10) {
58
+ TestValue(i);
59
+ TestValue(i - 1);
60
+ TestValue(i + 1);
61
+ }
62
+ }
63
+
64
+ BOOST_AUTO_TEST_CASE(Tens) {
65
+ Test10s<uint64_t>();
66
+ Test10s<int64_t>();
67
+ Test10s<uint32_t>();
68
+ Test10s<int32_t>();
69
+ }
70
+
71
+ BOOST_AUTO_TEST_CASE(Pointers) {
72
+ for (uintptr_t i = 1; i < std::numeric_limits<uintptr_t>::max() / 10; i *= 10) {
73
+ TestValue((const void*)i);
74
+ }
75
+ for (uintptr_t i = 0; i < 256; ++i) {
76
+ TestValue((const void*)i);
77
+ TestValue((const void*)(i + 0xf00));
78
+ }
79
+ }
80
+
81
+ }} // namespaces
cc-multilingual-main/cc_net/third_party/kenlm/util/joint_sort.hh ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef UTIL_JOINT_SORT_H
2
+ #define UTIL_JOINT_SORT_H
3
+
4
+ /* A terrifying amount of C++ to coax std::sort into soring one range while
5
+ * also permuting another range the same way.
6
+ */
7
+
8
+ #include "proxy_iterator.hh"
9
+
10
+ #include <algorithm>
11
+ #include <functional>
12
+
13
+ namespace util {
14
+
15
+ namespace detail {
16
+
17
+ template <class KeyIter, class ValueIter> class JointProxy;
18
+
19
+ template <class KeyIter, class ValueIter> class JointIter {
20
+ public:
21
+ JointIter() {}
22
+
23
+ JointIter(const KeyIter &key_iter, const ValueIter &value_iter) : key_(key_iter), value_(value_iter) {}
24
+
25
+ bool operator==(const JointIter<KeyIter, ValueIter> &other) const { return key_ == other.key_; }
26
+
27
+ bool operator<(const JointIter<KeyIter, ValueIter> &other) const { return (key_ < other.key_); }
28
+
29
+ std::ptrdiff_t operator-(const JointIter<KeyIter, ValueIter> &other) const { return key_ - other.key_; }
30
+
31
+ JointIter<KeyIter, ValueIter> &operator+=(std::ptrdiff_t amount) {
32
+ key_ += amount;
33
+ value_ += amount;
34
+ return *this;
35
+ }
36
+
37
+ friend void swap(JointIter &first, JointIter &second) {
38
+ using std::swap;
39
+ swap(first.key_, second.key_);
40
+ swap(first.value_, second.value_);
41
+ }
42
+
43
+ void DeepSwap(JointIter &other) {
44
+ using std::swap;
45
+ swap(*key_, *other.key_);
46
+ swap(*value_, *other.value_);
47
+ }
48
+
49
+ private:
50
+ friend class JointProxy<KeyIter, ValueIter>;
51
+ KeyIter key_;
52
+ ValueIter value_;
53
+ };
54
+
55
+ template <class KeyIter, class ValueIter> class JointProxy {
56
+ private:
57
+ typedef JointIter<KeyIter, ValueIter> InnerIterator;
58
+
59
+ public:
60
+ typedef struct {
61
+ typename std::iterator_traits<KeyIter>::value_type key;
62
+ typename std::iterator_traits<ValueIter>::value_type value;
63
+ const typename std::iterator_traits<KeyIter>::value_type &GetKey() const { return key; }
64
+ } value_type;
65
+
66
+ JointProxy(const KeyIter &key_iter, const ValueIter &value_iter) : inner_(key_iter, value_iter) {}
67
+ JointProxy(const JointProxy<KeyIter, ValueIter> &other) : inner_(other.inner_) {}
68
+
69
+ operator value_type() const {
70
+ value_type ret;
71
+ ret.key = *inner_.key_;
72
+ ret.value = *inner_.value_;
73
+ return ret;
74
+ }
75
+
76
+ JointProxy &operator=(const JointProxy &other) {
77
+ *inner_.key_ = *other.inner_.key_;
78
+ *inner_.value_ = *other.inner_.value_;
79
+ return *this;
80
+ }
81
+
82
+ JointProxy &operator=(const value_type &other) {
83
+ *inner_.key_ = other.key;
84
+ *inner_.value_ = other.value;
85
+ return *this;
86
+ }
87
+
88
+ typename std::iterator_traits<KeyIter>::reference GetKey() const {
89
+ return *(inner_.key_);
90
+ }
91
+
92
+ friend void swap(JointProxy<KeyIter, ValueIter> first, JointProxy<KeyIter, ValueIter> second) {
93
+ first.Inner().DeepSwap(second.Inner());
94
+ }
95
+
96
+ private:
97
+ friend class ProxyIterator<JointProxy<KeyIter, ValueIter> >;
98
+
99
+ InnerIterator &Inner() { return inner_; }
100
+ const InnerIterator &Inner() const { return inner_; }
101
+ InnerIterator inner_;
102
+ };
103
+
104
+ template <class Proxy, class Less> class LessWrapper : public std::binary_function<const typename Proxy::value_type &, const typename Proxy::value_type &, bool> {
105
+ public:
106
+ explicit LessWrapper(const Less &less) : less_(less) {}
107
+
108
+ bool operator()(const Proxy &left, const Proxy &right) const {
109
+ return less_(left.GetKey(), right.GetKey());
110
+ }
111
+ bool operator()(const Proxy &left, const typename Proxy::value_type &right) const {
112
+ return less_(left.GetKey(), right.GetKey());
113
+ }
114
+ bool operator()(const typename Proxy::value_type &left, const Proxy &right) const {
115
+ return less_(left.GetKey(), right.GetKey());
116
+ }
117
+ bool operator()(const typename Proxy::value_type &left, const typename Proxy::value_type &right) const {
118
+ return less_(left.GetKey(), right.GetKey());
119
+ }
120
+
121
+ private:
122
+ const Less less_;
123
+ };
124
+
125
+ } // namespace detail
126
+
127
+ template <class KeyIter, class ValueIter> class PairedIterator : public ProxyIterator<detail::JointProxy<KeyIter, ValueIter> > {
128
+ public:
129
+ PairedIterator(const KeyIter &key, const ValueIter &value) :
130
+ ProxyIterator<detail::JointProxy<KeyIter, ValueIter> >(detail::JointProxy<KeyIter, ValueIter>(key, value)) {}
131
+ };
132
+
133
+ template <class KeyIter, class ValueIter, class Less> void JointSort(const KeyIter &key_begin, const KeyIter &key_end, const ValueIter &value_begin, const Less &less) {
134
+ ProxyIterator<detail::JointProxy<KeyIter, ValueIter> > full_begin(detail::JointProxy<KeyIter, ValueIter>(key_begin, value_begin));
135
+ detail::LessWrapper<detail::JointProxy<KeyIter, ValueIter>, Less> less_wrap(less);
136
+ std::sort(full_begin, full_begin + (key_end - key_begin), less_wrap);
137
+ }
138
+
139
+
140
+ template <class KeyIter, class ValueIter> void JointSort(const KeyIter &key_begin, const KeyIter &key_end, const ValueIter &value_begin) {
141
+ JointSort(key_begin, key_end, value_begin, std::less<typename std::iterator_traits<KeyIter>::value_type>());
142
+ }
143
+
144
+ } // namespace util
145
+
146
+ #endif // UTIL_JOINT_SORT_H
cc-multilingual-main/cc_net/third_party/kenlm/util/joint_sort_test.cc ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "joint_sort.hh"
2
+
3
+ #define BOOST_TEST_MODULE JointSortTest
4
+ #include <boost/test/unit_test.hpp>
5
+
6
+ namespace util { namespace {
7
+
8
+ BOOST_AUTO_TEST_CASE(just_flip) {
9
+ char keys[2];
10
+ int values[2];
11
+ keys[0] = 1; values[0] = 327;
12
+ keys[1] = 0; values[1] = 87897;
13
+ JointSort<char *, int *>(keys + 0, keys + 2, values + 0);
14
+ BOOST_CHECK_EQUAL(0, keys[0]);
15
+ BOOST_CHECK_EQUAL(87897, values[0]);
16
+ BOOST_CHECK_EQUAL(1, keys[1]);
17
+ BOOST_CHECK_EQUAL(327, values[1]);
18
+ }
19
+
20
+ BOOST_AUTO_TEST_CASE(three) {
21
+ char keys[3];
22
+ int values[3];
23
+ keys[0] = 1; values[0] = 327;
24
+ keys[1] = 2; values[1] = 87897;
25
+ keys[2] = 0; values[2] = 10;
26
+ JointSort<char *, int *>(keys + 0, keys + 3, values + 0);
27
+ BOOST_CHECK_EQUAL(0, keys[0]);
28
+ BOOST_CHECK_EQUAL(1, keys[1]);
29
+ BOOST_CHECK_EQUAL(2, keys[2]);
30
+ }
31
+
32
+ BOOST_AUTO_TEST_CASE(char_int) {
33
+ char keys[4];
34
+ int values[4];
35
+ keys[0] = 3; values[0] = 327;
36
+ keys[1] = 1; values[1] = 87897;
37
+ keys[2] = 2; values[2] = 10;
38
+ keys[3] = 0; values[3] = 24347;
39
+ JointSort<char *, int *>(keys + 0, keys + 4, values + 0);
40
+ BOOST_CHECK_EQUAL(0, keys[0]);
41
+ BOOST_CHECK_EQUAL(24347, values[0]);
42
+ BOOST_CHECK_EQUAL(1, keys[1]);
43
+ BOOST_CHECK_EQUAL(87897, values[1]);
44
+ BOOST_CHECK_EQUAL(2, keys[2]);
45
+ BOOST_CHECK_EQUAL(10, values[2]);
46
+ BOOST_CHECK_EQUAL(3, keys[3]);
47
+ BOOST_CHECK_EQUAL(327, values[3]);
48
+ }
49
+
50
+ BOOST_AUTO_TEST_CASE(swap_proxy) {
51
+ char keys[2] = {0, 1};
52
+ int values[2] = {2, 3};
53
+ detail::JointProxy<char *, int *> first(keys, values);
54
+ detail::JointProxy<char *, int *> second(keys + 1, values + 1);
55
+ swap(first, second);
56
+ BOOST_CHECK_EQUAL(1, keys[0]);
57
+ BOOST_CHECK_EQUAL(0, keys[1]);
58
+ BOOST_CHECK_EQUAL(3, values[0]);
59
+ BOOST_CHECK_EQUAL(2, values[1]);
60
+ }
61
+
62
+ }} // namespace anonymous util
cc-multilingual-main/cc_net/third_party/kenlm/util/mmap.cc ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Memory mapping wrappers.
2
+ * ARM and MinGW ports contributed by Hideo Okuma and Tomoyuki Yoshimura at
3
+ * NICT.
4
+ */
5
+ #include "mmap.hh"
6
+
7
+ #include "exception.hh"
8
+ #include "file.hh"
9
+ #include "scoped.hh"
10
+
11
+ #include <iostream>
12
+
13
+ #include <cassert>
14
+ #include <fcntl.h>
15
+ #include <sys/types.h>
16
+ #include <sys/stat.h>
17
+ #include <cstdlib>
18
+
19
+ #if defined(_WIN32) || defined(_WIN64)
20
+ #include <windows.h>
21
+ #include <io.h>
22
+ #else
23
+ #include <sys/mman.h>
24
+ #include <unistd.h>
25
+ #endif
26
+
27
+ namespace util {
28
+
29
+ std::size_t SizePage() {
30
+ #if defined(_WIN32) || defined(_WIN64)
31
+ SYSTEM_INFO si;
32
+ GetSystemInfo(&si);
33
+ return si.dwAllocationGranularity;
34
+ #else
35
+ return sysconf(_SC_PAGE_SIZE);
36
+ #endif
37
+ }
38
+
39
+ scoped_mmap::~scoped_mmap() {
40
+ if (data_ != (void*)-1) {
41
+ try {
42
+ // Thanks Denis Filimonov for pointing out NFS likes msync first.
43
+ SyncOrThrow(data_, size_);
44
+ UnmapOrThrow(data_, size_);
45
+ } catch (const util::ErrnoException &e) {
46
+ std::cerr << e.what();
47
+ abort();
48
+ }
49
+ }
50
+ }
51
+
52
+ namespace {
53
+ template <class T> T RoundUpPow2(T value, T mult) {
54
+ return ((value - 1) & ~(mult - 1)) + mult;
55
+ }
56
+
57
+ std::size_t RoundUpSize(const scoped_memory &mem) {
58
+ switch(mem.source()) {
59
+ case scoped_memory::MMAP_ROUND_1G_ALLOCATED:
60
+ return RoundUpPow2<std::size_t>(mem.size(), 1ULL << 30);
61
+ case scoped_memory::MMAP_ROUND_2M_ALLOCATED:
62
+ return RoundUpPow2<std::size_t>(mem.size(), 1ULL << 21);
63
+ case scoped_memory::MMAP_ROUND_PAGE_ALLOCATED:
64
+ return RoundUpPow2<std::size_t>(mem.size(), static_cast<std::size_t>(SizePage()));
65
+ default:
66
+ return mem.size();
67
+ }
68
+ }
69
+
70
+ } // namespace
71
+
72
+ scoped_memory::scoped_memory(std::size_t size, bool zeroed) : data_(NULL), size_(0), source_(NONE_ALLOCATED) {
73
+ HugeMalloc(size, zeroed, *this);
74
+ }
75
+
76
+ void scoped_memory::reset(void *data, std::size_t size, Alloc source) {
77
+ switch(source_) {
78
+ case MMAP_ROUND_1G_ALLOCATED:
79
+ case MMAP_ROUND_2M_ALLOCATED:
80
+ case MMAP_ROUND_PAGE_ALLOCATED:
81
+ case MMAP_ALLOCATED:
82
+ scoped_mmap(data_, RoundUpSize(*this));
83
+ break;
84
+ case MALLOC_ALLOCATED:
85
+ free(data_);
86
+ break;
87
+ case NONE_ALLOCATED:
88
+ break;
89
+ }
90
+ data_ = data;
91
+ size_ = size;
92
+ source_ = source;
93
+ }
94
+
95
+ const int kFileFlags =
96
+ #if defined(_WIN32) || defined(_WIN64)
97
+ 0 // MapOrThrow ignores flags on windows
98
+ #elif defined(MAP_FILE)
99
+ MAP_FILE | MAP_SHARED
100
+ #else
101
+ MAP_SHARED
102
+ #endif
103
+ ;
104
+
105
+ void *MapOrThrow(std::size_t size, bool for_write, int flags, bool prefault, int fd, uint64_t offset) {
106
+ #ifdef MAP_POPULATE // Linux specific
107
+ if (prefault) {
108
+ flags |= MAP_POPULATE;
109
+ }
110
+ #endif
111
+ #if defined(_WIN32) || defined(_WIN64)
112
+ int protectC = for_write ? PAGE_READWRITE : PAGE_READONLY;
113
+ int protectM = for_write ? FILE_MAP_WRITE : FILE_MAP_READ;
114
+ uint64_t total_size = size + offset;
115
+ HANDLE hMapping = CreateFileMapping((HANDLE)_get_osfhandle(fd), NULL, protectC, total_size >> 32, static_cast<DWORD>(total_size), NULL);
116
+ UTIL_THROW_IF(!hMapping, ErrnoException, "CreateFileMapping failed");
117
+ LPVOID ret = MapViewOfFile(hMapping, protectM, offset >> 32, offset, size);
118
+ CloseHandle(hMapping);
119
+ UTIL_THROW_IF(!ret, ErrnoException, "MapViewOfFile failed");
120
+ #else
121
+ int protect = for_write ? (PROT_READ | PROT_WRITE) : PROT_READ;
122
+ void *ret;
123
+ UTIL_THROW_IF((ret = mmap(NULL, size, protect, flags, fd, offset)) == MAP_FAILED, ErrnoException, "mmap failed for size " << size << " at offset " << offset);
124
+ # ifdef MADV_HUGEPAGE
125
+ /* We like huge pages but it's fine if we can't have them. Note that huge
126
+ * pages are not supported for file-backed mmap on linux.
127
+ */
128
+ madvise(ret, size, MADV_HUGEPAGE);
129
+ # endif
130
+ #endif
131
+ return ret;
132
+ }
133
+
134
+ void SyncOrThrow(void *start, size_t length) {
135
+ #if defined(_WIN32) || defined(_WIN64)
136
+ UTIL_THROW_IF(!::FlushViewOfFile(start, length), ErrnoException, "Failed to sync mmap");
137
+ #else
138
+ UTIL_THROW_IF(length && msync(start, length, MS_SYNC), ErrnoException, "Failed to sync mmap");
139
+ #endif
140
+ }
141
+
142
+ void UnmapOrThrow(void *start, size_t length) {
143
+ #if defined(_WIN32) || defined(_WIN64)
144
+ UTIL_THROW_IF(!::UnmapViewOfFile(start), ErrnoException, "Failed to unmap a file");
145
+ #else
146
+ UTIL_THROW_IF(munmap(start, length), ErrnoException, "munmap failed with " << start << " for length " << length);
147
+ #endif
148
+ }
149
+
150
+ // Linux huge pages.
151
+ #ifdef __linux__
152
+
153
+ namespace {
154
+
155
+ bool TryHuge(std::size_t size, bool populate, uint8_t alignment_bits, scoped_memory::Alloc huge_scheme, scoped_memory &to) {
156
+ // Don't bother with these cases.
157
+ if (size < (1ULL << alignment_bits) || (1ULL << alignment_bits) < SizePage())
158
+ return false;
159
+
160
+ // First try: Linux >= 3.8 with manually configured hugetlb pages available.
161
+ int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | (alignment_bits << 26 /* This is MAP_HUGE_SHIFT but some headers are too old. */);
162
+ if (populate) flags |= MAP_POPULATE;
163
+ void *ret = mmap(NULL, size, PROT_READ | PROT_WRITE, flags, -1, 0);
164
+ if (ret != MAP_FAILED) {
165
+ to.reset(ret, size, huge_scheme);
166
+ return true;
167
+ }
168
+
169
+ // There weren't pages in a sysadmin-created pool. Let's get aligned memory
170
+ // and hope transparent huge pages kicks in. Align to a multiple of the huge
171
+ // page size by overallocating. I feel bad about doing this, but it's also how
172
+ // posix_memalign is implemented. And the memory is virtual.
173
+
174
+ // Round up requested size to multiple of page size. This will allow the pages after to be munmapped.
175
+ std::size_t size_up = RoundUpPow2(size, SizePage());
176
+
177
+ std::size_t ask = size_up + (1 << alignment_bits) - SizePage();
178
+ // Don't populate because this is asking for more than we will use.
179
+ scoped_mmap larger(mmap(NULL, ask, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0), ask);
180
+ if (larger.get() == MAP_FAILED) return false;
181
+
182
+ // Throw out pages before the alignment point.
183
+ uintptr_t base = reinterpret_cast<uintptr_t>(larger.get());
184
+ // Round up to next multiple of alignment.
185
+ uintptr_t rounded_up = RoundUpPow2(base, static_cast<uintptr_t>(1) << alignment_bits);
186
+ if (base != rounded_up) {
187
+ // If this throws an exception (which it shouldn't) then we want to unmap the whole thing by keeping it in larger.
188
+ UnmapOrThrow(larger.get(), rounded_up - base);
189
+ larger.steal();
190
+ larger.reset(reinterpret_cast<void*>(rounded_up), ask - (rounded_up - base));
191
+ }
192
+
193
+ // Throw out pages after the requested size.
194
+ assert(larger.size() >= size_up);
195
+ if (larger.size() > size_up) {
196
+ // This is where we assume size_up is a multiple of page size.
197
+ UnmapOrThrow(static_cast<uint8_t*>(larger.get()) + size_up, larger.size() - size_up);
198
+ larger.reset(larger.steal(), size_up);
199
+ }
200
+ #ifdef MADV_HUGEPAGE
201
+ madvise(larger.get(), size_up, MADV_HUGEPAGE);
202
+ #endif
203
+ to.reset(larger.steal(), size, scoped_memory::MMAP_ROUND_PAGE_ALLOCATED);
204
+ return true;
205
+ }
206
+
207
+ } // namespace
208
+
209
+ #endif
210
+
211
+ void HugeMalloc(std::size_t size, bool zeroed, scoped_memory &to) {
212
+ to.reset();
213
+ #ifdef __linux__
214
+ // TODO: architectures/page sizes other than 2^21 and 2^30.
215
+ // Attempt 1 GB pages.
216
+ // If the user asked for zeroed memory, assume they want it populated.
217
+ if (size >= (1ULL << 30) && TryHuge(size, zeroed, 30, scoped_memory::MMAP_ROUND_1G_ALLOCATED, to))
218
+ return;
219
+ // Attempt 2 MB pages.
220
+ if (size >= (1ULL << 21) && TryHuge(size, zeroed, 21, scoped_memory::MMAP_ROUND_2M_ALLOCATED, to))
221
+ return;
222
+ #endif // __linux__
223
+ // Non-linux will always do this, as will small allocations on Linux.
224
+ to.reset(zeroed ? calloc(1, size) : malloc(size), size, scoped_memory::MALLOC_ALLOCATED);
225
+ UTIL_THROW_IF(!to.get(), ErrnoException, "Failed to allocate " << size << " bytes");
226
+ }
227
+
228
+ namespace {
229
+ #ifdef __linux__
230
+ const std::size_t kTransitionHuge = std::max<std::size_t>(1ULL << 21, SizePage());
231
+ #endif // __linux__
232
+
233
+ void ReplaceAndCopy(std::size_t to, bool zero_new, scoped_memory &mem) {
234
+ scoped_memory replacement;
235
+ HugeMalloc(to, zero_new, replacement);
236
+ memcpy(replacement.get(), mem.get(), mem.size());
237
+ // This can't throw.
238
+ mem.reset(replacement.get(), replacement.size(), replacement.source());
239
+ replacement.steal();
240
+ }
241
+ } // namespace
242
+
243
+ void HugeRealloc(std::size_t to, bool zero_new, scoped_memory &mem) {
244
+ if (!to) {
245
+ mem.reset();
246
+ return;
247
+ }
248
+ switch (mem.source()) {
249
+ case scoped_memory::NONE_ALLOCATED:
250
+ HugeMalloc(to, zero_new, mem);
251
+ return;
252
+ #ifdef __linux__
253
+ // TODO really need to collapse these cases with a number.
254
+ case scoped_memory::MMAP_ROUND_1G_ALLOCATED:
255
+ case scoped_memory::MMAP_ROUND_2M_ALLOCATED:
256
+ case scoped_memory::MMAP_ROUND_PAGE_ALLOCATED:
257
+ case scoped_memory::MMAP_ALLOCATED:
258
+ // Downsizing below barrier?
259
+ if (to <= SizePage()) {
260
+ scoped_malloc replacement(malloc(to));
261
+ memcpy(replacement.get(), mem.get(), std::min(to, mem.size()));
262
+ if (zero_new && to > mem.size())
263
+ memset(static_cast<uint8_t*>(replacement.get()) + mem.size(), 0, to - mem.size());
264
+ mem.reset(replacement.release(), to, scoped_memory::MALLOC_ALLOCATED);
265
+ } else {
266
+ // main path: try to mremap.
267
+ void *new_addr = mremap(mem.get(), RoundUpSize(mem), to, MREMAP_MAYMOVE);
268
+ if (new_addr != MAP_FAILED) {
269
+ scoped_memory::Alloc source(mem.source()); // steal resets mem.source()
270
+ mem.steal(); // let go otherwise reset() will free it first
271
+ mem.reset(new_addr, to, source);
272
+ } else {
273
+ // Reallocating huge pages can fail with EINVAL.
274
+ // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/mm/mremap.c?id=refs/tags/v3.19#n346
275
+ ReplaceAndCopy(to, zero_new, mem);
276
+ }
277
+ }
278
+ return;
279
+ #endif // __linux__
280
+ case scoped_memory::MALLOC_ALLOCATED:
281
+ #ifdef __linux__
282
+ // Transition larger allocations to huge pages, but don't keep trying if we're still malloc allocated.
283
+ if (to >= kTransitionHuge && mem.size() < kTransitionHuge) {
284
+ ReplaceAndCopy(to, zero_new, mem);
285
+ return;
286
+ }
287
+ #endif // __linux__
288
+ {
289
+ void *new_addr = std::realloc(mem.get(), to);
290
+ UTIL_THROW_IF(!new_addr, ErrnoException, "realloc to " << to << " bytes failed.");
291
+ if (zero_new && to > mem.size())
292
+ memset(static_cast<uint8_t*>(new_addr) + mem.size(), 0, to - mem.size());
293
+ mem.steal();
294
+ mem.reset(new_addr, to, scoped_memory::MALLOC_ALLOCATED);
295
+ }
296
+ return;
297
+ default:
298
+ UTIL_THROW(Exception, "HugeRealloc called with type " << mem.source());
299
+ }
300
+ }
301
+
302
+ void MapRead(LoadMethod method, int fd, uint64_t offset, std::size_t size, scoped_memory &out) {
303
+ switch (method) {
304
+ case LAZY:
305
+ out.reset(MapOrThrow(size, false, kFileFlags, false, fd, offset), size, scoped_memory::MMAP_ALLOCATED);
306
+ break;
307
+ case POPULATE_OR_LAZY:
308
+ #ifdef MAP_POPULATE
309
+ case POPULATE_OR_READ:
310
+ #endif
311
+ out.reset(MapOrThrow(size, false, kFileFlags, true, fd, offset), size, scoped_memory::MMAP_ALLOCATED);
312
+ break;
313
+ #ifndef MAP_POPULATE
314
+ case POPULATE_OR_READ:
315
+ #endif
316
+ case READ:
317
+ HugeMalloc(size, false, out);
318
+ SeekOrThrow(fd, offset);
319
+ ReadOrThrow(fd, out.get(), size);
320
+ break;
321
+ case PARALLEL_READ:
322
+ UTIL_THROW(Exception, "Parallel read was removed from this repo.");
323
+ break;
324
+ }
325
+ }
326
+
327
+ void *MapZeroedWrite(int fd, std::size_t size) {
328
+ ResizeOrThrow(fd, 0);
329
+ ResizeOrThrow(fd, size);
330
+ return MapOrThrow(size, true, kFileFlags, false, fd, 0);
331
+ }
332
+
333
+ void *MapZeroedWrite(const char *name, std::size_t size, scoped_fd &file) {
334
+ file.reset(CreateOrThrow(name));
335
+ try {
336
+ return MapZeroedWrite(file.get(), size);
337
+ } catch (ErrnoException &e) {
338
+ e << " in file " << name;
339
+ throw;
340
+ }
341
+ }
342
+
343
+ Rolling::Rolling(const Rolling &copy_from, uint64_t increase) {
344
+ *this = copy_from;
345
+ IncreaseBase(increase);
346
+ }
347
+
348
+ Rolling &Rolling::operator=(const Rolling &copy_from) {
349
+ fd_ = copy_from.fd_;
350
+ file_begin_ = copy_from.file_begin_;
351
+ file_end_ = copy_from.file_end_;
352
+ for_write_ = copy_from.for_write_;
353
+ block_ = copy_from.block_;
354
+ read_bound_ = copy_from.read_bound_;
355
+
356
+ current_begin_ = 0;
357
+ if (copy_from.IsPassthrough()) {
358
+ current_end_ = copy_from.current_end_;
359
+ ptr_ = copy_from.ptr_;
360
+ } else {
361
+ // Force call on next mmap.
362
+ current_end_ = 0;
363
+ ptr_ = NULL;
364
+ }
365
+ return *this;
366
+ }
367
+
368
+ Rolling::Rolling(int fd, bool for_write, std::size_t block, std::size_t read_bound, uint64_t offset, uint64_t amount) {
369
+ current_begin_ = 0;
370
+ current_end_ = 0;
371
+ fd_ = fd;
372
+ file_begin_ = offset;
373
+ file_end_ = offset + amount;
374
+ for_write_ = for_write;
375
+ block_ = block;
376
+ read_bound_ = read_bound;
377
+ }
378
+
379
+ void *Rolling::ExtractNonRolling(scoped_memory &out, uint64_t index, std::size_t size) {
380
+ out.reset();
381
+ if (IsPassthrough()) return static_cast<uint8_t*>(get()) + index;
382
+ uint64_t offset = index + file_begin_;
383
+ // Round down to multiple of page size.
384
+ uint64_t cruft = offset % static_cast<uint64_t>(SizePage());
385
+ std::size_t map_size = static_cast<std::size_t>(size + cruft);
386
+ out.reset(MapOrThrow(map_size, for_write_, kFileFlags, true, fd_, offset - cruft), map_size, scoped_memory::MMAP_ALLOCATED);
387
+ return static_cast<uint8_t*>(out.get()) + static_cast<std::size_t>(cruft);
388
+ }
389
+
390
+ void Rolling::Roll(uint64_t index) {
391
+ assert(!IsPassthrough());
392
+ std::size_t amount;
393
+ if (file_end_ - (index + file_begin_) > static_cast<uint64_t>(block_)) {
394
+ amount = block_;
395
+ current_end_ = index + amount - read_bound_;
396
+ } else {
397
+ amount = file_end_ - (index + file_begin_);
398
+ current_end_ = index + amount;
399
+ }
400
+ ptr_ = static_cast<uint8_t*>(ExtractNonRolling(mem_, index, amount)) - index;
401
+
402
+ current_begin_ = index;
403
+ }
404
+
405
+ } // namespace util
cc-multilingual-main/cc_net/third_party/kenlm/util/mmap.hh ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef UTIL_MMAP_H
2
+ #define UTIL_MMAP_H
3
+ // Utilities for mmaped files.
4
+
5
+ #include <cstddef>
6
+ #include <limits>
7
+
8
+ #include <stdint.h>
9
+ #include <sys/types.h>
10
+
11
+ namespace util {
12
+
13
+ class scoped_fd;
14
+
15
+ std::size_t SizePage();
16
+
17
+ // (void*)-1 is MAP_FAILED; this is done to avoid including the mmap header here.
18
+ class scoped_mmap {
19
+ public:
20
+ scoped_mmap() : data_((void*)-1), size_(0) {}
21
+ scoped_mmap(void *data, std::size_t size) : data_(data), size_(size) {}
22
+ ~scoped_mmap();
23
+
24
+ void *get() const { return data_; }
25
+
26
+ const char *begin() const { return reinterpret_cast<char*>(data_); }
27
+ char *begin() { return reinterpret_cast<char*>(data_); }
28
+ const char *end() const { return reinterpret_cast<char*>(data_) + size_; }
29
+ char *end() { return reinterpret_cast<char*>(data_) + size_; }
30
+ std::size_t size() const { return size_; }
31
+
32
+ void reset(void *data, std::size_t size) {
33
+ scoped_mmap other(data_, size_);
34
+ data_ = data;
35
+ size_ = size;
36
+ }
37
+
38
+ void reset() {
39
+ reset((void*)-1, 0);
40
+ }
41
+
42
+ void *steal() {
43
+ void *ret = data_;
44
+ data_ = (void*)-1;
45
+ size_ = 0;
46
+ return ret;
47
+ }
48
+
49
+ private:
50
+ void *data_;
51
+ std::size_t size_;
52
+
53
+ scoped_mmap(const scoped_mmap &);
54
+ scoped_mmap &operator=(const scoped_mmap &);
55
+ };
56
+
57
+ /* For when the memory might come from mmap or malloc. Uses NULL and 0 for
58
+ * blanks even though mmap signals errors with (void*)-1).
59
+ */
60
+ class scoped_memory {
61
+ public:
62
+ typedef enum {
63
+ // TODO: store rounded up size instead?
64
+ MMAP_ROUND_1G_ALLOCATED, // The size was rounded up for a 1GB page. Do the same before munmap.
65
+ MMAP_ROUND_2M_ALLOCATED, // The size was rounded up for a 2MB page. Do the same before munmap.
66
+ MMAP_ROUND_PAGE_ALLOCATED, // The size was rounded up to a multiple of the default page size. Do the same before munmap.
67
+ MMAP_ALLOCATED, // munmap
68
+ MALLOC_ALLOCATED, // free
69
+ NONE_ALLOCATED // nothing to free (though there can be something here if it's owned by somebody else).
70
+ } Alloc;
71
+
72
+ scoped_memory(void *data, std::size_t size, Alloc source)
73
+ : data_(data), size_(size), source_(source) {}
74
+
75
+ scoped_memory() : data_(NULL), size_(0), source_(NONE_ALLOCATED) {}
76
+
77
+ // Calls HugeMalloc
78
+ scoped_memory(std::size_t to, bool zero_new);
79
+
80
+ #if __cplusplus >= 201103L
81
+ scoped_memory(scoped_memory &&from) noexcept
82
+ : data_(from.data_), size_(from.size_), source_(from.source_) {
83
+ from.steal();
84
+ }
85
+ #endif
86
+
87
+ ~scoped_memory() { reset(); }
88
+
89
+ void *get() const { return data_; }
90
+
91
+ const char *begin() const { return reinterpret_cast<char*>(data_); }
92
+ char *begin() { return reinterpret_cast<char*>(data_); }
93
+ const char *end() const { return reinterpret_cast<char*>(data_) + size_; }
94
+ char *end() { return reinterpret_cast<char*>(data_) + size_; }
95
+ std::size_t size() const { return size_; }
96
+
97
+ Alloc source() const { return source_; }
98
+
99
+ void reset() { reset(NULL, 0, NONE_ALLOCATED); }
100
+
101
+ void reset(void *data, std::size_t size, Alloc from);
102
+
103
+ void *steal() {
104
+ void *ret = data_;
105
+ data_ = NULL;
106
+ size_ = 0;
107
+ source_ = NONE_ALLOCATED;
108
+ return ret;
109
+ }
110
+
111
+ private:
112
+ void *data_;
113
+ std::size_t size_;
114
+
115
+ Alloc source_;
116
+
117
+ scoped_memory(const scoped_memory &);
118
+ scoped_memory &operator=(const scoped_memory &);
119
+ };
120
+
121
+ extern const int kFileFlags;
122
+
123
+ // Cross-platform, error-checking wrapper for mmap().
124
+ void *MapOrThrow(std::size_t size, bool for_write, int flags, bool prefault, int fd, uint64_t offset = 0);
125
+
126
+ // msync wrapper
127
+ void SyncOrThrow(void *start, size_t length);
128
+
129
+ // Cross-platform, error-checking wrapper for munmap().
130
+ void UnmapOrThrow(void *start, size_t length);
131
+
132
+ // Allocate memory, promising that all/vast majority of it will be used. Tries
133
+ // hard to use huge pages on Linux.
134
+ // If you want zeroed memory, pass zeroed = true.
135
+ void HugeMalloc(std::size_t size, bool zeroed, scoped_memory &to);
136
+
137
+ // Reallocates memory ala realloc but with option to zero the new memory.
138
+ // On Linux, the memory can come from anonymous mmap or malloc/calloc.
139
+ // On non-Linux, only malloc/calloc is supported.
140
+ //
141
+ // To summarize, any memory from HugeMalloc or HugeRealloc can be resized with
142
+ // this.
143
+ void HugeRealloc(std::size_t size, bool new_zeroed, scoped_memory &mem);
144
+
145
+ enum LoadMethod {
146
+ // mmap with no prepopulate
147
+ LAZY,
148
+ // On linux, pass MAP_POPULATE to mmap.
149
+ POPULATE_OR_LAZY,
150
+ // Populate on Linux. malloc and read on non-Linux.
151
+ POPULATE_OR_READ,
152
+ // malloc and read.
153
+ READ,
154
+ // malloc and read in parallel (recommended for Lustre)
155
+ PARALLEL_READ,
156
+ };
157
+
158
+ void MapRead(LoadMethod method, int fd, uint64_t offset, std::size_t size, scoped_memory &out);
159
+
160
+ // Open file name with mmap of size bytes, all of which are initially zero.
161
+ void *MapZeroedWrite(int fd, std::size_t size);
162
+ void *MapZeroedWrite(const char *name, std::size_t size, scoped_fd &file);
163
+
164
+ // Forward rolling memory map with no overlap.
165
+ class Rolling {
166
+ public:
167
+ Rolling() {}
168
+
169
+ explicit Rolling(void *data) { Init(data); }
170
+
171
+ Rolling(const Rolling &copy_from, uint64_t increase = 0);
172
+ Rolling &operator=(const Rolling &copy_from);
173
+
174
+ // For an actual rolling mmap.
175
+ explicit Rolling(int fd, bool for_write, std::size_t block, std::size_t read_bound, uint64_t offset, uint64_t amount);
176
+
177
+ // For a static mapping
178
+ void Init(void *data) {
179
+ ptr_ = data;
180
+ current_end_ = std::numeric_limits<uint64_t>::max();
181
+ current_begin_ = 0;
182
+ // Mark as a pass-through.
183
+ fd_ = -1;
184
+ }
185
+
186
+ void IncreaseBase(uint64_t by) {
187
+ file_begin_ += by;
188
+ ptr_ = static_cast<uint8_t*>(ptr_) + by;
189
+ if (!IsPassthrough()) current_end_ = 0;
190
+ }
191
+
192
+ void DecreaseBase(uint64_t by) {
193
+ file_begin_ -= by;
194
+ ptr_ = static_cast<uint8_t*>(ptr_) - by;
195
+ if (!IsPassthrough()) current_end_ = 0;
196
+ }
197
+
198
+ void *ExtractNonRolling(scoped_memory &out, uint64_t index, std::size_t size);
199
+
200
+ // Returns base pointer
201
+ void *get() const { return ptr_; }
202
+
203
+ // Returns base pointer.
204
+ void *CheckedBase(uint64_t index) {
205
+ if (index >= current_end_ || index < current_begin_) {
206
+ Roll(index);
207
+ }
208
+ return ptr_;
209
+ }
210
+
211
+ // Returns indexed pointer.
212
+ void *CheckedIndex(uint64_t index) {
213
+ return static_cast<uint8_t*>(CheckedBase(index)) + index;
214
+ }
215
+
216
+ private:
217
+ void Roll(uint64_t index);
218
+
219
+ // True if this is just a thin wrapper on a pointer.
220
+ bool IsPassthrough() const { return fd_ == -1; }
221
+
222
+ void *ptr_;
223
+ uint64_t current_begin_;
224
+ uint64_t current_end_;
225
+
226
+ scoped_memory mem_;
227
+
228
+ int fd_;
229
+ uint64_t file_begin_;
230
+ uint64_t file_end_;
231
+
232
+ bool for_write_;
233
+ std::size_t block_;
234
+ std::size_t read_bound_;
235
+ };
236
+
237
+ } // namespace util
238
+
239
+ #endif // UTIL_MMAP_H