Licensed Software/MATLAB: Difference between revisions

From HPCwiki
Jump to navigation Jump to search
m Haars0011 moved page Matlab to Licensed Software/MATLAB: Phase 1 § 5 P1.5.8: move MATLAB under Licensed Software as a sub-page (via move-page on MediaWiki MCP Server)
Phase 1 § 5 P1.5.8: rewrite — sentence-case headings, fix broken [url|text] links, syntaxhighlight matlab, fix MATLAB ... continuation; link into Licensed Software hub (via update-page on MediaWiki MCP Server)
 
Line 1: Line 1:
MATLAB is a non-free calculation language owned by Mathworks. The HPC has this installed as part of the WUR academic license, and so this is only available to WUR users.
MATLAB is a commercial numerical computing language owned by MathWorks. It is installed on Anunna under the WUR academic licence, so it is available to WUR users only. It is one of the [[Licensed Software | licensed packages]] on the cluster.


== Getting Started with Parallel Computing using MATLAB on the Anunna HPC Cluster ==
You can run MATLAB on the cluster either by loading the module and working in a cluster session, or by configuring a MATLAB client on your own desktop to submit jobs to Anunna. The sections below cover the parallel-computing setup, which lets MATLAB dispatch work to the cluster's compute nodes.


This document provides the steps to configure MATLAB to submit jobs to a cluster, retrieve results, and debug errors.
== Configuring MATLAB on the cluster ==


=== CONFIGURATION – MATLAB client on the cluster ===
After logging in, load the module and run <code>configCluster.sh</code> once per MATLAB version. This configures MATLAB so that jobs default to the cluster rather than the login node.
After logging into the cluster, configure MATLAB to run parallel jobs on your cluster by calling the shell script '''configCluster.sh'''. (after '''module load matlab''')
This only needs to be called once per version of MATLAB.
$ module load matlab
$ configCluster.sh
Jobs will now default to the cluster rather than submit to the login node.
=== INSTALLATION and CONFIGURATION – MATLAB client on the desktop ===


The Anunna MATLAB support package can be found as follows
<syntaxhighlight lang="bash">
module load matlab
configCluster.sh
</syntaxhighlight>


Windows: https://git.wur.nl/WUR-MATLAB-tools/support_packages/-/raw/main/wur.nonshared.R2022a.zip?inline=false
== Configuring a MATLAB client on your desktop ==


Linux/macOS: https://git.wur.nl/WUR-MATLAB-tools/support_packages/-/raw/main/wur.nonshared.R2022a.tar.gz?inline=false
To submit from MATLAB on your own machine, first install the WUR support package. Download the archive for your platform:


