code: # Copyright 2020-2022 Huawei Technologies Co., Ltd
  #
  # Licensed under the Apache License, Version 2.0 (the "License");
  # you may not use this file except in compliance with the License.
  # You may obtain a copy of the License at
  #
  # http://www.apache.org/licenses/LICENSE-2.0
  #
  # Unless required by applicable law or agreed to in writing, software
  # distributed under the License is distributed on an "AS IS" BASIS,
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  # See the License for the specific language governing permissions and
  # limitations under the License.
  # ============================================================================
  """ export checkpoint file into models"""
  
  import numpy as np
  
  import mindspore as ms
  from mindspore import Tensor
  
  from src.transformer_model import TransformerModel
  from src.model_utils.config import config
  from src.model_utils.moxing_adapter import moxing_wrapper
  from src.model_utils.device_adapter import get_device_id
  from eval import load_weights
  
  
  config.batch_size = config.batch_size_ev
  config.hidden_dropout_prob = config.hidden_dropout_prob_ev
  config.attention_probs_dropout_prob = config.attention_probs_dropout_prob_ev
  
  ms.set_context(mode=ms.GRAPH_MODE, device_target=config.device_target)
  if config.device_target == "Ascend":
      ms.set_context(device_id=get_device_id())
  
  def modelarts_pre_process():
      pass
  
  @moxing_wrapper(pre_process=modelarts_pre_process)
  def export_transformer():
      """ export_transformer """
      tfm_model = TransformerModel(config=config, is_training=False, use_one_hot_embeddings=False)
  
      parameter_dict = load_weights(config.model_file)
      ms.load_param_into_net(tfm_model, parameter_dict)
  
      source_ids = Tensor(np.ones((config.batch_size, config.seq_length)).astype(np.int32))
      source_mask = Tensor(np.ones((config.batch_size, config.seq_length)).astype(np.int32))
  
      ms.export(tfm_model, source_ids, source_mask, file_name=config.file_name, file_format=config.file_format)
  
  if __name__ == '__main__':
      export_transformer()
   # Copyright 2021 Huawei Technologies Co., Ltd
  #
  # Licensed under the Apache License, Version 2.0 (the "License");
  # you may not use this file except in compliance with the License.
  # You may obtain a copy of the License at
  #
  # http://www.apache.org/licenses/LICENSE-2.0
  #
  # Unless required by applicable law or agreed to in writing, software
  # distributed under the License is distributed on an "AS IS" BASIS,
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  # See the License for the specific language governing permissions and
  # limitations under the License.
  # ============================================================================
  """
  preprocess
  """
  import os
  import argparse
  import numpy as np
  from mindspore import ops, context
  import mindspore.dataset as ds
  import src.util as util
  from src.data.IterSamplers import CategoriesSampler
  from src.data.mini_Imagenet import MiniImageNet
  
  
  def gen_bin(args):
      """
      generate binary files
      """
      n_way = 5
      n_query = 15
      n_shots = [args.num_shots]
      root_path = os.path.join(args.root_path, args.dataset)
      testset = MiniImageNet(root_path, 'test')
  
      fs_loaders = []
      for n_shot in n_shots:
          test_sampler = CategoriesSampler(testset.data, testset.label, n_way, n_shot + n_query,
                                           200,
                                           args.ep_per_batch)
          test_loader = ds.GeneratorDataset(test_sampler, ['data'], shuffle=True)
          fs_loaders.append(test_loader)
  
      input_path = os.path.join(args.pre_result_path, "00_data")
      label_path = os.path.join(args.pre_result_path, "label.npy")
      shape_path = os.path.join(args.pre_result_path, "shape.npy")
      if not os.path.exists(input_path):
          os.makedirs(input_path)
  
      label_list = []
      shape_list = []
      for i, n_shot in enumerate(n_shots):
          np.random.seed(0)
          label_shot = []
          for j, data in enumerate(fs_loaders[i].create_dict_iterator()):
              x_shot, x_query = data['data'][:, :, :n_shot], data['data'][:, :, n_shot:]
              img_shape = x_query.shape[-3:]
              x_query = x_query.view(args.ep_per_batch, -1,
                                     *img_shape)  # bs*(way*n_query)*3*84*84
              label = util.make_nk_label(n_way, n_query, args.ep_per_batch)  # bs*(way*n_query)
              if j == 0:
                  shape_list.append(x_shot.shape)
                  shape_list.append(x_query.shape)
  
              img_shape = x_shot.shape[-3:]
  
              x_shot = x_shot.view(-1, *img_shape)
              x_query = x_query.view(-1, *img_shape)
              input0 = ops.Concat(0)([x_shot, x_query])
              file_name = "nshot_" + str(i) + "_" + str(j) + ".bin"
              input0.asnumpy().tofile(os.path.join(input_path, file_name))
              label_shot.append(label.asnumpy())
          label_list.append(label_shot)
  
      np.save(label_path, label_list)
      np.save(shape_path, shape_list)
  
  
  if __name__ == '__main__':
      parser = argparse.ArgumentParser()
      parser.add_argument('--root_path', default='./dataset/')
      parser.add_argument('--device_target', type=str, default='CPU', choices=['Ascend', 'GPU', 'CPU'])
      parser.add_argument('--dataset', default='mini-imagenet')
      parser.add_argument('--ep_per_batch', type=int, default=4)
      parser.add_argument('--pre_result_path', type=str, default='./preprocess_Result')
      parser.add_argument('--num_shots', type=int, default=1)
  
      args_opt = parser.parse_args()
      context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.device_target, save_graphs=False)
      gen_bin(args_opt)
   """
  # Copyright 2021 Huawei Technologies Co., Ltd
  #
  # Licensed under the Apache License, Version 2.0 (the "License");
  # you may not use this file except in compliance with the License.
  # You may obtain a copy of the License at
  #
  # http://www.apache.org/licenses/LICENSE-2.0
  #
  # Unless required by applicable law or agreed to in writing, software
  # distributed under the License is distributed on an "AS IS" BASIS,
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  # See the License for the specific language governing permissions and
  # limitations under the License.
  # ============================================================================
  """
  
  
  import mindspore as ms
  import mindspore.nn as nn
  import numpy as np
  
  class Basic_Block(nn.Cell):
      """
       Components constituting resnet50
      """
      expansion = 4
      def __init__(self, in_c, out_c, stride=1, downsample=None):
          super(Basic_Block, self).__init__()
          self.conv1 = nn.Conv2d(in_channels=in_c, out_channels=out_c, kernel_size=(1, 1), stride=1)
          self.bn1 = nn.BatchNorm2d(out_c, moving_mean_init=0, moving_var_init=1)
          self.conv2 = nn.Conv2d(in_channels=out_c, out_channels=out_c, kernel_size=(3, 3), stride=stride, \
                                 pad_mode='pad', padding=1)
          self.bn2 = nn.BatchNorm2d(out_c)
          self.conv3 = nn.Conv2d(in_channels=out_c, out_channels=out_c*4, kernel_size=(1, 1), stride=1)
          self.bn3 = nn.BatchNorm2d(out_c*4)
          self.relu = nn.ReLU()
          self.down_sample_layer = downsample
  
      def construct(self, x):
          """
  
          Args:
              x: tensor
  
          Returns: tensor
  
          """
          residual = x
          out = self.conv1(x)
          out = self.bn1(out)
          out = self.relu(out)
  
          out = self.conv2(out)
          out = self.bn2(out)
          out = self.relu(out)
  
          out = self.conv3(out)
          out = self.bn3(out)
  
          if self.down_sample_layer is not None:
              residual = self.down_sample_layer(residual)
          out = out + residual
          out = self.relu(out)
          return out
  
  
  class ResNet50(nn.Cell):
      """
      A BoneBack Net of RAS
      """
      def __init__(self):
          super(ResNet50, self).__init__()
          self.in_c = 64
          self.conv1 = nn.Conv2d(3, 64, kernel_size=(7, 7), stride=2, pad_mode='pad', padding=3)
          self.bn1 = nn.BatchNorm2d(64)
          self.relu = nn.ReLU()
          self.pool = nn.MaxPool2d(kernel_size=(3, 3), stride=2, pad_mode='same')
  
          self.layer1 = self._build_layer(Basic_Block, 64, 3, 1)
          self.layer2 = self._build_layer(Basic_Block, 128, 4, 2)
          self.layer3 = self._build_layer(Basic_Block, 256, 6, 2)
          self.layer4 = self._build_layer(Basic_Block, 512, 3, 2)
  
          for _, m in self.cells_and_names():
              if isinstance(m, nn.Conv2d):
                  n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                  m.weight.set_data(ms.Tensor(np.random.normal(0, np.sqrt(2./n), m.weight.data.shape).astype(np.float32)))
              elif isinstance(m, nn.BatchNorm2d):
                  m.gamma.set_data(ms.Tensor(np.ones(m.gamma.data.shape, dtype=np.float32)))
                  m.beta.set_data(ms.Tensor(np.zeros(m.beta.data.shape, dtype=np.float32)))
  
      def _build_layer(self, block, out_c, blocks, stride):
          layers = []
          downsample = nn.SequentialCell(nn.Conv2d(self.in_c, out_c*block.expansion, kernel_size=(1, 1), stride=stride),
                                         nn.BatchNorm2d(out_c*4))
          layers.append(block(self.in_c, out_c, stride=stride, downsample=downsample))
          self.in_c = out_c * block.expansion
          for _ in range(1, blocks):
              layers.append(block(self.in_c, out_c))
          return nn.SequentialCell(layers)
  
  
      def construct(self, x):
          """
  
          Args:
              x:
  
          Returns:
              5 outputs
          """
          out = self.conv1(x)
          out = self.bn1(out)
          x1 = self.relu(out)
          x2 = self.pool(x1)
  
          x2 = self.layer1(x2)
          x3 = self.layer2(x2)
          x4 = self.layer3(x3)
          x5 = self.layer4(x4)
  
          return x1, x2, x3, x4, x5
  
apis: numpy.ones
apis: numpy.save numpy.random.seed
apis: numpy.sqrt numpy.ones numpy.zeros