This repository has been archived by the owner on Jan 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 28
/
patch.diff
6401 lines (6305 loc) · 251 KB
/
patch.diff
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
diff --git a/3rdparty/mkldnn b/3rdparty/mkldnn
index 9910b48..08bd90c 160000
--- a/3rdparty/mkldnn
+++ b/3rdparty/mkldnn
@@ -1 +1 @@
-Subproject commit 9910b480296a0d1496db466531e56729b3922bbf
+Subproject commit 08bd90cca77683dd5d1c98068cea8b92ed05784d
diff --git a/3rdparty/sparse-matrix/Makefile b/3rdparty/sparse-matrix/Makefile
new file mode 100644
index 0000000..214312f
--- /dev/null
+++ b/3rdparty/sparse-matrix/Makefile
@@ -0,0 +1,21 @@
+CC = g++
+C = gcc
+MKLROOT = /opt/intel/mkl
+
+ifneq ($(USE_INTEL_PATH),)
+ MKLROOT = $(USE_INTEL_PATH)/mkl
+endif
+
+CFLAGS = -fpic -O2 -I/opt/intel/mkl/include -c -Wall -Werror -DMKL_ILP64 -m64 -std=c++11
+LDFLAGS = -Wl,--start-group -L${MKLROOT}/../compiler/lib/intel64 ${MKLROOT}/lib/intel64/libmkl_intel_ilp64.a ${MKLROOT}/lib/intel64/libmkl_intel_thread.a ${MKLROOT}/lib/intel64/libmkl_core.a -Wl,--end-group -liomp5 -lpthread -lm -ldl
+
+default: libsparse_matrix.so
+
+libsparse_matrix.so: sparse_matrix.o
+ $(CC) -shared -o libsparse_matrix.so sparse_matrix.o $(LDFLAGS)
+
+sparse_matrix.o: sparse_matrix.cc sparse_matrix.h
+ $(CC) $(CFLAGS) sparse_matrix.cc
+
+clean:
+ $(RM) libsparse_matrix.so *.o *~
diff --git a/3rdparty/sparse-matrix/sparse_matrix.cc b/3rdparty/sparse-matrix/sparse_matrix.cc
new file mode 100644
index 0000000..f402294
--- /dev/null
+++ b/3rdparty/sparse-matrix/sparse_matrix.cc
@@ -0,0 +1,45 @@
+#include <iostream>
+#include <string>
+#include <fstream>
+#include <mkl_spblas.h>
+#include "sparse_matrix.h"
+
+
+
+bool mkl_DotCsrDnsDns(SP_INT64* rows_start, SP_INT64* col_indx,
+ float* values, float* X, float* y,
+ int rows, int cols, int X_columns)
+{
+
+ sparse_index_base_t indexing = SPARSE_INDEX_BASE_ZERO;
+ sparse_status_t status;
+ sparse_matrix_t A = NULL;
+ sparse_layout_t layout = SPARSE_LAYOUT_ROW_MAJOR;
+ float one, zero;
+ one = (float)1.0;
+ zero = (float)0.0;
+
+ MKL_INT* rows_end = rows_start + 1;
+ status = mkl_sparse_s_create_csr(&A, indexing, rows, cols, rows_start, rows_end, col_indx, values);
+
+ if (status != SPARSE_STATUS_SUCCESS)
+ {
+ std::cout << "mkl_sparse_s_create_csr status :" << status << std::endl;
+ return false;
+ }
+ sparse_operation_t operation = SPARSE_OPERATION_NON_TRANSPOSE;
+ struct matrix_descr descrA;
+ descrA.type = SPARSE_MATRIX_TYPE_GENERAL;
+
+ status = mkl_sparse_s_mm(operation, one, A, descrA, layout, X, X_columns, X_columns, zero, y, X_columns);
+ if (status != SPARSE_STATUS_SUCCESS)
+ {
+ std::cout << "mkl_sparse_s_create_csr status :" << status << std::endl;
+ return false;
+ }
+
+ mkl_sparse_destroy(A);
+
+ return true;
+
+}
diff --git a/3rdparty/sparse-matrix/sparse_matrix.h b/3rdparty/sparse-matrix/sparse_matrix.h
new file mode 100644
index 0000000..93054a8
--- /dev/null
+++ b/3rdparty/sparse-matrix/sparse_matrix.h
@@ -0,0 +1,48 @@
+#ifndef MXNET_OPERATOR_SPARSE_MATRIX_INL_H_
+#define MXNET_OPERATOR_SPARSE_MATRIX_INL_H_
+
+
+#if (!defined(__INTEL_COMPILER)) & defined(_MSC_VER)
+#define SP_INT64 __int64
+#define SP_UINT64 unsigned __int64
+#else
+#define SP_INT64 long long int
+#define SP_UINT64 unsigned long long int
+#endif
+
+
+#if defined _WIN32 || defined __CYGWIN__
+ #ifdef BUILDING_DLL
+ #ifdef __GNUC__
+ #define SPM_API_PUBLIC __attribute__ ((dllexport))
+ #else
+ #define SPM_API_PUBLIC __declspec(dllexport) // Note: actually gcc seems to also supports this syntax.
+ #endif
+ #else
+ #ifdef __GNUC__
+ #define SPM_API_PUBLIC __attribute__ ((dllimport))
+ #else
+ #define SPM_API_PUBLIC __declspec(dllimport) // Note: actually gcc seems to also supports this syntax.
+ #endif
+ #endif
+ #define SPM_API_LOCAL
+#else
+ #if __GNUC__ >= 4
+ #define SPM_API_PUBLIC __attribute__ ((visibility ("default")))
+ #define SPM_API_LOCAL __attribute__ ((visibility ("hidden")))
+ #else
+ #define SPM_API_PUBLIC
+ #define SPM_API_LOCAL
+ #endif
+#endif
+
+
+
+extern "C"
+{
+ extern SPM_API_PUBLIC bool mkl_DotCsrDnsDns(SP_INT64* rows_start, SP_INT64* col_indx,
+ float* values, float* X, float* y, int rows, int cols, int X_columns);
+
+}
+
+#endif //MXNET_OPERATOR_SPARSE_MATRIX_INL_H_
\ No newline at end of file
diff --git a/Makefile b/Makefile
index 16ea59f..c8644bd 100644
--- a/Makefile
+++ b/Makefile
@@ -135,6 +135,12 @@ ifeq ($(USE_MKLDNN), 1)
LDFLAGS += -L$(MKLDNNROOT)/lib -lmkldnn -Wl,-rpath,'$${ORIGIN}'
endif
+ifeq ($(USE_BLAS), mkl)
+SPARSE_MATRIX_DIR = $(ROOTDIR)/3rdparty/sparse-matrix
+CFLAGS += -I$(SPARSE_MATRIX_DIR)
+LDFLAGS += -L$(SPARSE_MATRIX_DIR) -lsparse_matrix
+endif
+
# setup opencv
ifeq ($(USE_OPENCV), 1)
CFLAGS += -DMXNET_USE_OPENCV=1 $(shell pkg-config --cflags opencv)
diff --git a/ci/docker/install/ubuntu_mklml.sh b/ci/docker/install/ubuntu_mklml.sh
index 862e284..ba54bd4 100755
--- a/ci/docker/install/ubuntu_mklml.sh
+++ b/ci/docker/install/ubuntu_mklml.sh
@@ -21,5 +21,5 @@
# the whole docker cache for the image
set -ex
-wget -q --no-check-certificate -O /tmp/mklml.tgz https://github.com/intel/mkl-dnn/releases/download/v0.17-rc/mklml_lnx_2019.0.1.20180928.tgz
+wget -q --no-check-certificate -O /tmp/mklml.tgz https://github.com/intel/mkl-dnn/releases/download/v0.18-rc/mklml_lnx_2019.0.3.20190125.tgz
tar -zxf /tmp/mklml.tgz && cp -rf mklml_*/* /usr/local/ && rm -rf mklml_*
diff --git a/cmake/DownloadMKLML.cmake b/cmake/DownloadMKLML.cmake
index eabf861..5a2875b 100644
--- a/cmake/DownloadMKLML.cmake
+++ b/cmake/DownloadMKLML.cmake
@@ -19,15 +19,19 @@
message(STATUS "Downloading MKLML...")
-set(MKLDNN_RELEASE v0.17-rc)
-set(MKLML_RELEASE_FILE_SUFFIX 2019.0.1.20180928)
+set(MKLDNN_RELEASE v0.18-rc)
+set(MKLML_RELEASE_FILE_SUFFIX 2019.0.3.20190125)
+
+set(MKLDNN_WIN_MD5 88164189ff4f9ce8bcfd6065d4f2673d)
+set(MKLDNN_LNX_MD5 4e1a05d38491deb36001d62eae302920)
+set(MKLDNN_MAC_MD5 11a946c9623ef999145d6df92d803b2c)
if(MSVC)
set(MKL_NAME "mklml_win_${MKLML_RELEASE_FILE_SUFFIX}")
file(DOWNLOAD "https://github.com/intel/mkl-dnn/releases/download/${MKLDNN_RELEASE}/${MKL_NAME}.zip"
"${CMAKE_CURRENT_BINARY_DIR}/mklml/${MKL_NAME}.zip"
- EXPECTED_MD5 "443e661bdfd32dbbc99b460b43afceee" SHOW_PROGRESS)
+ EXPECTED_MD5 "${MKLDNN_WIN_MD5}" SHOW_PROGRESS)
file(DOWNLOAD "https://github.com/apache/incubator-mxnet/releases/download/utils/7z.exe"
"${CMAKE_CURRENT_BINARY_DIR}/mklml/7z2.exe"
EXPECTED_MD5 "E1CF766CF358F368EC97662D06EA5A4C" SHOW_PROGRESS)
@@ -47,7 +51,7 @@ elseif(APPLE)
file(DOWNLOAD "https://github.com/intel/mkl-dnn/releases/download/${MKLDNN_RELEASE}/${MKL_NAME}.tgz"
"${CMAKE_CURRENT_BINARY_DIR}/mklml/${MKL_NAME}.tgz"
- EXPECTED_MD5 "95f887af332205b1d15b392260003952" SHOW_PROGRESS)
+ EXPECTED_MD5 "${MKLDNN_MAC_MD5}" SHOW_PROGRESS)
execute_process(COMMAND "tar" "-xzf" "${CMAKE_CURRENT_BINARY_DIR}/mklml/${MKL_NAME}.tgz"
"-C" "${CMAKE_CURRENT_BINARY_DIR}/mklml/")
@@ -61,7 +65,7 @@ elseif(UNIX)
file(DOWNLOAD "https://github.com/intel/mkl-dnn/releases/download/${MKLDNN_RELEASE}/${MKL_NAME}.tgz"
"${CMAKE_CURRENT_BINARY_DIR}/mklml/${MKL_NAME}.tgz"
- EXPECTED_MD5 "a63abf155361322b9c03f8fc50f4f317" SHOW_PROGRESS)
+ EXPECTED_MD5 "${MKLDNN_LNX_MD5}" SHOW_PROGRESS)
execute_process(COMMAND "tar" "-xzf" "${CMAKE_CURRENT_BINARY_DIR}/mklml/${MKL_NAME}.tgz"
"-C" "${CMAKE_CURRENT_BINARY_DIR}/mklml/")
diff --git a/cpp-package/scripts/OpWrapperGenerator.py b/cpp-package/scripts/OpWrapperGenerator.py
index 1b5f8b5..c26c370 100644
--- a/cpp-package/scripts/OpWrapperGenerator.py
+++ b/cpp-package/scripts/OpWrapperGenerator.py
@@ -138,6 +138,8 @@ class Arg:
self.defaultString = 'Shape(' + self.defaultString[1:-1] + ")"
elif self.type == 'dmlc::optional<int>':
self.defaultString = self.type + '(' + self.defaultString + ')'
+ elif self.type == 'dmlc::optional<bool>':
+ self.defaultString = self.type + '(' + self.defaultString + ')'
elif typeString.startswith('caffe-layer-parameter'):
self.defaultString = 'textToCaffeLayerParameter(' + self.MakeCString(self.defaultString) + ')'
hasCaffe = True
diff --git a/docs/faq/env_var.md b/docs/faq/env_var.md
index c7d3b28..8d08e32 100644
--- a/docs/faq/env_var.md
+++ b/docs/faq/env_var.md
@@ -206,6 +206,12 @@ When USE_PROFILER is enabled in Makefile or CMake, the following environments ca
If no such algorithm exists given other constraints, MXNet will error out. This variable affects the choice
of CUDNN convolution algorithms. Please see [CUDNN developer guide](https://docs.nvidia.com/deeplearning/sdk/cudnn-developer-guide/index.html) for more details.
+* MXNET_CPU_PARALLEL_COPY_SIZE
+ - Values: Int ```(default=200000)```
+ - The minimum size to call parallel copy by OpenMP in CPU2CPU mode.
+ - When the array size is bigger than or equal to this threshold, NDArray::Copy(from, to) is implemented by OpenMP with the Recommended OMP Thread Count.
+ - When the array size is less than this threshold, NDArray::Copy(from , to)) is implemented by memcpy in single thread.
+
Settings for Minimum Memory Usage
---------------------------------
- Make sure ```min(MXNET_EXEC_NUM_TEMP, MXNET_GPU_WORKER_NTHREADS) = 1```
diff --git a/example/sparse/wide_deep_census_quantization/data.py b/example/sparse/wide_deep_census_quantization/data.py
new file mode 100644
index 0000000..d90dff5
--- /dev/null
+++ b/example/sparse/wide_deep_census_quantization/data.py
@@ -0,0 +1,143 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+# pylint: skip-file
+from csv import DictReader
+import os
+import mxnet as mx
+import numpy as np
+
+
+def get_uci_adult(data_dir, data_name, url):
+ if not os.path.isdir(data_dir):
+ os.mkdir(data_dir)
+ os.chdir(data_dir)
+ if (not os.path.exists(data_name)):
+ print("Dataset " + data_name + " not present. Downloading now ...")
+ os.system("wget %r" % url + data_name)
+ if "test" in data_name:
+ os.system("sed -i '1d' %r" % data_name)
+ print("Dataset " + data_name + " is now present.")
+ csr, dns, label = preprocess_uci_adult(data_name)
+ os.chdir("..")
+ return csr, dns, label
+
+max_dict = {'age': 90, 'education_num': 16, 'capital_gain': 99999, 'capital_loss': 4356, 'hours_per_week': 99}
+min_dict = {'age': 17, 'education_num': 1, 'capital_gain': 0, 'capital_loss': 0, 'hours_per_week': 1}
+
+def preprocess_uci_adult(data_name):
+ """Some tricks of feature engineering are adapted
+ from tensorflow's wide and deep tutorial.
+ """
+ csv_columns = [
+ "age", "workclass", "fnlwgt", "education", "education_num",
+ "marital_status", "occupation", "relationship", "race", "gender",
+ "capital_gain", "capital_loss", "hours_per_week", "native_country",
+ "income_bracket"
+ ]
+
+ vocabulary_dict = {
+ "gender": [
+ "Female", "Male"
+ ],
+ "education": [
+ "Bachelors", "HS-grad", "11th", "Masters", "9th",
+ "Some-college", "Assoc-acdm", "Assoc-voc", "7th-8th",
+ "Doctorate", "Prof-school", "5th-6th", "10th", "1st-4th",
+ "Preschool", "12th"
+ ],
+ "marital_status": [
+ "Married-civ-spouse", "Divorced", "Married-spouse-absent",
+ "Never-married", "Separated", "Married-AF-spouse", "Widowed"
+ ],
+ "relationship": [
+ "Husband", "Not-in-family", "Wife", "Own-child", "Unmarried",
+ "Other-relative"
+ ],
+ "workclass": [
+ "Self-emp-not-inc", "Private", "State-gov", "Federal-gov",
+ "Local-gov", "?", "Self-emp-inc", "Without-pay", "Never-worked"
+ ]
+ }
+ # wide columns
+ crossed_columns = [
+ ["education", "occupation"],
+ ["native_country", "occupation"],
+ ["age_buckets", "education", "occupation"],
+ ]
+ age_boundaries = [18, 25, 30, 35, 40, 45, 50, 55, 60, 65]
+ # deep columns
+ indicator_columns = ['workclass', 'education', 'gender', 'relationship']
+
+ embedding_columns = ['native_country', 'occupation']
+
+ continuous_columns = ['age', 'education_num', 'capital_gain', 'capital_loss', 'hours_per_week']
+ # income_bracket column is the label
+ labels = ["<", ">"]
+
+ hash_bucket_size = 1000
+ hash_bucket_int8 = 255
+ csr_ncols = len(crossed_columns) * hash_bucket_size
+ dns_ncols = len(continuous_columns) + len(embedding_columns)
+ for col in indicator_columns:
+ dns_ncols += len(vocabulary_dict[col])
+
+ label_list = []
+ csr_list = []
+ dns_list = []
+
+ with open(data_name) as f:
+ for row in DictReader(f, fieldnames=csv_columns):
+ label_list.append(labels.index(row['income_bracket'].strip()[0]))
+
+ for i, cols in enumerate(crossed_columns):
+ if cols[0] == "age_buckets":
+ age_bucket = np.digitize(float(row["age"]), age_boundaries)
+ s = '_'.join([row[col].strip() for col in cols[1:]])
+ s += '_' + str(age_bucket)
+ csr_list.append((i * hash_bucket_size + hash(s) % hash_bucket_size, 1.0))
+ else:
+ s = '_'.join([row[col].strip() for col in cols])
+ csr_list.append((i * hash_bucket_size + hash(s) % hash_bucket_size, 1.0))
+
+ dns_row = [0] * dns_ncols
+ dns_dim = 0
+ for col in embedding_columns:
+ dns_row[dns_dim] = hash(row[col].strip()) % hash_bucket_size
+ dns_dim += 1
+
+ for col in indicator_columns:
+ dns_row[dns_dim + vocabulary_dict[col].index(row[col].strip())] = 1.0
+ dns_dim += len(vocabulary_dict[col])
+ scale = 1.0 #this is adjustable to hit the good accuracy
+ for col in continuous_columns:
+ orig_range = float(max_dict[col] - min_dict[col])
+ dns_row[dns_dim] = (float(row[col].strip()) - min_dict[col]) * scale / orig_range
+ #dns_row[dns_dim] = float(row[col].strip())
+ dns_dim += 1
+
+ dns_list.append(dns_row)
+
+ data_list = [item[1] for item in csr_list]
+ indices_list = [item[0] for item in csr_list]
+ indptr_list = range(0, len(indices_list) + 1, len(crossed_columns))
+ # convert to ndarrays
+ csr = mx.nd.sparse.csr_matrix((data_list, indices_list, indptr_list),
+ shape=(len(label_list), hash_bucket_size * len(crossed_columns)))
+ dns = np.array(dns_list)
+ label = np.array(label_list)
+ return csr, dns, label
diff --git a/example/sparse/wide_deep_census_quantization/inference.py b/example/sparse/wide_deep_census_quantization/inference.py
new file mode 100644
index 0000000..92b0e06
--- /dev/null
+++ b/example/sparse/wide_deep_census_quantization/inference.py
@@ -0,0 +1,200 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import argparse
+import logging
+import os
+import time
+import mxnet as mx
+from mxnet import nd
+from mxnet.contrib.quantization import *
+from data import *
+from mxnet.base import check_call, _LIB
+
+def download_dataset(dataset_url, dataset_dir, logger=None):
+ if logger is not None:
+ logger.info('Downloading dataset for inference from %s to %s' % (dataset_url, dataset_dir))
+ mx.test_utils.download(dataset_url, dataset_dir)
+
+
+def load_model(symbol_file, param_file, logger=None):
+ cur_path = os.path.dirname(os.path.realpath(__file__))
+ symbol_file_path = os.path.join(cur_path, symbol_file)
+ if logger is not None:
+ logger.info('Loading symbol from file %s' % symbol_file_path)
+ symbol = mx.sym.load(symbol_file_path)
+
+ param_file_path = os.path.join(cur_path, param_file)
+ if logger is not None:
+ logger.info('Loading params from file %s' % param_file_path)
+ save_dict = nd.load(param_file_path)
+ arg_params = {}
+ aux_params = {}
+ for k, v in save_dict.items():
+ tp, name = k.split(':', 1)
+ if tp == 'arg':
+ arg_params[name] = v
+ if tp == 'aux':
+ aux_params[name] = v
+ return symbol, arg_params, aux_params
+
+
+def advance_data_iter(data_iter, n):
+ assert n >= 0
+ if n == 0:
+ return data_iter
+ has_next_batch = True
+ while has_next_batch:
+ try:
+ data_iter.next()
+ n -= 1
+ if n == 0:
+ return data_iter
+ except StopIteration:
+ has_next_batch = False
+
+
+
+# Related to feature engineering, please see preprocess in data.py
+ADULT = {
+ 'train': 'adult.data',
+ 'test': 'adult.test',
+ 'url': 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/',
+ 'num_linear_features': 3000,
+ 'num_embed_features': 2,
+ 'num_cont_features': 38,
+ 'embed_input_dims': [1000, 1000],
+ 'hidden_units': [32, 1024, 512, 256],
+}
+symbol_file = 'checkpoint-symbol.json'
+param_file = 'checkpoint-0009.params'
+#symbol_file = 'WD-quantized-162batches-naive-symbol.json'
+#param_file = 'WD-quantized-0000.params'
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='Score a model on a dataset')
+
+ parser.add_argument('--symbol-file', type=str, default=symbol_file, help='symbol file path')
+ parser.add_argument('--param-file', type=str, default=param_file, help='param file path')
+ parser.add_argument('--batch-size', type=int, default=1024)
+ parser.add_argument('--label-name', type=str, default='softmax_label')
+ parser.add_argument('--accuracy', type=bool, default=False)
+ parser.add_argument('--shuffle-dataset', action='store_true', default=True,
+ help='shuffle the calibration dataset')
+ parser.add_argument('--num-omp-threads', type=int, default=28)
+
+ args = parser.parse_args()
+
+
+ ctx = mx.cpu()
+
+
+ logging.basicConfig()
+ logger = logging.getLogger('logger')
+ logger.setLevel(logging.INFO)
+ if args.accuracy == True:
+ logger.info('Accuracy Mode')
+ else:
+ logger.info('Performance Mode')
+
+ symbol_file = args.symbol_file
+ param_file = args.param_file
+
+
+ batch_size = args.batch_size
+ logger.info('batch size = %d for inference' % batch_size)
+ label_name = args.label_name
+ logger.info('label_name = %s' % label_name)
+ data_dir = os.path.join(os.getcwd(), 'data')
+ val_data = os.path.join(data_dir, ADULT['test'])
+
+ if args.accuracy == False:
+ val_csr_np = np.load('train_csr.npy')
+ val_csr = mx.nd.sparse.csr_matrix(val_csr_np)
+ val_dns = np.load('train_dns.npy')
+ val_label = np.load('train_label.npy')
+ else:
+ val_csr_np = np.load('val_csr.npy')
+ val_csr = mx.nd.sparse.csr_matrix(val_csr_np)
+ val_dns = np.load('val_dns.npy')
+ val_label = np.load('val_label.npy')
+
+ # creating data iterator
+ data = mx.io.NDArrayIter({'csr_data': val_csr, 'dns_data': val_dns},
+ {'softmax_label': val_label}, batch_size,
+ shuffle=False, last_batch_handle='discard')
+
+ # loading model
+ sym, arg_params, aux_params = load_model(symbol_file, param_file, logger)
+
+ # make sure that fp32 inference works on the same images as calibrated quantized model
+
+ logger.info('Running model %s for inference' % symbol_file)
+
+ acc_m = mx.metric.create('acc')
+ mod = mx.mod.Module(symbol=sym, context=ctx, data_names=['csr_data', 'dns_data'], label_names=[label_name, ])
+ mod.bind(for_training=False,
+ data_shapes=data.provide_data,
+ label_shapes=data.provide_label)
+ mod.set_params(arg_params, aux_params)
+
+ check_call(_LIB.MXSetNumOMPThreads(ctypes.c_int(args.num_omp_threads)))
+ batch_data = []
+ nbatch = 0
+ for batch in data:
+ batch_data.append(batch)
+ #data warm up
+ wi = 50
+ i = 0
+ for batch in batch_data:
+ if i < wi:
+ mod.forward(batch, is_train=False)
+ i += 1
+ else:
+ break
+ data.hard_reset()
+ mx.nd.waitall()
+
+ collector = None
+
+ #real run
+ if "DO_WIDE_DEEP_PROFILING" in os.environ:
+ print("wide_deep profiling start !!!!!!!!!!!!!")
+ mx.profiler.set_config(profile_symbolic=True, profile_imperative=True, profile_memory=False, profile_api=False)
+ mx.profiler.set_state('run')
+
+ nbatch = 0
+ tic = time.time()
+ for batch in batch_data:
+ nbatch += 1
+ mod.forward(batch, is_train=False)
+ if args.accuracy == True:
+ for output in mod.get_outputs():
+ output.wait_to_read()
+ mod.update_metric(acc_m, batch.label)
+ else:
+ mx.nd.waitall()
+ speed = nbatch * batch_size / (time.time() - tic)
+ logger.info("Run [%d] Batchs \tSpeed: %.2f samples/sec", nbatch, speed)
+
+ if args.accuracy == True:
+ logger.info(acc_m.get())
+ if "DO_WIDE_DEEP_PROFILING" in os.environ :
+ print("wide_deep profiling end !")
+ mx.profiler.set_state('stop')
+ profiler_info = mx.profiler.dumps()
+ print(profiler_info)
diff --git a/example/sparse/wide_deep_census_quantization/model.py b/example/sparse/wide_deep_census_quantization/model.py
new file mode 100644
index 0000000..7e6e216
--- /dev/null
+++ b/example/sparse/wide_deep_census_quantization/model.py
@@ -0,0 +1,58 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import mxnet as mx
+
+
+def wide_deep_model(num_linear_features, num_embed_features, num_cont_features,
+ input_dims, hidden_units):
+ # wide model
+ csr_data = mx.symbol.Variable("csr_data", stype='csr')
+ label = mx.symbol.Variable("softmax_label")
+
+ norm_init = mx.initializer.Normal(sigma=0.01)
+ # weight with row_sparse storage type to enable sparse gradient updates
+ weight = mx.symbol.Variable("linear_weight", shape=(num_linear_features, hidden_units[3]),
+ init=norm_init, stype='row_sparse')
+ bias = mx.symbol.Variable("linear_bias", shape=(hidden_units[3],))
+ dot = mx.symbol.sparse.dot(csr_data, weight)
+ linear_out = mx.symbol.broadcast_add(dot, bias)
+ # deep model
+ dns_data = mx.symbol.Variable("dns_data")
+ # embedding features
+ x = mx.symbol.slice(data=dns_data, begin=(0, 0),
+ end=(None, num_embed_features))
+ embeds = mx.symbol.split(data=x, num_outputs=num_embed_features, squeeze_axis=1)
+ # continuous features
+ x = mx.symbol.slice(data=dns_data, begin=(0, num_embed_features),
+ end=(None, num_embed_features + num_cont_features))
+ features = [x]
+
+ for i, embed in enumerate(embeds):
+ embed_weight = mx.symbol.Variable('embed_%d_weight' % i, stype='row_sparse')
+ features.append(mx.symbol.sparse.Embedding(data=embed, weight=embed_weight,
+ input_dim=input_dims[i], output_dim=hidden_units[0], sparse_grad=True))
+
+ hidden = mx.symbol.concat(*features, dim=1)
+ hidden = mx.symbol.FullyConnected(data=hidden, num_hidden=hidden_units[1])
+ hidden = mx.symbol.Activation(data=hidden, act_type='relu')
+ hidden = mx.symbol.FullyConnected(data=hidden, num_hidden=hidden_units[2])
+ hidden = mx.symbol.Activation(data=hidden, act_type='relu')
+ deep_out = mx.symbol.FullyConnected(data=hidden, num_hidden=hidden_units[3])
+
+ out = mx.symbol.SoftmaxOutput(linear_out + deep_out, label, name='model')
+ return out
diff --git a/example/sparse/wide_deep_census_quantization/quant_accuracy.sh b/example/sparse/wide_deep_census_quantization/quant_accuracy.sh
new file mode 100755
index 0000000..dede7b8
--- /dev/null
+++ b/example/sparse/wide_deep_census_quantization/quant_accuracy.sh
@@ -0,0 +1,2 @@
+python inference.py --accuracy=True --symbol-file=WD-quantized-162batches-naive-symbol.json --param-file=WD-quantized-0000.params
+
diff --git a/example/sparse/wide_deep_census_quantization/qunatization_settings/all.py b/example/sparse/wide_deep_census_quantization/qunatization_settings/all.py
new file mode 100644
index 0000000..6cd6719
--- /dev/null
+++ b/example/sparse/wide_deep_census_quantization/qunatization_settings/all.py
@@ -0,0 +1,10 @@
+
+def get_qsettings():
+ settings = {
+ 'excluse': None,
+ 'quantized_alg_setting': {
+ 'fullyconnected1': ['int8', 'naive'],
+ 'fullyconnected1': ['uint8', 'naive'],
+ 'fullyconnected2': ['uint8', 'naive'], },
+ }
+ return settings
\ No newline at end of file
diff --git a/example/sparse/wide_deep_census_quantization/qunatization_settings/fc1_fc2.py b/example/sparse/wide_deep_census_quantization/qunatization_settings/fc1_fc2.py
new file mode 100644
index 0000000..2af04cf
--- /dev/null
+++ b/example/sparse/wide_deep_census_quantization/qunatization_settings/fc1_fc2.py
@@ -0,0 +1,9 @@
+
+def get_qsettings():
+ settings = {
+ 'excluse': ['fullyconnected0'],
+ 'quantized_alg_setting': {
+ 'fullyconnected1': ['uint8', 'naive'],
+ 'fullyconnected2': ['uint8', 'naive'], },
+ }
+ return settings
\ No newline at end of file
diff --git a/example/sparse/wide_deep_census_quantization/qunatization_settings/fullyconnected2.py b/example/sparse/wide_deep_census_quantization/qunatization_settings/fullyconnected2.py
new file mode 100644
index 0000000..ada3ab6
--- /dev/null
+++ b/example/sparse/wide_deep_census_quantization/qunatization_settings/fullyconnected2.py
@@ -0,0 +1,8 @@
+
+def get_qsettings():
+ settings = {
+ 'excluse': ['fullyconnected0', 'fullyconnected1'],
+ 'quantized_alg_setting': {'fullyconnected2': ['uint8', 'naive'],
+ },
+ }
+ return settings
\ No newline at end of file
diff --git a/example/sparse/wide_deep_census_quantization/train.py b/example/sparse/wide_deep_census_quantization/train.py
new file mode 100644
index 0000000..204b2c6
--- /dev/null
+++ b/example/sparse/wide_deep_census_quantization/train.py
@@ -0,0 +1,132 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import mxnet as mx
+from mxnet.test_utils import *
+from data import *
+from model import *
+import argparse
+import os
+
+
+parser = argparse.ArgumentParser(description="Run sparse wide and deep classification ",
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter)
+parser.add_argument('--num-epoch', type=int, default=10,
+ help='number of epochs to train')
+parser.add_argument('--batch-size', type=int, default=100,
+ help='number of examples per batch')
+parser.add_argument('--lr', type=float, default=0.001,
+ help='learning rate')
+parser.add_argument('--cuda', action='store_true', default=False,
+ help='Train on GPU with CUDA')
+parser.add_argument('--optimizer', type=str, default='adam',
+ help='what optimizer to use',
+ choices=["ftrl", "sgd", "adam"])
+parser.add_argument('--log-interval', type=int, default=100,
+ help='number of batches to wait before logging training status')
+
+
+# Related to feature engineering, please see preprocess in data.py
+ADULT = {
+ 'train': 'adult.data',
+ 'test': 'adult.test',
+ 'url': 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/',
+ 'num_linear_features': 3000,
+ 'num_embed_features': 2,
+ 'num_cont_features': 38,
+ 'embed_input_dims': [1000, 1000],
+ 'hidden_units': [32, 1024, 512, 256],
+}
+
+
+if __name__ == '__main__':
+ import logging
+ head = '%(asctime)-15s %(message)s'
+ logging.basicConfig(level=logging.INFO, format=head)
+
+ # arg parser
+ args = parser.parse_args()
+ logging.info(args)
+ num_epoch = args.num_epoch
+ batch_size = args.batch_size
+ optimizer = args.optimizer
+ log_interval = args.log_interval
+ lr = args.lr
+ ctx = mx.gpu(0) if args.cuda else mx.cpu()
+
+ # dataset
+ data_dir = os.path.join(os.getcwd(), 'data')
+ train_data = os.path.join(data_dir, ADULT['train'])
+ val_data = os.path.join(data_dir, ADULT['test'])
+ train_csr, train_dns, train_label = get_uci_adult(data_dir, ADULT['train'], ADULT['url'])
+ val_csr, val_dns, val_label = get_uci_adult(data_dir, ADULT['test'], ADULT['url'])
+ np.save('train_csr', train_csr.asnumpy())
+ np.save('train_dns', train_dns)
+ np.save('train_label', train_label)
+ np.save('val_csr', val_csr.asnumpy())
+ np.save('val_dns', val_dns)
+ np.save('val_label', val_label)
+
+ model = wide_deep_model(ADULT['num_linear_features'], ADULT['num_embed_features'],
+ ADULT['num_cont_features'], ADULT['embed_input_dims'],
+ ADULT['hidden_units'])
+
+ # data iterator
+ train_data = mx.io.NDArrayIter({'csr_data': train_csr, 'dns_data': train_dns},
+ {'softmax_label': train_label}, batch_size,
+ shuffle=True, last_batch_handle='discard')
+ eval_data = mx.io.NDArrayIter({'csr_data': val_csr, 'dns_data': val_dns},
+ {'softmax_label': val_label}, batch_size,
+ shuffle=True, last_batch_handle='discard')
+
+ # module
+ mod = mx.mod.Module(symbol=model, context=ctx ,data_names=['csr_data', 'dns_data'],
+ label_names=['softmax_label'])
+ mod.bind(data_shapes=train_data.provide_data, label_shapes=train_data.provide_label)
+ mod.init_params()
+ optim = mx.optimizer.create(optimizer, learning_rate=lr, rescale_grad=1.0/batch_size)
+ mod.init_optimizer(optimizer=optim)
+ # use accuracy as the metric
+ metric = mx.metric.create(['acc'])
+ # get the sparse weight parameter
+ speedometer = mx.callback.Speedometer(batch_size, log_interval)
+
+ logging.info('Training started ...')
+
+ data_iter = iter(train_data)
+ for epoch in range(num_epoch):
+ nbatch = 0
+ metric.reset()
+ for batch in data_iter:
+ nbatch += 1
+ mod.forward_backward(batch)
+ # update all parameters (including the weight parameter)
+ mod.update()
+ # update training metric
+ mod.update_metric(metric, batch.label)
+ speedometer_param = mx.model.BatchEndParam(epoch=epoch, nbatch=nbatch,
+ eval_metric=metric, locals=locals())
+ speedometer(speedometer_param)
+ # evaluate metric on validation dataset
+ score = mod.score(eval_data, ['acc'])
+ logging.info('epoch %d, accuracy = %s' % (epoch, score[0][1]))
+
+ mod.save_checkpoint("checkpoint", epoch, save_optimizer_states=True)
+ # reset the iterator for next pass of data
+ data_iter.reset()
+
+ logging.info('Training completed.')
diff --git a/example/sparse/wide_deep_census_quantization/wd_gen_qsym_mkldnn.py b/example/sparse/wide_deep_census_quantization/wd_gen_qsym_mkldnn.py
new file mode 100644
index 0000000..a609d92
--- /dev/null
+++ b/example/sparse/wide_deep_census_quantization/wd_gen_qsym_mkldnn.py
@@ -0,0 +1,169 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import argparse
+import os
+import logging
+import mxnet as mx
+from mxnet import nd
+from mxnet.contrib.quantization import *
+from mxnet.base import SymbolHandle, check_call, _LIB, mx_uint, c_str_array
+import ctypes
+
+
+
+def load_model(symbol_file, param_file, logger=None):
+ cur_path = os.path.dirname(os.path.realpath(__file__))
+ symbol_file_path = os.path.join(cur_path, symbol_file)
+ if logger is not None:
+ logger.info('Loading symbol from file %s' % symbol_file_path)
+ symbol = mx.sym.load(symbol_file_path)
+
+ param_file_path = os.path.join(cur_path, param_file)
+ if logger is not None:
+ logger.info('Loading params from file %s' % param_file_path)
+ save_dict = nd.load(param_file_path)
+ arg_params = {}
+ aux_params = {}
+ for k, v in save_dict.items():
+ tp, name = k.split(':', 1)
+ if tp == 'arg':
+ arg_params[name] = v
+ if tp == 'aux':
+ aux_params[name] = v
+ return symbol, arg_params, aux_params
+
+
+def save_symbol(fname, sym, logger=None):
+ if logger is not None:
+ logger.info('Saving symbol into file at %s' % fname)
+ sym.save(fname)
+
+
+def save_params(fname, arg_params, aux_params, logger=None):
+ if logger is not None:
+ logger.info('Saving params into file at %s' % fname)
+ save_dict = {('arg:%s' % k): v.as_in_context(cpu()) for k, v in arg_params.items()}
+ save_dict.update({('aux:%s' % k): v.as_in_context(cpu()) for k, v in aux_params.items()})
+ mx.nd.save(fname, save_dict)
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='Generate a calibrated quantized model from a FP32 model with Intel MKL-DNN support')
+ parser.add_argument('--batch-size', type=int, default=32)
+ parser.add_argument('--label-name', type=str, default='softmax_label')
+ parser.add_argument('--num-calib-batches', type=int, default=162,
+ help='number of batches for calibration')
+ parser.add_argument('--calib-mode', type=str, default='naive',
+ help='calibration mode used for generating calibration table for the quantized symbol; supports'
+ ' 1. none: no calibration will be used. The thresholds for quantization will be calculated'
+ ' on the fly. This will result in inference speed slowdown and loss of accuracy'
+ ' in general.'
+ ' 2. naive: simply take min and max values of layer outputs as thresholds for'
+ ' quantization. In general, the inference accuracy worsens with more examples used in'
+ ' calibration. It is recommended to use `entropy` mode as it produces more accurate'
+ ' inference results.'
+ ' 3. entropy: calculate KL divergence of the fp32 output and quantized output for optimal'
+ ' thresholds. This mode is expected to produce the best inference accuracy of all three'
+ ' kinds of quantized models if the calibration dataset is representative enough of the'
+ ' inference dataset.')
+ parser.add_argument('--quantized-dtype', type=str, default='uint8',
+ choices=['int8', 'uint8'],
+ help='quantization destination data type for input data')
+ parser.add_argument('--enable-calib-quantize', type=bool, default=True,
+ help='If enabled, the quantize op will '
+ 'be calibrated offline if calibration mode is '
+ 'enabled')
+ args = parser.parse_args()
+ ctx = mx.cpu(0)
+ logging.basicConfig()
+ logger = logging.getLogger('logger')
+ logger.setLevel(logging.INFO)
+
+ calib_mode = args.calib_mode
+ logger.info('calibration mode set to %s' % calib_mode)
+ batch_size = args.batch_size
+
+ train_csr_np = np.load('train_csr.npy')
+ train_csr = mx.nd.sparse.csr_matrix(train_csr_np)
+ train_dns = np.load('train_dns.npy')
+ train_label = np.load('train_label.npy')
+
+ val_csr_np = np.load('val_csr.npy')
+ val_csr = mx.nd.sparse.csr_matrix(val_csr_np)
+ val_dns = np.load('val_dns.npy')
+ val_label = np.load('val_label.npy')
+ # creating data iterator
+
+ # creating data iterator
+ data = mx.io.NDArrayIter({'csr_data': val_csr, 'dns_data': val_dns},
+ {'softmax_label': val_label}, batch_size,
+ shuffle=True, last_batch_handle='discard')
+ # loading model
+ sym, arg_params, aux_params = load_model('checkpoint-symbol.json', 'checkpoint-0009.params', logger)
+ sym = sym.get_backend_symbol('MKLDNN_PARALLEL_EMBEDDING')
+
+ # get batch size
+ batch_size = args.batch_size
+ logger.info('batch size = %d for calibration' % batch_size)
+
+ # get number of batches for calibration
+ num_calib_batches = args.num_calib_batches
+ if calib_mode == 'none':
+ logger.info('skip calibration step as calib_mode is none')
+ else:
+ logger.info('number of batches = %d for calibration' % num_calib_batches)
+
+
+
+ label_name = args.label_name
+ logger.info('label_name = %s' % label_name)
+
+ excluded_sym_names = None
+ prefix = 'WD'
+ epoch=0