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
|
%global _empty_manifest_terminate_build 0
Name: python-sparktorch
Version: 0.2.0
Release: 1
Summary: Distributed training of PyTorch networks on Apache Spark with ML Pipeline support
License: MIT
URL: https://github.com/dmmiller612/sparktorch
Source0: https://mirrors.nju.edu.cn/pypi/web/packages/15/f6/ab9a7187033d0ccc8a7a765a836f2b4f97c0d6a38b399cbf8eab1c5cfb19/sparktorch-0.2.0.tar.gz
BuildArch: noarch
Requires: python3-torch
Requires: python3-flask
Requires: python3-requests
Requires: python3-dill
%description
# SparkTorch
[](https://travis-ci.org/dmmiller612/sparktorch)
[](https://github.com/dmmiller612/sparktorch)
<img src="https://img.shields.io/pypi/v/sparktorch.svg" />

This is an implementation of Pytorch on Apache Spark. The goal of this library is to provide a simple, understandable interface
in distributing the training of your Pytorch model on Spark. With SparkTorch, you can easily integrate your deep
learning model with a ML Spark Pipeline. Underneath the hood, SparkTorch offers two distributed training approaches
through tree reductions and a parameter server. Through the api, the user can specify the style of training, whether
that is distributed synchronous or hogwild.
## Why should I use this?
Like SparkFlow, SparkTorch's main objective is to seamlessly work with Spark's ML Pipelines. This library provides three
core components:
* Data parallel distributed training for large datasets. SparkTorch offers distributed synchronous and asynchronous training methodologies.
This is useful for training very large datasets that do not fit into a single machine.
* Full integration with Spark's ML library. This ensures that you can save and load pipelines with your trained model.
* Inference. With SparkTorch, you can load your existing trained model and run inference on billions of records
in parallel.
On top of these features, SparkTorch can utilize barrier execution, ensuring that all executors run concurrently during
training (This is required for synchronous training approaches).
## Install
Install SparkTorch via pip: `pip install sparktorch`
SparkTorch requires Apache Spark >= 2.4.4, and has only been tested on PyTorch versions >= 1.3.0.
## Full Basic Example
```python
from sparktorch import serialize_torch_obj, SparkTorch
import torch
import torch.nn as nn
from pyspark.ml.feature import VectorAssembler
from pyspark.sql import SparkSession
from pyspark.ml.pipeline import Pipeline
spark = SparkSession.builder.appName("examples").master('local[2]').getOrCreate()
df = spark.read.option("inferSchema", "true").csv('mnist_train.csv').coalesce(2)
network = nn.Sequential(
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 256),
nn.ReLU(),
nn.Linear(256, 10),
nn.Softmax(dim=1)
)
# Build the pytorch object
torch_obj = serialize_torch_obj(
model=network,
criterion=nn.CrossEntropyLoss(),
optimizer=torch.optim.Adam,
lr=0.0001
)
# Setup features
vector_assembler = VectorAssembler(inputCols=df.columns[1:785], outputCol='features')
# Create a SparkTorch Model with torch distributed. Barrier execution is on by default for this mode.
spark_model = SparkTorch(
inputCol='features',
labelCol='_c0',
predictionCol='predictions',
torchObj=torch_obj,
iters=50,
verbose=1
)
# Can be used in a pipeline and saved.
p = Pipeline(stages=[vector_assembler, spark_model]).fit(df)
p.save('simple_dnn')
```
## Run the Examples
You can run the examples through docker by issuing the following commands at the root of the repository:
```bash
make docker-build
make docker-run-dnn
make docker-run-cnn
```
For the cnn example, you will need to give your docker container at least 8gb of memory.
## Documentation
This is a small documentation section on how to SparkTorch. Please look at the examples library for more details.
#### Creating a Torch Object
To create a Torch object for training, you will need to utilize the `serialize_torch_obj` from SparkTorch. To do so,
simply add your network, loss criterion, the optimizer class, and any options as a dictionary to supply to the optimizer
(such as learning rate). A simple example of this is:
```python
from sparktorch import serialize_torch_obj
torch_obj = serialize_torch_obj(
model=network,
criterion=nn.CrossEntropyLoss(),
optimizer=torch.optim.Adam,
lr=0.0001
)
```
When training neural networks on Spark, one issue that many face is OOM errors. To avoid this issue on the driver, you
can create a torch object that is only initialized on the worker nodes. To create this object, you can set up the
following:
```python
from sparktorch import serialize_torch_obj_lazy
torch_obj = serialize_torch_obj_lazy(
model=Network,
criterion=nn.CrossEntropyLoss,
optimizer=torch.optim.Adam,
optimizer_params={'lr': 0.001},
model_parameters={'some_model_param': 5}
)
```
The Network in the above example must be a nn.module pytorch class. If you need parameters passed into the constructor,
you can use the `model_parameters` parameter. The item will be passed in as **kwargs to the constructor.
NOTE: One thing to remember is that if your network is not a sequential, it will need to be saved in a separate file and
available in the python path. An example of this can be found in `simple_cnn.py`.
#### Training Options
There are two main training options with SparkTorch: `async` and `hogwild`. The async mode utilizes the torch distributed
package, ensuring that the networks are in sync through each iteration. This is the most supported version. When using
this option, you will need to be aware that barrier execution is enforced, meaning that the parallelism will need to match
the partitions.
The Hogwild approach utilizes a Flask Service underneath the hood. When using Hogwild, it is strongly recommended that you use the
`useBarrier` option to force barrier execution. Below are a list of parameters to SparkTorch and their meaning.
```
inputCol: Standard Spark InputCol that must be a Vector.
labelCol: Standard Spark Label column. Can be null.
torchObj: The TorchObj which is described in the `Creating a Torch Object` section.
iters: Number of iterations to run per partition.
predictionCol: The standard spark prediction column for the dataframe.
partitions: Ability to repartition during training.
acquireLock: Used in Hogwild only. Forces locking on the server.
verbose: Describes whether you want real time logging
partitionShuffles: Only used in Hogwild. Will reshuffle data after completing training.
port: Only used in hogwild. Server port.
useBarrier: Only used in hogwild. Describes whether you want barrier execution. (Async mode uses barrier by default)
useVectorOut: Boolean to describe if you want the model output to be a vector (Defaults to float).
earlyStopPatience: If greater than 0, it will enforce early stopping based on validation.
miniBatch: Minibatch size for training per iteration. (Randomly shuffled)
validationPct: Percentage to use for validation.
mode: which training mode to use. `synchronous` leverages torch distributed. `hogwild` currently uses the flask service.
device: Supply 'cpu' or 'cuda'
```
#### Saving and Loading Pipelines
Since saving and loading custom ML Transformers in pure python has not been implemented in PySpark, an extension has been
added here to make that possible. In order to save a Pyspark Pipeline with Apache Spark, one will need to use the overwrite function:
```python
p = Pipeline(stages=[va, encoded, spark_model]).fit(df)
p.write().overwrite().save("location")
```
For loading, a Pipeline wrapper has been provided in the pipeline_utils file. An example is below:
```python
from sparktorch import PysparkPipelineWrapper
from pyspark.ml.pipeline import PipelineModel
p = PysparkPipelineWrapper.unwrap(PipelineModel.load('location'))
```
Then you can perform predictions, etc with:
```python
predictions = p.transform(df)
```
#### Getting the Pytorch model from the training session
If you just want to get the Pytorch model after training, you can execute the following code:
```python
stm = SparkTorch(
inputCol='features',
labelCol='label',
predictionCol='predictions',
torchObj=network_with_params,
verbose=1,
iters=5
).fit(data)
py_model = stm.getPytorchModel()
```
#### Using a pretrained Pytorch model for inference
If you already have a trained Pytorch model, you can attach it your existing pipeline by directly creating a SparkTorchModel.
This can be done by running the following:
```python
from sparktorch import create_spark_torch_model
net = ... # Pretrained Network
spark_torch_model = create_spark_torch_model(
net,
inputCol='features',
predictionCol='predictions'
)
```
## Running
One big thing to remember is to add the `--executor cores 1` option to spark to ensure
each executor is only training one copy of the network. This will especially be needed for gpu training.
## Contributing
Contributions are always welcome. This could be fixing a bug, changing documentation, or adding a new feature. To test
new changes against existing tests, we have provided a Docker container which takes in an argument of the python version.
This allows the user to check their work before pushing to Github, where travis-ci will run.
For python 3.6
```
docker build -t local-test --build-arg PYTHON_VERSION=3.6 .
docker run --rm local-test:latest bash -i -c "pytest"
```
## Literature and Inspiration
* Distributed training: http://seba1511.net/dist_blog/
* HOGWILD!: A Lock-Free Approach to Parallelizing Stochastic Gradient Descent: https://arxiv.org/pdf/1106.5730.pdf
* Scaling Distributed Machine Learning with the Parameter Server: https://www.cs.cmu.edu/~muli/file/parameter_server_osdi14.pdf
%package -n python3-sparktorch
Summary: Distributed training of PyTorch networks on Apache Spark with ML Pipeline support
Provides: python-sparktorch
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-sparktorch
# SparkTorch
[](https://travis-ci.org/dmmiller612/sparktorch)
[](https://github.com/dmmiller612/sparktorch)
<img src="https://img.shields.io/pypi/v/sparktorch.svg" />

This is an implementation of Pytorch on Apache Spark. The goal of this library is to provide a simple, understandable interface
in distributing the training of your Pytorch model on Spark. With SparkTorch, you can easily integrate your deep
learning model with a ML Spark Pipeline. Underneath the hood, SparkTorch offers two distributed training approaches
through tree reductions and a parameter server. Through the api, the user can specify the style of training, whether
that is distributed synchronous or hogwild.
## Why should I use this?
Like SparkFlow, SparkTorch's main objective is to seamlessly work with Spark's ML Pipelines. This library provides three
core components:
* Data parallel distributed training for large datasets. SparkTorch offers distributed synchronous and asynchronous training methodologies.
This is useful for training very large datasets that do not fit into a single machine.
* Full integration with Spark's ML library. This ensures that you can save and load pipelines with your trained model.
* Inference. With SparkTorch, you can load your existing trained model and run inference on billions of records
in parallel.
On top of these features, SparkTorch can utilize barrier execution, ensuring that all executors run concurrently during
training (This is required for synchronous training approaches).
## Install
Install SparkTorch via pip: `pip install sparktorch`
SparkTorch requires Apache Spark >= 2.4.4, and has only been tested on PyTorch versions >= 1.3.0.
## Full Basic Example
```python
from sparktorch import serialize_torch_obj, SparkTorch
import torch
import torch.nn as nn
from pyspark.ml.feature import VectorAssembler
from pyspark.sql import SparkSession
from pyspark.ml.pipeline import Pipeline
spark = SparkSession.builder.appName("examples").master('local[2]').getOrCreate()
df = spark.read.option("inferSchema", "true").csv('mnist_train.csv').coalesce(2)
network = nn.Sequential(
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 256),
nn.ReLU(),
nn.Linear(256, 10),
nn.Softmax(dim=1)
)
# Build the pytorch object
torch_obj = serialize_torch_obj(
model=network,
criterion=nn.CrossEntropyLoss(),
optimizer=torch.optim.Adam,
lr=0.0001
)
# Setup features
vector_assembler = VectorAssembler(inputCols=df.columns[1:785], outputCol='features')
# Create a SparkTorch Model with torch distributed. Barrier execution is on by default for this mode.
spark_model = SparkTorch(
inputCol='features',
labelCol='_c0',
predictionCol='predictions',
torchObj=torch_obj,
iters=50,
verbose=1
)
# Can be used in a pipeline and saved.
p = Pipeline(stages=[vector_assembler, spark_model]).fit(df)
p.save('simple_dnn')
```
## Run the Examples
You can run the examples through docker by issuing the following commands at the root of the repository:
```bash
make docker-build
make docker-run-dnn
make docker-run-cnn
```
For the cnn example, you will need to give your docker container at least 8gb of memory.
## Documentation
This is a small documentation section on how to SparkTorch. Please look at the examples library for more details.
#### Creating a Torch Object
To create a Torch object for training, you will need to utilize the `serialize_torch_obj` from SparkTorch. To do so,
simply add your network, loss criterion, the optimizer class, and any options as a dictionary to supply to the optimizer
(such as learning rate). A simple example of this is:
```python
from sparktorch import serialize_torch_obj
torch_obj = serialize_torch_obj(
model=network,
criterion=nn.CrossEntropyLoss(),
optimizer=torch.optim.Adam,
lr=0.0001
)
```
When training neural networks on Spark, one issue that many face is OOM errors. To avoid this issue on the driver, you
can create a torch object that is only initialized on the worker nodes. To create this object, you can set up the
following:
```python
from sparktorch import serialize_torch_obj_lazy
torch_obj = serialize_torch_obj_lazy(
model=Network,
criterion=nn.CrossEntropyLoss,
optimizer=torch.optim.Adam,
optimizer_params={'lr': 0.001},
model_parameters={'some_model_param': 5}
)
```
The Network in the above example must be a nn.module pytorch class. If you need parameters passed into the constructor,
you can use the `model_parameters` parameter. The item will be passed in as **kwargs to the constructor.
NOTE: One thing to remember is that if your network is not a sequential, it will need to be saved in a separate file and
available in the python path. An example of this can be found in `simple_cnn.py`.
#### Training Options
There are two main training options with SparkTorch: `async` and `hogwild`. The async mode utilizes the torch distributed
package, ensuring that the networks are in sync through each iteration. This is the most supported version. When using
this option, you will need to be aware that barrier execution is enforced, meaning that the parallelism will need to match
the partitions.
The Hogwild approach utilizes a Flask Service underneath the hood. When using Hogwild, it is strongly recommended that you use the
`useBarrier` option to force barrier execution. Below are a list of parameters to SparkTorch and their meaning.
```
inputCol: Standard Spark InputCol that must be a Vector.
labelCol: Standard Spark Label column. Can be null.
torchObj: The TorchObj which is described in the `Creating a Torch Object` section.
iters: Number of iterations to run per partition.
predictionCol: The standard spark prediction column for the dataframe.
partitions: Ability to repartition during training.
acquireLock: Used in Hogwild only. Forces locking on the server.
verbose: Describes whether you want real time logging
partitionShuffles: Only used in Hogwild. Will reshuffle data after completing training.
port: Only used in hogwild. Server port.
useBarrier: Only used in hogwild. Describes whether you want barrier execution. (Async mode uses barrier by default)
useVectorOut: Boolean to describe if you want the model output to be a vector (Defaults to float).
earlyStopPatience: If greater than 0, it will enforce early stopping based on validation.
miniBatch: Minibatch size for training per iteration. (Randomly shuffled)
validationPct: Percentage to use for validation.
mode: which training mode to use. `synchronous` leverages torch distributed. `hogwild` currently uses the flask service.
device: Supply 'cpu' or 'cuda'
```
#### Saving and Loading Pipelines
Since saving and loading custom ML Transformers in pure python has not been implemented in PySpark, an extension has been
added here to make that possible. In order to save a Pyspark Pipeline with Apache Spark, one will need to use the overwrite function:
```python
p = Pipeline(stages=[va, encoded, spark_model]).fit(df)
p.write().overwrite().save("location")
```
For loading, a Pipeline wrapper has been provided in the pipeline_utils file. An example is below:
```python
from sparktorch import PysparkPipelineWrapper
from pyspark.ml.pipeline import PipelineModel
p = PysparkPipelineWrapper.unwrap(PipelineModel.load('location'))
```
Then you can perform predictions, etc with:
```python
predictions = p.transform(df)
```
#### Getting the Pytorch model from the training session
If you just want to get the Pytorch model after training, you can execute the following code:
```python
stm = SparkTorch(
inputCol='features',
labelCol='label',
predictionCol='predictions',
torchObj=network_with_params,
verbose=1,
iters=5
).fit(data)
py_model = stm.getPytorchModel()
```
#### Using a pretrained Pytorch model for inference
If you already have a trained Pytorch model, you can attach it your existing pipeline by directly creating a SparkTorchModel.
This can be done by running the following:
```python
from sparktorch import create_spark_torch_model
net = ... # Pretrained Network
spark_torch_model = create_spark_torch_model(
net,
inputCol='features',
predictionCol='predictions'
)
```
## Running
One big thing to remember is to add the `--executor cores 1` option to spark to ensure
each executor is only training one copy of the network. This will especially be needed for gpu training.
## Contributing
Contributions are always welcome. This could be fixing a bug, changing documentation, or adding a new feature. To test
new changes against existing tests, we have provided a Docker container which takes in an argument of the python version.
This allows the user to check their work before pushing to Github, where travis-ci will run.
For python 3.6
```
docker build -t local-test --build-arg PYTHON_VERSION=3.6 .
docker run --rm local-test:latest bash -i -c "pytest"
```
## Literature and Inspiration
* Distributed training: http://seba1511.net/dist_blog/
* HOGWILD!: A Lock-Free Approach to Parallelizing Stochastic Gradient Descent: https://arxiv.org/pdf/1106.5730.pdf
* Scaling Distributed Machine Learning with the Parameter Server: https://www.cs.cmu.edu/~muli/file/parameter_server_osdi14.pdf
%package help
Summary: Development documents and examples for sparktorch
Provides: python3-sparktorch-doc
%description help
# SparkTorch
[](https://travis-ci.org/dmmiller612/sparktorch)
[](https://github.com/dmmiller612/sparktorch)
<img src="https://img.shields.io/pypi/v/sparktorch.svg" />

This is an implementation of Pytorch on Apache Spark. The goal of this library is to provide a simple, understandable interface
in distributing the training of your Pytorch model on Spark. With SparkTorch, you can easily integrate your deep
learning model with a ML Spark Pipeline. Underneath the hood, SparkTorch offers two distributed training approaches
through tree reductions and a parameter server. Through the api, the user can specify the style of training, whether
that is distributed synchronous or hogwild.
## Why should I use this?
Like SparkFlow, SparkTorch's main objective is to seamlessly work with Spark's ML Pipelines. This library provides three
core components:
* Data parallel distributed training for large datasets. SparkTorch offers distributed synchronous and asynchronous training methodologies.
This is useful for training very large datasets that do not fit into a single machine.
* Full integration with Spark's ML library. This ensures that you can save and load pipelines with your trained model.
* Inference. With SparkTorch, you can load your existing trained model and run inference on billions of records
in parallel.
On top of these features, SparkTorch can utilize barrier execution, ensuring that all executors run concurrently during
training (This is required for synchronous training approaches).
## Install
Install SparkTorch via pip: `pip install sparktorch`
SparkTorch requires Apache Spark >= 2.4.4, and has only been tested on PyTorch versions >= 1.3.0.
## Full Basic Example
```python
from sparktorch import serialize_torch_obj, SparkTorch
import torch
import torch.nn as nn
from pyspark.ml.feature import VectorAssembler
from pyspark.sql import SparkSession
from pyspark.ml.pipeline import Pipeline
spark = SparkSession.builder.appName("examples").master('local[2]').getOrCreate()
df = spark.read.option("inferSchema", "true").csv('mnist_train.csv').coalesce(2)
network = nn.Sequential(
nn.Linear(784, 256),
nn.ReLU(),
nn.Linear(256, 256),
nn.ReLU(),
nn.Linear(256, 10),
nn.Softmax(dim=1)
)
# Build the pytorch object
torch_obj = serialize_torch_obj(
model=network,
criterion=nn.CrossEntropyLoss(),
optimizer=torch.optim.Adam,
lr=0.0001
)
# Setup features
vector_assembler = VectorAssembler(inputCols=df.columns[1:785], outputCol='features')
# Create a SparkTorch Model with torch distributed. Barrier execution is on by default for this mode.
spark_model = SparkTorch(
inputCol='features',
labelCol='_c0',
predictionCol='predictions',
torchObj=torch_obj,
iters=50,
verbose=1
)
# Can be used in a pipeline and saved.
p = Pipeline(stages=[vector_assembler, spark_model]).fit(df)
p.save('simple_dnn')
```
## Run the Examples
You can run the examples through docker by issuing the following commands at the root of the repository:
```bash
make docker-build
make docker-run-dnn
make docker-run-cnn
```
For the cnn example, you will need to give your docker container at least 8gb of memory.
## Documentation
This is a small documentation section on how to SparkTorch. Please look at the examples library for more details.
#### Creating a Torch Object
To create a Torch object for training, you will need to utilize the `serialize_torch_obj` from SparkTorch. To do so,
simply add your network, loss criterion, the optimizer class, and any options as a dictionary to supply to the optimizer
(such as learning rate). A simple example of this is:
```python
from sparktorch import serialize_torch_obj
torch_obj = serialize_torch_obj(
model=network,
criterion=nn.CrossEntropyLoss(),
optimizer=torch.optim.Adam,
lr=0.0001
)
```
When training neural networks on Spark, one issue that many face is OOM errors. To avoid this issue on the driver, you
can create a torch object that is only initialized on the worker nodes. To create this object, you can set up the
following:
```python
from sparktorch import serialize_torch_obj_lazy
torch_obj = serialize_torch_obj_lazy(
model=Network,
criterion=nn.CrossEntropyLoss,
optimizer=torch.optim.Adam,
optimizer_params={'lr': 0.001},
model_parameters={'some_model_param': 5}
)
```
The Network in the above example must be a nn.module pytorch class. If you need parameters passed into the constructor,
you can use the `model_parameters` parameter. The item will be passed in as **kwargs to the constructor.
NOTE: One thing to remember is that if your network is not a sequential, it will need to be saved in a separate file and
available in the python path. An example of this can be found in `simple_cnn.py`.
#### Training Options
There are two main training options with SparkTorch: `async` and `hogwild`. The async mode utilizes the torch distributed
package, ensuring that the networks are in sync through each iteration. This is the most supported version. When using
this option, you will need to be aware that barrier execution is enforced, meaning that the parallelism will need to match
the partitions.
The Hogwild approach utilizes a Flask Service underneath the hood. When using Hogwild, it is strongly recommended that you use the
`useBarrier` option to force barrier execution. Below are a list of parameters to SparkTorch and their meaning.
```
inputCol: Standard Spark InputCol that must be a Vector.
labelCol: Standard Spark Label column. Can be null.
torchObj: The TorchObj which is described in the `Creating a Torch Object` section.
iters: Number of iterations to run per partition.
predictionCol: The standard spark prediction column for the dataframe.
partitions: Ability to repartition during training.
acquireLock: Used in Hogwild only. Forces locking on the server.
verbose: Describes whether you want real time logging
partitionShuffles: Only used in Hogwild. Will reshuffle data after completing training.
port: Only used in hogwild. Server port.
useBarrier: Only used in hogwild. Describes whether you want barrier execution. (Async mode uses barrier by default)
useVectorOut: Boolean to describe if you want the model output to be a vector (Defaults to float).
earlyStopPatience: If greater than 0, it will enforce early stopping based on validation.
miniBatch: Minibatch size for training per iteration. (Randomly shuffled)
validationPct: Percentage to use for validation.
mode: which training mode to use. `synchronous` leverages torch distributed. `hogwild` currently uses the flask service.
device: Supply 'cpu' or 'cuda'
```
#### Saving and Loading Pipelines
Since saving and loading custom ML Transformers in pure python has not been implemented in PySpark, an extension has been
added here to make that possible. In order to save a Pyspark Pipeline with Apache Spark, one will need to use the overwrite function:
```python
p = Pipeline(stages=[va, encoded, spark_model]).fit(df)
p.write().overwrite().save("location")
```
For loading, a Pipeline wrapper has been provided in the pipeline_utils file. An example is below:
```python
from sparktorch import PysparkPipelineWrapper
from pyspark.ml.pipeline import PipelineModel
p = PysparkPipelineWrapper.unwrap(PipelineModel.load('location'))
```
Then you can perform predictions, etc with:
```python
predictions = p.transform(df)
```
#### Getting the Pytorch model from the training session
If you just want to get the Pytorch model after training, you can execute the following code:
```python
stm = SparkTorch(
inputCol='features',
labelCol='label',
predictionCol='predictions',
torchObj=network_with_params,
verbose=1,
iters=5
).fit(data)
py_model = stm.getPytorchModel()
```
#### Using a pretrained Pytorch model for inference
If you already have a trained Pytorch model, you can attach it your existing pipeline by directly creating a SparkTorchModel.
This can be done by running the following:
```python
from sparktorch import create_spark_torch_model
net = ... # Pretrained Network
spark_torch_model = create_spark_torch_model(
net,
inputCol='features',
predictionCol='predictions'
)
```
## Running
One big thing to remember is to add the `--executor cores 1` option to spark to ensure
each executor is only training one copy of the network. This will especially be needed for gpu training.
## Contributing
Contributions are always welcome. This could be fixing a bug, changing documentation, or adding a new feature. To test
new changes against existing tests, we have provided a Docker container which takes in an argument of the python version.
This allows the user to check their work before pushing to Github, where travis-ci will run.
For python 3.6
```
docker build -t local-test --build-arg PYTHON_VERSION=3.6 .
docker run --rm local-test:latest bash -i -c "pytest"
```
## Literature and Inspiration
* Distributed training: http://seba1511.net/dist_blog/
* HOGWILD!: A Lock-Free Approach to Parallelizing Stochastic Gradient Descent: https://arxiv.org/pdf/1106.5730.pdf
* Scaling Distributed Machine Learning with the Parameter Server: https://www.cs.cmu.edu/~muli/file/parameter_server_osdi14.pdf
%prep
%autosetup -n sparktorch-0.2.0
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-sparktorch -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Fri May 05 2023 Python_Bot <Python_Bot@openeuler.org> - 0.2.0-1
- Package Spec generated
|