コード例 #1
0
ファイル: locc.py プロジェクト: Shahip2016/Quantum
    def __measure_parameterized(self, state, which_qubits, result_desired,
                                theta):
        r"""进行参数化的测量。

        Args:
            state (ComplexVariable): 输入的量子态
            which_qubits (list): 测量作用的量子比特编号
            result_desired (list): 期望得到的测量结果,如 ``"0"``、``"1"`` 或者 ``["0", "1"]``
            theta (Variable): 测量运算的参数

        Returns:
            ComplexVariable: 测量坍塌后的量子态
            Variable:测量坍塌得到的概率
            list: 测量得到的结果(0 或 1)
        """
        n = self.get_qubit_number()
        assert len(which_qubits) == len(result_desired), \
            "the length of qubits wanted to be measured and the result desired should be same"
        op_list = [fluid.dygraph.to_variable(np.eye(2, dtype=np.complex128))
                   ] * n
        for idx in range(0, len(which_qubits)):
            i = which_qubits[idx]
            ele = result_desired[idx]
            if int(ele) == 0:
                basis0 = fluid.dygraph.to_variable(
                    np.array([[1, 0], [0, 0]], dtype=np.complex128))
                basis1 = fluid.dygraph.to_variable(
                    np.array([[0, 0], [0, 1]], dtype=np.complex128))
                rho0 = elementwise_mul(basis0, cos(theta[idx]))
                rho1 = elementwise_mul(basis1, sin(theta[idx]))
                rho = elementwise_add(rho0, rho1)
                op_list[i] = rho
            elif int(ele) == 1:
                # rho = diag(concat([cos(theta[idx]), sin(theta[idx])]))
                # rho = ComplexVariable(rho, zeros((2, 2), dtype="float64"))
                basis0 = fluid.dygraph.to_variable(
                    np.array([[1, 0], [0, 0]], dtype=np.complex128))
                basis1 = fluid.dygraph.to_variable(
                    np.array([[0, 0], [0, 1]], dtype=np.complex128))
                rho0 = elementwise_mul(basis0, sin(theta[idx]))
                rho1 = elementwise_mul(basis1, cos(theta[idx]))
                rho = elementwise_add(rho0, rho1)
                op_list[i] = rho
            else:
                print("cannot recognize the results_desired.")
            # rho = ComplexVariable(ones((2, 2), dtype="float64"), zeros((2, 2), dtype="float64"))
        measure_operator = fluid.dygraph.to_variable(op_list[0])
        if n > 1:
            for idx in range(1, len(op_list)):
                measure_operator = kron(measure_operator, op_list[idx])
        state_measured = matmul(matmul(measure_operator, state),
                                dagger(measure_operator))
        prob = trace(
            matmul(matmul(dagger(measure_operator), measure_operator),
                   state)).real
        state_measured = elementwise_div(state_measured, prob)
        return state_measured, prob, result_desired
コード例 #2
0
 def test_sin(self):
     program = Program()
     with program_guard(program):
         input = layers.data(name="input", shape=[16], dtype="float32")
         out = layers.sin(input, name='sin')
         self.assertIsNotNone(out)
     print(str(program))
コード例 #3
0
def compute_position_embedding(radians, speaker_position_rate):
    """Compute sin/cos interleaved matrix from the radians.
    
    Arg:
        radians (Variable): shape(n_vocab, embed_dim), dtype float32, the radians matrix.
        speaker_position_rate (Variable): shape(B, ), speaker positioning rate.
    
    Returns:
        Variable: shape(B, n_vocab, embed_dim), the sin, cos interleaved matrix.
    """
    _, embed_dim = radians.shape
    batch_size = speaker_position_rate.shape[0]
    scaled_radians = F.elementwise_mul(F.expand(F.unsqueeze(radians, [0]),
                                                [batch_size, 1, 1]),
                                       speaker_position_rate,
                                       axis=0)

    odd_mask = (np.arange(embed_dim) % 2).astype(np.float32)
    odd_mask = dg.to_variable(odd_mask)

    out = odd_mask * F.cos(scaled_radians) \
        + (1 - odd_mask) * F.sin(scaled_radians)
    out = F.concat(
        [F.zeros((batch_size, 1, embed_dim), radians.dtype), out[:, 1:, :]],
        axis=1)
    return out
