You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

强化学习复数状态Actor网络dtype不匹配错误解决方案咨询

问题解决:复数状态输入Actor网络的 dtype 不匹配错误

错误原因

报错核心是输入状态张量的 dtype(ComplexDouble)与网络层参数的 dtype(ComplexFloat)不一致,矩阵乘法要求参与运算的张量必须同类型,因此触发类型不匹配的运行时错误。

修复方案

1. 统一输入与网络的 dtype

在将numpy状态转为torch张量时,显式指定与网络一致的torch.complex64类型,避免默认转为ComplexDouble。

2. 修正动作选择方法的调用错误

select_action方法中错误调用了self.actor(state),应该直接调用self(state)(Actor类继承自nn.Module,实例本身即可触发forward方法)。

3. 移除冗余的参数类型转换代码

创建nn.Linear时已通过dtype=torch.complex64指定了参数类型,无需再手动执行self.l1.weight.to(torch.complex64)这类重复操作。

修改后的完整代码

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np

class Actor(nn.Module):
    def __init__(self, state_dim, action_dim, max_action):
        super(Actor, self).__init__()

        hidden_dim = 1 if state_dim == 0 else 2 ** (state_dim - 1).bit_length()
        print("hidden_dim", hidden_dim)

        # 创建Linear层时直接指定dtype,无需后续手动转换
        self.l1 = nn.Linear(state_dim, hidden_dim, dtype=torch.complex64)
        self.l2 = nn.Linear(hidden_dim, hidden_dim, dtype=torch.complex64)
        self.l3 = nn.Linear(hidden_dim, action_dim, dtype=torch.complex64)

        self.max_action = max_action
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.to(self.device)  # 将模型移动到指定设备

    def forward(self, state):
        a = F.relu(self.l1(state))
        a = F.relu(self.l2(a))
        return self.max_action * torch.tanh(self.l3(a))

    def select_action(self, state):
        # 显式指定dtype为torch.complex64,与网络参数保持一致
        state_tensor = torch.tensor(state.reshape(1, -1), dtype=torch.complex64)
        state = state_tensor.to(self.device)
        # 修正调用方式,直接用self(state)触发forward
        return self(state).cpu().data.numpy().flatten()

额外说明

如果你的状态数据本身是高精度的complex128(numpy),也可以选择将网络层的dtype改为torch.complex128,同时在创建张量时指定对应类型,核心是保证输入张量与网络参数的dtype完全一致。

内容的提问来源于stack exchange,提问作者user23366824

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 04:26:01