Shareddask.ipynbOpen in CoCalc
Author: Harald Schilly
Views : 133

Dask in Python 3 (Ubuntu Linux)

https://docs.dask.org/en/latest/

In [1]:
import dask dask.__version__
'2.6.0'
In [2]:
import distributed distributed.__version__
'2.6.0'
In [3]:
import dask import dask.distributed import os dask.config.set({ 'temporary_directory': os.path.expanduser('~/tmp'), 'scheduler.work-stealing': True })
<dask.config.set at 0x7f4a6b085be0>
In [4]:
dask.config.config
{'temporary-directory': '/home/user/tmp', 'array': {'svg': {'size': 120}}, 'distributed': {'version': 2, 'scheduler': {'allowed-failures': 3, 'bandwidth': 100000000, 'blocked-handlers': [], 'default-data-size': 1000, 'events-cleanup-delay': '1h', 'idle-timeout': None, 'transition-log-length': 100000, 'work-stealing': True, 'worker-ttl': None, 'pickle': True, 'preload': [], 'preload-argv': [], 'default-task-durations': {}, 'dashboard': {'status': {'task-stream-length': 1000}, 'tasks': {'task-stream-length': 100000}, 'tls': {'ca-file': None, 'key': None, 'cert': None}}}, 'worker': {'blocked-handlers': [], 'multiprocessing-method': 'forkserver', 'use-file-locking': True, 'connections': {'outgoing': 50, 'incoming': 10}, 'preload': [], 'preload-argv': [], 'daemon': True, 'lifetime': {'duration': None, 'stagger': '0 seconds', 'restart': False}, 'profile': {'interval': '10ms', 'cycle': '1000ms', 'low-level': False}, 'memory': {'target': 0.6, 'spill': 0.7, 'pause': 0.8, 'terminate': 0.95}}, 'client': {'heartbeat': '5s'}, 'deploy': {'lost-worker-timeout': '15s'}, 'comm': {'compression': 'auto', 'default-scheme': 'tcp', 'socket-backlog': 2048, 'recent-messages-log-length': 0, 'zstd': {'level': 3, 'threads': 0}, 'timeouts': {'connect': '10s', 'tcp': '30s'}, 'require-encryption': False, 'tls': {'ciphers': None, 'ca-file': None, 'scheduler': {'cert': None, 'key': None}, 'worker': {'key': None, 'cert': None}, 'client': {'key': None, 'cert': None}}}, 'dashboard': {'link': '{scheme}://{host}:{port}/status', 'export-tool': False}, 'admin': {'tick': {'interval': '20ms', 'limit': '3s'}, 'max-error-length': 10000, 'log-length': 10000, 'log-format': '%(name)s - %(levelname)s - %(message)s', 'pdb-on-err': False}}, 'scheduler': {'work-stealing': True}}
In [5]:
from dask.distributed import Client client = Client('127.0.0.1:8786') client

Client

Cluster

  • Workers: 2
  • Cores: 2
  • Memory: 512.00 MB

The dashboard is actually at https://cocalc.com/{{ THE PROJECT UUID }}/server/8787/status

Websocket forwarding doesn't work, though ... hmm...

alternatively, start an X11 desktop in cocalc and run google-chrome at http://127.0.0.1:8787/status

data array similar to numpy arrays

