@task
The task definition is the main parallelization mechanism for COMPSs.
It allows COMPSs to detect the units of work and their inputs/outputs in order to manage the execution in distributed environments.
Tip
These are the main questions that will direct you to the appropriate Section
Task Selection
As in the case of Java, a COMPSs Python application is a Python sequential program that contains calls to tasks. In particular, the user can select as a task:
Functions
Instance methods: methods invoked on objects
Class methods: static methods belonging to a class
The task definition in Python is done by means of Python decorators
instead of an annotated interface. In particular, the user needs to add
a @task decorator that describes the task before the
definition of the function/method.
As an example (Code 88), let us assume that the application calls
a function foo, which receives a file path (file_path – string
parameter) and a string parameter (value). The code of foo appends the
value into file_path.
def foo(file_path, value):
""" Update the file 'file_path' with the 'value'"""
with open(file_path, "a") as fd:
fd.write(value)
def main():
my_file = "sample_file.txt"
with open(my_file, "w") as fd:
fd.write("Hello")
foo(my_file, "World")
if __name__ == '__main__':
main()
In order to select foo as a task, the corresponding @task
decorator needs to be placed right before the definition of the
function, providing some metadata about the parameters of that function.
The @task decorator has to be imported from the pycompss
library (Code 89).
from pycompss.api.task import task
@task(metadata)
def foo(parameters):
...
See complete example
from pycompss.api.task import task
from pycompss.api.parameter import FILE_INOUT
@task(file_path=FILE_INOUT)
def foo(file_path, value):
""" Update the file 'file_path' with the 'value'"""
with open(file_path, "a") as fd:
fd.write(value)
def main():
my_file = "sample_file.txt"
with open(my_file, "w") as fd:
fd.write("Hello")
foo(my_file, "World")
if __name__ == '__main__':
main()
Tip
The PyCOMPSs task API also provides the @task decorator in camelcase
(@Task) with the same functionality.
The rationale of providing both @task and @Task relies on following
the PEP8 naming convention. Decorators are usually defined using lowercase,
but since the task decorator is implemented following the class pattern,
its name is also available as camelcase.
Important
The file that contains tasks definitions MUST ONLY contain imports
or the if __name__ == "__main__" section at the root level.
For example, Code 89 includes only the import for the
task decorator, and the main code is included into the main function.
The rationale of this is due to the fact that the module is loaded from PyCOMPSs. Since the code included at the root level of the file is executed when the module is loaded, this causes the execution to crash.
Function parameters
The @task decorator does not interfere with the function parameters, Consequently, the user can define the function parameters as normal python functions (Code 91).
@task()
def foo(param1, param2):
...
The use of *args and **kwargs as function parameters is
supported (Code 92).
*args and **kwargs example@task(returns=int)
def argkwarg_foo(*args, **kwargs):
...
And even with other parameters, such as usual parameters and default
defined arguments. Code 93 shows an example
of a task with two three parameters (whose one of them (s) has a default
value (2)), *args and **kwargs.
@task(returns=int)
def multiarguments_foo(v, w, s=2, *args, **kwargs):
...
Tasks within classes
Functions within classes can also be declared as tasks as normal functions.
The main difference is the existence of the self parameter which enables
to modify the callee object.
For tasks corresponding to instance methods, by default the task is
assumed to modify the callee object (the object on which the method is
invoked). The programmer can tell otherwise by setting the
target_direction argument of the @task decorator to IN
(Code 94).
class MyClass(object):
...
@task(target_direction=IN)
def instance_method(self):
... # self is NOT modified here
Class methods and static methods can also be declared as tasks. The only
requirement is to place the @classmethod or @staticmethod over
the @task decorator (Code 95).
Note that there is no need to use the target_direction flag within the
@task decorator.
@classmethod and @staticmethod tasks exampleclass MyClass(object):
...
@classmethod
@task()
def class_method(cls, a, b, c):
...
@staticmethod
@task(returns=int)
def static_method(a, b, c):
...
Tip
Tasks inheritance and overriding supported!!!
Caution
The objects used as task parameters MUST BE serializable:
Implement the
__getstate__and__setstate__functions in their classes for those objects that are not automatically serializable.The classes must not be declared in the same file that contains the main method (
if __name__ == '__main__') (known pickle issue).
Important
For instances of user-defined classes, the classes of these objects should have an empty constructor, otherwise the programmer will not be able to invoke task instance methods on those objects (Code 96).
# In file utils.py
from pycompss.api.task import task
class MyClass(object):
def __init__(self): # empty constructor
...
@task()
def yet_another_task(self):
# do something with the self attributes
...
...
# In file main.py
from pycompss.api.task import task
from utils import MyClass
@task(returns=MyClass)
def ret_foo():
...
myc = MyClass()
...
return myc
def main():
o = ret_foo()
# invoking a task instance method on a future object can only
# be done when an empty constructor is defined in the object's
# class
o.yet_another_task()
if __name__=='__main__':
main()
See complete example
utils.pyfrom pycompss.api.task import task
class MyClass(object):
def __init__(self):
""" Initializes self.value with 0 """
self.value = 0
@task()
def yet_another_task(self):
""" Increments self.value """
self.value = self.value + 1
main.pyfrom pycompss.api.task import task
from utils import MyClass
from pycompss.api.api import compss_wait_on
@task(returns=MyClass)
def ret_foo():
myc = MyClass()
return myc
def main():
o = ret_foo()
o.yet_another_task()
o = compss_wait_on(o)
print("Value: %d" % o.value)
if __name__=='__main__':
main()
Task Parameters
The metadata corresponding to a parameter is specified as an argument of
the @task decorator, whose name is the formal parameter’s name and whose
value defines the type and direction of the parameter. The parameter types and
directions can be:
- Types
Primitive types (integer, long, float, boolean, strings)
Objects (instances of user-defined classes, dictionaries, lists, tuples, complex numbers)
Files
Collections (instances of lists)
Dictionaries (instances of dictionary)
Streams
IO streams (for binaries)
- Direction
Read-only (
IN- default orIN_DELETE)Read-write (
INOUT)Write-only (
OUT)Concurrent (
CONCURRENT)Commutative (
COMMUTATIVE)
COMPSs is able to automatically infer the parameter type for primitive
types, strings and objects, while the user needs to specify it for
files. On the other hand, the direction is only mandatory for INOUT, OUT,
CONCURRENT and COMMUTATIVE parameters.
Note
Please note that in the following cases there is no need to include an argument in the @task decorator for a given task parameter:
Parameters of primitive types (integer, long, float, boolean) and strings: the type of these parameters can be automatically inferred by COMPSs, and their direction is always
IN.Read-only object parameters: the type of the parameter is automatically inferred, and the direction defaults to
IN.
The parameter metadata is available from the pycompss library (Code 99)
from pycompss.api.parameter import *
Objects
The default type for a parameter is object. Consequently, there is no need to use a specific keyword. However, it is necessary to indicate its direction (unless for input parameters):
PARAMETER |
DESCRIPTION |
|---|---|
|
The parameter is read-only. The type will be inferred. |
|
The parameter is read-only. The type will be inferred. Will be automatically removed after its usage. |
|
The parameter is read-write. The type will be inferred. |
|
The parameter is write-only. The type will be inferred. |
|
The parameter is read-write with concurrent access. The type will be inferred. |
|
The parameter is read-write with commutative access. The type will be inferred. |
Continuing with the example, in Code 100 the
decorator specifies that foo has a parameter called obj, of type object
and INOUT direction. Note how the second parameter, i, does not need to
be specified, since its type (integer) and direction (IN) are
automatically inferred by COMPSs.
INOUT) and input object (IN)from pycompss.api.task import task
from pycompss.api.parameter import INOUT, IN
@task(obj=INOUT, i=IN)
def foo(obj, i):
...
The previous task definition can be simplified due to the default IN direction
for objects (Code 101):
INOUT) simplifiedfrom pycompss.api.task import task
from pycompss.api.parameter import INOUT
@task(obj=INOUT)
def foo(obj, i):
...
Tip
In order to choose the appropriate direction, a good exercise is to think if
the function only consumes the object (IN), modifies the object (INOUT),
or produces an object (OUT).
Tip
The IN_DELETE definition is intended to one use objects. Consequently,
the information related to the object will be released as soon as possible.
The user can also define that the access to a object is concurrent
with CONCURRENT (Code 102). Tasks that share
a CONCURRENT parameter will be executed in parallel, if any other dependency
prevents this.
The CONCURRENT direction allows users to have access from multiple tasks to
the same object/file during their executions.
CONCURRENTfrom pycompss.api.task import task
from pycompss.api.parameter import CONCURRENT
@task(obj=CONCURRENT)
def foo(obj, i):
...
Caution
COMPSs does not manage the interaction with the objects used/modified concurrently. Taking care of the access/modification of the concurrent objects is responsibility of the developer.
Or even, the user can also define that the access to a parameter is commutative
with COMMUTATIVE (Code 103).
The execution order of tasks that share a COMMUTATIVE parameter can be changed
by the runtime following the commutative property.
COMMUTATIVEfrom pycompss.api.task import task
from pycompss.api.parameter import COMMUTATIVE
@task(obj=COMMUTATIVE)
def foo(obj, i):
...
Files
It is possible to define that a parameter is a file (FILE), and its direction:
PARAMETER |
DESCRIPTION |
|---|---|
|
The parameter is a file. The direction is assumed to be |
|
The parameter is a read-write file. |
|
The parameter is a write-only file. |
|
The parameter is a concurrent read-write file. |
|
The parameter is a commutative read-write file. |
Continuing with the example, in Code 104 the decorator
specifies that foo has a parameter called f, of type FILE and
INOUT direction (FILE_INOUT).
FILE_INOUT)from pycompss.api.task import task
from pycompss.api.parameter import FILE_INOUT
@task(f=FILE_INOUT)
def foo(f):
fd = open(f, 'a+')
...
# append something to fd
...
fd.close()
def main():
f = "/path/to/file.extension"
# Populate f
foo(f)
Tip
The value for a FILE (e.g. f) is a string pointing to the file
to be used at foo task. However, it can also be None if it is
optional. Consequently, the user can define task that can receive a FILE
or not, and act accordingly. For example (Code 105):
FILE_IN)from pycompss.api.task import task
from pycompss.api.parameter import FILE_IN
@task(f=FILE_IN)
def foo(f):
if f:
# Do something with the file
with open(f, 'r') as fd:
num_lines = len(rd.readlines())
return num_lines
else:
# Do something when there is no input file
return -1
def main():
f = "/path/to/file.extension"
# Populate f
num_lines_f = foo(f) # num_lines_f == actual number of lines of file.extension
g = None
num_lines_g = foo(g) # num_lines_g == -1
The user can also define that the access to file parameter is concurrent
with FILE_CONCURRENT (Code 106).
Tasks that share a FILE_CONCURRENT parameter will be executed in parallel,
if any other dependency prevents this.
The CONCURRENT direction allows users to have access from multiple tasks to
the same file during their executions.
FILE_CONCURRENTfrom pycompss.api.task import task
from pycompss.api.parameter import FILE_CONCURRENT
@task(f=FILE_CONCURRENT)
def foo(f, i):
...
Caution
COMPSs does not manage the interaction with the files used/modified concurrently. Taking care of the access/modification of the concurrent files is responsibility of the developer.
Or even, the user can also define that the access to a parameter is a file
FILE_COMMUTATIVE (Code 107).
The execution order of tasks that share a FILE_COMMUTATIVE parameter can be
changed by the runtime following the commutative property.
FILE_COMMUTATIVEfrom pycompss.api.task import task
from pycompss.api.parameter import FILE_COMMUTATIVE
@task(f=FILE_COMMUTATIVE)
def foo(f, i):
...
Directories
In addition to files, it is possible to define that a parameter is a directory
(DIRECTORY), and its direction:
PARAMETER |
DESCRIPTION |
|---|---|
|
The parameter is a directory and the direction is |
|
The parameter is a read-write directory. The directory will be compressed before any transfer among nodes. |
|
The parameter is a write-only directory. The directory will be compressed before any transfer among nodes. |
The definition of a DIRECTORY parameter is shown in
Code 108. The decorator specifies that foo
has a parameter called:
d_in, of typeDIRECTORYandINdirectiond_inout, of typeDIRECTORYandINOUTdirectiond_out, of typeDIRECTORYandOUTdirection
And finally synchronizes the values of the d_inout and d_out directories.
DIRECTORY)import os
from pycompss.api.task import task
from pycompss.api.parameter import DIRECTORY_IN
from pycompss.api.parameter import DIRECTORY_INOUT
from pycompss.api.parameter import DIRECTORY_OUT
from pycompss.api.api import compss_wait_on_directory
@task(d_in=DIRECTORY_IN, d_inout=DIRECTORY_INOUT, d_out=DIRECTORY_OUT)
def foo(d_in, d_inout, d_out):
# Read any file from d_in
for file in os.listdir(d_in):
with open(file, "r") as f: # Open in read mode
content = f.read()
...
...
# Read and/or write files from/within d_inout
for file in os.listdir(d_in):
with open(file, "rw") as f: # Open in read/write mode (could be "a" for append)
content = f.read()
# Update content
f.write(content)
...
...
# Write files to d_out
for file in os.listdir(d_in):
with open(file, "w") as f: # Open in write mode
f.write(new_content)
...
...
def main():
d_in="/path/to/in_directory/"
d_inout="/path/to/inout_directory/"
d_out="/path/to/out_directory/"
foo(d_in, d_inout, d_out)
compss_wait_on_directory(d_inout)
# Now it is possible to access to 'd_inout' updated contents
...
compss_wait_on_directory(d_out)
# Now it is possible to access to 'd_out' new contents
...
if __name__=="__main__":
main()
Collections
It is possible to specify that a parameter is a collection of elements (e.g. list) and its direction.
PARAMETER |
DESCRIPTION |
|---|---|
|
The parameter is read-only collection. |
|
The parameter is read-only collection for single usage (will be automatically removed after its usage). |
|
The parameter is read-write collection. |
|
The parameter is write-only collection. |
In this case (Code 109), the list may contain sub-objects that will be handled automatically by the runtime. It is important to annotate data structures as collections if in other tasks there are accesses to individual elements of these collections as parameters. Without this annotation, the runtime will not be able to identify data dependencies between the collections and the individual elements.
COLLECTION (IN)from pycompss.api.task import task
from pycompss.api.parameter import COLLECTION
@task(my_collection=COLLECTION)
def foo(my_collection):
for element in my_collection:
...
Caution
The current support for collections is limited to static number of elements lists.
Consequently, the length of the collection must be kept during the execution, and it is NOT possible to append or delete elements from the collection in the tasks (only to receive elements or to modify the existing if they are not primitives).
The sub-objects of the collection can be collections of elements (and
recursively). In this case, the runtime also keeps track of all elements
contained in all sub-collections. In order to improve the performance,
the depth of the sub-objects can be limited through the use of the
depth parameter (Code 110)
COLLECTION_IN and Depthfrom pycompss.api.task import task
from pycompss.api.parameter import COLLECTION_IN
@task(my_collection={Type:COLLECTION_IN, Depth:2})
def foo(my_collection):
for inner_collection in my_collection:
for element in inner_collection:
# The contents of element will not be tracked
...
Tip
A collection can contain dictionaries, and will be analyzed automatically.
Tip
If the collection is intended to be used only once with IN direction, the
COLLECTION_IN_DELETE type is recommended, since it automatically removes
the entire collection after the task. This enables to release as soon as
possible memory and storage.
Collections of files
It is also possible to specify that a parameter is a collection of files (e.g. list) and its direction.
PARAMETER |
DESCRIPTION |
|---|---|
|
The parameter is read-only collection of files. |
|
The parameter is read-write collection of files. |
|
The parameter is write-only collection of files. |
In this case (Code 111), the list may contain files that will be handled automatically by the runtime. It is important to annotate data structures as collections if in other tasks there are accesses to individual elements of these collections as parameters. Without this annotation, the runtime will not be able to identify data dependencies between the collections and the individual elements.
COLLECTION_FILE (IN)from pycompss.api.task import task
from pycompss.api.parameter import COLLECTION_FILE
@task(my_collection=COLLECTION_FILE)
def foo(my_collection):
for file in my_collection:
...
The file of the collection can be collections of elements (and
recursively). In this case, the runtime also keeps track of all files
contained in all sub-collections.
In order to improve the performance, the depth of the sub-files can be
limited through the use of the depth parameter as with objects
(Code 110)
Caution
The current support for collections of files is also limited to a static number of elements, as with Collections.
Dictionaries
It is possible to specify that a parameter is a dictionary of elements (e.g. dict) and its direction.
PARAMETER |
DESCRIPTION |
|---|---|
|
The parameter is read-only dictionary. |
|
The parameter is read-only dictionary for single usage (will be automatically removed after its usage). |
|
The parameter is read-write dictionary. |
As with the collections, it is possible to specify that a parameter is a dictionary of elements (e.g. dict) and its direction (DICTIONARY_IN or DICTIONARY_INOUT) (Code 112), whose sub-objects will be handled automatically by the runtime.
DICTIONARY (IN)from pycompss.api.task import task
from pycompss.api.parameter import DICTIONARY
@task(my_dictionary=DICTIONARY)
def foo(my_dictionary):
for k, v in my_dictionary.items():
...
Caution
The current support for dictionaries is also limited to a static number of elements, as with Collections.
The sub-objects of the dictionary can be collections or dictionary of elements
(and recursively). In this case, the runtime also keeps track of all elements
contained in all sub-collections/sub-dictionaries.
In order to improve the performance, the depth of the sub-objects can be
limited through the use of the depth parameter
(Code 113)
DICTIONARY_IN and Depthfrom pycompss.api.task import task
from pycompss.api.parameter import DICTIONARY_IN
@task(my_dictionary={Type:DICTIONARY_IN, Depth:2})
def foo(my_dictionary):
for key, inner_dictionary in my_dictionary.items():
for sub_key, sub_value in inner_dictionary.items():
# The contents of element will not be tracked
...
Tip
A dictionary can contain collections, and will be analyzed automatically.
Tip
If the dictionary is intended to be used only once with IN direction, the
DICTIONARY_IN_DELETE type is recommended, since it automatically removes
the entire dictionary after the task. This enables to release as soon as
possible memory and storage.
Streams
It is possible to use streams as input or output of the tasks by defining
that a parameter is STREAM and its direction.
PARAMETER |
DESCRIPTION |
|---|---|
|
The parameter is a read-only stream. |
|
The parameter is a write-only stream. |
For example, Code 114 shows an example using STREAM_IN or STREAM_OUT
parameters
This parameters enable to mix a task-driven workflow with a data-driven workflow.
STREAM_IN and STREAM_OUTfrom pycompss.api.task import task
from pycompss.api.parameter import STREAM_IN
from pycompss.api.parameter import STREAM_OUT
@task(ods=STREAM_OUT)
def write_objects(ods):
...
for i in range(NUM_OBJECTS):
# Build object
obj = MyObject()
# Publish object
ods.publish(obj)
...
...
# Mark the stream for closure
ods.close()
@task(ods=STREAM_IN, returns=int)
def read_objects(ods):
...
num_total = 0
while not ods.is_closed():
# Poll new objects
new_objects = ods.poll()
# Process files
...
# Accumulate read files
num_total += len(new_objects)
...
# Return the number of processed files
return num_total
The stream parameter also supports Files (Code 115).
STREAM_IN and STREAM_OUT for filesfrom pycompss.api.task import task
from pycompss.api.parameter import STREAM_IN
from pycompss.api.parameter import STREAM_OUT
@task(fds=STREAM_OUT)
def write_files(fds):
...
for i in range(NUM_FILES):
file_name = str(uuid.uuid4())
# Write file
with open(file_path, 'w') as f:
f.write("Test " + str(i))
...
...
# Mark the stream for closure
fds.close()
@task(fds=STREAM_IN, returns=int)
def read_files(fds):
...
num_total = 0
while not fds.is_closed():
# Poll new files
new_files = fds.poll()
# Process files
for nf in new_files:
with open(nf, 'r') as f:
...
# Accumulate read files
num_total += len(new_files)
...
...
# Return the number of processed files
return num_total
In addition, the stream parameter can also be defined for binary tasks (Code 116).
STREAM_OUT for binariesfrom pycompss.api.task import task
from pycompss.api.binary import binary
from pycompss.api.parameter import STREAM_OUT
@binary(binary="file_generator.sh")
@task(fds=STREAM_OUT)
def write_files(fds):
# Equivalent to: ./file_generator.sh > fds
pass
Code 117 shows an example of how streams are used in the main code. In this code snippet we can see how the object representing the data stream is created how the a producer task is invoked and how the stream data generated at tasks can be poll from the main code.
from pycompss.api.task import task
from pycompss.api.parameter import STREAM_OUT
from pycompss.streams.distro_stream import ObjectDistroStream
@task(ods=STREAM_OUT)
def write_objects(ods):
...
for i in range(NUM_OBJECTS):
# Build object
obj = MyObject()
# Publish object
ods.publish(obj)
...
...
# Mark the stream for closure
ods.close()
@task()
def process_object(obj):
...
# Do something with obj
...
if __name__=='__main__':
ods = ObjectDistroStream()
# Create producers
for _ in range(num_producers):
write_objects(ods, producer_sleep)
# Process stream
while not ods.is_closed():
# Poll new objects
new_objects = ods.poll()
# Process received objects
for obj in new_objects:
res = process_object(obj)
...
Standard Streams
Finally, a parameter can also be defined as the standard input, standard output, and standard error.
PARAMETER |
DESCRIPTION |
|---|---|
|
The parameter is a IO stream for standard input redirection. |
|
The parameter is a IO stream for standard output redirection. |
|
The parameter is a IO stream for standard error redirection. |
Caution
STDIN, STDOUT and STDERR are only supported in binary tasks
This is particularly useful with binary tasks that consume/produce from standard IO streams, and the user wants to redirect the standard input/output/error to a particular file. Code 118 shows an example of a binary task that invokes output_generator.sh which produces the result in the standard output, and the task takes that output and stores it into fds.
STDOUT for binariesfrom pycompss.api.task import task
from pycompss.api.binary import binary
from pycompss.api.parameter import STDOUT
@binary(binary="output_generator.sh")
@task(fds=STDOUT)
def write_files(fds):
# Equivalent to: ./file_generator.sh > fds
pass
Other Task Parameters
Task time out
The user is also able to define the time out of a task within the @task decorator
with the time_out=<TIME_IN_SECONDS> hint.
The runtime will cancel the task if the time to execute the task exceeds the time defined by the user.
For example, Code 119 shows how to specify that the unknown_duration_task
maximum duration before canceling (if exceeded) is one hour.
@task(time_out=3600)
def unknown_duration_task(self):
...
Scheduler hints
The programmer can provide hints to the scheduler through specific arguments within the @task decorator.
For instance, the programmer can mark a task as a high-priority task
with the priority argument of the @task decorator (Code 120).
In this way, when the task is free of dependencies, it will be scheduled before
any of the available low-priority (regular) tasks. This functionality is
useful for tasks that are in the critical path of the application’s task
dependency graph.
@task(priority=True)
def func():
...
Moreover, the user can also mark a task as distributed with the is_distributed argument or as replicated with the is_replicated argument (Code 121). When a task is marked with is_distributed=True, the method must be scheduled in a forced round robin among the available resources. On the other hand, when a task is marked with is_replicated=True, the method must be executed in all the worker nodes when invoked from the main application. The default value for these parameters is False.
@task(is_distributed=True)
def func():
...
@task(is_replicated=True)
def func2():
...
On failure task behavior
In case a task fails, the whole application behavior can be defined using the @on_failure decorator on top of the @task decorator (Code 122). It has four possible values that can be defined with the management parameter: ‘RETRY’, ‘CANCEL_SUCCESSORS’, ‘FAIL’ and ‘IGNORE’. ‘RETRY’ is the default behavior, making the task to be executed again (on the same worker or in another worker if the failure remains). ‘CANCEL_SUCCESSORS’ ignores the failed task and cancels the execution of the successor tasks, ‘FAIL’ stops the whole execution once a task fails and ‘IGNORE’ ignores the failure and continues with the normal execution.
from pycompss.api.task import task
from pycompss.api.on_failure import on_failure
@on_failure(management ='CANCEL_SUCCESSORS')
@task()
def func():
...
Since the ‘CANCEL_SUCCESSORS’ and ‘IGNORE’ policies enable to continue
the execution accepting that tasks may have failed, it is possible to define
the value for the objects and/or files produced by the failed tasks (INOUT,
OUT, FILE_INOUT, FILE_OUT and return).
This is considered as the default output objects/files.
For example, Code 123 shows a the func
task which returns one integer. In the case of failure within func, the
execution of the workflow will continue since the on failure management policy
is set to ‘IGNORE’, with 0 as return value.
from pycompss.api.task import task
from pycompss.api.on_failure import on_failure
@on_failure(management='IGNORE', returns=0)
@task(returns=int)
def func():
...
For the INOUT parameters, the default value can be set by using the parameter
name of func in the @on_failure decorator.
Code 124 shows how to define the default
value for a FILE_INOUT parameter (named f_inout).
The example is also valid for FILE_OUT values.
from pycompss.api.task import task
from pycompss.api.on_failure import on_failure
from pycompss.api.parameter import FILE_INOUT
@on_failure(management='IGNORE', f_inout="/path/to/default.file")
@task(f_inout=FILE_INOUT)
def func(f_inout):
...
Tip
The default FILE_INOUT/FILE_OUT can be generated at task generation time
by calling a function instead of providing a static file path.
Code 125 shows an example of this
case, where the default value for the output file produced by func is
defined by the generate_empty function.
from pycompss.api.task import task
from pycompss.api.on_failure import on_failure
from pycompss.api.parameter import FILE_OUT
def generate_empty(msg, name):
empty_file = "/tmp/empty_file_" + name
with open(empty_file, 'w') as f:
f.write("EMPTY FILE " + msg)
return empty_file
@on_failure(management='IGNORE', f_out=generate_empty("OUT", "out.tmp"))
@task(f_out=FILE_OUT)
def func(f_inout):
...
Task Parameters Summary
:numref:task_arguments summarizes all arguments that can be found in the @task decorator.
Argument |
Value |
|
|---|---|---|
Formal parameter name |
(default: empty) |
The parameter is an object or a simple tipe that will be inferred. |
IN |
Read-only parameter, all types. |
|
IN_DELETE |
Read-only parameter, all types. Automatic delete after usage. |
|
INOUT |
Read-write parameter, all types except file and primitives. |
|
OUT |
Write-only parameter, all types except file and primitives (requires default constructor). |
|
CONCURRENT |
Concurrent read-write parameter, all types except file and primitives. |
|
COMMUTATIVE |
Commutative read-write parameter, all types except file and primitives. |
|
FILE(_IN) |
Read-only file parameter. |
|
FILE_INOUT |
Read-write file parameter. |
|
FILE_OUT |
Write-only file parameter. |
|
FILE_CONCURRENT |
Concurrent read-write file parameter. |
|
FILE_COMMUTATIVE |
Commutative read-write file parameter. |
|
DIRECTORY(_IN) |
The parameter is a read-only directory. |
|
DIRECTORY_INOUT |
The parameter is a read-write directory. |
|
DIRECTORY_OUT |
the parameter is a write-only directory. |
|
COLLECTION(_IN) |
Read-only collection parameter ( |
|
COLLECTION_IN_DELETE |
Single usage read-only collection parameter ( |
|
COLLECTION_INOUT |
Read-write collection parameter ( |
|
COLLECTION_OUT |
Read-only collection parameter ( |
|
COLLECTION_FILE(_IN) |
Read-only collection of files parameter ( |
|
COLLECTION_FILE_INOUT |
Read-write collection of files parameter ( |
|
COLLECTION_FILE_OUT |
Read-only collection of files parameter ( |
|
DICTIONARY(_IN) |
Read-only dictionary parameter ( |
|
DICTIONARY_IN_DELETE |
Single usage read-only collection dictionary ( |
|
DICTIONARY_INOUT |
Read-write dictionary parameter ( |
|
STREAM_IN |
The parameter is a read-only stream. |
|
STREAM_OUT |
The parameter is a write-only stream. |
|
STDIN |
The parameter is a file for standard input redirection (only for binaries). |
|
STDOUT |
The parameter is a file for standard output redirection (only for binaries). |
|
STDERR |
The parameter is a file for standard error redirection (only for binaries). |
|
Explicit: |
||
returns |
Return type or number of returned elements |
|
target_direction |
INOUT (default), IN or CONCURRENT |
|
priority |
|
|
is_distributed |
|
|
is_replicated |
|
|
on_failure |
‘RETRY’ (default), ‘CANCEL_SUCCESSORS’, ‘FAIL’ or ‘IGNORE’ |
|
time_out |
|
|
cache_returns |
|
|
is_reduce |
|
|
chunk_size |
Reduction chunk size ( |
|
numba |
True or False (default) or mode ( |
|
numba_flags |
Numba flags ( |
|
numba_signature |
Numba signature ( |
|
numba_declaration |
Numba declaration ( |
|
Task Return
If the function or method returns a value, the programmer can use the returns argument within the @task decorator. In this argument, the programmer can specify the type of that value (Code 126).
@task(returns=int)
def ret_func():
return 1
Moreover, if the function or method returns more than one value, the programmer can specify how many and their type in the returns argument. Code 127 shows how to specify that two values (an integer and a list) are returned.
@task(returns=(int, list))
def ret_func():
return 1, [2, 3]
Alternatively, the user can specify the number of return statements as an integer value (Code 128). This way of specifying the amount of return eases the returns definition since the user does not need to specify explicitly the type of the return arguments. However, it must be considered that the type of the object returned when the task is invoked will be a future object. This consideration may lead to an error if the user expects to invoke a task defined within an object returned by a previous task. In this scenario, the solution is to specify explicitly the return type.
@task(returns=1)
def ret_func():
return "my_string"
@task(returns=2)
def ret_func():
return 1, [2, 3]
Important
If the programmer selects as a task a function or method that returns a value, that value is not generated until the task executes (Code 129).
@task(return=MyClass)
def ret_func():
return MyClass(...)
...
if __name__=='__main__':
o = ret_func() # o is a future object
The object returned can be involved in a subsequent task call, and the COMPSs runtime will automatically find the corresponding data dependency. In the following example, the object o is passed as a parameter and callee of two subsequent (asynchronous) tasks, respectively (Code 130).
if __name__=='__main__':
# o is a future object
o = ret_func()
...
another_task(o)
...
o.yet_another_task()
Tip
PyCOMPSs is able to infer if the task returns something and its amount in most cases. Consequently, the user can specify the task without returns argument. But this is discouraged since it requires code analysis, including an overhead that can be avoided by using the returns argument.
Tip
PyCOMPSs is compatible with Python 3 type hinting. So, if type hinting is present in the code, PyCOMPSs is able to detect the return type and use it (there is no need to use the returns):
@task()
def ret_func() -> str:
return "my_string"
@task()
def ret_func() -> (int, list):
return 1, [2, 3]
Integration with Numba
PyCOMPSs can also be used with Numba. Numba (http://numba.pydata.org/) is an Open Source JIT compiler for Python which provides a set of decorators and functionalities to translate Python functions to optimized machine code.
Basic usage
PyCOMPSs’ tasks can be decorated with Numba’s @jit/@njit decorator
(with the appropriate parameters) just below the @task decorator in order to
apply Numba to the task.
from pycompss.api.task import task # Import @task decorator
from numba import jit
@task(returns=1)
@jit()
def numba_func(a, b):
...
The task will be optimized by Numba within the worker node, enabling COMPSs to use the most efficient implementation of the task (and exploiting the compilation cache – any task that has already been compiled does not need to be recompiled in subsequent invocations).
Advanced usage
PyCOMPSs can be also used in conjunction with the Numba’s
@vectorize, @guvectorize, @stencil and @cfunc.
But since these decorators do not preserve the original argument specification
of the original function, their usage is done through the numba parameter
within the @task decorator.
The numba parameter accepts:
- Boolean:
True: Applies jit to the function.
- Dictionary{k, v}:
Applies jit with the dictionary parameters to the function (allows to specify specific jit parameters (e.g.
nopython=True)).
- String:
"jit": Applies jit to the function."njit": Applies jit with nopython=True to the function."generated_jit": Applies generated_jit to the function."vectorize": Applies vectorize to the function. Needs some extra flags in the @task decorator:numba_signature: String with the vectorize signature.
"guvectorize": Applies guvectorize to the function. Needs some extra flags in the @task decorator:numba_signature: String with the guvectorize signature.
numba_declaration: String with the guvectorize declaration.
"stencil": Applies stencil to the function."cfunc": Applies cfunc to the function. Needs some extra flags in the @task decorator:numba_signature: String with the cfunc signature.
Moreover, the @task decorator also allows to define specific flags for the
jit, njit, generated_jit, vectorize, guvectorize and cfunc
functionalities with the numba_flags hint.
This hint is used to declare a dictionary with the flags expected to use
with these numba functionalities. The default flag included by PyCOMPSs
is the cache=True in order to exploit the function caching of Numba
across tasks.
For example, to apply Numba jit to a task:
from pycompss.api.task import task
@task(numba='jit') # Aternatively: @task(numba=True)
def jit_func(a, b):
...
And if the developer wants to use specific flags with jit (e.g.
parallel=True), the numba_flags must be defined with a dictionary where
the key is the numba flag name, and the value, the numba flag value to use):
from pycompss.api.task import task
@task(numba='jit', numba_flags={'parallel':True})
def jit_func(a, b):
...
Other Numba’s functionalities require the specification of the function signature and declaration. In the next example a task that will use the vectorize with three parameters and a specific flag to target the CPU is shown:
from pycompss.api.task import task
@task(returns=1,
numba='vectorize',
numba_signature=['float32(float32, float32, float32)'],
numba_flags={'target':'cpu'})
def vectorize_task(a, b, c):
return a * b * c
Using Numba with GPUs
In addition, Numba is also able to optimize python code for GPUs that can be used within PyCOMPSs’ tasks. Task using Numba and a GPU shows an example of a task that performs a matrix multiplication in GPU (code from Numba documentation).
The main function creates the input and output matrices, and invokes
the do_matmul task which has a constraint of one CPU and one GPU. This task
first transfers the necessary data to the GPU using Numba’s cuda module,
then invokes the matmul function (that is decorated with
the Numba’s @cuda.jit`). When the execution in the GPU of the
``matmul finishes, the result is transferred to the cpu with
the copy_to_host function and the task result is returned.
import math
from numba import cuda, float64
import numpy as np
from pycompss.api.task import task
from pycompss.api.api import compss_wait_on
from pycompss.api.constraint import constraint
TPB = 16
@cuda.jit
def matmul(A, B, C):
"""Perform square matrix multiplication of C = A * B
"""
i, j = cuda.grid(2)
if i < C.shape[0] and j < C.shape[1]:
tmp = 0.
for k in range(A.shape[1]):
tmp += A[i, k] * B[k, j]
C[i, j] = tmp
@constraint(processors=[{'ProcessorType':'CPU', 'ComputingUnits':'1'},
{'ProcessorType':'GPU', 'ComputingUnits':'1'}])
@task(returns=1)
def do_matmul(a, b, c):
gpu_a = cuda.to_device(a)
gpu_b = cuda.to_device(b)
gpu_c = cuda.to_device(c)
threadsperblock = (TPB, TPB)
blockspergrid_x = math.ceil(gpu_c.shape[0] / threadsperblock[0])
blockspergrid_y = math.ceil(gpu_c.shape[1] / threadsperblock[1])
blockspergrid = (blockspergrid_x, blockspergrid_y)
matmul[blockspergrid, threadsperblock](gpu_a, gpu_b, gpu_c)
c = gpu_c.copy_to_host()
return c
def main():
a = np.random.uniform(1, 2, (4, 4))
b = np.random.uniform(1, 2, (4, 4))
c = np.zeros((4, 4))
result = do_matmul(a, b, c)
result = compss_wait_on(result)
print("a: \n %s" % str(a))
print("b: \n %s" % str(b))
print("Result: \n %s" % str(result))
print("Verification result: ")
print(a @ b)
if __name__=="__main__":
main()
Caution
The function compiled with Numba for GPU can not be a task since the step to transfer the data to the GPU and backwards needs to be explicitly performed by the user.
For this reason, the appropriate structure is composed by a task that has the necessary constraints, deals with the data movements and invokes the function compiled with Numba for GPU.
The main application can then invoke the task.
Important
In order to run with GPUs in local machine, you need to define the available
GPUs in the project.xml file.
As example, the following project.xml and resources.xml shall be
used with the --project and --resources correspondingly:
More details about Numba and the specification of the signature, declaration and flags can be found in the Numba’s webpage (http://numba.pydata.org/).