PXL
pxl::Map Class Reference

The Map class represents a map operation in the XCENA execution framework. More...

#include <map.hpp>

Public Types

using CompletionCallback = std::function< void(void *arg)>
 Callback function type for task completion. More...
 
using MessageCallback = std::function< void(void *message, void *arg)>
 Callback function type for task message. More...
 
using ErrorCallback = std::function< void(void *arg)>
 Callback function type for task error. More...
 

Public Member Functions

void setCompletionCallback (const CompletionCallback &callback, void *arg)
 Set the success callback function and user data. More...
 
void setMessageCallback (const MessageCallback &callback, void *arg)
 Set the message callback function and user data. More...
 
void setErrorCallback (const ErrorCallback &callback, void *arg)
 Set the error callback function and user data. More...
 
void setBatchSize (const uint32_t &batchSize)
 Sets batchSize for the task. More...
 
uint32_t getBatchSize () const
 Returns the batch size the next execution will use. More...
 
uint32_t getTaskCount () const
 Returns the task count this map was built with. More...
 
void setClusterBitmap (const uint32_t &clusterBitmap)
 Set the cluster bitmap for the map operation. More...
 
void setLocalityMode (const LocalityMode &mode)
 Set the locality mode for the map operation. More...
 
void setStream ()
 Set the default stream for the map operation. More...
 
void setStream (Stream *stream)
 Set the stream for the map operation. More...
 
uint32_t streamId () const
 Returns the stream ID that the map operation is associated with. More...
 
Result execute ()
 
template<typename... ARGS>
Result execute (ARGS &&... args)
 Execute the map operation. This method executes the map operation with the provided input arguments. More...
 
Result execute (std::vector< ArgInfo_t > &args)
 Execute the map operation with a vector of argument information. This method executes the map operation with the provided argument information. More...
 
template<typename... ARG>
Result setInput (ARG &&... args)
 Set the input for the map operation. This method sets the input for the map operation. More...
 
template<typename... ARG>
Result setOutput (ARG &&... args)
 Set the output for the map operation. This method sets the output for the map operation. More...
 
Result setInput (std::vector< ArgInfo_t > &args)
 Set the input for the map operation. This method sets the input for the map operation. More...
 
Result setOutput (std::vector< ArgInfo_t > &args)
 Set the output for the map operation. This method sets the output for the map operation. More...
 
Result cancel ()
 Request cancellation of the map operation and wait until it stops. More...
 
Result synchronize ()
 Synchronize the map operation. This method synchronizes the map operation, ensuring that all tasks are completed. More...
 
ExecuteStatus getExecuteStatus () const
 Gets the execution status of the map operation. More...
 
Progress_t getProgress () const
 Get dispatch/completion progress for the current or last run. More...
 
std::vector< KernelError_t > getKernelError ()
 Gets the error report of the map operation. More...
 
std::string getStats () const
 Gets the execution statistics of the map operation. More...
 
uint64_t id () const
 Gets ID of map object. More...
 
uint32_t deviceId () const
 Returns the device id this Map runs on. More...
 
Result enableProfiling (const xpti::ProfileConfig &config)
 Enable profiling for this map with the given configuration. More...
 
template<xpti::QueryKey Key>
xpti::SessionData< Key > getProfilingData (const xpti::QueryFilter &filter={}) const
 Get profiling data with type-safe automatic type deduction. More...
 
Result exportProfiling (const std::string &path, xpti::ExportFormat format) const
 Export profiling data in the specified format. More...
 
Result exportProfilingCsv (const std::string &path="") const
 Export profiling data to CSV files (convenience wrapper). More...
 

Protected Member Functions

virtual ~Map ()=default
 Default virtual destructor. More...
 

Friends

class impl::MapFactory
 

Detailed Description

The Map class represents a map operation in the XCENA execution framework.

The Map class is responsible for executing a map operation on a given job. It provides methods to set input and output arguments, set the batch size and synchronize the execution. The map operation can be executed by calling the execute method.

If a completion, message, or error callback throws, the exception is caught and logged on the invoking thread. It does not propagate through execute() or synchronize(), or escape the thread invoking the callback. Report callback failures through application-managed state instead of throwing.

