You've hit a classic performance bottleneck when dealing with matrix operations and memory layouts! Your understanding is spot on: performing a column-wise operation (like argmax with axis=0) on a row-major stored matrix (which is the default for NumPy, PyTorch CPU tensors, etc.) leads to scattered memory access and poor cache utilization.
ONNX Runtime, by design, executes the operations as defined in the ONNX graph. It operates on the logical tensor shape and axis definitions. It does not automatically re-layout data in memory or insert implicit Transpose operations just because it would be more performant for a specific operation on a specific CPU architecture with a specific input memory layout. That would be a semantic change to the graph.
Here are the common strategies to tackle this, from simplest to most advanced:
1. Pre-process the Data Before Feeding to ONNX Runtime (Most Common & Recommended)
This is often the most straightforward solution. You perform the transpose using your host language (e.g., Python with NumPy) before passing the data to InferenceSession.run().
How it works:
- You have a
(M, N) row-major matrix.
- You transpose it to
(N, M) in your host language. This creates a new contiguous block of memory that is now effectively "column-major" for the original data.
- You then run
ArgMax(axis=1) on this transposed matrix within ONNX Runtime.
Example:
import numpy as np
import onnxruntime as ort
import onnx
from onnx import helper, TensorProto
# 1. Define the input data (M rows, N columns, row-major)
M, N = 1000, 500
input_data_row_major = np.random.rand(M, N).astype(np.float32)
# 2. Create a simple ONNX graph for ArgMax
# We expect the input to be transposed, so ArgMax will be on axis=1
input_name = 'input_tensor'
output_name = 'output_argmax'
X = helper.make_tensor_value_info(input_name, TensorProto.FLOAT, [N, M]) # Note shape for transposed data
Y = helper.make_tensor_value_info(output_name, TensorProto.INT64, [N,]) # Output shape for argmax on axis 1
# ArgMax op: axis=1 means finding max along the columns of the *transposed* matrix
# which corresponds to finding max along rows of the *original* matrix.
# Wait, this is tricky. Let's clarify:
# Original: (M, N) matrix. Column-wise argmax means `axis=0` on original.
# Transposed: (N, M) matrix. Column-wise argmax on original is now ROW-WISE argmax on transposed.
# So, for the transposed (N,M) input, we need ArgMax(axis=1) to get the original column-wise result.
# Corrected logic:
# Original (M, N), column-wise argmax -> ArgMax(axis=0)
# If we transpose to (N, M), the elements of an original column are now the elements of a row in the transposed.
# So, to get original column-wise argmax, we need ArgMax(axis=1) on the (N, M) transposed matrix.
argmax_node = helper.make_node(
'ArgMax',
inputs=[input_name],
outputs=[output_name],
axis=1, # Operate along the new "columns" (which were original rows)
keepdims=0 # Remove the dimension
)
graph_def = helper.make_graph(
[argmax_node],
'argmax_graph',
[X],
[Y]
)
model_def = helper.make_model(graph_def, producer_name='argmax_test')
onnx.save(model_def, 'argmax_model.onnx')
# 3. Load the ONNX model
session_options = ort.SessionOptions()
session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
# You might want to increase OMP_NUM_THREADS if ArgMax is multi-threaded
# session_options.inter_op_num_threads = 4 # Example
session = ort.InferenceSession('argmax_model.onnx', session_options, providers=['CPUExecutionProvider'])
# 4. Perform transpose in NumPy
# This is the key step for performance
input_data_transposed = input_data_row_major.transpose() # From (M, N) to (N, M)
# 5. Run inference
ort_outputs = session.run(None, {input_name: input_data_transposed})
ort_argmax_result = ort_outputs[0]
# 6. Verify with NumPy's direct calculation
# The original problem was column-wise argmax on row-major data (axis=0)
np_argmax_result = np.argmax(input_data_row_major, axis=0)
print(f"ONNX Runtime ArgMax result shape: {ort_argmax_result.shape}")
print(f"NumPy ArgMax result shape: {np_argmax_result.shape}")
print(f"Results match: {np.array_equal(ort_argmax_result, np_argmax_result)}")
# Timing comparison (for larger matrices, this will be significant)
import time
# Warm-up
_ = session.run(None, {input_name: input_data_transposed})
# Test ONNX Runtime with pre-transposed data
start_time = time.time()
for _ in range(10): # Run multiple times for better average
_ = session.run(None, {input_name: input_data_transposed})
end_time = time.time()
print(f"ONNX Runtime (with pre-transpose) avg time: {(end_time - start_time) / 10:.4f}s")
# Test NumPy direct column-wise (which is slow for large data)
start_time = time.time()
for _ in range(10):
_ = np.argmax(input_data_row_major, axis=0)
end_time = time.time()
print(f"NumPy direct (column-wise) avg time: {(end_time - start_time) / 10:.4f}s")
# For fairness, also time the NumPy transpose itself
start_time = time.time()
for _ in range(10):
_ = input_data_row_major.transpose()
_ = np.argmax(_, axis=1) # The axis on the transposed data
end_time = time.time()
print(f"NumPy transpose + row-wise argmax avg time: {(end_time - start_time) / 10:.4f}s")
You will likely find that NumPy transpose + ONNX ArgMax is much faster than ONNX ArgMax on row-major data, and competitive with NumPy transpose + NumPy ArgMax. The total time will include the NumPy transpose, but it's an optimized C/Fortran operation, usually very fast.
2. Add a Transpose Operation to Your ONNX Graph
You can explicitly add a Transpose node to your ONNX graph before the ArgMax node. ONNX Runtime will then execute this Transpose operation. While it still involves data movement, it keeps the entire pipeline within ONNX Runtime.
How it works:
- Your input is
(M, N) row-major.
- You add a
Transpose node to make it (N, M).
- You then add an
ArgMax node operating on axis=1 (as described above for the transposed data).
Example:
import numpy as np
import onnxruntime as ort
import onnx
from onnx import helper, TensorProto
# 1. Define the input data (M rows, N columns, row-major)
M, N = 1000, 500
input_data_row_major = np.random.rand(M, N).astype(np.float32)
# 2. Create an ONNX graph with Transpose + ArgMax
input_name = 'input_tensor'
transposed_name = 'transposed_tensor'
output_name = 'output_argmax'
# Input to the graph: (M, N)
X = helper.make_tensor_value_info(input_name, TensorProto.FLOAT, [M, N])
# Transpose node: from (M, N) to (N, M)
transpose_node = helper.make_node(
'Transpose',
inputs=[input_name],
outputs=[transposed_name],
perm=[1, 0] # Swap dimensions
)
# ArgMax node: axis=1 for the (N, M) transposed data
Y = helper.make_tensor_value_info(output_name, TensorProto.INT64, [N,]) # Output is (N,)
argmax_node = helper.make_node(
'ArgMax',
inputs=[transposed_name],
outputs=[output_name],
axis=1,
keepdims=0
)
graph_def = helper.make_graph(
[transpose_node, argmax_node],
'transpose_argmax_graph',
[X],
[Y]
)
model_def = helper.make_model(graph_def, producer_name='transpose_argmax_test')
onnx.save(model_def, 'transpose_argmax_model.onnx')
# 3. Load the ONNX model
session_options = ort.SessionOptions()
session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL # Let ONNX Runtime optimize
session = ort.InferenceSession('transpose_argmax_model.onnx', session_options, providers=['CPUExecutionProvider'])
# 4. Run inference with the original row-major data
ort_outputs = session.run(None, {input_name: input_data_row_major})
ort_argmax_result = ort_outputs[0]
# 5. Verify with NumPy's direct calculation
np_argmax_result = np.argmax(input_data_row_major, axis=0)
print(f"ONNX Runtime ArgMax result shape: {ort_argmax_result.shape}")
print(f"NumPy ArgMax result shape: {np_argmax_result.shape}")
print(f"Results match: {np.array_equal(ort_argmax_result, np_argmax_result)}")
# Timing comparison
# Warm-up
_ = session.run(None, {input_name: input_data_row_major})
# Test ONNX Runtime with internal Transpose
start_time = time.time()
for _ in range(10):
_ = session.run(None, {input_name: input_data_row_major})
end_time = time.time()
print(f"ONNX Runtime (with internal transpose) avg time: {(end_time - start_time) / 10:.4f}s")
# Test NumPy direct column-wise
start_time = time.time()
for _ in range(10):
_ = np.argmax(input_data_row_major, axis=0)
end_time = time.time()
print(f"NumPy direct (column-wise) avg time: {(end_time - start_time) / 10:.4f}s")
This approach is cleaner from an ONNX graph perspective as it's self-contained. The performance will depend on ONNX Runtime's Transpose implementation. For large matrices, Transpose is generally memory-bandwidth bound, but it will still be better than cache-thrashing ArgMax.
3. Change How the Data is Stored/Generated Initially
If you have control over how the matrix is created or loaded, the absolute best solution is to store it in a way that is already conducive to column-wise operations. For example, store it in column-major order (like Fortran/MATLAB arrays).
If it's already a NumPy array, you can use np.array(data, order='F') to create a Fortran-order (column-major) array. Then, you'd feed this directly to ONNX Runtime and specify ArgMax(axis=0). The underlying data access for ArgMax(axis=0) would then be contiguous.
Example:
import numpy as np
import onnxruntime as ort
import onnx
from onnx import helper, TensorProto
# 1. Define input data (M rows, N columns, store as column-major/Fortran order)
M, N = 1000, 500
input_data_col_major = np.asfortranarray(np.random.rand(M, N)).astype(np.float32)
# 2. Create ONNX graph for ArgMax (axis=0 for column-wise on column-major data)
input_name = 'input_tensor'
output_name = 'output_argmax'
# Input to the graph: (M, N)
X = helper.make_tensor_value_info(input_name, TensorProto.FLOAT, [M, N])
Y = helper.make_tensor_value_info(output_name, TensorProto.INT64, [N,]) # Output shape
argmax_node = helper.make_node(
'ArgMax',
inputs=[input_name],
outputs=[output_name],
axis=0, # This now works efficiently because input is column-major
keepdims=0
)
graph_def = helper.make_graph(
[argmax_node],
'argmax_col_major_graph',
[X],
[Y]
)
model_def = helper.make_model(graph_def, producer_name='argmax_col_major_test')
onnx.save(model_def, 'argmax_col_major_model.onnx')
# 3. Load the ONNX model
session_options = ort.SessionOptions()
session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
session = ort.InferenceSession('argmax_col_major_model.onnx', session_options, providers=['CPUExecutionProvider'])
# 4. Run inference
ort_outputs = session.run(None, {input_name: input_data_col_major})
ort_argmax_result = ort_outputs[0]
# 5. Verify with NumPy (needs to be done on row-major for direct comparison or specify order)
np_argmax_result = np.argmax(input_data_col_major, axis=0) # This will be fast as input is col-major
print(f"ONNX Runtime ArgMax result shape: {ort_argmax_result.shape}")
print(f"NumPy ArgMax result shape: {np_argmax_result.shape}")
print(f"Results match: {np.array_equal(ort_argmax_result, np_argmax_result)}")
# Timing comparison
# Warm-up
_ = session.run(None, {input_name: input_data_col_major})
# Test ONNX Runtime with column-major input
start_time = time.time()
for _ in range(10):
_ = session.run(None, {input_name: input_data_col_major})
end_time = time.time()
print(f"ONNX Runtime (with column-major input) avg time: {(end_time - start_time) / 10:.4f}s")
# Test NumPy direct column-wise on Fortran-order array
start_time = time.time()
for _ in range(10):
_ = np.argmax(input_data_col_major, axis=0)
end_time = time.time()
print(f"NumPy direct (column-wise on F-order) avg time: {(end_time - start_time) / 10:.4f}s")
This is the most performant scenario as it avoids any explicit or implicit data re-layout at inference time.
4. Custom ONNX Runtime Operator (Advanced)
For extreme performance needs and very specific operations, you could implement a custom ONNX Runtime operator in C++. This operator would take the row-major matrix as input and directly implement the column-wise argmax using optimized memory access patterns (e.g., highly optimized loops, possibly SIMD instructions), avoiding any explicit Transpose or intermediate memory copies.
Pros: Maximum performance, highly specialized.
Cons: Significant development effort, requires C++ knowledge, compilation, and maintaining a custom ONNX Runtime build or extension. Not portable out-of-the-box.
Conclusion and Recommendation:
- For most cases, Option 1 (Pre-process outside ONNX Runtime with NumPy/PyTorch transpose) or Option 2 (Add Transpose inside the ONNX graph) are your best bets. Option 1 keeps your ONNX graph simpler and leverages highly optimized host-language array operations. Option 2 keeps the entire pipeline within ONNX Runtime. The performance difference between them often comes down to the efficiency of NumPy's
transpose vs. ONNX Runtime's Transpose implementation for your specific data sizes and hardware.
- If you have control over the data source, Option 3 (Store/Generate data in column-major format) is ideal. It avoids any data rearrangement overhead at inference time.
- Option 4 is for very specialized scenarios where the above options are insufficient.
Always profile your chosen solution with your actual data and hardware to determine the true performance impact.