code
stringlengths
208
42.9k
apis
list
extract_api
stringlengths
129
69.9k
# Some code is modified from pytorch # pytorch is licensed under BSD # From PyTorch: # Copyright (c) 2016- Facebook, Inc (<NAME>) # Copyright (c) 2014- Facebook, Inc (<NAME>) # Copyright (c) 2011-2014 Idiap Research Institute (<NAME>) # Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu) # Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu) # Copyright (c) 2011-2013 NYU (<NAME>) # Copyright (c) 2006-2010 NEC Laboratories America (<NAME>, <NAME>, <NAME>, <NAME>) # Copyright (c) 2006 Idiap Research Institute (<NAME>) # Copyright (c) 2001-2004 Idiap Research Institute (<NAME>, <NAME>, <NAME>) # From Caffe2: # Copyright (c) 2016-present, Facebook Inc. All rights reserved. # All contributions by Facebook: # Copyright (c) 2016 Facebook Inc. # All contributions by Google: # Copyright (c) 2015 Google Inc. # All rights reserved. # All contributions by Yang<NAME>: # Copyright (c) 2015 Yang<NAME> # All rights reserved. # All contributions by Kakao Brain: # Copyright 2019-2020 Kakao Brain # All contributions from Caffe: # Copyright(c) 2013, 2014, 2015, the respective contributors # All rights reserved. # All other contributions: # Copyright(c) 2015, 2016 the respective contributors # All rights reserved. # Caffe2 uses a copyright model similar to Caffe: each contributor holds # copyright over their contributions to Caffe2. The project versioning records # all such contribution and copyright details. If a contributor wants to further # mark their specific copyright on a particular contribution, they should # indicate their copyright solely in the commit message of the change when it is # committed. # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America # and IDIAP Research Institute nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import megengine as mge import megengine.module as M from megengine import functional as F from megengine import Parameter from megengine.module.init import xavier_uniform_, zeros_ from typing import List, Tuple, Dict, Optional import numpy as np from .utility import safe_masked_fill, has_nan_or_inf def multi_head_attention_forward( query: mge.Tensor, key: mge.Tensor, value: mge.Tensor, embed_dim_to_check: int, num_heads: int, in_proj_weight: mge.Tensor, in_proj_bias: Optional[mge.Tensor], bias_k: Optional[mge.Tensor], bias_v: Optional[mge.Tensor], add_zero_attn: bool, dropout_p: float, out_proj_weight: mge.Tensor, out_proj_bias: Optional[mge.Tensor], training: bool = True, key_padding_mask: Optional[mge.Tensor] = None, need_weights: bool = True, attn_mask: Optional[mge.Tensor] = None, use_separate_proj_weight: bool = False, q_proj_weight: Optional[mge.Tensor] = None, k_proj_weight: Optional[mge.Tensor] = None, v_proj_weight: Optional[mge.Tensor] = None, static_k: Optional[mge.Tensor] = None, static_v: Optional[mge.Tensor] = None, proj_only: bool = False ) -> Tuple[mge.Tensor, Optional[mge.Tensor]]: r""" Args: query, key, value: map a query and a set of key-value pairs to an output. See "Attention Is All You Need" for more details. embed_dim_to_check: total dimension of the model. num_heads: parallel attention heads. in_proj_weight, in_proj_bias: input projection weight and bias. bias_k, bias_v: bias of the key and value sequences to be added at dim=0. add_zero_attn: add a new batch of zeros to the key and value sequences at dim=1. dropout_p: probability of an element to be zeroed. out_proj_weight, out_proj_bias: the output projection weight and bias. training: apply dropout if is ``True``. key_padding_mask: if provided, specified padding elements in the key will be ignored by the attention. This is an binary mask. When the value is True, the corresponding value on the attention layer will be filled with -inf. need_weights: output attn_output_weights. attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all the batches while a 3D mask allows to specify a different mask for the entries of each batch. use_separate_proj_weight: the function accept the proj. weights for query, key, and value in different forms. If false, in_proj_weight will be used, which is a combination of q_proj_weight, k_proj_weight, v_proj_weight. q_proj_weight, k_proj_weight, v_proj_weight, in_proj_bias: input projection weight and bias. static_k, static_v: static key and value used for attention operators. Shape: Inputs: - query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is the embedding dimension. - key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is the embedding dimension. - value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is the embedding dimension. - key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length. If a ByteTensor is provided, the non-zero positions will be ignored while the zero positions will be unchanged. If a BoolTensor is provided, the positions with the value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged. - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length. 3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length, S is the source sequence length. attn_mask ensures that position i is allowed to attend the unmasked positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True`` are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor is provided, it will be added to the attention weight. - static_k: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length, N is the batch size, E is the embedding dimension. E/num_heads is the head dimension. - static_v: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length, N is the batch size, E is the embedding dimension. E/num_heads is the head dimension. Outputs: - attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is the embedding dimension. - attn_output_weights: :math:`(N, L, S)` where N is the batch size, L is the target sequence length, S is the source sequence length. """ tgt_len, bsz, embed_dim = query.shape assert embed_dim == embed_dim_to_check # allow MHA to have different sizes for the feature dimension assert key.shape[0] == value.shape[0] and key.shape[1] == value.shape[1] if isinstance(embed_dim, mge.Tensor): # embed_dim can be a tensor when JIT tracing #head_dim = embed_dim.div(num_heads, rounding_mode='trunc') #NOTE: when positive number, floor_div is equivalent to trunc_div (in megengine only floor_div is available) head_dim = F.floor_div(embed_dim, num_heads) else: head_dim = embed_dim // num_heads assert head_dim * num_heads == embed_dim, "embed_dim must be divisible by num_heads" scaling = float(head_dim) ** -0.5 assert not use_separate_proj_weight assert need_weights assert attn_mask is None assert bias_k is None and bias_v is None assert not add_zero_attn # This is inline in_proj function with in_proj_weight and in_proj_bias _b = in_proj_bias _start = 0 _end = embed_dim _w = in_proj_weight[_start:_end, :] if _b is not None: _b = _b[_start:_end] q = F.linear(query, _w, _b) # This is inline in_proj function with in_proj_weight and in_proj_bias _b = in_proj_bias _start = embed_dim _end = embed_dim * 2 _w = in_proj_weight[_start:_end, :] if _b is not None: _b = _b[_start:_end] k = F.linear(key, _w, _b) # This is inline in_proj function with in_proj_weight and in_proj_bias _b = in_proj_bias _start = embed_dim * 2 _end = None _w = in_proj_weight[_start:, :] if _b is not None: _b = _b[_start:] v = F.linear(value, _w, _b) q = q * scaling raw_v = v raw_v = raw_v.reshape(-1, bsz, num_heads, head_dim) if proj_only: return query, None, raw_v # convert ByteTensor key_padding_mask to bool if key_padding_mask is not None and key_padding_mask.dtype == np.uint8: warnings.warn( "Byte tensor for key_padding_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead." ) key_padding_mask = key_padding_mask.astype(np.bool) #def _pad_last_dim_right_only(tensor): # ''' # To replace with torch.nn.functional.pad(tensor, (0, 1)) # ''' # return F.concat([tensor, F.expand_dims(F.zeros(tensor.shape[:-1]), axis=-1)], axis=-1) #q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1) q = q.reshape(tgt_len, bsz * num_heads, head_dim).transpose(1, 0, 2) if k is not None: #k = k.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) k = k.reshape(-1, bsz * num_heads, head_dim).transpose(1, 0, 2) if v is not None: #v = v.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) v = v.reshape(-1, bsz * num_heads, head_dim).transpose(1, 0, 2) if static_k is not None: assert static_k.shape[0] == bsz * num_heads assert static_k.shape[2] == head_dim k = static_k if static_v is not None: assert static_v.shape[0] == bsz * num_heads assert static_v.shape[2] == head_dim v = static_v src_len = k.shape[1] if key_padding_mask is not None: assert key_padding_mask.shape[1] == src_len #attn_output_weights = torch.bmm(q, k.transpose(1, 2)) attn_output_weights = F.matmul(q, k.transpose(0, 2, 1)) assert list(attn_output_weights.shape) == [bsz * num_heads, tgt_len, src_len] if key_padding_mask is not None: attn_output_weights = attn_output_weights.reshape(bsz, num_heads, tgt_len, src_len) key_padding_mask = F.expand_dims(F.expand_dims(key_padding_mask, axis=1), axis=2) attn_output_weights = safe_masked_fill(attn_output_weights, key_padding_mask, float("-inf")) attn_output_weights = attn_output_weights.reshape(bsz * num_heads, tgt_len, src_len) attn_output_weights_no_softmax = attn_output_weights attn_output_weights = F.softmax(attn_output_weights, axis=-1) attn_output_weights = F.dropout(attn_output_weights, dropout_p, training=training) attn_output = F.matmul(attn_output_weights, v) assert attn_output.shape == (bsz * num_heads, tgt_len, head_dim) attn_output = F.transpose(attn_output, (1, 0, 2)).reshape(tgt_len, bsz, embed_dim) attn_output = F.nn.linear(attn_output, out_proj_weight, out_proj_bias) # average attention weights over heads attn_output_weights = attn_output_weights_no_softmax.reshape(bsz, num_heads, tgt_len, src_len) return attn_output, attn_output_weights, raw_v class MultiheadAttention(M.Module): r"""Allows the model to jointly attend to information from different representation subspaces. See `Attention Is All You Need <https://arxiv.org/abs/1706.03762>`_ .. math:: \text{MultiHead}(Q, K, V) = \text{Concat}(head_1,\dots,head_h)W^O where :math:`head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)`. Args: embed_dim: total dimension of the model. num_heads: parallel attention heads. dropout: a Dropout layer on attn_output_weights. Default: 0.0. bias: add bias as module parameter. Default: True. add_bias_kv: add bias to the key and value sequences at dim=0. add_zero_attn: add a new batch of zeros to the key and value sequences at dim=1. kdim: total number of features in key. Default: None. vdim: total number of features in value. Default: None. batch_first: If ``True``, then the input and output tensors are provided as (batch, seq, feature). Default: ``False`` (seq, batch, feature). Note that if :attr:`kdim` and :attr:`vdim` are None, they will be set to :attr:`embed_dim` such that query, key, and value have the same number of features. Examples:: >>> multihead_attn = nn.MultiheadAttention(embed_dim, num_heads) >>> attn_output, attn_output_weights = multihead_attn(query, key, value) """ __constants__ = ['batch_first'] bias_k: Optional[mge.Tensor] bias_v: Optional[mge.Tensor] def __init__(self, embed_dim, num_heads, dropout=0., bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None, batch_first=False): super(MultiheadAttention, self).__init__() self.embed_dim = embed_dim self.kdim = kdim if kdim is not None else embed_dim self.vdim = vdim if vdim is not None else embed_dim # True By default self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim self.num_heads = num_heads self.dropout = dropout # False By default self.batch_first = batch_first self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads" self.in_proj_weight = Parameter(F.zeros((3 * embed_dim, embed_dim))) if bias: self.in_proj_bias = Parameter(F.zeros((3 * embed_dim,))) else: self.in_proj_bias = None self.out_proj = M.Linear(embed_dim, embed_dim, bias=bias) if add_bias_kv: self.bias_k = Parameter(F.zeros((1, 1, embed_dim))) self.bias_v = Parameter(F.zeros((1, 1, embed_dim))) else: self.bias_k = self.bias_v = None self.add_zero_attn = add_zero_attn self._reset_parameters() def _reset_parameters(self): xavier_uniform_(self.in_proj_weight) if self.in_proj_bias is not None: zeros_(self.in_proj_bias) zeros_(self.out_proj.bias) if self.bias_k is not None: xavier_normal_(self.bias_k) if self.bias_v is not None: xavier_normal_(self.bias_v) def __setstate__(self, state): # Support loading old MultiheadAttention checkpoints generated by v1.1.0 if '_qkv_same_embed_dim' not in state: state['_qkv_same_embed_dim'] = True super(MultiheadAttention, self).__setstate__(state) def forward(self, query: mge.Tensor, key: mge.Tensor, value: mge.Tensor, key_padding_mask: Optional[mge.Tensor] = None, need_weights: bool = True, attn_mask: Optional[mge.Tensor] = None, proj_only=False) -> Tuple[mge.Tensor, Optional[mge.Tensor]]: r""" Args: query, key, value: map a query and a set of key-value pairs to an output. See "Attention Is All You Need" for more details. key_padding_mask: if provided, specified padding elements in the key will be ignored by the attention. When given a binary mask and a value is True, the corresponding value on the attention layer will be ignored. When given a byte mask and a value is non-zero, the corresponding value on the attention layer will be ignored need_weights: output attn_output_weights. attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all the batches while a 3D mask allows to specify a different mask for the entries of each batch. Shapes for inputs: - query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is the embedding dimension. :math:`(N, L, E)` if ``batch_first`` is ``True``. - key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is the embedding dimension. :math:`(N, S, E)` if ``batch_first`` is ``True``. - value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is the embedding dimension. :math:`(N, S, E)` if ``batch_first`` is ``True``. - key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length. If a ByteTensor is provided, the non-zero positions will be ignored while the position with the zero positions will be unchanged. If a BoolTensor is provided, the positions with the value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged. - attn_mask: if a 2D mask: :math:`(L, S)` where L is the target sequence length, S is the source sequence length. If a 3D mask: :math:`(N\cdot\text{num\_heads}, L, S)` where N is the batch size, L is the target sequence length, S is the source sequence length. ``attn_mask`` ensure that position i is allowed to attend the unmasked positions. If a ByteTensor is provided, the non-zero positions are not allowed to attend while the zero positions will be unchanged. If a BoolTensor is provided, positions with ``True`` is not allowed to attend while ``False`` values will be unchanged. If a FloatTensor is provided, it will be added to the attention weight. Shapes for outputs: - attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is the embedding dimension. :math:`(N, L, E)` if ``batch_first`` is ``True``. - attn_output_weights: :math:`(N, L, S)` where N is the batch size, L is the target sequence length, S is the source sequence length. """ attn_output, attn_output_weights, values = multi_head_attention_forward( query, key, value, self.embed_dim, self.num_heads, self.in_proj_weight, self.in_proj_bias, self.bias_k, self.bias_v, self.add_zero_attn, self.dropout, self.out_proj.weight, self.out_proj.bias, training=self.training, key_padding_mask=key_padding_mask, need_weights=need_weights, #need_weights by default is True attn_mask=attn_mask, proj_only=proj_only) return attn_output, attn_output_weights, values
[ "megengine.functional.nn.linear", "megengine.functional.floor_div", "megengine.functional.zeros", "megengine.module.init.zeros_", "megengine.functional.matmul", "megengine.functional.softmax", "megengine.functional.expand_dims", "megengine.functional.transpose", "megengine.functional.dropout", "megengine.module.Linear", "megengine.functional.linear", "megengine.module.init.xavier_uniform_" ]
[((9573, 9596), 'megengine.functional.linear', 'F.linear', (['query', '_w', '_b'], {}), '(query, _w, _b)\n', (9581, 9596), True, 'from megengine import functional as F\n'), ((9843, 9864), 'megengine.functional.linear', 'F.linear', (['key', '_w', '_b'], {}), '(key, _w, _b)\n', (9851, 9864), True, 'from megengine import functional as F\n'), ((10098, 10121), 'megengine.functional.linear', 'F.linear', (['value', '_w', '_b'], {}), '(value, _w, _b)\n', (10106, 10121), True, 'from megengine import functional as F\n'), ((12452, 12491), 'megengine.functional.softmax', 'F.softmax', (['attn_output_weights'], {'axis': '(-1)'}), '(attn_output_weights, axis=-1)\n', (12461, 12491), True, 'from megengine import functional as F\n'), ((12518, 12578), 'megengine.functional.dropout', 'F.dropout', (['attn_output_weights', 'dropout_p'], {'training': 'training'}), '(attn_output_weights, dropout_p, training=training)\n', (12527, 12578), True, 'from megengine import functional as F\n'), ((12598, 12630), 'megengine.functional.matmul', 'F.matmul', (['attn_output_weights', 'v'], {}), '(attn_output_weights, v)\n', (12606, 12630), True, 'from megengine import functional as F\n'), ((12805, 12861), 'megengine.functional.nn.linear', 'F.nn.linear', (['attn_output', 'out_proj_weight', 'out_proj_bias'], {}), '(attn_output, out_proj_weight, out_proj_bias)\n', (12816, 12861), True, 'from megengine import functional as F\n'), ((8958, 8991), 'megengine.functional.floor_div', 'F.floor_div', (['embed_dim', 'num_heads'], {}), '(embed_dim, num_heads)\n', (8969, 8991), True, 'from megengine import functional as F\n'), ((15589, 15630), 'megengine.module.Linear', 'M.Linear', (['embed_dim', 'embed_dim'], {'bias': 'bias'}), '(embed_dim, embed_dim, bias=bias)\n', (15597, 15630), True, 'import megengine.module as M\n'), ((15963, 15999), 'megengine.module.init.xavier_uniform_', 'xavier_uniform_', (['self.in_proj_weight'], {}), '(self.in_proj_weight)\n', (15978, 15999), False, 'from megengine.module.init import xavier_uniform_, zeros_\n'), ((12125, 12164), 'megengine.functional.expand_dims', 'F.expand_dims', (['key_padding_mask'], {'axis': '(1)'}), '(key_padding_mask, axis=1)\n', (12138, 12164), True, 'from megengine import functional as F\n'), ((12718, 12753), 'megengine.functional.transpose', 'F.transpose', (['attn_output', '(1, 0, 2)'], {}), '(attn_output, (1, 0, 2))\n', (12729, 12753), True, 'from megengine import functional as F\n'), ((15390, 15425), 'megengine.functional.zeros', 'F.zeros', (['(3 * embed_dim, embed_dim)'], {}), '((3 * embed_dim, embed_dim))\n', (15397, 15425), True, 'from megengine import functional as F\n'), ((16055, 16080), 'megengine.module.init.zeros_', 'zeros_', (['self.in_proj_bias'], {}), '(self.in_proj_bias)\n', (16061, 16080), False, 'from megengine.module.init import xavier_uniform_, zeros_\n'), ((16093, 16119), 'megengine.module.init.zeros_', 'zeros_', (['self.out_proj.bias'], {}), '(self.out_proj.bias)\n', (16099, 16119), False, 'from megengine.module.init import xavier_uniform_, zeros_\n'), ((15487, 15512), 'megengine.functional.zeros', 'F.zeros', (['(3 * embed_dim,)'], {}), '((3 * embed_dim,))\n', (15494, 15512), True, 'from megengine import functional as F\n'), ((15692, 15718), 'megengine.functional.zeros', 'F.zeros', (['(1, 1, embed_dim)'], {}), '((1, 1, embed_dim))\n', (15699, 15718), True, 'from megengine import functional as F\n'), ((15756, 15782), 'megengine.functional.zeros', 'F.zeros', (['(1, 1, embed_dim)'], {}), '((1, 1, embed_dim))\n', (15763, 15782), True, 'from megengine import functional as F\n')]
import megengine as mge import megengine.module as nn import megengine.functional as F from model.module import Encoder, Fusion, Decoder, Regression from common import se3, quaternion import math class OMNet(nn.Module): def __init__(self, params): super(OMNet, self).__init__() self.num_iter = params.titer self.encoder = [Encoder() for _ in range(self.num_iter)] self.fusion = [Fusion() for _ in range(self.num_iter)] self.decoder = [Decoder() for _ in range(self.num_iter)] self.regression = [Regression() for _ in range(self.num_iter)] self.overlap_dist = params.overlap_dist for m in self.modules(): if isinstance(m, nn.Conv1d) or isinstance(m, nn.Linear): nn.init.msra_normal_(m.weight, a=math.sqrt(5)) if m.bias is not None: fan_in, _ = nn.init.calculate_fan_in_and_fan_out(m.weight) bound = 1 / math.sqrt(fan_in) nn.init.uniform_(m.bias, -bound, bound) # elif isinstance(m, nn.BatchNorm1d): # nn.init.ones_(m.weight) # nn.init.zeros_(m.bias) def generate_overlap_mask(self, points_src, points_ref, mask_src, mask_ref, transform_gt): points_src[F.logical_not(mask_src.astype("bool")), :] = 50.0 points_ref[F.logical_not(mask_ref.astype("bool")), :] = 100.0 points_src = se3.mge_transform(transform_gt, points_src) points_src = F.expand_dims(points_src, axis=2) points_ref = F.expand_dims(points_ref, axis=1) dist_matrix = F.sqrt(F.sum(F.square(points_src - points_ref), axis=-1)) # (B, N, N) dist_s2r = F.min(dist_matrix, axis=2) dist_r2s = F.min(dist_matrix, axis=1) overlap_src_mask = dist_s2r < self.overlap_dist # (B, N) overlap_ref_mask = dist_r2s < self.overlap_dist # (B, N) return overlap_src_mask, overlap_ref_mask def forward(self, data_batch): endpoints = {} xyz_src = data_batch["points_src"] xyz_ref = data_batch["points_ref"] transform_gt = data_batch["transform_gt"] pose_gt = data_batch["pose_gt"] # init endpoints all_src_cls_pair = [] all_ref_cls_pair = [] all_transform_pair = [] all_pose_pair = [] all_xyz_src_t = [xyz_src] # init params B, src_N, _ = xyz_src.shape _, ref_N, _ = xyz_ref.shape init_quat = F.tile(mge.tensor([1, 0, 0, 0], dtype="float32"), (B, 1)) # (B, 4) init_translate = F.tile(mge.tensor([0, 0, 0], dtype="float32"), (B, 1)) # (B, 3) pose_pred = F.concat((init_quat, init_translate), axis=1) # (B, 7) # rename xyz_src xyz_src_iter = F.copy(xyz_src, device=xyz_src.device) for i in range(self.num_iter): # deley mask if i < 2: src_pred_mask = F.ones((B, src_N), dtype=xyz_src.dtype) ref_pred_mask = F.ones((B, ref_N), dtype=xyz_ref.dtype) # encoder src_encoder_feats, src_glob_feat = self.encoder[i](xyz_src_iter.transpose(0, 2, 1).detach(), F.expand_dims(src_pred_mask, axis=1)) ref_encoder_feats, ref_glob_feat = self.encoder[i](xyz_ref.transpose(0, 2, 1).detach(), F.expand_dims(ref_pred_mask, axis=1)) # fusion src_concat_feat = F.concat( (src_encoder_feats[0], F.repeat(src_glob_feat, src_N, axis=2), F.repeat(ref_glob_feat, src_N, axis=2)), axis=1) ref_concat_feat = F.concat( (ref_encoder_feats[0], F.repeat(ref_glob_feat, ref_N, axis=2), F.repeat(src_glob_feat, ref_N, axis=2)), axis=1) _, src_fused_feat = self.fusion[i](src_concat_feat, F.expand_dims(src_pred_mask, axis=1)) _, ref_fused_feat = self.fusion[i](ref_concat_feat, F.expand_dims(ref_pred_mask, axis=1)) # decoder src_decoder_feats, src_cls_pred = self.decoder[i](src_fused_feat) ref_decoder_feats, ref_cls_pred = self.decoder[i](ref_fused_feat) # regression src_feat = F.concat(src_decoder_feats, axis=1) * F.expand_dims(src_pred_mask, axis=1) ref_feat = F.concat(ref_decoder_feats, axis=1) * F.expand_dims(ref_pred_mask, axis=1) concat_feat = F.concat((src_fused_feat, src_feat, ref_fused_feat, ref_feat), axis=1) concat_feat = F.max(concat_feat, axis=-1) pose_pred_iter = self.regression[i](concat_feat) # (B, 7) xyz_src_iter = quaternion.mge_quat_transform(pose_pred_iter, xyz_src_iter.detach()) pose_pred = quaternion.mge_transform_pose(pose_pred.detach(), pose_pred_iter) transform_pred = quaternion.mge_quat2mat(pose_pred) # compute overlap and cls gt overlap_src_mask, overlap_ref_mask = self.generate_overlap_mask(F.copy(xyz_src, device=xyz_src.device), F.copy(xyz_ref, device=xyz_ref.device), src_pred_mask, ref_pred_mask, transform_gt) # overlap_src_mask, overlap_ref_mask = self.generate_overlap_mask(xyz_src, xyz_ref, src_pred_mask, ref_pred_mask, transform_gt) src_cls_gt = F.ones((B, src_N)) * overlap_src_mask ref_cls_gt = F.ones((B, ref_N)) * overlap_ref_mask src_pred_mask = F.argmax(src_cls_pred, axis=1) ref_pred_mask = F.argmax(ref_cls_pred, axis=1) # add endpoints all_src_cls_pair.append([src_cls_gt, src_cls_pred]) all_ref_cls_pair.append([ref_cls_gt, ref_cls_pred]) all_transform_pair.append([transform_gt, transform_pred]) all_pose_pair.append([pose_gt, pose_pred]) all_xyz_src_t.append(xyz_src_iter) endpoints["all_src_cls_pair"] = all_src_cls_pair endpoints["all_ref_cls_pair"] = all_ref_cls_pair endpoints["all_transform_pair"] = all_transform_pair endpoints["all_pose_pair"] = all_pose_pair endpoints["transform_pair"] = [transform_gt, transform_pred] endpoints["pose_pair"] = [pose_gt, pose_pred] endpoints["all_xyz_src_t"] = all_xyz_src_t return endpoints def fetch_net(params): if params.net_type == "omnet": net = OMNet(params) else: raise NotImplementedError return net
[ "megengine.functional.repeat", "megengine.module.init.calculate_fan_in_and_fan_out", "megengine.functional.ones", "megengine.functional.expand_dims", "megengine.functional.concat", "megengine.functional.max", "megengine.functional.min", "megengine.functional.argmax", "megengine.tensor", "megengine.functional.copy", "megengine.module.init.uniform_", "megengine.functional.square" ]
[((1424, 1467), 'common.se3.mge_transform', 'se3.mge_transform', (['transform_gt', 'points_src'], {}), '(transform_gt, points_src)\n', (1441, 1467), False, 'from common import se3, quaternion\n'), ((1489, 1522), 'megengine.functional.expand_dims', 'F.expand_dims', (['points_src'], {'axis': '(2)'}), '(points_src, axis=2)\n', (1502, 1522), True, 'import megengine.functional as F\n'), ((1544, 1577), 'megengine.functional.expand_dims', 'F.expand_dims', (['points_ref'], {'axis': '(1)'}), '(points_ref, axis=1)\n', (1557, 1577), True, 'import megengine.functional as F\n'), ((1690, 1716), 'megengine.functional.min', 'F.min', (['dist_matrix'], {'axis': '(2)'}), '(dist_matrix, axis=2)\n', (1695, 1716), True, 'import megengine.functional as F\n'), ((1736, 1762), 'megengine.functional.min', 'F.min', (['dist_matrix'], {'axis': '(1)'}), '(dist_matrix, axis=1)\n', (1741, 1762), True, 'import megengine.functional as F\n'), ((2653, 2698), 'megengine.functional.concat', 'F.concat', (['(init_quat, init_translate)'], {'axis': '(1)'}), '((init_quat, init_translate), axis=1)\n', (2661, 2698), True, 'import megengine.functional as F\n'), ((2758, 2796), 'megengine.functional.copy', 'F.copy', (['xyz_src'], {'device': 'xyz_src.device'}), '(xyz_src, device=xyz_src.device)\n', (2764, 2796), True, 'import megengine.functional as F\n'), ((353, 362), 'model.module.Encoder', 'Encoder', ([], {}), '()\n', (360, 362), False, 'from model.module import Encoder, Fusion, Decoder, Regression\n'), ((417, 425), 'model.module.Fusion', 'Fusion', ([], {}), '()\n', (423, 425), False, 'from model.module import Encoder, Fusion, Decoder, Regression\n'), ((481, 490), 'model.module.Decoder', 'Decoder', ([], {}), '()\n', (488, 490), False, 'from model.module import Encoder, Fusion, Decoder, Regression\n'), ((549, 561), 'model.module.Regression', 'Regression', ([], {}), '()\n', (559, 561), False, 'from model.module import Encoder, Fusion, Decoder, Regression\n'), ((2482, 2523), 'megengine.tensor', 'mge.tensor', (['[1, 0, 0, 0]'], {'dtype': '"""float32"""'}), "([1, 0, 0, 0], dtype='float32')\n", (2492, 2523), True, 'import megengine as mge\n'), ((2575, 2613), 'megengine.tensor', 'mge.tensor', (['[0, 0, 0]'], {'dtype': '"""float32"""'}), "([0, 0, 0], dtype='float32')\n", (2585, 2613), True, 'import megengine as mge\n'), ((4439, 4509), 'megengine.functional.concat', 'F.concat', (['(src_fused_feat, src_feat, ref_fused_feat, ref_feat)'], {'axis': '(1)'}), '((src_fused_feat, src_feat, ref_fused_feat, ref_feat), axis=1)\n', (4447, 4509), True, 'import megengine.functional as F\n'), ((4536, 4563), 'megengine.functional.max', 'F.max', (['concat_feat'], {'axis': '(-1)'}), '(concat_feat, axis=-1)\n', (4541, 4563), True, 'import megengine.functional as F\n'), ((4850, 4884), 'common.quaternion.mge_quat2mat', 'quaternion.mge_quat2mat', (['pose_pred'], {}), '(pose_pred)\n', (4873, 4884), False, 'from common import se3, quaternion\n'), ((5573, 5603), 'megengine.functional.argmax', 'F.argmax', (['src_cls_pred'], {'axis': '(1)'}), '(src_cls_pred, axis=1)\n', (5581, 5603), True, 'import megengine.functional as F\n'), ((5632, 5662), 'megengine.functional.argmax', 'F.argmax', (['ref_cls_pred'], {'axis': '(1)'}), '(ref_cls_pred, axis=1)\n', (5640, 5662), True, 'import megengine.functional as F\n'), ((1613, 1646), 'megengine.functional.square', 'F.square', (['(points_src - points_ref)'], {}), '(points_src - points_ref)\n', (1621, 1646), True, 'import megengine.functional as F\n'), ((2916, 2955), 'megengine.functional.ones', 'F.ones', (['(B, src_N)'], {'dtype': 'xyz_src.dtype'}), '((B, src_N), dtype=xyz_src.dtype)\n', (2922, 2955), True, 'import megengine.functional as F\n'), ((2988, 3027), 'megengine.functional.ones', 'F.ones', (['(B, ref_N)'], {'dtype': 'xyz_ref.dtype'}), '((B, ref_N), dtype=xyz_ref.dtype)\n', (2994, 3027), True, 'import megengine.functional as F\n'), ((3156, 3192), 'megengine.functional.expand_dims', 'F.expand_dims', (['src_pred_mask'], {'axis': '(1)'}), '(src_pred_mask, axis=1)\n', (3169, 3192), True, 'import megengine.functional as F\n'), ((3413, 3449), 'megengine.functional.expand_dims', 'F.expand_dims', (['ref_pred_mask'], {'axis': '(1)'}), '(ref_pred_mask, axis=1)\n', (3426, 3449), True, 'import megengine.functional as F\n'), ((3872, 3908), 'megengine.functional.expand_dims', 'F.expand_dims', (['src_pred_mask'], {'axis': '(1)'}), '(src_pred_mask, axis=1)\n', (3885, 3908), True, 'import megengine.functional as F\n'), ((3974, 4010), 'megengine.functional.expand_dims', 'F.expand_dims', (['ref_pred_mask'], {'axis': '(1)'}), '(ref_pred_mask, axis=1)\n', (3987, 4010), True, 'import megengine.functional as F\n'), ((4240, 4275), 'megengine.functional.concat', 'F.concat', (['src_decoder_feats'], {'axis': '(1)'}), '(src_decoder_feats, axis=1)\n', (4248, 4275), True, 'import megengine.functional as F\n'), ((4278, 4314), 'megengine.functional.expand_dims', 'F.expand_dims', (['src_pred_mask'], {'axis': '(1)'}), '(src_pred_mask, axis=1)\n', (4291, 4314), True, 'import megengine.functional as F\n'), ((4338, 4373), 'megengine.functional.concat', 'F.concat', (['ref_decoder_feats'], {'axis': '(1)'}), '(ref_decoder_feats, axis=1)\n', (4346, 4373), True, 'import megengine.functional as F\n'), ((4376, 4412), 'megengine.functional.expand_dims', 'F.expand_dims', (['ref_pred_mask'], {'axis': '(1)'}), '(ref_pred_mask, axis=1)\n', (4389, 4412), True, 'import megengine.functional as F\n'), ((5003, 5041), 'megengine.functional.copy', 'F.copy', (['xyz_src'], {'device': 'xyz_src.device'}), '(xyz_src, device=xyz_src.device)\n', (5009, 5041), True, 'import megengine.functional as F\n'), ((5119, 5157), 'megengine.functional.copy', 'F.copy', (['xyz_ref'], {'device': 'xyz_ref.device'}), '(xyz_ref, device=xyz_ref.device)\n', (5125, 5157), True, 'import megengine.functional as F\n'), ((5444, 5462), 'megengine.functional.ones', 'F.ones', (['(B, src_N)'], {}), '((B, src_N))\n', (5450, 5462), True, 'import megengine.functional as F\n'), ((5507, 5525), 'megengine.functional.ones', 'F.ones', (['(B, ref_N)'], {}), '((B, ref_N))\n', (5513, 5525), True, 'import megengine.functional as F\n'), ((878, 924), 'megengine.module.init.calculate_fan_in_and_fan_out', 'nn.init.calculate_fan_in_and_fan_out', (['m.weight'], {}), '(m.weight)\n', (914, 924), True, 'import megengine.module as nn\n'), ((995, 1034), 'megengine.module.init.uniform_', 'nn.init.uniform_', (['m.bias', '(-bound)', 'bound'], {}), '(m.bias, -bound, bound)\n', (1011, 1034), True, 'import megengine.module as nn\n'), ((3551, 3589), 'megengine.functional.repeat', 'F.repeat', (['src_glob_feat', 'src_N'], {'axis': '(2)'}), '(src_glob_feat, src_N, axis=2)\n', (3559, 3589), True, 'import megengine.functional as F\n'), ((3591, 3629), 'megengine.functional.repeat', 'F.repeat', (['ref_glob_feat', 'src_N'], {'axis': '(2)'}), '(ref_glob_feat, src_N, axis=2)\n', (3599, 3629), True, 'import megengine.functional as F\n'), ((3719, 3757), 'megengine.functional.repeat', 'F.repeat', (['ref_glob_feat', 'ref_N'], {'axis': '(2)'}), '(ref_glob_feat, ref_N, axis=2)\n', (3727, 3757), True, 'import megengine.functional as F\n'), ((3759, 3797), 'megengine.functional.repeat', 'F.repeat', (['src_glob_feat', 'ref_N'], {'axis': '(2)'}), '(src_glob_feat, ref_N, axis=2)\n', (3767, 3797), True, 'import megengine.functional as F\n'), ((793, 805), 'math.sqrt', 'math.sqrt', (['(5)'], {}), '(5)\n', (802, 805), False, 'import math\n'), ((957, 974), 'math.sqrt', 'math.sqrt', (['fan_in'], {}), '(fan_in)\n', (966, 974), False, 'import math\n')]
#! /usr/bin/env python3 # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import argparse import logging import re from collections import namedtuple import numpy as np from tqdm import tqdm import megengine as mge from megengine.core.tensor.dtype import is_quantize from megengine.logger import _imperative_rt_logger, get_logger, set_mgb_log_level from megengine.utils.module_stats import ( enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats, ) from megengine.utils.network import Network logger = get_logger(__name__) def visualize( model_path: str, log_path: str, input: np.ndarray = None, inp_dict: dict = None, cal_params: bool = True, cal_flops: bool = True, cal_activations: bool = True, logging_to_stdout: bool = True, bar_length_max: int = 20, ): r"""Load megengine dumped model and visualize graph structure with tensorboard log files. Can also record and print model's statistics like :func:`~.module_stats` Args: model_path: dir path for megengine dumped model. log_path: dir path for tensorboard graph log. input: user defined input data for running model and calculating stats, alternative with inp_dict, used when the model has only one input. inp_dict: input dict for running model and calculating stats, alternative with input, used when the model has more than one input. When both input and inp_dict are None, a random input will be used. cal_params: whether calculate and record params size. cal_flops: whether calculate and record op flops. cal_activations: whether calculate and record op activations. logging_to_stdout: whether print all calculated statistic details. bar_length_max: size of bar indicating max flops or parameter size in net stats. model_path: str: log_path: str: input: np.ndarray: inp_dict: dict: cal_params: bool: cal_flops: bool: cal_activations: bool: logging_to_stdout: bool: bar_length_max: int: """ if log_path: try: from tensorboard.compat.proto.attr_value_pb2 import AttrValue from tensorboard.compat.proto.config_pb2 import RunMetadata from tensorboard.compat.proto.graph_pb2 import GraphDef from tensorboard.compat.proto.node_def_pb2 import NodeDef from tensorboard.compat.proto.step_stats_pb2 import ( AllocatorMemoryUsed, DeviceStepStats, NodeExecStats, StepStats, ) from tensorboard.compat.proto.tensor_shape_pb2 import TensorShapeProto from tensorboard.compat.proto.versions_pb2 import VersionDef from tensorboardX import SummaryWriter except ImportError: logger.error( "TensorBoard and TensorboardX are required for visualize.", exc_info=True, ) return enable_receptive_field() graph = Network.load(model_path) graph.reset_batch_size(1) has_input = False if input is not None or inp_dict is not None: has_input = True repl_dict = {} inp_vars = graph.input_vars if inp_dict is not None: assert len(inp_dict) == len( inp_vars ), "Inputs are not sufficient for calculation." for v in inp_vars: new_input = graph.make_const(inp_dict[v.name], name=v.name) repl_dict[v] = new_input else: assert len(inp_vars) == 1, "The graph needs more than one input." inp_var = inp_vars[0] repl_dict[inp_var] = graph.make_const(input, name=inp_var.name) graph.replace_vars(repl_dict=repl_dict) graph._compile() def process_name(name): # nodes that start with point or contain float const will lead to display bug if not re.match(r"^[+-]?\d*\.\d*", name): name = name.replace(".", "/") return name.encode(encoding="utf-8") summary = [["item", "value"]] node_list = [] flops_list = [] params_list = [] activations_list = [] total_stats = namedtuple( "total_stats", ["param_size", "param_dims", "flops", "act_size", "act_dims"] ) stats_details = namedtuple("module_stats", ["params", "flops", "activations"]) for node in tqdm(graph.all_oprs): if hasattr(node, "output_idx"): node_oup = node.outputs[node.output_idx] else: if len(node.outputs) != 1: logger.warning( "OpNode {} has more than one output and not has 'output_idx' attr.".format( node ) ) node_oup = node.outputs[0] inp_list = [process_name(var.owner.name) for var in node.inputs] if log_path: # detail format see tensorboard/compat/proto/attr_value.proto attr = { "_output_shapes": AttrValue( list=AttrValue.ListValue( shape=[ TensorShapeProto( dim=[ TensorShapeProto.Dim(size=d) for d in node_oup.shape ] ) ] ) ), "params": AttrValue(s=str(node.params).encode(encoding="utf-8")), "dtype": AttrValue(s=str(node_oup.dtype).encode(encoding="utf-8")), } if cal_flops: flops_stats = get_op_stats(node, node.inputs, node.outputs) if flops_stats is not None: # add op flops attr if log_path and hasattr(flops_stats, "flops_num"): attr["flops"] = AttrValue( s=sizeof_fmt(flops_stats["flops"]).encode(encoding="utf-8") ) flops_stats["name"] = node.name flops_stats["class_name"] = node.type flops_list.append(flops_stats) if cal_activations: acts = get_activation_stats(node_oup, has_input=has_input) acts["name"] = node.name acts["class_name"] = node.type activations_list.append(acts) if cal_params: if node.type == "ImmutableTensor": param_stats = get_param_stats(node_oup) # add tensor size attr if log_path: attr["size"] = AttrValue( s=sizeof_fmt(param_stats["size"]).encode(encoding="utf-8") ) param_stats["name"] = node.name params_list.append(param_stats) if log_path: node_list.append( NodeDef( name=process_name(node.name), op=node.type, input=inp_list, attr=attr, ) ) # summary extra_info = { "#ops": len(graph.all_oprs), "#params": len(params_list), } ( total_flops, total_param_dims, total_param_size, total_act_dims, total_act_size, ) = (0, 0, 0, 0, 0) if cal_params: total_param_dims, total_param_size, params_list = sum_param_stats( params_list, bar_length_max ) extra_info["total_param_dims"] = sizeof_fmt(total_param_dims, suffix="") extra_info["total_param_size"] = sizeof_fmt(total_param_size) if logging_to_stdout: print_param_stats(params_list) if cal_flops: total_flops, flops_list = sum_op_stats(flops_list, bar_length_max) extra_info["total_flops"] = sizeof_fmt(total_flops, suffix="OPs") if logging_to_stdout: print_op_stats(flops_list) if cal_activations: total_act_dims, total_act_size, activations_list = sum_activations_stats( activations_list, bar_length_max ) extra_info["total_act_dims"] = sizeof_fmt(total_act_dims, suffix="") extra_info["total_act_size"] = sizeof_fmt(total_act_size) if logging_to_stdout: print_activations_stats(activations_list, has_input=has_input) if cal_flops and cal_params: extra_info["flops/param_size"] = "{:3.3f}".format( total_flops / total_param_size ) if log_path: graph_def = GraphDef(node=node_list, versions=VersionDef(producer=22)) device = "/device:CPU:0" stepstats = RunMetadata( step_stats=StepStats(dev_stats=[DeviceStepStats(device=device)]) ) writer = SummaryWriter(log_path) writer._get_file_writer().add_graph((graph_def, stepstats)) print_summary(**extra_info) return ( total_stats( param_size=total_param_size, param_dims=total_param_dims, flops=total_flops, act_size=total_act_size, act_dims=total_act_dims, ), stats_details( params=params_list, flops=flops_list, activations=activations_list ), ) def main(): parser = argparse.ArgumentParser( description="load a megengine dumped model and export log file for tensorboard visualization.", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument("model_path", help="dumped model path.") parser.add_argument("--log_path", help="tensorboard log path.") parser.add_argument( "--load_input_data", help="load input data from pickle file; it should be a numpy array or a dict of numpy array", ) parser.add_argument( "--bar_length_max", type=int, default=20, help="size of bar indicating max flops or parameter size in net stats.", ) parser.add_argument( "--cal_params", action="store_true", help="whether calculate and record params size.", ) parser.add_argument( "--cal_flops", action="store_true", help="whether calculate and record op flops.", ) parser.add_argument( "--cal_activations", action="store_true", help="whether calculate and record op activations.", ) parser.add_argument( "--logging_to_stdout", action="store_true", help="whether print all calculated statistic details.", ) parser.add_argument( "--all", action="store_true", help="whether print all stats. Tensorboard logs will be placed in './log' if not specified.", ) args = parser.parse_args() if args.load_input_data: logger.info("load data from {}".format(args.load_input_data)) data = mge.load(args.load_input_data) if isinstance(data, dict): for v in data.values(): assert isinstance( v, np.ndarray ), "data should provide ndarray; got {} instead".format(v) args.inp_dict = data elif isinstance(data, np.ndarray): args.input = data else: logger.error("input data should be a numpy array or a dict of numpy array") if args.all: args.cal_params = True args.cal_flops = True args.cal_activations = True args.logging_to_stdout = True if not args.log_path: args.log_path = "./log" kwargs = vars(args) kwargs.pop("all") kwargs.pop("load_input_data") visualize(**kwargs) if __name__ == "__main__": main()
[ "megengine.utils.module_stats.sum_op_stats", "megengine.logger.get_logger", "megengine.utils.module_stats.print_param_stats", "megengine.utils.module_stats.sum_param_stats", "megengine.utils.module_stats.get_param_stats", "megengine.utils.module_stats.print_op_stats", "megengine.utils.network.Network.load", "megengine.utils.module_stats.get_op_stats", "megengine.utils.module_stats.sum_activations_stats", "megengine.utils.module_stats.sizeof_fmt", "megengine.utils.module_stats.get_activation_stats", "megengine.utils.module_stats.print_summary", "megengine.load", "megengine.utils.module_stats.print_activations_stats", "megengine.utils.module_stats.enable_receptive_field" ]
[((1019, 1039), 'megengine.logger.get_logger', 'get_logger', (['__name__'], {}), '(__name__)\n', (1029, 1039), False, 'from megengine.logger import _imperative_rt_logger, get_logger, set_mgb_log_level\n'), ((3458, 3482), 'megengine.utils.module_stats.enable_receptive_field', 'enable_receptive_field', ([], {}), '()\n', (3480, 3482), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((3496, 3520), 'megengine.utils.network.Network.load', 'Network.load', (['model_path'], {}), '(model_path)\n', (3508, 3520), False, 'from megengine.utils.network import Network\n'), ((4678, 4770), 'collections.namedtuple', 'namedtuple', (['"""total_stats"""', "['param_size', 'param_dims', 'flops', 'act_size', 'act_dims']"], {}), "('total_stats', ['param_size', 'param_dims', 'flops', 'act_size',\n 'act_dims'])\n", (4688, 4770), False, 'from collections import namedtuple\n'), ((4801, 4863), 'collections.namedtuple', 'namedtuple', (['"""module_stats"""', "['params', 'flops', 'activations']"], {}), "('module_stats', ['params', 'flops', 'activations'])\n", (4811, 4863), False, 'from collections import namedtuple\n'), ((4881, 4901), 'tqdm.tqdm', 'tqdm', (['graph.all_oprs'], {}), '(graph.all_oprs)\n', (4885, 4901), False, 'from tqdm import tqdm\n'), ((9338, 9365), 'megengine.utils.module_stats.print_summary', 'print_summary', ([], {}), '(**extra_info)\n', (9351, 9365), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((9745, 9930), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""load a megengine dumped model and export log file for tensorboard visualization."""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description=\n 'load a megengine dumped model and export log file for tensorboard visualization.'\n , formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n", (9768, 9930), False, 'import argparse\n'), ((7889, 7933), 'megengine.utils.module_stats.sum_param_stats', 'sum_param_stats', (['params_list', 'bar_length_max'], {}), '(params_list, bar_length_max)\n', (7904, 7933), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((7997, 8036), 'megengine.utils.module_stats.sizeof_fmt', 'sizeof_fmt', (['total_param_dims'], {'suffix': '""""""'}), "(total_param_dims, suffix='')\n", (8007, 8036), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((8078, 8106), 'megengine.utils.module_stats.sizeof_fmt', 'sizeof_fmt', (['total_param_size'], {}), '(total_param_size)\n', (8088, 8106), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((8233, 8273), 'megengine.utils.module_stats.sum_op_stats', 'sum_op_stats', (['flops_list', 'bar_length_max'], {}), '(flops_list, bar_length_max)\n', (8245, 8273), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((8310, 8347), 'megengine.utils.module_stats.sizeof_fmt', 'sizeof_fmt', (['total_flops'], {'suffix': '"""OPs"""'}), "(total_flops, suffix='OPs')\n", (8320, 8347), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((8501, 8556), 'megengine.utils.module_stats.sum_activations_stats', 'sum_activations_stats', (['activations_list', 'bar_length_max'], {}), '(activations_list, bar_length_max)\n', (8522, 8556), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((8618, 8655), 'megengine.utils.module_stats.sizeof_fmt', 'sizeof_fmt', (['total_act_dims'], {'suffix': '""""""'}), "(total_act_dims, suffix='')\n", (8628, 8655), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((8695, 8721), 'megengine.utils.module_stats.sizeof_fmt', 'sizeof_fmt', (['total_act_size'], {}), '(total_act_size)\n', (8705, 8721), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((9241, 9264), 'tensorboardX.SummaryWriter', 'SummaryWriter', (['log_path'], {}), '(log_path)\n', (9254, 9264), False, 'from tensorboardX import SummaryWriter\n'), ((11326, 11356), 'megengine.load', 'mge.load', (['args.load_input_data'], {}), '(args.load_input_data)\n', (11334, 11356), True, 'import megengine as mge\n'), ((4417, 4452), 're.match', 're.match', (['"""^[+-]?\\\\d*\\\\.\\\\d*"""', 'name'], {}), "('^[+-]?\\\\d*\\\\.\\\\d*', name)\n", (4425, 4452), False, 'import re\n'), ((6131, 6176), 'megengine.utils.module_stats.get_op_stats', 'get_op_stats', (['node', 'node.inputs', 'node.outputs'], {}), '(node, node.inputs, node.outputs)\n', (6143, 6176), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((6670, 6721), 'megengine.utils.module_stats.get_activation_stats', 'get_activation_stats', (['node_oup'], {'has_input': 'has_input'}), '(node_oup, has_input=has_input)\n', (6690, 6721), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((8149, 8179), 'megengine.utils.module_stats.print_param_stats', 'print_param_stats', (['params_list'], {}), '(params_list)\n', (8166, 8179), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((8390, 8416), 'megengine.utils.module_stats.print_op_stats', 'print_op_stats', (['flops_list'], {}), '(flops_list)\n', (8404, 8416), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((8764, 8826), 'megengine.utils.module_stats.print_activations_stats', 'print_activations_stats', (['activations_list'], {'has_input': 'has_input'}), '(activations_list, has_input=has_input)\n', (8787, 8826), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((6945, 6970), 'megengine.utils.module_stats.get_param_stats', 'get_param_stats', (['node_oup'], {}), '(node_oup)\n', (6960, 6970), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((9045, 9068), 'tensorboard.compat.proto.versions_pb2.VersionDef', 'VersionDef', ([], {'producer': '(22)'}), '(producer=22)\n', (9055, 9068), False, 'from tensorboard.compat.proto.versions_pb2 import VersionDef\n'), ((9181, 9211), 'tensorboard.compat.proto.step_stats_pb2.DeviceStepStats', 'DeviceStepStats', ([], {'device': 'device'}), '(device=device)\n', (9196, 9211), False, 'from tensorboard.compat.proto.step_stats_pb2 import AllocatorMemoryUsed, DeviceStepStats, NodeExecStats, StepStats\n'), ((6393, 6425), 'megengine.utils.module_stats.sizeof_fmt', 'sizeof_fmt', (["flops_stats['flops']"], {}), "(flops_stats['flops'])\n", (6403, 6425), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((7111, 7142), 'megengine.utils.module_stats.sizeof_fmt', 'sizeof_fmt', (["param_stats['size']"], {}), "(param_stats['size'])\n", (7121, 7142), False, 'from megengine.utils.module_stats import enable_receptive_field, get_activation_stats, get_op_stats, get_param_stats, print_activations_stats, print_op_stats, print_param_stats, print_summary, sizeof_fmt, sum_activations_stats, sum_op_stats, sum_param_stats\n'), ((5718, 5746), 'tensorboard.compat.proto.tensor_shape_pb2.TensorShapeProto.Dim', 'TensorShapeProto.Dim', ([], {'size': 'd'}), '(size=d)\n', (5738, 5746), False, 'from tensorboard.compat.proto.tensor_shape_pb2 import TensorShapeProto\n')]
# Copyright (c) 2020 <NAME> # This code is licensed under MIT license # (https://github.com/kwotsin/mimicry/blob/master/LICENSE) # ------------------------------------------------------------------------------ # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2020 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # This file has been modified by Megvii ("Megvii Modifications"). # All Megvii Modifications are Copyright (C) 2014-2019 Megvii Inc. All rights reserved. # ------------------------------------------------------------------------------ import megengine.functional as F from megengine.core.tensor_factory import zeros def ns_loss_gen(output_fake): r""" Non-saturating loss for generator. Args: output_fake (Tensor): Discriminator output logits for fake images. Returns: Tensor: A scalar tensor loss output. """ output_fake = F.sigmoid(output_fake) return -F.log(output_fake + 1e-8).mean() # def ns_loss_gen(output_fake): # """numerical stable version""" # return F.log(1 + F.exp(-output_fake)).mean() def _bce_loss_with_logits(output, labels, **kwargs): r""" Sigmoid cross entropy with logits, see tensorflow https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_cross_entropy_with_logits """ loss = F.maximum(output, 0) - output * labels + F.log(1 + F.exp(-F.abs(output))) return loss.mean() def minimax_loss_dis(output_fake, output_real, real_label_val=1.0, fake_label_val=0.0, **kwargs): r""" Standard minimax loss for GANs through the BCE Loss with logits fn. Args: output_fake (Tensor): Discriminator output logits for fake images. output_real (Tensor): Discriminator output logits for real images. real_label_val (int): Label for real images. fake_label_val (int): Label for fake images. device (torch.device): Torch device object for sending created data. Returns: Tensor: A scalar tensor loss output. """ # Produce real and fake labels. fake_labels = zeros((output_fake.shape[0], 1)) + fake_label_val real_labels = zeros((output_real.shape[0], 1)) + real_label_val # FF, compute loss and backprop D errD_fake = _bce_loss_with_logits(output=output_fake, labels=fake_labels, **kwargs) errD_real = _bce_loss_with_logits(output=output_real, labels=real_labels, **kwargs) # Compute cumulative error loss = errD_real + errD_fake return loss def wasserstein_loss_gen(output_fake): r""" Computes the wasserstein loss for generator. Args: output_fake (Tensor): Discriminator output logits for fake images. Returns: Tensor: A scalar tensor loss output. """ loss = -output_fake.mean() return loss def wasserstein_loss_dis(output_real, output_fake): r""" Computes the wasserstein loss for the discriminator. Args: output_real (Tensor): Discriminator output logits for real images. output_fake (Tensor): Discriminator output logits for fake images. Returns: Tensor: A scalar tensor loss output. """ loss = -1.0 * output_real.mean() + output_fake.mean() return loss
[ "megengine.functional.maximum", "megengine.functional.sigmoid", "megengine.core.tensor_factory.zeros", "megengine.functional.log", "megengine.functional.abs" ]
[((1132, 1154), 'megengine.functional.sigmoid', 'F.sigmoid', (['output_fake'], {}), '(output_fake)\n', (1141, 1154), True, 'import megengine.functional as F\n'), ((2374, 2406), 'megengine.core.tensor_factory.zeros', 'zeros', (['(output_fake.shape[0], 1)'], {}), '((output_fake.shape[0], 1))\n', (2379, 2406), False, 'from megengine.core.tensor_factory import zeros\n'), ((2442, 2474), 'megengine.core.tensor_factory.zeros', 'zeros', (['(output_real.shape[0], 1)'], {}), '((output_real.shape[0], 1))\n', (2447, 2474), False, 'from megengine.core.tensor_factory import zeros\n'), ((1547, 1567), 'megengine.functional.maximum', 'F.maximum', (['output', '(0)'], {}), '(output, 0)\n', (1556, 1567), True, 'import megengine.functional as F\n'), ((1168, 1194), 'megengine.functional.log', 'F.log', (['(output_fake + 1e-08)'], {}), '(output_fake + 1e-08)\n', (1173, 1194), True, 'import megengine.functional as F\n'), ((1605, 1618), 'megengine.functional.abs', 'F.abs', (['output'], {}), '(output)\n', (1610, 1618), True, 'import megengine.functional as F\n')]
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2020 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import numpy as np import pytest from helpers import MLP import megengine._internal as mgb import megengine.functional as F from megengine.core import Graph from megengine.module import Linear, Module from megengine.optimizer import SGD from megengine.test import assertTensorClose def test_compile_multi_times_eager(): return # XXX: rewrite or remove this test data = Input("data", shape=(2, 28)) label = Input("label", shape=(2,), dtype=np.int32) mlp = MLP() opt = SGD(mlp.parameters(requires_grad=True), lr=0.01) pred0 = mlp(data) pred = F.softmax(pred0) loss = F.square_loss(pred, label.reshape(2, 1)) opt.zero_grad() grads = opt.backward(loss) opt.step() f0 = compile(pred, None) f1 = compile([pred, loss], grads, copy=False) for _ in range(3): data = np.random.random((2, 28)).astype(np.float32) label = np.random.randint(0, 10, (2,)).astype(np.float32) out0 = f0(data=data) out1 = f1(data=data, label=label) assertTensorClose(out0[0], out1[0]) def test_compile_multi_times_static(): return # XXX: rewrite or remove this test with Graph() as cg: cg.set_option("eager_evaluation", False) data = Input("data", shape=(2, 28)) label = Input("label", shape=(2,), dtype=np.int32) mlp = MLP() opt = SGD(mlp.parameters(requires_grad=True), lr=0.01) pred0 = mlp(data) pred = F.softmax(pred0) loss = F.square_loss(pred, label.reshape(2, 1)) opt.zero_grad() grads = opt.backward(loss) opt.step() f0 = compile(pred, None) f1 = compile([pred, loss], grads, copy=True) data = np.random.random((2, 28)).astype(np.float32) label = np.random.randint(0, 10, (2,)).astype(np.float32) out0 = f0(data=data) out1 = f1(data=data, label=label) assertTensorClose(out0[0], out1[0]) _ = compile([pred, loss], grads, copy=False) with pytest.raises(mgb.MegBrainError): f0(data=data)
[ "megengine.test.assertTensorClose", "megengine.core.Graph", "megengine.functional.softmax" ]
[((853, 858), 'helpers.MLP', 'MLP', ([], {}), '()\n', (856, 858), False, 'from helpers import MLP\n'), ((952, 968), 'megengine.functional.softmax', 'F.softmax', (['pred0'], {}), '(pred0)\n', (961, 968), True, 'import megengine.functional as F\n'), ((1395, 1430), 'megengine.test.assertTensorClose', 'assertTensorClose', (['out0[0]', 'out1[0]'], {}), '(out0[0], out1[0])\n', (1412, 1430), False, 'from megengine.test import assertTensorClose\n'), ((1528, 1535), 'megengine.core.Graph', 'Graph', ([], {}), '()\n', (1533, 1535), False, 'from megengine.core import Graph\n'), ((1710, 1715), 'helpers.MLP', 'MLP', ([], {}), '()\n', (1713, 1715), False, 'from helpers import MLP\n'), ((1821, 1837), 'megengine.functional.softmax', 'F.softmax', (['pred0'], {}), '(pred0)\n', (1830, 1837), True, 'import megengine.functional as F\n'), ((2265, 2300), 'megengine.test.assertTensorClose', 'assertTensorClose', (['out0[0]', 'out1[0]'], {}), '(out0[0], out1[0])\n', (2282, 2300), False, 'from megengine.test import assertTensorClose\n'), ((2368, 2400), 'pytest.raises', 'pytest.raises', (['mgb.MegBrainError'], {}), '(mgb.MegBrainError)\n', (2381, 2400), False, 'import pytest\n'), ((1205, 1230), 'numpy.random.random', 'np.random.random', (['(2, 28)'], {}), '((2, 28))\n', (1221, 1230), True, 'import numpy as np\n'), ((1266, 1296), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10)', '(2,)'], {}), '(0, 10, (2,))\n', (1283, 1296), True, 'import numpy as np\n'), ((2075, 2100), 'numpy.random.random', 'np.random.random', (['(2, 28)'], {}), '((2, 28))\n', (2091, 2100), True, 'import numpy as np\n'), ((2136, 2166), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10)', '(2,)'], {}), '(0, 10, (2,))\n', (2153, 2166), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2020 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import os import time import numpy as np import pytest from megengine.data.collator import Collator from megengine.data.dataloader import DataLoader from megengine.data.dataset import ArrayDataset from megengine.data.sampler import RandomSampler, SequentialSampler from megengine.data.transform import PseudoTransform, Transform def init_dataset(): sample_num = 100 rand_data = np.random.randint(0, 255, size=(sample_num, 1, 32, 32), dtype=np.uint8) label = np.random.randint(0, 10, size=(sample_num,), dtype=int) dataset = ArrayDataset(rand_data, label) return dataset def test_dataloader_init(): dataset = init_dataset() with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=2, divide=True) with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=-1) with pytest.raises(ValueError): dataloader = DataLoader(dataset, timeout=-1) with pytest.raises(ValueError): dataloader = DataLoader(dataset, num_workers=0, divide=True) dataloader = DataLoader(dataset) assert isinstance(dataloader.sampler, SequentialSampler) assert isinstance(dataloader.transform, PseudoTransform) assert isinstance(dataloader.collator, Collator) dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=6, drop_last=False) ) assert len(dataloader) == 17 dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=6, drop_last=True) ) assert len(dataloader) == 16 def test_dataloader_serial(): dataset = init_dataset() dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False) ) for (data, label) in dataloader: assert data.shape == (4, 1, 32, 32) assert label.shape == (4,) def test_dataloader_parallel(): # set max shared memory to 100M os.environ["MGE_PLASMA_MEMORY"] = "100000000" dataset = init_dataset() dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), num_workers=2, divide=False, ) for (data, label) in dataloader: assert data.shape == (4, 1, 32, 32) assert label.shape == (4,) dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), num_workers=2, divide=True, ) for (data, label) in dataloader: assert data.shape == (4, 1, 32, 32) assert label.shape == (4,) def test_dataloader_parallel_timeout(): dataset = init_dataset() class TimeoutTransform(Transform): def __init__(self): pass def apply(self, input): time.sleep(10) return input dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), transform=TimeoutTransform(), num_workers=2, timeout=2, ) with pytest.raises(RuntimeError, match=r".*timeout.*"): data_iter = iter(dataloader) batch_data = next(data_iter) def test_dataloader_parallel_worker_exception(): dataset = init_dataset() class FakeErrorTransform(Transform): def __init__(self): pass def apply(self, input): y = x + 1 return input dataloader = DataLoader( dataset, sampler=RandomSampler(dataset, batch_size=4, drop_last=False), transform=FakeErrorTransform(), num_workers=2, ) with pytest.raises(RuntimeError, match=r"worker.*died"): data_iter = iter(dataloader) batch_data = next(data_iter)
[ "megengine.data.sampler.RandomSampler", "megengine.data.dataloader.DataLoader", "megengine.data.dataset.ArrayDataset" ]
[((767, 838), 'numpy.random.randint', 'np.random.randint', (['(0)', '(255)'], {'size': '(sample_num, 1, 32, 32)', 'dtype': 'np.uint8'}), '(0, 255, size=(sample_num, 1, 32, 32), dtype=np.uint8)\n', (784, 838), True, 'import numpy as np\n'), ((851, 906), 'numpy.random.randint', 'np.random.randint', (['(0)', '(10)'], {'size': '(sample_num,)', 'dtype': 'int'}), '(0, 10, size=(sample_num,), dtype=int)\n', (868, 906), True, 'import numpy as np\n'), ((921, 951), 'megengine.data.dataset.ArrayDataset', 'ArrayDataset', (['rand_data', 'label'], {}), '(rand_data, label)\n', (933, 951), False, 'from megengine.data.dataset import ArrayDataset\n'), ((1440, 1459), 'megengine.data.dataloader.DataLoader', 'DataLoader', (['dataset'], {}), '(dataset)\n', (1450, 1459), False, 'from megengine.data.dataloader import DataLoader\n'), ((1039, 1064), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1052, 1064), False, 'import pytest\n'), ((1087, 1134), 'megengine.data.dataloader.DataLoader', 'DataLoader', (['dataset'], {'num_workers': '(2)', 'divide': '(True)'}), '(dataset, num_workers=2, divide=True)\n', (1097, 1134), False, 'from megengine.data.dataloader import DataLoader\n'), ((1144, 1169), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1157, 1169), False, 'import pytest\n'), ((1192, 1227), 'megengine.data.dataloader.DataLoader', 'DataLoader', (['dataset'], {'num_workers': '(-1)'}), '(dataset, num_workers=-1)\n', (1202, 1227), False, 'from megengine.data.dataloader import DataLoader\n'), ((1237, 1262), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1250, 1262), False, 'import pytest\n'), ((1285, 1316), 'megengine.data.dataloader.DataLoader', 'DataLoader', (['dataset'], {'timeout': '(-1)'}), '(dataset, timeout=-1)\n', (1295, 1316), False, 'from megengine.data.dataloader import DataLoader\n'), ((1326, 1351), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (1339, 1351), False, 'import pytest\n'), ((1374, 1421), 'megengine.data.dataloader.DataLoader', 'DataLoader', (['dataset'], {'num_workers': '(0)', 'divide': '(True)'}), '(dataset, num_workers=0, divide=True)\n', (1384, 1421), False, 'from megengine.data.dataloader import DataLoader\n'), ((3392, 3440), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {'match': '""".*timeout.*"""'}), "(RuntimeError, match='.*timeout.*')\n", (3405, 3440), False, 'import pytest\n'), ((3960, 4009), 'pytest.raises', 'pytest.raises', (['RuntimeError'], {'match': '"""worker.*died"""'}), "(RuntimeError, match='worker.*died')\n", (3973, 4009), False, 'import pytest\n'), ((1690, 1743), 'megengine.data.sampler.RandomSampler', 'RandomSampler', (['dataset'], {'batch_size': '(6)', 'drop_last': '(False)'}), '(dataset, batch_size=6, drop_last=False)\n', (1703, 1743), False, 'from megengine.data.sampler import RandomSampler, SequentialSampler\n'), ((1837, 1889), 'megengine.data.sampler.RandomSampler', 'RandomSampler', (['dataset'], {'batch_size': '(6)', 'drop_last': '(True)'}), '(dataset, batch_size=6, drop_last=True)\n', (1850, 1889), False, 'from megengine.data.sampler import RandomSampler, SequentialSampler\n'), ((2044, 2097), 'megengine.data.sampler.RandomSampler', 'RandomSampler', (['dataset'], {'batch_size': '(4)', 'drop_last': '(False)'}), '(dataset, batch_size=4, drop_last=False)\n', (2057, 2097), False, 'from megengine.data.sampler import RandomSampler, SequentialSampler\n'), ((2432, 2485), 'megengine.data.sampler.RandomSampler', 'RandomSampler', (['dataset'], {'batch_size': '(4)', 'drop_last': '(False)'}), '(dataset, batch_size=4, drop_last=False)\n', (2445, 2485), False, 'from megengine.data.sampler import RandomSampler, SequentialSampler\n'), ((2717, 2770), 'megengine.data.sampler.RandomSampler', 'RandomSampler', (['dataset'], {'batch_size': '(4)', 'drop_last': '(False)'}), '(dataset, batch_size=4, drop_last=False)\n', (2730, 2770), False, 'from megengine.data.sampler import RandomSampler, SequentialSampler\n'), ((3139, 3153), 'time.sleep', 'time.sleep', (['(10)'], {}), '(10)\n', (3149, 3153), False, 'import time\n'), ((3242, 3295), 'megengine.data.sampler.RandomSampler', 'RandomSampler', (['dataset'], {'batch_size': '(4)', 'drop_last': '(False)'}), '(dataset, batch_size=4, drop_last=False)\n', (3255, 3295), False, 'from megengine.data.sampler import RandomSampler, SequentialSampler\n'), ((3827, 3880), 'megengine.data.sampler.RandomSampler', 'RandomSampler', (['dataset'], {'batch_size': '(4)', 'drop_last': '(False)'}), '(dataset, batch_size=4, drop_last=False)\n', (3840, 3880), False, 'from megengine.data.sampler import RandomSampler, SequentialSampler\n')]
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import os import platform import sys import pytest from megengine.core import _config as config from megengine.core import _trace_option as trace_option from megengine.core import get_option from megengine.core._imperative_rt.core2 import ( _get_amp_dtype_autocast, _get_amp_high_prec_dtype, _get_amp_low_prec_dtype, _get_convert_inputs, ) from megengine.core.tensor import amp from megengine.device import get_device_count sys.path.append(os.path.join(os.path.dirname(__file__), "helpers")) _ngpu = get_device_count("gpu") @pytest.fixture(autouse=True) def skip_by_ngpu(request): if request.node.get_closest_marker("require_ngpu"): require_ngpu = int(request.node.get_closest_marker("require_ngpu").args[0]) if require_ngpu > _ngpu: pytest.skip("skipped for ngpu unsatisfied: {}".format(require_ngpu)) @pytest.fixture(autouse=True) def skip_distributed(request): if request.node.get_closest_marker("distributed_isolated"): if platform.system() in ("Windows", "Darwin"): pytest.skip( "skipped for distributed unsupported at platform: {}".format( platform.system() ) ) @pytest.fixture(autouse=True) def run_around_tests(): env_vars1 = { "symbolic_shape": trace_option.use_symbolic_shape(), "async_level": get_option("async_level"), "enable_drop": get_option("enable_drop"), "max_recompute_time": get_option("max_recompute_time"), "catch_worker_execption": get_option("catch_worker_execption"), "enable_host_compute": get_option("enable_host_compute"), # "record_computing_path": get_option("record_computing_path"), "disable_memory_forwarding": get_option("disable_memory_forwarding"), "enable_dtr_auto_drop": get_option("enable_dtr_auto_drop"), "enable_dtr_sqrt_sampling": get_option("enable_dtr_sqrt_sampling"), "dtr_eviction_threshold": get_option("dtr_eviction_threshold"), "dtr_evictee_minimum_size": get_option("dtr_evictee_minimum_size"), "benchmark_kernel": config.benchmark_kernel, "deterministic_kernel": config.deterministic_kernel, "compute_mode": config._compute_mode, "conv_format": config._conv_format, "amp_enabled": amp.enabled, "convert_inputs": _get_convert_inputs(), "amp_dtype_autocast": _get_amp_dtype_autocast(), "amp_high_prec_dtype": _get_amp_high_prec_dtype(), "amp_low_prec_dtype": _get_amp_low_prec_dtype(), } yield env_vars2 = { "symbolic_shape": trace_option.use_symbolic_shape(), "async_level": get_option("async_level"), "enable_drop": get_option("enable_drop"), "max_recompute_time": get_option("max_recompute_time"), "catch_worker_execption": get_option("catch_worker_execption"), "enable_host_compute": get_option("enable_host_compute"), # "record_computing_path": get_option("record_computing_path"), "disable_memory_forwarding": get_option("disable_memory_forwarding"), "enable_dtr_auto_drop": get_option("enable_dtr_auto_drop"), "enable_dtr_sqrt_sampling": get_option("enable_dtr_sqrt_sampling"), "dtr_eviction_threshold": get_option("dtr_eviction_threshold"), "dtr_evictee_minimum_size": get_option("dtr_evictee_minimum_size"), "benchmark_kernel": config.benchmark_kernel, "deterministic_kernel": config.deterministic_kernel, "compute_mode": config._compute_mode, "conv_format": config._conv_format, "amp_enabled": amp.enabled, "convert_inputs": _get_convert_inputs(), "amp_dtype_autocast": _get_amp_dtype_autocast(), "amp_high_prec_dtype": _get_amp_high_prec_dtype(), "amp_low_prec_dtype": _get_amp_low_prec_dtype(), } for key in env_vars1: assert ( env_vars1[key] == env_vars2[key] ), "{} have been changed after test".format(key)
[ "megengine.core._imperative_rt.core2._get_amp_low_prec_dtype", "megengine.core._imperative_rt.core2._get_amp_high_prec_dtype", "megengine.device.get_device_count", "megengine.core._trace_option.use_symbolic_shape", "megengine.core._imperative_rt.core2._get_amp_dtype_autocast", "megengine.core.get_option", "megengine.core._imperative_rt.core2._get_convert_inputs" ]
[((873, 896), 'megengine.device.get_device_count', 'get_device_count', (['"""gpu"""'], {}), "('gpu')\n", (889, 896), False, 'from megengine.device import get_device_count\n'), ((900, 928), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (914, 928), False, 'import pytest\n'), ((1213, 1241), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (1227, 1241), False, 'import pytest\n'), ((1568, 1596), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)'}), '(autouse=True)\n', (1582, 1596), False, 'import pytest\n'), ((825, 850), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (840, 850), False, 'import os\n'), ((1665, 1698), 'megengine.core._trace_option.use_symbolic_shape', 'trace_option.use_symbolic_shape', ([], {}), '()\n', (1696, 1698), True, 'from megengine.core import _trace_option as trace_option\n'), ((1723, 1748), 'megengine.core.get_option', 'get_option', (['"""async_level"""'], {}), "('async_level')\n", (1733, 1748), False, 'from megengine.core import get_option\n'), ((1773, 1798), 'megengine.core.get_option', 'get_option', (['"""enable_drop"""'], {}), "('enable_drop')\n", (1783, 1798), False, 'from megengine.core import get_option\n'), ((1830, 1862), 'megengine.core.get_option', 'get_option', (['"""max_recompute_time"""'], {}), "('max_recompute_time')\n", (1840, 1862), False, 'from megengine.core import get_option\n'), ((1898, 1934), 'megengine.core.get_option', 'get_option', (['"""catch_worker_execption"""'], {}), "('catch_worker_execption')\n", (1908, 1934), False, 'from megengine.core import get_option\n'), ((1967, 2000), 'megengine.core.get_option', 'get_option', (['"""enable_host_compute"""'], {}), "('enable_host_compute')\n", (1977, 2000), False, 'from megengine.core import get_option\n'), ((2111, 2150), 'megengine.core.get_option', 'get_option', (['"""disable_memory_forwarding"""'], {}), "('disable_memory_forwarding')\n", (2121, 2150), False, 'from megengine.core import get_option\n'), ((2184, 2218), 'megengine.core.get_option', 'get_option', (['"""enable_dtr_auto_drop"""'], {}), "('enable_dtr_auto_drop')\n", (2194, 2218), False, 'from megengine.core import get_option\n'), ((2256, 2294), 'megengine.core.get_option', 'get_option', (['"""enable_dtr_sqrt_sampling"""'], {}), "('enable_dtr_sqrt_sampling')\n", (2266, 2294), False, 'from megengine.core import get_option\n'), ((2330, 2366), 'megengine.core.get_option', 'get_option', (['"""dtr_eviction_threshold"""'], {}), "('dtr_eviction_threshold')\n", (2340, 2366), False, 'from megengine.core import get_option\n'), ((2404, 2442), 'megengine.core.get_option', 'get_option', (['"""dtr_evictee_minimum_size"""'], {}), "('dtr_evictee_minimum_size')\n", (2414, 2442), False, 'from megengine.core import get_option\n'), ((2710, 2731), 'megengine.core._imperative_rt.core2._get_convert_inputs', '_get_convert_inputs', ([], {}), '()\n', (2729, 2731), False, 'from megengine.core._imperative_rt.core2 import _get_amp_dtype_autocast, _get_amp_high_prec_dtype, _get_amp_low_prec_dtype, _get_convert_inputs\n'), ((2763, 2788), 'megengine.core._imperative_rt.core2._get_amp_dtype_autocast', '_get_amp_dtype_autocast', ([], {}), '()\n', (2786, 2788), False, 'from megengine.core._imperative_rt.core2 import _get_amp_dtype_autocast, _get_amp_high_prec_dtype, _get_amp_low_prec_dtype, _get_convert_inputs\n'), ((2821, 2847), 'megengine.core._imperative_rt.core2._get_amp_high_prec_dtype', '_get_amp_high_prec_dtype', ([], {}), '()\n', (2845, 2847), False, 'from megengine.core._imperative_rt.core2 import _get_amp_dtype_autocast, _get_amp_high_prec_dtype, _get_amp_low_prec_dtype, _get_convert_inputs\n'), ((2879, 2904), 'megengine.core._imperative_rt.core2._get_amp_low_prec_dtype', '_get_amp_low_prec_dtype', ([], {}), '()\n', (2902, 2904), False, 'from megengine.core._imperative_rt.core2 import _get_amp_dtype_autocast, _get_amp_high_prec_dtype, _get_amp_low_prec_dtype, _get_convert_inputs\n'), ((2966, 2999), 'megengine.core._trace_option.use_symbolic_shape', 'trace_option.use_symbolic_shape', ([], {}), '()\n', (2997, 2999), True, 'from megengine.core import _trace_option as trace_option\n'), ((3024, 3049), 'megengine.core.get_option', 'get_option', (['"""async_level"""'], {}), "('async_level')\n", (3034, 3049), False, 'from megengine.core import get_option\n'), ((3074, 3099), 'megengine.core.get_option', 'get_option', (['"""enable_drop"""'], {}), "('enable_drop')\n", (3084, 3099), False, 'from megengine.core import get_option\n'), ((3131, 3163), 'megengine.core.get_option', 'get_option', (['"""max_recompute_time"""'], {}), "('max_recompute_time')\n", (3141, 3163), False, 'from megengine.core import get_option\n'), ((3199, 3235), 'megengine.core.get_option', 'get_option', (['"""catch_worker_execption"""'], {}), "('catch_worker_execption')\n", (3209, 3235), False, 'from megengine.core import get_option\n'), ((3268, 3301), 'megengine.core.get_option', 'get_option', (['"""enable_host_compute"""'], {}), "('enable_host_compute')\n", (3278, 3301), False, 'from megengine.core import get_option\n'), ((3412, 3451), 'megengine.core.get_option', 'get_option', (['"""disable_memory_forwarding"""'], {}), "('disable_memory_forwarding')\n", (3422, 3451), False, 'from megengine.core import get_option\n'), ((3485, 3519), 'megengine.core.get_option', 'get_option', (['"""enable_dtr_auto_drop"""'], {}), "('enable_dtr_auto_drop')\n", (3495, 3519), False, 'from megengine.core import get_option\n'), ((3557, 3595), 'megengine.core.get_option', 'get_option', (['"""enable_dtr_sqrt_sampling"""'], {}), "('enable_dtr_sqrt_sampling')\n", (3567, 3595), False, 'from megengine.core import get_option\n'), ((3631, 3667), 'megengine.core.get_option', 'get_option', (['"""dtr_eviction_threshold"""'], {}), "('dtr_eviction_threshold')\n", (3641, 3667), False, 'from megengine.core import get_option\n'), ((3705, 3743), 'megengine.core.get_option', 'get_option', (['"""dtr_evictee_minimum_size"""'], {}), "('dtr_evictee_minimum_size')\n", (3715, 3743), False, 'from megengine.core import get_option\n'), ((4011, 4032), 'megengine.core._imperative_rt.core2._get_convert_inputs', '_get_convert_inputs', ([], {}), '()\n', (4030, 4032), False, 'from megengine.core._imperative_rt.core2 import _get_amp_dtype_autocast, _get_amp_high_prec_dtype, _get_amp_low_prec_dtype, _get_convert_inputs\n'), ((4064, 4089), 'megengine.core._imperative_rt.core2._get_amp_dtype_autocast', '_get_amp_dtype_autocast', ([], {}), '()\n', (4087, 4089), False, 'from megengine.core._imperative_rt.core2 import _get_amp_dtype_autocast, _get_amp_high_prec_dtype, _get_amp_low_prec_dtype, _get_convert_inputs\n'), ((4122, 4148), 'megengine.core._imperative_rt.core2._get_amp_high_prec_dtype', '_get_amp_high_prec_dtype', ([], {}), '()\n', (4146, 4148), False, 'from megengine.core._imperative_rt.core2 import _get_amp_dtype_autocast, _get_amp_high_prec_dtype, _get_amp_low_prec_dtype, _get_convert_inputs\n'), ((4180, 4205), 'megengine.core._imperative_rt.core2._get_amp_low_prec_dtype', '_get_amp_low_prec_dtype', ([], {}), '()\n', (4203, 4205), False, 'from megengine.core._imperative_rt.core2 import _get_amp_dtype_autocast, _get_amp_high_prec_dtype, _get_amp_low_prec_dtype, _get_convert_inputs\n'), ((1348, 1365), 'platform.system', 'platform.system', ([], {}), '()\n', (1363, 1365), False, 'import platform\n'), ((1515, 1532), 'platform.system', 'platform.system', ([], {}), '()\n', (1530, 1532), False, 'import platform\n')]
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import os import platform import re import subprocess import sys from math import ceil import numpy as np import pytest import megengine as mge import megengine.autodiff as ad import megengine.distributed as dist import megengine.functional as F from megengine.device import get_default_device, set_default_device from megengine.functional.debug_param import set_conv_execution_strategy from megengine.module import AvgPool2d, BatchNorm2d, Conv2d, Linear, Module from megengine.optimizer import SGD from megengine.tensor import Tensor p_num = 4 def get_gpu_name(): try: gpu_info = subprocess.check_output( ["nvidia-smi", "--query-gpu=gpu_name", "--format=csv,noheader"] ) gpu_info = gpu_info.decode("ascii").split("\n")[0] except: gpu_info = "None" return gpu_info def get_cpu_name(): cpu_info = "None" try: cpu_info = subprocess.check_output(["cat", "/proc/cpuinfo"]).decode("ascii") for line in cpu_info.split("\n"): if "model name" in line: return re.sub(".*model name.*:", "", line, 1).strip() except: pass return cpu_info def get_xpu_name(): if mge.is_cuda_available(): return get_gpu_name() else: return get_cpu_name() class MnistNet(Module): def __init__(self, has_bn=True): super().__init__() self.conv0 = Conv2d(1, 20, kernel_size=5, bias=True) self.pool0 = AvgPool2d(2) self.conv1 = Conv2d(20, 20, kernel_size=5, bias=True) self.pool1 = AvgPool2d(2) self.fc0 = Linear(20 * 4 * 4, 500, bias=True) self.fc1 = Linear(500, 10, bias=True) self.bn0 = None self.bn1 = None if has_bn: self.bn0 = BatchNorm2d(20) self.bn1 = BatchNorm2d(20) def forward(self, x): x = self.conv0(x) if self.bn0: x = self.bn0(x) x = F.relu(x) x = self.pool0(x) x = self.conv1(x) if self.bn1: x = self.bn1(x) x = F.relu(x) x = self.pool1(x) x = F.flatten(x, 1) x = self.fc0(x) x = F.relu(x) x = self.fc1(x) return x def train(data, label, net, opt, gm): opt.clear_grad() with gm: pred = net(data) loss = F.nn.cross_entropy(pred, label) gm.backward(loss) opt.step() return loss def update_model(model_path): """ Update the dumped model with test cases for new reference values. The model with pre-trained weights is trained for one iter with the test data attached. The loss and updated net state dict is dumped. .. code-block:: python from test_dp_correctness import update_model update_model('mnist_model_with_test.mge') # for gpu update_model('mnist_model_with_test_cpu.mge') # for cpu """ net = MnistNet(has_bn=True) checkpoint = mge.load(model_path) net.load_state_dict(checkpoint["net_init"]) lr = checkpoint["sgd_lr"] opt = SGD(net.parameters(), lr=lr) gm = ad.GradManager().attach( net.parameters(), callbacks=[dist.make_allreduce_cb("MEAN", dist.WORLD)] ) data = Tensor(checkpoint["data"], dtype=np.float32) label = Tensor(checkpoint["label"], dtype=np.int32) opt.clear_grad() loss = train(data, label, net=net, opt=opt) opt.step() xpu_name = get_xpu_name() checkpoint.update( {"net_updated": net.state_dict(), "loss": loss.numpy(), "xpu": xpu_name} ) mge.serialization.save(checkpoint, model_path) def run_test( model_path, use_jit, use_symbolic, sublinear_memory_config=None, max_err=None, ): """ Load the model with test cases and run the training for one iter. The loss and updated weights are compared with reference value to verify the correctness. Dump a new file with updated result by calling update_model if you think the test fails due to numerical rounding errors instead of bugs. Please think twice before you do so. """ checkpoint = mge.load(model_path) data = checkpoint["data"] label = checkpoint["label"] @dist.launcher def worker(max_err): net = MnistNet(has_bn=True) net.load_state_dict(checkpoint["net_init"]) lr = checkpoint["sgd_lr"] opt = SGD(net.parameters(), lr=lr) gm = ad.GradManager().attach( net.parameters(), callbacks=[dist.make_allreduce_cb("MEAN", dist.WORLD)] ) # use same data and label for all gpu's # such that the result does not depend on number of gpu data_train = Tensor(data) label_train = Tensor(label) loss = train(data_train, label_train, net, opt, gm) np.testing.assert_allclose(loss.numpy(), checkpoint["loss"], atol=max_err) if dist.get_rank(): return for param, param_ref in zip( net.state_dict().items(), checkpoint["net_updated"].items() ): assert param[0] == param_ref[0] if "bn" in param[0]: ref = param_ref[1].reshape(param[1].shape) np.testing.assert_allclose(param[1], ref, atol=max_err) else: np.testing.assert_allclose(param[1], param_ref[1], atol=max_err) worker(max_err) @pytest.mark.require_ngpu(2) @pytest.mark.isolated_distributed def test_dp_correctness(): model_name = "mnist_model_with_test.mge" model_path = os.path.join(os.path.dirname(__file__), model_name) set_conv_execution_strategy("HEURISTIC_REPRODUCIBLE") run_test(model_path, False, False, max_err=1e-5)
[ "megengine.autodiff.GradManager", "megengine.module.Conv2d", "megengine.module.AvgPool2d", "megengine.functional.nn.cross_entropy", "megengine.functional.debug_param.set_conv_execution_strategy", "megengine.distributed.make_allreduce_cb", "megengine.serialization.save", "megengine.is_cuda_available", "megengine.module.BatchNorm2d", "megengine.load", "megengine.functional.relu", "megengine.functional.flatten", "megengine.distributed.get_rank", "megengine.tensor.Tensor", "megengine.module.Linear" ]
[((5688, 5715), 'pytest.mark.require_ngpu', 'pytest.mark.require_ngpu', (['(2)'], {}), '(2)\n', (5712, 5715), False, 'import pytest\n'), ((1564, 1587), 'megengine.is_cuda_available', 'mge.is_cuda_available', ([], {}), '()\n', (1585, 1587), True, 'import megengine as mge\n'), ((3294, 3314), 'megengine.load', 'mge.load', (['model_path'], {}), '(model_path)\n', (3302, 3314), True, 'import megengine as mge\n'), ((3566, 3610), 'megengine.tensor.Tensor', 'Tensor', (["checkpoint['data']"], {'dtype': 'np.float32'}), "(checkpoint['data'], dtype=np.float32)\n", (3572, 3610), False, 'from megengine.tensor import Tensor\n'), ((3623, 3666), 'megengine.tensor.Tensor', 'Tensor', (["checkpoint['label']"], {'dtype': 'np.int32'}), "(checkpoint['label'], dtype=np.int32)\n", (3629, 3666), False, 'from megengine.tensor import Tensor\n'), ((3898, 3944), 'megengine.serialization.save', 'mge.serialization.save', (['checkpoint', 'model_path'], {}), '(checkpoint, model_path)\n', (3920, 3944), True, 'import megengine as mge\n'), ((4434, 4454), 'megengine.load', 'mge.load', (['model_path'], {}), '(model_path)\n', (4442, 4454), True, 'import megengine as mge\n'), ((5895, 5948), 'megengine.functional.debug_param.set_conv_execution_strategy', 'set_conv_execution_strategy', (['"""HEURISTIC_REPRODUCIBLE"""'], {}), "('HEURISTIC_REPRODUCIBLE')\n", (5922, 5948), False, 'from megengine.functional.debug_param import set_conv_execution_strategy\n'), ((975, 1067), 'subprocess.check_output', 'subprocess.check_output', (["['nvidia-smi', '--query-gpu=gpu_name', '--format=csv,noheader']"], {}), "(['nvidia-smi', '--query-gpu=gpu_name',\n '--format=csv,noheader'])\n", (998, 1067), False, 'import subprocess\n'), ((1770, 1809), 'megengine.module.Conv2d', 'Conv2d', (['(1)', '(20)'], {'kernel_size': '(5)', 'bias': '(True)'}), '(1, 20, kernel_size=5, bias=True)\n', (1776, 1809), False, 'from megengine.module import AvgPool2d, BatchNorm2d, Conv2d, Linear, Module\n'), ((1831, 1843), 'megengine.module.AvgPool2d', 'AvgPool2d', (['(2)'], {}), '(2)\n', (1840, 1843), False, 'from megengine.module import AvgPool2d, BatchNorm2d, Conv2d, Linear, Module\n'), ((1865, 1905), 'megengine.module.Conv2d', 'Conv2d', (['(20)', '(20)'], {'kernel_size': '(5)', 'bias': '(True)'}), '(20, 20, kernel_size=5, bias=True)\n', (1871, 1905), False, 'from megengine.module import AvgPool2d, BatchNorm2d, Conv2d, Linear, Module\n'), ((1927, 1939), 'megengine.module.AvgPool2d', 'AvgPool2d', (['(2)'], {}), '(2)\n', (1936, 1939), False, 'from megengine.module import AvgPool2d, BatchNorm2d, Conv2d, Linear, Module\n'), ((1959, 1993), 'megengine.module.Linear', 'Linear', (['(20 * 4 * 4)', '(500)'], {'bias': '(True)'}), '(20 * 4 * 4, 500, bias=True)\n', (1965, 1993), False, 'from megengine.module import AvgPool2d, BatchNorm2d, Conv2d, Linear, Module\n'), ((2013, 2039), 'megengine.module.Linear', 'Linear', (['(500)', '(10)'], {'bias': '(True)'}), '(500, 10, bias=True)\n', (2019, 2039), False, 'from megengine.module import AvgPool2d, BatchNorm2d, Conv2d, Linear, Module\n'), ((2299, 2308), 'megengine.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (2305, 2308), True, 'import megengine.functional as F\n'), ((2422, 2431), 'megengine.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (2428, 2431), True, 'import megengine.functional as F\n'), ((2470, 2485), 'megengine.functional.flatten', 'F.flatten', (['x', '(1)'], {}), '(x, 1)\n', (2479, 2485), True, 'import megengine.functional as F\n'), ((2522, 2531), 'megengine.functional.relu', 'F.relu', (['x'], {}), '(x)\n', (2528, 2531), True, 'import megengine.functional as F\n'), ((2687, 2718), 'megengine.functional.nn.cross_entropy', 'F.nn.cross_entropy', (['pred', 'label'], {}), '(pred, label)\n', (2705, 2718), True, 'import megengine.functional as F\n'), ((4995, 5007), 'megengine.tensor.Tensor', 'Tensor', (['data'], {}), '(data)\n', (5001, 5007), False, 'from megengine.tensor import Tensor\n'), ((5030, 5043), 'megengine.tensor.Tensor', 'Tensor', (['label'], {}), '(label)\n', (5036, 5043), False, 'from megengine.tensor import Tensor\n'), ((5201, 5216), 'megengine.distributed.get_rank', 'dist.get_rank', ([], {}), '()\n', (5214, 5216), True, 'import megengine.distributed as dist\n'), ((5852, 5877), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (5867, 5877), False, 'import os\n'), ((2130, 2145), 'megengine.module.BatchNorm2d', 'BatchNorm2d', (['(20)'], {}), '(20)\n', (2141, 2145), False, 'from megengine.module import AvgPool2d, BatchNorm2d, Conv2d, Linear, Module\n'), ((2169, 2184), 'megengine.module.BatchNorm2d', 'BatchNorm2d', (['(20)'], {}), '(20)\n', (2180, 2184), False, 'from megengine.module import AvgPool2d, BatchNorm2d, Conv2d, Linear, Module\n'), ((3442, 3458), 'megengine.autodiff.GradManager', 'ad.GradManager', ([], {}), '()\n', (3456, 3458), True, 'import megengine.autodiff as ad\n'), ((1275, 1324), 'subprocess.check_output', 'subprocess.check_output', (["['cat', '/proc/cpuinfo']"], {}), "(['cat', '/proc/cpuinfo'])\n", (1298, 1324), False, 'import subprocess\n'), ((3504, 3546), 'megengine.distributed.make_allreduce_cb', 'dist.make_allreduce_cb', (['"""MEAN"""', 'dist.WORLD'], {}), "('MEAN', dist.WORLD)\n", (3526, 3546), True, 'import megengine.distributed as dist\n'), ((4741, 4757), 'megengine.autodiff.GradManager', 'ad.GradManager', ([], {}), '()\n', (4755, 4757), True, 'import megengine.autodiff as ad\n'), ((5509, 5564), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['param[1]', 'ref'], {'atol': 'max_err'}), '(param[1], ref, atol=max_err)\n', (5535, 5564), True, 'import numpy as np\n'), ((5599, 5663), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['param[1]', 'param_ref[1]'], {'atol': 'max_err'}), '(param[1], param_ref[1], atol=max_err)\n', (5625, 5663), True, 'import numpy as np\n'), ((4807, 4849), 'megengine.distributed.make_allreduce_cb', 'dist.make_allreduce_cb', (['"""MEAN"""', 'dist.WORLD'], {}), "('MEAN', dist.WORLD)\n", (4829, 4849), True, 'import megengine.distributed as dist\n'), ((1443, 1481), 're.sub', 're.sub', (['""".*model name.*:"""', '""""""', 'line', '(1)'], {}), "('.*model name.*:', '', line, 1)\n", (1449, 1481), False, 'import re\n')]
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2020 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import contextlib import os import tempfile import numpy as np import pytest import megengine as mge import megengine._internal as mgb import megengine.module as M from megengine import jit, tensor from megengine.core.tensor import Tensor from megengine.jit import SublinearMemoryConfig from megengine.test import assertTensorClose @contextlib.contextmanager def mkstemp(): fd, path = tempfile.mkstemp() try: os.close(fd) yield path finally: os.remove(path) def load_and_compile(fpath): cg, _, outputs = mgb.load_comp_graph_from_file(fpath) inputs = mgb.cgtools.get_dep_vars(outputs, "Host2DeviceCopy") inputs = sorted(inputs, key=lambda i: i.name) outputs = list(map(mgb.copy_output, outputs)) if len(outputs) == 1: (outputs,) = outputs return cg.compile(inputs, outputs) def test_symbolic(): @jit.trace(symbolic=False) def f(x): return Tensor(mgb.opr.assert_equal(x._symvar, x._symvar + 1)) with pytest.raises(mgb.exc.MegBrainError): f.trace(0) @jit.trace(symbolic=True) def f(x): return Tensor(mgb.opr.assert_equal(x._symvar, x._symvar + 1)) f.trace(0) def test_dump(): @jit.trace(symbolic=True) def f(x, y): return x * y f.trace(0, 0) with mkstemp() as out: f.dump(out) g = load_and_compile(out) np.testing.assert_allclose(g([1, 2, 3], [1, 2, 3]), [1, 4, 9]) def test_goptions(): @jit.trace(symbolic=True, opt_level=0) def f(x): return x / x @jit.trace(symbolic=True, opt_level=1) def g(x): return x / x out = f([0.0]).numpy() # out is nan if out == out: raise # with gopt, x / x returns 1 out = g([0.0]).numpy() assert out == 1 def test_json_prof(): @jit.trace(symbolic=True, profiling=True) def f(x): return x * x f([0.0]) out = f.get_profile() assert out.get("profiler") def test_capture_dump(): p = tensor(7) @jit.trace(symbolic=True) def f(x): return x * p f.trace(0) with mkstemp() as out: f.dump(out) g = load_and_compile(out) np.testing.assert_allclose(g([1, 2, 3]), [7, 14, 21]) def test_dump_volatile(): p = tensor(7) @jit.trace(symbolic=True) def f(x): return x * p f.trace(0) with mkstemp() as out: f.dump(out) cg, _, outputs = mgb.load_comp_graph_from_file(out) (out,) = outputs assert mgb.cgtools.get_type(mgb.cgtools.get_inputs(out)[1]) == "SharedDeviceTensor" def test_shape_tracing(): for symbolic in [False, True]: @jit.trace(symbolic=symbolic) def f(x): a, b = x.shape return a * b assert f(np.zeros([4, 3], dtype="float32")).item() == 12 assert f(np.zeros([6, 4], dtype="float32")).item() == 24 def test_shape_infer(): @jit.trace(symbolic=True) def f(x): a, b = x.shape return sum(x[i] for i in range(a)) x = np.random.randn(3, 10).astype("float32") assertTensorClose(f(x), x.sum(0)) x = np.random.randn(4, 10).astype("float32") assertTensorClose(f(x), x[:3].sum(0)) def test_dump_bn_fused(): class ConvBNReLU(M.Sequential): def __init__(self): super(ConvBNReLU, self).__init__( M.Conv2d(3, 4, 3, 1, 1, groups=1, bias=False), M.BatchNorm2d(4), M.ReLU(), ) net = ConvBNReLU() net.eval() @jit.trace(symbolic=True) def fun(data): return net(data) data = np.random.random([1, 3, 224, 224]).astype(np.float32) fun.trace(data) with mkstemp() as out: fun.dump(out, optimize_for_inference=True) cg, _, outputs = mgb.load_comp_graph_from_file(out) (out,) = outputs inputs = mgb.cgtools.get_inputs(out) assert len(inputs) == 2 and ( mgb.cgtools.get_type(inputs[0]) == "MultipleDeviceTensorHolder" and mgb.cgtools.get_type(inputs[1]) == "ConvolutionForward" ) # Simply verify the options passed down def test_sublinear(): config = SublinearMemoryConfig(genetic_nr_iter=10) @jit.trace(symbolic=True, sublinear_memory_config=config) def f(x): return x + x f([0.0])
[ "megengine._internal.cgtools.get_dep_vars", "megengine.tensor", "megengine.module.ReLU", "megengine._internal.cgtools.get_inputs", "megengine.module.BatchNorm2d", "megengine._internal.load_comp_graph_from_file", "megengine.module.Conv2d", "megengine._internal.opr.assert_equal", "megengine.jit.trace", "megengine.jit.SublinearMemoryConfig", "megengine._internal.cgtools.get_type" ]
[((770, 788), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {}), '()\n', (786, 788), False, 'import tempfile\n'), ((927, 963), 'megengine._internal.load_comp_graph_from_file', 'mgb.load_comp_graph_from_file', (['fpath'], {}), '(fpath)\n', (956, 963), True, 'import megengine._internal as mgb\n'), ((977, 1029), 'megengine._internal.cgtools.get_dep_vars', 'mgb.cgtools.get_dep_vars', (['outputs', '"""Host2DeviceCopy"""'], {}), "(outputs, 'Host2DeviceCopy')\n", (1001, 1029), True, 'import megengine._internal as mgb\n'), ((1252, 1277), 'megengine.jit.trace', 'jit.trace', ([], {'symbolic': '(False)'}), '(symbolic=False)\n', (1261, 1277), False, 'from megengine import jit, tensor\n'), ((1435, 1459), 'megengine.jit.trace', 'jit.trace', ([], {'symbolic': '(True)'}), '(symbolic=True)\n', (1444, 1459), False, 'from megengine import jit, tensor\n'), ((1584, 1608), 'megengine.jit.trace', 'jit.trace', ([], {'symbolic': '(True)'}), '(symbolic=True)\n', (1593, 1608), False, 'from megengine import jit, tensor\n'), ((1844, 1881), 'megengine.jit.trace', 'jit.trace', ([], {'symbolic': '(True)', 'opt_level': '(0)'}), '(symbolic=True, opt_level=0)\n', (1853, 1881), False, 'from megengine import jit, tensor\n'), ((1923, 1960), 'megengine.jit.trace', 'jit.trace', ([], {'symbolic': '(True)', 'opt_level': '(1)'}), '(symbolic=True, opt_level=1)\n', (1932, 1960), False, 'from megengine import jit, tensor\n'), ((2184, 2224), 'megengine.jit.trace', 'jit.trace', ([], {'symbolic': '(True)', 'profiling': '(True)'}), '(symbolic=True, profiling=True)\n', (2193, 2224), False, 'from megengine import jit, tensor\n'), ((2367, 2376), 'megengine.tensor', 'tensor', (['(7)'], {}), '(7)\n', (2373, 2376), False, 'from megengine import jit, tensor\n'), ((2383, 2407), 'megengine.jit.trace', 'jit.trace', ([], {'symbolic': '(True)'}), '(symbolic=True)\n', (2392, 2407), False, 'from megengine import jit, tensor\n'), ((2636, 2645), 'megengine.tensor', 'tensor', (['(7)'], {}), '(7)\n', (2642, 2645), False, 'from megengine import jit, tensor\n'), ((2652, 2676), 'megengine.jit.trace', 'jit.trace', ([], {'symbolic': '(True)'}), '(symbolic=True)\n', (2661, 2676), False, 'from megengine import jit, tensor\n'), ((3280, 3304), 'megengine.jit.trace', 'jit.trace', ([], {'symbolic': '(True)'}), '(symbolic=True)\n', (3289, 3304), False, 'from megengine import jit, tensor\n'), ((3884, 3908), 'megengine.jit.trace', 'jit.trace', ([], {'symbolic': '(True)'}), '(symbolic=True)\n', (3893, 3908), False, 'from megengine import jit, tensor\n'), ((4212, 4239), 'megengine._internal.cgtools.get_inputs', 'mgb.cgtools.get_inputs', (['out'], {}), '(out)\n', (4234, 4239), True, 'import megengine._internal as mgb\n'), ((4497, 4538), 'megengine.jit.SublinearMemoryConfig', 'SublinearMemoryConfig', ([], {'genetic_nr_iter': '(10)'}), '(genetic_nr_iter=10)\n', (4518, 4538), False, 'from megengine.jit import SublinearMemoryConfig\n'), ((4545, 4601), 'megengine.jit.trace', 'jit.trace', ([], {'symbolic': '(True)', 'sublinear_memory_config': 'config'}), '(symbolic=True, sublinear_memory_config=config)\n', (4554, 4601), False, 'from megengine import jit, tensor\n'), ((806, 818), 'os.close', 'os.close', (['fd'], {}), '(fd)\n', (814, 818), False, 'import os\n'), ((859, 874), 'os.remove', 'os.remove', (['path'], {}), '(path)\n', (868, 874), False, 'import os\n'), ((1372, 1408), 'pytest.raises', 'pytest.raises', (['mgb.exc.MegBrainError'], {}), '(mgb.exc.MegBrainError)\n', (1385, 1408), False, 'import pytest\n'), ((2801, 2835), 'megengine._internal.load_comp_graph_from_file', 'mgb.load_comp_graph_from_file', (['out'], {}), '(out)\n', (2830, 2835), True, 'import megengine._internal as mgb\n'), ((3019, 3047), 'megengine.jit.trace', 'jit.trace', ([], {'symbolic': 'symbolic'}), '(symbolic=symbolic)\n', (3028, 3047), False, 'from megengine import jit, tensor\n'), ((4142, 4176), 'megengine._internal.load_comp_graph_from_file', 'mgb.load_comp_graph_from_file', (['out'], {}), '(out)\n', (4171, 4176), True, 'import megengine._internal as mgb\n'), ((1314, 1360), 'megengine._internal.opr.assert_equal', 'mgb.opr.assert_equal', (['x._symvar', '(x._symvar + 1)'], {}), '(x._symvar, x._symvar + 1)\n', (1334, 1360), True, 'import megengine._internal as mgb\n'), ((1496, 1542), 'megengine._internal.opr.assert_equal', 'mgb.opr.assert_equal', (['x._symvar', '(x._symvar + 1)'], {}), '(x._symvar, x._symvar + 1)\n', (1516, 1542), True, 'import megengine._internal as mgb\n'), ((3394, 3416), 'numpy.random.randn', 'np.random.randn', (['(3)', '(10)'], {}), '(3, 10)\n', (3409, 3416), True, 'import numpy as np\n'), ((3481, 3503), 'numpy.random.randn', 'np.random.randn', (['(4)', '(10)'], {}), '(4, 10)\n', (3496, 3503), True, 'import numpy as np\n'), ((3965, 3999), 'numpy.random.random', 'np.random.random', (['[1, 3, 224, 224]'], {}), '([1, 3, 224, 224])\n', (3981, 3999), True, 'import numpy as np\n'), ((2890, 2917), 'megengine._internal.cgtools.get_inputs', 'mgb.cgtools.get_inputs', (['out'], {}), '(out)\n', (2912, 2917), True, 'import megengine._internal as mgb\n'), ((3718, 3763), 'megengine.module.Conv2d', 'M.Conv2d', (['(3)', '(4)', '(3)', '(1)', '(1)'], {'groups': '(1)', 'bias': '(False)'}), '(3, 4, 3, 1, 1, groups=1, bias=False)\n', (3726, 3763), True, 'import megengine.module as M\n'), ((3781, 3797), 'megengine.module.BatchNorm2d', 'M.BatchNorm2d', (['(4)'], {}), '(4)\n', (3794, 3797), True, 'import megengine.module as M\n'), ((3815, 3823), 'megengine.module.ReLU', 'M.ReLU', ([], {}), '()\n', (3821, 3823), True, 'import megengine.module as M\n'), ((4282, 4313), 'megengine._internal.cgtools.get_type', 'mgb.cgtools.get_type', (['inputs[0]'], {}), '(inputs[0])\n', (4302, 4313), True, 'import megengine._internal as mgb\n'), ((4358, 4389), 'megengine._internal.cgtools.get_type', 'mgb.cgtools.get_type', (['inputs[1]'], {}), '(inputs[1])\n', (4378, 4389), True, 'import megengine._internal as mgb\n'), ((3136, 3169), 'numpy.zeros', 'np.zeros', (['[4, 3]'], {'dtype': '"""float32"""'}), "([4, 3], dtype='float32')\n", (3144, 3169), True, 'import numpy as np\n'), ((3201, 3234), 'numpy.zeros', 'np.zeros', (['[6, 4]'], {'dtype': '"""float32"""'}), "([6, 4], dtype='float32')\n", (3209, 3234), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2020 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import argparse import multiprocessing import time # pylint: disable=import-error import model as snet_model import megengine import megengine.data as data import megengine.data.transform as T import megengine.distributed as dist import megengine.functional as F logging = megengine.logger.get_logger() def main(): parser = argparse.ArgumentParser(description="MegEngine ImageNet Training") parser.add_argument("-d", "--data", metavar="DIR", help="path to imagenet dataset") parser.add_argument( "-a", "--arch", default="shufflenet_v2_x1_0", help="model architecture (default: shufflenet_v2_x1_0)", ) parser.add_argument( "-n", "--ngpus", default=None, type=int, help="number of GPUs per node (default: None, use all available GPUs)", ) parser.add_argument( "-m", "--model", metavar="PKL", default=None, help="path to model checkpoint" ) parser.add_argument("-j", "--workers", default=2, type=int) parser.add_argument( "-p", "--print-freq", default=20, type=int, metavar="N", help="print frequency (default: 10)", ) parser.add_argument("--dist-addr", default="localhost") parser.add_argument("--dist-port", default=23456, type=int) parser.add_argument("--world-size", default=1, type=int) parser.add_argument("--rank", default=0, type=int) args = parser.parse_args() # create server if is master if args.rank <= 0: server = dist.Server(port=args.dist_port) # pylint: disable=unused-variable # noqa: F841 # get device count with multiprocessing.Pool(1) as pool: ngpus_per_node, _ = pool.map(megengine.get_device_count, ["gpu", "cpu"]) if args.ngpus: ngpus_per_node = args.ngpus # launch processes procs = [] for local_rank in range(ngpus_per_node): p = multiprocessing.Process( target=worker, kwargs=dict( rank=args.rank * ngpus_per_node + local_rank, world_size=args.world_size * ngpus_per_node, ngpus_per_node=ngpus_per_node, args=args, ), ) p.start() procs.append(p) # join processes for p in procs: p.join() def worker(rank, world_size, ngpus_per_node, args): # init process group if world_size > 1: dist.init_process_group( master_ip=args.dist_addr, port=args.dist_port, world_size=world_size, rank=rank, device=rank % ngpus_per_node, backend="nccl", ) logging.info( "init process group rank %d / %d", dist.get_rank(), dist.get_world_size() ) # build dataset _, valid_dataloader = build_dataset(args) # build model model = snet_model.__dict__[args.arch](pretrained=args.model is None) if args.model is not None: logging.info("load from checkpoint %s", args.model) checkpoint = megengine.load(args.model) if "state_dict" in checkpoint: state_dict = checkpoint["state_dict"] model.load_state_dict(state_dict) def valid_step(image, label): logits = model(image) loss = F.nn.cross_entropy(logits, label) acc1, acc5 = F.topk_accuracy(logits, label, topk=(1, 5)) # calculate mean values if world_size > 1: loss = F.distributed.all_reduce_sum(loss) / world_size acc1 = F.distributed.all_reduce_sum(acc1) / world_size acc5 = F.distributed.all_reduce_sum(acc5) / world_size return loss, acc1, acc5 model.eval() _, valid_acc1, valid_acc5 = valid(valid_step, valid_dataloader, args) logging.info( "Test Acc@1 %.3f, Acc@5 %.3f", valid_acc1, valid_acc5, ) def valid(func, data_queue, args): objs = AverageMeter("Loss") top1 = AverageMeter("Acc@1") top5 = AverageMeter("Acc@5") clck = AverageMeter("Time") t = time.time() for step, (image, label) in enumerate(data_queue): image = megengine.tensor(image, dtype="float32") label = megengine.tensor(label, dtype="int32") n = image.shape[0] loss, acc1, acc5 = func(image, label) objs.update(loss.item(), n) top1.update(100 * acc1.item(), n) top5.update(100 * acc5.item(), n) clck.update(time.time() - t, n) t = time.time() if step % args.print_freq == 0 and dist.get_rank() == 0: logging.info("Test step %d, %s %s %s %s", step, objs, top1, top5, clck) return objs.avg, top1.avg, top5.avg def build_dataset(args): train_dataloader = None valid_dataset = data.dataset.ImageNet(args.data, train=False) valid_sampler = data.SequentialSampler( valid_dataset, batch_size=100, drop_last=False ) valid_dataloader = data.DataLoader( valid_dataset, sampler=valid_sampler, transform=T.Compose( [ T.Resize(256), T.CenterCrop(224), T.Normalize( mean=[103.530, 116.280, 123.675], std=[57.375, 57.120, 58.395] ), # BGR T.ToMode("CHW"), ] ), num_workers=args.workers, ) return train_dataloader, valid_dataloader class AverageMeter: """Computes and stores the average and current value""" def __init__(self, name, fmt=":.3f"): self.name = name self.fmt = fmt self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def __str__(self): fmtstr = "{name} {val" + self.fmt + "} ({avg" + self.fmt + "})" return fmtstr.format(**self.__dict__) if __name__ == "__main__": main()
[ "megengine.data.dataset.ImageNet", "megengine.logger.get_logger", "megengine.functional.nn.cross_entropy", "megengine.distributed.init_process_group", "megengine.functional.topk_accuracy", "megengine.data.SequentialSampler", "megengine.tensor", "megengine.distributed.Server", "megengine.functional.distributed.all_reduce_sum", "megengine.load", "megengine.data.transform.Normalize", "megengine.data.transform.CenterCrop", "megengine.distributed.get_rank", "megengine.data.transform.Resize", "megengine.distributed.get_world_size", "megengine.data.transform.ToMode" ]
[((653, 682), 'megengine.logger.get_logger', 'megengine.logger.get_logger', ([], {}), '()\n', (680, 682), False, 'import megengine\n'), ((710, 776), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""MegEngine ImageNet Training"""'}), "(description='MegEngine ImageNet Training')\n", (733, 776), False, 'import argparse\n'), ((4432, 4443), 'time.time', 'time.time', ([], {}), '()\n', (4441, 4443), False, 'import time\n'), ((5137, 5182), 'megengine.data.dataset.ImageNet', 'data.dataset.ImageNet', (['args.data'], {'train': '(False)'}), '(args.data, train=False)\n', (5158, 5182), True, 'import megengine.data as data\n'), ((5203, 5273), 'megengine.data.SequentialSampler', 'data.SequentialSampler', (['valid_dataset'], {'batch_size': '(100)', 'drop_last': '(False)'}), '(valid_dataset, batch_size=100, drop_last=False)\n', (5225, 5273), True, 'import megengine.data as data\n'), ((1918, 1950), 'megengine.distributed.Server', 'dist.Server', ([], {'port': 'args.dist_port'}), '(port=args.dist_port)\n', (1929, 1950), True, 'import megengine.distributed as dist\n'), ((2033, 2056), 'multiprocessing.Pool', 'multiprocessing.Pool', (['(1)'], {}), '(1)\n', (2053, 2056), False, 'import multiprocessing\n'), ((2808, 2967), 'megengine.distributed.init_process_group', 'dist.init_process_group', ([], {'master_ip': 'args.dist_addr', 'port': 'args.dist_port', 'world_size': 'world_size', 'rank': 'rank', 'device': '(rank % ngpus_per_node)', 'backend': '"""nccl"""'}), "(master_ip=args.dist_addr, port=args.dist_port,\n world_size=world_size, rank=rank, device=rank % ngpus_per_node, backend\n ='nccl')\n", (2831, 2967), True, 'import megengine.distributed as dist\n'), ((3432, 3458), 'megengine.load', 'megengine.load', (['args.model'], {}), '(args.model)\n', (3446, 3458), False, 'import megengine\n'), ((3670, 3703), 'megengine.functional.nn.cross_entropy', 'F.nn.cross_entropy', (['logits', 'label'], {}), '(logits, label)\n', (3688, 3703), True, 'import megengine.functional as F\n'), ((3725, 3768), 'megengine.functional.topk_accuracy', 'F.topk_accuracy', (['logits', 'label'], {'topk': '(1, 5)'}), '(logits, label, topk=(1, 5))\n', (3740, 3768), True, 'import megengine.functional as F\n'), ((4515, 4555), 'megengine.tensor', 'megengine.tensor', (['image'], {'dtype': '"""float32"""'}), "(image, dtype='float32')\n", (4531, 4555), False, 'import megengine\n'), ((4572, 4610), 'megengine.tensor', 'megengine.tensor', (['label'], {'dtype': '"""int32"""'}), "(label, dtype='int32')\n", (4588, 4610), False, 'import megengine\n'), ((4859, 4870), 'time.time', 'time.time', ([], {}), '()\n', (4868, 4870), False, 'import time\n'), ((3111, 3126), 'megengine.distributed.get_rank', 'dist.get_rank', ([], {}), '()\n', (3124, 3126), True, 'import megengine.distributed as dist\n'), ((3128, 3149), 'megengine.distributed.get_world_size', 'dist.get_world_size', ([], {}), '()\n', (3147, 3149), True, 'import megengine.distributed as dist\n'), ((3847, 3881), 'megengine.functional.distributed.all_reduce_sum', 'F.distributed.all_reduce_sum', (['loss'], {}), '(loss)\n', (3875, 3881), True, 'import megengine.functional as F\n'), ((3914, 3948), 'megengine.functional.distributed.all_reduce_sum', 'F.distributed.all_reduce_sum', (['acc1'], {}), '(acc1)\n', (3942, 3948), True, 'import megengine.functional as F\n'), ((3981, 4015), 'megengine.functional.distributed.all_reduce_sum', 'F.distributed.all_reduce_sum', (['acc5'], {}), '(acc5)\n', (4009, 4015), True, 'import megengine.functional as F\n'), ((4827, 4838), 'time.time', 'time.time', ([], {}), '()\n', (4836, 4838), False, 'import time\n'), ((4915, 4930), 'megengine.distributed.get_rank', 'dist.get_rank', ([], {}), '()\n', (4928, 4930), True, 'import megengine.distributed as dist\n'), ((5441, 5454), 'megengine.data.transform.Resize', 'T.Resize', (['(256)'], {}), '(256)\n', (5449, 5454), True, 'import megengine.data.transform as T\n'), ((5472, 5489), 'megengine.data.transform.CenterCrop', 'T.CenterCrop', (['(224)'], {}), '(224)\n', (5484, 5489), True, 'import megengine.data.transform as T\n'), ((5507, 5579), 'megengine.data.transform.Normalize', 'T.Normalize', ([], {'mean': '[103.53, 116.28, 123.675]', 'std': '[57.375, 57.12, 58.395]'}), '(mean=[103.53, 116.28, 123.675], std=[57.375, 57.12, 58.395])\n', (5518, 5579), True, 'import megengine.data.transform as T\n'), ((5645, 5660), 'megengine.data.transform.ToMode', 'T.ToMode', (['"""CHW"""'], {}), "('CHW')\n", (5653, 5660), True, 'import megengine.data.transform as T\n')]
import math import numpy import megengine as mge import megengine.module as M import megengine.functional as F from .layer_norm import LayerNorm class DecoderLayer(M.Module): """Single decoder layer module.""" def __init__( self, size, self_attn, src_attn, feed_forward, dropout_rate, normalize_before=True, ): """Construct an DecoderLayer object.""" super(DecoderLayer, self).__init__() self.size = size self.self_attn = self_attn self.src_attn = src_attn self.feed_forward = feed_forward self.norm1 = LayerNorm(size) self.norm2 = LayerNorm(size) self.norm3 = LayerNorm(size) self.dropout = M.dropout.Dropout(dropout_rate) self.normalize_before = normalize_before def forward(self, tgt, tgt_mask, memory, memory_mask, cache=None): """Compute decoded features. Args: tgt (megengine.Tensor): decoded previous target features (batch, max_time_out, size) tgt_mask (megengine.Tensor): mask for x (batch, max_time_out) memory (megengine.Tensor): encoded source features (batch, max_time_in, size) memory_mask (megengine.Tensor): mask for memory (batch, max_time_in) cache (megengine.Tensor): cached output (batch, max_time_out-1, size) """ residual = tgt if self.normalize_before: tgt = self.norm1(tgt) if cache is None: tgt_q = tgt tgt_q_mask = tgt_mask else: # compute only the last frame query keeping dim: max_time_out -> 1 assert cache.shape == ( tgt.shape[0], tgt.shape[1] - 1, self.size, ), f"{cache.shape} == {(tgt.shape[0], tgt.shape[1] - 1, self.size)}" tgt_q = tgt[:, -1:, :] residual = residual[:, -1:, :] tgt_q_mask = None if tgt_mask is not None: tgt_q_mask = tgt_mask[:, -1:, :] x = residual + self.dropout(self.self_attn(tgt_q, tgt, tgt, tgt_q_mask)) if not self.normalize_before: x = self.norm1(x) residual = x if self.normalize_before: x = self.norm2(x) x = residual + self.dropout(self.src_attn(x, memory, memory, memory_mask)) if not self.normalize_before: x = self.norm2(x) residual = x if self.normalize_before: x = self.norm3(x) x = residual + self.dropout(self.feed_forward(x)) if not self.normalize_before: x = self.norm3(x) if cache is not None: x = F.concat([cache, x], axis=1) return x, tgt_mask, memory, memory_mask
[ "megengine.module.dropout.Dropout", "megengine.functional.concat" ]
[((744, 775), 'megengine.module.dropout.Dropout', 'M.dropout.Dropout', (['dropout_rate'], {}), '(dropout_rate)\n', (761, 775), True, 'import megengine.module as M\n'), ((2705, 2733), 'megengine.functional.concat', 'F.concat', (['[cache, x]'], {'axis': '(1)'}), '([cache, x], axis=1)\n', (2713, 2733), True, 'import megengine.functional as F\n')]
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Copyright (c) Megvii, Inc. and its affiliates. import argparse from loguru import logger import multiprocessing as mp import megengine as mge import megengine.distributed as dist from yolox.core import Trainer from yolox.exp import get_exp from yolox.utils import configure_nccl def make_parser(): parser = argparse.ArgumentParser("YOLOX train parser") parser.add_argument("-expn", "--experiment-name", type=str, default=None) parser.add_argument("-n", "--name", type=str, default=None, help="model name") parser.add_argument("-b", "--batch-size", type=int, default=64, help="batch size") parser.add_argument( "-d", "--devices", default=None, type=int, help="device for training" ) parser.add_argument( "-f", "--exp_file", default=None, type=str, help="plz input your expriment description file", ) parser.add_argument( "--resume", default=False, action="store_true", help="resume training" ) parser.add_argument("-c", "--ckpt", default=None, type=str, help="checkpoint file") parser.add_argument( "--num_machine", default=1, type=int, help="num of node for training" ) parser.add_argument( "--machine_rank", default=0, type=int, help="node rank for multi-node training" ) parser.add_argument( "--sync_level", type=int, default=None, help="config sync level, use 0 to debug" ) parser.add_argument( "opts", help="Modify config options using the command-line", default=None, nargs=argparse.REMAINDER, ) return parser @logger.catch def main(exp, args): if not args.experiment_name: args.experiment_name = exp.exp_name # set environment variables for distributed training configure_nccl() # enable dtr to avoid CUDA OOM mge.dtr.enable() if args.sync_level is not None: # NOTE: use sync_level = 0 to debug mge error from megengine.core._imperative_rt.core2 import config_async_level logger.info("Using aysnc_level {}".format(args.sync_level)) config_async_level(args.sync_level) trainer = Trainer(exp, args) trainer.train() if __name__ == "__main__": args = make_parser().parse_args() exp = get_exp(args.exp_file, args.name) exp.merge(args.opts) mp.set_start_method("spawn") num_gpus = dist.helper.get_device_count_by_fork("gpu") if args.devices is None: args.devices = num_gpus assert args.devices <= num_gpus if args.devices > 1: train = dist.launcher(main, n_gpus=args.devices) train(exp, args) else: main(exp, args)
[ "megengine.dtr.enable", "megengine.distributed.helper.get_device_count_by_fork", "megengine.distributed.launcher", "megengine.core._imperative_rt.core2.config_async_level" ]
[((364, 409), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""YOLOX train parser"""'], {}), "('YOLOX train parser')\n", (387, 409), False, 'import argparse\n'), ((1837, 1853), 'yolox.utils.configure_nccl', 'configure_nccl', ([], {}), '()\n', (1851, 1853), False, 'from yolox.utils import configure_nccl\n'), ((1894, 1910), 'megengine.dtr.enable', 'mge.dtr.enable', ([], {}), '()\n', (1908, 1910), True, 'import megengine as mge\n'), ((2204, 2222), 'yolox.core.Trainer', 'Trainer', (['exp', 'args'], {}), '(exp, args)\n', (2211, 2222), False, 'from yolox.core import Trainer\n'), ((2320, 2353), 'yolox.exp.get_exp', 'get_exp', (['args.exp_file', 'args.name'], {}), '(args.exp_file, args.name)\n', (2327, 2353), False, 'from yolox.exp import get_exp\n'), ((2384, 2412), 'multiprocessing.set_start_method', 'mp.set_start_method', (['"""spawn"""'], {}), "('spawn')\n", (2403, 2412), True, 'import multiprocessing as mp\n'), ((2428, 2471), 'megengine.distributed.helper.get_device_count_by_fork', 'dist.helper.get_device_count_by_fork', (['"""gpu"""'], {}), "('gpu')\n", (2464, 2471), True, 'import megengine.distributed as dist\n'), ((2153, 2188), 'megengine.core._imperative_rt.core2.config_async_level', 'config_async_level', (['args.sync_level'], {}), '(args.sync_level)\n', (2171, 2188), False, 'from megengine.core._imperative_rt.core2 import config_async_level\n'), ((2613, 2653), 'megengine.distributed.launcher', 'dist.launcher', (['main'], {'n_gpus': 'args.devices'}), '(main, n_gpus=args.devices)\n', (2626, 2653), True, 'import megengine.distributed as dist\n')]
import numpy as np import megengine.functional as F from common import se3, so3 def compute_losses(endpoints, params): loss = {} # compute losses if params.loss_type == "finet": num_iter = len(endpoints["all_pose_pair"]) triplet_loss = {} for i in range(num_iter): # reg loss pose_pair = endpoints["all_pose_pair"][i] loss["quat_{}".format(i)] = F.nn.l1_loss(pose_pair[0][:, :4], pose_pair[1][:, :4]) * params.loss_alpha1 loss["translate_{}".format(i)] = F.nn.square_loss(pose_pair[0][:, 4:], pose_pair[1][:, 4:]) * params.loss_alpha2 # transformation sensitivity loss (TSL) if i < 2: all_R_feats = endpoints["all_R_feats"][i] all_t_feats = endpoints["all_t_feats"][i] # R feats triplet loss R_feats_pos = F.nn.square_loss(all_t_feats[0], all_t_feats[1]) R_feats_neg = F.nn.square_loss(all_R_feats[0], all_R_feats[1]) triplet_loss["R_feats_triplet_pos_{}".format(i)] = R_feats_pos triplet_loss["R_feats_triplet_neg_{}".format(i)] = R_feats_neg loss["R_feats_triplet_{}".format(i)] = (F.clip(-R_feats_neg + params.margin[i], lower=0.0) + R_feats_pos) * params.loss_alpha3 # t feats triplet loss t_feats_pos = F.nn.square_loss(all_R_feats[0], all_R_feats[2]) t_feats_neg = F.nn.square_loss(all_t_feats[0], all_t_feats[2]) triplet_loss["t_feats_triplet_pos_{}".format(i)] = t_feats_pos triplet_loss["t_feats_triplet_neg_{}".format(i)] = t_feats_neg loss["t_feats_triplet_{}".format(i)] = (F.clip(-t_feats_neg + params.margin[i], lower=0.0) + t_feats_pos) * params.loss_alpha3 # point-wise feature dropout loss (PFDL) all_dropout_R_feats = endpoints["all_dropout_R_feats"][i] all_dropout_t_feats = endpoints["all_dropout_t_feats"][i] loss["src_R_feats_dropout_{}".format(i)] = F.nn.square_loss(all_dropout_R_feats[0], all_dropout_R_feats[1]) * params.loss_alpha4 loss["ref_R_feats_dropout_{}".format(i)] = F.nn.square_loss(all_dropout_R_feats[2], all_dropout_R_feats[3]) * params.loss_alpha4 loss["src_t_feats_dropout_{}".format(i)] = F.nn.square_loss(all_dropout_t_feats[0], all_dropout_t_feats[1]) * params.loss_alpha4 loss["ref_t_feats_dropout_{}".format(i)] = F.nn.square_loss(all_dropout_t_feats[2], all_dropout_t_feats[3]) * params.loss_alpha4 # total loss total_losses = [] for k in loss: total_losses.append(loss[k]) loss["total"] = F.sum(F.concat(total_losses)) else: raise NotImplementedError return loss def compute_metrics(endpoints, params): metrics = {} gt_transforms = endpoints["transform_pair"][0] pred_transforms = endpoints["transform_pair"][1] # Euler angles, Individual translation errors (Deep Closest Point convention) if "prnet" in params.transform_type: r_gt_euler_deg = so3.mge_dcm2euler(gt_transforms[:, :3, :3], seq="zyx") r_pred_euler_deg = so3.mge_dcm2euler(pred_transforms[:, :3, :3], seq="zyx") else: r_gt_euler_deg = so3.mge_dcm2euler(gt_transforms[:, :3, :3], seq="xyz") r_pred_euler_deg = so3.mge_dcm2euler(pred_transforms[:, :3, :3], seq="xyz") t_gt = gt_transforms[:, :3, 3] t_pred = pred_transforms[:, :3, 3] r_mse = F.mean((r_gt_euler_deg - r_pred_euler_deg)**2, axis=1) r_mae = F.mean(F.abs(r_gt_euler_deg - r_pred_euler_deg), axis=1) t_mse = F.mean((t_gt - t_pred)**2, axis=1) t_mae = F.mean(F.abs(t_gt - t_pred), axis=1) r_mse = F.mean(r_mse) t_mse = F.mean(t_mse) r_mae = F.mean(r_mae) t_mae = F.mean(t_mae) # Rotation, translation errors (isotropic, i.e. doesn"t depend on error # direction, which is more representative of the actual error) concatenated = se3.mge_concatenate(se3.mge_inverse(gt_transforms), pred_transforms) rot_trace = concatenated[:, 0, 0] + concatenated[:, 1, 1] + concatenated[:, 2, 2] residual_rotdeg = F.acos(F.clip(0.5 * (rot_trace - 1), -1.0, 1.0)) * 180.0 / np.pi residual_transmag = F.norm(concatenated[:, :, 3], axis=-1) err_r = F.mean(residual_rotdeg) err_t = F.mean(residual_transmag) # weighted score of isotropic errors score = err_r * 0.01 + err_t metrics = {"R_MSE": r_mse, "R_MAE": r_mae, "t_MSE": t_mse, "t_MAE": t_mae, "Err_R": err_r, "Err_t": err_t, "score": score} return metrics
[ "megengine.functional.nn.l1_loss", "megengine.functional.clip", "megengine.functional.nn.square_loss", "megengine.functional.mean", "megengine.functional.norm", "megengine.functional.abs", "megengine.functional.concat" ]
[((3616, 3672), 'megengine.functional.mean', 'F.mean', (['((r_gt_euler_deg - r_pred_euler_deg) ** 2)'], {'axis': '(1)'}), '((r_gt_euler_deg - r_pred_euler_deg) ** 2, axis=1)\n', (3622, 3672), True, 'import megengine.functional as F\n'), ((3752, 3788), 'megengine.functional.mean', 'F.mean', (['((t_gt - t_pred) ** 2)'], {'axis': '(1)'}), '((t_gt - t_pred) ** 2, axis=1)\n', (3758, 3788), True, 'import megengine.functional as F\n'), ((3849, 3862), 'megengine.functional.mean', 'F.mean', (['r_mse'], {}), '(r_mse)\n', (3855, 3862), True, 'import megengine.functional as F\n'), ((3875, 3888), 'megengine.functional.mean', 'F.mean', (['t_mse'], {}), '(t_mse)\n', (3881, 3888), True, 'import megengine.functional as F\n'), ((3901, 3914), 'megengine.functional.mean', 'F.mean', (['r_mae'], {}), '(r_mae)\n', (3907, 3914), True, 'import megengine.functional as F\n'), ((3927, 3940), 'megengine.functional.mean', 'F.mean', (['t_mae'], {}), '(t_mae)\n', (3933, 3940), True, 'import megengine.functional as F\n'), ((4370, 4408), 'megengine.functional.norm', 'F.norm', (['concatenated[:, :, 3]'], {'axis': '(-1)'}), '(concatenated[:, :, 3], axis=-1)\n', (4376, 4408), True, 'import megengine.functional as F\n'), ((4421, 4444), 'megengine.functional.mean', 'F.mean', (['residual_rotdeg'], {}), '(residual_rotdeg)\n', (4427, 4444), True, 'import megengine.functional as F\n'), ((4457, 4482), 'megengine.functional.mean', 'F.mean', (['residual_transmag'], {}), '(residual_transmag)\n', (4463, 4482), True, 'import megengine.functional as F\n'), ((3216, 3270), 'common.so3.mge_dcm2euler', 'so3.mge_dcm2euler', (['gt_transforms[:, :3, :3]'], {'seq': '"""zyx"""'}), "(gt_transforms[:, :3, :3], seq='zyx')\n", (3233, 3270), False, 'from common import se3, so3\n'), ((3298, 3354), 'common.so3.mge_dcm2euler', 'so3.mge_dcm2euler', (['pred_transforms[:, :3, :3]'], {'seq': '"""zyx"""'}), "(pred_transforms[:, :3, :3], seq='zyx')\n", (3315, 3354), False, 'from common import se3, so3\n'), ((3390, 3444), 'common.so3.mge_dcm2euler', 'so3.mge_dcm2euler', (['gt_transforms[:, :3, :3]'], {'seq': '"""xyz"""'}), "(gt_transforms[:, :3, :3], seq='xyz')\n", (3407, 3444), False, 'from common import se3, so3\n'), ((3472, 3528), 'common.so3.mge_dcm2euler', 'so3.mge_dcm2euler', (['pred_transforms[:, :3, :3]'], {'seq': '"""xyz"""'}), "(pred_transforms[:, :3, :3], seq='xyz')\n", (3489, 3528), False, 'from common import se3, so3\n'), ((3690, 3730), 'megengine.functional.abs', 'F.abs', (['(r_gt_euler_deg - r_pred_euler_deg)'], {}), '(r_gt_euler_deg - r_pred_euler_deg)\n', (3695, 3730), True, 'import megengine.functional as F\n'), ((3806, 3826), 'megengine.functional.abs', 'F.abs', (['(t_gt - t_pred)'], {}), '(t_gt - t_pred)\n', (3811, 3826), True, 'import megengine.functional as F\n'), ((4124, 4154), 'common.se3.mge_inverse', 'se3.mge_inverse', (['gt_transforms'], {}), '(gt_transforms)\n', (4139, 4154), False, 'from common import se3, so3\n'), ((2819, 2841), 'megengine.functional.concat', 'F.concat', (['total_losses'], {}), '(total_losses)\n', (2827, 2841), True, 'import megengine.functional as F\n'), ((420, 474), 'megengine.functional.nn.l1_loss', 'F.nn.l1_loss', (['pose_pair[0][:, :4]', 'pose_pair[1][:, :4]'], {}), '(pose_pair[0][:, :4], pose_pair[1][:, :4])\n', (432, 474), True, 'import megengine.functional as F\n'), ((541, 599), 'megengine.functional.nn.square_loss', 'F.nn.square_loss', (['pose_pair[0][:, 4:]', 'pose_pair[1][:, 4:]'], {}), '(pose_pair[0][:, 4:], pose_pair[1][:, 4:])\n', (557, 599), True, 'import megengine.functional as F\n'), ((881, 929), 'megengine.functional.nn.square_loss', 'F.nn.square_loss', (['all_t_feats[0]', 'all_t_feats[1]'], {}), '(all_t_feats[0], all_t_feats[1])\n', (897, 929), True, 'import megengine.functional as F\n'), ((960, 1008), 'megengine.functional.nn.square_loss', 'F.nn.square_loss', (['all_R_feats[0]', 'all_R_feats[1]'], {}), '(all_R_feats[0], all_R_feats[1])\n', (976, 1008), True, 'import megengine.functional as F\n'), ((1435, 1483), 'megengine.functional.nn.square_loss', 'F.nn.square_loss', (['all_R_feats[0]', 'all_R_feats[2]'], {}), '(all_R_feats[0], all_R_feats[2])\n', (1451, 1483), True, 'import megengine.functional as F\n'), ((1514, 1562), 'megengine.functional.nn.square_loss', 'F.nn.square_loss', (['all_t_feats[0]', 'all_t_feats[2]'], {}), '(all_t_feats[0], all_t_feats[2])\n', (1530, 1562), True, 'import megengine.functional as F\n'), ((2169, 2233), 'megengine.functional.nn.square_loss', 'F.nn.square_loss', (['all_dropout_R_feats[0]', 'all_dropout_R_feats[1]'], {}), '(all_dropout_R_feats[0], all_dropout_R_feats[1])\n', (2185, 2233), True, 'import megengine.functional as F\n'), ((2310, 2374), 'megengine.functional.nn.square_loss', 'F.nn.square_loss', (['all_dropout_R_feats[2]', 'all_dropout_R_feats[3]'], {}), '(all_dropout_R_feats[2], all_dropout_R_feats[3])\n', (2326, 2374), True, 'import megengine.functional as F\n'), ((2451, 2515), 'megengine.functional.nn.square_loss', 'F.nn.square_loss', (['all_dropout_t_feats[0]', 'all_dropout_t_feats[1]'], {}), '(all_dropout_t_feats[0], all_dropout_t_feats[1])\n', (2467, 2515), True, 'import megengine.functional as F\n'), ((2592, 2656), 'megengine.functional.nn.square_loss', 'F.nn.square_loss', (['all_dropout_t_feats[2]', 'all_dropout_t_feats[3]'], {}), '(all_dropout_t_feats[2], all_dropout_t_feats[3])\n', (2608, 2656), True, 'import megengine.functional as F\n'), ((4288, 4328), 'megengine.functional.clip', 'F.clip', (['(0.5 * (rot_trace - 1))', '(-1.0)', '(1.0)'], {}), '(0.5 * (rot_trace - 1), -1.0, 1.0)\n', (4294, 4328), True, 'import megengine.functional as F\n'), ((1223, 1273), 'megengine.functional.clip', 'F.clip', (['(-R_feats_neg + params.margin[i])'], {'lower': '(0.0)'}), '(-R_feats_neg + params.margin[i], lower=0.0)\n', (1229, 1273), True, 'import megengine.functional as F\n'), ((1777, 1827), 'megengine.functional.clip', 'F.clip', (['(-t_feats_neg + params.margin[i])'], {'lower': '(0.0)'}), '(-t_feats_neg + params.margin[i], lower=0.0)\n', (1783, 1827), True, 'import megengine.functional as F\n')]
# -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import numpy as np import pytest import megengine as mge import megengine.distributed as dist from megengine import tensor from megengine.distributed.functional import ( all_gather, all_to_all, gather, reduce_scatter_sum, scatter, ) from megengine.jit import trace @pytest.mark.require_ngpu(2) @pytest.mark.parametrize("shape", [(2, 3), (8, 10), (99, 77), (2, 2, 2, 2)], ids=str) @pytest.mark.parametrize("symbolic", [False, True], ids=str) @pytest.mark.parametrize("axis", [0, 1], ids=str) @pytest.mark.isolated_distributed def test_all_gather(shape, symbolic, axis): @dist.launcher(n_gpus=2) def worker(data, expect): rank = dist.get_rank() inp = tensor(data[rank]) def func(): output = all_gather(inp, axis=axis) return output func = trace(symbolic=symbolic)(func) output = func() assert np.allclose(output.numpy(), expect[rank]) x = np.random.random_sample(shape).astype("float32") y = np.random.random_sample(shape).astype("float32") z = np.concatenate((x, y), axis=axis) data = (x, y) expect = (z, z) worker(data, expect) @pytest.mark.require_ngpu(2) @pytest.mark.parametrize( "shape,symbolic", [((2, 4, 6, 8), False), ((2, 4, 6, 8), True)], ids=str ) @pytest.mark.parametrize("axis", [1, 0, 2, 3], ids=str) @pytest.mark.isolated_distributed def test_reduce_scatter_sum(shape, symbolic, axis): @dist.launcher(n_gpus=2) def worker(data, expect): rank = dist.get_rank() inp = tensor(data[rank]) def func(): output = reduce_scatter_sum(inp, axis=axis) return output func = trace(symbolic=symbolic)(func) output = func() assert np.allclose(output.numpy(), expect[rank]) x = np.random.random_sample(shape).astype("float32") y = np.random.random_sample(shape).astype("float32") z = x + y data = (x, y) z = np.split(z, 2, axis=axis) z = np.concatenate(z, axis=0) expect = (z[: z.shape[0] // 2], z[z.shape[0] // 2 :]) worker(data, expect) @pytest.mark.require_ngpu(2) @pytest.mark.parametrize( "shape,symbolic", [((2, 4, 6, 8), True), ((2, 4, 6, 8), False)], ids=str ) @pytest.mark.parametrize("axis", [1, 0, 2, 3], ids=str) @pytest.mark.isolated_distributed def test_scatter(shape, symbolic, axis): @dist.launcher(n_gpus=2) def worker(data, expect): rank = dist.get_rank() inp = tensor(data[rank]) def func(): output = scatter(inp, axis=axis) return output func = trace(symbolic=symbolic)(func) output = func() assert np.allclose(output.numpy(), expect[rank]) x = np.random.random_sample(shape).astype("float32") y = x + 1 data = (x, y) _x = np.split(x, 2, axis=axis) _x = np.concatenate(_x, axis=0) expect = (_x[: _x.shape[0] // 2], _x[_x.shape[0] // 2 :]) worker(data, expect) @pytest.mark.require_ngpu(2) @pytest.mark.parametrize("shape", [(2, 4, 6, 8)], ids=str) @pytest.mark.parametrize("symbolic", [False, True], ids=str) @pytest.mark.parametrize( "split_axis,concat_axis", [(0, 1), (1, 0), (2, 0), (0, 2), (2, 3)], ids=str ) @pytest.mark.isolated_distributed def test_all_to_all(shape, symbolic, split_axis, concat_axis): @dist.launcher(n_gpus=2) def worker(data): rank = dist.get_rank() inp = tensor(data[rank]) def func(): all_to_all_output = all_to_all( inp, split_axis=split_axis, concat_axis=concat_axis ) gather_C = gather(inp, axis=concat_axis) gather_B = gather(all_to_all_output, axis=split_axis) if rank == 0: return gather_B, gather_C return all_to_all_output func = trace(symbolic=symbolic)(func) ret = func() if rank == 0: assert np.allclose(ret[0], ret[1]) x = np.random.random_sample(shape).astype("float32") y = np.random.random_sample(shape).astype("float32") data = (x, y) worker(data)
[ "megengine.tensor", "megengine.distributed.functional.reduce_scatter_sum", "megengine.distributed.get_rank", "megengine.distributed.functional.all_gather", "megengine.distributed.functional.scatter", "megengine.distributed.functional.all_to_all", "megengine.jit.trace", "megengine.distributed.launcher", "megengine.distributed.functional.gather" ]
[((666, 693), 'pytest.mark.require_ngpu', 'pytest.mark.require_ngpu', (['(2)'], {}), '(2)\n', (690, 693), False, 'import pytest\n'), ((695, 783), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""shape"""', '[(2, 3), (8, 10), (99, 77), (2, 2, 2, 2)]'], {'ids': 'str'}), "('shape', [(2, 3), (8, 10), (99, 77), (2, 2, 2, 2)],\n ids=str)\n", (718, 783), False, 'import pytest\n'), ((781, 840), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""symbolic"""', '[False, True]'], {'ids': 'str'}), "('symbolic', [False, True], ids=str)\n", (804, 840), False, 'import pytest\n'), ((842, 890), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""axis"""', '[0, 1]'], {'ids': 'str'}), "('axis', [0, 1], ids=str)\n", (865, 890), False, 'import pytest\n'), ((1538, 1565), 'pytest.mark.require_ngpu', 'pytest.mark.require_ngpu', (['(2)'], {}), '(2)\n', (1562, 1565), False, 'import pytest\n'), ((1567, 1668), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""shape,symbolic"""', '[((2, 4, 6, 8), False), ((2, 4, 6, 8), True)]'], {'ids': 'str'}), "('shape,symbolic', [((2, 4, 6, 8), False), ((2, 4, 6,\n 8), True)], ids=str)\n", (1590, 1668), False, 'import pytest\n'), ((1672, 1726), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""axis"""', '[1, 0, 2, 3]'], {'ids': 'str'}), "('axis', [1, 0, 2, 3], ids=str)\n", (1695, 1726), False, 'import pytest\n'), ((2468, 2495), 'pytest.mark.require_ngpu', 'pytest.mark.require_ngpu', (['(2)'], {}), '(2)\n', (2492, 2495), False, 'import pytest\n'), ((2497, 2598), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""shape,symbolic"""', '[((2, 4, 6, 8), True), ((2, 4, 6, 8), False)]'], {'ids': 'str'}), "('shape,symbolic', [((2, 4, 6, 8), True), ((2, 4, 6,\n 8), False)], ids=str)\n", (2520, 2598), False, 'import pytest\n'), ((2602, 2656), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""axis"""', '[1, 0, 2, 3]'], {'ids': 'str'}), "('axis', [1, 0, 2, 3], ids=str)\n", (2625, 2656), False, 'import pytest\n'), ((3326, 3353), 'pytest.mark.require_ngpu', 'pytest.mark.require_ngpu', (['(2)'], {}), '(2)\n', (3350, 3353), False, 'import pytest\n'), ((3355, 3412), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""shape"""', '[(2, 4, 6, 8)]'], {'ids': 'str'}), "('shape', [(2, 4, 6, 8)], ids=str)\n", (3378, 3412), False, 'import pytest\n'), ((3414, 3473), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""symbolic"""', '[False, True]'], {'ids': 'str'}), "('symbolic', [False, True], ids=str)\n", (3437, 3473), False, 'import pytest\n'), ((3475, 3579), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""split_axis,concat_axis"""', '[(0, 1), (1, 0), (2, 0), (0, 2), (2, 3)]'], {'ids': 'str'}), "('split_axis,concat_axis', [(0, 1), (1, 0), (2, 0),\n (0, 2), (2, 3)], ids=str)\n", (3498, 3579), False, 'import pytest\n'), ((974, 997), 'megengine.distributed.launcher', 'dist.launcher', ([], {'n_gpus': '(2)'}), '(n_gpus=2)\n', (987, 997), True, 'import megengine.distributed as dist\n'), ((1438, 1471), 'numpy.concatenate', 'np.concatenate', (['(x, y)'], {'axis': 'axis'}), '((x, y), axis=axis)\n', (1452, 1471), True, 'import numpy as np\n'), ((1818, 1841), 'megengine.distributed.launcher', 'dist.launcher', ([], {'n_gpus': '(2)'}), '(n_gpus=2)\n', (1831, 1841), True, 'import megengine.distributed as dist\n'), ((2322, 2347), 'numpy.split', 'np.split', (['z', '(2)'], {'axis': 'axis'}), '(z, 2, axis=axis)\n', (2330, 2347), True, 'import numpy as np\n'), ((2356, 2381), 'numpy.concatenate', 'np.concatenate', (['z'], {'axis': '(0)'}), '(z, axis=0)\n', (2370, 2381), True, 'import numpy as np\n'), ((2737, 2760), 'megengine.distributed.launcher', 'dist.launcher', ([], {'n_gpus': '(2)'}), '(n_gpus=2)\n', (2750, 2760), True, 'import megengine.distributed as dist\n'), ((3174, 3199), 'numpy.split', 'np.split', (['x', '(2)'], {'axis': 'axis'}), '(x, 2, axis=axis)\n', (3182, 3199), True, 'import numpy as np\n'), ((3209, 3235), 'numpy.concatenate', 'np.concatenate', (['_x'], {'axis': '(0)'}), '(_x, axis=0)\n', (3223, 3235), True, 'import numpy as np\n'), ((3684, 3707), 'megengine.distributed.launcher', 'dist.launcher', ([], {'n_gpus': '(2)'}), '(n_gpus=2)\n', (3697, 3707), True, 'import megengine.distributed as dist\n'), ((1043, 1058), 'megengine.distributed.get_rank', 'dist.get_rank', ([], {}), '()\n', (1056, 1058), True, 'import megengine.distributed as dist\n'), ((1073, 1091), 'megengine.tensor', 'tensor', (['data[rank]'], {}), '(data[rank])\n', (1079, 1091), False, 'from megengine import tensor\n'), ((1887, 1902), 'megengine.distributed.get_rank', 'dist.get_rank', ([], {}), '()\n', (1900, 1902), True, 'import megengine.distributed as dist\n'), ((1917, 1935), 'megengine.tensor', 'tensor', (['data[rank]'], {}), '(data[rank])\n', (1923, 1935), False, 'from megengine import tensor\n'), ((2806, 2821), 'megengine.distributed.get_rank', 'dist.get_rank', ([], {}), '()\n', (2819, 2821), True, 'import megengine.distributed as dist\n'), ((2836, 2854), 'megengine.tensor', 'tensor', (['data[rank]'], {}), '(data[rank])\n', (2842, 2854), False, 'from megengine import tensor\n'), ((3745, 3760), 'megengine.distributed.get_rank', 'dist.get_rank', ([], {}), '()\n', (3758, 3760), True, 'import megengine.distributed as dist\n'), ((3775, 3793), 'megengine.tensor', 'tensor', (['data[rank]'], {}), '(data[rank])\n', (3781, 3793), False, 'from megengine import tensor\n'), ((1134, 1160), 'megengine.distributed.functional.all_gather', 'all_gather', (['inp'], {'axis': 'axis'}), '(inp, axis=axis)\n', (1144, 1160), False, 'from megengine.distributed.functional import all_gather, all_to_all, gather, reduce_scatter_sum, scatter\n'), ((1203, 1227), 'megengine.jit.trace', 'trace', ([], {'symbolic': 'symbolic'}), '(symbolic=symbolic)\n', (1208, 1227), False, 'from megengine.jit import trace\n'), ((1324, 1354), 'numpy.random.random_sample', 'np.random.random_sample', (['shape'], {}), '(shape)\n', (1347, 1354), True, 'import numpy as np\n'), ((1381, 1411), 'numpy.random.random_sample', 'np.random.random_sample', (['shape'], {}), '(shape)\n', (1404, 1411), True, 'import numpy as np\n'), ((1978, 2012), 'megengine.distributed.functional.reduce_scatter_sum', 'reduce_scatter_sum', (['inp'], {'axis': 'axis'}), '(inp, axis=axis)\n', (1996, 2012), False, 'from megengine.distributed.functional import all_gather, all_to_all, gather, reduce_scatter_sum, scatter\n'), ((2055, 2079), 'megengine.jit.trace', 'trace', ([], {'symbolic': 'symbolic'}), '(symbolic=symbolic)\n', (2060, 2079), False, 'from megengine.jit import trace\n'), ((2176, 2206), 'numpy.random.random_sample', 'np.random.random_sample', (['shape'], {}), '(shape)\n', (2199, 2206), True, 'import numpy as np\n'), ((2233, 2263), 'numpy.random.random_sample', 'np.random.random_sample', (['shape'], {}), '(shape)\n', (2256, 2263), True, 'import numpy as np\n'), ((2897, 2920), 'megengine.distributed.functional.scatter', 'scatter', (['inp'], {'axis': 'axis'}), '(inp, axis=axis)\n', (2904, 2920), False, 'from megengine.distributed.functional import all_gather, all_to_all, gather, reduce_scatter_sum, scatter\n'), ((2963, 2987), 'megengine.jit.trace', 'trace', ([], {'symbolic': 'symbolic'}), '(symbolic=symbolic)\n', (2968, 2987), False, 'from megengine.jit import trace\n'), ((3084, 3114), 'numpy.random.random_sample', 'np.random.random_sample', (['shape'], {}), '(shape)\n', (3107, 3114), True, 'import numpy as np\n'), ((3847, 3910), 'megengine.distributed.functional.all_to_all', 'all_to_all', (['inp'], {'split_axis': 'split_axis', 'concat_axis': 'concat_axis'}), '(inp, split_axis=split_axis, concat_axis=concat_axis)\n', (3857, 3910), False, 'from megengine.distributed.functional import all_gather, all_to_all, gather, reduce_scatter_sum, scatter\n'), ((3964, 3993), 'megengine.distributed.functional.gather', 'gather', (['inp'], {'axis': 'concat_axis'}), '(inp, axis=concat_axis)\n', (3970, 3993), False, 'from megengine.distributed.functional import all_gather, all_to_all, gather, reduce_scatter_sum, scatter\n'), ((4017, 4059), 'megengine.distributed.functional.gather', 'gather', (['all_to_all_output'], {'axis': 'split_axis'}), '(all_to_all_output, axis=split_axis)\n', (4023, 4059), False, 'from megengine.distributed.functional import all_gather, all_to_all, gather, reduce_scatter_sum, scatter\n'), ((4181, 4205), 'megengine.jit.trace', 'trace', ([], {'symbolic': 'symbolic'}), '(symbolic=symbolic)\n', (4186, 4205), False, 'from megengine.jit import trace\n'), ((4274, 4301), 'numpy.allclose', 'np.allclose', (['ret[0]', 'ret[1]'], {}), '(ret[0], ret[1])\n', (4285, 4301), True, 'import numpy as np\n'), ((4311, 4341), 'numpy.random.random_sample', 'np.random.random_sample', (['shape'], {}), '(shape)\n', (4334, 4341), True, 'import numpy as np\n'), ((4368, 4398), 'numpy.random.random_sample', 'np.random.random_sample', (['shape'], {}), '(shape)\n', (4391, 4398), True, 'import numpy as np\n')]
import numpy as np import megengine as mge import megengine.functional as F from common import se3, so3 def compute_losses(data_batch, endpoints, params): loss = {} # compute losses if params.loss_type == "omnet": num_iter = len(endpoints["all_pose_pair"]) for i in range(num_iter): # mask loss src_cls_pair, ref_cls_pair = endpoints["all_src_cls_pair"][i], endpoints["all_ref_cls_pair"][i] src_cls = F.nn.frequency_weighted_cross_entropy(src_cls_pair[1], src_cls_pair[0], weight=mge.tensor([0.7, 0.3])) ref_cls = F.nn.frequency_weighted_cross_entropy(ref_cls_pair[1], ref_cls_pair[0], weight=mge.tensor([0.7, 0.3])) loss["cls_{}".format(i)] = (src_cls + ref_cls) / 2.0 # reg loss pose_pair = endpoints["all_pose_pair"][i] loss["quat_{}".format(i)] = F.nn.l1_loss(pose_pair[1][:, :4], pose_pair[0][:, :4]) * params.loss_alpha1 loss["translate_{}".format(i)] = F.nn.square_loss(pose_pair[1][:, 4:], pose_pair[0][:, 4:]) * params.loss_alpha2 # total loss total_losses = [] for k in loss: total_losses.append(loss[k]) loss["total"] = F.sum(F.concat(total_losses)) else: raise NotImplementedError return loss def compute_metrics(data_batch, endpoints, params): metrics = {} gt_transforms = endpoints["transform_pair"][0] pred_transforms = endpoints["transform_pair"][1] # Euler angles, Individual translation errors (Deep Closest Point convention) if "prnet" in params.transform_type: r_gt_euler_deg = so3.mge_dcm2euler(gt_transforms[:, :3, :3], seq="zyx") r_pred_euler_deg = so3.mge_dcm2euler(pred_transforms[:, :3, :3], seq="zyx") else: r_gt_euler_deg = so3.mge_dcm2euler(gt_transforms[:, :3, :3], seq="xyz") r_pred_euler_deg = so3.mge_dcm2euler(pred_transforms[:, :3, :3], seq="xyz") t_gt = gt_transforms[:, :3, 3] t_pred = pred_transforms[:, :3, 3] r_mse = F.mean((r_gt_euler_deg - r_pred_euler_deg)**2, axis=1) r_mae = F.mean(F.abs(r_gt_euler_deg - r_pred_euler_deg), axis=1) t_mse = F.mean((t_gt - t_pred)**2, axis=1) t_mae = F.mean(F.abs(t_gt - t_pred), axis=1) r_mse = F.mean(r_mse) t_mse = F.mean(t_mse) r_mae = F.mean(r_mae) t_mae = F.mean(t_mae) # Rotation, translation errors (isotropic, i.e. doesn"t depend on error # direction, which is more representative of the actual error) concatenated = se3.mge_concatenate(se3.mge_inverse(gt_transforms), pred_transforms) rot_trace = concatenated[:, 0, 0] + concatenated[:, 1, 1] + concatenated[:, 2, 2] residual_rotdeg = F.acos(F.clip(0.5 * (rot_trace - 1), -1.0, 1.0)) * 180.0 / np.pi residual_transmag = F.norm(concatenated[:, :, 3], axis=-1) err_r = F.mean(residual_rotdeg) err_t = F.mean(residual_transmag) # weighted score of isotropic errors score = err_r * 0.01 + err_t metrics = {"R_MSE": r_mse, "R_MAE": r_mae, "t_MSE": t_mse, "t_MAE": t_mae, "Err_R": err_r, "Err_t": err_t, "score": score} # metrics = utils.tensor_mge(metrics, check_on=False) return metrics
[ "megengine.tensor", "megengine.functional.nn.l1_loss", "megengine.functional.clip", "megengine.functional.nn.square_loss", "megengine.functional.mean", "megengine.functional.norm", "megengine.functional.abs", "megengine.functional.concat" ]
[((2027, 2083), 'megengine.functional.mean', 'F.mean', (['((r_gt_euler_deg - r_pred_euler_deg) ** 2)'], {'axis': '(1)'}), '((r_gt_euler_deg - r_pred_euler_deg) ** 2, axis=1)\n', (2033, 2083), True, 'import megengine.functional as F\n'), ((2163, 2199), 'megengine.functional.mean', 'F.mean', (['((t_gt - t_pred) ** 2)'], {'axis': '(1)'}), '((t_gt - t_pred) ** 2, axis=1)\n', (2169, 2199), True, 'import megengine.functional as F\n'), ((2260, 2273), 'megengine.functional.mean', 'F.mean', (['r_mse'], {}), '(r_mse)\n', (2266, 2273), True, 'import megengine.functional as F\n'), ((2286, 2299), 'megengine.functional.mean', 'F.mean', (['t_mse'], {}), '(t_mse)\n', (2292, 2299), True, 'import megengine.functional as F\n'), ((2312, 2325), 'megengine.functional.mean', 'F.mean', (['r_mae'], {}), '(r_mae)\n', (2318, 2325), True, 'import megengine.functional as F\n'), ((2338, 2351), 'megengine.functional.mean', 'F.mean', (['t_mae'], {}), '(t_mae)\n', (2344, 2351), True, 'import megengine.functional as F\n'), ((2781, 2819), 'megengine.functional.norm', 'F.norm', (['concatenated[:, :, 3]'], {'axis': '(-1)'}), '(concatenated[:, :, 3], axis=-1)\n', (2787, 2819), True, 'import megengine.functional as F\n'), ((2832, 2855), 'megengine.functional.mean', 'F.mean', (['residual_rotdeg'], {}), '(residual_rotdeg)\n', (2838, 2855), True, 'import megengine.functional as F\n'), ((2868, 2893), 'megengine.functional.mean', 'F.mean', (['residual_transmag'], {}), '(residual_transmag)\n', (2874, 2893), True, 'import megengine.functional as F\n'), ((1627, 1681), 'common.so3.mge_dcm2euler', 'so3.mge_dcm2euler', (['gt_transforms[:, :3, :3]'], {'seq': '"""zyx"""'}), "(gt_transforms[:, :3, :3], seq='zyx')\n", (1644, 1681), False, 'from common import se3, so3\n'), ((1709, 1765), 'common.so3.mge_dcm2euler', 'so3.mge_dcm2euler', (['pred_transforms[:, :3, :3]'], {'seq': '"""zyx"""'}), "(pred_transforms[:, :3, :3], seq='zyx')\n", (1726, 1765), False, 'from common import se3, so3\n'), ((1801, 1855), 'common.so3.mge_dcm2euler', 'so3.mge_dcm2euler', (['gt_transforms[:, :3, :3]'], {'seq': '"""xyz"""'}), "(gt_transforms[:, :3, :3], seq='xyz')\n", (1818, 1855), False, 'from common import se3, so3\n'), ((1883, 1939), 'common.so3.mge_dcm2euler', 'so3.mge_dcm2euler', (['pred_transforms[:, :3, :3]'], {'seq': '"""xyz"""'}), "(pred_transforms[:, :3, :3], seq='xyz')\n", (1900, 1939), False, 'from common import se3, so3\n'), ((2101, 2141), 'megengine.functional.abs', 'F.abs', (['(r_gt_euler_deg - r_pred_euler_deg)'], {}), '(r_gt_euler_deg - r_pred_euler_deg)\n', (2106, 2141), True, 'import megengine.functional as F\n'), ((2217, 2237), 'megengine.functional.abs', 'F.abs', (['(t_gt - t_pred)'], {}), '(t_gt - t_pred)\n', (2222, 2237), True, 'import megengine.functional as F\n'), ((2535, 2565), 'common.se3.mge_inverse', 'se3.mge_inverse', (['gt_transforms'], {}), '(gt_transforms)\n', (2550, 2565), False, 'from common import se3, so3\n'), ((1219, 1241), 'megengine.functional.concat', 'F.concat', (['total_losses'], {}), '(total_losses)\n', (1227, 1241), True, 'import megengine.functional as F\n'), ((877, 931), 'megengine.functional.nn.l1_loss', 'F.nn.l1_loss', (['pose_pair[1][:, :4]', 'pose_pair[0][:, :4]'], {}), '(pose_pair[1][:, :4], pose_pair[0][:, :4])\n', (889, 931), True, 'import megengine.functional as F\n'), ((998, 1056), 'megengine.functional.nn.square_loss', 'F.nn.square_loss', (['pose_pair[1][:, 4:]', 'pose_pair[0][:, 4:]'], {}), '(pose_pair[1][:, 4:], pose_pair[0][:, 4:])\n', (1014, 1056), True, 'import megengine.functional as F\n'), ((2699, 2739), 'megengine.functional.clip', 'F.clip', (['(0.5 * (rot_trace - 1))', '(-1.0)', '(1.0)'], {}), '(0.5 * (rot_trace - 1), -1.0, 1.0)\n', (2705, 2739), True, 'import megengine.functional as F\n'), ((546, 568), 'megengine.tensor', 'mge.tensor', (['[0.7, 0.3]'], {}), '([0.7, 0.3])\n', (556, 568), True, 'import megengine as mge\n'), ((671, 693), 'megengine.tensor', 'mge.tensor', (['[0.7, 0.3]'], {}), '([0.7, 0.3])\n', (681, 693), True, 'import megengine as mge\n')]
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2020 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # pylint: disable=import-error,no-name-in-module,no-member from test.utils import LinearOpr import megengine as mge import megengine.module as M import numpy as np from megengine.core.tensor import dtype from megengine.core.tensor.dtype import _builtin_quant_dtypes from megengine.module.quant_dequant import QuantStub from megengine.quantization.quantize import quantize_qat from megengine.quantization.utils import create_qparams from megengine.traced_module.fake_quant import FakeQuantize from .test_caffe import _test_convert_result from .tm_utils import get_traced_module max_err = 1e-6 def get_qat_net(inp_dtype, net, num_inp=1, shape=(1, 16, 32, 32)): qat_net = quantize_qat(net) inps = [] for _ in range(num_inp): data1 = mge.tensor(np.random.random(shape)) * 16 data1 = data1.astype(inp_dtype) inp1 = mge.tensor(dtype.convert_from_qint8(data1.numpy())) inp1.qparams.scale = mge.tensor(dtype.get_scale(inp_dtype)) inp1.qparams.dtype_meta = dtype._builtin_quant_dtypes["qint8"] inps.append(inp1) return qat_net, inps def get_qat_inputs_quint8(inp_dtype, num_inp=1, shape=(1, 16, 384, 512)): inps = [] for _ in range(num_inp): data1 = mge.tensor(np.random.random(shape)) * 16 data1 = data1.astype(inp_dtype) inp1 = mge.tensor(dtype.convert_from_quint8(data1.numpy())) inp1.qparams.scale = mge.tensor(dtype.get_scale(inp_dtype)) inp1.qparams.zero_point = mge.tensor(dtype.get_zero_point(inp_dtype)) inp1.qparams.dtype_meta = dtype._builtin_quant_dtypes["quint8"] inps.append(inp1) return inps def test_linear(): net = LinearOpr() inp_dtype = dtype.qint8(16.0 / 128.0) qat_net, inps = get_qat_net(inp_dtype, net, shape=(10, 100)) traced_module, tm_result = get_traced_module(qat_net, inps[0]) inp = inps[0].astype(inp_dtype) _test_convert_result(inp, traced_module, tm_result, max_err, require_quantize=False) def test_add(): class ElemwiseOpr(M.Module): def __init__(self,): super().__init__() self.data = np.ones((2, 3, 224, 224)).astype(np.float32) self.data1 = np.random.random((1, 3, 1, 1)).astype(np.float32) self.add1 = M.Elemwise("add") self.add2 = M.Elemwise("add") self.add3 = M.Elemwise("add") scale = mge.tensor((16.0 / 128.0)) self.quant_stub = QuantStub() self.quant_stub.act_fake_quant = FakeQuantize( _builtin_quant_dtypes["qint8"] ) self.quant_stub.act_fake_quant.set_qparams( create_qparams( dtype_meta=_builtin_quant_dtypes["qint8"], scale=scale, zero_point=None, ) ) self.quant_stub1 = QuantStub() self.quant_stub1.act_fake_quant = FakeQuantize( _builtin_quant_dtypes["qint8"] ) self.quant_stub1.act_fake_quant.set_qparams( create_qparams( dtype_meta=_builtin_quant_dtypes["qint8"], scale=scale, zero_point=None, ) ) def forward(self, a): n = self.quant_stub(mge.tensor(np.float32(10))) data1 = self.quant_stub1(mge.tensor(self.data1)) x = self.add1(a, n) y = self.add2(a, data1) z = self.add3(x, y) return z net = ElemwiseOpr() inp_dtype = dtype.qint8(16.0 / 128.0) qat_net, inps = get_qat_net(inp_dtype, net, shape=(1, 3, 1, 1)) traced_module, tm_result = get_traced_module(qat_net, inps[0]) print(traced_module.flatten().graph) inp = inps[0].astype(inp_dtype) _test_convert_result( inp, traced_module, tm_result, max_err, require_quantize=False, split_conv_relu=True, ) def test_det_model(): net = mge.load("models_fire_det.fix_batch.fuse_scale_cpu.pkl") inp_dtype = dtype.qint8(16.0 / 128.0) qat_net, inps = get_qat_net(inp_dtype, net, shape=(1, 3, 512, 512)) traced_module, tm_result = get_traced_module(qat_net, inps[0]) inp = inps[0].astype(inp_dtype) _test_convert_result(inp, traced_module, tm_result, max_err, require_quantize=False) def test_snpe_model_8f(): model = "8w16f_backbone.tm" net = mge.load(model) print(net.flatten().graph) inp_dtype = dtype.quint8(16.0 / 128.0, 128) inps = get_qat_inputs_quint8(inp_dtype, num_inp=2, shape=(1, 16, 384, 512)) tm_result = dict(zip(net.graph.outputs, net(*inps))) _test_convert_result( inps, net, tm_result, max_err, input_data_type="quint8", input_scales=inps[0].qparams.scale, input_zero_points=inps[0].qparams.zero_point, require_quantize=False, param_fake_quant=True, split_conv_relu=True, input_name=["inp", "prev"], )
[ "megengine.core.tensor.dtype.get_scale", "megengine.quantization.quantize.quantize_qat", "megengine.tensor", "megengine.core.tensor.dtype.get_zero_point", "megengine.core.tensor.dtype.qint8", "megengine.core.tensor.dtype.quint8", "megengine.module.quant_dequant.QuantStub", "megengine.quantization.utils.create_qparams", "megengine.module.Elemwise", "megengine.traced_module.fake_quant.FakeQuantize", "megengine.load" ]
[((1033, 1050), 'megengine.quantization.quantize.quantize_qat', 'quantize_qat', (['net'], {}), '(net)\n', (1045, 1050), False, 'from megengine.quantization.quantize import quantize_qat\n'), ((2023, 2034), 'test.utils.LinearOpr', 'LinearOpr', ([], {}), '()\n', (2032, 2034), False, 'from test.utils import LinearOpr\n'), ((2051, 2076), 'megengine.core.tensor.dtype.qint8', 'dtype.qint8', (['(16.0 / 128.0)'], {}), '(16.0 / 128.0)\n', (2062, 2076), False, 'from megengine.core.tensor import dtype\n'), ((3910, 3935), 'megengine.core.tensor.dtype.qint8', 'dtype.qint8', (['(16.0 / 128.0)'], {}), '(16.0 / 128.0)\n', (3921, 3935), False, 'from megengine.core.tensor import dtype\n'), ((4348, 4404), 'megengine.load', 'mge.load', (['"""models_fire_det.fix_batch.fuse_scale_cpu.pkl"""'], {}), "('models_fire_det.fix_batch.fuse_scale_cpu.pkl')\n", (4356, 4404), True, 'import megengine as mge\n'), ((4421, 4446), 'megengine.core.tensor.dtype.qint8', 'dtype.qint8', (['(16.0 / 128.0)'], {}), '(16.0 / 128.0)\n', (4432, 4446), False, 'from megengine.core.tensor import dtype\n'), ((4781, 4796), 'megengine.load', 'mge.load', (['model'], {}), '(model)\n', (4789, 4796), True, 'import megengine as mge\n'), ((4844, 4875), 'megengine.core.tensor.dtype.quint8', 'dtype.quint8', (['(16.0 / 128.0)', '(128)'], {}), '(16.0 / 128.0, 128)\n', (4856, 4875), False, 'from megengine.core.tensor import dtype\n'), ((1298, 1324), 'megengine.core.tensor.dtype.get_scale', 'dtype.get_scale', (['inp_dtype'], {}), '(inp_dtype)\n', (1313, 1324), False, 'from megengine.core.tensor import dtype\n'), ((1772, 1798), 'megengine.core.tensor.dtype.get_scale', 'dtype.get_scale', (['inp_dtype'], {}), '(inp_dtype)\n', (1787, 1798), False, 'from megengine.core.tensor import dtype\n'), ((1845, 1876), 'megengine.core.tensor.dtype.get_zero_point', 'dtype.get_zero_point', (['inp_dtype'], {}), '(inp_dtype)\n', (1865, 1876), False, 'from megengine.core.tensor import dtype\n'), ((2613, 2630), 'megengine.module.Elemwise', 'M.Elemwise', (['"""add"""'], {}), "('add')\n", (2623, 2630), True, 'import megengine.module as M\n'), ((2655, 2672), 'megengine.module.Elemwise', 'M.Elemwise', (['"""add"""'], {}), "('add')\n", (2665, 2672), True, 'import megengine.module as M\n'), ((2697, 2714), 'megengine.module.Elemwise', 'M.Elemwise', (['"""add"""'], {}), "('add')\n", (2707, 2714), True, 'import megengine.module as M\n'), ((2736, 2760), 'megengine.tensor', 'mge.tensor', (['(16.0 / 128.0)'], {}), '(16.0 / 128.0)\n', (2746, 2760), True, 'import megengine as mge\n'), ((2793, 2804), 'megengine.module.quant_dequant.QuantStub', 'QuantStub', ([], {}), '()\n', (2802, 2804), False, 'from megengine.module.quant_dequant import QuantStub\n'), ((2850, 2894), 'megengine.traced_module.fake_quant.FakeQuantize', 'FakeQuantize', (["_builtin_quant_dtypes['qint8']"], {}), "(_builtin_quant_dtypes['qint8'])\n", (2862, 2894), False, 'from megengine.traced_module.fake_quant import FakeQuantize\n'), ((3209, 3220), 'megengine.module.quant_dequant.QuantStub', 'QuantStub', ([], {}), '()\n', (3218, 3220), False, 'from megengine.module.quant_dequant import QuantStub\n'), ((3267, 3311), 'megengine.traced_module.fake_quant.FakeQuantize', 'FakeQuantize', (["_builtin_quant_dtypes['qint8']"], {}), "(_builtin_quant_dtypes['qint8'])\n", (3279, 3311), False, 'from megengine.traced_module.fake_quant import FakeQuantize\n'), ((1121, 1144), 'numpy.random.random', 'np.random.random', (['shape'], {}), '(shape)\n', (1137, 1144), True, 'import numpy as np\n'), ((1594, 1617), 'numpy.random.random', 'np.random.random', (['shape'], {}), '(shape)\n', (1610, 1617), True, 'import numpy as np\n'), ((2997, 3088), 'megengine.quantization.utils.create_qparams', 'create_qparams', ([], {'dtype_meta': "_builtin_quant_dtypes['qint8']", 'scale': 'scale', 'zero_point': 'None'}), "(dtype_meta=_builtin_quant_dtypes['qint8'], scale=scale,\n zero_point=None)\n", (3011, 3088), False, 'from megengine.quantization.utils import create_qparams\n'), ((3415, 3506), 'megengine.quantization.utils.create_qparams', 'create_qparams', ([], {'dtype_meta': "_builtin_quant_dtypes['qint8']", 'scale': 'scale', 'zero_point': 'None'}), "(dtype_meta=_builtin_quant_dtypes['qint8'], scale=scale,\n zero_point=None)\n", (3429, 3506), False, 'from megengine.quantization.utils import create_qparams\n'), ((3724, 3746), 'megengine.tensor', 'mge.tensor', (['self.data1'], {}), '(self.data1)\n', (3734, 3746), True, 'import megengine as mge\n'), ((2469, 2494), 'numpy.ones', 'np.ones', (['(2, 3, 224, 224)'], {}), '((2, 3, 224, 224))\n', (2476, 2494), True, 'import numpy as np\n'), ((2539, 2569), 'numpy.random.random', 'np.random.random', (['(1, 3, 1, 1)'], {}), '((1, 3, 1, 1))\n', (2555, 2569), True, 'import numpy as np\n'), ((3670, 3684), 'numpy.float32', 'np.float32', (['(10)'], {}), '(10)\n', (3680, 3684), True, 'import numpy as np\n')]