Definition at line 47 of file map.hpp.

Member Typedef Documentation

◆ CompletionCallback

using pxl::Map::CompletionCallback = std::function<void(void* arg)>

Callback function type for task completion.

Parameters
argArgument to be passed to the callback function.

This callback is called when the map has completed execution.

Definition at line 59 of file map.hpp.

◆ ErrorCallback

using pxl::Map::ErrorCallback = std::function<void(void* arg)>

Callback function type for task error.

Parameters
argArgument to be passed to the callback function.

This callback is called when the map has encountered an error during execution.

Definition at line 78 of file map.hpp.

◆ MessageCallback

using pxl::Map::MessageCallback = std::function<void(void* message, void* arg)>

Callback function type for task message.

Parameters
messagePointer to the device's message data.
argArgument to be passed to the callback function.

This callback is called when the map has received a message from the device.

Definition at line 69 of file map.hpp.

Constructor & Destructor Documentation

◆ ~Map()

virtual pxl::Map::~Map ( )
protectedvirtualdefault

Default virtual destructor.

Member Function Documentation

◆ cancel()

Result pxl::Map::cancel ( )

Request cancellation of the map operation and wait until it stops.

Returns
Result indicating the outcome of the cancellation request.
  • Success: there was no active execution, the cancellation was honored, or the execution had already been recorded as finished when this call arrived.
  • DeviceError: the execution this call waited on ended in Fail; callers should not re-execute.

Cancellation is a soft stop: tasks already dispatched to the device cannot be interrupted. This call sets a cancel flag, then waits for any in-flight tasks to complete naturally. Once all outstanding work is drained, the map transitions to ExecuteStatus::Cancelled and this call returns.

Side effects:

  • Remaining (unissued) batches are skipped.
  • Output data is not synced back (syncFromDevice is skipped).
  • Neither the completion callback nor the error callback is invoked, EXCEPT when a device error occurs concurrently with cancel. In that case the map transitions to Fail (not Cancelled) and the error callback fires so the caller can diagnose the hardware condition.
  • The message callback is still invoked for messages received before cancel took effect.

After a successful cancellation, the map may be re-executed via execute(). The internal argument caches (pinned device memory for constants and NDArrays) are preserved across cancel so re-execute with the same argument types avoids re-allocation.

When called during an active execution, cancel() waits for its completion record to be published and returns the recorded result. If the record has already been published, cancel() returns Success without making any changes, even when the execution failed. Consequently, two cancellation requests for the same failed run return DeviceError and then Success.

Completion and error callbacks run after the record is published, so a cancel() call from either callback also returns Success without making any changes. Success does not imply that the Map can be executed again; check getExecuteStatus() before re-executing it.

Warning
Do not call this function from a Map message callback. The same dispatch thread delivers the task completions that cancel() waits for.

This function leaves the Map unchanged and returns Success if the Map has not started yet (Idle) or its most recent execution has already been recorded.

Note
This is a blocking call. It waits indefinitely for outstanding device work to complete. A non-blocking variant may be added later.

Example usage:

map->execute(input1, input2);
// ... some condition triggers cancellation
if (map->cancel() == pxl::Result::Success)
{
// Inspect the status: an active run may now be Cancelled, while an
// already-terminal map keeps its existing status.
}

◆ deviceId()

uint32_t pxl::Map::deviceId ( ) const

Returns the device id this Map runs on.

◆ enableProfiling()

Result pxl::Map::enableProfiling ( const xpti::ProfileConfig &  config)

Enable profiling for this map with the given configuration.

Parameters
configProfile configuration to use for profiling.
Returns
Result indicating the success or failure of the operation.
Note
When the XPTI_ENABLE=1 environment variable is set (e.g., via xtop run), profiling is automatically enabled in the constructor with a default configuration. In this case, subsequent calls to enableProfiling() are ignored and return Success. xtop run controls profiling entirely through its own configuration (YAML/env vars), so user-specified config is intentionally not applied.

Example usage:

