Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LIB: Add mindspore backend #169

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions lib/sedna/backend/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,24 @@
def set_backend(estimator=None, config=None):
"""Create Trainer clss."""
if estimator is None:
return
return None
if config is None:
config = BaseConfig()
use_cuda = False
use_npu = False
backend_type = os.getenv(
'BACKEND_TYPE', config.get("backend_type", "UNKNOWN")
)
backend_type = str(backend_type).upper()
device_category = os.getenv(
'DEVICE_CATEGORY', config.get("device_category", "CPU")
)
if 'CUDA_VISIBLE_DEVICES' in os.environ:

# NPU>GPU>CPU
if device_category == "NPU":
use_npu = True
os.environ['DEVICE_CATEGORY'] = "NPU"
elif 'CUDA_VISIBLE_DEVICES' in os.environ:
os.environ['DEVICE_CATEGORY'] = 'GPU'
use_cuda = True
else:
Expand All @@ -44,14 +50,18 @@ def set_backend(estimator=None, config=None):
from sedna.backend.tensorflow import TFBackend as REGISTER
elif backend_type == "KERAS":
from sedna.backend.tensorflow import KerasBackend as REGISTER
elif backend_type == "MINDSPORE":
from sedna.backend.mindspore import MSBackend as REGISTER
else:
warnings.warn(f"{backend_type} Not Support yet, use itself")
from sedna.backend.base import BackendBase as REGISTER

model_save_url = config.get("model_url")
base_model_save = config.get("base_model_url") or model_save_url
model_save_name = config.get("model_name")
return REGISTER(
estimator=estimator, use_cuda=use_cuda,
use_npu=use_npu,
model_save_path=base_model_save,
model_name=model_save_name,
model_save_url=model_save_url
Expand Down
8 changes: 6 additions & 2 deletions lib/sedna/backend/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class BackendBase:
def __init__(self, estimator, fine_tune=True, **kwargs):
self.framework = ""
self.estimator = estimator
self.use_npu = True if kwargs.get("use_npu") else False
self.use_cuda = True if kwargs.get("use_cuda") else False
self.fine_tune = fine_tune
self.model_save_path = kwargs.get("model_save_path") or "/tmp"
Expand All @@ -34,8 +35,11 @@ def __init__(self, estimator, fine_tune=True, **kwargs):
def model_name(self):
if self.default_name:
return self.default_name
model_postfix = {"pytorch": ".pth",
"keras": ".pb", "tensorflow": ".pb"}
model_postfix = {
"pytorch": ".pth",
"keras": ".pb",
"tensorflow": ".pb",
"mindspore": ".ckpt"}
continue_flag = "_finetune_" if self.fine_tune else ""
post_fix = model_postfix.get(self.framework, ".pkl")
return f"model{continue_flag}{self.framework}{post_fix}"
Expand Down
74 changes: 74 additions & 0 deletions lib/sedna/backend/mindspore/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Copyright 2021 The KubeEdge Authors.
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for your great job! BTW, should we provide some example about mindspore to end user? joint inference or incremental learning?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, I'll upload a resnet example by tomorrow

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@chou-shun please put your example in lib/examples/backend/mindspore/.

#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

import mindspore.context as context
from sedna.backend.base import BackendBase
from sedna.common.file_ops import FileOps


class MSBackend(BackendBase):
def __init__(self, estimator, fine_tune=True, **kwargs):
super(MSBackend, self).__init__(estimator=estimator,
fine_tune=fine_tune,
**kwargs)
self.framework = "mindspore"

if self.use_npu:
context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
elif self.use_cuda:
context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
else:
context.set_context(mode=context.GRAPH_MODE, device_target="CPU")

if callable(self.estimator):
self.estimator = self.estimator()

def train(self, train_data, valid_data=None, **kwargs):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on existing specifications, the first parameter in train is lib.sedna.datasources.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is because both formats (CSV, TXT) in datasource do not support cifar-10 datasets.
cifar-10: data_batch_1.bin, data_batch_2.bin, data_batch_3.bin,..., test_batch.bin

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for the misunderstanding. datasource inherited of BaseDataSource,as that core feature of sedna require identifying the features and labels from data input, we specify that the first parameter for train/evaluate of the ML framework must be a specific object (inherited of BaseDataSource).

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, I get it. However, should I develop a specific datasource for the cifar-10 dataset? This will be a little complicated...

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be a huge help to our community. And I would like you to give the professional advice on how to design DataSource.
In this example, it might be solved by:

from sedna.datasources import BaseDataSource

mnist_ds = ds.MnistDataset(train_data_path)

train_data = BaseDataSource(data_type="train")
train_data.x = []
train_data.y = []
for item in mnist_ds.create_dict_iterator():
     train_data.x.append(item["image"].asnumpy())
     train_data.y.append(item["label"].asnumpy())

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, I'll solve it as soon as possible.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried your method, but it didn't work very well. That is because, for method mindspore.Model.train, the data passed to it MUST BE a mindspore.Dataset, and can not be a BaseDataSource.
Here are some solutions I thought of:

    1. Abandon class mindspore.Model and adopt a more flexible approach: for data in dataloader: loss = network(data), loss.update().
    1. Repackage train_data into a mindspore.Dataset in interface.py.

For solution 1, it increases the difficulty of model development and is not a popular way.
For solution 2, actually it is counterintuitive.
Which do you prefer? Or do you have a more reasonable solution?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PTAL @jaypume

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest that BaseDataSorce is designed to compatible with existing Dataset such as mindspore.Dataset, torch.utils.data.Dataset, tf.data.Dataset. If the Dataset instance is passed to for example FederatedLearning.train(tfDatasetInstance), it should work.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest that BaseDataSorce is designed to compatible with existing Dataset such as mindspore.Dataset, torch.utils.data.Dataset, tf.data.Dataset. If the Dataset instance is passed to for example FederatedLearning.train(tfDatasetInstance), it should work.

You can help us raise an issue so we can track it.

if callable(self.estimator):
self.estimator = self.estimator()
if self.fine_tune and FileOps.exists(self.model_save_path):
self.finetune()
self.has_load = True
varkw = self.parse_kwargs(self.estimator.train, **kwargs)
return self.estimator.train(train_data=train_data,
valid_data=valid_data,
**varkw)

def predict(self, data, **kwargs):
if not self.has_load:
self.load()
varkw = self.parse_kwargs(self.estimator.predict, **kwargs)
return self.estimator.predict(data=data, **varkw)

def evaluate(self, data, **kwargs):
if not self.has_load:
self.load()
varkw = self.parse_kwargs(self.estimator.evaluate, **kwargs)
return self.estimator.evaluate(data, **varkw)

def finetune(self):
"""todo: no support yet"""

def load_weights(self):
model_path = FileOps.join_path(self.model_save_path, self.model_name)
if os.path.exists(model_path):
self.estimator.load_weights(model_path)

def get_weights(self):
"""todo: no support yet"""
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return self.estimator.parameters_dict()


def set_weights(self, weights):
"""todo: no support yet"""
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for name, weight in weights.items():
weights[name] = mindspore.Parameter(weight, name=name)
mindspore.load_param_into_net(self.estimator, weights, strict_load=True)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

self.estimator is not a net. get_weights and set_weights would to be developed later:)
mindspore.load_param_into_net(net, parameter_dict, strict_load=False)