Repository navigation
Expand file tree
/
Copy pathEmbed.cpp
More file actions
96 lines (67 loc) · 2.23 KB
/
Copy pathEmbed.cpp
File metadata and controls
96 lines (67 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* @author Jamie (jamie.lim@kakaocorp.com)
* @copyright Copyright (C) 2018-, Kakao Corp. All rights reserved.
*/
#include "khaiii/Embed.hpp"
//////////////
// includes //
//////////////
#include <cstdlib>
#include <string>
#include "khaiii/Config.hpp"
#ifndef NDEBUG
#include "khaiii/util.hpp"
#endif
namespace khaiii {
using std::make_shared;
using std::shared_ptr;
using std::string;
////////////////////
// static members //
////////////////////
shared_ptr<spdlog::logger> Embed::_log = spdlog::stderr_color_mt("Embed");
/////////////
// methods //
/////////////
void Embed::open(const Config& cfg, string dir) {
_embed_mmf.open(fmt::format("{}/embed.bin", dir));
_keys = reinterpret_cast<const wchar_t*>(_embed_mmf.data());
const float* val_start = reinterpret_cast<const float*>(_keys + cfg.vocab_size);
for (int i = 0; i < cfg.vocab_size; ++i) {
const float* embed_start = val_start + i * cfg.embed_dim;
_vals.emplace_back(embedding_t(const_cast<float*>(embed_start), cfg.embed_dim));
SPDLOG_TRACE(_log, "[{}] {}", i, _vals[i]);
}
}
void Embed::close() {
_embed_mmf.close();
}
const embedding_t& Embed::operator[](wchar_t chr) const {
const wchar_t* found = reinterpret_cast<const wchar_t*>(
bsearch(&chr, _keys, _vals.size(), sizeof(wchar_t), Embed::_key_cmp));
int idx = 1; // unknown character index is 1
if (found != nullptr) idx = found - _keys;
#ifndef NDEBUG
wchar_t wstr[2] = {chr, 0};
SPDLOG_TRACE(_log, "'{}'({}) {}", wstr_to_utf8(wstr), idx, _vals.at(idx));
#endif
return _vals.at(idx);
}
const embedding_t& Embed::left_word_bound() const {
return _vals.at(2);
}
const embedding_t& Embed::right_word_bound() const {
return _vals.at(3);
}
const embedding_t& Embed::left_padding() const {
return _vals.at(0); // padding index is 0 which is zero vector
}
const embedding_t& Embed::right_padding() const {
return _vals.at(0); // padding index is 0 which is zero vector
}
int Embed::_key_cmp(const void* left, const void* right) {
const wchar_t* left_ = reinterpret_cast<const wchar_t*>(left);
const wchar_t* right_ = reinterpret_cast<const wchar_t*>(right);
return *left_ - *right_;
}
} // namespace khaiii