xpti::ProfileConfig config;
config.mode = xpti::ProfileMode::HostAndDevice;
config.hostSamplingRate = 1000; // milliseconds (0 = use default 1000ms)
config.deviceSamplingRate = 100; // milliseconds (0 = use default 1ms)
config.collectMetrics = true;
config.collectEvents = true;
auto result = map->enableProfiling(config);
if (result != pxl::Result::Success)
{
// Handle error
}

◆ execute() [1/3]

Result pxl::Map::execute ( )
inline

Definition at line 245 of file map.hpp.

246  {
248  }

◆ execute() [2/3]

template<typename... ARGS>
Result pxl::Map::execute ( ARGS &&...  args)
inline

Execute the map operation. This method executes the map operation with the provided input arguments.

Template Parameters
ARGSTypes of the input arguments.
Parameters
argsInput arguments.
Returns
Result indicating the success or failure of the operation.
Note
If the underlying stream's internal queue is full, this call blocks until a slot becomes available. Returns Failure if the stream is torn down or its consumer thread dies while waiting.
Warning
If validation fails because the argument count is too high, a host-memory pointer is unsupported, or an NDArray shape does not match, this function returns InvalidArgument and leaves the Map in ExecuteStatus::Fail. Rebuild the Map before retrying.

Example usage:

const uint32_t testCount = 100;
auto map = job->buildMap(testCount);
auto input1 = new int [testCount];
auto input2 = new float [testCount];
auto input3 = std::make_unique<double[]>(testCount);
... //set input args
auto result = map->execute(input1, input2, input3.get());
if (result != pxl::Result::Success)
{
// Handle map operation failure
}

Definition at line 286 of file map.hpp.

287  {
288  std::vector<ArgInfo_t> argInfos;
289  if (buildArgInfo(argInfos, std::forward<ARGS>(args)...) == false)
290  {
292  }
293 
294  return execute(argInfos);
295  }
Result execute()
Definition: map.hpp:245

◆ execute() [3/3]

Result pxl::Map::execute ( std::vector< ArgInfo_t > &  args)

Execute the map operation with a vector of argument information. This method executes the map operation with the provided argument information.

Parameters
argsA vector of ArgInfo_t structures containing the argument information.
Returns
Result indicating the success or failure of the operation.
Note
If the underlying stream's internal queue is full, this call blocks until a slot becomes available. Returns Failure if the stream is torn down or its consumer thread dies while waiting.
Warning
If validation fails because the argument count is too high, the vector is empty, a host-memory pointer is unsupported, or an NDArray shape does not match, this function returns InvalidArgument and leaves the Map in ExecuteStatus::Fail. Rebuild the Map before retrying.

Example usage:

std::vector<ArgInfo_t> args;
args.push_back(ArgInfo_t{ArgType::Constant, &input1, sizeof(int)});
args.push_back(ArgInfo_t{ArgType::DeviceMemory, input2, sizeof(float*)});
args.push_back(ArgInfo_t{ArgType::NDArray, &ndarrayArg, sizeof(NDArray<float>)});
... //set input args
auto result = map->execute(args);
if (result != pxl::Result::Success)
{
// Handle map operation failure
}

◆ exportProfiling()

Result pxl::Map::exportProfiling ( const std::string &  path,
xpti::ExportFormat  format 
) const

Export profiling data in the specified format.

Parameters
pathOutput directory path (empty string uses default: "session_data").
formatExport format: Csv, Xpti, or Both.
Returns
Result indicating the success or failure of the operation.

Example usage:

// Export as .xpti (SQLite) for xtop analysis
map->exportProfiling("./output", xpti::ExportFormat::Xpti);
// Export as CSV
map->exportProfiling("./output", xpti::ExportFormat::Csv);
// Export both formats
map->exportProfiling("./output", xpti::ExportFormat::Both);

◆ exportProfilingCsv()

Result pxl::Map::exportProfilingCsv ( const std::string &  path = "") const

Export profiling data to CSV files (convenience wrapper).

Parameters
pathOutput path for CSV files (empty string uses default: "session_data").
Returns
Result indicating the success or failure of the operation.

◆ getBatchSize()

