# 定义 QLSTM 类，集成 QuantumEmbedding、QuantumAttention 和量子门控机制
class QLSTM(nn.Module):
    def __init__(self,
                 vocab_size,
                 embedding_dim,
                 hidden_size,
                 n_qubits=8,
                 n_qlayers=1,
                 backend='default.qubit',
                 dropout_rate=dropout_rate):
        super(QLSTM, self).__init__()
        self.vocab_size = vocab_size
        self.embedding_dim = embedding_dim
        self.hidden_size = hidden_size
        self.n_qubits = n_qubits
        self.n_qlayers = n_qlayers
        self.backend = backend

        # 经典嵌入层
        self.classical_embedding = nn.Embedding(vocab_size, embedding_dim)
        self.embedding_linear = nn.Linear(embedding_dim, 2 * n_qubits)  # 用于 QuantumEmbedding 和 QuantumAttention

        # 定义量子设备
        self.dev = qml.device(self.backend, wires=self.n_qubits)

        # 定义量子电路
        def circuit(inputs,
                    weights_embedding,
                    weights_attention,
                    weights_f_ry, weights_f_rz, weights_f_layers,
                    weights_i_ry, weights_i_rz, weights_i_layers,
                    weights_g_ry, weights_g_rz, weights_g_layers,
                    weights_o_ry, weights_o_rz, weights_o_layers):
            wires_type = list(range(self.n_qubits))

            # Quantum Embedding via AngleEmbedding
            qml.AngleEmbedding(inputs[:self.n_qubits], wires=wires_type, rotation='Y')

            # Quantum Attention via StronglyEntanglingLayers
            qml.StronglyEntanglingLayers(weights_attention, wires=wires_type)

            # ------------------ 遗忘门（Forget Gate） ------------------
            # 应用 Hadamard 门
            for i in range(self.n_qubits):
                qml.Hadamard(wires=wires_type[i])

            # 应用 RY 和 RZ 旋转
            for i in range(self.n_qubits):
                qml.RY(weights_f_ry[i], wires=wires_type[i])
                qml.RZ(weights_f_rz[i], wires=wires_type[i])

            # 创建纠缠（CNOT 门）
            for i in range(1, 3):
                for j in range(self.n_qubits):
                    target = j + i if j + i < self.n_qubits else j + i - self.n_qubits
                    qml.CNOT(wires=[wires_type[j], wires_type[target]])

            # 应用 RX、RY、RZ 旋转
            for layer in range(self.n_qlayers):
                for i in range(self.n_qubits):
                    qml.RX(weights_f_layers[layer][0][i], wires=wires_type[i])
                    qml.RY(weights_f_layers[layer][1][i], wires=wires_type[i])
                    qml.RZ(weights_f_layers[layer][2][i], wires=wires_type[i])

            # 测量 PauliZ 期望值作为遗忘门输出
            f_t = [qml.expval(qml.PauliZ(wires=i)) for i in range(self.n_qubits)]

            # ------------------ 输入门（Input Gate） ------------------
            # 应用 Hadamard 门
            for i in range(self.n_qubits):
                qml.Hadamard(wires=wires_type[i])

            # 应用 RY 和 RZ 旋转
            for i in range(self.n_qubits):
                qml.RY(weights_i_ry[i], wires=wires_type[i])
                qml.RZ(weights_i_rz[i], wires=wires_type[i])

            # 创建纠缠（CNOT 门）
            for i in range(1, 3):
                for j in range(self.n_qubits):
                    target = j + i if j + i < self.n_qubits else j + i - self.n_qubits
                    qml.CNOT(wires=[wires_type[j], wires_type[target]])

            # 应用 RX、RY、RZ 旋转
            for layer in range(self.n_qlayers):
                for i in range(self.n_qubits):
                    qml.RX(weights_i_layers[layer][0][i], wires=wires_type[i])
                    qml.RY(weights_i_layers[layer][1][i], wires=wires_type[i])
                    qml.RZ(weights_i_layers[layer][2][i], wires=wires_type[i])

            # 测量 PauliZ 期望值作为输入门输出
            i_t = [qml.expval(qml.PauliZ(wires=i)) for i in range(self.n_qubits)]

            # ------------------ 候选记忆细胞（Cell Gate） ------------------
            # 应用 Hadamard 门
            for i in range(self.n_qubits):
                qml.Hadamard(wires=wires_type[i])

            # 应用 RY 和 RZ 旋转
            for i in range(self.n_qubits):
                qml.RY(weights_g_ry[i], wires=wires_type[i])
                qml.RZ(weights_g_rz[i], wires=wires_type[i])

            # 创建纠缠（CNOT 门）
            for i in range(1, 3):
                for j in range(self.n_qubits):
                    target = j + i if j + i < self.n_qubits else j + i - self.n_qubits
                    qml.CNOT(wires=[wires_type[j], wires_type[target]])

            # 应用 RX、RY、RZ 旋转
            for layer in range(self.n_qlayers):
                for i in range(self.n_qubits):
                    qml.RX(weights_g_layers[layer][0][i], wires=wires_type[i])
                    qml.RY(weights_g_layers[layer][1][i], wires=wires_type[i])
                    qml.RZ(weights_g_layers[layer][2][i], wires=wires_type[i])

            # 测量 PauliZ 期望值作为候选记忆细胞输出
            g_t = [qml.expval(qml.PauliZ(wires=i)) for i in range(self.n_qubits)]

            # ------------------ 输出门（Output Gate） ------------------
            # 应用 Hadamard 门
            for i in range(self.n_qubits):
                qml.Hadamard(wires=wires_type[i])

            # 应用 RY 和 RZ 旋转
            for i in range(self.n_qubits):
                qml.RY(weights_o_ry[i], wires=wires_type[i])
                qml.RZ(weights_o_rz[i], wires=wires_type[i])

            # 创建纠缠（CNOT 门）
            for i in range(1, 3):
                for j in range(self.n_qubits):
                    target = j + i if j + i < self.n_qubits else j + i - self.n_qubits
                    qml.CNOT(wires=[wires_type[j], wires_type[target]])

            # 应用 RX、RY、RZ 旋转
            for layer in range(self.n_qlayers):
                for i in range(self.n_qubits):
                    qml.RX(weights_o_layers[layer][0][i], wires=wires_type[i])
                    qml.RY(weights_o_layers[layer][1][i], wires=wires_type[i])
                    qml.RZ(weights_o_layers[layer][2][i], wires=wires_type[i])

            # 测量 PauliZ 期望值作为输出门输出
            o_t = [qml.expval(qml.PauliZ(wires=i)) for i in range(self.n_qubits)]

            return f_t + i_t + g_t + o_t

        # 定义权重形状，所有参数扁平化
        weight_shapes = {
            "weights_embedding": (1, 2 * n_qubits, 3),  # 用于 QuantumEmbedding 和 QuantumAttention 的权重
            "weights_attention": (1, n_qubits, 3),  # QuantumAttention 的权重
            "weights_f_ry": (n_qubits,),
            "weights_f_rz": (n_qubits,),
            "weights_f_layers": (n_qlayers, 3, n_qubits),
            "weights_i_ry": (n_qubits,),
            "weights_i_rz": (n_qubits,),
            "weights_i_layers": (n_qlayers, 3, n_qubits),
            "weights_g_ry": (n_qubits,),
            "weights_g_rz": (n_qubits,),
            "weights_g_layers": (n_qlayers, 3, n_qubits),
            "weights_o_ry": (n_qubits,),
            "weights_o_rz": (n_qubits,),
            "weights_o_layers": (n_qlayers, 3, n_qubits)
        }

        # 创建 QNode
        self.qnode = qml.QNode(circuit, self.dev, interface='torch', diff_method='backprop')

        # 创建 TorchLayer
        self.qlayer = qml.qnn.TorchLayer(self.qnode, weight_shapes)

        # 定义线性层，将量子输出映射到隐藏状态维度
        self.fc_f = nn.Linear(n_qubits, hidden_size)
        self.fc_i = nn.Linear(n_qubits, hidden_size)
        self.fc_g = nn.Linear(n_qubits, hidden_size)
        self.fc_o = nn.Linear(n_qubits, hidden_size)

        # Dropout 层
        self.dropout = nn.Dropout(dropout_rate)

    def forward(self, x):
        # x: [batch_size, seq_length]
        batch_size, seq_length = x.size()

        # 经典嵌入
        embeddings = self.classical_embedding(x)  # [batch_size, seq_length, embedding_dim]
        embeddings = self.embedding_linear(embeddings)  # [batch_size, seq_length, 2 * n_qubits]
        embeddings = F.normalize(embeddings, p=2, dim=-1)

        # 初始化隐藏状态和记忆细胞
        h_t = torch.zeros(batch_size, self.hidden_size, dtype=torch.float32, device=x.device)
        c_t = torch.zeros(batch_size, self.hidden_size, dtype=torch.float32, device=x.device)

        outputs = []
        # 注意力权重在统一量子层中未单独提取

        for t in range(seq_length):
            # 获取当前时间步的嵌入
            x_t = embeddings[:, t, :]  # [batch_size, 2 * n_qubits]

            # 应用量子层
            # 由于 TorchLayer 只能处理单个样本，我们需要逐个处理批量中的样本
            q_outputs = []
            for b in range(batch_size):
                q_output = self.qlayer(x_t[b])  # [4 * n_qubits]
                q_outputs.append(q_output)
            q_outputs = torch.stack(q_outputs)  # [batch_size, 4 * n_qubits]

            # 分割量子输出为四个门
            f_t_q = q_outputs[:, 0:self.n_qubits]
            i_t_q = q_outputs[:, self.n_qubits:2 * self.n_qubits]
            g_t_q = q_outputs[:, 2 * self.n_qubits:3 * self.n_qubits]
            o_t_q = q_outputs[:, 3 * self.n_qubits:4 * self.n_qubits]

            # 映射到隐藏状态维度
            f_t = torch.sigmoid(self.fc_f(f_t_q))  # [batch_size, hidden_size]
            i_t = torch.sigmoid(self.fc_i(i_t_q))  # [batch_size, hidden_size]
            g_t = torch.tanh(self.fc_g(g_t_q))  # [batch_size, hidden_size]
            o_t = torch.sigmoid(self.fc_o(o_t_q))  # [batch_size, hidden_size]

            # 更新记忆细胞和隐藏状态
            c_t = f_t * c_t + i_t * g_t  # [batch_size, hidden_size]
            h_t = o_t * torch.tanh(c_t)  # [batch_size, hidden_size]

            # 应用 Dropout
            h_t = self.dropout(h_t)

            # 记录输出
            outputs.append(h_t.unsqueeze(1))  # [batch_size, 1, hidden_size]

        # 拼接所有时间步的输出
        outputs = torch.cat(outputs, dim=1)  # [batch_size, seq_length, hidden_size]

        # 根据需求返回序列或最后一个隐藏状态
        if self.training or self.return_sequences:
            return outputs, None  # 返回序列和注意力权重（注意力权重在统一层中未提取）
        else:
            return outputs[:, -1, :], None  # [batch_size, hidden_size], [None]


