1# Copyright 2020 Huawei Technologies Co., Ltd 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# ============================================================================ 15"""Utility functions to help distribution class.""" 16import numpy as np 17from mindspore.ops import operations as P 18from mindspore.common import dtype as mstype 19 20 21def exp_generic(input_x): 22 """ 23 Log op on Ascend doesn't support int types. 24 Fix this with casting the type. 25 """ 26 exp = P.Exp() 27 cast = P.Cast() 28 dtype = P.DType() 29 checktype = P.IsSubClass() 30 31 if not checktype(dtype(input_x), mstype.float_): 32 input_x = cast(input_x, mstype.float32) 33 return exp(input_x) 34 35 36def log_generic(input_x): 37 """ 38 Log op on Ascend is calculated as log(abs(x)). 39 Fix this with putting negative values as nan. 40 And log op on Ascend doesn't support int types. 41 Fix this with casting the type. 42 """ 43 log = P.Log() 44 less = P.Less() 45 lessequal = P.LessEqual() 46 fill = P.Fill() 47 cast = P.Cast() 48 dtype = P.DType() 49 shape = P.Shape() 50 select = P.Select() 51 checktype = P.IsSubClass() 52 53 if not checktype(dtype(input_x), mstype.float_): 54 input_x = cast(input_x, mstype.float32) 55 nan = fill(dtype(input_x), shape(input_x), np.nan) 56 inf = fill(dtype(input_x), shape(input_x), np.inf) 57 neg_x = less(input_x, 0.0) 58 nonpos_x = lessequal(input_x, 0.0) 59 log_x = log(input_x) 60 result = select(nonpos_x, -inf, log_x) 61 return select(neg_x, nan, result) 62 63 64def log1p_generic(x): 65 """ 66 Log1p ops on GPU device or when device_target == GPU. 67 """ 68 return log_generic(x + 1.0) 69 70 71def broadcast_to(x, target): 72 """ 73 Broadcast x to the shape of target. 74 """ 75 shape = P.Shape() 76 if shape(x) == shape(target): 77 return x 78 return P.BroadcastTo(shape(target))(x) 79