MindSpore代码评注 #32
|
|
@ -19,6 +19,12 @@
|
|||
#include <vector>
|
||||
#include "utils/hashing.h"
|
||||
|
||||
"""
|
||||
这段代码定义了'mindspore'和'abstract'两个命名空间,以及
|
||||
'Evaluator','Ana'和'AbstractFunction'三个类的部分实现;其中
|
||||
'AbstractFunction'类包含一个静态成员函数'MakeAbstractFunction'
|
||||
用于构建'AbstractFunction'实例
|
||||
"""
|
||||
namespace mindspore {
|
||||
namespace abstract {
|
||||
class Evaluator;
|
||||
|
|
@ -30,6 +36,12 @@ AbstractFunctionPtr AbstractFunction::MakeAbstractFunction(const AbstractFuncAto
|
|||
return std::make_shared<AbstractFuncUnion>(func_list);
|
||||
}
|
||||
|
||||
"""
|
||||
'AbstractFuncAtom'类的成员函数Join用于将两个抽象函数合并为一个新的抽象函数。
|
||||
它首先检查other是否是AbstractFuncAtom类型的实例,如果是,则根据两个对象是否相等来决定返回当前对象或者创建一个新的AbstractFuncUnion实例。
|
||||
如果other不是AbstractFuncAtom类型的实例,则尝试将其转换为AbstractFuncUnion类型,并根据当前对象是否是other_union的超集来决定返回other
|
||||
或者创建一个新的AbstractFuncUnion实例。
|
||||
"""
|
||||
AbstractFunctionPtr AbstractFuncAtom::Join(const AbstractFunctionPtr &other) {
|
||||
MS_EXCEPTION_IF_NULL(other);
|
||||
auto this_func = shared_from_base<AbstractFuncAtom>();
|
||||
|
|
@ -55,6 +67,11 @@ bool AbstractFuncAtom::operator==(const AbstractFunction &other) const { return
|
|||
|
||||
AbstractFuncUnion::AbstractFuncUnion(const AbstractFuncAtomPtrList &func_list) { func_list_ = func_list; }
|
||||
|
||||
"""
|
||||
这段代码的作用是将AbstractFuncUnion类的构造函数用于创建抽象函数联合对象,
|
||||
将两个抽象函数的智能指针作为参数,然后通过遍历这两个抽象函数,
|
||||
将其中的AbstractFuncAtomPtr类型的指针存储在func_list_成员变量中
|
||||
"""
|
||||
AbstractFuncUnion::AbstractFuncUnion(const AbstractFunctionPtr &first, const AbstractFunctionPtr &second) {
|
||||
AbstractFuncAtomPtrList new_func_list;
|
||||
auto build_func_list = [&new_func_list](const AbstractFuncAtomPtr &func) { new_func_list.push_back(func); };
|
||||
|
|
@ -64,7 +81,12 @@ AbstractFuncUnion::AbstractFuncUnion(const AbstractFunctionPtr &first, const Abs
|
|||
second->Visit(build_func_list);
|
||||
func_list_ = new_func_list;
|
||||
}
|
||||
|
||||
|
||||
"""
|
||||
AbstractFuncUnion类的成员函数ToString用于将抽象函数联合对象的信息转换为字符串形式。
|
||||
它首先创建一个std::ostringstream对象,并使用循环遍历func_list_容器中的每个元素,将元素的信息拼接到buffer中。
|
||||
最后,将buffer转换为std::string类型,并返回该字符串
|
||||
"""
|
||||
std::string AbstractFuncUnion::ToString() const {
|
||||
std::ostringstream buffer;
|
||||
buffer << "AbstractFuncUnion({";
|
||||
|
|
@ -78,6 +100,11 @@ std::string AbstractFuncUnion::ToString() const {
|
|||
return buffer.str();
|
||||
}
|
||||
|
||||
"""
|
||||
AbstractFuncUnion类的成员函数ToString的重载实现用于将抽象函数联合对象的信息转换为字符串形式。
|
||||
如果verbose参数为true,则直接调用默认版本的ToString函数,打印所有抽象函数的详细信息。
|
||||
如果verbose参数为false,则只打印联合的类型名称和每个抽象函数的基本信息,并在元素之间添加逗号和空格
|
||||
"""
|
||||
std::string AbstractFuncUnion::ToString(bool verbose) const {
|
||||
if (verbose) {
|
||||
return ToString();
|
||||
|
|
@ -97,6 +124,11 @@ std::string AbstractFuncUnion::ToString(bool verbose) const {
|
|||
return buffer.str();
|
||||
}
|
||||
|
||||
"""
|
||||
AbstractFuncUnion类的成员函数IsSuperSet用于判断当前的抽象函数联合对象是否包含另一个抽象函数对象的所有成员函数。
|
||||
它通过遍历other中的每个成员函数,判断其是否存在于当前的抽象函数联合对象的func_list_中,
|
||||
并最终返回一个布尔值,表示是否是other的超集。
|
||||
"""
|
||||
bool AbstractFuncUnion::IsSuperSet(const AbstractFunctionPtr &other) {
|
||||
MS_EXCEPTION_IF_NULL(other);
|
||||
std::vector<bool> is_in_list;
|
||||
|
|
@ -111,6 +143,14 @@ bool AbstractFuncUnion::IsSuperSet(const AbstractFunctionPtr &other) {
|
|||
return std::all_of(is_in_list.begin(), is_in_list.end(), [](bool is_in) { return is_in; });
|
||||
}
|
||||
|
||||
|
||||
"""
|
||||
AbstractFuncUnion类的成员函数Join用于将两个抽象函数对象合并成一个新的抽象函数对象。
|
||||
如果other是AbstractFuncAtom类型的对象且当前的AbstractFuncUnion对象包含了other中的所有成员函数,
|
||||
则返回当前的AbstractFuncUnion对象;否则,创建一个新的AbstractFuncUnion对象,
|
||||
并将this_func和other作为参数传递给构造函数。如果other不是AbstractFuncAtom类型的对象,
|
||||
则尝试将其转换为AbstractFuncUnion类型,并进行类似的检查
|
||||
"""
|
||||
AbstractFunctionPtr AbstractFuncUnion::Join(const AbstractFunctionPtr &other) {
|
||||
auto this_func = shared_from_base<AbstractFunction>();
|
||||
MS_EXCEPTION_IF_NULL(other);
|
||||
|
|
@ -134,6 +174,12 @@ void AbstractFuncUnion::Visit(std::function<void(const AbstractFuncAtomPtr &)> v
|
|||
}
|
||||
}
|
||||
|
||||
"""
|
||||
AbstractFuncUnion类的operator==运算符的重载实现用于判断两个抽象函数对象是否相等。
|
||||
首先检查other是否是AbstractFuncUnion类型的对象,如果不是则直接返回false。
|
||||
然后比较两个抽象函数对象的成员函数数量是否相同,如果不同则返回false。
|
||||
最后,通过比较两个抽象函数对象的成员函数列表是否相等来判断它们是否相等。
|
||||
"""
|
||||
bool AbstractFuncUnion::operator==(const AbstractFunction &other) const {
|
||||
if (!other.isa<AbstractFuncUnion>()) {
|
||||
return false;
|
||||
|
|
@ -145,6 +191,11 @@ bool AbstractFuncUnion::operator==(const AbstractFunction &other) const {
|
|||
return func_list_ == other_union->func_list_;
|
||||
}
|
||||
|
||||
"""
|
||||
AbstractFuncUnion类的成员函数hash用于计算抽象函数联合对象的哈希值。
|
||||
它通过循环遍历联合中的每个成员函数,将每个成员函数的哈希值与之前累积的哈希值进行组合,
|
||||
从而得到最终的哈希值,用于快速查找和比较。
|
||||
"""
|
||||
std::size_t AbstractFuncUnion::hash() const {
|
||||
std::size_t hash_sum = 0;
|
||||
for (const auto &f : func_list_) {
|
||||
|
|
@ -154,6 +205,12 @@ std::size_t AbstractFuncUnion::hash() const {
|
|||
return hash_sum;
|
||||
}
|
||||
|
||||
"""
|
||||
PrimitiveAbstractClosure类的operator==运算符的重载实现用于判断两个原语抽象闭包对象是否相等。
|
||||
首先检查other是否是原语抽象闭包类型的对象,如果不是则直接返回false。
|
||||
然后比较两个原语抽象闭包对象的prim_和tracking_id()成员变量是否相等,
|
||||
如果都相等,则返回true,表示两个原语抽象闭包对象相等;否则返回false,表示两个原语抽象闭包对象不相等。
|
||||
"""
|
||||
bool PrimitiveAbstractClosure::operator==(const AbstractFunction &other) const {
|
||||
if (!other.isa<PrimitiveAbstractClosure>()) {
|
||||
return false;
|
||||
|
|
@ -162,6 +219,11 @@ bool PrimitiveAbstractClosure::operator==(const AbstractFunction &other) const {
|
|||
return (prim_ == other_abs.prim_) && (tracking_id() == other_abs.tracking_id());
|
||||
}
|
||||
|
||||
"""
|
||||
PrimitiveAbstractClosure类的成员函数hash用于计算原语抽象闭包对象的哈希值。
|
||||
它通过将跟踪ID(tid())、原语操作符指针(prim_)以及跟踪ID节点指针(tracking_id())的哈希值进行组合,得到最终的哈希值,用于快速查找和比较。
|
||||
在计算哈希值时,保持与operator==运算符实现的比较条件相一致,以确保哈希值和相等性的定义是一致的
|
||||
"""
|
||||
std::size_t PrimitiveAbstractClosure::hash() const {
|
||||
// Keep in sync with operator==() which compares tid, prim_ & tracking_id;
|
||||
auto hash_value = static_cast<std::size_t>(tid());
|
||||
|
|
@ -231,6 +293,14 @@ std::size_t MetaFuncGraphAbstractClosure::hash() const {
|
|||
return hash_value;
|
||||
}
|
||||
|
||||
"""
|
||||
MetaFuncGraphAbstractClosure类的成员函数ToString用于返回一个描述元函数图抽象闭包的字符串。
|
||||
PartialAbstractClosure类的operator==运算符的重载实现用于判断两个部分抽象闭包对象是否相等。
|
||||
首先检查other是否是部分抽象闭包类型的对象,如果不是则直接返回false。
|
||||
然后比较两个部分抽象闭包对象的fn_成员变量是否相等,以及args_spec_list_成员变量的大小是否相等。
|
||||
最后,比较args_spec_list_成员变量是否相等:
|
||||
如果相等则返回true,表示两个部分抽象闭包对象相等;否则返回false,表示两个部分抽象闭包对象不相等
|
||||
"""
|
||||
std::string MetaFuncGraphAbstractClosure::ToString() const {
|
||||
MS_EXCEPTION_IF_NULL(meta_func_graph_);
|
||||
return "MetaFuncGraphAbstractClosure: " + meta_func_graph_->name();
|
||||
|
|
@ -257,6 +327,12 @@ std::size_t PartialAbstractClosure::hash() const {
|
|||
return hash_value;
|
||||
}
|
||||
|
||||
"""
|
||||
PartialAbstractClosure类的成员函数 ToString 用于返回部分抽象闭包对象的字符串表示。
|
||||
它通过遍历 args_spec_list_ 容器中的每个成员对象,将函数对象的字符串表示和参数的字符串表示连接起来,最终得到部分抽象闭包对象的完整字符串表示。
|
||||
在处理参数对象时,如果对象是 AbstractFuncAtom 类型的,则直接获取其类型名;否则,获取对象的字符串表示。
|
||||
返回的字符串形如 "PartialAbstractClosure(fn_name(arg1, arg2, ...))",其中 fn_name 是函数对象的名称,arg1、arg2 等是参数对象的字符串表示
|
||||
"""
|
||||
std::string PartialAbstractClosure::ToString() const {
|
||||
std::ostringstream buffer;
|
||||
buffer << "PartialAbstractClosure(" << fn_->ToString() << "(";
|
||||
|
|
@ -363,6 +439,14 @@ std::size_t VirtualAbstractClosure::hash() const {
|
|||
return hash_value;
|
||||
}
|
||||
|
||||
"""
|
||||
VirtualAbstractClosure类的成员函数ToString用于返回虚函数抽象闭包对象的字符串表示。
|
||||
它通过遍历args_spec_list_容器中的每个参数对象,将参数对象的位置和类型名或字符串表示连接起来,最终得到虚函数抽象闭包对象的参数部分的字符串表示。
|
||||
在处理参数对象时,如果对象是AbstractFuncAtom类型的,则直接获取其类型名;否则,获取对象的字符串表示。
|
||||
最后,将参数部分的字符串表示和输出对象的字符串表示连接起来,返回虚函数抽象闭包对象的完整字符串表示。
|
||||
返回的字符串形如 "VirtualAbstractClosure(args: {[0]: arg1, [1]: arg2, ...}, output: output_obj)",
|
||||
其中 arg1、arg2 等是参数对象的字符串表示,output_obj 是输出对象的字符串表示
|
||||
"""
|
||||
std::string VirtualAbstractClosure::ToString() const {
|
||||
std::ostringstream buffer;
|
||||
buffer << "VirtualAbstractClosure(args: {";
|
||||
|
|
@ -383,6 +467,13 @@ std::string VirtualAbstractClosure::ToString() const {
|
|||
return buffer.str();
|
||||
}
|
||||
|
||||
"""
|
||||
TypedPrimitiveAbstractClosure类的operator==运算符的重载实现用于判断两个类型化原语抽象闭包对象是否相等。
|
||||
首先检查other是否是类型化原语抽象闭包类型的对象,如果不是则直接返回false。
|
||||
然后比较两个类型化原语抽象闭包对象的output_和prim_成员变量是否相等,以及args_spec_list_成员变量的大小是否相等。
|
||||
最后,比较args_spec_list_成员变量是否相等,如果相等则返回true,表示两个类型化原语抽象闭包对象相等;
|
||||
否则返回false,表示两个类型化原语抽象闭包对象不相等
|
||||
"""
|
||||
bool TypedPrimitiveAbstractClosure::operator==(const AbstractFunction &other) const {
|
||||
if (!other.isa<TypedPrimitiveAbstractClosure>()) {
|
||||
return false;
|
||||
|
|
@ -406,6 +497,14 @@ std::size_t TypedPrimitiveAbstractClosure::hash() const {
|
|||
return hash_value;
|
||||
}
|
||||
|
||||
"""
|
||||
TypedPrimitiveAbstractClosure类的ToString成员函数用于返回类型化原语抽象闭包对象的字符串表示。
|
||||
它通过遍历args_spec_list_容器中的每个参数对象,将参数对象的位置和类型名或字符串表示连接起来,最终得到类型化原语抽象闭包对象的参数部分的字符串表示。
|
||||
在处理参数对象时,如果对象是AbstractFuncAtom类型的,则直接获取其类型名;否则,获取对象的字符串表示。
|
||||
最后,将参数部分的字符串表示和输出对象的字符串表示连接起来,返回类型化原语抽象闭包对象的完整字符串表示。
|
||||
返回的字符串形如 "TypedPrimitiveAbstractClosure: primitive: prim_name(args: {[0]: arg1, [1]: arg2, ...}, output: output_obj)",
|
||||
其中 prim_name 是原语操作符的名称,arg1、arg2 等是参数对象的字符串表示,output_obj 是输出对象的字符串表示。
|
||||
"""
|
||||
std::string TypedPrimitiveAbstractClosure::ToString() const {
|
||||
std::ostringstream buffer;
|
||||
buffer << "TypedPrimitiveAbstractClosure: primitive: " << prim_->name() << "(args: {";
|
||||
|
|
|
|||
|
|
@ -25,7 +25,9 @@ from ..ops.composite import GradOperation
|
|||
grad = GradOperation(get_all=False, get_by_list=False, sens_param=False)
|
||||
_eps_net = ops.Eps()
|
||||
|
||||
|
||||
"""
|
||||
用于在深度学习或数值计算中,确保输入张量的数据类型与模型或算法的要求相匹配
|
||||
"""
|
||||
def _convert_64_to_32(tensor):
|
||||
"""Convert Tensor with float64/int64 types to float32/int32."""
|
||||
if tensor.dtype == mstype.float64:
|
||||
|
|
@ -34,7 +36,10 @@ def _convert_64_to_32(tensor):
|
|||
return tensor.astype("int32")
|
||||
return tensor
|
||||
|
||||
|
||||
"""
|
||||
用于将一组输入参数转换为张量(Tensor)类型,并可以根据需要指定输出张量的数据类型。
|
||||
参数类型检查和转换确保了输入参数满足张量操作的要求,同时允许对输入数据进行数据类型的转换
|
||||
"""
|
||||
def _to_tensor(*args, dtype=None):
|
||||
"""Returns each input as Tensor"""
|
||||
res = ()
|
||||
|
|
@ -52,7 +57,11 @@ def _to_tensor(*args, dtype=None):
|
|||
return res[0]
|
||||
return res
|
||||
|
||||
|
||||
"""
|
||||
用于将输入的张量或数组转换为标量值(单个数值),如果输入已经是标量,则直接返回输入。
|
||||
在处理深度学习或数值计算任务中,确保输出结果是标量的情况下非常有用。
|
||||
如果输入不是标量,函数 将尝试将其转换为标量,否则会引发异常。
|
||||
"""
|
||||
def _to_scalar(arr):
|
||||
"""Convert a scalar Tensor or ndarray to a scalar."""
|
||||
if isinstance(arr, (int, float, bool)):
|
||||
|
|
@ -63,11 +72,16 @@ def _to_scalar(arr):
|
|||
return arr.asnumpy().item()
|
||||
raise ValueError("{} are not supported.".format(type(arr)))
|
||||
|
||||
|
||||
"""
|
||||
计算输入张量 x 的 epsilon 值
|
||||
"""
|
||||
def _eps(x):
|
||||
return _eps_net(x[(0,) * x.ndim])
|
||||
|
||||
|
||||
"""
|
||||
用于对输入张量进行归一化操作,但会检查阈值,如果归一化结果小于阈值,则将其截断为零,以确保结果不会受到微小值的影响。
|
||||
在深度学习中用于处理梯度或特征的归一化,以防止数值不稳定性。
|
||||
"""
|
||||
def _safe_normalize(x, threshold=None):
|
||||
"""Normalize method that cast very small results to zero."""
|
||||
x_sum2 = F.reduce_sum(F.pows(x, 2.0))
|
||||
|
|
@ -84,7 +98,9 @@ def _safe_normalize(x, threshold=None):
|
|||
norm = where(use_norm, norm, zeros_like(norm))
|
||||
return normalized_x, norm
|
||||
|
||||
|
||||
"""
|
||||
用于计算稀疏矩阵(CSRTensor)和普通张量(通常是向量)之间的点积,并确保输出的形状与输入矩阵的形状一致。
|
||||
"""
|
||||
def sparse_dot(a, b):
|
||||
"""Returns the dot product of CSRTensor and generic Tensor(vector)."""
|
||||
b_aligned = F.reshape(b, (b.shape[0], -1))
|
||||
|
|
@ -92,7 +108,12 @@ def sparse_dot(a, b):
|
|||
res = F.reshape(res, a.shape[:-1] + b.shape[1:])
|
||||
return res
|
||||
|
||||
|
||||
"""
|
||||
用于根据输入参数的类型选择合适的函数来规范化用于计算矩阵-向量乘积的参数。
|
||||
如果输入是 Tensor 类型,则返回一个普通矩阵-向量乘积函数;
|
||||
如果输入是 CSRTensor 类型,则返回一个稀疏矩阵-向量乘积函数;
|
||||
如果输入不是这两种类型之一,直接返回输入参数.
|
||||
"""
|
||||
def _normalize_matvec(f):
|
||||
"""Normalize an argument for computing matrix-vector products."""
|
||||
if isinstance(f, Tensor):
|
||||
|
|
@ -103,7 +124,10 @@ def _normalize_matvec(f):
|
|||
|
||||
return f
|
||||
|
||||
|
||||
"""
|
||||
用于计算输入向量 x 的范数,具体是无穷范数还是2范数取决于 ord_ 参数的值。
|
||||
如果 ord_ 是无穷范数,就计算无穷范数的值;否则,计算2范数的值。
|
||||
"""
|
||||
def _norm(x, ord_=None):
|
||||
if ord_ == mnp.inf:
|
||||
res = mnp.max(mnp.abs(x))
|
||||
|
|
@ -111,7 +135,10 @@ def _norm(x, ord_=None):
|
|||
res = mnp.sqrt(mnp.sum(x ** 2))
|
||||
return res
|
||||
|
||||
|
||||
"""
|
||||
用于对输入张量的维度进行转置操作,将倒数第一个维度和倒数第二个维度的位置互换。
|
||||
用于调整张量的维度顺序,以匹配不同的计算或模型需求。
|
||||
"""
|
||||
def _nd_transpose(a):
|
||||
dims = a.ndim
|
||||
if dims < 2:
|
||||
|
|
@ -120,31 +147,36 @@ def _nd_transpose(a):
|
|||
axes = axes[:-2] + (axes[-1],) + (axes[-2],)
|
||||
return ops.transpose(a, axes)
|
||||
|
||||
|
||||
#用于检查两个参数的关系,例如检查一个参数是否在某个范围内或符合某个条件
|
||||
def _value_check(func_name, arg1, arg2, arg_name='', attr_name='', op="in", fmt="attr", msg=None):
|
||||
return _super_check(pack(arg1, arg2), (func_name, arg_name, attr_name), op, fmt, msg, True)
|
||||
|
||||
|
||||
#用于检查一个参数的类型是否与期望的类型相符
|
||||
def _type_check(func_name, arg1, arg2, arg_name='', op="isinstance", fmt="type", msg=None):
|
||||
return _super_check(pack(arg1, arg2), (func_name, arg_name), op, fmt, msg, False)
|
||||
|
||||
|
||||
#用于检查参数的 MindSpore 数据类型(mstype)是否与期望的数据类型相符。
|
||||
def _mstype_check(func_name, arg, arg_mstype, arg_name='a'):
|
||||
return _super_check((F.typeof(arg), arg_mstype), pack(arg, arg_mstype, func_name, arg_name), "isinstance", "mstype",
|
||||
None, False)
|
||||
|
||||
|
||||
#用于检查参数的数据类型是否符合预期的数据类型
|
||||
def _dtype_check(func_name, arg, arg_dtype, arg_name='a'):
|
||||
return _super_check((F.dtype(arg), arg_dtype), (func_name, arg_name, "data type"), "in", "attr", None, False)
|
||||
|
||||
|
||||
"""
|
||||
用于检查输入参数是否是一个二维方阵,即具有相同的行和列数。
|
||||
"""
|
||||
def _square_check(func_name, arg, arg_name='a'):
|
||||
arg_shape = arg.shape
|
||||
_super_check((len(arg_shape), 2), (func_name, arg_name, 'dimension'), '==', 'attr', None, True)
|
||||
_super_check(arg_shape, (func_name, arg_name), '==', 'square', None, True)
|
||||
return arg
|
||||
|
||||
|
||||
"""
|
||||
用于检查用于求解线性方程组的输入参数,包括系数矩阵和右侧向量(或矩阵),
|
||||
以确保它们满足求解线性方程组的要求;包括检查维度、形状和数据类型等方面的条件。
|
||||
"""
|
||||
def _solve_check(func_name, arg1, arg2, arg1_name='a', arg2_name='b', sparse=False):
|
||||
arg1_shape, arg1_dtype = arg1.shape, F.dtype(arg1)
|
||||
arg2_shape, arg2_dtype = arg2.shape, F.dtype(arg2)
|
||||
|
|
@ -154,7 +186,10 @@ def _solve_check(func_name, arg1, arg2, arg1_name='a', arg2_name='b', sparse=Fal
|
|||
_super_check((arg1_dtype, arg2_dtype), (func_name, arg1_name, arg2_name, 'data type'), '==', 'match', None, False)
|
||||
return arg1, arg2
|
||||
|
||||
|
||||
"""
|
||||
用于检查和规范化用于求解线性方程组的参数,包括左侧矩阵 a、预条件矩阵 m、右侧向量 b 和初始解 x0。
|
||||
确保参数的正确性和一致性,以便在迭代求解过程中得到准确的结果。
|
||||
"""
|
||||
def _sparse_check(func_name, a, m, b, x0):
|
||||
"""Used for cg, bicgstab and gmres method."""
|
||||
|
||||
|
|
|
|||
|
|
@ -13,9 +13,9 @@
|
|||
# limitations under the License.
|
||||
# ============================================================================
|
||||
"""mindspore_test_framework"""
|
||||
import mindspore.context as context
|
||||
|
||||
import mindspore.context as context #导入了MindSpore框架中的’context‘模块
|
||||
|
||||
#该函数整体作用是设置模块的执行环境
|
||||
def setup_module(module):
|
||||
# pylint: disable=unused-argument
|
||||
context.set_context(mode=context.GRAPH_MODE)
|
||||
context.set_context(mode=context.GRAPH_MODE)#’GRAPH_MODE‘是MindSpore的执行模式之一,使用图优化的方式来执行计算图,在训练过程中会提供更好的性能
|
||||
|
|
|
|||
|
|
@ -13,17 +13,27 @@
|
|||
# limitations under the License.
|
||||
# ==============================================================================
|
||||
import numpy as np
|
||||
|
||||
import mindspore._c_dataengine as cde
|
||||
"""
|
||||
导入了MindSpore深度学习框架中的数据引擎模块
|
||||
用于数据预处理和数据增强等任务
|
||||
"""
|
||||
import mindspore._c_dataengine as cde
|
||||
|
||||
|
||||
"""
|
||||
创建一个张量形状并进行一些断言测试
|
||||
测试'cde.TensorShape()'函数的行为是否符合预期
|
||||
"""
|
||||
def test_shape():
|
||||
x = [2, 3]
|
||||
s = cde.TensorShape(x)
|
||||
assert s.as_list() == x
|
||||
assert s.is_known()
|
||||
|
||||
|
||||
"""
|
||||
使用NumPy和'cde'模块进行一些基本的数组操作
|
||||
并添加了更多的断言测试来验证结果
|
||||
"""
|
||||
def test_basic():
|
||||
x = np.array([1, 2, 3, 4, 5])
|
||||
n = cde.Tensor(x)
|
||||
|
|
@ -41,7 +51,10 @@ def test_basic():
|
|||
assert n.type() == cde.DataType("int64")
|
||||
assert arr.__array_interface__['data'] == arr2.__array_interface__['data']
|
||||
|
||||
|
||||
"""
|
||||
'test_strides()'函数对NumPy数组和'cde'模块中的张量进行了转换操作,并进行了断言测试
|
||||
测试结果可以帮助确保转换操作的过程没有产生错误
|
||||
"""
|
||||
def test_strides():
|
||||
x = np.array([[1, 2, 3], [4, 5, 6]])
|
||||
n1 = cde.Tensor(x[:, 1])
|
||||
|
|
|
|||
|
|
@ -13,8 +13,11 @@
|
|||
# limitations under the License.
|
||||
# ============================================================================
|
||||
""" test model train """
|
||||
import numpy as np
|
||||
|
||||
"""
|
||||
导入MindSpore中的一些基本块和类
|
||||
"""
|
||||
import numpy as np
|
||||
import mindspore.nn as nn
|
||||
from mindspore import Tensor, Parameter, Model
|
||||
from mindspore.common.initializer import initializer
|
||||
|
|
@ -28,7 +31,20 @@ def lr_gen(fn, epoch_size):
|
|||
for i in range(epoch_size):
|
||||
yield fn(i)
|
||||
|
||||
|
||||
"""
|
||||
函数参数:
|
||||
net :代表要训练的神经网络模型
|
||||
input_np :包含输入数据的NumPy数组
|
||||
label_np :包含标签数据的NumPy数组
|
||||
epoch_size :指定训练的轮数
|
||||
函数流程:
|
||||
定义损失函数 SoftmaxCrossEntropyWithLogits 作为交叉熵损失,并使用 sparse=True 表示标签数据为稀疏的,reduction="mean" 表示使用平均损失。
|
||||
定义优化器 Momentum 并设置学习率为 lr_gen(lambda i: 0.1, epoch_size),使用动量算法进行模型参数优化。
|
||||
创建一个模型 Model 实例。
|
||||
使用 WithLossCell 将网络模型 net 和损失函数 loss 关联,并使用 TrainOneStepCell 创建一个用于单步训练的网络实例 _train_net,其中使用了之前定义的损失函数和优化器。
|
||||
将 _train_net 设置为训练模式。对标签数据进行处理,将其从 one-hot 编码转换为单热编码。
|
||||
通过循环迭代 epoch_size 次进行模型训练,每个迭代周期调用 _train_net 对输入数据进行单步训练。
|
||||
“”“
|
||||
def me_train_tensor(net, input_np, label_np, epoch_size=2):
|
||||
"""me_train_tensor"""
|
||||
loss = SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean")
|
||||
|
|
@ -43,7 +59,10 @@ def me_train_tensor(net, input_np, label_np, epoch_size=2):
|
|||
print(f"epoch %d" % (epoch))
|
||||
_train_net(Tensor(input_np), Tensor(label_np))
|
||||
|
||||
|
||||
"""
|
||||
测试用例函数;用于测试MindSpore框架中的P.BiasAdd操作和相关逻辑的正确性。
|
||||
函数中的Net类定义了一个简单的神经网络,用于测试加法操作的正确性。
|
||||
"""
|
||||
def test_bias_add(test_with_simu):
|
||||
"""test_bias_add"""
|
||||
import mindspore.context as context
|
||||
|
|
@ -143,6 +162,10 @@ def test_net():
|
|||
output = self.dense(output)
|
||||
return output
|
||||
|
||||
"""
|
||||
使用了定义的Net类和me_train_tensor函数
|
||||
对神经网络进行了简单的训练
|
||||
"""
|
||||
net = Net()
|
||||
input_np = np.ones([32, 3, 224, 224]).astype(np.float32) * 0.01
|
||||
label_np = np.ones([32, 12]).astype(np.int32)
|
||||
|
|
|
|||
|
|
@ -13,6 +13,15 @@
|
|||
# limitations under the License.
|
||||
# ============================================================================
|
||||
import numpy as np
|
||||
"""
|
||||
导入执行上下文设置模块:mindspore.context as context。
|
||||
导入神经网络相关模块:mindspore.nn as nn。
|
||||
导入功能性操作模块:mindspore.ops.functional as F。
|
||||
导入数据类型模块:from mindspore.common import dtype as mstype。
|
||||
导入张量模块:from mindspore.common.tensor import Tensor。
|
||||
导入复合操作模块:from mindspore.ops import composite as C。
|
||||
导入原始操作模块:from mindspore.ops import operations as P。
|
||||
"""
|
||||
|
||||
import mindspore.context as context
|
||||
import mindspore.nn as nn
|
||||
|
|
@ -22,6 +31,10 @@ from mindspore.common.tensor import Tensor
|
|||
from mindspore.ops import composite as C
|
||||
from mindspore.ops import operations as P
|
||||
|
||||
"""
|
||||
将MindSpore的执行模式设置为图模式。MindSpore支持两种执行模式:图模式和Pynative模式。
|
||||
图模式通常用于生产环境,对计算进行优化;Pynative模式用于开发和调试
|
||||
"""
|
||||
context.set_context(mode=context.GRAPH_MODE)
|
||||
add1 = P.Add()
|
||||
mul1 = P.MatMul()
|
||||
|
|
@ -31,7 +44,9 @@ add2 = P.Add()
|
|||
def add(x, y):
|
||||
return add1(x, y)
|
||||
|
||||
|
||||
"""
|
||||
定义了一个执行特定操作序列的自定义神经网络模型,该操作序列包括数学运算和与 NPU 上的浮点数状态相关的操作。
|
||||
"""
|
||||
class Func(nn.Cell):
|
||||
def __init__(self):
|
||||
super(Func, self).__init__()
|
||||
|
|
@ -57,7 +72,10 @@ class Func(nn.Cell):
|
|||
|
||||
grad_s = C.GradOperation(get_all=True, sens_param=True)
|
||||
|
||||
|
||||
"""
|
||||
定义了一个神经网络模型,该模型的前向传播包括了各种操作,包括数学运算、梯度计算以及 NPU 上的浮点数状态处理。
|
||||
模型的目的是将输入数据 'x'、'y' 和敏感度 'sens' 传递到一系列操作中,最终得到前向传播的输出 'out'。
|
||||
"""
|
||||
class Net(nn.Cell):
|
||||
def __init__(self):
|
||||
super(Net, self).__init__()
|
||||
|
|
@ -98,7 +116,11 @@ def test_sens():
|
|||
net = Net()
|
||||
_ = net(x, y, sens)
|
||||
|
||||
|
||||
"""
|
||||
定义了一个神经网络模型 Net_hyper,其主要作用是执行一系列操作,
|
||||
包括进行数学运算和处理 NPU(神经处理单元) 上的浮点数状态。
|
||||
与之前的代码段相比,这段代码的不同之处在于使用了超级操作(C.hyper_add)来执行元素级加法。
|
||||
"""
|
||||
class Net_hyper(nn.Cell):
|
||||
def __init__(self):
|
||||
super(Net_hyper, self).__init__()
|
||||
|
|
|
|||
|
|
@ -23,7 +23,10 @@ from mindspore import Tensor
|
|||
from mindspore.common import dtype as mstype
|
||||
from mindspore.common.api import _cell_graph_executor
|
||||
|
||||
|
||||
'''
|
||||
'CentralCropNet'类的目的是为了在神经网络中方便地应用中心裁剪操作。
|
||||
通过创建一个实例并将图像数据传递给'construct'方法来实现中心裁剪,从而得到裁剪后的区域
|
||||
'''
|
||||
class CentralCropNet(nn.Cell):
|
||||
def __init__(self, central_fraction):
|
||||
super(CentralCropNet, self).__init__()
|
||||
|
|
@ -32,39 +35,53 @@ class CentralCropNet(nn.Cell):
|
|||
def construct(self, image):
|
||||
return self.net(image)
|
||||
|
||||
|
||||
'''
|
||||
用于测试3D中心裁剪操作。测试中心裁剪网络在给定参数和输入的情况下是否能被成功编译并执行;
|
||||
如测试通过,则表明中心裁剪网络在图执行模式下能够正常工作
|
||||
'''
|
||||
def test_compile_3d_central_crop():
|
||||
central_fraction = 0.2
|
||||
net = CentralCropNet(central_fraction)
|
||||
image = Tensor(np.random.random((3, 16, 16)), mstype.float32)
|
||||
_cell_graph_executor.compile(net, image)
|
||||
|
||||
|
||||
'''
|
||||
用于测试一个4D的中心裁剪网络在给定参数和输入情况下是否能够被成功编译并执行
|
||||
'''
|
||||
def test_compile_4d_central_crop():
|
||||
central_fraction = 0.5
|
||||
net = CentralCropNet(central_fraction)
|
||||
image = Tensor(np.random.random((8, 3, 16, 16)), mstype.float32)
|
||||
_cell_graph_executor.compile(net, image)
|
||||
|
||||
|
||||
'''
|
||||
测试在传入不合理的中心裁剪比例时,是否会引发预期类型错误异常。
|
||||
如果测试通过,则表明在处理不合理的输入时具有正确的异常处理机制
|
||||
'''
|
||||
def test_central_fraction_bool():
|
||||
central_fraction = True
|
||||
with pytest.raises(TypeError):
|
||||
_ = CentralCropNet(central_fraction)
|
||||
|
||||
|
||||
'''
|
||||
该函数用于测试中心裁剪操作在传入负值作为中心裁剪比例时是否会引发预期的值错误异常
|
||||
'''
|
||||
def test_central_crop_central_fraction_negative():
|
||||
central_fraction = -1.0
|
||||
with pytest.raises(ValueError):
|
||||
_ = CentralCropNet(central_fraction)
|
||||
|
||||
|
||||
'''
|
||||
用于测试中心裁剪操作在传入零作为中心裁剪比例时是否会引发预期的值错误异常
|
||||
'''
|
||||
def test_central_fraction_zero():
|
||||
central_fraction = 0.0
|
||||
with pytest.raises(ValueError):
|
||||
_ = CentralCropNet(central_fraction)
|
||||
|
||||
|
||||
'''
|
||||
用于测试在传入维度不正确的 5D 输入时,是否会引发预期的值错误异常
|
||||
'''
|
||||
def test_central_crop_invalid_5d_input():
|
||||
invalid_shape = (8, 3, 16, 16, 1)
|
||||
invalid_image = Tensor(np.random.random(invalid_shape))
|
||||
|
|
|
|||
|
|
@ -14,10 +14,16 @@
|
|||
# ============================================================================
|
||||
""" test_run_config """
|
||||
import pytest
|
||||
|
||||
''''
|
||||
从MindSpore库中导入CheckpointConfig类
|
||||
指定训练过程中保存检查点的条件
|
||||
''''
|
||||
from mindspore.train.callback import CheckpointConfig
|
||||
|
||||
|
||||
'''
|
||||
定义测试函数通过断言来验证在初始化'CheckpointConfig'类后,
|
||||
对象的属性是否被正确设置,并确保'get_checkpoint_policy()'方法能够正确返回检查点策略的相关信息。
|
||||
'''
|
||||
def test_init():
|
||||
""" test_init """
|
||||
save_checkpoint_steps = 1
|
||||
|
|
@ -31,7 +37,12 @@ def test_init():
|
|||
policy = config.get_checkpoint_policy()
|
||||
assert policy['keep_checkpoint_max'] == keep_checkpoint_max
|
||||
|
||||
|
||||
'''
|
||||
函数 test_arguments_values()验证'CheckpointConfig'类在初始化和参数设置方面的正确性,
|
||||
以确保在使用该类时能够提供有效的参数,并正确处理可能出现的异常情况。
|
||||
这是一种测试驱动开发(Test-Driven Development,TDD)的实践方式,
|
||||
通过编写测试来规范类的行为和功能,保证其在使用中的稳定性和正确性。
|
||||
'''
|
||||
def test_arguments_values():
|
||||
""" test_arguments_values """
|
||||
config = CheckpointConfig()
|
||||
|
|
|
|||
Loading…
Reference in New Issue