# 定义集成量子注意力的分类模型
class QShallowClassificationLSTMWithAttention(nn.Module):
    def __init__(self, vocab_size, embedding_dim, hidden_size, n_qubits=8, n_qlayers=1, num_classes=2,
                 dropout_rate=dropout_rate, backend='default.qubit'):
        super(QShallowClassificationLSTMWithAttention, self).__init__()
        self.vocab_size = vocab_size
        self.hidden_size = hidden_size
        self.num_layers = n_qlayers
        self.num_classes = num_classes

        # 使用集成的 QLSTM
        self.lstm = QLSTM(
            vocab_size=vocab_size,
            embedding_dim=embedding_dim,
            hidden_size=hidden_size,
            n_qubits=n_qubits,
            n_qlayers=n_qlayers,
            backend=backend,
            dropout_rate=dropout_rate
        )

        # 分类层
        self.linear = nn.Linear(hidden_size, num_classes)

    def forward(self, x):
        # QLSTM
        outputs, _ = self.lstm(x)  # [batch_size, seq_length, hidden_size]

        # 取最后一个时间步的隐藏状态
        last_hidden = outputs[:, -1, :]  # [batch_size, hidden_size]

        # 分类
        out = self.linear(last_hidden)  # [batch_size, num_classes]

        return out请你分析我的代码中，是否实现了在输入阶段将数据转换为量子态，模型内部均以量子态进行处理，在最终输出转换回经典态？