-
Notifications
You must be signed in to change notification settings - Fork 346
/
ParallelTopicModel.java
2082 lines (1661 loc) · 77 KB
/
ParallelTopicModel.java
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
/* Copyright (C) 2005 Univ. of Massachusetts Amherst, Computer Science Dept.
This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit).
http:https://www.cs.umass.edu/~mccallum/mallet
This software is provided under the terms of the Common Public License,
version 1.0, as published by http:https://www.opensource.org. For further
information, see the file `LICENSE' included with this distribution. */
package cc.mallet.topics;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Formatter;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.TreeSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import com.carrotsearch.hppc.ObjectIntHashMap;
import com.google.errorprone.annotations.Var;
import cc.mallet.types.Alphabet;
import cc.mallet.types.AugmentableFeatureVector;
import cc.mallet.types.Dirichlet;
import cc.mallet.types.FeatureSequence;
import cc.mallet.types.FeatureSequenceWithBigrams;
import cc.mallet.types.IDSorter;
import cc.mallet.types.Instance;
import cc.mallet.types.InstanceList;
import cc.mallet.types.LabelAlphabet;
import cc.mallet.types.LabelSequence;
import cc.mallet.types.MatrixOps;
import cc.mallet.types.RankedFeatureVector;
import cc.mallet.util.MalletLogger;
import cc.mallet.util.Randoms;
/**
* Simple parallel threaded implementation of LDA,
* following Newman, Asuncion, Smyth and Welling, Distributed Algorithms for Topic Models
* JMLR (2009), with SparseLDA sampling scheme and data structure from
* Yao, Mimno and McCallum, Efficient Methods for Topic Model Inference on Streaming Document Collections, KDD (2009).
*
* @author David Mimno, Andrew McCallum
*/
public class ParallelTopicModel implements Serializable {
public static final int UNASSIGNED_TOPIC = -1;
public static Logger logger = MalletLogger.getLogger(ParallelTopicModel.class.getName());
public ArrayList<TopicAssignment> data; // the training instances and their topic assignments
public Alphabet alphabet; // the alphabet for the input data
public LabelAlphabet topicAlphabet; // the alphabet for the topics
public int numTopics; // Number of topics to be fit
// These values are used to encode type/topic counts as
// count/topic pairs in a single int.
public int topicMask;
public int topicBits;
public int numTypes;
public long totalTokens;
public double[] alpha; // Dirichlet(alpha,alpha,...) is the distribution over topics
public double alphaSum;
public double beta; // Prior on per-topic multinomial distribution over words
public double betaSum;
public boolean usingSymmetricAlpha = false;
public static final double DEFAULT_BETA = 0.01;
public int[][] typeTopicCounts; // indexed by <feature index, topic index>
public int[] tokensPerTopic; // indexed by <topic index>
// for dirichlet estimation
public int[] docLengthCounts; // histogram of document sizes
public int[][] topicDocCounts; // histogram of document/topic counts, indexed by <topic index, sequence position index>
public int numIterations = 1000;
public int burninPeriod = 200;
public int saveSampleInterval = 10;
public int optimizeInterval = 50;
public int temperingInterval = 0;
public int showTopicsInterval = 50;
public int wordsPerTopic = 7;
public int saveStateInterval = 0;
public String stateFilename = null;
public int saveModelInterval = 0;
public String modelFilename = null;
public int randomSeed = -1;
public NumberFormat formatter;
public boolean printLogLikelihood = true;
// The number of times each type appears in the corpus
int[] typeTotals;
// The max over typeTotals, used for beta optimization
int maxTypeCount;
int numThreads = 1;
public ParallelTopicModel (int numberOfTopics) {
this (numberOfTopics, numberOfTopics, DEFAULT_BETA);
}
public ParallelTopicModel (int numberOfTopics, double alphaSum, double beta) {
this (newLabelAlphabet (numberOfTopics), alphaSum, beta);
}
private static LabelAlphabet newLabelAlphabet (int numTopics) {
LabelAlphabet ret = new LabelAlphabet();
for (int i = 0; i < numTopics; i++) {
ret.lookupIndex("topic"+i);
}
return ret;
}
public ParallelTopicModel (LabelAlphabet topicAlphabet, double alphaSum, double beta) {
this.data = new ArrayList<TopicAssignment>();
this.topicAlphabet = topicAlphabet;
this.alphaSum = alphaSum;
this.beta = beta;
setNumTopics(topicAlphabet.size());
formatter = NumberFormat.getInstance();
formatter.setMaximumFractionDigits(5);
logger.info("Mallet LDA: " + numTopics + " topics, " + topicBits + " topic bits, " +
Integer.toBinaryString(topicMask) + " topic mask");
}
public Alphabet getAlphabet() { return alphabet; }
public LabelAlphabet getTopicAlphabet() { return topicAlphabet; }
public int getNumTopics() { return numTopics; }
/** Set or reset the number of topics. This method will not change any token-topic assignments,
so it should only be used before initializing or restoring a previously saved state. */
public void setNumTopics(int numTopics) {
this.numTopics = numTopics;
if (Integer.bitCount(numTopics) == 1) {
// exact power of 2
topicMask = numTopics - 1;
topicBits = Integer.bitCount(topicMask);
}
else {
// otherwise add an extra bit
topicMask = Integer.highestOneBit(numTopics) * 2 - 1;
topicBits = Integer.bitCount(topicMask);
}
this.alpha = new double[numTopics];
Arrays.fill(alpha, alphaSum / numTopics);
tokensPerTopic = new int[numTopics];
}
public ArrayList<TopicAssignment> getData() { return data; }
public int[][] getTypeTopicCounts() { return typeTopicCounts; }
public int[] getTokensPerTopic() { return tokensPerTopic; }
public void setNumIterations (int numIterations) {
this.numIterations = numIterations;
}
public void setBurninPeriod (int burninPeriod) {
this.burninPeriod = burninPeriod;
}
public void setTopicDisplay(int interval, int n) {
this.showTopicsInterval = interval;
this.wordsPerTopic = n;
}
public void setRandomSeed(int seed) {
randomSeed = seed;
}
/** Interval for optimizing Dirichlet hyperparameters */
public void setOptimizeInterval(int interval) {
this.optimizeInterval = interval;
// Make sure we always have at least one sample
// before optimizing hyperparameters
if (saveSampleInterval > optimizeInterval) {
saveSampleInterval = optimizeInterval;
}
}
public void setSymmetricAlpha(boolean b) {
usingSymmetricAlpha = b;
}
public void setTemperingInterval(int interval) {
temperingInterval = interval;
}
public void setNumThreads(int threads) {
this.numThreads = threads;
}
/** Define how often and where to save a text representation of the current state.
* Files are GZipped.
*
* @param interval Save a copy of the state every <code>interval</code> iterations.
* @param filename Save the state to this file, with the iteration number as a suffix
*/
public void setSaveState(int interval, String filename) {
this.saveStateInterval = interval;
this.stateFilename = filename;
}
/** Define how often and where to save a serialized model.
*
* @param interval Save a serialized model every <code>interval</code> iterations.
* @param filename Save to this file, with the iteration number as a suffix
*/
public void setSaveSerializedModel(int interval, String filename) {
this.saveModelInterval = interval;
this.modelFilename = filename;
}
public void addInstances (InstanceList training) {
alphabet = training.getDataAlphabet();
numTypes = alphabet.size();
betaSum = beta * numTypes;
Randoms random;
if (randomSeed == -1) {
random = new Randoms();
}
else {
random = new Randoms(randomSeed);
}
for (Instance instance : training) {
FeatureSequence tokens = (FeatureSequence) instance.getData();
LabelSequence topicSequence =
new LabelSequence(topicAlphabet, new int[ tokens.size() ]);
int[] topics = topicSequence.getFeatures();
for (int position = 0; position < tokens.getLength(); position++) {
int topic = random.nextInt(numTopics);
topics[position] = topic;
}
TopicAssignment t = new TopicAssignment(instance, topicSequence);
data.add(t);
}
buildInitialTypeTopicCounts();
initializeHistograms();
}
public void initializeFromState(File stateFile) throws IOException {
@Var
String line;
@Var
String[] fields;
BufferedReader reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(stateFile))));
line = reader.readLine();
// Skip some lines starting with "#" that describe the format and specify hyperparameters
while (line.startsWith("#")) {
if (line.startsWith("#alpha : ")) {
line = line.replace("#alpha : ", "");
fields = line.split(" ");
setNumTopics(fields.length);
this.alphaSum = 0.0;
for (int topic = 0; topic < fields.length; topic++) {
this.alpha[topic] = Double.parseDouble(fields[topic]);
this.alphaSum += this.alpha[topic];
}
}
else if (line.startsWith("#beta : ")) {
line = line.replace("#beta : ", "");
this.beta = Double.parseDouble(line);
this.betaSum = beta * numTypes;
}
line = reader.readLine();
}
fields = line.split(" ");
for (TopicAssignment document: data) {
FeatureSequence tokens = (FeatureSequence) document.instance.getData();
FeatureSequence topicSequence = (FeatureSequence) document.topicSequence;
int[] topics = topicSequence.getFeatures();
for (int position = 0; position < tokens.size(); position++) {
int type = tokens.getIndexAtPosition(position);
if (type == Integer.parseInt(fields[3])) {
topics[position] = Integer.parseInt(fields[5]);
}
else {
System.err.println("instance list and state do not match: " + line);
throw new IllegalStateException();
}
line = reader.readLine();
if (line != null) {
fields = line.split(" ");
}
}
}
buildInitialTypeTopicCounts();
initializeHistograms();
}
public void buildInitialTypeTopicCounts () {
typeTopicCounts = new int[numTypes][];
tokensPerTopic = new int[numTopics];
// Get the total number of occurrences of each word type
//int[] typeTotals = new int[numTypes];
typeTotals = new int[numTypes];
// Create the type-topic counts data structure
for (TopicAssignment document : data) {
FeatureSequence tokens = (FeatureSequence) document.instance.getData();
for (int position = 0; position < tokens.getLength(); position++) {
int type = tokens.getIndexAtPosition(position);
typeTotals[ type ]++;
}
}
maxTypeCount = 0;
// Allocate enough space so that we never have to worry about
// overflows: either the number of topics or the number of times
// the type occurs.
for (int type = 0; type < numTypes; type++) {
if (typeTotals[type] > maxTypeCount) { maxTypeCount = typeTotals[type]; }
typeTopicCounts[type] = new int[ Math.min(numTopics, typeTotals[type]) ];
}
for (TopicAssignment document : data) {
FeatureSequence tokens = (FeatureSequence) document.instance.getData();
FeatureSequence topicSequence = (FeatureSequence) document.topicSequence;
int[] topics = topicSequence.getFeatures();
for (int position = 0; position < tokens.size(); position++) {
int topic = topics[position];
if (topic == UNASSIGNED_TOPIC) { continue; }
tokensPerTopic[topic]++;
// The format for these arrays is
// the topic in the rightmost bits
// the count in the remaining (left) bits.
// Since the count is in the high bits, sorting (desc)
// by the numeric value of the int guarantees that
// higher counts will be before the lower counts.
int type = tokens.getIndexAtPosition(position);
int[] currentTypeTopicCounts = typeTopicCounts[ type ];
// Start by assuming that the array is either empty
// or is in sorted (descending) order.
// Here we are only adding counts, so if we find
// an existing location with the topic, we only need
// to ensure that it is not larger than its left neighbor.
@Var
int index = 0;
@Var
int currentTopic = currentTypeTopicCounts[index] & topicMask;
@Var
int currentValue;
while (currentTypeTopicCounts[index] > 0 && currentTopic != topic) {
index++;
if (index == currentTypeTopicCounts.length) {
logger.info("overflow on type " + type + " for topic " + topic);
StringBuilder out = new StringBuilder();
for (int value: currentTypeTopicCounts) {
out.append(value + " ");
}
logger.info(out.toString());
}
currentTopic = currentTypeTopicCounts[index] & topicMask;
}
currentValue = currentTypeTopicCounts[index] >> topicBits;
if (currentValue == 0) {
// new value is 1, so we don't have to worry about sorting
// (except by topic suffix, which doesn't matter)
currentTypeTopicCounts[index] =
(1 << topicBits) + topic;
}
else {
currentTypeTopicCounts[index] =
((currentValue + 1) << topicBits) + topic;
// Now ensure that the array is still sorted by
// bubbling this value up.
while (index > 0 &&
currentTypeTopicCounts[index] > currentTypeTopicCounts[index - 1]) {
int temp = currentTypeTopicCounts[index];
currentTypeTopicCounts[index] = currentTypeTopicCounts[index - 1];
currentTypeTopicCounts[index - 1] = temp;
index--;
}
}
}
}
}
/**
* Gather statistics on the size of documents
* and create histograms for use in Dirichlet hyperparameter
* optimization.
*/
private void initializeHistograms() {
@Var
int maxTokens = 0;
totalTokens = 0;
@Var
int seqLen;
for (int doc = 0; doc < data.size(); doc++) {
FeatureSequence fs = (FeatureSequence) data.get(doc).instance.getData();
seqLen = fs.getLength();
if (seqLen > maxTokens)
maxTokens = seqLen;
totalTokens += seqLen;
}
logger.info("max tokens: " + maxTokens);
logger.info("total tokens: " + totalTokens);
docLengthCounts = new int[maxTokens + 1];
topicDocCounts = new int[numTopics][maxTokens + 1];
}
public void optimizeAlpha(WorkerCallable[] callables) {
// First clear the sufficient statistic histograms
Arrays.fill(docLengthCounts, 0);
for (int topic = 0; topic < topicDocCounts.length; topic++) {
Arrays.fill(topicDocCounts[topic], 0);
}
for (int thread = 0; thread < numThreads; thread++) {
int[] sourceLengthCounts = callables[thread].getDocLengthCounts();
int[][] sourceTopicCounts = callables[thread].getTopicDocCounts();
for (int count=0; count < sourceLengthCounts.length; count++) {
if (sourceLengthCounts[count] > 0) {
docLengthCounts[count] += sourceLengthCounts[count];
sourceLengthCounts[count] = 0;
}
}
for (int topic=0; topic < numTopics; topic++) {
if (! usingSymmetricAlpha) {
for (int count=0; count < sourceTopicCounts[topic].length; count++) {
if (sourceTopicCounts[topic][count] > 0) {
topicDocCounts[topic][count] += sourceTopicCounts[topic][count];
sourceTopicCounts[topic][count] = 0;
}
}
}
else {
// For the symmetric version, we only need one
// count array, which I'm putting in the same
// data structure, but for topic 0. All other
// topic histograms will be empty.
// I'm duplicating this for loop, which
// isn't the best thing, but it means only checking
// whether we are symmetric or not numTopics times,
// instead of numTopics * longest document length.
for (int count=0; count < sourceTopicCounts[topic].length; count++) {
if (sourceTopicCounts[topic][count] > 0) {
topicDocCounts[0][count] += sourceTopicCounts[topic][count];
// ^ the only change
sourceTopicCounts[topic][count] = 0;
}
}
}
}
}
if (usingSymmetricAlpha) {
alphaSum = Dirichlet.learnSymmetricConcentration(topicDocCounts[0],
docLengthCounts,
numTopics,
alphaSum);
for (int topic = 0; topic < numTopics; topic++) {
alpha[topic] = alphaSum / numTopics;
}
}
else {
try {
alphaSum = Dirichlet.learnParameters(alpha, topicDocCounts, docLengthCounts, 1.001, 1.0, 1);
} catch (RuntimeException e) {
// Dirichlet optimization has become unstable. This is known to happen for very small corpora (~5 docs).
logger.warning("Dirichlet optimization has become unstable. Resetting to alpha_t = 1.0.");
alphaSum = numTopics;
for (int topic = 0; topic < numTopics; topic++) {
alpha[topic] = 1.0;
}
}
}
}
public void temperAlpha(WorkerCallable[] callables) {
// First clear the sufficient statistic histograms
Arrays.fill(docLengthCounts, 0);
for (int topic = 0; topic < topicDocCounts.length; topic++) {
Arrays.fill(topicDocCounts[topic], 0);
}
for (int thread = 0; thread < numThreads; thread++) {
int[] sourceLengthCounts = callables[thread].getDocLengthCounts();
int[][] sourceTopicCounts = callables[thread].getTopicDocCounts();
for (int count=0; count < sourceLengthCounts.length; count++) {
if (sourceLengthCounts[count] > 0) {
sourceLengthCounts[count] = 0;
}
}
for (int topic=0; topic < numTopics; topic++) {
for (int count=0; count < sourceTopicCounts[topic].length; count++) {
if (sourceTopicCounts[topic][count] > 0) {
sourceTopicCounts[topic][count] = 0;
}
}
}
}
for (int topic = 0; topic < numTopics; topic++) {
alpha[topic] = 1.0;
}
alphaSum = numTopics;
}
public void optimizeBeta(WorkerCallable[] callables) {
// The histogram starts at count 0, so if all of the
// tokens of the most frequent type were assigned to one topic,
// we would need to store a maxTypeCount + 1 count.
int[] countHistogram = new int[maxTypeCount + 1];
// Now count the number of type/topic pairs that have
// each number of tokens.
@Var
int index;
for (int type = 0; type < numTypes; type++) {
int[] counts = typeTopicCounts[type];
index = 0;
while (index < counts.length &&
counts[index] > 0) {
int count = counts[index] >> topicBits;
countHistogram[count]++;
index++;
}
}
// Figure out how large we need to make the "observation lengths"
// histogram.
@Var
int maxTopicSize = 0;
for (int topic = 0; topic < numTopics; topic++) {
if (tokensPerTopic[topic] > maxTopicSize) {
maxTopicSize = tokensPerTopic[topic];
}
}
// Now allocate it and populate it.
int[] topicSizeHistogram = new int[maxTopicSize + 1];
for (int topic = 0; topic < numTopics; topic++) {
topicSizeHistogram[ tokensPerTopic[topic] ]++;
}
betaSum = Dirichlet.learnSymmetricConcentration(countHistogram,
topicSizeHistogram,
numTypes,
betaSum);
beta = betaSum / numTypes;
logger.info("[beta: " + formatter.format(beta) + "] ");
// Now publish the new value
for (int thread = 0; thread < numThreads; thread++) {
callables[thread].resetBeta(beta, betaSum);
}
}
public void estimate () throws IOException {
long startTime = System.currentTimeMillis();
WorkerCallable[] callables = new WorkerCallable[numThreads];
@Var
int docsPerThread = data.size() / numThreads;
@Var
int offset = 0;
if (numThreads > 1) {
for (int thread = 0; thread < numThreads; thread++) {
int[] callableTotals = new int[numTopics];
System.arraycopy(tokensPerTopic, 0, callableTotals, 0, numTopics);
int[][] callableCounts = new int[numTypes][];
for (int type = 0; type < numTypes; type++) {
int[] counts = new int[typeTopicCounts[type].length];
System.arraycopy(typeTopicCounts[type], 0, counts, 0, counts.length);
callableCounts[type] = counts;
}
// some docs may be missing at the end due to integer division
if (thread == numThreads - 1) {
docsPerThread = data.size() - offset;
}
Randoms random;
if (randomSeed == -1) {
random = new Randoms();
}
else {
random = new Randoms(randomSeed);
}
callables[thread] = new WorkerCallable(numTopics,
alpha, alphaSum, beta,
random, data,
callableCounts, callableTotals,
offset, docsPerThread);
callables[thread].initializeAlphaStatistics(docLengthCounts.length);
offset += docsPerThread;
}
}
else {
// If there is only one thread, copy the typeTopicCounts
// arrays directly, rather than allocating new memory.
Randoms random;
if (randomSeed == -1) {
random = new Randoms();
}
else {
random = new Randoms(randomSeed);
}
callables[0] = new WorkerCallable(numTopics,
alpha, alphaSum, beta,
random, data,
typeTopicCounts, tokensPerTopic,
offset, docsPerThread);
callables[0].initializeAlphaStatistics(docLengthCounts.length);
// If there is only one thread, we
// can avoid communications overhead.
// This switch informs the thread not to
// gather statistics for its portion of the data.
callables[0].makeOnlyThread();
}
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
for (int iteration = 1; iteration <= numIterations; iteration++) {
long iterationStart = System.currentTimeMillis();
if (showTopicsInterval != 0 && iteration != 0 && iteration % showTopicsInterval == 0) {
logger.info("\n" + displayTopWords (wordsPerTopic, false));
}
if (saveStateInterval != 0 && iteration % saveStateInterval == 0) {
this.printState(new File(stateFilename + '.' + iteration));
}
if (saveModelInterval != 0 && iteration % saveModelInterval == 0) {
this.write(new File(modelFilename + '.' + iteration));
}
if (numThreads > 1) {
// If this is a hyperparameter-optimizing iteration, ask the threads
// to save the information we need to make that calculation.
if (iteration > burninPeriod && optimizeInterval != 0 && iteration % saveSampleInterval == 0) {
for (int thread = 0; thread < numThreads; thread++) {
callables[thread].collectAlphaStatistics();
}
}
// The main sampling process.
@Var
int totalChanges = 0;
try {
List<Future<Integer>> futures = executor.invokeAll(Arrays.asList(callables));
for (Future<Integer> future: futures) {
totalChanges += future.get();
}
} catch (Exception e) {
e.printStackTrace();
}
//logger.info("changes: " + ((double) totalChanges / totalTokens));
//System.out.print("[" + (System.currentTimeMillis() - iterationStart) + "] ");
// Each thread has now become out of synch. Merge all the
// sampling statistics back together.
// Clear the type/topic counts
Arrays.fill(tokensPerTopic, 0);
for (int type = 0; type < numTypes; type++) {
int[] targetCounts = typeTopicCounts[type];
Arrays.fill(targetCounts, 0);
}
for (int thread = 0; thread < numThreads; thread++) {
// Handle the total-tokens-per-topic array
int[] sourceTotals = callables[thread].getTokensPerTopic();
for (int topic = 0; topic < numTopics; topic++) {
tokensPerTopic[topic] += sourceTotals[topic];
}
}
List mergeCallables = new ArrayList();
for (int thread = 0; thread < numThreads; thread++) {
mergeCallables.add(new MergeCallable(callables, typeTopicCounts, numTypes, numTopics, thread, topicMask, topicBits));
}
try {
List<Future<String>> futures = executor.invokeAll(mergeCallables);
for (Future<String> future: futures) {
future.get();
}
} catch (Exception e) {
e.printStackTrace();
}
//System.out.print("[" + (System.currentTimeMillis() - iterationStart) + "] ");
// Now that we have merged the sampling statistics, propagate
// them back out to the individual threads.
List copyCallables = new ArrayList();
for (int thread = 0; thread < numThreads; thread++) {
copyCallables.add(new CopyCallable(callables[thread], typeTopicCounts, tokensPerTopic));
}
try {
List<Future<String>> futures = executor.invokeAll(copyCallables);
for (Future<String> future: futures) {
future.get();
}
} catch (Exception e) {
e.printStackTrace();
}
}
else {
// The single-threaded version
if (iteration > burninPeriod && optimizeInterval != 0 &&
iteration % saveSampleInterval == 0) {
callables[0].collectAlphaStatistics();
}
try {
callables[0].call();
} catch (Exception e) {
e.printStackTrace();
}
}
long elapsedMillis = System.currentTimeMillis() - iterationStart;
if (elapsedMillis < 1000) {
logger.fine(elapsedMillis + "ms ");
}
else {
logger.fine((elapsedMillis/1000) + "s ");
}
if (iteration > burninPeriod && optimizeInterval != 0 &&
iteration % optimizeInterval == 0) {
optimizeAlpha(callables);
optimizeBeta(callables);
logger.fine("[O " + (System.currentTimeMillis() - iterationStart) + "] ");
}
if (iteration % 10 == 0) {
if (printLogLikelihood) {
logger.info ("<" + iteration + "> LL/token: " + formatter.format(modelLogLikelihood() / totalTokens));
}
else {
logger.info ("<" + iteration + ">");
}
}
}
executor.shutdownNow();
@Var
long seconds = Math.round((System.currentTimeMillis() - startTime)/1000.0);
@Var
long minutes = seconds / 60; seconds %= 60;
@Var
long hours = minutes / 60; minutes %= 60;
@Var
long days = hours / 24; hours %= 24;
StringBuilder timeReport = new StringBuilder();
timeReport.append("\nTotal time: ");
if (days != 0) { timeReport.append(days); timeReport.append(" days "); }
if (hours != 0) { timeReport.append(hours); timeReport.append(" hours "); }
if (minutes != 0) { timeReport.append(minutes); timeReport.append(" minutes "); }
timeReport.append(seconds); timeReport.append(" seconds");
logger.info(timeReport.toString());
}
/** This method implements iterated conditional modes, which is equivalent to Gibbs sampling,
* but replacing sampling from the conditional distribution with taking the maximum
* topic. It tends to converge within a small number of iterations for models that have
* reached a good state through Gibbs sampling. */
public void maximize(int iterations) {
@Var
int iteration = 0;
@Var
int totalChange = Integer.MAX_VALUE;
double[] topicCoefficients = new double[numTopics];
@Var
int currentTopic;
@Var
int currentValue;
while (iteration < iterations && totalChange > 0) {
long iterationStart = System.currentTimeMillis();
totalChange = 0;
// Loop over every document in the corpus
for (int doc = 0; doc < data.size(); doc++) {
FeatureSequence tokenSequence =
(FeatureSequence) data.get(doc).instance.getData();
LabelSequence topicSequence =
(LabelSequence) data.get(doc).topicSequence;
int[] oneDocTopics = topicSequence.getFeatures();
@Var
int[] currentTypeTopicCounts;
@Var
int type;
@Var
int oldTopic;
@Var
int newTopic;
int docLength = tokenSequence.getLength();
int[] localTopicCounts = new int[numTopics];
//populate topic counts
for (int position = 0; position < docLength; position++) {
localTopicCounts[oneDocTopics[position]]++;
}
@Var
int globalMaxTopic = 0;
@Var
double globalMaxScore = 0.0;
for (int topic = 0; topic < numTopics; topic++) {
topicCoefficients[topic] = (alpha[topic] + localTopicCounts[topic]) / (betaSum + tokensPerTopic[topic]);
if (beta * topicCoefficients[topic] > globalMaxScore) {
globalMaxTopic = topic;
globalMaxScore = beta * topicCoefficients[topic];
}
}
@Var
double score;
@Var
double maxScore;
double[] topicTermScores = new double[numTopics];
//Iterate over the positions (words) in the document
for (int position = 0; position < docLength; position++) {
type = tokenSequence.getIndexAtPosition(position);
oldTopic = oneDocTopics[position];
// Grab the relevant row from our two-dimensional array
currentTypeTopicCounts = typeTopicCounts[type];
//Remove this token from all counts.
localTopicCounts[oldTopic]--;
tokensPerTopic[oldTopic]--;
// Recalculate the word-invariant part
topicCoefficients[oldTopic] = (alpha[oldTopic] + localTopicCounts[oldTopic]) / (betaSum + tokensPerTopic[oldTopic]);
// If the topic we just decremented was the previous max topic, search
// for a new max topic.
if (oldTopic == globalMaxTopic) {
globalMaxScore = beta * topicCoefficients[oldTopic];
for (int topic = 0; topic < numTopics; topic++) {
if (beta * topicCoefficients[topic] > globalMaxScore) {
globalMaxTopic = topic;
globalMaxScore = beta * topicCoefficients[topic];
}
}
}
newTopic = globalMaxTopic;
maxScore = globalMaxScore;
assert(tokensPerTopic[oldTopic] >= 0) : "old Topic " + oldTopic + " below 0";
@Var
int index = 0;
@Var
boolean alreadyDecremented = false;
while (index < currentTypeTopicCounts.length &&
currentTypeTopicCounts[index] > 0) {
currentTopic = currentTypeTopicCounts[index] & topicMask;
currentValue = currentTypeTopicCounts[index] >> topicBits;
if (! alreadyDecremented && currentTopic == oldTopic) {
// We're decrementing and adding up the
// sampling weights at the same time, but
// decrementing may require us to reorder
// the topics, so after we're done here,
// look at this cell in the array again.
currentValue --;
if (currentValue == 0) {
currentTypeTopicCounts[index] = 0;
}