uint32_t pxl::Map::getBatchSize ( ) const

Returns the batch size the next execution will use.

Returns
Tasks each MU Core runs back to back. This is the runtime default until setBatchSize() changes it, and the default is not 1.
Note
A map dispatches ceil(taskCount / batchSize) packets, not taskCount. A caller whose kernel expects every task to be running at the same time — one that waits for its peers before returning — must check this is 1 and call setBatchSize(1) if it is not: with a larger batch the core runs its tasks one after another, so waiting for a peer means waiting for a task that has not started.
Warning
Read it back after setting it. setBatchSize() returns void and declines silently on a map that was already invalidated, leaving the default in place; reading it back is the only way to see that. A map invalidated after the set still reports 1 — invalidation does not undo it — but that case ends in execute() returning InvalidArgument, not in the hang above.
Note
Read this before execute(). It reports what setBatchSize() last accepted, so it is only meaningful on the thread that configures the map.

Example usage:

map->setBatchSize(1);
if (map->getBatchSize() != 1)
{
// The map is invalidated. Do not launch a peer-waiting kernel.
}

◆ getExecuteStatus()

ExecuteStatus pxl::Map::getExecuteStatus ( ) const

Gets the execution status of the map operation.

Returns
ExecuteStatus for the current or most recent execution. This is a live snapshot: while a run is in flight it reports the stage that run has reached, so on its own it does not tell the caller that a run finished.

Whether a request was accepted is the return value of execute(), and whether a finished run ended in error is the return value of synchronize(). This call answers the remaining question: once synchronize() has returned, whether the run completed normally or was cancelled.

Example usage:

// synchronize() returned Success, so the run is finished and did not
// fail. Only Completed and Cancelled remain.
if (map->getExecuteStatus() == pxl::ExecuteStatus::Cancelled)
{
// A cancel() landed before the run finished.
}
Note
Successful execution reports ExecuteStatus::Completed. Code that previously treated ExecuteStatus::Idle as successful completion must migrate to Completed or use the result of synchronize().

◆ getKernelError()

std::vector<KernelError_t> pxl::Map::getKernelError ( )

Gets the error report of the map operation.

Returns
Vector of KernelError_t structures containing the error report. If the task is successful, the beginIndex and endIndex will be set to 0xFFFFFFFF. If the task is unsuccessful, the beginIndex and endIndex will indicate the range of the failed task index.

Example usage:

auto kernelError = map->getKernelError();
for (const auto& error : kernelError)
{
if (error.beginIndex != 0xFFFFFFFF && error.endIndex != 0xFFFFFFFF)
{
// Handle error
}
}

◆ getProfilingData()

template<xpti::QueryKey Key>
xpti::SessionData<Key> pxl::Map::getProfilingData ( const xpti::QueryFilter &  filter = {}) const
inline

Get profiling data with type-safe automatic type deduction.

Template Parameters
KeyQuery key type (e.g., xpti::QueryKey::EventsDevice, xpti::QueryKey::MetricsRawL1)
Parameters
filterOptional filter to apply to the data (default: no filter).
Returns
Profiling collection that behaves like a std::vector and exposes exportCsv().

Example usage:

