-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLM.cpp
More file actions
1592 lines (1505 loc) · 41.7 KB
/
LM.cpp
File metadata and controls
1592 lines (1505 loc) · 41.7 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
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
/*
* LM.cc --
* Generic LM methods
*
*/
#pragma once
#include "stdafx.h"
#ifndef lint
static char LM_Copyright[] = "Copyright (c) 1995-2012 SRI International, 2012 Microsoft Corp. All Rights Reserved.";
static char LM_RcsId[] = "@(#)$Header: /home/srilm/CVS/srilm/lm/src/LM.cc,v 1.91 2012/10/29 17:25:03 mcintyre Exp $";
#endif
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <assert.h>
//#include "TLSWrapper.h"
//#include "tserror.h"
//#include "NgramStats.cpp"
#if !defined(_MSC_VER) && !defined(WIN32)
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <sys/wait.h>
#define SOCKET_ERROR_STRING ts_strerror(errno)
#define closesocket(s) close(s) // MS compatibility
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
typedef int SOCKET;
#if __INTEL_COMPILER == 700
// old Intel compiler cannot deal with optimized byteswapping functions
#undef htons
#undef ntohs
#endif
#ifdef NEED_SOCKLEN_T
typedef int socklen_t;
#endif
#else /* native MSWindows */
#include <winsock.h>
#ifdef _MSC_VER
#pragma comment(lib, "wsock32.lib")
#endif
typedef int socklen_t;
WSADATA wsaData;
int wsaInitialized = 0;
const int REMOTELM_MAXREQUESTLEN = 100;
/*
* Windows equivalent of strerror()
*/
const char *
WSA_strerror(int errCode)
{
char *errMsg;
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM, 0,
errCode, 0, (LPWSTR)&errMsg, 0, 0) == 0)
{
return "unknown error";
} else {
// This leaks some memory, but we don't care since code typically exits after error
return errMsg;
}
}
#define SOCKET_ERROR_STRING WSA_strerror(WSAGetLastError())
#endif /* !_MSC_VER && !WIN32 */
#ifdef NEED_RAND48
extern "C" {
double drand48();
}
#endif
#include "LM.h"
//#include "RemoteLM.h"
//#include "NgramStats.h"
//#include "NBest.h"
#include "Array.cpp"
#include <stdlib.h>
/*
* Debugging levels used in this file
*/
#define DEBUG_PRINT_DOC_PROBS 0
#define DEBUG_PRINT_SENT_PROBS 1
#define DEBUG_PRINT_WORD_PROBS 2
#define DEBUG_PRINT_PROB_SUMS 3
#define DEBUG_PRINT_PROB_RANKS 4
const char *defaultStateTag = "<LMstate>";
char ctsBuffer[100]; /* used by countToString() */
unsigned LM::initialDebugLevel = 0;
/*
* Initialization
* The LM is created with a reference to a Vocab, so various
* LMs and other objects can share one Vocab. The LM will typically
* add words to the Vocab as needed.
*/
LM::LM(Vocab &vocab)
: vocab(vocab), noiseVocab(vocab)
{
_running = false;
reverseWords = false;
addSentStart = true;
addSentEnd = true;
stateTag = defaultStateTag;
writeInBinary = false;
debugme(initialDebugLevel);
}
LM::~LM()
{
}
/*
* Contextual word probabilities from strings
* The default method for word strings looks up the word indices
* for both the word and its context and gets its probabilities
* from the LM.
*/
LogP
LM::wordProb(VocabString word, const VocabString *context)
{
unsigned int len = vocab.length(context);
makeArray(VocabIndex, cids, len + 1);
if (addUnkWords()) {
vocab.addWords(context, cids, len + 1);
} else {
vocab.getIndices(context, cids, len + 1, vocab.unkIndex());
}
LogP prob = wordProb(vocab.getIndex(word, vocab.unkIndex()), cids);
return prob;
}
/* Word probability with cached context
* Recomputes the conditional probability of a word using a context
* that is guaranteed to be identical to the last call to wordProb.
* This implementation compute prob from scratch, but the idea is that
* other language models use caches that depend on the context.
*/
LogP
LM::wordProbRecompute(VocabIndex word, const VocabIndex *context)
{
return wordProb(word, context);
}
/*
* Check if LM needs to add unknown words to vocabulary implicitly
*/
Boolean
LM::addUnkWords()
{
return false;
}
/*
* Non-word testing
* Returns true for pseudo-word tokens that don't correspond to
* observable events (e.g., context tags or hidden events).
*/
Boolean
LM::isNonWord(VocabIndex word)
{
return vocab.isNonEvent(word);
}
/*
* Update the ranking statistics
*/
//void
//LM::updateRanks(LogP logp, const VocabIndex *context,
// FloatCount &r1, FloatCount &r5, FloatCount &r10,
// FloatCount weight)
//{
// unsigned rank = 0;
// unsigned eq = 0;
//
// Prob prob = LogPtoProb(logp);
//
// /*
// * prob summing interrupts sequential processing mode
// */
// Boolean wasRunning = running(false);
//
// VocabIter iter(vocab);
// VocabIndex wid;
// Boolean first = true;
//
// while (iter.next(wid)) {
// if (!isNonWord(wid)) {
// Prob p = LogPtoProb(first ?
// wordProb(wid, context) :
// wordProbRecompute(wid, context));
//
// if (fabs(p - prob) < Prob_Epsilon) {
// eq ++;
// } else if (p > prob) {
// rank ++;
// }
//
// first = false;
//
// if (rank+eq/2 > 10) // NOTE: this depends on max rank being counted
// break;
// }
// }
//
// rank = rank+eq/2;
//
// if (rank < 10) {
// r10 += weight;
// if (rank < 5) {
// r5 += weight;
// if (rank < 1) {
// r1 += weight;
// }
// }
// }
//
// running(wasRunning);
//}
/*
* Total probabilites
* For debugging purposes, compute the sum of all word probs
* in a context.
*/
Prob
LM::wordProbSum(const VocabIndex *context)
{
Prob total = 0.0;
VocabIter iter(vocab);
VocabIndex wid;
Boolean first = true;
/*
* prob summing interrupts sequential processing mode
*/
Boolean wasRunning = running(false);
while (iter.next(wid)) {
if (!isNonWord(wid)) {
total += LogPtoProb(first ?
wordProb(wid, context) :
wordProbRecompute(wid, context));
first = false;
}
}
running(wasRunning);
return total;
}
/*
* Sentence probabilities from strings
* The default method for sentences of word strings is to translate
* them to word index sequences and get its probability from the LM.
*/
//LogP
//LM::sentenceProb(const VocabString *sentence, TextStats &stats)
//{
// unsigned int len = vocab.length(sentence);
// makeArray(VocabIndex, wids, len + 1);
//
// if (addUnkWords()) {
// vocab.addWords(sentence, wids, len + 1);
// } else {
// vocab.getIndices(sentence, wids, len + 1, vocab.unkIndex());
// }
//
// LogP prob = sentenceProb(wids, stats);
//
// return prob;
//}
/*
* Convenience function that reverses a sentence (for wordProb computation),
* adds begin/end sentence tokens, and removes pause tokens.
* It returns the number of words excluding these special tokens.
*/
unsigned
LM::prepareSentence(const VocabIndex *sentence, VocabIndex *reversed,
unsigned len)
{
unsigned i, j = 0;
/*
* Add </s> token if not already there.
*/
if (len == 0 || sentence[reverseWords ? 0 : len - 1] != vocab.seIndex()) {
if (addSentEnd) {
reversed[j++] = vocab.seIndex();
}
}
for (i = 1; i <= len; i++) {
VocabIndex word = sentence[reverseWords ? i - 1 : len - i];
if (word == vocab.pauseIndex() || noiseVocab.getWord(word)) {
continue;
}
reversed[j++] = word;
}
/*
* Add <s> token if not already there
*/
if (len == 0 || sentence[reverseWords ? len - 1 : 0] != vocab.ssIndex()) {
if (addSentStart) {
reversed[j++] = vocab.ssIndex();
} else {
reversed[j++] = Vocab_None;
}
}
reversed[j] = Vocab_None;
return j - 2;
}
/*
* Convenience functions that strips noise and pause tags from a words string
*/
//VocabIndex *
//LM::removeNoise(VocabIndex *words)
//{
// unsigned from, to;
//
// for (from = 0, to = 0; words[from] != Vocab_None; from ++) {
// if (words[from] != vocab.pauseIndex() &&
// !noiseVocab.getWord(words[from]))
// {
// words[to++] = words[from];
// }
// }
// words[to] = Vocab_None;
//
// return words;
//}
/*
* Sentence probabilities from indices
* The default method is to accumulate the contextual word
* probabilities including that of the sentence end.
*/
//LogP
//LM::sentenceProb(const VocabIndex *sentence, TextStats &stats)
//{
// TextStats myStats;
//
// unsigned int len = vocab.length(sentence);
// makeArray(VocabIndex, reversed, len + 2 + 1);
// unsigned int i;
//
// /*
// * Indicate to lm methods that we're in sequential processing
// * mode.
// */
// Boolean wasRunning = running(true);
//
// /*
// * Contexts are represented most-recent-word-first.
// * Also, we have to prepend the sentence-begin token,
// * and append the sentence-end token.
// */
// len = prepareSentence(sentence, reversed, len);
//
// /*
// * Prefetch ngrams if desired
// */
// unsigned prefetching = prefetchingNgrams();
// if (prefetching > 0) {
// NgramStats ngrams(vocab, prefetching);
//
// Vocab::reverse(reversed);
//
// /*
// * Extract ngrams corresponding to maximal word contexts
// */
// for (unsigned i = 0; reversed[i] != Vocab_None; i++) {
// unsigned minNgramLen;
//
// if (i == 0) minNgramLen = 1;
// else if (len - i < prefetching) minNgramLen = len - i;
// else minNgramLen = prefetching;
//
// ngrams.incrementCounts(reversed + i, minNgramLen);
// }
//
// prefetchNgrams(ngrams);
//
// Vocab::reverse(reversed);
// }
//
// for (i = len; (int)i >= 0; i--) {
// LogP probSum;
//
// if (debug(DEBUG_PRINT_WORD_PROBS)) {
// dout() << "\tp( " << vocab.getWord(reversed[i]) << " | "
// << (reversed[i+1] != Vocab_None ?
// vocab.getWord(reversed[i+1]) : "")
// << (i < len ? " ..." : " ") << ") \t= " ;
//
// if (debug(DEBUG_PRINT_PROB_SUMS) &&
// !debug(DEBUG_PRINT_PROB_RANKS))
// {
// /*
// * XXX: because wordProb can change the state of the LM
// * we need to compute wordProbSum first.
// */
// probSum = wordProbSum(&reversed[i + 1]);
// }
// }
//
// LogP prob = wordProb(reversed[i], &reversed[i + 1]);
//
// if (debug(DEBUG_PRINT_PROB_RANKS)) {
// if (reversed[i] != vocab.seIndex()) {
// // exclude end of sentence marker
// updateRanks(prob, &reversed[i + 1],
// myStats.r1, myStats.r5, myStats.r10);
// } else {
// updateRanks(prob, &reversed[i + 1],
// myStats.r1se, myStats.r5se, myStats.r10se);
// }
//
// myStats.rTotal += 1;
// }
//
// if (debug(DEBUG_PRINT_WORD_PROBS)) {
// dout() << " " << LogPtoProb(prob) << " [ " << prob << " ]";
// if (debug(DEBUG_PRINT_PROB_SUMS) && !debug(DEBUG_PRINT_PROB_RANKS)) {
// dout() << " / " << probSum;
// if (fabs(probSum - 1.0) > 0.0001) {
// cerr << "\nwarning: word probs for this context sum to "
// << probSum << " != 1 : "
// << (vocab.use(), &reversed[i + 1]) << endl;
// }
// }
// dout() << endl;
// }
//
// /*
// * If the probability returned is zero but the
// * word in question is <unk> we assume this is closed-vocab
// * model and count it as an OOV. (This allows open-vocab
// * models to return regular probabilties for <unk>.)
// * If this happens and the word is not <unk> then we are
// * dealing with a broken language model that return
// * zero probabilities for known words, and we count them
// * as a "zeroProb".
// */
// if (prob == LogP_Zero) {
// if (reversed[i] == vocab.unkIndex()) {
// myStats.numOOVs ++;
// } else {
// myStats.zeroProbs ++;
//
// myStats.posQuadLoss += 1.0;
// myStats.posAbsLoss += 1.0;
// }
// } else {
// myStats.prob += prob;
//
// Prob loss = 1.0 - LogPtoProb(prob);
// if (loss < 0.0) loss = 0.0;
// myStats.posQuadLoss += loss*loss;
// myStats.posAbsLoss += loss;
// }
// }
//
// running(wasRunning);
//
// /*
// * Update stats with this sentence
// */
// if (reversed[0] == vocab.seIndex()) {
// myStats.numSentences = 1;
// myStats.numWords += len;
// } else {
// myStats.numWords += len + 1;
// }
//
// stats.increment(myStats);
//
// return myStats.prob;
//}
/*
* Compute joint probability of a word context (a reversed word sequence)
*/
LogP
LM::contextProb(const VocabIndex *context, unsigned clength)
{
unsigned useLength = Vocab::length(context);
LogP jointProb = LogP_One;
if (clength < useLength) {
useLength = clength;
}
/*
* If the context is empty there is nothing left to do: return LogP_One
*/
if (useLength > 0) {
/*
* Turn off debugging for contextProb computation
*/
Boolean wasRunning = running(false);
TruncatedContext usedContext(context, useLength);
/*
* Accumulate conditional probs for all words in used context
*/
for (unsigned i = useLength; i > 0; i--) {
VocabIndex word = usedContext[i - 1];
/*
* If we're computing the marginal probability of the unigram
* <s> context we have to look up </s> instead since the former
* has prob = 0.
*/
if (i == useLength && word == vocab.ssIndex()) {
word = vocab.seIndex();
}
LogP wprob = wordProb(word, &usedContext[i]);
/*
* If word is a non-event it has probability zero in the model,
* so the best we can do is to skip it.
* Note that above mapping turns <s> into a non-non-event, so
* it will be included.
*/
if (wprob != LogP_Zero || !vocab.isNonEvent(word)) {
jointProb += wprob;
}
}
running(wasRunning);
}
return jointProb;
}
/*
* Compute an aggregate log probability, perplexity, etc., much like
* sentenceProb, except that it uses counts instead of actual
* sentences.
*/
//template <class CountT>
//LogP
//LM::countsProb(NgramCounts<CountT> &counts, TextStats &stats,
// unsigned countorder, Boolean entropy)
//{
// unsigned prefetching = prefetchingNgrams();
// if (prefetching > 0) {
// prefetchNgrams(counts);
// }
//
// makeArray(VocabIndex, ngram, countorder + 1);
//
// LogP totalProb = 0.0;
//
// /*
// * Indicate to lm methods that we're in sequential processing
// * mode.
// */
// Boolean wasRunning = running(true);
//
// /*
// * Enumerate all counts up to the order indicated
// */
// for (unsigned i = 1; i <= countorder; i++ ) {
// // use sorted enumeration in debug mode only
// NgramCountsIter<CountT> ngramIter(counts, ngram, i,
// !debug(DEBUG_PRINT_WORD_PROBS) ? 0 :
// vocab.compareIndex());
//
// CountT *count;
//
// /*
// * This enumerates all ngrams of the given order
// */
// while ((count = ngramIter.next())) {
// TextStats ngramStats;
//
// /*
// * Skip zero counts since they don't contribute anything to
// * the probability
// */
// if (*count == 0) {
// continue;
// }
//
// /*
// * reverse ngram for lookup
// */
// Vocab::reverse(ngram);
//
// /*
// * The rest of this loop is patterned after LM::sentenceProb()
// */
//
// if (debug(DEBUG_PRINT_WORD_PROBS)) {
// dout() << "\tp( " << vocab.getWord(ngram[0]) << " | "
// << (vocab.use(), &ngram[1])
// << " ) \t= " ;
// }
// LogP prob = wordProb(ngram[0], &ngram[1]);
//
// LogP jointProb = !entropy ? LogP_One :
// contextProb(ngram, countorder);
// Prob weight = *count * LogPtoProb(jointProb);
//
// if (debug(DEBUG_PRINT_WORD_PROBS)) {
// dout() << " " << LogPtoProb(prob) << " [ " << prob;
//
// /*
// * Include ngram count if not unity, so we can compute the
// * aggregate log probability from the output
// */
// if (weight != 1.0) {
// dout() << " *" << weight;
// }
// dout() << " ]";
//
// if (debug(DEBUG_PRINT_PROB_RANKS)) {
// if (ngram[0] != vocab.seIndex()) {
// // exclude end of sentence marker
// updateRanks(prob, &ngram[1],
// ngramStats.r1, ngramStats.r5, ngramStats.r10, *count);
// } else {
// updateRanks(prob, &ngram[1],
// ngramStats.r1se, ngramStats.r5se, ngramStats.r10se, *count);
// }
//
// ngramStats.rTotal = *count;
// }
//
// if (debug(DEBUG_PRINT_PROB_SUMS) && !debug(DEBUG_PRINT_PROB_RANKS)) {
// Prob probSum = wordProbSum(&ngram[1]);
// dout() << " / " << probSum;
// if (fabs(probSum - 1.0) > 0.0001) {
// cerr << "\nwarning: word probs for this context sum to "
// << probSum << " != 1 : "
// << (vocab.use(), &ngram[1]) << endl;
// }
// }
// dout() << endl;
// }
//
// /*
// * ngrams ending in </s> are counted as sentences, all others
// * as words. This keeps the output compatible with that of
// * LM::pplFile().
// */
// if (ngram[0] == vocab.seIndex()) {
// ngramStats.numSentences = *count;
// } else {
// ngramStats.numWords = *count;
// }
//
// /*
// * If the probability returned is zero but the
// * word in question is <unk> we assume this is closed-vocab
// * model and count it as an OOV. (This allows open-vocab
// * models to return regular probabilties for <unk>.)
// * If this happens and the word is not <unk> then we are
// * dealing with a broken language model that return
// * zero probabilities for known words, and we count them
// * as a "zeroProb".
// */
// if (prob == LogP_Zero) {
// if (ngram[0] == vocab.unkIndex()) {
// ngramStats.numOOVs = *count;
// } else {
// ngramStats.zeroProbs = *count;
//
// ngramStats.posQuadLoss = 1.0 * *count;
// ngramStats.posAbsLoss = 1.0 * *count;
// }
// } else {
// totalProb +=
// (ngramStats.prob = weight * prob);
//
// Prob loss = 1.0 - LogPtoProb(prob);
// if (loss < 0.0) loss = 0.0;
// ngramStats.posQuadLoss = loss*loss * *count;
// ngramStats.posAbsLoss = loss * *count;
// }
//
// stats.increment(ngramStats);
//
// Vocab::reverse(ngram);
// }
// }
//
// running(wasRunning);
//
// /*
// * If computing entropy set total number of events to 1 so that
// * ppl computation reflects entropy.
// */
// if (entropy) {
// stats.numSentences = 0;
// stats.numWords = 1;
// }
//
// return totalProb;
//}
///*
// * instantiate countsProb() for count types used
// */
//template LogP
//LM::countsProb(NgramCounts<Count> &counts, TextStats &stats,
// unsigned order, Boolean entropy);
//#ifdef USE_XCOUNTS
//template LogP
//LM::countsProb(NgramCounts<NgramCount> &counts, TextStats &stats,
// unsigned order, Boolean entropy);
//#endif
//template LogP
//LM::countsProb(NgramCounts<FloatCount> &counts, TextStats &stats,
// unsigned order, Boolean entropy);
/*
* Perplexity from counts
* The escapeString is an optional line prefix that marks information
* that should be passed through unchanged. This is useful in
* constructing rescoring filters that feed hypothesis strings to
* pplCountsFile(), but also need to pass other information to downstream
* processing.
* If the entropy flag is true, the count log probabilities will be
* weighted by the joint probabilities on the ngrams. I.e., the
* output will be p(w,h) log p(pw|h) for each ngram, and the overall
* result will be the entropy of the conditional N-gram distribution.
*/
//template <class CountT>
//CountT
//LM::pplCountsFile(File &file, unsigned order, TextStats &stats,
// const char *escapeString, Boolean entropy,
// NgramCounts<CountT> *counts)
//{
// char *line;
// unsigned escapeLen = escapeString ? strlen(escapeString) : 0;
// unsigned stateTagLen = stateTag ? strlen(stateTag) : 0;
//
// VocabString words[maxNgramOrder + 1];
// makeArray(VocabIndex, wids, order + 1);
// TextStats sentenceStats;
// Boolean haveData = false;
// Boolean useCounts = (counts != 0);
//
// if (!useCounts) {
// counts = new NgramCounts<CountT>(vocab, order);
// assert(counts != 0);
// }
//
// while ((line = file.getline())) {
//
// if (escapeString && strncmp(line, escapeString, escapeLen) == 0) {
// /*
// * Output sentence-level statistics before each escaped line
// */
// if (haveData) {
// countsProb(*counts, sentenceStats, order, entropy);
//
// if (debug(DEBUG_PRINT_SENT_PROBS)) {
// dout() << sentenceStats << endl;
// }
//
// stats.increment(sentenceStats);
// sentenceStats.reset();
//
// if (useCounts) {
// counts->clear();
// } else {
// delete counts;
// counts = new NgramCounts<CountT>(vocab, order);
// assert(counts != 0);
// }
// haveData = false;
// }
//
// dout() << line;
//
// continue;
// }
//
// /*
// * check for directives to change the global LM state
// */
// if (stateTag && strncmp(line, stateTag, stateTagLen) == 0) {
// /*
// * pass the state info the lm to let it do whatever
// * it wants with it
// */
// setState(&line[stateTagLen]);
// continue;
// }
//
// CountT count;
// unsigned howmany =
// counts->parseNgram(line, words, maxNgramOrder + 1, count);
//
// /*
// * Skip this entry if the length of the ngram exceeds our
// * maximum order
// */
// if (howmany == 0) {
// file.position() << "malformed N-gram count or more than "
// << maxNgramOrder << " words per line\n";
// continue;
// } else if (howmany > order) {
// continue;
// }
//
// /*
// * Map words to indices
// */
// if (addUnkWords()) {
// vocab.addWords(words, wids, order + 1);
// } else {
// vocab.getIndices(words, wids, order + 1, vocab.unkIndex());
// }
//
// /*
// * Update the counts
// */
// *counts->insertCount(wids) += count;
//
// haveData = true;
// }
//
// /*
// * Output and update final sentence-level statistics
// */
// if (haveData) {
// countsProb(*counts, sentenceStats, order, entropy);
//
// if (debug(DEBUG_PRINT_SENT_PROBS)) {
// dout() << sentenceStats << endl;
// }
//
// stats.increment(sentenceStats);
// }
//
// if (!useCounts) {
// delete counts;
// }
//
// return (CountT)stats.numWords;
//}
///*
// * instantiate pplCountsFile() for count types used
// */
//template Count
//LM::pplCountsFile(File &file, unsigned order, TextStats &stats,
// const char *escapeString, Boolean entropy,
// NgramCounts<Count> *counts);
//#ifdef USE_XCOUNTS
//template NgramCount
//LM::pplCountsFile(File &file, unsigned order, TextStats &stats,
// const char *escapeString, Boolean entropy,
// NgramCounts<NgramCount> *counts);
//#endif
//template FloatCount
//LM::pplCountsFile(File &file, unsigned order, TextStats &stats,
// const char *escapeString, Boolean entropy,
// NgramCounts<FloatCount> *counts);
/*
* Perplexity from text
* The escapeString is an optional line prefix that marks information
* that should be passed through unchanged. This is useful in
* constructing rescoring filters that feed hypothesis strings to
* pplFile(), but also need to pass other information to downstream
* processing.
*/
//unsigned int
//LM::pplFile(File &file, TextStats &stats, const char *escapeString)
//{
// char *line;
// unsigned escapeLen = escapeString ? strlen(escapeString) : 0;
// unsigned stateTagLen = stateTag ? strlen(stateTag) : 0;
// VocabString sentence[maxWordsPerLine + 1];
// unsigned totalWords = 0;
// unsigned sentNo = 0;
// TextStats documentStats;
// Boolean printDocumentStats = false;
//
// while ((line = file.getline())) {
//
// if (escapeString && strncmp(line, escapeString, escapeLen) == 0) {
// if (sentNo > 0 && debuglevel() == DEBUG_PRINT_DOC_PROBS) {
// dout() << documentStats << endl;
// documentStats.reset();
// printDocumentStats = true;
// }
// dout() << line;
// continue;
// }
//
// /*
// * check for directives to change the global LM state
// */
// if (stateTag && strncmp(line, stateTag, stateTagLen) == 0) {
// /*
// * pass the state info the lm to let it do whatever
// * it wants with it
// */
// setState(&line[stateTagLen]);
// continue;
// }
//
// sentNo ++;
//
// unsigned int numWords =
// vocab.parseWords(line, sentence, maxWordsPerLine + 1);
//
// if (numWords == maxWordsPerLine + 1) {
// file.position() << "too many words per sentence\n";
// } else {
// TextStats sentenceStats;
//
// if (debug(DEBUG_PRINT_SENT_PROBS)) {
// dout() << sentence << endl;
// }
// LogP prob = sentenceProb(sentence, sentenceStats);
//
// totalWords += numWords;
//
// if (debug(DEBUG_PRINT_SENT_PROBS)) {
// dout() << sentenceStats << endl;
// }
//
// stats.increment(sentenceStats);
// documentStats.increment(sentenceStats);
// }
// }
//
// if (printDocumentStats) {
// dout() << documentStats << endl;
// }
//
// return totalWords;
//}
//unsigned
//LM::rescoreFile(File &file, double lmScale, double wtScale,
// LM &oldLM, double oldLmScale, double oldWtScale,
// const char *escapeString)
//{
// char *line;
// unsigned escapeLen = escapeString ? strlen(escapeString) : 0;
// unsigned stateTagLen = stateTag ? strlen(stateTag) : 0;
// unsigned sentNo = 0;
//
// while ((line = file.getline())) {
//
// if (escapeString && strncmp(line, escapeString, escapeLen) == 0) {
// fputs(line, stdout);
// continue;
// }
//
// /*
// * check for directives to change the global LM state
// */
// if (stateTag && strncmp(line, stateTag, stateTagLen) == 0) {
// /*
// * pass the state info the lm to let let if do whatever
// * it wants with it