Download the appropriate archive file and start MATLAB. The archive file should be untarred/unzipped in the location returned by calling
* [https://git.wur.nl/WUR-MATLAB-tools/support_packages/-/raw/main/wur.nonshared.R2022a.zip?inline=false Windows (R2022a, .zip)]
>> userpath
* [https://git.wur.nl/WUR-MATLAB-tools/support_packages/-/raw/main/wur.nonshared.R2022a.tar.gz?inline=false Linux / macOS (R2022a, .tar.gz)]
Configure MATLAB to run parallel jobs on your cluster by calling '''configCluster'''. '''configCluster''' only needs to be called once per version of MATLAB.
>> configCluster
Submission to the remote cluster requires SSH credentials. You will be prompted for your ssh username and password or identity file (private key). The username and location of the private key will be stored in MATLAB for future sessions.
Jobs will now default to the cluster rather than submit to the local machine.
NOTE: If you would like to submit to the local machine then run the following command:
>> % Get a handle to the local resources
>> c = parcluster('local');
==== CONFIGURING JOBS====
Prior to submitting the job, we can specify various parameters to pass to our jobs, such as queue, e-mail, walltime, etc. The following is a partial list of parameters.  See AdditionalProperties for the complete list.  Only MemUsage and WallTime are required.  


<pre>
Unpack it in the directory MATLAB reports for <code>userpath</code>, then configure the cluster profile (once per MATLAB version):
>> % Get a handle to the cluster
 
>> c = parcluster;
<syntaxhighlight lang="matlab">
[REQUIRED]
>> userpath
>> configCluster
</syntaxhighlight>


>> % Specify memory to use for MATLAB jobs, per core (default: 4gb)
Submitting to the cluster requires SSH credentials; MATLAB prompts for your SSH username and password or identity file and remembers them for later sessions. Jobs then default to the cluster instead of your local machine. To submit to your local machine instead:
>> c.AdditionalProperties.MemUsage = '6gb';


>> % Specify the walltime (e.g., 5 hours)
<syntaxhighlight lang="matlab">
>> c.AdditionalProperties.WallTime = '05:00:00';
>> c = parcluster('local');
</syntaxhighlight>


[OPTIONAL]
== Configuring jobs ==


>> % Specify an account to use for MATLAB jobs
Before submitting, set job parameters through <code>AdditionalProperties</code>. Only <code>MemUsage</code> and <code>WallTime</code> are required; the rest are optional.
>> c.AdditionalProperties.AccountName = 'account-name';


>> % Assign a comment to the job
<syntaxhighlight lang="matlab">
>> c.AdditionalProperties.Comment = 'a-comment';
>> c = parcluster;


>> % Request a specific GPU flavor (e.g., V100)
% Required
>> c.AdditionalProperties.Constraint = 'V100';
>> c.AdditionalProperties.MemUsage = '6gb';        % memory per core (default 4gb)
>> c.AdditionalProperties.WallTime = '05:00:00';   % walltime, e.g. 5 hours


>> % Specify e-mail address to receive notifications about your job
% Optional
>> c.AdditionalProperties.AccountName = 'account-name';
>> c.AdditionalProperties.Comment = 'a-comment';
>> c.AdditionalProperties.Constraint = 'V100';    % request a specific GPU flavour
>> c.AdditionalProperties.EmailAddress = 'user-id@wur.nl';
>> c.AdditionalProperties.EmailAddress = 'user-id@wur.nl';
>> % Specify number of GPUs
>> c.AdditionalProperties.GpusPerNode = 1;
>> c.AdditionalProperties.GpusPerNode = 1;
 
>> c.AdditionalProperties.QoS = 'the-qos';         % default: std
>> % Specify a QoS (default: std)
>> c.AdditionalProperties.QoS = 'the-qos';
 
>> % Specify a queue to use for MATLAB jobs
>> c.AdditionalProperties.QueueName = 'queue-name';
>> c.AdditionalProperties.QueueName = 'queue-name';
>> % Require exclusive nodes
>> c.AdditionalProperties.RequireExclusiveNode = true;
>> c.AdditionalProperties.RequireExclusiveNode = true;
>> % Specify a reservation
>> c.AdditionalProperties.Reservation = 'a-reservation';
>> c.AdditionalProperties.Reservation = 'a-reservation';
>> c.AdditionalProperties.Tmp = '20g';            % local /tmp space
</syntaxhighlight>


>> % Request there be (for example) 20 GB of local disk space in /tmp
Save the profile so the settings persist between MATLAB sessions, and display the current values with:
>> c.AdditionalProperties.Tmp = 20g;
</pre>


Save changes after modifying AdditionalProperties for the above changes to persist between MATLAB sessions.
<syntaxhighlight lang="matlab">
>> c.saveProfile
>> c.saveProfile
>> c.AdditionalProperties
</syntaxhighlight>


To see the values of the current configuration options, display AdditionalProperties.
Unset a value by assigning an empty string and saving again:


>> % To view current properties
<syntaxhighlight lang="matlab">
>> c.AdditionalProperties
>> c.AdditionalProperties.EmailAddress = '';
>> c.saveProfile
</syntaxhighlight>


Unset a value when no longer needed.
== Interactive pool jobs ==
>> % Turn off email notifications
>> c.AdditionalProperties.EmailAddress = '';
>> c.saveProfile
==== INTERACTIVE JOBS - MATLAB client on the cluster ====  
To run an interactive pool job on the cluster, continue to use parpool as you’ve done before.
Be aware that (depending on load on the cluster) it might take a while for your requested resources to be available.
>> % Get a handle to the cluster
>> c = parcluster;


>> % Open a pool of 64 workers on the cluster
Use <code>parpool</code> as usual; the pool now runs across cluster nodes rather than locally. Depending on cluster load, it may take a while for the requested resources to become available.
>> pool = c.parpool(64);


Rather than running local on the local machine, the pool can now run across multiple nodes on the cluster.
<syntaxhighlight lang="matlab">
>> c = parcluster;
>> pool = c.parpool(64);          % open a pool of 64 workers


>> % Run a parfor over 1000 iterations
>> parfor idx = 1:1000
>> parfor idx = 1:1000
       a(idx) = ...
       a(idx) =
  end
    end


Once we’re done with the pool, delete it.
>> pool.delete                    % close the pool when done
</syntaxhighlight>


>> % Delete the pool
== Independent batch jobs ==
>> pool.delete


==== INDEPENDENT BATCH JOB ====
The <code>batch</code> command submits asynchronous jobs and returns a job object used to retrieve the output.


Use the batch command to submit asynchronous jobs to the cluster.  The batch command will return a job object which is used to access the output of the submitted job.  See the MATLAB documentation for more help on batch.
<syntaxhighlight lang="matlab">
<pre>
>> % Get a handle to the cluster
>> c = parcluster;
>> c = parcluster;
>> job = c.batch(@pwd, 1, {}, 'CurrentFolder', '.', 'AutoAddClientPath', false);


>> % Submit job to query where MATLAB is running on the cluster
>> job.State                      % query state
>> job = c.batch(@pwd, 1, {}, …
>> job.fetchOutputs{:}           % fetch results once finished
      'CurrentFolder','.', 'AutoAddClientPath',false);
>> job.delete                    % delete when no longer needed
</syntaxhighlight>


>> % Query job for state
To list current and past jobs, and fetch results from an earlier one:
>> job.State


>> % If state is finished, fetch the results
<syntaxhighlight lang="matlab">
>> job.fetchOutputs{:}
>> c = parcluster;
>> jobs = c.Jobs;                % array of all jobs
>> job2 = c.Jobs(2);              % a job by index
>> job2.fetchOutputs{:}
</syntaxhighlight>


<code>fetchOutputs</code> retrieves function return values; for a script job, use <code>load</code> instead. Data written to files on the cluster must be retrieved from the filesystem directly.


>> % Delete the job after results are no longer needed
== Parallel batch jobs ==
>> job.delete
</pre>
To retrieve a list of currently running or completed jobs, call parcluster to retrieve the cluster object.  The cluster object stores an array of jobs that were run, are running, or are queued to run.  This allows us to fetch the results of completed jobs.  Retrieve and view the list of jobs as shown below.
>> c = parcluster;
>> jobs = c.Jobs;
Once we’ve identified the job we want, we can retrieve the results as we’ve done previously.
fetchOutputs is used to retrieve function output arguments; if calling batch with a script, use load instead.  Data that has been written to files on the cluster needs be retrieved directly from the file system (e.g. via ftp).


To view results of a previously completed job:
To run a parallel workflow, pass a <code>Pool</code> size to <code>batch</code>. Take this example function, saved as <code>parallel_example.m</code>:
>> % Get a handle to the job with ID 2
>> job2 = c.Jobs(2);


NOTE: You can view a list of your jobs, as well as their IDs, using the above c.Jobs command. 
<syntaxhighlight lang="matlab">
>> % Fetch results for job with ID 2
function [t, A] = parallel_example(iter)
>> job2.fetchOutputs{:}


==== PARALLEL BATCH JOB ====
if nargin == 0
Users can also submit parallel workflows with the batch command.  Let’s use the following example for a parallel job, which is saved as '''parallel_example.m'''. 
<pre>
function [t, A] = parallel_example(iter)
if nargin==0
     iter = 8;
     iter = 8;
end
end
 
disp('Start sim')
disp('Start sim')
t0 = tic;
t0 = tic;
parfor idx = 1:iter
parfor idx = 1:iter
     A(idx) = idx;
     A(idx) = idx;
     pause(2)
     pause(2)
    idx
end
end
t = toc(t0);
t = toc(t0);
disp('Sim completed')
disp('Sim completed')
save RESULTS A
save RESULTS A
 
end
end
</pre>
</syntaxhighlight>
This time when we use the batch command, to run a parallel job, we’ll also specify a MATLAB Pool.   
<pre>
>> % Get a handle to the cluster
>> c = parcluster;


>> % Submit a batch pool job using 4 workers for 16 simulations
Submit it with a pool of workers:
>> job = c.batch(@parallel_example, 1, {16}, 'Pool',4, …
      'CurrentFolder','.', 'AutoAddClientPath',false);


>> % View current job status
<syntaxhighlight lang="matlab">
>> c = parcluster;
>> job = c.batch(@parallel_example, 1, {16}, 'Pool', 4, 'CurrentFolder', '.', 'AutoAddClientPath', false);
>> job.State
>> job.State
>> % Fetch the results after a finished state is retrieved
>> job.fetchOutputs{:}
>> job.fetchOutputs{:}
ans =
</syntaxhighlight>
8.8872
</pre>
The job ran in 8.89 seconds using four workers.  Note that these jobs will always request N+1 CPU cores, since one worker is required to manage the batch job and pool of workers.  For example, a job that needs eight workers will consume nine CPU cores.
We’ll run the same simulation but increase the Pool size.  This time, to retrieve the results later, we’ll keep track of the job ID.


NOTE: For some applications, there will be a diminishing return when allocating too many workers, as the overhead may exceed computation time.  
A pool job always requests '''N+1''' CPU cores: one worker manages the pool, so a job needing eight workers consumes nine cores. Allocating too many workers can give diminishing returns once the coordination overhead outweighs the computation, so tune the worker count for your workload.
<pre>
>> % Get a handle to the cluster
>> c = parcluster;


>> % Submit a batch pool job using 8 workers for 16 simulations
To retrieve a job later, keep its ID and find it again:
>> job = c.batch(@parallel_example, 1, {16}, 'Pool', 8, …
      'CurrentFolder','.', 'AutoAddClientPath',false);


>> % Get the job ID
<syntaxhighlight lang="matlab">
>> id = job.ID
>> id = job.ID
id =
4
>> % Clear job from workspace (as though we quit MATLAB)
>> clear job
>> clear job
</pre>
 
Once we have a handle to the cluster, we’ll call the findJob method to search for the job with the specified job ID. 
<pre>
>> % Get a handle to the cluster
>> c = parcluster;
>> c = parcluster;
>> job = c.findJob('ID', id);
>> job.State
>> job.fetchOutputs{:}
</syntaxhighlight>


>> % Find the old job
== Debugging ==
>> job = c.findJob('ID', 4);


>> % Retrieve the state of the job
If a job errors, view its log with <code>getDebugLog</code>. For an independent multi-task job, give the task; for a pool job, give the job object:
>> job.State
 
ans =
<syntaxhighlight lang="matlab">
finished
>> c.getDebugLog(job.Tasks(3))   % independent job, specific task
>> % Fetch the results
>> c.getDebugLog(job)           % pool job
>> job.fetchOutputs{:};
</syntaxhighlight>
ans =
 
4.7270
If an administrator asks for the scheduler ID of a job:
</pre>
 
The job now runs in 4.73 seconds using eight workers.  Run code with different number of workers to determine the ideal number to use.
<syntaxhighlight lang="matlab">
Alternatively, to retrieve job results via a graphical user interface, use the Job Monitor (Parallel > Monitor Jobs).
==== DEBUGGING ====
If a serial job produces an error, call the getDebugLog method to view the error log file.  When submitting independent jobs, with multiple tasks, specify the task number. 
>> c.getDebugLog(job.Tasks(3))
For Pool jobs, only specify the job object.
>> c.getDebugLog(job)
When troubleshooting a job, the cluster admin may request the scheduler ID of the job.  This can be derived by calling schedID
<pre>
>> schedID(job)
>> schedID(job)
ans =
</syntaxhighlight>
25539
 
</pre>
== See also ==
==== TO LEARN MORE ====
 
To learn more about the MATLAB Parallel Computing Toolbox, check out these resources:
* [[Licensed Software]]
* [https://www.mathworks.com/help/parallel-computing/examples.html|Parallel Computing Coding Examples]
* [[Environment Modules]]
* [http://www.mathworks.com/help/distcomp/index.html|Parallel Computing Documentation]
* [[Batch Jobs]]
* [http://www.mathworks.com/products/parallel-computing/index.html|Parallel Computing Overview]
 
* [http://www.mathworks.com/products/parallel-computing/tutorials.html|Parallel Computing Tutorials]
== External links ==
* [http://www.mathworks.com/products/parallel-computing/videos.html|Parallel Computing Videos]
 
* [http://www.mathworks.com/products/parallel-computing/webinars.html|Parallel Computing Webinars]
* [https://www.mathworks.com/help/parallel-computing/ MATLAB Parallel Computing Toolbox documentation]
* [https://www.mathworks.com/help/parallel-computing/examples.html MATLAB Parallel Computing examples]

Latest revision as of 14:23, 16 June 2026

MATLAB is a commercial numerical computing language owned by MathWorks. It is installed on Anunna under the WUR academic licence, so it is available to WUR users only. It is one of the licensed packages on the cluster.

You can run MATLAB on the cluster either by loading the module and working in a cluster session, or by configuring a MATLAB client on your own desktop to submit jobs to Anunna. The sections below cover the parallel-computing setup, which lets MATLAB dispatch work to the cluster's compute nodes.

Configuring MATLAB on the cluster

After logging in, load the module and run configCluster.sh once per MATLAB version. This configures MATLAB so that jobs default to the cluster rather than the login node.

module load matlab
configCluster.sh

Configuring a MATLAB client on your desktop

To submit from MATLAB on your own machine, first install the WUR support package. Download the archive for your platform:

Unpack it in the directory MATLAB reports for userpath, then configure the cluster profile (once per MATLAB version):

>> userpath
>> configCluster

Submitting to the cluster requires SSH credentials; MATLAB prompts for your SSH username and password or identity file and remembers them for later sessions. Jobs then default to the cluster instead of your local machine. To submit to your local machine instead:

>> c = parcluster('local');

Configuring jobs

Before submitting, set job parameters through AdditionalProperties. Only MemUsage and WallTime are required; the rest are optional.

>> c = parcluster;

% Required
>> c.AdditionalProperties.MemUsage = '6gb';        % memory per core (default 4gb)
>> c.AdditionalProperties.WallTime = '05:00:00';   % walltime, e.g. 5 hours

% Optional
>> c.AdditionalProperties.AccountName = 'account-name';
>> c.AdditionalProperties.Comment = 'a-comment';
>> c.AdditionalProperties.Constraint = 'V100';     % request a specific GPU flavour
>> c.AdditionalProperties.EmailAddress = 'user-id@wur.nl';
>> c.AdditionalProperties.GpusPerNode = 1;
>> c.AdditionalProperties.QoS = 'the-qos';         % default: std
>> c.AdditionalProperties.QueueName = 'queue-name';
>> c.AdditionalProperties.RequireExclusiveNode = true;
>> c.AdditionalProperties.Reservation = 'a-reservation';
>> c.AdditionalProperties.Tmp = '20g';             % local /tmp space

Save the profile so the settings persist between MATLAB sessions, and display the current values with:

>> c.saveProfile
>> c.AdditionalProperties

Unset a value by assigning an empty string and saving again:

>> c.AdditionalProperties.EmailAddress = '';
>> c.saveProfile

Interactive pool jobs

Use parpool as usual; the pool now runs across cluster nodes rather than locally. Depending on cluster load, it may take a while for the requested resources to become available.

>> c = parcluster;
>> pool = c.parpool(64);          % open a pool of 64 workers

>> parfor idx = 1:1000
       a(idx) = ...
   end

>> pool.delete                    % close the pool when done

Independent batch jobs

The batch command submits asynchronous jobs and returns a job object used to retrieve the output.

>> c = parcluster;
>> job = c.batch(@pwd, 1, {}, 'CurrentFolder', '.', 'AutoAddClientPath', false);

>> job.State                      % query state
>> job.fetchOutputs{:}            % fetch results once finished
>> job.delete                     % delete when no longer needed

To list current and past jobs, and fetch results from an earlier one:

>> c = parcluster;
>> jobs = c.Jobs;                 % array of all jobs
>> job2 = c.Jobs(2);              % a job by index
>> job2.fetchOutputs{:}

fetchOutputs retrieves function return values; for a script job, use load instead. Data written to files on the cluster must be retrieved from the filesystem directly.

Parallel batch jobs

To run a parallel workflow, pass a Pool size to batch. Take this example function, saved as parallel_example.m:

function [t, A] = parallel_example(iter)

if nargin == 0
    iter = 8;
end

disp('Start sim')
t0 = tic;
parfor idx = 1:iter
    A(idx) = idx;
    pause(2)
end
t = toc(t0);
disp('Sim completed')
save RESULTS A

end

Submit it with a pool of workers:

>> c = parcluster;
>> job = c.batch(@parallel_example, 1, {16}, 'Pool', 4, 'CurrentFolder', '.', 'AutoAddClientPath', false);
>> job.State
>> job.fetchOutputs{:}

A pool job always requests N+1 CPU cores: one worker manages the pool, so a job needing eight workers consumes nine cores. Allocating too many workers can give diminishing returns once the coordination overhead outweighs the computation, so tune the worker count for your workload.

To retrieve a job later, keep its ID and find it again:

>> id = job.ID
>> clear job

>> c = parcluster;
>> job = c.findJob('ID', id);
>> job.State
>> job.fetchOutputs{:}

Debugging

If a job errors, view its log with getDebugLog. For an independent multi-task job, give the task; for a pool job, give the job object:

>> c.getDebugLog(job.Tasks(3))   % independent job, specific task
>> c.getDebugLog(job)            % pool job

If an administrator asks for the scheduler ID of a job:

>> schedID(job)

See also