In this tutorial we present advanced features of Parsl including its ability to support multiple sites, elastically scale across sites, and its support for fault tolerance.
In the "parsl-introduction" notebook we showed how a configuration file controls the execution provider and model used to execute a Parsl script. While we showed only a single site, Parsl is capable of distributing workload over several sites simultaneously. Below we show an example configuration that combines local thread execution and local pilot job execution. By default, Apps will execute on any configured sites. However, you can also specify a specific site, or sites, on which an App can execute by adding a list of sites to the App decorator. In the following cells, we show a three-stage workflow in which the first app uses local threads, the second uses local pilot jobs, and the third (with no sites specified) will use either threads or pilot jobs.
First, we define two "sites", which in this example are both local. The first uses threads, and the second uses pilot job execution. We then instantiate a DataFlowKernel object with these two sites.
from parsl.config import Config
from parsl.executors.threads import ThreadPoolExecutor
from parsl.executors import HighThroughputExecutor
from parsl.providers import LocalProvider
from parsl.channels import LocalChannel
# Define a configuration for using local threads and pilot jobs
multi_site_config = Config(
executors=[
ThreadPoolExecutor(
max_threads=8,
label='local_threads'
),
HighThroughputExecutor(
label="local_htex",
worker_debug=True,
cores_per_worker=1,
provider=LocalProvider(
channel=LocalChannel(),
init_blocks=1,
max_blocks=1,
),
)
]
)
Next, we define three Apps, which have the same functionality as in the previous tutorial. However, the first is specified to use the first site only, the second is specific to use the second site only, and the third doesn't have a site specification, so it can run on any available site.
import parsl
from parsl.app.app import python_app, bash_app
parsl.load(multi_site_config)
# Generate app runs using the "local_threads" executor
@bash_app(executors=["local_threads"])
def generate(outputs=[]):
return "echo $(( RANDOM )) &> {outputs[0]}"
# Concat app runs using the "local_ipp" executor
@bash_app(executors=["local_htex"])
def concat(inputs=[], outputs=[]):
return "cat {0} > {1}".format(" ".join(inputs), outputs[0])
# Total app runs using either executor
@python_app
def total(inputs=[]):
total = 0
with open(inputs[0], 'r') as f:
for l in f:
total += int(l)
return total
Finally, we run the apps, and cleanup.
# Create 5 files with random numbers
output_files = []
for i in range (5):
output_files.append(generate(outputs=['random-%s.txt' % i]))
# Concatenate the files into a single file
cc = concat(inputs=[i.outputs[0].filepath for i in output_files], outputs=["all.txt"])
# Calculate the sum of the random numbers
result = total(inputs=[cc.outputs[0]])
print (result.result())
parsl.clear()
As a Parsl script is evaluated, it creates a collection of tasks for asynchronous execution. In most cases this stream of tasks is variable as different stages of the workflow are evaluated. To address this variability, Parsl is able to monitor the flow of tasks and elastically provision resources, within user specified bounds, in response.
In the following example, we declare the range of blocks to be provisioned from 0 to 10 (minBlocks and maxBlocks, respectively). We then set parallelism to 0.1, which means that Parsl will favor reusing resources rather than provisioning new resources. You should see that the app is executed on the same process ID.
import parsl
from parsl.app.app import python_app, bash_app
from parsl.providers import LocalProvider
from parsl.channels import LocalChannel
from parsl.config import Config
from parsl.executors.ipp import IPyParallelExecutor
local_ipp = Config(
executors=[
IPyParallelExecutor(
label="local_ipp",
provider=LocalProvider(
channel=LocalChannel(),
init_blocks=1,
max_blocks=10,
parallelism=0.1,
)
)
]
)
parsl.load(local_ipp)
@python_app
def py_hello():
import time
import os
time.sleep(5)
return "(%s) Hello World!" % os.getpid()
results = {}
for i in range(0, 10):
results[i] = py_hello()
print("Waiting for results ....")
for i in range(0, 10):
print(results[i].result())
parsl.clear()
We now modify the parallelism option to 1. This configuration means that Parsl will favor elastic growth to execute as many tasks simultaineously as possible, up to the user defined limit. You can modify the parallelism between 0 and 1 to experiment with different scaling policies.
import parsl
from parsl.app.app import python_app, bash_app
from parsl.providers import LocalProvider
from parsl.channels import LocalChannel
from parsl.config import Config
from parsl.executors.ipp import IPyParallelExecutor
local_ipp = Config(
executors=[
IPyParallelExecutor(
label="local_ipp",
provider=LocalProvider(
channel=LocalChannel(),
init_blocks=1,
max_blocks=10,
parallelism=1,
)
)
]
)
parsl.load(local_ipp)
@python_app
def py_hello():
import time
import os
time.sleep(5)
return "(%s) Hello World!" % os.getpid()
results = {}
for i in range(0, 10):
results[i] = py_hello()
print("Waiting for results ....")
for i in range(0, 10):
print(results[i].result())
parsl.clear()
Workflows are often re-executed for various reasons, including workflow or node failure, code errors, or extension of the workflow. It is inefficient to re-execute apps that have succesfully completed. Parsl provides two mechanisms to improve efficacy via app caching and/or workflow-level checkpointing.
When developing a workflow, developers often re-execute the same workflow with incremental changes. Often large fragments of the workflow are re-executed even though they have not been modified. This wastes not only time but also computational resources. App Caching solves this problem by caching results from apps that have completed so that they can be re-used. Caching is enabled by setting the cache
argument to the App wrapper. Note: the cached result is returned only when the same function, with the same name, input arguments, and function body is called. If any of these are changed, a new result is computed and returned.
The following example shows two calls to the slow_message
app with the same message. You will see that the first call is slow (since the app sleeps for 5 seconds), but the second call returns immedidately (the app is not actually executed this time, so there is no sleep delay).
Note: running this example in Jupyter notebooks will cache the results through subsequent executions of the cell.
import parsl
from parsl.app.app import python_app, bash_app
from parsl.providers import LocalProvider
from parsl.channels import LocalChannel
from parsl.config import Config
from parsl.executors import HighThroughputExecutor
local_htex = Config(
executors=[
HighThroughputExecutor(
label="htex_Local",
worker_debug=True,
cores_per_worker=1,
provider=LocalProvider(
channel=LocalChannel(),
init_blocks=1,
max_blocks=10,
parallelism=1,
)
)
]
)
parsl.load(local_htex)
@python_app(cache = True)
def slow_message(message):
import time
time.sleep(5)
return message
# First call to slow_message will calcuate the value
first = slow_message("Hello World")
print ("First: %s" % first.result())
# Second call to slow_message with the same args will
# return immediately
second = slow_message("Hello World")
print ("Second: %s" % second.result())
# Third call to slow_message with different arguments
# will again wait
third = slow_message("Hello World!")
print ("Third: %s" % third.result())
parsl.clear()
Parsl's checkpointing model enables workflow state to be saved and then used at a later time to resume execution from that point. Checkpointing provides workflow-level fault tolerance, insuring against failure of the Parsl control process.
Parsl implements an incremental checkpointing model: each explicit checkpoint will save state changes from the previous checkpoint. Thus, the full history of a workflow may be distributed across multiple checkpoints.
Checkpointing uses App caching to store results. Thus, the same caveats apply to non-deterministic functions. That is, the checkpoint saves results for an instance of an App when it has the same name, arguments, and function body.
In this example we demonstrate how to automatically checkpoint workflows when tasks succesfully execute. This is enabled in the config by setting checkpointMode
to task_exit
. Other checkpointing models are described in the checkpointing documentation.
import parsl
from parsl.app.app import python_app, bash_app
from parsl.providers import LocalProvider
from parsl.channels import LocalChannel
from parsl.config import Config
from parsl.executors import HighThroughputExecutor
from parsl.executors import IPyParallelExecutor
local_ipp = Config(
executors=[
IPyParallelExecutor(
label="ipp_Local",
provider=LocalProvider(
channel=LocalChannel(),
)
)
],
checkpoint_mode='task_exit',
)
dfk = parsl.load(local_htex)
@python_app(cache=True)
def slow_double(x):
import time
time.sleep(5)
return x * 2
d = []
for i in range(5):
d.append(slow_double(i))
# wait for results
print([d[i].result() for i in range(5)])
parsl.clear()
To restart from a previous checkpoint the DFK must be configured with the appropriate checkpoint file. In most cases this is likley to be the most recent checkpoint file created. The following approach works with any checkpoint file, irrespective of which checkpointing method was used to create it.
In this example we reload the most recent checkpoint and attempt to run the same workflow. The results return immediately as there is no need to rexecute each app.
from parsl.utils import get_all_checkpoints
from parsl import set_stream_logger, NullHandler
# set the stream logger to print debug messages
#set_stream_logger()
local_htex.checkpoint_files = get_all_checkpoints()
parsl.load(local_ipp)
# Rerun the same workflow
d = []
for i in range(5):
d.append(slow_double(i))
# wait for results
print([d[i].result() for i in range(5)])
parsl.clear()
Parsl uses Glous for wide area data movement. The following example shows how you can sort a publicly acessible Globus file containing random strings.
Note: to run this example you will need to run in a location with a Globus endpoint and make that endpoint known to the configuration. E.g., for BlueWaters you will need to include the following configuration:
storage_access=[GlobusScheme(
endpoint_uuid="d59900ef-6d04-11e5-ba46-22000b92c6ec",
endpoint_path="/",
local_path="/"
)]
Make sure to activate the destination endpoint before running this example. You can activate the endpoint on the Globus website or via the Globus Python SDK.
import parsl
from parsl.app.app import python_app, bash_app
from parsl.data_provider.files import File
from parsl.config import Config
from parsl.data_provider.scheme import GlobusScheme
from parsl.executors.threads import ThreadPoolExecutor
config = Config(
executors=[
ThreadPoolExecutor(
label='local_threads_globus',
storage_access=[GlobusScheme(
endpoint_uuid='d59900ef-6d04-11e5-ba46-22000b92c6ec', # Please replace UUID with your uuid
endpoint_path='/', # Please replace with your path
local_path='/'
)],
)
],
)
parsl.load(config)
@python_app
def sort_strings(inputs=[], outputs=[]):
with open(inputs[0], 'r') as u:
strs = u.readlines()
strs.sort()
with open(outputs[0].filepath, 'w') as s:
for e in strs:
s.write(e)
unsorted_globus_file = File('globus://03d7d06a-cb6b-11e8-8c6a-0a1d4c5c824a/unsorted.txt')
sorted_globus_file = File('globus://d59900ef-6d04-11e5-ba46-22000b92c6ec/sorted.txt')
f = sort_strings(inputs=[unsorted_globus_file], outputs=[sorted_globus_file])
print (f.result())
parsl.clear()
Parsl can be configured to capture fine grain monitoring information about workflows and resource usage. To enable monitoring you must add the monitoring hub to the configuration.
Note: in this example we set the resource monitoring interval to 3 seconds so that we can capture resource information from short running tasks. In practice you will likely use a longer interval.
import parsl
from parsl.monitoring.monitoring import MonitoringHub
from parsl.config import Config
from parsl.executors import HighThroughputExecutor
from parsl.addresses import address_by_hostname
import logging
config = Config(
executors=[
HighThroughputExecutor(
label="local_htex",
address=address_by_hostname(),
)
],
monitoring=MonitoringHub(
hub_address=address_by_hostname(),
hub_port=6553,
resource_monitoring_interval=3,
)
)
parsl.load(config)
# Run a simple workflow
@python_app(cache=True)
def slow_double(x):
import time
time.sleep(15)
return x * 2
d = []
for i in range(5):
d.append(slow_double(i))
# wait for results
print([d[i].result() for i in range(5)])
parsl.clear()
Parsl includes a web-based visualization interface that can be used to inspect monitoring information in tables and graphs. To view the web interface run the parsl-visualize command.
Alternatively, monitoring information is stored in a local SQLite database. You can connect to this database directly from your notebook.
import sqlite3
conn = sqlite3.connect('monitoring.db')
c = conn.cursor()
c.execute('SELECT * from workflow')
workflows = c.fetchall()
print("Workflows")
for w in workflows:
print(w)
c.execute('SELECT * from task where run_id="%s"' % w[0])
tasks = c.fetchall()
print("Tasks")
for t in tasks:
print(t)
c.execute('SELECT * from resource where run_id="%s"' % w[0])
resources = c.fetchall()
print("Tasks")
for r in resources:
print(r)
conn.close()