auto events = map->getProfilingData<xpti::QueryKey::EventsDevice>();
// Export with custom path
events.exportCsv(\"filtered_events.csv\");
// Export with default path (session_data/DeviceEvents.csv)
events.exportCsv(\"\");
for (const auto& event : events)
{
// inspect data
}

Definition at line 674 of file map.hpp.

674  {}) const
675  {
676  // Use this map's id() as sessionId
677  return xpti::getSessionData<Key>(id(), filter);
678  }

◆ getProgress()

Progress_t pxl::Map::getProgress ( ) const

Get dispatch/completion progress for the current or last run.

Returns
Progress_t with target/issued/done packet counts.

Counts are updated live while the map is executing and remain at the run's final values after it reaches a terminal state (Completed / Fail / Cancelled). On cancel, targetCount is clamped to whatever was already dispatched, so doneCount == targetCount means all in-flight work has drained.

Note
Reads are not serialized against the consumer thread — the returned counts are a best-effort snapshot, fine for progress bars and post-cancel inspection but not for tight synchronization.

Example usage:

auto p = map->getProgress();
printf("%u/%u issued, %u done\n", p.issuedCount, p.targetCount, p.doneCount);

◆ getStats()

std::string pxl::Map::getStats ( ) const

Gets the execution statistics of the map operation.

Returns
A string containing the execution statistics.
Note
The Request phase spans from the first submit attempt to the last accepted submit. When the submit ring is full the Map yields to its Stream between attempts, so on a Stream shared by several Maps that span also covers work the Stream ran for the other Maps. A per-Map Total can then exceed the Map's own wall-clock time.

Example usage:

auto stats = map->getStats();
std::cout << "Execution statistics: " << stats << std::endl;

◆ getTaskCount()

uint32_t pxl::Map::getTaskCount ( ) const

Returns the task count this map was built with.

Returns
The taskCount passed to Job::buildMap().
Note
For a caller that also has to tell something else how many tasks there are — a resident kernel's control block, say — reading it here beats passing the same number twice. The two disagreeing is worse than a hang in one direction: told fewer tasks than the map dispatches, such a caller sees a round finish while tasks are still working and reads their output early.

◆ id()

uint64_t pxl::Map::id ( ) const

Gets ID of map object.

Returns
ID of the map object. Example usage:
auto mapId = map->getId();
std::cout << "Map ID: " << mapId << std::endl;

◆ setBatchSize()

void pxl::Map::setBatchSize ( const uint32_t &  batchSize)

Sets batchSize for the task.

Parameters
batchSizeNumber of tasks to be executed sequentially as a batch on a single MU Core.

◆ setClusterBitmap()

void pxl::Map::setClusterBitmap ( const uint32_t &  clusterBitmap)

Set the cluster bitmap for the map operation.

Parameters
clusterBitmapNumber of cluster bitmap to be used for the map operation. Set to 0 to use all clusters.

◆ setCompletionCallback()

void pxl::Map::setCompletionCallback ( const CompletionCallback &  callback,
void *  arg 
)

Set the success callback function and user data.

Parameters
callbackCompletion callback function to be called when the map operation is successful.
argUser data to be passed to the success callback function.

Example usage:

int uerData = 100;
auto callback = [](void* arg)
{
int* data = (int*)arg;
std::cout << "Map operation successful : " << *data << std::endl;
};
map->setCompletionCallback(callback, &userData);

◆ setErrorCallback()

void pxl::Map::setErrorCallback ( const ErrorCallback &  callback,
void *  arg 
)

Set the error callback function and user data.

Parameters
callbackError callback function to be called when the map operation encounters an error.
argUser data to be passed to the error callback function.

Example usage:

int userData = 200;
auto callback = [](void* arg)
{
int* data = (int*)arg;
std::cout << "Map operation failed : " << *data << std::endl;
};
map->setErrorCallback(callback, &errorUserData);

◆ setInput() [1/2]

template<typename... ARG>
Result pxl::Map::setInput ( ARG &&...  args)
inline

Set the input for the map operation. This method sets the input for the map operation.

Template Parameters
ARGType of the input argument.
Parameters
argInput argument.

Example usage:

int* input = reinterpret_cast<int*>(malloc(sizeof(int) * 100));
map->setInput(input);

Definition at line 345 of file map.hpp.

346  {
347  std::vector<ArgInfo_t> argInfos;
348  if (buildArgInfo(argInfos, std::forward<ARG>(args)...) == false)
349  {
351  }
352  return setInput(argInfos);
353  }
Result setInput(ARG &&... args)
Set the input for the map operation. This method sets the input for the map operation.
Definition: map.hpp:345

◆ setInput() [2/2]

Result pxl::Map::setInput ( std::vector< ArgInfo_t > &  args)

Set the input for the map operation. This method sets the input for the map operation.

Parameters
argsInput arguments.

Example usage:

std::vector<ArgInfo_t> args;
args.push_back(ArgInfo_t{ArgType::Constant, &input1, sizeof(int)});
args.push_back(ArgInfo_t{ArgType::DeviceMemory, input2, sizeof(float*)});
args.push_back(ArgInfo_t{ArgType::NDArray, &ndarrayArg, sizeof(NDArray<float>)});
map->setInput(args);

◆ setLocalityMode()

void pxl::Map::setLocalityMode ( const LocalityMode &  mode)

Set the locality mode for the map operation.

Parameters
modeLocalityMode to be used for the map operation.

◆ setMessageCallback()

void pxl::Map::setMessageCallback ( const MessageCallback &  callback,
void *  arg 
)

Set the message callback function and user data.

Parameters
callbackMessage callback function to be called when the map operation encounters an message event.
argUser data to be passed to the message callback function.

Example usage:

auto callback = [](void* message, void* arg)
{
printf("Message : %s\n", (char*)message);
};
map->setMessageCallback(callback, nullptr);

◆ setOutput() [1/2]

template<typename... ARG>
Result pxl::Map::setOutput ( ARG &&...  args)
inline

Set the output for the map operation. This method sets the output for the map operation.

Template Parameters
ARGType of the output argument.
Parameters
argOutput argument.

Example usage:

int* output = reinterpret_cast<int*>(malloc(sizeof(int) * 100));
map->setOutput(output);

Definition at line 369 of file map.hpp.

370  {
371  std::vector<ArgInfo_t> argInfos;
372  if (buildArgInfo(argInfos, std::forward<ARG>(args)...) == false)
373  {
375  }
376  return setOutput(argInfos);
377  }
Result setOutput(ARG &&... args)
Set the output for the map operation. This method sets the output for the map operation.
Definition: map.hpp:369

◆ setOutput() [2/2]

Result pxl::Map::setOutput ( std::vector< ArgInfo_t > &  args)

Set the output for the map operation. This method sets the output for the map operation.

Parameters
argsOutput arguments.

Example usage:

std::vector<ArgInfo_t> args;
args.push_back(ArgInfo_t{ArgType::Constant, &output1, sizeof(int)});
args.push_back(ArgInfo_t{ArgType::DeviceMemory, output2, sizeof(float*)});
args.push_back(ArgInfo_t{ArgType::NDArray, &ndarrayArg, sizeof(NDArray<float>)});
map->setOutput(args);

◆ setStream() [1/2]

void pxl::Map::setStream ( )

Set the default stream for the map operation.

This function sets the stream to the default stream. Use this when no specific stream is required.

Note
Call only while no execution is in flight. A call made while an execute is in flight is rejected, because a task completion may still need to wake the previously bound stream.

Example usage:

map->setStream();

◆ setStream() [2/2]

void pxl::Map::setStream ( Stream *  stream)

Set the stream for the map operation.

Parameters
streamPointer to the Stream object to be used for the map operation.
Note
Call only while no execution is in flight. A call made while an execute is in flight is rejected, because a task completion may still need to wake the previously bound stream.

Example usage:

auto stream = context->createStream();
map->setStream(stream);

◆ streamId()

uint32_t pxl::Map::streamId ( ) const

Returns the stream ID that the map operation is associated with.

Returns
The stream ID.

◆ synchronize()

Result pxl::Map::synchronize ( )

Synchronize the map operation. This method synchronizes the map operation, ensuring that all tasks are completed.

Returns
Result indicating the outcome:
Warning
Do not call this function from a Map message callback before the run it waits on has published its completion record. The same dispatch thread delivers that completion, so the wait never ends.

Example usage:

const uint32_t testCount = 100;
auto map = job->buildMap(testCount);
auto input1 = new int [testCount];
auto input2 = new float [testCount];
auto input3 = new double [testCount];
... //set input args
auto result = map->execute(input1, input2, input3);
if (result != pxl::Result::Success)
{
// Handle map operation failure
}
else
{
auto syncResult = map->synchronize();
if (syncResult != pxl::Result::Success)
{
// Handle synchronization failure
}
}

Friends And Related Function Documentation

◆ impl::MapFactory

friend class impl::MapFactory
friend

Definition at line 50 of file map.hpp.


The documentation for this class was generated from the following file: