forked from dotnet/machinelearning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataViewUtils.cs
More file actions
1377 lines (1230 loc) · 61.5 KB
/
Copy pathDataViewUtils.cs
File metadata and controls
1377 lines (1230 loc) · 61.5 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using Microsoft.ML.Data.Conversion;
using Microsoft.ML.Internal.Utilities;
namespace Microsoft.ML.Data
{
public static class DataViewUtils
{
/// <summary>
/// Generate a unique temporary column name for the given schema.
/// Use tag to independently create multiple temporary, unique column
/// names for a single transform.
/// </summary>
public static string GetTempColumnName(this Schema schema, string tag = null)
{
Contracts.CheckValue(schema, nameof(schema));
int col;
if (!string.IsNullOrWhiteSpace(tag) && !schema.TryGetColumnIndex(tag, out col))
return tag;
for (int i = 0; ; i++)
{
string name = string.IsNullOrWhiteSpace(tag) ?
string.Format("temp_{0:000}", i) :
string.Format("temp_{0}_{1:000}", tag, i);
if (!schema.TryGetColumnIndex(name, out col))
return name;
}
}
/// <summary>
/// Generate n unique temporary column names for the given schema.
/// Use tag to independently create multiple temporary, unique column
/// names for a single transform.
/// </summary>
public static string[] GetTempColumnNames(this Schema schema, int n, string tag = null)
{
Contracts.CheckValue(schema, nameof(schema));
Contracts.Check(n > 0, "n");
var res = new string[n];
int j = 0;
for (int i = 0; i < n; i++)
{
for (; ; )
{
string name = string.IsNullOrWhiteSpace(tag) ?
string.Format("temp_{0:000}", j) :
string.Format("temp_{0}_{1:000}", tag, j);
j++;
int col;
if (!schema.TryGetColumnIndex(name, out col))
{
res[i] = name;
break;
}
}
}
return res;
}
/// <summary>
/// Get the row count from the input view by any means necessary, even explicit enumeration
/// and counting if <see cref="IDataView.GetRowCount"/> insists on returning <c>null</c>.
/// </summary>
public static long ComputeRowCount(IDataView view)
{
long? countNullable = view.GetRowCount();
if (countNullable != null)
return countNullable.Value;
long count = 0;
using (var cursor = view.GetRowCursor(col => false))
{
while (cursor.MoveNext())
count++;
}
return count;
}
/// <summary>
/// Get the target number of threads to use, given a host and another indicator of thread count.
/// When num > 0, this uses num limited to twice what the host says. Otherwise, if preferOne
/// is true, it returns 1. Otherwise, it returns what the host says.
/// </summary>
public static int GetThreadCount(IHost host, int num = 0, bool preferOne = false)
{
Contracts.CheckValue(host, nameof(host));
int conc = host.ConcurrencyFactor;
if (conc <= 0)
conc = Math.Max(2, Environment.ProcessorCount - 1);
if (num > 0)
return Math.Min(num, 2 * conc);
if (preferOne)
return 1;
return conc;
}
/// <summary>
/// Try to create a cursor set from upstream and consolidate it here. The host determines
/// the target cardinality of the cursor set.
/// </summary>
public static bool TryCreateConsolidatingCursor(out RowCursor curs,
IDataView view, Func<int, bool> predicate, IHost host, Random rand)
{
Contracts.CheckValue(host, nameof(host));
host.CheckValue(view, nameof(view));
host.CheckValue(predicate, nameof(predicate));
int cthd = GetThreadCount(host);
host.Assert(cthd > 0);
if (cthd == 1 || !AllCachable(view.Schema, predicate))
{
curs = null;
return false;
}
var inputs = view.GetRowCursorSet(predicate, cthd, rand);
host.Check(Utils.Size(inputs) > 0);
if (inputs.Length == 1)
curs = inputs[0];
else
{
// We have a somewhat arbitrary batch size of about 64 for buffering results from the
// intermediate cursors, since that at least empirically for most datasets seems to
// strike a nice balance between a size large enough to benefit from parallelism but
// small enough so as to not be too onerous to keep in memory.
const int batchSize = 64;
curs = DataViewUtils.ConsolidateGeneric(host, inputs, batchSize);
}
return true;
}
/// <summary>
/// From the given input cursor, split it into a cursor set with the given
/// cardinality. If not all the active columns are cachable, this will only
/// produce the given input cursor.
/// </summary>
public static RowCursor[] CreateSplitCursors(IChannelProvider provider, RowCursor input, int num)
{
Contracts.CheckValue(provider, nameof(provider));
provider.CheckValue(input, nameof(input));
if (num <= 1)
return new RowCursor[1] { input };
// If any active columns are not cachable, we can't split.
if (!AllCachable(input.Schema, input.IsColumnActive))
return new RowCursor[1] { input };
// REVIEW: Should we limit the cardinality to some reasonable size?
// REVIEW: Ideally a splitter should be owned by a data view
// we might split, so that we can share the cache pools among multiple
// cursors.
// REVIEW: Keep the utility method here, move this splitter stuff
// to some other file.
return Splitter.Split(provider, input.Schema, input, num);
}
/// <summary>
/// Return whether all the active columns, as determined by the predicate, are
/// cachable - either primitive types or vector types.
/// </summary>
public static bool AllCachable(Schema schema, Func<int, bool> predicate)
{
Contracts.CheckValue(schema, nameof(schema));
Contracts.CheckValue(predicate, nameof(predicate));
for (int col = 0; col < schema.Count; col++)
{
if (!predicate(col))
continue;
var type = schema[col].Type;
if (!IsCachable(type))
return false;
}
return true;
}
/// <summary>
/// Determine whether the given type is cachable - either a primitive type or a vector type.
/// </summary>
public static bool IsCachable(this ColumnType type)
{
return type != null && (type.IsPrimitive || type.IsVector);
}
/// <summary>
/// Tests whether the cursors are mutually compatible for consolidation,
/// that is, they all are non-null, have the same schemas, and the same
/// set of columns are active.
/// </summary>
public static bool SameSchemaAndActivity(RowCursor[] cursors)
{
// There must be something to actually consolidate.
if (Utils.Size(cursors) == 0)
return true;
var firstCursor = cursors[0];
if (firstCursor == null)
return false;
if (cursors.Length == 1)
return true;
var schema = firstCursor.Schema;
// All cursors must have the same schema.
for (int i = 1; i < cursors.Length; ++i)
{
if (cursors[i] == null || cursors[i].Schema != schema)
return false;
}
// All cursors must have the same columns active.
for (int c = 0; c < schema.Count; ++c)
{
bool active = firstCursor.IsColumnActive(c);
for (int i = 1; i < cursors.Length; ++i)
{
if (cursors[i].IsColumnActive(c) != active)
return false;
}
}
return true;
}
/// <summary>
/// Given a parallel cursor set, this consolidates them into a single cursor. The batchSize
/// is a hint used for efficiency.
/// </summary>
public static RowCursor ConsolidateGeneric(IChannelProvider provider, RowCursor[] inputs, int batchSize)
{
Contracts.CheckValue(provider, nameof(provider));
provider.CheckNonEmpty(inputs, nameof(inputs));
provider.CheckParam(batchSize >= 0, nameof(batchSize));
if (inputs.Length == 1)
return inputs[0];
object[] pools = null;
return Splitter.Consolidate(provider, inputs, batchSize, ref pools);
}
/// <summary>
/// A convenience class to facilitate the creation of a split, as well as a convenient
/// place to store shared resources that can be reused among multiple splits of a cursor
/// with the same schema. Since splitting also returns a consolidator, this also contains
/// a consolidating logic.
///
/// In a very rough sense, both the splitters and consolidators are written in the same way:
/// For all input cursors, and all active columns, an "in pipe" is created. A worker thread
/// per input cursor busily retrieves values from the cursors and stores them in the "in
/// pipe." At appropriate times, "batch" objects are synthesized from the inputs consumed
/// thusfar, and inserted into a blocking collection. The output cursor or cursors likewise
/// have a set of "out pipe" instances, one per each of the active columns, through which
/// successive batches are presented for consumption by the user of the output cursors. Of
/// course, both split and consolidate have many details from which they differ, for example, the
/// consolidator must accept batches as they come and reconcile them among multiple inputs,
/// while the splitter is more free.
///
/// It is ideal if a data view that could be split retains one of these objects itself,
/// so that multiple splittings will have the capability of sharing buffers from cursoring
/// to cursoring, but this is not required.
/// </summary>
private sealed class Splitter
{
private readonly Schema _schema;
private readonly object[] _cachePools;
/// <summary>
/// Pipes, in addition to column values, will also communicate extra information
/// enumerated within this. This enum serves the purpose of providing nice readable
/// indices to these "extra" information in pipes.
/// </summary>
private enum ExtraIndex
{
Id,
#pragma warning disable MSML_GeneralName // Allow for this private enum.
_Lim
#pragma warning restore MSML_GeneralName
}
private Splitter(Schema schema)
{
Contracts.AssertValue(schema);
_schema = schema;
_cachePools = new object[_schema.Count + (int)ExtraIndex._Lim];
}
public static RowCursor Consolidate(IChannelProvider provider, RowCursor[] inputs, int batchSize, ref object[] ourPools)
{
Contracts.AssertValue(provider);
using (var ch = provider.Start("Consolidate"))
{
return ConsolidateCore(provider, inputs, ref ourPools, ch);
}
}
private static RowCursor ConsolidateCore(IChannelProvider provider, RowCursor[] inputs, ref object[] ourPools, IChannel ch)
{
ch.CheckNonEmpty(inputs, nameof(inputs));
if (inputs.Length == 1)
return inputs[0];
ch.CheckParam(SameSchemaAndActivity(inputs), nameof(inputs), "Inputs not compatible for consolidation");
RowCursor cursor = inputs[0];
var schema = cursor.Schema;
ch.CheckParam(AllCachable(schema, cursor.IsColumnActive), nameof(inputs), "Inputs had some uncachable input columns");
int[] activeToCol;
int[] colToActive;
Utils.BuildSubsetMaps(schema.Count, cursor.IsColumnActive, out activeToCol, out colToActive);
// Because the schema of the consolidator is not necessary fixed, we are merely
// opportunistic about buffer sharing, from cursoring to cursoring. If we can do
// it easily, great, if not, no big deal.
if (Utils.Size(ourPools) != schema.Count)
ourPools = new object[schema.Count + (int)ExtraIndex._Lim];
// Create the out pipes.
OutPipe[] outPipes = new OutPipe[activeToCol.Length + (int)ExtraIndex._Lim];
for (int i = 0; i < activeToCol.Length; ++i)
{
int c = activeToCol[i];
ColumnType type = schema[c].Type;
var pool = GetPool(type, ourPools, c);
outPipes[i] = OutPipe.Create(type, pool);
}
int idIdx = activeToCol.Length + (int)ExtraIndex.Id;
outPipes[idIdx] = OutPipe.Create(NumberType.UG, GetPool(NumberType.UG, ourPools, idIdx));
// Create the structures to synchronize between the workers and the consumer.
const int toConsumeBound = 4;
var toConsume = new BlockingCollection<Batch>(toConsumeBound);
var batchColumnPool = new MadeObjectPool<BatchColumn[]>(() => new BatchColumn[outPipes.Length]);
Thread[] workers = new Thread[inputs.Length];
MinWaiter waiter = new MinWaiter(workers.Length);
bool done = false;
for (int t = 0; t < workers.Length; ++t)
{
var localCursor = inputs[t];
ch.Assert(localCursor.State == CursorState.NotStarted);
// Note that these all take ownership of their respective cursors,
// so they all handle their disposal internal to the thread.
workers[t] = Utils.CreateBackgroundThread(() =>
{
// This will be the last batch sent in the finally. If iteration procedes without
// error, it will remain null, and be sent as a sentinel. If iteration results in
// an exception that we catch, the exception catching block will set this to an
// exception bearing block, and that will be passed along as the last block instead.
Batch lastBatch = null;
try
{
using (localCursor)
{
InPipe[] inPipes = new InPipe[outPipes.Length];
for (int i = 0; i < activeToCol.Length; ++i)
inPipes[i] = outPipes[i].CreateInPipe(RowCursorUtils.GetGetterAsDelegate(localCursor, activeToCol[i]));
inPipes[idIdx] = outPipes[idIdx].CreateInPipe(localCursor.GetIdGetter());
long oldBatch = 0;
int count = 0;
// This event is used to synchronize ourselves using a MinWaiter
// so that we add batches to the consumer queue at the appropriate time.
ManualResetEventSlim waiterEvent = null;
Action pushBatch = () =>
{
if (count > 0)
{
var batchColumns = batchColumnPool.Get();
for (int i = 0; i < inPipes.Length; ++i)
batchColumns[i] = inPipes[i].GetBatchColumnAndReset();
// REVIEW: Is it worth not allocating new Batch object for each batch?
var batch = new Batch(batchColumnPool, batchColumns, count, oldBatch);
count = 0;
// The waiter event should never be null since this is only
// called after a point where waiter.Register has been called.
ch.AssertValue(waiterEvent);
waiterEvent.Wait();
waiterEvent = null;
toConsume.Add(batch);
}
};
// Handle the first one separately, then go into the main loop.
if (localCursor.MoveNext() && !done)
{
oldBatch = localCursor.Batch;
foreach (var pipe in inPipes)
pipe.Fill();
count++;
// Register with the min waiter that we want to wait on this batch number.
waiterEvent = waiter.Register(oldBatch);
while (localCursor.MoveNext() && !done)
{
if (oldBatch != localCursor.Batch)
{
ch.Assert(count == 0 || localCursor.Batch > oldBatch);
pushBatch();
oldBatch = localCursor.Batch;
waiterEvent = waiter.Register(oldBatch);
}
foreach (var pipe in inPipes)
pipe.Fill();
count++;
}
pushBatch();
}
}
}
catch (Exception ex)
{
// Whoops, we won't be sending null as the sentinel now.
lastBatch = new Batch(ex);
toConsume.Add(new Batch(ex));
}
finally
{
if (waiter.Retire() == 0)
{
if (lastBatch == null)
{
// If it wasn't null, this already sent along an exception bearing batch, in which
// case sending the sentinel is unnecessary and unhelpful.
toConsume.Add(null);
}
toConsume.CompleteAdding();
}
}
});
workers[t].Start();
}
Action quitAction = () =>
{
done = true;
var myOutPipes = outPipes;
foreach (var batch in toConsume.GetConsumingEnumerable())
{
if (batch == null)
continue;
batch.SetAll(myOutPipes);
foreach (var outPipe in myOutPipes)
outPipe.Unset();
}
foreach (Thread thread in workers)
thread.Join();
};
return new Cursor(provider, schema, activeToCol, colToActive, outPipes, toConsume, quitAction);
}
private static object GetPool(ColumnType type, object[] pools, int poolIdx)
{
Func<object[], int, object> func = GetPoolCore<int>;
var method = func.GetMethodInfo().GetGenericMethodDefinition().MakeGenericMethod(type.RawType);
return method.Invoke(null, new object[] { pools, poolIdx });
}
private static MadeObjectPool<T[]> GetPoolCore<T>(object[] pools, int poolIdx)
{
var pool = pools[poolIdx] as MadeObjectPool<T[]>;
if (pool == null)
pools[poolIdx] = pool = new MadeObjectPool<T[]>(() => null);
return pool;
}
public static RowCursor[] Split(IChannelProvider provider, Schema schema, RowCursor input, int cthd)
{
Contracts.AssertValue(provider, "provider");
var splitter = new Splitter(schema);
using (var ch = provider.Start("CursorSplitter"))
{
var result = splitter.SplitCore(provider, input, cthd);
return result;
}
}
private RowCursor[] SplitCore(IChannelProvider ch, RowCursor input, int cthd)
{
Contracts.AssertValue(ch);
ch.AssertValue(input);
ch.Assert(input.Schema == _schema);
ch.Assert(cthd >= 2);
ch.Assert(AllCachable(_schema, input.IsColumnActive));
// REVIEW: Should the following be configurable?
// How would we even expose these sorts of parameters to a user?
const int maxBatchCount = 128;
const int toConsumeBound = 4;
// Create the mappings between active column index, and column index.
int[] activeToCol;
int[] colToActive;
Utils.BuildSubsetMaps(_schema.Count, input.IsColumnActive, out activeToCol, out colToActive);
Func<RowCursor, int, InPipe> createFunc = CreateInPipe<int>;
var inGenMethod = createFunc.GetMethodInfo().GetGenericMethodDefinition();
object[] arguments = new object[] { input, 0 };
// Only one set of in-pipes, one per column, as well as for extra side information.
InPipe[] inPipes = new InPipe[activeToCol.Length + (int)ExtraIndex._Lim];
// There are as many sets of out pipes as there are output cursors.
OutPipe[][] outPipes = new OutPipe[cthd][];
for (int i = 0; i < cthd; ++i)
outPipes[i] = new OutPipe[inPipes.Length];
// For each column, create the InPipe, and all OutPipes per output cursor.
for (int c = 0; c < activeToCol.Length; ++c)
{
ch.Assert(0 <= activeToCol[c] && activeToCol[c] < _schema.Count);
ch.Assert(c == 0 || activeToCol[c - 1] < activeToCol[c]);
ch.Assert(input.IsColumnActive(activeToCol[c]));
var type = input.Schema[activeToCol[c]].Type;
ch.Assert(type.IsCachable());
arguments[1] = activeToCol[c];
var inPipe = inPipes[c] =
(InPipe)inGenMethod.MakeGenericMethod(type.RawType).Invoke(this, arguments);
for (int i = 0; i < cthd; ++i)
outPipes[i][c] = inPipe.CreateOutPipe(type);
}
// Beyond the InPipes corresponding to column values, we have extra side info pipes.
int idIdx = activeToCol.Length + (int)ExtraIndex.Id;
inPipes[idIdx] = CreateIdInPipe(input);
for (int i = 0; i < cthd; ++i)
outPipes[i][idIdx] = inPipes[idIdx].CreateOutPipe(NumberType.UG);
var toConsume = new BlockingCollection<Batch>(toConsumeBound);
var batchColumnPool = new MadeObjectPool<BatchColumn[]>(() => new BatchColumn[inPipes.Length]);
bool done = false;
int outputsRunning = cthd;
// Set up and start the thread that consumes the input, and utilizes the InPipe
// instances to compose the Batch objects. The thread takes ownership of the
// cursor, and so handles its disposal.
Thread thread = Utils.CreateBackgroundThread(
() =>
{
Batch lastBatch = null;
try
{
using (input)
{
long batchId = 0;
int count = 0;
Action pushBatch = () =>
{
var batchColumns = batchColumnPool.Get();
for (int c = 0; c < inPipes.Length; ++c)
batchColumns[c] = inPipes[c].GetBatchColumnAndReset();
// REVIEW: Is it worth not allocating new Batch object for each batch?
var batch = new Batch(batchColumnPool, batchColumns, count, batchId++);
count = 0;
toConsume.Add(batch);
};
while (input.MoveNext() && !done)
{
foreach (var pipe in inPipes)
pipe.Fill();
if (++count >= maxBatchCount)
pushBatch();
}
if (count > 0)
pushBatch();
}
}
catch (Exception ex)
{
lastBatch = new Batch(ex);
}
finally
{
// The last batch might be an exception, as in the above case. We pass along the exception
// bearing batch as the first of the last batches, so that the first worker to encounter this
// will know to throw. The remaining get the regular "stop working" null sentinel.
toConsume.Add(lastBatch);
for (int i = 1; i < cthd; ++i)
toConsume.Add(null);
toConsume.CompleteAdding();
}
});
thread.Start();
Action quitAction = () =>
{
int remaining = Interlocked.Decrement(ref outputsRunning);
ch.Assert(remaining >= 0);
if (remaining == 0)
{
done = true;
// A relatively quick and convenient way to dispose of batches, is to use
// set/unset on some output pipes repeatedly. Since all have been disposed,
// we may as well use the first set of output pipes.
var myOutPipes = outPipes[0];
foreach (var batch in toConsume.GetConsumingEnumerable())
{
if (batch == null)
continue;
batch.SetAll(myOutPipes);
foreach (var outPipe in myOutPipes)
outPipe.Unset();
}
thread.Join();
}
};
var cursors = new Cursor[cthd];
for (int i = 0; i < cthd; ++i)
cursors[i] = new Cursor(ch, _schema, activeToCol, colToActive, outPipes[i], toConsume, quitAction);
return cursors;
}
/// <summary>
/// An in pipe creator intended to be used from the splitter only.
/// </summary>
private InPipe CreateInPipe<T>(Row input, int col)
{
Contracts.AssertValue(input);
Contracts.Assert(0 <= col && col < _schema.Count);
return CreateInPipeCore(col, input.GetGetter<T>(col));
}
/// <summary>
/// An in pipe creator intended to be used from the splitter only.
/// </summary>
private InPipe CreateIdInPipe(Row input)
{
Contracts.AssertValue(input);
return CreateInPipeCore(_schema.Count + (int)ExtraIndex.Id, input.GetIdGetter());
}
private InPipe CreateInPipeCore<T>(int poolIdx, ValueGetter<T> getter)
{
Contracts.Assert(0 <= poolIdx && poolIdx < _cachePools.Length);
Contracts.AssertValue(getter);
var pool = (MadeObjectPool<T[]>)_cachePools[poolIdx];
if (pool == null)
{
// REVIEW: If we changed our InPipe behavior so that it only worked over a maximum size
// in all scenarios, both during splitting and consolidating, it would be possible to set this
// to be of fixed size so we don't have to do reallocation.
Interlocked.CompareExchange(ref _cachePools[poolIdx], new MadeObjectPool<T[]>(() => null), null);
pool = (MadeObjectPool<T[]>)_cachePools[poolIdx];
}
return InPipe.Create(pool, getter);
}
/// <summary>
/// There is one of these created per input cursor, per "channel" of information
/// (necessary channels include values from active columns, as well as additional
/// side information), in both splitting and consolidating. This is a running buffer
/// of the input cursor's values. It is used to create <see cref="BatchColumn"/> objects.
/// </summary>
private abstract class InPipe
{
public int Count { get; protected set; }
private InPipe()
{
}
public abstract void Fill();
public abstract BatchColumn GetBatchColumnAndReset();
public static InPipe Create<T>(MadeObjectPool<T[]> pool, ValueGetter<T> getter)
{
return new Impl<T>(pool, getter);
}
/// <summary>
/// Creates an out pipe corresponding to the in pipe. This is useful for the splitter,
/// when we are creating an in pipe.
/// </summary>
public abstract OutPipe CreateOutPipe(ColumnType type);
private sealed class Impl<T> : InPipe
{
private readonly MadeObjectPool<T[]> _pool;
private readonly ValueGetter<T> _getter;
private T[] _values;
public Impl(MadeObjectPool<T[]> pool, ValueGetter<T> getter)
{
Contracts.AssertValue(pool);
Contracts.AssertValue(getter);
_pool = pool;
_getter = getter;
_values = _pool.Get();
Contracts.AssertValueOrNull(_values);
}
public override void Fill()
{
Utils.EnsureSize(ref _values, Count + 1, keepOld: true);
_getter(ref _values[Count++]);
}
public override BatchColumn GetBatchColumnAndReset()
{
// REVIEW: Is it worth avoiding an allocation of these new BatchColumn objects?
var retval = new BatchColumn.Impl<T>(_values, Count);
_values = _pool.Get();
Count = 0;
return retval;
}
public override OutPipe CreateOutPipe(ColumnType type)
{
Contracts.AssertValue(type);
Contracts.Assert(typeof(T) == type.RawType);
return OutPipe.Create(type, _pool);
}
}
}
/// <summary>
/// These are objects continuously created by the <see cref="InPipe"/> to spin off the
/// values they have collected. They are collected into a <see cref="Batch"/>
/// object, and eventually one is consumed by an <see cref="OutPipe"/> instance.
/// </summary>
private abstract class BatchColumn
{
public readonly int Count;
private BatchColumn(int count)
{
Contracts.Assert(count > 0);
Count = count;
}
public sealed class Impl<T> : BatchColumn
{
public readonly T[] Values;
public Impl(T[] values, int count)
: base(count)
{
Contracts.Assert(Utils.Size(values) >= count);
Values = values;
}
}
}
/// <summary>
/// This holds a collection of <see cref="BatchColumn"/> objects, which together hold all
/// the values from a set of rows from the input cursor. These are produced as needed
/// by the input cursor reader, and consumed by each of the output cursors.
///
/// This class also serves a secondary role in marshalling exceptions thrown in the workers
/// producing batches, into the threads consuming these batches.
/// <see cref="HasException"/> lets us know if this is one of these "special" batches.
/// If it is, then the <see cref="SetAll"/> method will throw whenever it is called, by the
/// consumer of the batches.
/// </summary>
private sealed class Batch
{
private readonly MadeObjectPool<BatchColumn[]> _pool;
private readonly BatchColumn[] _batchColumns;
public readonly int Count;
public readonly long BatchId;
private readonly Exception _ex;
public bool HasException { get { return _ex != null; } }
/// <summary>
/// Construct a batch object to communicate the <see cref="BatchColumn"/> objects to consumers.
/// </summary>
public Batch(MadeObjectPool<BatchColumn[]> pool, BatchColumn[] batchColumns, int count, long batchId)
{
Contracts.AssertValue(pool);
Contracts.AssertValue(batchColumns);
Contracts.Assert(count > 0);
Contracts.Assert(batchId >= 0);
Contracts.Assert(batchColumns.All(bc => bc.Count == count));
_pool = pool;
_batchColumns = batchColumns;
Count = count;
BatchId = batchId;
Contracts.Assert(!HasException);
}
/// <summary>
/// Construct a batch object to communicate that something went wrong. In this case all other fields
/// will have default values.
/// </summary>
public Batch(Exception ex)
{
Contracts.AssertValue(ex);
_ex = ex;
Contracts.Assert(HasException);
}
/// <summary>
/// Gives all of the batch columns to the output pipes. This should be called only once,
/// per batch object, because the the batch columns will be returned to the pool.
///
/// If this was an exception bearing batch, that exception will be propagated and thrown
/// in this.
/// </summary>
public void SetAll(OutPipe[] pipes)
{
if (_ex != null)
throw Contracts.Except(_ex, "Splitter/consolidator worker encountered exception while consuming source data");
Contracts.Assert(Utils.Size(pipes) == _batchColumns.Length);
for (int p = 0; p < _batchColumns.Length; ++p)
{
pipes[p].Set(_batchColumns[p]);
_batchColumns[p] = null;
}
_pool.Return(_batchColumns);
}
}
/// <summary>
/// This helps a cursor present the results of a <see cref="BatchColumn"/>. Practically its role
/// really is to just provide a stable delegate for the <see cref="Row.GetGetter{T}(int)"/>.
/// There is one of these created per column, per output cursor, i.e., in splitting
/// there are <c>n</c> of these created per column, and when consolidating only one of these
/// is created per column.
/// </summary>
private abstract class OutPipe
{
private int _count;
private int _index;
public int Remaining => _count - _index;
private OutPipe()
{
}
public static OutPipe Create(ColumnType type, object pool)
{
Contracts.AssertValue(type);
Contracts.AssertValue(pool);
Type pipeType;
if (type.IsVector)
pipeType = typeof(ImplVec<>).MakeGenericType(type.ItemType.RawType);
else
{
Contracts.Assert(type.IsPrimitive);
pipeType = typeof(ImplOne<>).MakeGenericType(type.RawType);
}
var constructor = pipeType.GetConstructor(new Type[] { typeof(object) });
return (OutPipe)constructor.Invoke(new object[] { pool });
}
/// <summary>
/// Creates an in pipe corresponding to this out pipe. Useful for the consolidator,
/// when we are creating many in pipes from a single out pipe.
/// </summary>
public abstract InPipe CreateInPipe(Delegate getter);
/// <summary>
/// Sets this <see cref="OutPipe"/> to start presenting the output of a batch column.
/// Note that this positions the output on the first item, not before the first item,
/// so it is not necessary to call <see cref="MoveNext"/> to get the first value.
/// </summary>
/// <param name="batchCol">The batch column whose values we should start presenting.</param>
public abstract void Set(BatchColumn batchCol);
public abstract void Unset();
public abstract Delegate GetGetter();
/// <summary>
/// Moves to the next value. Note that this should be called only when we are certain that
/// we have a next value to move to, that is, when <see cref="Remaining"/> is non-zero.
/// </summary>
public void MoveNext()
{
Contracts.Assert(_index < _count);
++_index;
}
private abstract class Impl<T> : OutPipe
{
private readonly MadeObjectPool<T[]> _pool;
protected T[] Values;
public Impl(object pool)
{
Contracts.Assert(pool is MadeObjectPool<T[]>);
_pool = (MadeObjectPool<T[]>)pool;
}
public override InPipe CreateInPipe(Delegate getter)
{
Contracts.AssertValue(getter);
Contracts.Assert(getter is ValueGetter<T>);
return InPipe.Create<T>(_pool, (ValueGetter<T>)getter);
}
public override void Set(BatchColumn batchCol)
{
Contracts.AssertValue(batchCol);
Contracts.Assert(batchCol is BatchColumn.Impl<T>);
// In all possible scenarios, there is never cause for an output pipe
// to end early while the cursor itself has more rows, I believe, except
// if we at some point decide to optimize move many.
Contracts.Assert(_count == 0 || (_index == _count - 1));
// REVIEW: This sort of loose typing makes me angry. Roar!
var batchColTyped = (BatchColumn.Impl<T>)batchCol;
if (Values != null)
_pool.Return(Values);
Values = batchColTyped.Values;
_count = batchColTyped.Count;
_index = 0;
Contracts.Assert(_count <= Utils.Size(Values));
}
public override void Unset()
{
Contracts.Assert(_index <= _count);
if (Values != null)
_pool.Return(Values);
Values = null;
_count = 0;
_index = 0;
}
public override Delegate GetGetter()
{
ValueGetter<T> getter = Getter;
return getter;
}
protected abstract void Getter(ref T value);
}
private sealed class ImplVec<T> : Impl<VBuffer<T>>
{
public ImplVec(object pool)
: base(pool)
{
}
protected override void Getter(ref VBuffer<T> value)
{
Contracts.Check(_index < _count, "Cannot get value as the cursor is not in a good state");
Values[_index].CopyTo(ref value);
}
}
private sealed class ImplOne<T> : Impl<T>
{
public ImplOne(object pool)
: base(pool)
{
}
protected override void Getter(ref T value)
{
Contracts.Check(_index < _count, "Cannot get value as the cursor is not in a good state");
value = Values[_index];
}
}
}
/// <summary>
/// A cursor used by both the splitter and consolidator, that iteratively consumes
/// <see cref="Batch"/> objects from the input blocking collection, and yields the
/// values stored therein through the help of <see cref="OutPipe"/> objects.
/// </summary>
private sealed class Cursor : RootCursorBase
{
private readonly Schema _schema;
private readonly int[] _activeToCol;
private readonly int[] _colToActive;
private readonly OutPipe[] _pipes;
private readonly Delegate[] _getters;
private readonly ValueGetter<RowId> _idGetter;
private readonly BlockingCollection<Batch> _batchInputs;
private readonly Action _quitAction;
private int _remaining;
private long _batch;
private bool _disposed;