├── .clang-format
├── .gitmodules
├── CMakeLists.txt
├── LICENSE
├── Makefile
├── README.md
├── extern
├── catch.hpp
├── mew.h
└── tblr.h
├── koan.cpp
├── koan.png
├── koan
├── cli.h
├── def.h
├── indexmap.h
├── reader.h
├── sample.h
├── sigmoid.h
├── timer.h
├── trainer.h
└── util.h
├── tests
├── test_gradcheck.cpp
└── test_utils.cpp
├── word2vec_train_times_cbow.png
└── word2vec_train_times_sg.png
/.clang-format:
--------------------------------------------------------------------------------
1 | Language: Cpp
2 | AccessModifierOffset: -1
3 | AlignAfterOpenBracket: Align
4 | AlignConsecutiveAssignments: false
5 | AlignConsecutiveDeclarations: false
6 | AlignEscapedNewlines: Right
7 | AlignOperands: true
8 | AlignTrailingComments: true
9 | AllowAllParametersOfDeclarationOnNextLine: false
10 | AllowShortBlocksOnASingleLine: true
11 | AllowShortCaseLabelsOnASingleLine: true
12 | AllowShortFunctionsOnASingleLine: Inline
13 | AllowShortIfStatementsOnASingleLine: true
14 | AllowShortLoopsOnASingleLine: true
15 | AlwaysBreakAfterDefinitionReturnType: None
16 | AlwaysBreakAfterReturnType: None
17 | AlwaysBreakBeforeMultilineStrings: false
18 | AlwaysBreakTemplateDeclarations: true
19 | BinPackArguments: false
20 | BinPackParameters: false
21 | BraceWrapping:
22 | AfterClass: false
23 | AfterControlStatement: false
24 | AfterEnum: false
25 | AfterFunction: false
26 | AfterNamespace: false
27 | AfterObjCDeclaration: false
28 | AfterStruct: false
29 | AfterUnion: false
30 | BeforeCatch: false
31 | BeforeElse: false
32 | IndentBraces: false
33 | SplitEmptyFunction: false
34 | SplitEmptyRecord: false
35 | SplitEmptyNamespace: false
36 | BreakBeforeBinaryOperators: None
37 | BreakBeforeBraces: Custom
38 | BreakBeforeInheritanceComma: false
39 | BreakBeforeTernaryOperators: true
40 | BreakConstructorInitializersBeforeComma: false
41 | BreakConstructorInitializers: BeforeColon
42 | BreakAfterJavaFieldAnnotations: false
43 | BreakStringLiterals: false
44 | ColumnLimit: 80
45 | CommentPragmas: ''
46 | CompactNamespaces: false
47 | ConstructorInitializerAllOnOneLineOrOnePerLine: true
48 | ConstructorInitializerIndentWidth: 4
49 | ContinuationIndentWidth: 4
50 | Cpp11BracedListStyle: true
51 | DerivePointerAlignment: false
52 | DisableFormat: false
53 | ExperimentalAutoDetectBinPacking: false
54 | FixNamespaceComments: true
55 | IncludeCategories:
56 | - Regex: 'koan'
57 | Priority: 1
58 | - Regex: '\.'
59 | Priority: 2
60 | IndentCaseLabels: false
61 | IndentWidth: 2
62 | IndentWrappedFunctionNames: false
63 | KeepEmptyLinesAtTheStartOfBlocks: true
64 | MaxEmptyLinesToKeep: 1
65 | NamespaceIndentation: None
66 | PenaltyBreakAssignment: 2
67 | PenaltyBreakBeforeFirstCallParameter: 19
68 | PenaltyBreakComment: 300
69 | PenaltyBreakFirstLessLess: 120
70 | PenaltyBreakString: 1000
71 | PenaltyExcessCharacter: 1000000
72 | PenaltyReturnTypeOnItsOwnLine: 60
73 | PointerAlignment: Left
74 | ReflowComments: true
75 | SortIncludes: true
76 | SortUsingDeclarations: true
77 | SpaceAfterCStyleCast: false
78 | SpaceAfterTemplateKeyword: true
79 | SpaceBeforeAssignmentOperators: true
80 | SpaceBeforeParens: ControlStatements
81 | SpaceInEmptyParentheses: false
82 | SpacesBeforeTrailingComments: 1
83 | SpacesInAngles: false
84 | SpacesInContainerLiterals: true
85 | SpacesInCStyleCastParentheses: false
86 | SpacesInParentheses: false
87 | SpacesInSquareBrackets: false
88 | Standard: Cpp11
89 | TabWidth: 2
90 | UseTab: Never
91 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "eigen"]
2 | path = eigen
3 | url = https://gitlab.com/libeigen/eigen
4 |
--------------------------------------------------------------------------------
/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.10)
2 |
3 | project(koan)
4 |
5 | set(CMAKE_CXX_STANDARD 17)
6 | set(CMAKE_CXX_STANDARD_REQUIRED True)
7 |
8 | add_executable(koan koan.cpp)
9 | add_executable(test_utils tests/test_utils.cpp)
10 | add_executable(test_gradcheck tests/test_gradcheck.cpp)
11 |
12 | include_directories("${PROJECT_SOURCE_DIR}/")
13 | include_directories("${PROJECT_SOURCE_DIR}/eigen/")
14 |
15 | target_include_directories(test_utils PUBLIC "${PROJECT_SOURCE_DIR}/extern")
16 | target_include_directories(test_gradcheck PUBLIC "${PROJECT_SOURCE_DIR}/extern")
17 |
18 | add_compile_options(-Wall -Wextra -Werror)
19 |
20 | if(KOAN_ENABLE_ZIP)
21 | target_compile_options(koan PUBLIC -Ofast -march=native -mtune=native -DKOAN_ENABLE_ZIP)
22 | else()
23 | target_compile_options(koan PUBLIC -Ofast -march=native -mtune=native)
24 | endif()
25 |
26 | set(THREADS_PREFER_PTHREAD_FLAG ON)
27 | find_package(Threads REQUIRED)
28 |
29 | if(KOAN_ENABLE_ZIP)
30 | find_package(ZLIB REQUIRED)
31 | target_link_libraries(koan PRIVATE Threads::Threads ZLIB::ZLIB)
32 | else()
33 | target_link_libraries(koan PRIVATE Threads::Threads)
34 | endif()
35 |
36 |
37 | install(TARGETS koan DESTINATION bin)
38 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright 2020 Bloomberg Finance L.P.
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
204 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | CXX = g++
2 |
3 | BUILD_PATH = ./build
4 | EIGEN_INCLUDE = ./eigen/
5 |
6 | INCLUDES = -I$(EIGEN_INCLUDE) -I./
7 |
8 | CXXFLAGS = -std=c++17 -Wall -Wextra -pthread
9 |
10 | ZIPFLAGS = -lz -DKOAN_ENABLE_ZIP
11 |
12 | OPTFLAGS = -Ofast -march=native -mtune=native
13 | DEBUGFLAGS = -g -O0
14 |
15 | build_path:
16 | @mkdir -p $(BUILD_PATH)
17 |
18 | % : %.cpp build_path
19 | $(CXX) $< $(CXXFLAGS) ${ZIPFLAGS} $(OPTFLAGS) $(INCLUDES) -o $(BUILD_PATH)/$@
20 |
21 | debug : koan.cpp build_path
22 | $(CXX) $< $(CXXFLAGS) ${ZIPFLAGS} $(DEBUGFLAGS) $(INCLUDES) -o $(BUILD_PATH)/koan
23 |
24 | test_utils : tests/test_utils.cpp build_path
25 | $(CXX) $< $(CXXFLAGS) ${ZIPFLAGS} $(DEBUGFLAGS) $(INCLUDES) -I./extern/ -o $(BUILD_PATH)/test_utils
26 |
27 | test_gradcheck : tests/test_gradcheck.cpp build_path
28 | $(CXX) $< $(CXXFLAGS) ${ZIPFLAGS} $(DEBUGFLAGS) $(INCLUDES) -I./extern/ -o $(BUILD_PATH)/test_gradcheck
29 |
30 | all: koan test_utils test_gradcheck
31 |
32 | clean:
33 | rm -rf $(BUILD_PATH)
34 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |

