Parallel GRASS jobs: Difference between revisions

From GRASS-Wiki
Jump to navigation Jump to search
(pretty code)
(GRASS on a cluster: cross-link wiki pages)
(76 intermediate revisions by 6 users not shown)
Line 2: Line 2:


NOTE: GRASS 6 libraries are NOT thread safe (except for GPDE, see below).
NOTE: GRASS 6 libraries are NOT thread safe (except for GPDE, see below).
GRASS doesn't perform any locking on the files within a GRASS
database, so the user may end up with one process reading a file while
another process is in the middle of writing it. The most problematic
case is the WIND file, which contains the [[current region]], although
there are others.
If a user wants to run multiple commands concurrently, steps need to
be taken to ensure that this type of conflict doesn't happen. For the
current region, the user can use the WIND_OVERRIDE environment variable to
specify a named region which should be used instead of the WIND file.
Or the user can use the GRASS_REGION environment variable to specify the
region parameters (the syntax is the same as the WIND file, but with
newlines replaced with semicolons). With this approach, the region can
only be read, not modified.
Problems can also arise if the user reads files from another mapset while
another session is modifying those files. The WIND file isn't an issue
here, nor are the files containing raster data (which are updated
atomically), but the various support files may be.
See below for ways around these limitations.


=== Background ===
=== Background ===
Line 7: Line 30:
This you should know about GRASS' behaviour concerning multiple jobs:
This you should know about GRASS' behaviour concerning multiple jobs:
* You can run '''multiple processes''' in '''multiple locations''' ([http://grass.osgeo.org/grass64/manuals/html64_user/helptext.html what's that?]). ''Peaceful coexistence.''
* You can run '''multiple processes''' in '''multiple locations''' ([http://grass.osgeo.org/grass64/manuals/html64_user/helptext.html what's that?]). ''Peaceful coexistence.''
* You can run multiple processes in the same mapset, but only if the region is untouched (but it's really not recommended). Better launch each job in its own mapset within the location.
* You can run multiple processes in the same mapset, but only if the region is untouched. If you are unsure, it's recommended to  launch each job in its own mapset within the location.
* You can run '''multiple processes''' in the '''same location''', but in '''different mapsets'''. ''Peaceful coexistence.''
* You can run '''multiple processes''' in the '''same location''', but in '''different mapsets'''. ''Peaceful coexistence.''


Line 16: Line 39:
* time series: run each map elaboration on a different node.
* time series: run each map elaboration on a different node.


=== GPDE using OpenMP ===
See the [[Parallelizing Scripts]] wiki page


The only parallelized library in GRASS >=6.3 is GRASS Partial Differential Equations Library (GPDE). Read more in [[OpenMP]].
== Working with tiles ==


=== PBS ===
Huge map reprojection example:


Note: For PBS details, read on [http://en.wikipedia.org/wiki/Portable_Batch_System here].
'''Q:''' I'd like to try splitting a large raster into small chunks and then projecting each one separately, sending the project command to the background. The problem is that, if the GRASS command changes the region settings, things might not work.


You need essentially two scripts:
'''A:''' {{cmd|r.proj}} doesn't change the region.
* GRASS job script (which takes the name(s) of map(s) to elaborate from environmental variables
* script to launch this GRASS-script as job for each map to elaborate


'''General steps (for multiple serial jobs on many CPUs):'''
Processing the map in chunks requires setting a different region for
each command. That can be done by creating named regions and using the
WIND_OVERRIDE environment variable, e.g.:


* Job definition
<source lang="bash">
** PBS setup (in the header): define calculation time, number of nodes, number of processors, amount of RAM for individual job;
      g.region ... save=region1
** data are stored in centralized directory which is seen by all nodes;
      g.region ... save=region2
* Job execution (launch of jobs)
      ...
** user launches all jobs ("qsub"), they are submitted to the queue. Use the [[GRASS and Shell#GRASS_Batch_jobs|GRASS_BATCH_JOB]] variable to define the name of the elaboration script.
      WIND_OVERRIDE=region1 r.proj ... &
** the scheduler optimizes among all user the execution of the jobs according to available resources and requested resources;
      WIND_OVERRIDE=region2 r.proj ... &
** for the user this means that 0..max jobs are executed in parallel (unless the administrators didn't define either priority or limits). The user can then observe the job queue ("showq") to see other jobs ahead and scheduling of own jobs. Once a job is running, the cluster possibly sends a notification email to the user, the same again when a job is terminating.
      ...
** At the end of the elaboration call a second batch job which only contains g.copy to copy the result into a common mapset. There is a low risk of race condition here in case that two nodes finish at the same time but this could be even trapped in a loop which checks if the target mapset is locked and, if needed, launches g.copy again 'till success.
</source>
* Job planning
** The challenging part for the user is to estimate the execution time since PBS kills jobs which exceed the requested time. The same applies to the request for number of nodes and CPUs per node as well as the amount of needed RAM. Usually tests are needed to see the performance in order to impose the values correctly in the PBS script (see below).


'''How to write the scripts:'''
(for python see the grass.use_temp_region() function)
To avoid race conditions, you can automatically generate multiple mapsets in a given location. When you start GRASS (in your script) with path to grassdata/location/mapset/ and the requested mapset does not yet exist, it will be automatically created. So, as first step in your job script, be sure to run
      g.mapsets add=mapset1_with_data[,mapset2_with_data]
to make the data which you want to elaborate accessible. You would then loop over many map names (e.g. "aqua_lst1km20020706.LST_Night_1km.filt") and launch the script with map name as first parameter:


<source lang="bash">
The main factor which is likely to affect parallelism is the fact that the processes won't share their caches, so there'll be some degree of inefficiency if there's substantial overlap between the source areas for the processes.
      ------- snip (you need to update this for PBS stuff and save as 'launch_grassjob_55min.sh' -----------
 
      #!/bin/sh
If you have more than one such map to project, processing entire maps in parallel might be a better choice (so that you get N maps projected in 10 hours rather than 1 map in 10/N hours).
      ### Project number, enter if applicable (needed to manage your CPU hours)
 
      #PBS -A HPC2N-2008-001
== Parallelized code ==
      #
 
      ### Job name - defaults to name of submit script
=== OpenMP ===
      #PBS -N modis_interpolation_GRASS_RST.sh
 
      #
Good for a single system with a multi-core CPU.
      ### Output files - defaults to jobname.[eo]jobnumber
 
      #PBS -o modis_rst.$MYMODIS.out
Configure GRASS 7 with:
      #PBS -e modis_rst.$MYMODIS.err
./configure --with-openmp
      #
 
      ### Mail on - a=abort, b=beginning, e=end - defaults to a
==== GPDE using OpenMP ====
      #PBS -m abe
 
      ### Number of nodes - defaults to 1:1
The only parallelized library in GRASS >=6.3 is GRASS Partial Differential Equations Library (GPDE) and the gmath library in GRASS 7. Read more in [[OpenMP]].
      ### Requesting 1 nodes with 1 processor per node:
 
      #PBS -l nodes=1:ppn=1
=== Python ===
      ### Requesting time - defaults to 30 minutes
 
      #PBS -l walltime=00:55:00
[http://grass.osgeo.org/grass73/manuals/libpython/pygrass.modules.interface.html?highlight=parallelmodulequeue#pygrass.modules.interface.module.ParallelModuleQueue PyGRASS ParallelModuleQueue]
      ### amount of physical memory (in MB) each processor will use with a line:
 
      #PBS -l pvmem=3000m
=== pthreads ===
 
      # we'll call this script below in a loop, giving the name of the map to elaborate as parameter
Note: only used in the r.mapcalc ''parser''!
      MYMAPSET=$1
 
      MYLOC=nc_spm08
Good for a single system with a multi-core CPU.
      TARGETMAPSET=results
 
     
Configure GRASS 7 with:
      # define as env. variable the batch job which does the real GRASS elaboration (so, which contains the GRASS commands)
./configure --with-pthread
      # (job scripts need executable flag be set)
 
      GRASS_BATCH_JOB=/shareddisk/modis_job.sh
The ''parser'' of {{cmd|r.mapcalc}} in GRASS 7 has been parallelized using GNU {{wikipedia|pthreads}}. The computation itself is executed serially.
      grass64 -c -text /shareddisk/grassdata/$MYLOC/$MYMAPSET
 
     
=== Bourne and Python Scripts ===
      # since we write results to a temporary mapset, copy over result to target mapset
 
      # this we launch again as small GRASS job
Good for a single system with a multi-core CPU.
      export INMAP=${CURRMAP}_rst
 
      export INMAPSET=$MYMAPSET
Often very easy & can be done without modification to the main source code.
      export OUTMAP=$INMAP
 
      export GRASS_BATCH_JOB=/shareddisk/gcopyjob.sh
* See the [[Parallelizing Scripts]] wiki page
      grass64 -c -text  /shareddisk/grassdata/$MYLOC/$TARGETMAPSET
 
      if [ $? -ne 0 ] ; then
=== OpenMPI ===
        # race condition with other copy job...
 
        echo "ERROR while running $GRASS_BATCH_JOB, retrying..."
Good for a multi-system cluster connected by a fast network.
        sleep 2
 
        $HOME/binaries/bin/grass64 -text grassdata/$MYLOC/$TARGETMAPSET
The {{AddonCmd|GIPE}} ''i.vi.mpi'' addon module has been created as a MPI ({{wikipedia|Message Passing Interface}}) implementation of the {{AddonCmd|GIPE}} ''i.vi'' addon module.
        if [ $? -ne 0 ] ; then
* See also the [[Agriculture and HPC]] wiki page.
            echo "ERROR while running $GRASS_BATCH_JOB, retrying..."
 
            sleep 7
=== MPI Programming ===
            $HOME/binaries/bin/grass64 -text grassdata/$MYLOC/$TARGETMAPSET
 
            if [ $? -ne 0 ] ; then
There is a sample implementation at module level in [http://trac.osgeo.org/grass/browser/grass-addons/grass7/imagery/i.vi.mpi i.vi.mpi]
              echo "FINAL ERROR while running $GRASS_BATCH_JOB, giving up!"
 
              exit 1
=== GPU Programming ===
            else
 
              echo "Done $GRASS_BATCH_JOB of <$INMAP>"
Good for certain kinds of calculations (e.g. ray-tracing) on a single system with a fast graphics card.
            fi
 
        else
There is a version of the {{cmd|r.sun}} module which has been modified to use {{wikipedia|OpenCL}}. (works; still experimental)
            echo "Done $GRASS_BATCH_JOB of <$INMAP>"
 
        fi
* See [[GPU]]
      else
 
        echo "Done $GRASS_BATCH_JOB of <$INMAP>"
Configure GRASS 7 with:
      fi
  ./configure --with-opencl
 
== Cluster and Grid computing ==
 
A cluster or grid computing system  consists of a number of computers that are tightly coupled together. The manager or master controls the utilization of compute nodes.
 
=== Job scheduler ===


Common job schedulers are [https://slurm.schedmd.com/ SLURM], [http://www.adaptivecomputing.com/products/open-source/torque/ TORQUE], [http://www.pbspro.org/ PBS], [https://arc.liv.ac.uk/trac/SGE Son of Grid Engine], and [https://kubernetes.io/ kubernetes]


      exit 0
See also [https://slurm.schedmd.com/rosetta.html Rosetta Stone of Workload Managers]
      ------- snap ----------
</source>


You see, that GRASS is run twice. Note that you need GRASS Version >=6.3 to make use of GRASS_BATCH_JOB (if variable is present, GRASS automatically executes that job instead of launching the normal interactive user interface).
A job consists of tasks, e.g. processing of a single raster map in a time series of many raster maps. Jobs are assigned to a queue and started as soon as a slot in the queue is free. Jobs are removed from the queue once they finished.


The script 'gcopyjob.sh' simply contains:
=== GRASS on a cluster ===
<source lang="bash">
      ------- snip -----------
      #!/bin/sh
     
      # copy files from one mapset to another avoiding race conditions on target mapset
      LIST=`g.mlist type=rast mapset=$INMAPSET`
     
      for map in $LIST ; do
        g.copy rast=$map@$INMAPSET,$map --o
        if [ $? -ne 0 ] ; then
                # maybe race condition with other copy job...
                g.message -e 'ERROR while <g.copy ...>, retrying...'
                sleep 2
                g.copy rast=$map@$INMAPSET,$map --o
                if [ $? -ne 0 ] ; then
                        g.message -e 'ERROR while <g.copy ...>, retrying...'
                        sleep 3
                        g.copy rast=$map@$INMAPSET,$map --o
                        if [ $? -ne 0 ] ; then
                                g.message -e 'FINAL ERROR while <g.copy ...>, giving up!'
                                exit 1
                        else
                                echo "Done g.copy of <$map>"
                        fi
                else
                        echo "Done g.copy of <$map>"
                fi
        else
                echo "Done g.copy of <$map>"
        fi
      done
     
      ------- snap ----------
</source>


'''Launching many jobs:'''
If you want to launch several GRASS jobs in parallel, you might consider to launch each job in its own mapset.


We do this by simply looping over all map names to elaborate:
* set up chunks of data to be processed (temporal or spatial, temporal chunks are usually easier to handle)
<source lang="bash">
* write a script with the actual processing of one chunk
      cd /shareddisk/
* write a script that initializes GRASS, creates a unique mapset, executes the script with the actual processing, and copies the results to a common mapset
      # loop and launch (we just pick the names from the GRASS DB itself; here: do all maps)
* add that script as a task to a job, create one job for each data chunk
      # instead of launching immediately, we create a launch script:
      for i in `find grassdata/myloc/modis_originals/cell/ -name '*'` ; do
          NAME=`basename $i`
          echo qsub -v MYMODIS=$NAME ./launch_grassjob_55min.sh
      done | sort > launch1.sh


      # now really launch the jobs:
The general concept is to create a script that
      sh launch1.sh
</source>


That's it! Emails will arrive to notify upon begin, abort (hopefully not!) and end of job execution.
# creates a unique temporary mapset
# creates a unique temporary GISRC file for this mapset
# does the processing in this mapset
# changes to the target mapset by updating the GISRC file, verify with g.gisenv
# copies results from the temporary mapset to the target mapset
# deletes the temporary mapset and GISRC file


=== Grid Engine ===
Such a script should not call grassXY and must be executable outside GRASS, because it is establishing a GRASS session, performing some processing, and closing the GRASS session, all by itself. See also [[GRASS_and_Shell|GRASS and Shell]].


* URL: http://gridengine.sunsource.net/ (see user docs there and [http://docs.sun.com/app/docs/coll/1017.3?q=N1GE here])
Such a script will take arguments to specify the particular data to be processed.
* Lauching jobs: qsub
* Navigating the Grid Engine System with GUI: qmon
* Job statstics: qstat


A job specification for an HPC job scheduler would then contain this script with specific arguments.


Example script to lauch Grid Engine jobs:
The common bottleneck when using GRASS on a cluster is often disk I/O. Try to start the jobs with nice/ionice to reduce strain on the storage devices.
<source lang="bash">
      #!/bin/sh
      # Serial job, MODIS LST elaboration
      # Markus Neteler, 2008
      ## GE settings
      # request Bourne shell as shell for job
      #$ -S /bin/sh
      # run in current working directory
      #$ -cwd
      # We want Grid Engine to send mail when the job begins and when it ends.
      #$ -M neteler@somewhere.it
      #$ -m abe
      # bash debug output
      #set -x
      ############
      # SUBMIT from home dir to node:
      #  cd $HOME
      #  qsub -cwd -l mem_free=3000M -v MYMODIS=aqua_lst1km20020706.LST_Night_1km.filt cea_launch_grassjob_55min.sh
      #
      # WATCH
      #  watch 'qstat  | grep "$USER\|job-ID"'
      #    Under the state column you can see the status of your job. Some of the codes are
      #    * r: the job is running
      #    * t: the job is being transferred to a cluster node
      #    * qw: the job is queued (and not running yet)
      #    * Eqw: an error occurred with the job
      #
      ###########
      # mount shared filesystem (not needed on al clusters)
      gfsmount
      # Change to the directory where the files are located
      export GFSDIR=/gfs/`whoami`
      cd $GFSDIR
      export MYGDATA=$GFSDIR/grassdata
      ########### nothing to change below ###########
      export MODISMAP="$MYMODIS"
      # use map name as MAPSET to avoid GRASS lock
      MYMAPSET=`echo $MYMODIS | sed 's+_1km.filt++g'`
      MYLOC=pat
      MYUSER=$MYMAPSET
      TARGETMAPSET=modisLSTinterpolation
      GRASS_BATCH_JOB=$HOME/modis_interpolation_GRASS_RST.sh
      # print nice percentages:
      export GRASS_MESSAGE_FORMAT=plain
      ####
      # better say where to find libs and bins:
      export PATH=$HOME/binaries/bin:$PATH
      export LD_LIBRARY_PATH=$HOME/binaries/lib/
      rm -f modis_rst.$MYMODIS.out modis_rst.$MYMODIS.err
      # Set the global grassrc file with individual file name
      # don't use HOME but $GFSDIR:
      MYGISRC="$GFSDIR/.grassrc6.$MYUSER.`uname -n`.$MYMODIS"
      #generate GISRCRC
      echo "GISDBASE: $MYGDATA" > "$MYGISRC"
      echo "LOCATION_NAME: $MYLOC" >> "$MYGISRC"
      echo "MAPSET: $MYMAPSET" >> "$MYGISRC"
      echo "GRASS_GUI: text"  >> "$MYGISRC"
      echo "MYGISRC: $MYGISRC"
      cat $MYGISRC
      # say that we are running
      echo "GISDBASE=$MYGDATA/$MYLOC/$MYMAPSET" > $GFSDIR/running_job.$JOB_NAME$.$SGE_CELL.txt
      echo "SGE_JOBNAME: $JOB_NAME; SGE_CELL: $SGE_CELL" >> $GFSDIR/running_job.$JOB_NAME.$SGE_CELL.txt
      # path to GRASS settings file
      export GISRC=$MYGISRC
      # vars defined above:
      export GRASS_BATCH_JOB
      export MODISMAP
      # run the GRASS job:
      $HOME/binaries/bin/grass64 -c -text $MYGDATA/$MYLOC/$MYMAPSET
      # copy over result to target mapset
      export INMAP=${MYMODIS}_rst_model
      export INMAPSET=$MYMAPSET
      export OUTMAP=`echo $INMAP | sed 's+_1km.filt_rst_model+_1km.rst+g'`
      export GRASS_BATCH_JOB=$HOME/gcopyjob.sh
      $HOME/binaries/bin/grass64 -text $MYGDATA/$MYLOC/$TARGETMAPSET
      # remove tmp mapset
      rm -rf $MYGDATA/$MYLOC/$MYMAPSET
      rm -f $GFSDIR/running_job.$JOB_NAME$.$SGE_CELL.txt ${MYGISRC}
      echo "Hopefully successfully finished"
      # unmount shared filesystem (not needed on al clusters)
      cd /
      fusermount -u $GFSDIR
      exit 0
</source>


Launch many jobs through "for" loop as described in the PBS section above.
== Cloud computing ==


=== OpenMosix ===
GRASS GIS 7 is running in the cloud as web processing service backend. Have a look at:


''NOTE: The openMosix Project has officially closed as of March 1, 2008.''
{{YouTube|jg2pb_Xjq8Y|desc=GRASS 7 in the cloud (by Sören Gebbert)}}


If you want to launch several GRASS jobs in parallel, you have to launch each job in its own mapset. Be sure to indicate the mapset correctly in the GISRC file (see above). You can use the process ID (PID, get with $$ or use PBS jobname) to generate a almost unique number which you can add to the mapset name.
This Open Cloud GIS has been set up in a private Amazon compatible cloud environment using:
* Ubuntu 10.04 LTS and 10.10 cloud server edition
* Eucalyptus Cloud
* GRASS GIS 7 latest svn
* PyWPS latest svn
* wps-grass-bridge latest svn
* QGIS 1.7 with a modified QWPS plugin


== GRASS GIS on VPS ==


Now you could launch the jobs on an [http://openmosix.sourceforge.net/ openMosix cluster] (just install openMosix on your colleague's computers...).
Instructions to run GRASS GIS on a commercial VPS to do some memory-intensive operations:


=== Tips & Tricks ===
http://plantarum.ca/code/medium-performance-cluster/


* When working with long time series and {{cmd|r.series}} starts to complain that files are missing/not readable, check if you opened more than 1024 files in this process. this is the typical limit (check with ulimit -n). To overcome this problem, the admin has to add in /etc/security/limits.conf something like this:
== Hints for NFS users ==
* AVOID script forking on the cluster (but inclusion via ". script.sh" works ok). This means that the GRASS_BATCH_JOB approach is prone to '''fail'''. It is highly recommended to simply set a series of environmental variables to define the GRASS session, see [[GRASS_and_Shell#Automated_batch_jobs:_Setting_the_GRASS_environmental_variables|here]] how to do that.
* be careful with concurrent file writing (use "lockfile" locking, the lockfile command is provided by [http://www.procmail.org/ procmail]);
* store as much temporary data as possible (even the final maps) on the local blade disks if you have.
* finally collect all results from local blade disks *after* the parallel job execution in a sequential collector job (I am writing that now) to not kill NFS. For example, Grid Engine offers a "hold" function to only execute the collector job after having done the rest.
* If all else fails, and the I/O load is not too great, consider using {{wikipedia|sshfs}} with ssh passkeys instead of NFS.
* In some situations it is necessary to preserve the same directory structure on all nodes, and symlinks are a nice way to do that, but some (closed source 3rd party which will remain nameless) software insists on expanding symlinks. In this situation the [http://code.google.com/p/bindfs/ bindfs] FUSE extension can help. It is safer to use than "mount" binds, and you don't have to be root to set them up. As with ''sshfs'' there is a performance penalty so it may not be appropriate in high I/O situations.


  # Limit user nofile - max number of open files
== Error: Too many open files ==
  * soft  nofile 1500
  * hard  nofile 1800


For less invasive solution which still requires root access, see [http://lists.osgeo.org/pipermail/grass-dev/2008-November/040886.html here].
When working with long time series and {{cmd|r.series}} starts to complain that files are missing/not readable or the message
Too many open files


For a solution, see [[Large_raster_data_processing#Number_of_open_files_limitation]]


* See the poor-man's multi-processing script on the [[OpenMP]] wiki page.
== Misc Tips & Tricks ==
See the poor-man's multi-processing script on the [[Parallelizing Scripts]] wiki page. This approach has been used in the {{AddonCmd|r3.in.xyz}} addon script.


== See also ==
== See also ==


This Wiki:
* [[GRASS_and_Shell#Automated_batch_jobs:_Setting_the_GRASS_environmental_variables|GRASS batch jobs]] (by settings env. variables)
* The [[OpenMP]] wiki page.
* The [[Parallelizing Scripts]] wiki page.
* [[GPU]] computing
Elsewhere:
* [http://gfoss.blogspot.com/2008/11/building-cluster-for-grass-gis-and.html Building a cluster for GRASS GIS and other software from the OSGeo stack]
* [http://gfoss.blogspot.com/2008/11/building-cluster-for-grass-gis-and.html Building a cluster for GRASS GIS and other software from the OSGeo stack]
 
* https://research.csc.fi/supercomputers-and-gis
 


[[Category:Parallelization]]
[[Category:Parallelization]]
[[Category: massive data analysis]]

Revision as of 21:39, 10 March 2018

Parallel GRASS jobs

NOTE: GRASS 6 libraries are NOT thread safe (except for GPDE, see below).

GRASS doesn't perform any locking on the files within a GRASS database, so the user may end up with one process reading a file while another process is in the middle of writing it. The most problematic case is the WIND file, which contains the current region, although there are others.

If a user wants to run multiple commands concurrently, steps need to be taken to ensure that this type of conflict doesn't happen. For the current region, the user can use the WIND_OVERRIDE environment variable to specify a named region which should be used instead of the WIND file.

Or the user can use the GRASS_REGION environment variable to specify the region parameters (the syntax is the same as the WIND file, but with newlines replaced with semicolons). With this approach, the region can only be read, not modified.

Problems can also arise if the user reads files from another mapset while another session is modifying those files. The WIND file isn't an issue here, nor are the files containing raster data (which are updated atomically), but the various support files may be.

See below for ways around these limitations.

Background

This you should know about GRASS' behaviour concerning multiple jobs:

  • You can run multiple processes in multiple locations (what's that?). Peaceful coexistence.
  • You can run multiple processes in the same mapset, but only if the region is untouched. If you are unsure, it's recommended to launch each job in its own mapset within the location.
  • You can run multiple processes in the same location, but in different mapsets. Peaceful coexistence.

Approach

Essentially there are at least two approaches of "poor man" parallelization without modifying GRASS source code:

  • split map into spatial chunks (possibly with overlap to gain smooth results)
  • time series: run each map elaboration on a different node.

See the Parallelizing Scripts wiki page

Working with tiles

Huge map reprojection example:

Q: I'd like to try splitting a large raster into small chunks and then projecting each one separately, sending the project command to the background. The problem is that, if the GRASS command changes the region settings, things might not work.

A: r.proj doesn't change the region.

Processing the map in chunks requires setting a different region for each command. That can be done by creating named regions and using the WIND_OVERRIDE environment variable, e.g.:

       g.region ... save=region1
       g.region ... save=region2
       ...
       WIND_OVERRIDE=region1 r.proj ... &
       WIND_OVERRIDE=region2 r.proj ... &
       ...

(for python see the grass.use_temp_region() function)

The main factor which is likely to affect parallelism is the fact that the processes won't share their caches, so there'll be some degree of inefficiency if there's substantial overlap between the source areas for the processes.

If you have more than one such map to project, processing entire maps in parallel might be a better choice (so that you get N maps projected in 10 hours rather than 1 map in 10/N hours).

Parallelized code

OpenMP

Good for a single system with a multi-core CPU.

Configure GRASS 7 with:

./configure --with-openmp

GPDE using OpenMP

The only parallelized library in GRASS >=6.3 is GRASS Partial Differential Equations Library (GPDE) and the gmath library in GRASS 7. Read more in OpenMP.

Python

PyGRASS ParallelModuleQueue

pthreads

Note: only used in the r.mapcalc parser!

Good for a single system with a multi-core CPU.

Configure GRASS 7 with:

./configure --with-pthread

The parser of r.mapcalc in GRASS 7 has been parallelized using GNU pthreads. The computation itself is executed serially.

Bourne and Python Scripts

Good for a single system with a multi-core CPU.

Often very easy & can be done without modification to the main source code.

OpenMPI

Good for a multi-system cluster connected by a fast network.

The GIPE i.vi.mpi addon module has been created as a MPI (Message Passing Interface) implementation of the GIPE i.vi addon module.

MPI Programming

There is a sample implementation at module level in i.vi.mpi

GPU Programming

Good for certain kinds of calculations (e.g. ray-tracing) on a single system with a fast graphics card.

There is a version of the r.sun module which has been modified to use OpenCL. (works; still experimental)

Configure GRASS 7 with:

 ./configure --with-opencl

Cluster and Grid computing

A cluster or grid computing system consists of a number of computers that are tightly coupled together. The manager or master controls the utilization of compute nodes.

Job scheduler

Common job schedulers are SLURM, TORQUE, PBS, Son of Grid Engine, and kubernetes

See also Rosetta Stone of Workload Managers

A job consists of tasks, e.g. processing of a single raster map in a time series of many raster maps. Jobs are assigned to a queue and started as soon as a slot in the queue is free. Jobs are removed from the queue once they finished.

GRASS on a cluster

If you want to launch several GRASS jobs in parallel, you might consider to launch each job in its own mapset.

  • set up chunks of data to be processed (temporal or spatial, temporal chunks are usually easier to handle)
  • write a script with the actual processing of one chunk
  • write a script that initializes GRASS, creates a unique mapset, executes the script with the actual processing, and copies the results to a common mapset
  • add that script as a task to a job, create one job for each data chunk

The general concept is to create a script that

  1. creates a unique temporary mapset
  2. creates a unique temporary GISRC file for this mapset
  3. does the processing in this mapset
  4. changes to the target mapset by updating the GISRC file, verify with g.gisenv
  5. copies results from the temporary mapset to the target mapset
  6. deletes the temporary mapset and GISRC file

Such a script should not call grassXY and must be executable outside GRASS, because it is establishing a GRASS session, performing some processing, and closing the GRASS session, all by itself. See also GRASS and Shell.

Such a script will take arguments to specify the particular data to be processed.

A job specification for an HPC job scheduler would then contain this script with specific arguments.

The common bottleneck when using GRASS on a cluster is often disk I/O. Try to start the jobs with nice/ionice to reduce strain on the storage devices.

Cloud computing

GRASS GIS 7 is running in the cloud as web processing service backend. Have a look at:


GRASS 7 in the cloud (by Sören Gebbert)

This Open Cloud GIS has been set up in a private Amazon compatible cloud environment using:

  • Ubuntu 10.04 LTS and 10.10 cloud server edition
  • Eucalyptus Cloud
  • GRASS GIS 7 latest svn
  • PyWPS latest svn
  • wps-grass-bridge latest svn
  • QGIS 1.7 with a modified QWPS plugin

GRASS GIS on VPS

Instructions to run GRASS GIS on a commercial VPS to do some memory-intensive operations:

http://plantarum.ca/code/medium-performance-cluster/

Hints for NFS users

  • AVOID script forking on the cluster (but inclusion via ". script.sh" works ok). This means that the GRASS_BATCH_JOB approach is prone to fail. It is highly recommended to simply set a series of environmental variables to define the GRASS session, see here how to do that.
  • be careful with concurrent file writing (use "lockfile" locking, the lockfile command is provided by procmail);
  • store as much temporary data as possible (even the final maps) on the local blade disks if you have.
  • finally collect all results from local blade disks *after* the parallel job execution in a sequential collector job (I am writing that now) to not kill NFS. For example, Grid Engine offers a "hold" function to only execute the collector job after having done the rest.
  • If all else fails, and the I/O load is not too great, consider using sshfs with ssh passkeys instead of NFS.
  • In some situations it is necessary to preserve the same directory structure on all nodes, and symlinks are a nice way to do that, but some (closed source 3rd party which will remain nameless) software insists on expanding symlinks. In this situation the bindfs FUSE extension can help. It is safer to use than "mount" binds, and you don't have to be root to set them up. As with sshfs there is a performance penalty so it may not be appropriate in high I/O situations.

Error: Too many open files

When working with long time series and r.series starts to complain that files are missing/not readable or the message

Too many open files

For a solution, see Large_raster_data_processing#Number_of_open_files_limitation

Misc Tips & Tricks

See the poor-man's multi-processing script on the Parallelizing Scripts wiki page. This approach has been used in the r3.in.xyz addon script.

See also

This Wiki:

Elsewhere: