MultiheadAttention nok after 4D -> 3D conversion

HI,

PyTorch MHA works fine with 3D tensor in HAR parsing with DFC compiler version 3.34

*class Direct3DMHA(nn.Module):
def init(self):
super().init()
self.mha = nn.MultiheadAttention(
embed_dim=128,
num_heads=4,
batch_first=True,
dropout=0.0,
)

def forward(self, x):
output, _ = self.mha(x, x, x, need_weights=False)
return output

def main():
os.makedirs(OUTPUT_DIR, exist_ok=True)
torch.manual_seed(0)
model = Direct3DMHA().eval()
x = torch.randn(1, 25, 128)
with torch.no_grad():
pt = model(x)*

But I need to perform it on a 4D tensor [1, 4,25, 128]. Here I am converting it to a 3D tensor with PyTorch unbind

*q_windows = torch.unbind(Q, dim=1)
k_windows = torch.unbind(K, dim=1)
v_windows = torch.unbind(V, dim=1)
q = q_windows[i]
k = k_windows[i]
v = v_windows[i]

print(f"\n========== Window {i} ==========")

print("MHA input:")
print(" Q:", tuple(q.shape))
print(" K:", tuple(k.shape))
print(" V:", tuple(v.shape))

# Feed the selected 3D tensors directly to nn.MultiheadAttention.
# nn.MultiheadAttention performs its own learned Q/K/V projections.
output, _ = self.mha(
q,
k,
v,
need_weights=False
)
*
HAR parsing fails with the error message -*

[info] Memory: Total: 53GB, Available: 51GB
[info] System info: OS: Linux, Kernel: 6.8.0-1015-azure
[info] Hailo DFC Version: 3.34.0
[info] HailoRT Version: Not Installed
[info] PCIe: No Hailo PCIe device was found
[info] Running hailo parser onnx dustnet_attention_direct_mha.onnx --net-name dustnet_attention_direct_mha_unbind --har-path dustnet_attention_direct_mha_unbind.har --hw-arch hailo8 --input-format NCHW --tensor-shapes [1,128,20,20] --parsing-report-path parsing_report_unbind_rerun.html
[info] Translation started on ONNX model dustnet_attention_direct_mha_unbind
[info] Restored ONNX model dustnet_attention_direct_mha_unbind (completion time: 00:00:00.01)
[info] Extracted ONNXRuntime meta-data for Hailo model (completion time: 00:00:00.64)
[info] Simplified ONNX model for a parsing retry attempt (completion time: 00:00:01.22)
Parsing failed with recommendations for end node names: [‘/mha_1/Transpose_2’, ‘/mha_3/Transpose_3’, ‘/mha_2/Transpose_2’, ‘/mha/Transpose_3’, ‘/mha_1/Transpose_3’, ‘/mha_2/Transpose_3’, ‘/mha_1/Transpose_1’, ‘/mha/Transpose_1’, ‘/mha_3/Transpose_2’, ‘/mha_2/Transpose_1’, ‘/mha_3/Transpose_1’, ‘/mha/Transpose_2’].
Would you like to parse again with the recommendation? (y/n)
Traceback (most recent call last):
File “/home/subnath/hailo_venv/bin/hailo”, line 6, in
sys.exit(main())
^^^^^^
File “/home/subnath/hailo_venv/lib/python3.12/site-packages/hailo_sdk_client/tools/cmd_utils/main.py”, line 111, in main
ret_val = client_command_runner.run()
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “/home/subnath/hailo_venv/lib/python3.12/site-packages/hailo_sdk_client/tools/cmd_utils/base_utils.py”, line 68, in run
return self._run(argv)
^^^^^^^^^^^^^^^
File “/home/subnath/hailo_venv/lib/python3.12/site-packages/hailo_sdk_client/tools/cmd_utils/base_utils.py”, line 89, in _run
return args.func(args)
^^^^^^^^^^^^^^^
File “/home/subnath/hailo_venv/lib/python3.12/site-packages/hailo_sdk_client/tools/parser_cli.py”, line 236, in run
self._handle_recommendation_exception(err, args, net_name, tensor_shapes, command, save_model)
File “/home/subnath/hailo_venv/lib/python3.12/site-packages/hailo_sdk_client/tools/parser_cli.py”, line 263, in _handle_recommendation_exception
raise ParsingWithRecommendationCLIException(
hailo_sdk_client.tools.parser_cli.ParsingWithRecommendationCLIException: Parsing failed. The errors found in the graph are:
UnsupportedShuffleLayerError in op /mha/Reshape_3: Failed to determine type of layer to create in node /mha/Reshape_3
UnsupportedShuffleLayerError in op /mha/Reshape_4: Failed to determine type of layer to create in node /mha/Reshape_4
UnsupportedShuffleLayerError in op /mha/Reshape_5: Failed to determine type of layer to create in node /mha/Reshape_5
UnsupportedShuffleLayerError in op /mha_1/Reshape_3: Failed to determine type of layer to create in node /mha_1/Reshape_3
UnsupportedShuffleLayerError in op /mha_1/Reshape_4: Failed to determine type of layer to create in node /mha_1/Reshape_4
UnsupportedShuffleLayerError in op /mha_1/Reshape_5: Failed to determine type of layer to create in node /mha_1/Reshape_5
UnsupportedShuffleLayerError in op /mha_2/Reshape_3: Failed to determine type of layer to create in node /mha_2/Reshape_3
UnsupportedShuffleLayerError in op /mha_2/Reshape_4: Failed to determine type of layer to create in node /mha_2/Reshape_4
UnsupportedShuffleLayerError in op /mha_2/Reshape_5: Failed to determine type of layer to create in node /mha_2/Reshape_5
UnsupportedShuffleLayerError in op /mha_3/Reshape_3: Failed to determine type of layer to create in node /mha_3/Reshape_3
UnsupportedShuffleLayerError in op /mha_3/Reshape_4: Failed to determine type of layer to create in node /mha_3/Reshape_4
UnsupportedShuffleLayerError in op /mha_3/Reshape_5: Failed to determine type of layer to create in node /mha_3/Reshape_5
UnsupportedShuffleLayerError in op /mha/Transpose_5: Failed to determine type of layer to create in node /mha/Transpose_5
UnsupportedShuffleLayerError in op /mha_1/Transpose_5: Failed to determine type of layer to create in node /mha_1/Transpose_5
UnsupportedShuffleLayerError in op /mha_2/Transpose_5: Failed to determine type of layer to create in node /mha_2/Transpose_5
UnsupportedShuffleLayerError in op /mha_3/Transpose_5: Failed to determine type of layer to create in node /mha_3/Transpose_5
UnsupportedSoftmaxLayerError in op /mha/Softmax: Unsupported softmax
UnsupportedSoftmaxLayerError in op /mha_1/Softmax: Unsupported softmax
UnsupportedSoftmaxLayerError in op /mha_2/Softmax: Unsupported softmax
UnsupportedSoftmaxLayerError in op /mha_3/Softmax: Unsupported softmax
*
Does it anything to do with the reshape support as documented in chapter 5.5.29. Reshape Reshape is supported in the following cases:

Any update on this?

Due to this issue, we are unable to perform Multi Head Attention (MHA) on window-based partitions 5x5 from frame. We have to perform on entire frame 640 x 640.

There are couple of issues if MHA is performed on entire frame-

1)Exponentially increasing number of operations required. Lets assume Frame is 80 x 80. Window size 5 x 5. Hence tokens = 25. With this, number of calculations required for the Attention Matrix is 25 x 25 = 625. Number of batches or windows = 80 x 80 / 25 = 256.
Total number of calculations for the whole frame is 256 x 625 = 160,000.
If we perform MHA on the full frame wise, the number of calculations required 6400 x 6400 = 40960000 which is much higher.

2)Quantization with optimization_level=2 requires more GPU memory and fails with OOM. To address this, fallback to CPU is required which goes for longer time.

3)Calibration fails with error message - *"hailo_model_optimization.acceleras.utils.acceleras_exceptions.AccelerasUnsupportedError: layer cdm_dust_density_global_attention_2ep/matmul7 does not support shift delta. To overcome this issue you should force larger range at the inputs of the layer using
command quantization_param([layer_name], force_range_in=[range_min0, range_max0, range_min1, range_max1], force_range_index=[0, 1]) current range of input 0 is
[0.001, 0.006] and input 1 is [-12.285, 17.021].You should increase the multiplication of these ranges by a factor of 4.391, e.g. you can apply factor of sqrt(4.391) to both inputs:
quantization_param([cdm_dust_density_global_attention_2ep/matmul7], force_range_in=[0.002, 0.013, -25.743, 35.667], force_range_index=[0,1])"
*
This is already discussed in the other community tickets
Optimization error: layer does not support shift delta - General Discussion - Hailo Community

Help with Custom ONNX Model Optimization – matmul2 Layer Error - General Discussion - Hailo Community

Can’t compile onnx to hef - General Discussion - Hailo Community

problem with optimize model AccelerasUnsupportedError - General Discussion - Hailo Community

Although this can be fixed with the workaround done in model script file, but as the ONNX graph matmul layer grows with the token size, this error gets reported for a greater number of matmul layers. Fixing those one at a time and get a successful calibration is quite time consuming