Licensed Software/MATLAB: Difference between revisions

From HPCwiki
Jump to navigation Jump to search
Haars001 (talk | contribs)
Replaced with content provided by Mathworks
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)
 
(6 intermediate revisions by 2 users not shown)
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 into the cluster, configure MATLAB to run parallel jobs on your cluster by calling the shell script configCluster.sh  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 local machine.
INSTALLATION and CONFIGURATION – MATLAB client on the desktop
The Anunna MATLAB support package can be found as follows
Windows: TBD
Linux/macOS: TBD


Download the appropriate archive file and start MATLAB. The archive file should be untarred/unzipped in the location returned by calling
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.
 
<syntaxhighlight lang="bash">
module load matlab
configCluster.sh
</syntaxhighlight>
 
== 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:
 
* [https://git.wur.nl/WUR-MATLAB-tools/support_packages/-/raw/main/wur.nonshared.R2022a.zip?inline=false Windows (R2022a, .zip)]
* [https://git.wur.nl/WUR-MATLAB-tools/support_packages/-/raw/main/wur.nonshared.R2022a.tar.gz?inline=false Linux / macOS (R2022a, .tar.gz)]
 
Unpack it in the directory MATLAB reports for <code>userpath</code>, then configure the cluster profile (once per MATLAB version):
 
<syntaxhighlight lang="matlab">
>> userpath
>> userpath
Configure MATLAB to run parallel jobs on your cluster by calling configCluster.  configCluster only needs to be called once per version of MATLAB.
>> configCluster
>> 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.
</syntaxhighlight>
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:
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:
>> % Get a handle to the local resources
 
<syntaxhighlight lang="matlab">
>> c = parcluster('local');
>> c = parcluster('local');
CONFIGURING JOBS
</syntaxhighlight>
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.
 
>> % Get a handle to the cluster
== Configuring jobs ==
>> c = parcluster;
[REQUIRED]


>> % Specify memory to use for MATLAB jobs, per core (default: 4gb)
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.MemUsage = '6gb';


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


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


>> % Specify an account to use for MATLAB jobs
% Optional
>> c.AdditionalProperties.AccountName = 'account-name';
>> c.AdditionalProperties.AccountName = 'account-name';
>> % Assign a comment to the job
>> c.AdditionalProperties.Comment = 'a-comment';
>> c.AdditionalProperties.Comment = 'a-comment';
 
>> c.AdditionalProperties.Constraint = 'V100';     % request a specific GPU flavour
>> % Request a specific GPU flavor (e.g., V100)
>> c.AdditionalProperties.Constraint = 'V100';
 
>> % Specify e-mail address to receive notifications about your job
>> 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;


 
<syntaxhighlight lang="matlab">
Save changes after modifying AdditionalProperties for the above changes to persist between MATLAB sessions.
>> 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
 
Unset a value when no longer needed.
>> % Turn off email notifications
>> c.AdditionalProperties.EmailAddress = '';
>> c.AdditionalProperties.EmailAddress = '';
>> c.saveProfile
>> c.saveProfile
INTERACTIVE JOBS - MATLAB client on the cluster
</syntaxhighlight>
To run an interactive pool job on the cluster, continue to use parpool as you’ve done before.
 
>> % Get a handle to the cluster
== Interactive pool jobs ==
>> 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>
 
== Independent batch jobs ==
 
The <code>batch</code> command submits asynchronous jobs and returns a job object used to retrieve the output.


>> % Delete the pool
<syntaxhighlight lang="matlab">
>> pool.delete
INDEPENDENT BATCH JOB
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.
>> % 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


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.
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>:
>> 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:
>> % 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
>> job2.fetchOutputs{:}
PARALLEL BATCH JOB
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. 
function [t, A] = parallel_example(iter)
function [t, A] = parallel_example(iter)
 
if nargin==0
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
</syntaxhighlight>


This time when we use the batch command, to run a parallel job, we’ll also specify a MATLAB Pool.   
Submit it with a pool of workers:
>> % Get a handle to the cluster
 
<syntaxhighlight lang="matlab">
>> c = parcluster;
>> c = parcluster;
 
>> job = c.batch(@parallel_example, 1, {16}, 'Pool', 4, 'CurrentFolder', '.', 'AutoAddClientPath', false);
>> % Submit a batch pool job using 4 workers for 16 simulations
>> job = c.batch(@parallel_example, 1, {16}, 'Pool',4,
      'CurrentFolder','.', 'AutoAddClientPath',false);
 
>> % View current job status
>> job.State
>> job.State
>> job.fetchOutputs{:}
</syntaxhighlight>


>> % Fetch the results after a finished state is retrieved
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.
>> job.fetchOutputs{:}
ans =
8.8872
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.  
>> % 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
Once we have a handle to the cluster, we’ll call the findJob method to search for the job with the specified job ID. 
 
>> % 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:
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.
 
Alternatively, to retrieve job results via a graphical user interface, use the Job Monitor (Parallel > Monitor Jobs).
<syntaxhighlight lang="matlab">
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
>> schedID(job)
>> schedID(job)
ans =  
</syntaxhighlight>
25539
 
TO LEARN MORE
== See also ==
To learn more about the MATLAB Parallel Computing Toolbox, check out these resources:
 
• Parallel Computing Coding Examples
* [[Licensed Software]]
• Parallel Computing Documentation
* [[Environment Modules]]
• Parallel Computing Overview
* [[Batch Jobs]]
• Parallel Computing Tutorials
 
Parallel Computing Videos
== External links ==
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