-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathPathEvaluator.hpp
1307 lines (1177 loc) · 38.3 KB
/
PathEvaluator.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <fstream>
#include <kiwi/Kiwi.h>
#include <kiwi/Utils.h>
#include <kiwi/TemplateUtils.hpp>
#include <kiwi/Form.h>
#include "ArchAvailable.h"
#include "KTrie.h"
#include "FeatureTestor.h"
#include "FrozenTrie.hpp"
#include "LmState.hpp"
#include "StrUtils.h"
#include "SortUtils.hpp"
#include "LimitedVector.hpp"
using namespace std;
namespace kiwi
{
struct SpecialState
{
uint8_t singleQuote : 1;
uint8_t doubleQuote : 1;
uint8_t bulletHash : 6;
SpecialState() : singleQuote{ 0 }, doubleQuote{ 0 }, bulletHash{ 0 }
{
}
operator uint8_t() const
{
return reinterpret_cast<const uint8_t&>(*this);
}
bool operator<(const SpecialState& o) const
{
return (uint8_t)(*this) < (uint8_t)o;
}
bool operator==(const SpecialState& o) const
{
return (uint8_t)(*this) == (uint8_t)o;
}
};
template<class LmState>
struct WordLL;
using Wid = uint32_t;
enum class PathEvaluatingMode
{
topN,
top1,
top1Small,
};
class PathEvaluator
{
public:
struct Result
{
const Morpheme* morph = nullptr;
KString str;
uint32_t begin = 0, end = 0;
float wordScore = 0, typoCost = 0;
uint32_t typoFormId = 0;
uint32_t nodeId = 0;
Result(const Morpheme* _morph = nullptr,
const KString& _str = {},
uint32_t _begin = 0,
uint32_t _end = 0,
float _wordScore = 0,
float _typoCost = 0,
uint32_t _typoFormId = 0,
uint32_t _nodeId = 0
)
: morph{ _morph }, str{ _str }, begin{ _begin }, end{ _end },
wordScore{ _wordScore }, typoCost{ _typoCost }, typoFormId{ _typoFormId }, nodeId{ _nodeId }
{
}
bool operator==(const Result& o) const
{
return morph == o.morph
&& str == o.str
&& begin == o.begin
&& end == o.end
&& wordScore == o.wordScore
&& typoCost == o.typoCost
&& typoFormId == o.typoFormId;
}
};
using Path = Vector<Result>;
struct ChunkResult
{
Path path;
float score = 0;
SpecialState prevState;
SpecialState curState;
ChunkResult(Path&& _path = {}, float _score = 0, SpecialState _prevState = {}, SpecialState _curState = {})
: path{ move(_path) }, score{ _score }, prevState{ _prevState }, curState{ _curState }
{}
ChunkResult(const Path& _path, float _score = 0, SpecialState _prevState = {}, SpecialState _curState = {})
: path{ _path }, score{ _score }, prevState{ _prevState }, curState{ _curState }
{}
};
template<class LmState>
static Vector<ChunkResult> findBestPath(const Kiwi* kw,
const Vector<SpecialState>& prevSpStates,
const KGraphNode* graph,
const size_t graphSize,
const size_t topN,
bool openEnd,
bool splitComplex = false,
bool splitSaisiot = false,
bool mergeSaisiot = false,
const std::unordered_set<const Morpheme*>* blocklist = nullptr
);
template<class LmState, class CandTy>
static void evalPath(const Kiwi* kw,
const KGraphNode* startNode,
const KGraphNode* node,
const size_t topN,
Vector<Vector<WordLL<LmState>>>& cache,
const Vector<U16StringView>& ownFormList,
size_t i,
size_t ownFormId,
CandTy&& cands,
bool unknownForm,
const Vector<SpecialState>& prevSpStates,
bool splitComplex = false,
bool splitSaisiot = false,
bool mergeSaisiot = false,
const std::unordered_set<const Morpheme*>* blocklist = nullptr
);
template<PathEvaluatingMode mode, class LmState>
static void evalSingleMorpheme(
Vector<WordLL<LmState>>& resultOut,
const Kiwi* kw,
const Vector<U16StringView>& ownForms,
const Vector<Vector<WordLL<LmState>>>& cache,
size_t ownFormId,
const Morpheme* curMorph,
const KGraphNode* node,
const KGraphNode* startNode,
const size_t topN,
const float ignoreCondScore,
const float nodeLevelDiscount,
const Vector<SpecialState>& prevSpStates
);
};
using FnFindBestPath = decltype(&PathEvaluator::findBestPath<KnLMState<ArchType::none, uint16_t>>);
template<template<ArchType> class LmState>
struct FindBestPathGetter
{
template<std::ptrdiff_t i>
struct Wrapper
{
static constexpr FnFindBestPath value = &PathEvaluator::findBestPath<LmState<static_cast<ArchType>(i)>>;
};
};
template<class LmState>
struct WordLL
{
const Morpheme* morpheme = nullptr;
float accScore = 0, accTypoCost = 0;
const WordLL* parent = nullptr;
LmState lmState;
Wid wid = 0;
uint16_t ownFormId = 0;
uint8_t combineSocket = 0;
uint8_t rootId = 0;
SpecialState spState;
WordLL() = default;
WordLL(const Morpheme* _morph, float _accScore, float _accTypoCost, const WordLL* _parent, LmState _lmState, SpecialState _spState)
: morpheme{ _morph },
accScore{ _accScore },
accTypoCost{ _accTypoCost },
parent{ _parent },
lmState{ _lmState },
spState{ _spState },
rootId{ parent ? parent->rootId : (uint8_t)0 }
{
}
const WordLL* root() const
{
if (parent) return parent->root();
else return this;
}
};
static constexpr uint8_t commonRootId = -1;
template<class LmState>
struct PathHash
{
LmState lmState;
uint8_t rootId, spState;
PathHash(LmState _lmState = {}, uint8_t _rootId = 0, SpecialState _spState = {})
: lmState{ _lmState }, rootId{ _rootId }, spState { _spState }
{
}
PathHash(const WordLL<LmState>& wordLl, const Morpheme* morphBase)
: PathHash{ wordLl.lmState, wordLl.rootId, wordLl.spState }
{
}
bool operator==(const PathHash& o) const
{
return lmState == o.lmState && rootId == o.rootId && spState == o.spState;
}
};
template<size_t windowSize, ArchType _arch, class VocabTy>
struct PathHash<SbgState<windowSize, _arch, VocabTy>>
{
using LmState = SbgState<windowSize, _arch, VocabTy>;
KnLMState<_arch, VocabTy> lmState;
array<VocabTy, 4> lastMorphemes;
uint8_t rootId, spState;
PathHash(LmState _lmState = {}, uint8_t _rootId = 0, SpecialState _spState = {})
: lmState{ _lmState }, rootId{ _rootId }, spState{ _spState }
{
_lmState.getLastHistory(lastMorphemes.data(), lastMorphemes.size());
}
PathHash(const WordLL<LmState>& wordLl, const Morpheme* morphBase)
: PathHash{ wordLl.lmState, wordLl.rootId, wordLl.spState }
{
}
bool operator==(const PathHash& o) const
{
return lmState == o.lmState && lastMorphemes == o.lastMorphemes && spState == o.spState;
}
};
template<class LmState>
struct Hash<PathHash<LmState>>
{
size_t operator()(const PathHash<LmState>& p) const
{
size_t ret = 0;
if (sizeof(PathHash<LmState>) % sizeof(size_t))
{
auto ptr = reinterpret_cast<const uint32_t*>(&p);
for (size_t i = 0; i < sizeof(PathHash<LmState>) / sizeof(uint32_t); ++i)
{
ret ^= ptr[i];
}
}
else
{
auto ptr = reinterpret_cast<const size_t*>(&p);
for (size_t i = 0; i < sizeof(PathHash<LmState>) / sizeof(size_t); ++i)
{
ret ^= ptr[i];
}
}
return ret;
}
};
struct WordLLGreater
{
template<class LmState>
bool operator()(const WordLL<LmState>& a, const WordLL<LmState>& b) const
{
return a.accScore > b.accScore;
}
};
template<class LmState>
inline std::ostream& printDebugPath(std::ostream& os, const WordLL<LmState>& src)
{
if (src.parent)
{
printDebugPath(os, *src.parent);
}
if (src.morpheme) src.morpheme->print(os);
else os << "NULL";
os << " , ";
return os;
}
inline bool hasLeftBoundary(const KGraphNode* node)
{
// 시작 지점은 항상 왼쪽 경계로 처리
if (node->getPrev()->endPos == 0) return true;
// 이전 노드의 끝지점이 현재 노드보다 작은 경우 왼쪽 경계로 처리
if (node->getPrev()->endPos < node->startPos) return true;
// 이전 노드가 구두점이나 특수 문자인 경우
if (!node->getPrev()->uform.empty())
{
// 닫는 괄호는 왼쪽 경계로 처리하지 않음
auto c = node->getPrev()->uform.back();
auto tag = identifySpecialChr(c);
if (tag == POSTag::ssc || c == u'"' || c == u'\'') return false;
// 나머지 특수문자는 왼쪽 경계로 처리
if (POSTag::sf <= tag && tag <= POSTag::sb) return true;
}
return false;
}
inline bool isInflectendaNP(const Morpheme* morph)
{
return morph->tag == POSTag::np && morph->kform->size() == 1 && (
(*morph->kform)[0] == u'나' || (*morph->kform)[0] == u'너' || (*morph->kform)[0] == u'저');
}
inline bool isInflectendaJ(const Morpheme* morph)
{
return (morph->tag == POSTag::jks || morph->tag == POSTag::jkc) && morph->kform->size() == 1 && (*morph->kform)[0] == u'가';
}
inline bool isVerbL(const Morpheme* morph)
{
return isVerbClass(morph->tag) && morph->kform && !morph->kform->empty() && morph->kform->back() == u'ᆯ';
}
inline bool isBadPairOfVerbL(const Morpheme* morph)
{
auto onset = (morph->kform && !morph->kform->empty()) ? morph->kform->front() : 0;
return onset == u'으' || onset == u'느' || (u'사' <= onset && onset <= u'시');
}
inline bool isPositiveVerb(const Morpheme* morph)
{
return isVerbClass(morph->tag) && FeatureTestor::isMatched(morph->kform, CondPolarity::positive);
}
inline bool isNegativeVerb(const Morpheme* morph)
{
return isVerbClass(morph->tag) && FeatureTestor::isMatched(morph->kform, CondPolarity::negative);
}
inline bool isVerbVowel(const Morpheme* morph)
{
return isVerbClass(morph->tag) && morph->kform && !morph->kform->empty() && !isHangulCoda(morph->kform->back());
}
inline uint8_t hashSbTypeOrder(uint8_t type, uint8_t order)
{
return ((type << 1) ^ (type >> 7) ^ order) % 63 + 1;
}
struct RuleBasedScorer
{
Kiwi::SpecialMorph curMorphSpecialType;
size_t curMorphSbType;
int curMorphSbOrder;
bool vowelE, infJ, badPairOfL, positiveE, contractableE;
CondPolarity condP;
RuleBasedScorer(const Kiwi* kw, const Morpheme* curMorph, const KGraphNode* node)
:
curMorphSpecialType{ kw->determineSpecialMorphType(kw->morphToId(curMorph)) },
curMorphSbType{ curMorph->tag == POSTag::sb ? getSBType(joinHangul(*curMorph->kform)) : 0 },
curMorphSbOrder{ curMorphSbType ? curMorph->senseId : 0 },
vowelE{ isEClass(curMorph->tag) && curMorph->kform && hasNoOnset(*curMorph->kform) },
infJ{ isInflectendaJ(curMorph) },
badPairOfL{ isBadPairOfVerbL(curMorph) },
positiveE{ isEClass(curMorph->tag) && node->form && node->form->form[0] == u'아' },
contractableE{ isEClass(curMorph->tag) && curMorph->kform && !curMorph->kform->empty() && (*curMorph->kform)[0] == u'어' },
condP{ curMorph->polar }
{
}
float operator()(const Morpheme* prevMorpheme, const SpecialState prevSpState) const
{
float accScore = 0;
// 불규칙 활용 형태소 뒤에 모음 어미가 붙는 경우 벌점 부여
if (vowelE && isIrregular(prevMorpheme->tag))
{
accScore -= 10;
}
// 나/너/저 뒤에 주격 조사 '가'가 붙는 경우 벌점 부여
if (infJ && isInflectendaNP(prevMorpheme))
{
accScore -= 5;
}
// ㄹ 받침 용언 뒤에 으/느/ㅅ으로 시작하는 형태소가 올 경우 벌점 부여
if (badPairOfL && isVerbL(prevMorpheme))
{
accScore -= 7;
}
// 동사 뒤가 아니거나, 앞의 동사가 양성이 아닌데, 양성모음용 어미가 등장한 경우 벌점 부여
if (positiveE && !isPositiveVerb(prevMorpheme))
{
accScore -= 100;
}
// 아/어로 시작하는 어미가 받침 없는 동사 뒤에서 축약되지 않은 경우 벌점 부여
if (contractableE && isVerbVowel(prevMorpheme))
{
accScore -= 3;
}
// 형용사 사용 불가 어미인데 형용사 뒤에 등장
if (condP == CondPolarity::non_adj && (prevMorpheme->tag == POSTag::va || prevMorpheme->tag == POSTag::xsa))
{
accScore -= 10;
}
if (curMorphSpecialType <= Kiwi::SpecialMorph::singleQuoteNA)
{
if (static_cast<uint8_t>(curMorphSpecialType) != prevSpState.singleQuote)
{
accScore -= 2;
}
}
else if (curMorphSpecialType <= Kiwi::SpecialMorph::doubleQuoteNA)
{
if ((static_cast<uint8_t>(curMorphSpecialType) - 3) != prevSpState.doubleQuote)
{
accScore -= 2;
}
}
// discount for SB in form "[가-하]."
if (curMorphSbType == 5)
{
accScore -= 5;
}
if (curMorphSbType && isEClass(prevMorpheme->tag) && prevMorpheme->tag != POSTag::ef)
{
accScore -= 10;
}
if (curMorphSbType && prevSpState.bulletHash == hashSbTypeOrder(curMorphSbType, curMorphSbOrder))
{
accScore += 3;
}
return accScore;
}
};
inline bool isQuote(Kiwi::SpecialMorph m)
{
return m == Kiwi::SpecialMorph::singleQuoteOpen || m == Kiwi::SpecialMorph::singleQuoteClose
|| m == Kiwi::SpecialMorph::doubleQuoteOpen || m == Kiwi::SpecialMorph::doubleQuoteClose;
}
template<PathEvaluatingMode mode, class LmState>
class BestPathConatiner;
template<class LmState>
class BestPathConatiner<PathEvaluatingMode::topN, LmState>
{
// pair: [index, size]
UnorderedMap<PathHash<LmState>, pair<uint32_t, uint32_t>> bestPathIndex;
Vector<WordLL<LmState>> bestPathValues;
public:
inline void clear()
{
bestPathIndex.clear();
bestPathValues.clear();
}
inline void insert(const PathHash<LmState>& ph, size_t topN, uint8_t rootId,
const Morpheme* morph, float accScore, float accTypoCost, const WordLL<LmState>* parent, LmState&& lmState, SpecialState spState)
{
auto inserted = bestPathIndex.emplace(ph, make_pair((uint32_t)bestPathValues.size(), 1));
if (inserted.second)
{
bestPathValues.emplace_back(morph, accScore, accTypoCost, parent, move(lmState), spState);
if (rootId != commonRootId) bestPathValues.back().rootId = rootId;
bestPathValues.resize(bestPathValues.size() + topN - 1);
}
else
{
auto bestPathFirst = bestPathValues.begin() + inserted.first->second.first;
auto bestPathLast = bestPathValues.begin() + inserted.first->second.first + inserted.first->second.second;
if (distance(bestPathFirst, bestPathLast) < topN)
{
*bestPathLast = WordLL<LmState>{ morph, accScore, accTypoCost, parent, move(lmState), spState };
if (rootId != commonRootId) bestPathLast->rootId = rootId;
push_heap(bestPathFirst, bestPathLast + 1, WordLLGreater{});
++inserted.first->second.second;
}
else
{
if (accScore > bestPathFirst->accScore)
{
pop_heap(bestPathFirst, bestPathLast, WordLLGreater{});
*(bestPathLast - 1) = WordLL<LmState>{ morph, accScore, accTypoCost, parent, move(lmState), spState };
if (rootId != commonRootId) (*(bestPathLast - 1)).rootId = rootId;
push_heap(bestPathFirst, bestPathLast, WordLLGreater{});
}
}
}
}
inline void writeTo(Vector<WordLL<LmState>>& resultOut, const Morpheme* curMorph, Wid lastSeqId, size_t ownFormId)
{
for (auto& p : bestPathIndex)
{
const auto index = p.second.first;
const auto size = p.second.second;
for (size_t i = 0; i < size; ++i)
{
resultOut.emplace_back(move(bestPathValues[index + i]));
auto& newPath = resultOut.back();
// fill the rest information of resultOut
newPath.wid = lastSeqId;
if (curMorph->chunks.empty() || curMorph->complex || curMorph->saisiot)
{
newPath.combineSocket = curMorph->combineSocket;
newPath.ownFormId = ownFormId;
}
}
}
}
};
template<class LmState>
class BestPathConatiner<PathEvaluatingMode::top1, LmState>
{
UnorderedMap<PathHash<LmState>, WordLL<LmState>> bestPathes;
public:
inline void clear()
{
bestPathes.clear();
}
inline void insert(const PathHash<LmState>& ph, size_t topN, uint8_t rootId,
const Morpheme* morph, float accScore, float accTypoCost, const WordLL<LmState>* parent, LmState&& lmState, SpecialState spState)
{
WordLL<LmState> newPath{ morph, accScore, accTypoCost, parent, move(lmState), spState };
if (rootId != commonRootId) newPath.rootId = rootId;
auto inserted = bestPathes.emplace(ph, newPath);
if (!inserted.second)
{
auto& target = inserted.first->second;
if (accScore > target.accScore)
{
target = newPath;
}
}
}
inline void writeTo(Vector<WordLL<LmState>>& resultOut, const Morpheme* curMorph, Wid lastSeqId, size_t ownFormId)
{
for (auto& p : bestPathes)
{
resultOut.emplace_back(move(p.second));
auto& newPath = resultOut.back();
// fill the rest information of resultOut
newPath.wid = lastSeqId;
if (curMorph->chunks.empty() || curMorph->complex || curMorph->saisiot)
{
newPath.combineSocket = curMorph->combineSocket;
newPath.ownFormId = ownFormId;
}
}
}
};
template<class LmState>
class BestPathConatiner<PathEvaluatingMode::top1Small, LmState>
{
Vector<PathHash<LmState>> bestPathIndicesSmall;
Vector<WordLL<LmState>> bestPathValuesSmall;
public:
inline void clear()
{
bestPathIndicesSmall.clear();
bestPathValuesSmall.clear();
}
inline void insert(const PathHash<LmState>& ph, size_t topN, uint8_t rootId,
const Morpheme* morph, float accScore, float accTypoCost, const WordLL<LmState>* parent, LmState&& lmState, SpecialState spState)
{
const auto it = find(bestPathIndicesSmall.begin(), bestPathIndicesSmall.end(), ph);
if (it == bestPathIndicesSmall.end())
{
bestPathIndicesSmall.push_back(ph);
bestPathValuesSmall.emplace_back(morph, accScore, accTypoCost, parent, move(lmState), spState);
if (rootId != commonRootId) bestPathValuesSmall.back().rootId = rootId;
}
else
{
auto& target = bestPathValuesSmall[it - bestPathIndicesSmall.begin()];
if (accScore > target.accScore)
{
target = WordLL<LmState>{ morph, accScore, accTypoCost, parent, move(lmState), spState };
if (rootId != commonRootId) target.rootId = rootId;
}
}
}
inline void writeTo(Vector<WordLL<LmState>>& resultOut, const Morpheme* curMorph, Wid lastSeqId, size_t ownFormId)
{
for (auto& p : bestPathValuesSmall)
{
resultOut.emplace_back(move(p));
auto& newPath = resultOut.back();
// fill the rest information of resultOut
newPath.wid = lastSeqId;
if (curMorph->chunks.empty() || curMorph->complex || curMorph->saisiot)
{
newPath.combineSocket = curMorph->combineSocket;
newPath.ownFormId = ownFormId;
}
}
}
};
template<PathEvaluatingMode mode, class LmState>
void PathEvaluator::evalSingleMorpheme(
Vector<WordLL<LmState>>& resultOut,
const Kiwi* kw,
const Vector<U16StringView>& ownForms,
const Vector<Vector<WordLL<LmState>>>& cache,
size_t ownFormId,
const Morpheme* curMorph,
const KGraphNode* node,
const KGraphNode* startNode,
const size_t topN,
const float ignoreCondScore,
const float nodeLevelDiscount,
const Vector<SpecialState>& prevSpStates
)
{
thread_local BestPathConatiner<mode, LmState> bestPathCont;
thread_local Vector<uint8_t> rootIds;
const LangModel& langMdl = kw->langMdl;
const Morpheme* morphBase = kw->morphemes.data();
const auto spacePenalty = kw->spacePenalty;
const bool allowedSpaceBetweenChunk = kw->spaceTolerance > 0;
const size_t langVocabSize = langMdl.knlm->getHeader().vocab_size;
const Morpheme* lastMorph;
Wid firstWid;
if (curMorph->chunks.empty() || curMorph->complex || curMorph->saisiot)
{
lastMorph = curMorph->getCombined() ? curMorph->getCombined() : curMorph;
firstWid = curMorph->lmMorphemeId;
}
// if the morpheme has chunk set
else
{
lastMorph = curMorph->chunks[curMorph->chunks.size() - 1];
firstWid = curMorph->chunks[0]->lmMorphemeId;
}
Wid lastSeqId;
if (within(lastMorph, kw->morphemes.data() + langVocabSize, kw->morphemes.data() + kw->morphemes.size()))
{
lastSeqId = lastMorph - kw->morphemes.data();
}
else
{
lastSeqId = lastMorph->lmMorphemeId;
}
bestPathCont.clear();
const float additionalScore = curMorph->userScore + nodeLevelDiscount + kw->tagScorer.evalLeftBoundary(hasLeftBoundary(node), curMorph->tag);
RuleBasedScorer ruleBasedScorer{ kw, curMorph, node };
for (auto* prev = node->getPrev(); prev; prev = prev->getSibling())
{
for (auto& prevPath : cache[prev - startNode])
{
// 사이시옷 뒤에 명사가 아닌 태그가 오거나 공백이 있는 경우 제외
if (prevPath.morpheme->tag == POSTag::z_siot && (
!isNNClass(curMorph->tag) || prev->endPos < node->startPos
))
{
continue;
}
float candScore = prevPath.accScore + additionalScore;
if (prevPath.combineSocket)
{
// merge <v> <chunk> with only the same socket
if (prevPath.combineSocket != curMorph->combineSocket || (curMorph->chunks.empty() || curMorph->complex || curMorph->saisiot))
{
continue;
}
if (prev->endPos < node->startPos)
{
if (allowedSpaceBetweenChunk) candScore -= spacePenalty;
else continue;
}
firstWid = morphBase[prevPath.wid].getCombined()->lmMorphemeId;
}
const kchar_t* leftFormFirst, * leftFormLast;
if (prevPath.ownFormId)
{
leftFormFirst = ownForms[prevPath.ownFormId - 1].data();
leftFormLast = leftFormFirst + ownForms[0].size();
}
else if (morphBase[prevPath.wid].kform && !morphBase[prevPath.wid].kform->empty())
{
leftFormFirst = morphBase[prevPath.wid].kform->data();
leftFormLast = leftFormFirst + morphBase[prevPath.wid].kform->size();
}
else
{
leftFormFirst = prevPath.morpheme->getForm().data();
leftFormLast = leftFormFirst + prevPath.morpheme->getForm().size();
}
const CondVowel cvowel = curMorph->vowel;
const CondPolarity cpolar = curMorph->polar;
const bool leftFormEndswithSSC = leftFormFirst < leftFormLast && identifySpecialChr(leftFormLast[-1]) == POSTag::ssc;
if (prevPath.morpheme->tag == POSTag::ssc || leftFormEndswithSSC)
{
// 이전 형태소가 닫는 괄호인 경우 좌측 결합조건을 적용하지 않음
}
else if (ignoreCondScore)
{
candScore += FeatureTestor::isMatched(leftFormFirst, leftFormLast, cvowel, cpolar) ? 0 : ignoreCondScore;
}
else
{
if (!FeatureTestor::isMatched(leftFormFirst, leftFormLast, cvowel, cpolar)) continue;
}
auto cLmState = prevPath.lmState;
if (curMorph->combineSocket && (curMorph->chunks.empty() || curMorph->complex || curMorph->saisiot))
{
// no-op
}
else
{
if (morphBase[firstWid].tag == POSTag::p)
{
// prohibit <v> without <chunk>
goto continueFor;
}
float ll = cLmState.next(langMdl, firstWid);
candScore += ll;
if (!(curMorph->chunks.empty() || curMorph->complex || curMorph->saisiot))
{
for (size_t i = 1; i < curMorph->chunks.size(); ++i)
{
const auto wid = curMorph->chunks[i]->lmMorphemeId;
if (morphBase[wid].tag == POSTag::p)
{
// prohibit <v> without <chunk>
goto continueFor;
}
ll = cLmState.next(langMdl, wid);
candScore += ll;
}
}
}
if ((ruleBasedScorer.curMorphSbType || isQuote(ruleBasedScorer.curMorphSpecialType)) && prevPath.rootId == commonRootId)
{
rootIds.resize(prevSpStates.size());
iota(rootIds.begin(), rootIds.end(), 0);
}
else
{
rootIds.resize(1);
rootIds[0] = commonRootId;
}
for (auto rootId : rootIds)
{
const auto* prevMorpheme = &morphBase[prevPath.wid];
auto spState = prevPath.spState;
if (rootId != commonRootId)
{
spState = prevSpStates[rootId];
}
const float candScoreWithRule = candScore + ruleBasedScorer(prevMorpheme, spState);
// update special state
if (ruleBasedScorer.curMorphSpecialType == Kiwi::SpecialMorph::singleQuoteOpen) spState.singleQuote = 1;
else if (ruleBasedScorer.curMorphSpecialType == Kiwi::SpecialMorph::singleQuoteClose) spState.singleQuote = 0;
else if (ruleBasedScorer.curMorphSpecialType == Kiwi::SpecialMorph::doubleQuoteOpen) spState.doubleQuote = 1;
else if (ruleBasedScorer.curMorphSpecialType == Kiwi::SpecialMorph::doubleQuoteClose) spState.doubleQuote = 0;
if (ruleBasedScorer.curMorphSbType)
{
spState.bulletHash = hashSbTypeOrder(ruleBasedScorer.curMorphSbType, ruleBasedScorer.curMorphSbOrder + 1);
}
PathHash<LmState> ph{ cLmState, prevPath.rootId, spState };
bestPathCont.insert(ph, topN, rootId, curMorph, candScoreWithRule, prevPath.accTypoCost + node->typoCost, &prevPath, move(cLmState), spState);
}
continueFor:;
}
}
bestPathCont.writeTo(resultOut, curMorph, lastSeqId, ownFormId);
return;
}
template<class LmState, class CandTy>
void PathEvaluator::evalPath(const Kiwi* kw,
const KGraphNode* startNode,
const KGraphNode* node,
const size_t topN,
Vector<Vector<WordLL<LmState>>>& cache,
const Vector<U16StringView>& ownFormList,
size_t i,
size_t ownFormId,
CandTy&& cands,
bool unknownForm,
const Vector<SpecialState>& prevSpStates,
bool splitComplex,
bool splitSaisiot,
bool mergeSaisiot,
const std::unordered_set<const Morpheme*>* blocklist
)
{
const size_t langVocabSize = kw->langMdl.knlm->getHeader().vocab_size;
auto& nCache = cache[i];
Vector<WordLL<LmState>> refCache;
float whitespaceDiscount = 0;
if (node->uform.empty() && !node->form->form.empty() && node->spaceErrors)
{
whitespaceDiscount = -kw->spacePenalty * node->spaceErrors;
}
const float typoDiscount = -node->typoCost * kw->typoCostWeight;
float unknownFormDiscount = 0;
if (unknownForm)
{
size_t unknownLen = node->uform.empty() ? node->form->form.size() : node->uform.size();
unknownFormDiscount = -(unknownLen * kw->unkFormScoreScale + kw->unkFormScoreBias);
}
const float nodeLevelDiscount = whitespaceDiscount + typoDiscount + unknownFormDiscount;
size_t totalPrevPathes = 0;
for (auto* prev = node->getPrev(); prev; prev = prev->getSibling())
{
totalPrevPathes += cache[prev - startNode].size();
}
const bool useContainerForSmall = totalPrevPathes <= 48;
for (bool ignoreCond : {false, true})
{
for (auto& curMorph : cands)
{
if (splitComplex && curMorph->hasComplex()) continue;
if (blocklist && curMorph->hasMorpheme(*blocklist)) continue;
// 덧붙은 받침(zCoda)을 위한 지름길
if (curMorph->tag == POSTag::z_coda)
{
for (auto* prev = node->getPrev(); prev; prev = prev->getSibling())
{
for (auto& p : cache[prev - startNode])
{
auto lastTag = kw->morphemes[p.wid].tag;
if (!isJClass(lastTag) && !isEClass(lastTag)) continue;
nCache.emplace_back(p);
auto& newPath = nCache.back();
newPath.accScore += curMorph->userScore * kw->typoCostWeight;
newPath.accTypoCost -= curMorph->userScore;
newPath.parent = &p;
newPath.morpheme = &kw->morphemes[curMorph->lmMorphemeId];
newPath.wid = curMorph->lmMorphemeId;
}
}
continue;
}
// 사이시옷(zSiot)을 위한 지름길
if (curMorph->tag == POSTag::z_siot)
{
if (!(splitSaisiot || mergeSaisiot))
{
continue;
}
for (auto* prev = node->getPrev(); prev; prev = prev->getSibling())
{
for (auto& p : cache[prev - startNode])
{
auto lastTag = kw->morphemes[p.wid].tag;
if (!isNNClass(lastTag)) continue;
nCache.emplace_back(p);
auto& newPath = nCache.back();
newPath.accScore += curMorph->userScore * kw->typoCostWeight;
newPath.accTypoCost -= curMorph->userScore;
newPath.parent = &p;
newPath.morpheme = &kw->morphemes[curMorph->lmMorphemeId];
newPath.wid = curMorph->lmMorphemeId;
}
}
continue;
}
// if the morpheme has chunk set
if (!(curMorph->chunks.empty() || curMorph->complex || curMorph->saisiot))
{
// '하다/하게/하지'가 '다/게/지'로 축약된 경우인데 앞에 공백이 있는 경우는 탐색후보에서 제외
if (node->prev && node[-(int)node->prev].endPos < node->startPos
&& curMorph->kform
&& curMorph->kform->size() == 1
&& ((*curMorph->kform)[0] == u'다' || (*curMorph->kform)[0] == u'게' || (*curMorph->kform)[0] == u'지')
&& curMorph->chunks[0]->kform
&& curMorph->chunks[0]->kform->size() == 1
&& (*curMorph->chunks[0]->kform)[0] == u'하')
{
continue;
}
}
if (topN > 1)
{
evalSingleMorpheme<PathEvaluatingMode::topN>(nCache, kw, ownFormList, cache,
ownFormId, curMorph,
node, startNode, topN, ignoreCond ? -10 : 0, nodeLevelDiscount, prevSpStates);
}
else if (useContainerForSmall)
{
evalSingleMorpheme<PathEvaluatingMode::top1Small>(nCache, kw, ownFormList, cache,
ownFormId, curMorph,
node, startNode, topN, ignoreCond ? -10 : 0, nodeLevelDiscount, prevSpStates);
}
else
{
evalSingleMorpheme<PathEvaluatingMode::top1>(nCache, kw, ownFormList, cache,
ownFormId, curMorph,
node, startNode, topN, ignoreCond ? -10 : 0, nodeLevelDiscount, prevSpStates);
}
}
if (!nCache.empty()) break;
}
thread_local Vector<float> maxScores;
maxScores.clear();
maxScores.resize((1 + prevSpStates.size()) * topN, -INFINITY);
if (topN == 1)
{
for (auto& c : nCache)
{
if (c.morpheme->combineSocket) continue;
const auto rootId = c.rootId == commonRootId ? 0 : c.rootId + 1;
maxScores[rootId] = max(maxScores[rootId], c.accScore);
}
}
else
{
for (auto& c : nCache)
{
if (c.morpheme->combineSocket) continue;
const auto rootId = c.rootId == commonRootId ? 0 : c.rootId + 1;
if (c.accScore > maxScores[rootId * topN])
{
pop_heap(maxScores.begin() + rootId * topN, maxScores.begin() + (rootId + 1) * topN, greater<float>{});
maxScores[rootId * topN + topN - 1] = c.accScore;
push_heap(maxScores.begin() + rootId * topN, maxScores.begin() + (rootId + 1) * topN, greater<float>{});
}
}
}
size_t validCount = 0;
for (size_t i = 0; i < nCache.size(); ++i)
{
const auto rootId = nCache[i].rootId == commonRootId ? 0 : nCache[i].rootId + 1;
if (nCache[i].accScore + kw->cutOffThreshold < maxScores[rootId * topN]) continue;
if (validCount != i) nCache[validCount] = move(nCache[i]);
validCount++;
}
nCache.resize(validCount);
}