MindSpore代码评注 #32

Open
Link_pursuit wants to merge 8 commits from Link_pursuit/mindspore2022:master into master
8 changed files with 260 additions and 40 deletions

View File

@ -19,6 +19,12 @@
#include <vector> #include <vector>
#include "utils/hashing.h" #include "utils/hashing.h"
"""
'mindspore''abstract'
'Evaluator','Ana''AbstractFunction'
'AbstractFunction''MakeAbstractFunction'
'AbstractFunction'
"""
namespace mindspore { namespace mindspore {
namespace abstract { namespace abstract {
class Evaluator; class Evaluator;
@ -30,6 +36,12 @@ AbstractFunctionPtr AbstractFunction::MakeAbstractFunction(const AbstractFuncAto
return std::make_shared<AbstractFuncUnion>(func_list); 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) { AbstractFunctionPtr AbstractFuncAtom::Join(const AbstractFunctionPtr &other) {
MS_EXCEPTION_IF_NULL(other); MS_EXCEPTION_IF_NULL(other);
auto this_func = shared_from_base<AbstractFuncAtom>(); 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::AbstractFuncUnion(const AbstractFuncAtomPtrList &func_list) { func_list_ = func_list; }
"""
AbstractFuncUnion类的构造函数用于创建抽象函数联合对象
AbstractFuncAtomPtr类型的指针存储在func_list_成员变量中
"""
AbstractFuncUnion::AbstractFuncUnion(const AbstractFunctionPtr &first, const AbstractFunctionPtr &second) { AbstractFuncUnion::AbstractFuncUnion(const AbstractFunctionPtr &first, const AbstractFunctionPtr &second) {
AbstractFuncAtomPtrList new_func_list; AbstractFuncAtomPtrList new_func_list;
auto build_func_list = [&new_func_list](const AbstractFuncAtomPtr &func) { new_func_list.push_back(func); }; 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); second->Visit(build_func_list);
func_list_ = new_func_list; func_list_ = new_func_list;
} }
"""
AbstractFuncUnion类的成员函数ToString用于将抽象函数联合对象的信息转换为字符串形式
std::ostringstream对象使func_list_容器中的每个元素buffer中
buffer转换为std::string类型
"""
std::string AbstractFuncUnion::ToString() const { std::string AbstractFuncUnion::ToString() const {
std::ostringstream buffer; std::ostringstream buffer;
buffer << "AbstractFuncUnion({"; buffer << "AbstractFuncUnion({";
@ -78,6 +100,11 @@ std::string AbstractFuncUnion::ToString() const {
return buffer.str(); return buffer.str();
} }
"""
AbstractFuncUnion类的成员函数ToString的重载实现用于将抽象函数联合对象的信息转换为字符串形式
verbose参数为trueToString函数
verbose参数为false
"""
std::string AbstractFuncUnion::ToString(bool verbose) const { std::string AbstractFuncUnion::ToString(bool verbose) const {
if (verbose) { if (verbose) {
return ToString(); return ToString();
@ -97,6 +124,11 @@ std::string AbstractFuncUnion::ToString(bool verbose) const {
return buffer.str(); return buffer.str();
} }
"""
AbstractFuncUnion类的成员函数IsSuperSet用于判断当前的抽象函数联合对象是否包含另一个抽象函数对象的所有成员函数
other中的每个成员函数func_list_中
other的超集
"""
bool AbstractFuncUnion::IsSuperSet(const AbstractFunctionPtr &other) { bool AbstractFuncUnion::IsSuperSet(const AbstractFunctionPtr &other) {
MS_EXCEPTION_IF_NULL(other); MS_EXCEPTION_IF_NULL(other);
std::vector<bool> is_in_list; 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; }); 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) { AbstractFunctionPtr AbstractFuncUnion::Join(const AbstractFunctionPtr &other) {
auto this_func = shared_from_base<AbstractFunction>(); auto this_func = shared_from_base<AbstractFunction>();
MS_EXCEPTION_IF_NULL(other); 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 { bool AbstractFuncUnion::operator==(const AbstractFunction &other) const {
if (!other.isa<AbstractFuncUnion>()) { if (!other.isa<AbstractFuncUnion>()) {
return false; return false;
@ -145,6 +191,11 @@ bool AbstractFuncUnion::operator==(const AbstractFunction &other) const {
return func_list_ == other_union->func_list_; return func_list_ == other_union->func_list_;
} }
"""
AbstractFuncUnion类的成员函数hash用于计算抽象函数联合对象的哈希值
"""
std::size_t AbstractFuncUnion::hash() const { std::size_t AbstractFuncUnion::hash() const {
std::size_t hash_sum = 0; std::size_t hash_sum = 0;
for (const auto &f : func_list_) { for (const auto &f : func_list_) {
@ -154,6 +205,12 @@ std::size_t AbstractFuncUnion::hash() const {
return hash_sum; return hash_sum;
} }
"""
PrimitiveAbstractClosure类的operator==
other是否是原语抽象闭包类型的对象false
prim_和tracking_id()
truefalse
"""
bool PrimitiveAbstractClosure::operator==(const AbstractFunction &other) const { bool PrimitiveAbstractClosure::operator==(const AbstractFunction &other) const {
if (!other.isa<PrimitiveAbstractClosure>()) { if (!other.isa<PrimitiveAbstractClosure>()) {
return false; return false;
@ -162,6 +219,11 @@ bool PrimitiveAbstractClosure::operator==(const AbstractFunction &other) const {
return (prim_ == other_abs.prim_) && (tracking_id() == other_abs.tracking_id()); return (prim_ == other_abs.prim_) && (tracking_id() == other_abs.tracking_id());
} }
"""
PrimitiveAbstractClosure类的成员函数hash用于计算原语抽象闭包对象的哈希值
IDtid()(prim_)ID节点指针(tracking_id())
operator==
"""
std::size_t PrimitiveAbstractClosure::hash() const { std::size_t PrimitiveAbstractClosure::hash() const {
// Keep in sync with operator==() which compares tid, prim_ & tracking_id; // Keep in sync with operator==() which compares tid, prim_ & tracking_id;
auto hash_value = static_cast<std::size_t>(tid()); auto hash_value = static_cast<std::size_t>(tid());
@ -231,6 +293,14 @@ std::size_t MetaFuncGraphAbstractClosure::hash() const {
return hash_value; return hash_value;
} }
"""
MetaFuncGraphAbstractClosure类的成员函数ToString用于返回一个描述元函数图抽象闭包的字符串
PartialAbstractClosure类的operator==
other是否是部分抽象闭包类型的对象false
fn_成员变量是否相等args_spec_list_成员变量的大小是否相等
args_spec_list_成员变量是否相等
truefalse
"""
std::string MetaFuncGraphAbstractClosure::ToString() const { std::string MetaFuncGraphAbstractClosure::ToString() const {
MS_EXCEPTION_IF_NULL(meta_func_graph_); MS_EXCEPTION_IF_NULL(meta_func_graph_);
return "MetaFuncGraphAbstractClosure: " + meta_func_graph_->name(); return "MetaFuncGraphAbstractClosure: " + meta_func_graph_->name();
@ -257,6 +327,12 @@ std::size_t PartialAbstractClosure::hash() const {
return hash_value; return hash_value;
} }
"""
PartialAbstractClosure类的成员函数 ToString
args_spec_list_
AbstractFuncAtom
"PartialAbstractClosure(fn_name(arg1, arg2, ...))" fn_name arg1arg2
"""
std::string PartialAbstractClosure::ToString() const { std::string PartialAbstractClosure::ToString() const {
std::ostringstream buffer; std::ostringstream buffer;
buffer << "PartialAbstractClosure(" << fn_->ToString() << "("; buffer << "PartialAbstractClosure(" << fn_->ToString() << "(";
@ -363,6 +439,14 @@ std::size_t VirtualAbstractClosure::hash() const {
return hash_value; return hash_value;
} }
"""
VirtualAbstractClosure类的成员函数ToString用于返回虚函数抽象闭包对象的字符串表示
args_spec_list_容器中的每个参数对象
AbstractFuncAtom类型的
"VirtualAbstractClosure(args: {[0]: arg1, [1]: arg2, ...}, output: output_obj)"
arg1arg2 output_obj
"""
std::string VirtualAbstractClosure::ToString() const { std::string VirtualAbstractClosure::ToString() const {
std::ostringstream buffer; std::ostringstream buffer;
buffer << "VirtualAbstractClosure(args: {"; buffer << "VirtualAbstractClosure(args: {";
@ -383,6 +467,13 @@ std::string VirtualAbstractClosure::ToString() const {
return buffer.str(); return buffer.str();
} }
"""
TypedPrimitiveAbstractClosure类的operator==
other是否是类型化原语抽象闭包类型的对象false
output_和prim_成员变量是否相等args_spec_list_成员变量的大小是否相等
args_spec_list_成员变量是否相等true
false
"""
bool TypedPrimitiveAbstractClosure::operator==(const AbstractFunction &other) const { bool TypedPrimitiveAbstractClosure::operator==(const AbstractFunction &other) const {
if (!other.isa<TypedPrimitiveAbstractClosure>()) { if (!other.isa<TypedPrimitiveAbstractClosure>()) {
return false; return false;
@ -406,6 +497,14 @@ std::size_t TypedPrimitiveAbstractClosure::hash() const {
return hash_value; return hash_value;
} }
"""
TypedPrimitiveAbstractClosure类的ToString成员函数用于返回类型化原语抽象闭包对象的字符串表示
args_spec_list_容器中的每个参数对象
AbstractFuncAtom类型的
"TypedPrimitiveAbstractClosure: primitive: prim_name(args: {[0]: arg1, [1]: arg2, ...}, output: output_obj)"
prim_name arg1arg2 output_obj
"""
std::string TypedPrimitiveAbstractClosure::ToString() const { std::string TypedPrimitiveAbstractClosure::ToString() const {
std::ostringstream buffer; std::ostringstream buffer;
buffer << "TypedPrimitiveAbstractClosure: primitive: " << prim_->name() << "(args: {"; buffer << "TypedPrimitiveAbstractClosure: primitive: " << prim_->name() << "(args: {";

View File

@ -25,7 +25,9 @@ from ..ops.composite import GradOperation
grad = GradOperation(get_all=False, get_by_list=False, sens_param=False) grad = GradOperation(get_all=False, get_by_list=False, sens_param=False)
_eps_net = ops.Eps() _eps_net = ops.Eps()
"""
用于在深度学习或数值计算中确保输入张量的数据类型与模型或算法的要求相匹配
"""
def _convert_64_to_32(tensor): def _convert_64_to_32(tensor):
"""Convert Tensor with float64/int64 types to float32/int32.""" """Convert Tensor with float64/int64 types to float32/int32."""
if tensor.dtype == mstype.float64: if tensor.dtype == mstype.float64:
@ -34,7 +36,10 @@ def _convert_64_to_32(tensor):
return tensor.astype("int32") return tensor.astype("int32")
return tensor return tensor
"""
用于将一组输入参数转换为张量Tensor类型并可以根据需要指定输出张量的数据类型
参数类型检查和转换确保了输入参数满足张量操作的要求同时允许对输入数据进行数据类型的转换
"""
def _to_tensor(*args, dtype=None): def _to_tensor(*args, dtype=None):
"""Returns each input as Tensor""" """Returns each input as Tensor"""
res = () res = ()
@ -52,7 +57,11 @@ def _to_tensor(*args, dtype=None):
return res[0] return res[0]
return res return res
"""
用于将输入的张量或数组转换为标量值单个数值如果输入已经是标量则直接返回输入
在处理深度学习或数值计算任务中确保输出结果是标量的情况下非常有用
如果输入不是标量函数 将尝试将其转换为标量否则会引发异常
"""
def _to_scalar(arr): def _to_scalar(arr):
"""Convert a scalar Tensor or ndarray to a scalar.""" """Convert a scalar Tensor or ndarray to a scalar."""
if isinstance(arr, (int, float, bool)): if isinstance(arr, (int, float, bool)):
@ -63,11 +72,16 @@ def _to_scalar(arr):
return arr.asnumpy().item() return arr.asnumpy().item()
raise ValueError("{} are not supported.".format(type(arr))) raise ValueError("{} are not supported.".format(type(arr)))
"""
计算输入张量 x epsilon
"""
def _eps(x): def _eps(x):
return _eps_net(x[(0,) * x.ndim]) return _eps_net(x[(0,) * x.ndim])
"""
用于对输入张量进行归一化操作但会检查阈值如果归一化结果小于阈值则将其截断为零以确保结果不会受到微小值的影响
在深度学习中用于处理梯度或特征的归一化以防止数值不稳定性
"""
def _safe_normalize(x, threshold=None): def _safe_normalize(x, threshold=None):
"""Normalize method that cast very small results to zero.""" """Normalize method that cast very small results to zero."""
x_sum2 = F.reduce_sum(F.pows(x, 2.0)) 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)) norm = where(use_norm, norm, zeros_like(norm))
return normalized_x, norm return normalized_x, norm
"""
用于计算稀疏矩阵CSRTensor和普通张量通常是向量之间的点积并确保输出的形状与输入矩阵的形状一致
"""
def sparse_dot(a, b): def sparse_dot(a, b):
"""Returns the dot product of CSRTensor and generic Tensor(vector).""" """Returns the dot product of CSRTensor and generic Tensor(vector)."""
b_aligned = F.reshape(b, (b.shape[0], -1)) 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:]) res = F.reshape(res, a.shape[:-1] + b.shape[1:])
return res return res
"""
用于根据输入参数的类型选择合适的函数来规范化用于计算矩阵-向量乘积的参数
如果输入是 Tensor 类型则返回一个普通矩阵-向量乘积函数
如果输入是 CSRTensor 类型则返回一个稀疏矩阵-向量乘积函数
如果输入不是这两种类型之一直接返回输入参数.
"""
def _normalize_matvec(f): def _normalize_matvec(f):
"""Normalize an argument for computing matrix-vector products.""" """Normalize an argument for computing matrix-vector products."""
if isinstance(f, Tensor): if isinstance(f, Tensor):
@ -103,7 +124,10 @@ def _normalize_matvec(f):
return f return f
"""
用于计算输入向量 x 的范数具体是无穷范数还是2范数取决于 ord_ 参数的值
如果 ord_ 是无穷范数就计算无穷范数的值否则计算2范数的值
"""
def _norm(x, ord_=None): def _norm(x, ord_=None):
if ord_ == mnp.inf: if ord_ == mnp.inf:
res = mnp.max(mnp.abs(x)) res = mnp.max(mnp.abs(x))
@ -111,7 +135,10 @@ def _norm(x, ord_=None):
res = mnp.sqrt(mnp.sum(x ** 2)) res = mnp.sqrt(mnp.sum(x ** 2))
return res return res
"""
用于对输入张量的维度进行转置操作将倒数第一个维度和倒数第二个维度的位置互换
用于调整张量的维度顺序以匹配不同的计算或模型需求
"""
def _nd_transpose(a): def _nd_transpose(a):
dims = a.ndim dims = a.ndim
if dims < 2: if dims < 2:
@ -120,31 +147,36 @@ def _nd_transpose(a):
axes = axes[:-2] + (axes[-1],) + (axes[-2],) axes = axes[:-2] + (axes[-1],) + (axes[-2],)
return ops.transpose(a, axes) return ops.transpose(a, axes)
#用于检查两个参数的关系,例如检查一个参数是否在某个范围内或符合某个条件
def _value_check(func_name, arg1, arg2, arg_name='', attr_name='', op="in", fmt="attr", msg=None): 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) 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): 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) 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'): 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", return _super_check((F.typeof(arg), arg_mstype), pack(arg, arg_mstype, func_name, arg_name), "isinstance", "mstype",
None, False) None, False)
#用于检查参数的数据类型是否符合预期的数据类型
def _dtype_check(func_name, arg, arg_dtype, arg_name='a'): 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) 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'): def _square_check(func_name, arg, arg_name='a'):
arg_shape = arg.shape arg_shape = arg.shape
_super_check((len(arg_shape), 2), (func_name, arg_name, 'dimension'), '==', 'attr', None, True) _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) _super_check(arg_shape, (func_name, arg_name), '==', 'square', None, True)
return arg return arg
"""
用于检查用于求解线性方程组的输入参数包括系数矩阵和右侧向量或矩阵
以确保它们满足求解线性方程组的要求包括检查维度形状和数据类型等方面的条件
"""
def _solve_check(func_name, arg1, arg2, arg1_name='a', arg2_name='b', sparse=False): def _solve_check(func_name, arg1, arg2, arg1_name='a', arg2_name='b', sparse=False):
arg1_shape, arg1_dtype = arg1.shape, F.dtype(arg1) arg1_shape, arg1_dtype = arg1.shape, F.dtype(arg1)
arg2_shape, arg2_dtype = arg2.shape, F.dtype(arg2) 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) _super_check((arg1_dtype, arg2_dtype), (func_name, arg1_name, arg2_name, 'data type'), '==', 'match', None, False)
return arg1, arg2 return arg1, arg2
"""
用于检查和规范化用于求解线性方程组的参数包括左侧矩阵 a预条件矩阵 m右侧向量 b 和初始解 x0
确保参数的正确性和一致性以便在迭代求解过程中得到准确的结果
"""
def _sparse_check(func_name, a, m, b, x0): def _sparse_check(func_name, a, m, b, x0):
"""Used for cg, bicgstab and gmres method.""" """Used for cg, bicgstab and gmres method."""

View File

@ -13,9 +13,9 @@
# limitations under the License. # limitations under the License.
# ============================================================================ # ============================================================================
"""mindspore_test_framework""" """mindspore_test_framework"""
import mindspore.context as context import mindspore.context as context #导入了MindSpore框架中的context模块
#该函数整体作用是设置模块的执行环境
def setup_module(module): def setup_module(module):
# pylint: disable=unused-argument # pylint: disable=unused-argument
context.set_context(mode=context.GRAPH_MODE) context.set_context(mode=context.GRAPH_MODE)#GRAPH_MODE是MindSpore的执行模式之一使用图优化的方式来执行计算图在训练过程中会提供更好的性能

View File

@ -13,17 +13,27 @@
# limitations under the License. # limitations under the License.
# ============================================================================== # ==============================================================================
import numpy as np import numpy as np
"""
import mindspore._c_dataengine as cde 导入了MindSpore深度学习框架中的数据引擎模块
用于数据预处理和数据增强等任务
"""
import mindspore._c_dataengine as cde
"""
创建一个张量形状并进行一些断言测试
测试'cde.TensorShape()'函数的行为是否符合预期
"""
def test_shape(): def test_shape():
x = [2, 3] x = [2, 3]
s = cde.TensorShape(x) s = cde.TensorShape(x)
assert s.as_list() == x assert s.as_list() == x
assert s.is_known() assert s.is_known()
"""
使用NumPy和'cde'模块进行一些基本的数组操作
并添加了更多的断言测试来验证结果
"""
def test_basic(): def test_basic():
x = np.array([1, 2, 3, 4, 5]) x = np.array([1, 2, 3, 4, 5])
n = cde.Tensor(x) n = cde.Tensor(x)
@ -41,7 +51,10 @@ def test_basic():
assert n.type() == cde.DataType("int64") assert n.type() == cde.DataType("int64")
assert arr.__array_interface__['data'] == arr2.__array_interface__['data'] assert arr.__array_interface__['data'] == arr2.__array_interface__['data']
"""
'test_strides()'函数对NumPy数组和'cde'模块中的张量进行了转换操作并进行了断言测试
测试结果可以帮助确保转换操作的过程没有产生错误
"""
def test_strides(): def test_strides():
x = np.array([[1, 2, 3], [4, 5, 6]]) x = np.array([[1, 2, 3], [4, 5, 6]])
n1 = cde.Tensor(x[:, 1]) n1 = cde.Tensor(x[:, 1])

View File

@ -13,8 +13,11 @@
# limitations under the License. # limitations under the License.
# ============================================================================ # ============================================================================
""" test model train """ """ test model train """
import numpy as np
"""
导入MindSpore中的一些基本块和类
"""
import numpy as np
import mindspore.nn as nn import mindspore.nn as nn
from mindspore import Tensor, Parameter, Model from mindspore import Tensor, Parameter, Model
from mindspore.common.initializer import initializer from mindspore.common.initializer import initializer
@ -28,7 +31,20 @@ def lr_gen(fn, epoch_size):
for i in range(epoch_size): for i in range(epoch_size):
yield fn(i) 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): def me_train_tensor(net, input_np, label_np, epoch_size=2):
"""me_train_tensor""" """me_train_tensor"""
loss = SoftmaxCrossEntropyWithLogits(sparse=True, reduction="mean") 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)) print(f"epoch %d" % (epoch))
_train_net(Tensor(input_np), Tensor(label_np)) _train_net(Tensor(input_np), Tensor(label_np))
"""
测试用例函数用于测试MindSpore框架中的P.BiasAdd操作和相关逻辑的正确性
函数中的Net类定义了一个简单的神经网络用于测试加法操作的正确性
"""
def test_bias_add(test_with_simu): def test_bias_add(test_with_simu):
"""test_bias_add""" """test_bias_add"""
import mindspore.context as context import mindspore.context as context
@ -143,6 +162,10 @@ def test_net():
output = self.dense(output) output = self.dense(output)
return output return output
"""
使用了定义的Net类和me_train_tensor函数
对神经网络进行了简单的训练
"""
net = Net() net = Net()
input_np = np.ones([32, 3, 224, 224]).astype(np.float32) * 0.01 input_np = np.ones([32, 3, 224, 224]).astype(np.float32) * 0.01
label_np = np.ones([32, 12]).astype(np.int32) label_np = np.ones([32, 12]).astype(np.int32)

View File

@ -13,6 +13,15 @@
# limitations under the License. # limitations under the License.
# ============================================================================ # ============================================================================
import numpy as np 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.context as context
import mindspore.nn as nn 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 composite as C
from mindspore.ops import operations as P from mindspore.ops import operations as P
"""
将MindSpore的执行模式设置为图模式MindSpore支持两种执行模式图模式和Pynative模式
图模式通常用于生产环境对计算进行优化Pynative模式用于开发和调试
"""
context.set_context(mode=context.GRAPH_MODE) context.set_context(mode=context.GRAPH_MODE)
add1 = P.Add() add1 = P.Add()
mul1 = P.MatMul() mul1 = P.MatMul()
@ -31,7 +44,9 @@ add2 = P.Add()
def add(x, y): def add(x, y):
return add1(x, y) return add1(x, y)
"""
定义了一个执行特定操作序列的自定义神经网络模型该操作序列包括数学运算和与 NPU 上的浮点数状态相关的操作
"""
class Func(nn.Cell): class Func(nn.Cell):
def __init__(self): def __init__(self):
super(Func, self).__init__() super(Func, self).__init__()
@ -57,7 +72,10 @@ class Func(nn.Cell):
grad_s = C.GradOperation(get_all=True, sens_param=True) grad_s = C.GradOperation(get_all=True, sens_param=True)
"""
定义了一个神经网络模型该模型的前向传播包括了各种操作包括数学运算梯度计算以及 NPU 上的浮点数状态处理
模型的目的是将输入数据 'x''y' 和敏感度 'sens' 传递到一系列操作中最终得到前向传播的输出 'out'
"""
class Net(nn.Cell): class Net(nn.Cell):
def __init__(self): def __init__(self):
super(Net, self).__init__() super(Net, self).__init__()
@ -98,7 +116,11 @@ def test_sens():
net = Net() net = Net()
_ = net(x, y, sens) _ = net(x, y, sens)
"""
定义了一个神经网络模型 Net_hyper其主要作用是执行一系列操作
包括进行数学运算和处理 NPU神经处理单元 上的浮点数状态
与之前的代码段相比这段代码的不同之处在于使用了超级操作C.hyper_add来执行元素级加法
"""
class Net_hyper(nn.Cell): class Net_hyper(nn.Cell):
def __init__(self): def __init__(self):
super(Net_hyper, self).__init__() super(Net_hyper, self).__init__()

View File

@ -23,7 +23,10 @@ from mindspore import Tensor
from mindspore.common import dtype as mstype from mindspore.common import dtype as mstype
from mindspore.common.api import _cell_graph_executor from mindspore.common.api import _cell_graph_executor
'''
'CentralCropNet'类的目的是为了在神经网络中方便地应用中心裁剪操作
通过创建一个实例并将图像数据传递给'construct'方法来实现中心裁剪从而得到裁剪后的区域
'''
class CentralCropNet(nn.Cell): class CentralCropNet(nn.Cell):
def __init__(self, central_fraction): def __init__(self, central_fraction):
super(CentralCropNet, self).__init__() super(CentralCropNet, self).__init__()
@ -32,39 +35,53 @@ class CentralCropNet(nn.Cell):
def construct(self, image): def construct(self, image):
return self.net(image) return self.net(image)
'''
用于测试3D中心裁剪操作测试中心裁剪网络在给定参数和输入的情况下是否能被成功编译并执行
如测试通过则表明中心裁剪网络在图执行模式下能够正常工作
'''
def test_compile_3d_central_crop(): def test_compile_3d_central_crop():
central_fraction = 0.2 central_fraction = 0.2
net = CentralCropNet(central_fraction) net = CentralCropNet(central_fraction)
image = Tensor(np.random.random((3, 16, 16)), mstype.float32) image = Tensor(np.random.random((3, 16, 16)), mstype.float32)
_cell_graph_executor.compile(net, image) _cell_graph_executor.compile(net, image)
'''
用于测试一个4D的中心裁剪网络在给定参数和输入情况下是否能够被成功编译并执行
'''
def test_compile_4d_central_crop(): def test_compile_4d_central_crop():
central_fraction = 0.5 central_fraction = 0.5
net = CentralCropNet(central_fraction) net = CentralCropNet(central_fraction)
image = Tensor(np.random.random((8, 3, 16, 16)), mstype.float32) image = Tensor(np.random.random((8, 3, 16, 16)), mstype.float32)
_cell_graph_executor.compile(net, image) _cell_graph_executor.compile(net, image)
'''
测试在传入不合理的中心裁剪比例时是否会引发预期类型错误异常
如果测试通过则表明在处理不合理的输入时具有正确的异常处理机制
'''
def test_central_fraction_bool(): def test_central_fraction_bool():
central_fraction = True central_fraction = True
with pytest.raises(TypeError): with pytest.raises(TypeError):
_ = CentralCropNet(central_fraction) _ = CentralCropNet(central_fraction)
'''
该函数用于测试中心裁剪操作在传入负值作为中心裁剪比例时是否会引发预期的值错误异常
'''
def test_central_crop_central_fraction_negative(): def test_central_crop_central_fraction_negative():
central_fraction = -1.0 central_fraction = -1.0
with pytest.raises(ValueError): with pytest.raises(ValueError):
_ = CentralCropNet(central_fraction) _ = CentralCropNet(central_fraction)
'''
用于测试中心裁剪操作在传入零作为中心裁剪比例时是否会引发预期的值错误异常
'''
def test_central_fraction_zero(): def test_central_fraction_zero():
central_fraction = 0.0 central_fraction = 0.0
with pytest.raises(ValueError): with pytest.raises(ValueError):
_ = CentralCropNet(central_fraction) _ = CentralCropNet(central_fraction)
'''
用于测试在传入维度不正确的 5D 输入时是否会引发预期的值错误异常
'''
def test_central_crop_invalid_5d_input(): def test_central_crop_invalid_5d_input():
invalid_shape = (8, 3, 16, 16, 1) invalid_shape = (8, 3, 16, 16, 1)
invalid_image = Tensor(np.random.random(invalid_shape)) invalid_image = Tensor(np.random.random(invalid_shape))

View File

@ -14,10 +14,16 @@
# ============================================================================ # ============================================================================
""" test_run_config """ """ test_run_config """
import pytest import pytest
''''
从MindSpore库中导入CheckpointConfig类
指定训练过程中保存检查点的条件
''''
from mindspore.train.callback import CheckpointConfig from mindspore.train.callback import CheckpointConfig
'''
定义测试函数通过断言来验证在初始化'CheckpointConfig'类后
对象的属性是否被正确设置并确保'get_checkpoint_policy()'方法能够正确返回检查点策略的相关信息
'''
def test_init(): def test_init():
""" test_init """ """ test_init """
save_checkpoint_steps = 1 save_checkpoint_steps = 1
@ -31,7 +37,12 @@ def test_init():
policy = config.get_checkpoint_policy() policy = config.get_checkpoint_policy()
assert policy['keep_checkpoint_max'] == keep_checkpoint_max assert policy['keep_checkpoint_max'] == keep_checkpoint_max
'''
函数 test_arguments_values()验证'CheckpointConfig'类在初始化和参数设置方面的正确性
以确保在使用该类时能够提供有效的参数并正确处理可能出现的异常情况
这是一种测试驱动开发Test-Driven DevelopmentTDD的实践方式
通过编写测试来规范类的行为和功能保证其在使用中的稳定性和正确性
'''
def test_arguments_values(): def test_arguments_values():
""" test_arguments_values """ """ test_arguments_values """
config = CheckpointConfig() config = CheckpointConfig()