/
in_place.clj
518 lines (454 loc) · 20.4 KB
/
in_place.clj
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
(ns tech.libs.arrow.in-place
(:require [tech.v2.datatype.mmap :as mmap]
[tech.libs.arrow.copying :as arrow]
[tech.v2.datatype :as dtype]
[tech.ml.dataset.impl.column :as col-impl]
[tech.ml.dataset.impl.dataset :as ds-impl]
[tech.ml.dataset.base :as ds-base]
[clojure.core.protocols :as clj-proto]
[clojure.datafy :refer [datafy]])
(:import [tech.v2.datatype.mmap NativeBuffer]
[org.apache.arrow.vector.ipc.message MessageSerializer
MessageMetadataResult]
[org.apache.arrow.vector TypeLayout Float8Vector]
[org.apache.arrow.flatbuf Message MessageHeader DictionaryBatch RecordBatch]
[org.apache.arrow.vector.types TimeUnit FloatingPointPrecision DateUnit]
[org.apache.arrow.vector.types.pojo FieldType ArrowType Field Schema
ArrowType$Int ArrowType$FloatingPoint ArrowType$Bool
ArrowType$Utf8 ArrowType$Date ArrowType$Time ArrowType$Timestamp
ArrowType$Duration DictionaryEncoding]
[tech.ml.dataset.dynamic_int_list DynamicIntList]
[tech.ml.dataset.string_table StringTable]
[java.util ArrayList HashMap List]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(defn align-offset
^long [^long off]
(let [alignment (rem off 8)]
(if (== 0 alignment)
off
(+ off (- 8 alignment)))))
(defn message-id->message-type
[^long message-id]
(case message-id
1 :schema
2 :dictionary-batch
3 :record-batch
{:unexpected-message-type message-id}))
(defn read-message
"returns a pair of offset-data and message."
[^NativeBuffer data]
(when-not (== 0 (.n-elems data))
(let [msg-size (mmap/read-int data)
[msg-size offset] (if (== -1 msg-size)
[(mmap/read-int data 4) 8]
[msg-size 4])
offset (long offset)
msg-size (long msg-size)]
(when (> msg-size 0)
(let [new-msg (Message/getRootAsMessage
(-> (dtype/sub-buffer data offset msg-size)
(dtype/->buffer-backing-store)))
next-buf (dtype/sub-buffer data (+ offset msg-size))
body-length (.bodyLength new-msg)
aligned-offset (align-offset (+ offset msg-size body-length))]
(merge
{:next-data (dtype/sub-buffer data aligned-offset)
:message new-msg
:message-type (message-id->message-type (.headerType new-msg))}
(when-not (== 0 body-length)
{:body (dtype/sub-buffer next-buf 0 (.bodyLength new-msg))})))))))
(defn message-seq
"Given a native buffer of arrow stream data, produce a sequence of flatbuf messages"
[^NativeBuffer data]
(when-let [msg (read-message data)]
(cons msg (lazy-seq (message-seq (:next-data msg))))))
(extend-protocol clj-proto/Datafiable
ArrowType$Int
(datafy [this]
(let [signed? (.getIsSigned this)
bit-width (.getBitWidth this)]
{:datatype (if signed?
(case bit-width
8 :int8
16 :int16
32 :int32
64 :int64)
(case bit-width
8 :uint8
16 :uint16
32 :uint32
64 :uint64))}))
ArrowType$Utf8
(datafy [this]
{:datatype :string
:encoding :utf-8})
ArrowType$FloatingPoint
(datafy [this]
{:datatype (condp = (.getPrecision this)
FloatingPointPrecision/HALF :float16
FloatingPointPrecision/SINGLE :float32
FloatingPointPrecision/DOUBLE :float64)})
ArrowType$Timestamp
(datafy [this]
(merge
(if (= (.getUnit this) TimeUnit/MILLISECOND)
{:datatype :epoch-milliseconds}
{:datatype :int64 :time-unit (condp = (.getUnit this)
TimeUnit/MICROSECOND :microsecond
TimeUnit/NANOSECOND :nanosecond
TimeUnit/SECOND :second)})
(when (and (.getTimezone this)
(not= 0 (count (.getTimezone this))))
{:timezone (.getTimezone this)})))
ArrowType$Bool
(datafy [this] {:datatype :boolean})
DictionaryEncoding
(datafy [this] {:id (.getId this)
:ordered? (.isOrdered this)
:index-type (datafy (.getIndexType this))}))
(defn read-schema
"returns a pair of offset-data and schema"
[{:keys [message body message-type]}]
(let [schema (MessageSerializer/deserializeSchema ^Message message)
fields
(->> (.getFields schema)
(mapv (fn [^Field field]
(let [arrow-type (.getType (.getFieldType field))
datafied-data (datafy arrow-type)]
(when-not (map? datafied-data)
(throw (Exception.
(format "Failed to datafy datatype %s"
(type arrow-type)))))
(merge
{:name (.getName field)
:nullable? (.isNullable field)
:field-type datafied-data
:metadata (.getMetadata field)}
(when-let [encoding (.getDictionary field)]
{:dictionary-encoding (datafy encoding)}))))))]
{:fields fields
:encodings (->> (map :dictionary-encoding fields)
(remove nil?)
(map (juxt :id identity))
(into {}))
:metadata (.getCustomMetadata schema)}))
(defn read-record-batch
([^RecordBatch record-batch ^NativeBuffer data]
{:nodes (->> (range (.nodesLength record-batch))
(mapv #(let [node (.nodes record-batch (int %))]
{:n-elems (.length node)
:n-null-entries (.nullCount node)})))
:buffers (->> (range (.buffersLength record-batch))
(mapv #(let [buffer (.buffers record-batch (int %))]
(dtype/sub-buffer data (.offset buffer)
(.length buffer)))))})
([{:keys [message body message-type] :as msg}]
(read-record-batch (.header ^Message message (RecordBatch.)) body)))
(defn- check-message-type
[expected-type actual-type]
(when-not (= actual-type expected-type)
(throw (Exception.
(format "Expected message type %s, got %s"
expected-type actual-type) ))))
(defn read-dictionary-batch
[{:keys [message body message-type]}]
(check-message-type :dictionary-batch message-type)
(let [^DictionaryBatch db (.header ^Message message (DictionaryBatch.))]
{:id (.id db)
:delta? (.isDelta db)
:records (read-record-batch (.data db) body)}))
(defmulti parse-message
"Given a message, parse it just a bit into a more interpretable datastructure."
:message-type)
(defmethod parse-message :schema
[msg]
(assoc (read-schema msg)
:message-type (:message-type msg)))
(defmethod parse-message :dictionary-batch
[msg]
(assoc (read-dictionary-batch msg)
:message-type (:message-type msg)))
(defmethod parse-message :record-batch
[msg]
(assoc (read-record-batch msg)
:message-type (:message-type msg)))
(def fixed-type-layout [:validity :data])
(def variable-type-layout [:validity :int32 :int8])
(def large-variable-type-layout [:validity :int64 :int8])
(defn offsets-data->string-reader
^List [offsets data n-elems]
(let [n-elems (long n-elems)
offsets (dtype/->reader offsets)]
(dtype/object-reader
n-elems
(fn [^long idx]
(let [start-off (long (offsets idx))
end-off (long (offsets (inc idx)))
^bytes byte-data (-> (dtype/sub-buffer data start-off
(- end-off start-off))
(dtype/->array-copy))]
(String. byte-data)))
:string)))
(defn dictionary->strings
"Returns a map of {:id :strings}"
[{:keys [id delta? records] :as dict}]
(let [nodes (:nodes records)
buffers (:buffers records)
_ (assert (== 1 (count nodes)))
_ (assert (== 3 (count buffers)))
node (first nodes)
[bitwise offsets databuf] buffers
n-elems (long (:n-elems node))
offsets (-> (mmap/set-native-datatype offsets :int32)
(dtype/sub-buffer 0 n-elems))
data (mmap/set-native-datatype databuf :int8)
str-data (dtype/make-container :list :string
(offsets-data->string-reader offsets data n-elems))]
{:id id
:strings str-data}))
(defn string-data->column-data
[dict-map encoding buffers n-elems]
(if encoding
(let [str-list (get-in dict-map [(:id encoding) :strings])
index-data (-> (first buffers)
(mmap/set-native-datatype
(get-in encoding [:index-type :datatype]))
(dtype/sub-buffer 0 n-elems)
(dtype/->reader :int32))
retval (StringTable. str-list nil (DynamicIntList. index-data index-data))]
retval)
(let [[offsets varchar-data] buffers]
(offsets-data->string-reader (mmap/set-native-datatype offsets :int32)
varchar-data n-elems))))
(defn records->ds
[schema dict-map record-batch]
(let [{:keys [fields]} schema
{:keys [nodes buffers]} record-batch]
(assert (= (count fields) (count nodes)))
(->> (map vector fields nodes)
(reduce (fn [[retval ^long buf-idx] [field node]]
(let [field-dtype (get-in field [:field-type :datatype])
col-metadata (dissoc (:field-type field) :datatype)
encoding (get field :dictionary-encoding)
n-buffers (long (if (and (= :string field-dtype)
(not encoding))
3
2))
specific-bufs (subvec buffers buf-idx
(+ buf-idx n-buffers))
n-elems (long (:n-elems node))
missing (if (== 0 (long (:n-null-entries node)))
(dtype/->bitmap-set)
(arrow/int8-buf->missing (first specific-bufs)
n-elems))
metadata (into col-metadata (:metadata field))]
[(conj retval
(col-impl/new-column
(:name field)
(case field-dtype
:string (string-data->column-data
dict-map encoding (drop 1 specific-bufs)
n-elems)
:boolean (arrow/bitbuffer->boolean-reader
(second specific-bufs) n-elems)
(-> (mmap/set-native-datatype
(second specific-bufs) field-dtype)
(dtype/sub-buffer 0 n-elems)))
metadata
missing))
(+ buf-idx n-buffers)]))
[[] 0])
(first)
(ds-impl/new-dataset))))
(defn- parse-next-dataset
[fdata schema messages fname idx]
(when (seq messages)
(let [dict-messages (take-while #(= (:message-type %) :dictionary-batch)
messages)
rest-messages (drop (count dict-messages) messages)
dict-map (->> dict-messages
(map dictionary->strings)
(map (juxt :id identity))
(into {}))
data-record (first rest-messages)]
(cons
(-> (records->ds schema dict-map data-record)
(ds-base/set-dataset-name (format "%s-%03d" fname idx))
;;Assoc on the file data so the gc doesn't release the source memory map
;;until no one is accessing the dataset any more in the case where
;;the file was opened with {:resource-type :gc}
(vary-meta assoc :source-mmap fdata))
(lazy-seq (parse-next-dataset fdata schema (rest rest-messages)
fname (inc (long idx))))))))
(defn stream->dataset-seq-inplace
"Loads data up to and including the first data record. Returns the a lazy
sequence of datasets. Datasets use mmapped data, however, so realizing the
entire sequence is usually safe, even for datasets that are larger than
available RAM.
This method is expected to be called from within a stack resource context
unless options include {:resource-type :gc}. See documentation for
tech.v2.datatype.mmap/mmap-file."
[fname & [options]]
(let [fdata (mmap/mmap-file fname options)
messages (mapv parse-message (message-seq fdata))
schema (first messages)
_ (when-not (= :schema (:message-type schema))
(throw (Exception. "Initial message is not a schema message.")))
messages (rest messages)]
(parse-next-dataset fdata schema messages fname 0)))
(defn read-stream-dataset-inplace
"Loads data up to and including the first data record. Returns the dataset
and the memory-mapped file.
This method is expected to be called from within a stack resource context."
[fname & [options]]
(let [fdata (mmap/mmap-file fname options)
messages (mapv parse-message (message-seq fdata))
schema (first messages)
_ (when-not (= :schema (:message-type schema))
(throw (Exception. "Initial message is not a schema message.")))
messages (rest messages)
dict-messages (take-while #(= (:message-type %) :dictionary-batch)
messages)
rest-messages (drop (count dict-messages) messages)
dict-map (->> dict-messages
(map dictionary->strings)
(map (juxt :id identity))
(into {}))
data-record (first rest-messages)]
(when-not (= :record-batch (:message-type data-record))
(throw (Exception. "No data records detected")))
(when (seq (rest rest-messages))
(throw (Exception. "File contains multiple record batches.
Please use stream->dataset-seq-inplace.")))
(-> (records->ds schema dict-map data-record)
(ds-base/set-dataset-name fname)
;;We have to be sure that the dataset keeps a reference to the file data
;;else the GC may clean up our mmap before we are ready.
(vary-meta assoc :source-mmap fdata))))
(comment
;;Overriding to use GC memory management. Default is stack and thus needs to be in
;;a call to resource/stack-resource-context.
(def fdata (mmap/mmap-file "test.arrow" {:resource-type :gc}))
(def messages (mapv parse-message (message-seq fdata)))
(assert (= 3 (count messages)))
(assert (= [:schema :dictionary-batch :record-batch] (mapv :message-type messages)))
(def schema (nth messages 0))
(def dict (nth messages 1))
(def record (nth messages 2))
(def dict-data (dictionary->strings dict))
(def dict-map {(:id dict-data) dict-data})
(def inplace-ds (records->ds schema dict-map record))
(require '[criterium.core :as crit])
(require '[tech.v2.datatype.functional :as dfn])
(require '[tech.resource :as resource])
(require '[tech.parallel.for :as parallel-for])
(require '[tech.v2.datatype.typecast :as typecast])
(defn fast-reduce-plus
^double [rdr]
(let [rdr (typecast/datatype->reader :float64 rdr)]
(parallel-for/indexed-map-reduce
(.lsize rdr)
(fn [^long start-idx ^long group-len]
(let [end-idx (long (+ start-idx group-len))]
(loop [idx (long start-idx)
result 0.0]
(if (< idx end-idx)
(recur (unchecked-inc idx)
(+ result (.read rdr idx)))
result))))
(partial reduce +))))
(defn sum-test-1
[]
(resource/stack-resource-context
(let [ds (read-dataset-inplace "big-stocks.feather")]
(fast-reduce-plus (ds "price")))))
;; Evaluation count : 96 in 6 samples of 16 calls.
;; Execution time mean : 7.955908 ms
;; Execution time std-deviation : 1.019668 ms
;; Execution time lower quantile : 6.706196 ms ( 2.5%)
;; Execution time upper quantile : 9.318124 ms (97.5%)
;; Overhead used : 2.377233 ns
(require '[tech.io :as io])
(defn sum-test-2
[]
(let [ds (io/get-nippy "big-stocks.nippy")]
(dfn/reduce-+ (ds "price"))))
;; Evaluation count : 12 in 6 samples of 2 calls.
;; Execution time mean : 86.257718 ms
;; Execution time std-deviation : 681.391723 µs
;; Execution time lower quantile : 85.376117 ms ( 2.5%)
;; Execution time upper quantile : 86.987293 ms (97.5%)
;; Overhead used : 2.635202 ns
(import '[org.apache.arrow.vector.ipc ArrowStreamReader ArrowStreamWriter ArrowFileReader])
(defn sum-test-3
[]
(with-open [istream (io/input-stream "big-stocks.feather")
reader (ArrowStreamReader. istream (arrow/allocator))]
(.loadNextBatch reader)
(fast-reduce-plus (.get (.getFieldVectors (.getVectorSchemaRoot reader))
2))))
;; Evaluation count : 6 in 6 samples of 1 calls.
;; Execution time mean : 104.142056 ms
;; Execution time std-deviation : 810.545821 µs
;; Execution time lower quantile : 103.241336 ms ( 2.5%)
;; Execution time upper quantile : 105.123550 ms (97.5%)
;; Overhead used : 2.377233 ns
(defn mean-test-4
[]
(with-open [istream (io/input-stream "big-stocks.feather")
reader (ArrowStreamReader. istream (arrow/allocator))]
(.loadNextBatch reader)
(let [^Float8Vector vecdata (.get
(.getFieldVectors (.getVectorSchemaRoot reader))
2)
n-elems (dtype/ecount vecdata)]
(dfn/mean (dtype/make-reader :float64 (dtype/ecount vecdata)
(.get vecdata idx))))))
;; Evaluation count : 6 in 6 samples of 1 calls.
;; Execution time mean : 170.486968 ms
;; Execution time std-deviation : 1.872698 ms
;; Execution time lower quantile : 168.327549 ms ( 2.5%)
;; Execution time upper quantile : 172.799712 ms (97.5%)
;; Overhead used : 2.635202 ns
(defn inplace-load
[]
(resource/stack-resource-context
(read-dataset-inplace "big-stocks.feather")
:ok))
;; Evaluation count : 4566 in 6 samples of 761 calls.
;; Execution time mean : 133.148490 µs
;; Execution time std-deviation : 1.476486 µs
;; Execution time lower quantile : 131.670752 µs ( 2.5%)
;; Execution time upper quantile : 134.852840 µs (97.5%)
;; Overhead used : 2.635202 ns
(defn nippy-load
[]
(io/get-nippy "big-stocks.nippy"))
;; Evaluation count : 12 in 6 samples of 2 calls.
;; Execution time mean : 62.058715 ms
;; Execution time std-deviation : 3.312573 ms
;; Execution time lower quantile : 58.691642 ms ( 2.5%)
;; Execution time upper quantile : 66.867313 ms (97.5%)
;; Overhead used : 2.635202 ns
;; Found 1 outliers in 6 samples (16.6667 %)
;; low-severe 1 (16.6667 %)
;; Variance from outliers : 14.1278 % Variance is moderately inflated by outliers
(defn arrow-stream-load
[]
(with-open [istream (io/input-stream "big-stocks.feather")
reader (ArrowStreamReader. istream (arrow/allocator))]
(.loadNextBatch reader)))
;; Evaluation count : 6 in 6 samples of 1 calls.
;; Execution time mean : 104.879396 ms
;; Execution time std-deviation : 1.227596 ms
;; Execution time lower quantile : 103.101944 ms ( 2.5%)
;; Execution time upper quantile : 106.109886 ms (97.5%)
;; Overhead used : 2.635202 ns
;;Fails to load the file...
(defn arrow-file-load
[]
(with-open [istream (java.io.RandomAccessFile. "big-stocks.file.feather" "r")
reader (ArrowFileReader. (.getChannel istream) (arrow/allocator))]
(.loadNextBatch reader)))
)