PaddlePaddle / Paddle

PArallel Distributed Deep LEarning: Machine Learning Framework from Industrial Practice (『飞桨』核心框架,深度学习&机器学习高性能单机、分布式训练和跨平台部署)
http://www.paddlepaddle.org/
Apache License 2.0
22.14k stars 5.56k forks source link

动转静模型i保存nference模型用于部署 #43795

Closed fan-min-97 closed 1 year ago

fan-min-97 commented 2 years ago

请提出你的问题 Please ask your question

# save inference model
from paddle.static import InputSpec
# 加载训练好的模型参数
state_dict = paddle.load("./mnist.pdparams")
# 将训练好的参数读取到网络中
model.set_state_dict(state_dict)
# 设置模型为评估模式
model.eval()

# 保存inference模型
paddle.jit.save(
    layer=model,
    path="inference/mnist",
    input_spec=[InputSpec(shape=[None, 784], dtype='float32')])

print("==>Inference model saved in inference/mnist.")

在动态转静态时, input_spec=[InputSpec(shape=[None, 784], dtype='float32')]) ,总是报错,写成这样的报错是需要4-5个dimension写成 input_spec=[InputSpec(shape=[None, 3,60,640], dtype='float32')]),显示float需要的的是str或者number,而不是list。请问这个地方怎么写呢?

paddle-bot-old[bot] commented 2 years ago

您好,我们已经收到了您的问题,会安排技术人员尽快解答您的问题,请耐心等待。请您再次检查是否提供了清晰的问题描述、复现代码、环境&版本、报错信息等。同时,您也可以通过查看官网API文档常见问题历史IssueAI社区来寻求解答。祝您生活愉快~

Hi! We've received your issue and please be patient to get responded. We will arrange technicians to answer your questions as soon as possible. Please make sure that you have posted enough message to demo your request. You may also check out the APIFAQGithub Issue and AI community to get the answer.Have a nice day!

Aurelius84 commented 2 years ago

可否提供下你的model.forward 函数签名?

fan-min-97 commented 2 years ago

class Model(nn.Layer):     def init(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None, mode='training'):  # model, input channels, number of classes         super().init()         if isinstance(cfg, dict):             self.yaml = cfg  # model dict         else:  # is *.yaml             import yaml  # for paddle hub             self.yaml_file = Path(cfg).name             with open(cfg, errors='ignore') as f:                 self.yaml = yaml.safe_load(f)  # model dict

        # Define model         ch = self.yaml['ch'] = self.yaml.get('ch', ch)  # input channels         if nc and nc != self.yaml['nc']:             print(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")             self.yaml['nc'] = nc  # override yaml value         if anchors:             print(f'Overriding model.yaml anchors with anchors={anchors}')             self.yaml['anchors'] = round(anchors)  # override yaml value         self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch], mode=mode)  # model, savelist         self.names = [str(i) for i in range(self.yaml['nc'])]  # default names         self.inplace = self.yaml.get('inplace', True)

        # Build strides, anchors         m = self.model[-1]  # Detect()         if isinstance(m, Detect):             s = 256  # 2x min stride             m.inplace = self.inplace             m.stride = paddle.to_tensor([s / x.shape[-2] for x in self.forward(paddle.zeros([1, ch, s, s]))])  # forward             m.anchors /= m.stride.reshape([-1, 1, 1])             check_anchor_order(m)             self.stride = m.stride             self._initialize_biases()  # only run once

        # Init weights, biases         initialize_weights(self)         self.info()         print('')

def forward(self, x, augment=False, profile=False, visualize=False):         if augment:             return self._forward_augment(x)  # augmented inference, None         return self._forward_once(x, profile, visualize)  # single-scale inference, train

    def _forward_augment(self, x):         img_size = x.shape[-2:]  # height, width         s = [1, 0.83, 0.67]  # scales         f = [None, 3, None]  # flips (2-ud, 3-lr)         y = []  # outputs         for si, fi in zip(s, f):             xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))             yi = self._forwardonce(xi)[0]  # forward             # cv2.imwrite(f'img{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1])  # save             yi = self._descale_pred(yi, fi, si, img_size)             y.append(yi)         y = self._clip_augmented(y)  # clip augmented tails         return paddle.concat(y, 1), None  # augmented inference, train

    def _forward_once(self, x, profile=False, visualize=False):         y, dt = [], []  # outputs         for m in self.model:             if m.f != -1:  # if not from previous layer                 x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers             if profile:                 self._profile_one_layer(m, x, dt)             x = m(x)             y.append(x if m.i in self.save else None)  # save output             if visualize:                 feature_visualization(x, m.type, m.i, save_dir=visualize)         return x


以上是class Model中的函数,动态转静态paddle.jit.save input_spec=([InputSpec(shape=[None,3,608,608], dtype='float32',name='input')])

paddle.jit.save(     layer=model,     path="inference",     input_spec=[input])

总是报错,求回复咋改哦

------------------ 原始邮件 ------------------ 发件人: "PaddlePaddle/Paddle" @.>; 发送时间: 2022年6月24日(星期五) 上午10:14 @.>; @.**@.>; 主题: Re: [PaddlePaddle/Paddle] 动转静模型i保存nference模型用于部署 (Issue #43795)

可否提供下你的model.forward 函数签名?

— Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you authored the thread.Message ID: @.***>

Aurelius84 commented 2 years ago

抱歉,上面的代码似乎是乱码的,可否重贴一下?另外,请问你在训练时输入的Tensor的shape是什么样的?

paddle-bot[bot] commented 1 year ago

Since you haven\'t replied for more than a year, we have closed this issue/pr. If the problem is not solved or there is a follow-up one, please reopen it at any time and we will continue to follow up. 由于您超过一年未回复,我们将关闭这个issue/pr。 若问题未解决或有后续问题,请随时重新打开,我们会继续跟进。