In [6]:
import dask.array as da
In [7]:
x = da.random.random((1000, 1000), chunks=(300, 300)) x
Array Chunk
Bytes 8.00 MB 720.00 kB
Shape (1000, 1000) (300, 300)
Count 16 Tasks 16 Chunks
Type float64 numpy.ndarray
1000 1000
In [8]:
client.scatter(x)
Future: Array status: finished, type: Array, key: Array-abf1decf79094e7812a9f1beaa91865f
In [9]:
y = x + x.T z = y[::50, 100:].mean(axis=1) z
Array Chunk
Bytes 160 B 48 B
Shape (20,) (6,)
Count 84 Tasks 4 Chunks
Type float64 numpy.ndarray
20 1
In [10]:
z.shape
(20,)
In [11]:
out = z.compute() out
array([1.01078095, 0.99266174, 0.99929112, 0.99543269, 0.99301255, 1.00884673, 0.99465439, 0.99806313, 0.98933095, 0.97612307, 1.0045283 , 1.01754985, 1.00694673, 0.99860598, 1.00416055, 0.98243844, 0.98565595, 0.99309106, 1.00129066, 0.98720415])
In [12]:
rz = (z[:100].sum() / z[:100].shape[0]) rz.compute()
0.9969834490537816
In [13]:
rz.visualize()

functions and native lists

In [14]:
fn = lambda x : x**3 - x**2 + 1 def neg(a): import time time.sleep(.1) return -a A = client.map(fn, range(10)) B = client.map(neg, A) C = client.map(lambda a, b: a+b, A, B) total = client.submit(sum, B) total.result()
-1750
In [15]:
client.gather(C)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

loops?

In [16]:
def fib(x): if x <= 1: return 1 else: return fib(x - 2) + fib(x - 1)
In [32]:
[fib(_) for _ in range(20)]
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]

Dask Bags

In [18]:
import dask.bag as db b1 = db.from_sequence(range(-1031, 1000), npartitions=50) b1
dask.bag<from_se..., npartitions=50>
In [19]:
import operator
In [20]:
is_odd = lambda x : x % 2 == 0 #b1.groupby(is_odd).map(lambda k_v : (k_v[0], sum(k_v[1]))).compute() b1.foldby(is_odd, operator.add, 0).compute()
[(False, -16256), (True, -16240)]

Dask Delayed

In [21]:
from dask import delayed
In [22]:
inc = lambda x : x+1 from operator import add
In [23]:
z = delayed(0) for i in range(5): x = delayed(inc)(i) y = delayed(inc)(delayed(add)(i, x)) z = delayed(add)(z, y) z.compute()
30
In [24]:
z.vizualize(filename=os.path.expanduser('~/dask-delayed-1.png'), format='png')
Delayed('vizualize-80c4aa09-8e73-46e0-bc7c-d511365af3ef')
In [25]:
z.vizualize()
Delayed('vizualize-d83217ed-91ba-463b-a002-146a6afa5414')
In [26]:
import dask_ml dask_ml.__version__
'1.0.0'
In [27]:
from dask_ml.preprocessing import Categorizer, DummyEncoder from dask_ml.linear_model import LogisticRegression
In [28]:
lr = LogisticRegression() lr
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True, intercept_scaling=1.0, max_iter=100, multi_class='ovr', n_jobs=1, penalty='l2', random_state=None, solver='admm', solver_kwargs=None, tol=0.0001, verbose=0, warm_start=False)
In [29]:
from joblib import parallel_backend with parallel_backend('dask') as pb: print(pb[0])
<joblib._dask.DaskDistributedBackend object at 0x7f4a3e7282e8>
In [30]:
import joblib joblib.__version__
'0.13.2'
In [ ]:
In [ ]:
In [ ]:

Ad-hoc Local Cluster

In [31]:
from dask.distributed import Client, LocalCluster import dask.array as da cluster = LocalCluster( n_workers=3, threads_per_worker=1, processes=True, diagnostics_port=None, ) client = Client(cluster) x = da.random.random((300, 300), chunks=(10, 10)) y = x + x.T z = (y.mean(axis=1) / y.shape[0]).std() print(z.compute())
/usr/local/lib/python3.6/dist-packages/distributed/dashboard/core.py:72: UserWarning: Port 8787 is already in use. Perhaps you already have a cluster running? Hosting the diagnostics dashboard on a random port instead. warnings.warn("\n" + msg)
7.55359119714641e-05
In [ ]:
In [ ]:
In [ ]: