# 运行时错误：调用 cudnnSetRNNDescriptor_v8 时出现 CUDNN_STATUS_BAD_PARAM

- **ID:** `cuda/cudnn-rnn-hidden-size-mismatch`
- **领域:** cuda
- **类别:** runtime_error
- **错误码:** `CUDNN_STATUS_BAD_PARAM`
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

提供给 RNN/LSTM/GRU 层的隐藏层大小不是 32 或 64 的倍数（取决于 cuDNN 版本和 RNN 模式），违反了 cuDNN 性能内核的对齐要求，或层数为零。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| cuDNN 8.9.0 | active | — | — |
| cuDNN 8.9.5 | active | — | — |
| PyTorch 2.1.0 | active | — | — |
| TensorFlow 2.14 | active | — | — |

## 解决方案

1. ```
   将隐藏层大小设置为 64 的倍数（某些 cuDNN 版本为 32）。例如，如果 hidden_size=100，改为 128。在 PyTorch 中：`nn.LSTM(input_size, hidden_size=128, num_layers=2)`。通过检查 `hidden_size % 64 == 0` 验证。
   ```
2. ```
   如果必须保留任意隐藏层大小，设置 `torch.backends.cudnn.rnn.allow_tf32 = False` 和 `torch.backends.cudnn.deterministic = True` 强制回退到可能不强制对齐的实现（性能损失）。
   ```
3. ```
   在传递给 RNN 之前，使用 `torch.nn.functional.pad` 将隐藏状态张量显式填充到下一个 64 的倍数，然后将输出切片回原始大小。
   ```

## 无效尝试

- **Setting `torch.backends.cudnn.enabled = False` to disable cuDNN** — Disabling cuDNN may fall back to a non-cuDNN RNN implementation that still validates hidden size; also significantly degrades performance. (70% 失败率)
- **Reducing the number of RNN layers arbitrarily** — The error is about hidden size alignment, not layer count; reducing layers only helps if num_layers was zero, which is rare. (90% 失败率)
- **Switching to a different RNN cell type (e.g., LSTM to GRU) without changing hidden size** — The alignment requirement applies to all cuDNN RNN cells; the error persists if hidden size is not a multiple of the alignment. (85% 失败率)