コード例 #4
0
    def get_embedding(self, num_embeddings,
                      embedding_dim, padding_idx=None):
        """
        Build sinusoidal embeddings.
        This matches the implementation in tensor2tensor,
        but differs slightly from the description
        in Section 3.5 of "Attention Is All You Need".
        """
        half_dim = embedding_dim // 2
        emb = layers.log(float(10000)) / (half_dim - -1)
        emb = layers.exp(layers.arange(
            start=0, end=half_dim, dtype='float32') * -emb)

        # [num_embeddings, embedding_dim // 2]
        emb = layers.unsqueeze(layers.arange(-num_embeddings // 2,
                                             num_embeddings // 2, dtype='float32'), axis=1) *\
            layers.unsqueeze(emb, axis=0)

        emb = layers.concat([layers.sin(emb), layers.cos(emb)], dim=1)
        # [num_embeddings, embedding_dim]
        if embedding_dim % 2 == 1:
            emb = layers.concat(
                [emb, layers.zeros(shape=(num_embeddings, 1))], dim=1)
        if padding_idx is not None:
            emb[paddings_idx, :] = 0
        self.origin_shift = num_embeddings // 2
        return emb
コード例 #5
0
    def forward(self, tensor_list: NestedTensor):
        x = tensor_list.tensors
        mask = tensor_list.mask
        assert mask is not None
        bs, h, w = mask.shape

        mask = mask.numpy()
        not_mask = ~mask
        not_mask = dg.to_variable(not_mask).astype('float32')
        y_embed = L.cumsum(not_mask, axis=1)  # [batch_size, h, w]
        x_embed = L.cumsum(not_mask, axis=2)  # [batch_size, h, w]
        if self.normalize:
            eps = 1e-6
            y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
            x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale

        dim_t = (np.arange(0, self.num_pos_feats, 1,
                           dtype="float32"))  # [num_pos_feats]
        dim_t = self.temperature**(2 * (dim_t // 2) / self.num_pos_feats
                                   )  # [num_pos_feats]
        dim_t = dg.to_variable(dim_t)

        x_embed = L.unsqueeze(x_embed, 3)  # [batch_size, h, w, 1]
        y_embed = L.unsqueeze(y_embed, 3)  # [batch_size, h, w, 1]
        pos_x = x_embed / dim_t  # [batch_size, h, w, num_pos_feats]
        pos_y = y_embed / dim_t  # [batch_size, h, w, num_pos_feats]
        pos_x_1 = L.sin(pos_x[:, :, :,
                              0::2])  # [batch_size, h, w, num_pos_feats / 2]
        pos_x_2 = L.cos(pos_x[:, :, :,
                              1::2])  # [batch_size, h, w, num_pos_feats / 2]
        pos_y_1 = L.sin(pos_y[:, :, :,
                              0::2])  # [batch_size, h, w, num_pos_feats / 2]
        pos_y_2 = L.cos(pos_y[:, :, :,
                              1::2])  # [batch_size, h, w, num_pos_feats / 2]
        pos_x = L.reshape(L.stack([pos_x_1, pos_x_2], axis=4),
                          (bs, h, w, -1))  # [batch_size, h, w, num_pos_feats]
        pos_y = L.reshape(L.stack([pos_y_1, pos_y_2], axis=4),
                          (bs, h, w, -1))  # [batch_size, h, w, num_pos_feats]

        pos = L.concat((pos_y, pos_x),
                       axis=3)  # [batch_size, h, w, num_pos_feats * 2]
        pos = L.transpose(pos,
                          perm=(0, 3, 1,
                                2))  # [batch_size, num_pos_feats * 2, h, w]
        return pos
コード例 #6
0
ファイル: utils.py プロジェクト: shyamalschandra/Quantum-2
def rotation_y(theta):
    """
    :param theta: must be a scale, shape [1], 'float32'
    :return:
    """

    cos_value = cos(theta/2)
    sin_value = sin(theta/2)
    ry_re = concat([cos_value, -sin_value, sin_value, cos_value], axis=0)
    ry_im = pp_zeros([2, 2], "float32")
    return ComplexVariable(reshape(ry_re, [2, 2]), ry_im)
コード例 #7
0
ファイル: utils.py プロジェクト: shyamalschandra/Quantum-2
def rotation_z(theta):
    """
    :param theta: must be a scale, shape [1], 'float32'
    :return:
    """

    cos_value = cos(theta/2)
    sin_value = sin(theta/2)
    zero_pd = pp_zeros([1], "float32")
    rz_re = concat([cos_value, zero_pd, zero_pd, cos_value], axis=0)
    rz_im = concat([-sin_value, zero_pd, zero_pd, sin_value], axis=0)

    return ComplexVariable(reshape(rz_re, [2, 2]), reshape(rz_im, [2, 2]))
コード例 #8
0
ファイル: utils.py プロジェクト: test-tttt/test-rtd
def rotation_y(theta):
    r"""生成单量子比特Y门

    Args:
        theta (Variable): Y门的旋转角度

    Returns:
        ComplexVariable: 单量子比特Y门的矩阵形式
    """

    cos_value = cos(theta / 2)
    sin_value = sin(theta / 2)
    ry_re = concat([cos_value, -sin_value, sin_value, cos_value], axis=0)
    ry_im = pp_zeros([2, 2], "float32")
    return ComplexVariable(reshape(ry_re, [2, 2]), ry_im)
コード例 #9
0
ファイル: utils.py プロジェクト: test-tttt/test-rtd
def rotation_z(theta):
    r"""生成单量子比特Z门

    Args:
        theta (Variable): Z门的旋转角度

    Returns:
        ComplexVariable: 单量子比特Z门的矩阵形式
    """

    cos_value = cos(theta / 2)
    sin_value = sin(theta / 2)
    zero_pd = pp_zeros([1], "float32")
    rz_re = concat([cos_value, zero_pd, zero_pd, cos_value], axis=0)
    rz_im = concat([-sin_value, zero_pd, zero_pd, sin_value], axis=0)

    return ComplexVariable(reshape(rz_re, [2, 2]), reshape(rz_im, [2, 2]))
コード例 #10
0
def compute_position_embedding_single_speaker(radians, speaker_position_rate):
    """Compute sin/cos interleaved matrix from the radians.
    
    Arg:
        radians (Variable): shape(n_vocab, embed_dim), dtype float32, the radians matrix.
        speaker_position_rate (float or Variable): float or Variable of shape(1, ), speaker positioning rate.
    
    Returns:
        Variable: shape(n_vocab, embed_dim), the sin, cos interleaved matrix.
    """
    _, embed_dim = radians.shape
    scaled_radians = radians * speaker_position_rate

    odd_mask = (np.arange(embed_dim) % 2).astype(np.float32)
    odd_mask = dg.to_variable(odd_mask)

    out = odd_mask * F.cos(scaled_radians) \
        + (1 - odd_mask) * F.sin(scaled_radians)
    return out
コード例 #11
0
def positional_encoding(tensor, start_index, omega):
    """
    tensor: a reference tensor we use to get shape. actually only T and C are needed. Shape(B, T, C)
    start_index: int, we can actually use start and length to specify them.
    omega (B,): speaker position rates

    return (B, T, C), position embedding
    """
    dtype = omega.dtype
    _, length, dimension = tensor.shape
    index = F.range(start_index, start_index + length, 1, dtype=dtype)
    channel = F.range(0, dimension, 2, dtype=dtype)

    p = F.unsqueeze(omega, [1, 2]) \
      * F.unsqueeze(index, [1]) \
      / (10000 ** (channel / float(dimension)))

    encodings = F.concat([F.sin(p), F.cos(p)], axis=2)
    return encodings