2 |
3 | > ... the Zen attitude is that words and truth are incompatible, or at least that no words can capture truth.
4 | >
5 | > Douglas R. Hofstadter
6 |
7 | A word2vec negative sampling implementation with correct CBOW update. kōan only depends on Eigen.
8 |
9 | _Authors_: Ozan İrsoy, Adrian Benton, Karl Stratos
10 |
11 | Thanks to Cyril Khazan for helping kōan better scale to many threads.
12 |
13 | ## Menu
14 |
15 | - [Rationale](#rationale)
16 | - [Building](#building)
17 | - [Quick start](#quick-start)
18 | - [Installation](#installation)
19 | - [License](#license)
20 |
21 | ## Rationale
22 |
23 | Although continuous bag of word (CBOW) embeddings can be trained more quickly than skipgram (SG) embeddings, it is a common belief that SG embeddings tend to perform better in practice. This was observed by the original authors of Word2Vec [1] and also in subsequent work [2]. However, we found that popular implementations of word2vec with negative sampling such as [word2vec](https://github.com/tmikolov/word2vec/) and [gensim](https://github.com/RaRe-Technologies/gensim/) do not implement the CBOW update correctly, thus potentially leading to misconceptions about the performance of CBOW embeddings when trained correctly.
24 |
25 | We release kōan so that others can efficiently train CBOW embeddings using the corrected weight update. See this [technical report](https://arxiv.org/abs/2012.15332) for benchmarks of kōan vs. gensim word2vec negative sampling implementations. If you use kōan to learn word embeddings for your own work, please cite:
26 |
27 | > Ozan İrsoy, Adrian Benton, and Karl Stratos. "Corrected CBOW Performs as well as Skip-gram." The 2nd Workshop on Insights from Negative Results in NLP (__2021__).
28 |
29 | [1] Tomas Mikolov, Ilya Sutskever, Kai Chen, Greg S Corrado, and Jeff Dean. Distributed representations of words and phrases and their compositionality. In Advances in neural information processing systems, pages 3111–3119, 2013.
30 |
31 | [2] Karl Stratos, Michael Collins, and Daniel Hsu. Model-based word embeddings from decompositions of count matrices. In Proceedings of the 53rd Annual Meeting of the Association for Computational Linguistics and the 7th International Joint Conference on Natural Language Processing
32 | (Volume 1: Long Papers), pages 1282–1291, 2015.
33 |
34 | See [here](https://doi.org/10.5281/zenodo.5542319) for kōan embeddings trained on the English cleaned common crawl corpus (C4).
35 |
36 | ## Building
37 |
38 | You need a C++17 supporting compiler to build koan (tested with g++ 7.5.0, 8.4.0, 9.3.0, and clang 11.0.3).
39 |
40 | To build koan and all tests:
41 | ```
42 | mkdir build
43 | cd build
44 | cmake ..
45 | cmake --build ./
46 | ```
47 |
48 | Run tests with (assuming you are still under `build`):
49 | ```
50 | ./test_gradcheck
51 | ./test_utils
52 | ```
53 |
54 | ## Installation
55 |
56 | Installation is as simple as placing the koan binary on your `PATH`
57 | (you might need sudo):
58 |
59 | ```
60 | cmake --install ./
61 | ```
62 |
63 | ## Quick Start
64 |
65 | To train word embeddings on [Wikitext-2](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/), first clone and build koan:
66 |
67 | ```
68 | git clone --recursive git@github.com:bloomberg/koan.git
69 | cd koan
70 | mkdir build
71 | cd build
72 | cmake .. && cmake --build ./
73 | cd ..
74 | ```
75 |
76 | Download and unzip the Wikitext-2 corpus:
77 |
78 | ```
79 | curl https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-v1.zip --output wikitext-2-v1.zip
80 | unzip wikitext-2-v1.zip
81 | head -n 5 ./wikitext-2/wiki.train.tokens
82 | ```
83 |
84 | And learn CBOW embeddings on the training fold with:
85 |
86 | ```
87 | ./build/koan -V 2000000 \
88 | --epochs 10 \
89 | --dim 300 \
90 | --negatives 5 \
91 | --context-size 5 \
92 | -l 0.075 \
93 | --threads 16 \
94 | --cbow true \
95 | --min-count 2 \
96 | --file ./wikitext-2/wiki.train.tokens
97 | ```
98 |
99 | or skipgram embeddings by running with `--cbow false`. `./build/koan --help` for a full list of command-line arguments and descriptions. Learned embeddings will be saved to `embeddings_${CURRENT_TIMESTAMP}.txt` in the present working directory.
100 |
101 | ## License
102 |
103 | Please read the [LICENSE](LICENSE) file.
104 |
105 | ## Benchmarks
106 |
107 | 

108 |
109 | See the [report](https://arxiv.org/abs/2012.15332) for more details.
110 |
--------------------------------------------------------------------------------
/extern/mew.h:
--------------------------------------------------------------------------------
1 | /*
2 | ** Copyright 2020 Bloomberg Finance L.P.
3 | **
4 | ** Licensed under the Apache License, Version 2.0 (the "License");
5 | ** you may not use this file except in compliance with the License.
6 | ** You may obtain a copy of the License at
7 | **
8 | ** http://www.apache.org/licenses/LICENSE-2.0
9 | **
10 | ** Unless required by applicable law or agreed to in writing, software
11 | ** distributed under the License is distributed on an "AS IS" BASIS,
12 | ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | ** See the License for the specific language governing permissions and
14 | ** limitations under the License.
15 | */
16 |
17 | #ifndef MEW_H
18 | #define MEW_H
19 |
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 |
30 | namespace mew {
31 |
32 | using Strings = std::vector;
33 | using StringsList = std::vector;
34 |
35 | // double precision seconds
36 | using Duration = std::chrono::duration>;
37 |
38 | enum AnimationStyle : unsigned short {
39 | Ellipsis,
40 | Clock,
41 | Moon,
42 | Earth,
43 | Bar,
44 | Square,
45 | };
46 |
47 | const static StringsList animation_stills_{
48 | {". ", ".. ", "..."},
49 | {"🕐", "🕜", "🕑", "🕝", "🕒", "🕞", "🕓", "🕟", "🕔", "🕠", "🕕", "🕡",
50 | "🕖", "🕢", "🕗", "🕣", "🕘", "🕤", "🕙", "🕥", "🕚", "🕦", "🕛", "🕧"},
51 | {"🌕", "🌖", "🌗", "🌘", "🌑", "🌒", "🌓", "🌔"},
52 | {"🌎", "🌍", "🌏"},
53 | {"-", "/", "|", "\\"},
54 | {"▖", "▘", "▝", "▗"},
55 | };
56 |
57 | enum ProgressBarStyle : unsigned short { Bars, Blocks, Arrow };
58 |
59 | const static StringsList progress_partials_{
60 | {"|"},
61 | {"▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"},
62 | {">", "="},
63 | };
64 |
65 | enum class Speed : unsigned short { None, Last, Overall, Both };
66 |
67 | template
68 | class AsyncDisplay {
69 | private:
70 | Duration period_;
71 | std::unique_ptr displayer_;
72 | std::condition_variable completion_;
73 | std::mutex completion_m_;
74 | bool complete_ = false;
75 |
76 | std::string message_;
77 | std::ostream& out_;
78 |
79 | // Render animation, progress bar, etc. Needs to be specialized.
80 | void render_(std::ostream& out) { static_cast(*this).render_(out); }
81 |
82 | // Display message (maybe with animation, progress bar, etc)
83 | void display_() {
84 | out_ << "\r";
85 | render_(out_);
86 | out_ << std::flush;
87 | }
88 |
89 | protected:
90 | void render_message_(std::ostream& out) {
91 | if (not message_.empty()) { out << message_ << " "; }
92 | }
93 |
94 | public:
95 | AsyncDisplay(std::string message = "",
96 | double period = 1,
97 | std::ostream& out = std::cout)
98 | : period_(period), message_(std::move(message)), out_(out) {}
99 |
100 | AsyncDisplay(std::string message,
101 | Duration period,
102 | std::ostream& out = std::cout)
103 | : period_(period), message_(std::move(message)), out_(out) {}
104 |
105 | AsyncDisplay(const AsyncDisplay& other)
106 | : period_(other.period_),
107 | complete_(other.complete_),
108 | message_(other.message_),
109 | out_(other.out_) {}
110 |
111 | AsyncDisplay(AsyncDisplay&& other)
112 | : period_(std::move(other.period_)),
113 | complete_(std::move(other.complete_)),
114 | message_(std::move(other.message_)),
115 | out_(other.out_) {}
116 |
117 | void start() {
118 | displayer_ = std::make_unique([this]() {
119 | display_();
120 | while (true) {
121 | std::unique_lock lock(completion_m_);
122 | completion_.wait_for(lock, period_);
123 | display_();
124 | if (complete_) { break; }
125 | }
126 | });
127 | }
128 |
129 | void done() {
130 | if (not displayer_) { return; } // already done() before; noop
131 | {
132 | std::lock_guard lock(completion_m_);
133 | complete_ = true;
134 | }
135 | completion_.notify_all();
136 | displayer_->join();
137 | displayer_.reset();
138 | out_ << std::endl;
139 | }
140 |
141 | template
142 | friend class Composite;
143 | };
144 |
145 | class Animation : public AsyncDisplay {
146 | private:
147 | unsigned short frame_ = 0;
148 | const Strings& stills_;
149 |
150 | void render_(std::ostream& out) {
151 | this->render_message_(out);
152 | out << stills_[frame_] << " ";
153 | frame_ = (frame_ + 1) % stills_.size();
154 | }
155 |
156 | public:
157 | using Style = AnimationStyle;
158 |
159 | Animation(std::string message = "",
160 | Style style = Ellipsis,
161 | double period = 1,
162 | std::ostream& out = std::cout)
163 | : AsyncDisplay(message, period, out),
164 | stills_(animation_stills_[static_cast(style)]) {}
165 |
166 | Animation(const Animation&) = default;
167 | Animation(Animation&&) = default;
168 |
169 | friend class AsyncDisplay;
170 | template
171 | friend class Composite;
172 | };
173 |
174 | template
175 | class Composite : public AsyncDisplay> {
176 | private:
177 | LeftDisplay left_;
178 | RightDisplay right_;
179 |
180 | void render_(std::ostream& out) {
181 | left_.render_(out);
182 | out << " ";
183 | right_.render_(out);
184 | }
185 |
186 | public:
187 | Composite(LeftDisplay left, RightDisplay right)
188 | : AsyncDisplay>(left.message_,
189 | left.period_,
190 | left.out_),
191 | left_(std::move(left)),
192 | right_(std::move(right)) {}
193 |
194 | friend class AsyncDisplay>;
195 | template
196 | friend class Composite;
197 | };
198 |
199 | template
200 | auto operator|(LeftDisplay left, RightDisplay right) {
201 | return Composite(std::move(left),
202 | std::move(right));
203 | }
204 |
205 | template
206 | struct ProgressTraits {
207 | using value_type = Progress;
208 | };
209 |
210 | template
211 | struct ProgressTraits> {
212 | using value_type = Progress;
213 | };
214 |
215 | template
216 | class Speedometer {
217 | private:
218 | Progress& progress_; // Current amount of work done
219 | Speed speed_; // Time period to compute speed over
220 | std::string unit_of_speed_; // unit (message) to display alongside speed
221 |
222 | using Clock = std::chrono::system_clock;
223 | using Time = std::chrono::time_point;
224 |
225 | Time start_time_, last_start_time_;
226 | typename ProgressTraits