internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: PaddlePaddle/PaddleSeg

Issue:
训练结束后自动导出IOU指标最好的模型
自动导出IOU指标最好的模型，而不是导出 `final`


Discussion:
您好，此功能正在开发中，敬请期待！

Resolving patch:
diff --git a/pdseg/train.py b/pdseg/train.py
--- a/pdseg/train.py
+++ b/pdseg/train.py
@@ -179,6 +179,13 @@ def load_checkpoint(exe, program):
     return begin_epoch
 
 
+def update_best_model(ckpt_dir):
+    best_model_dir = os.path.join(cfg.TRAIN.MODEL_SAVE_DIR, 'best_model')
+    if os.path.exists(best_model_dir):
+        shutil.rmtree(best_model_dir)
+    shutil.copytree(ckpt_dir, best_model_dir)
+
+
 def print_info(*msg):
     if cfg.TRAINER_ID == 0:
         print(*msg)
@@ -341,6 +348,8 @@ def var_shape_matched(var, shape):
     all_step *= (cfg.SOLVER.NUM_EPOCHS - begin_epoch + 1)
 
     avg_loss = 0.0
+    best_mIoU = 0.0
+
     timer = Timer()
     timer.start()
     if begin_epoch > cfg.SOLVER.NUM_EPOCHS:
@@ -445,6 +454,14 @@ def var_shape_matched(var, shape):
                     log_writer.add_scalar('Evaluate/mean_acc', mean_acc,
                                           global_step)
 
+                if mean_iou > best_mIoU:
+                    best_mIoU = mean_iou
+                    update_best_model(ckpt_dir)
+                    print_info("Save best model {} to {}, mIoU = {:.4f}".format(
+                        ckpt_dir,
+                        os.path.join(cfg.TRAIN.MODEL_SAVE_DIR, 'best_model'),
+                        mean_iou))
+
             # Use Tensorboard to visualize results
             if args.use_tb and cfg.DATASET.VIS_FILE_LIST is not None:
                 visualize(


Test patch:
Repository: PaddlePaddle/PaddleSeg

Issue:
评估时模型路径不存在直接报load op的错



Discussion:

Resolving patch:
diff --git a/pdseg/eval.py b/pdseg/eval.py
--- a/pdseg/eval.py
+++ b/pdseg/eval.py
@@ -111,6 +111,9 @@ def data_generator():
 
     ckpt_dir = cfg.TEST.TEST_MODEL if not ckpt_dir else ckpt_dir
 
+    if not os.path.exists(ckpt_dir):
+        raise ValueError('The TEST.TEST_MODEL {} is not found'.format(ckpt_dir))
+
     if ckpt_dir is not None:
         print('load test model:', ckpt_dir)
         fluid.io.load_params(exe, ckpt_dir, main_program=test_prog)


Test patch:
Repository: PaddlePaddle/PaddleSeg

Issue:
文件列表生成工具问题
在使用pdseg/tools/create_dataset_list.py时，我的数据集中有个别图像没有对应的标注图像，能够正常生成训练列表，但出现标注图和原图对应不上的问题。
![image](https://user-images.githubusercontent.com/30919197/71572213-079b0c80-2b19-11ea-8d6e-c1556d09956c.png)



Discussion:

Resolving patch:
diff --git a/pdseg/tools/create_dataset_list.py b/pdseg/tools/create_dataset_list.py
--- a/pdseg/tools/create_dataset_list.py
+++ b/pdseg/tools/create_dataset_list.py
@@ -116,18 +116,19 @@ def generate_list(args):
         label_files = get_files(1, dataset_split, args)
         if not image_files:
             img_dir = os.path.join(dataset_root, args.folder[0], dataset_split)
-            print("No files in {}".format(img_dir))
+            warnings.warn("No images in {} !!!".format(img_dir))
         num_images = len(image_files)
 
         if not label_files:
             label_dir = os.path.join(dataset_root, args.folder[1], dataset_split)
-            print("No files in {}".format(label_dir))
+            warnings.warn("No labels in {} !!!".format(label_dir))
         num_label = len(label_files)
 
-        if num_images < num_label:
-            warnings.warn("number of images = {}  <  number of labels = {}."
-                          .format(num_images, num_label))
-            continue
+        if num_images != num_label and num_label > 0:
+            raise Exception("Number of images = {}    number of labels = {} \n"
+                            "Either number of images is equal to number of labels, "
+                            "or number of labels is equal to 0.\n"
+                            "Please check your dataset!".format(num_images, num_label))
 
         file_list = os.path.join(dataset_root, dataset_split + '.txt')
         with open(file_list, "w") as f:


Test patch:
Repository: PaddlePaddle/PaddleSeg

Issue:
infer.py中的bug
（1）132行中，if (ori_h != eval_crop_size[0] or ori_w != eval_crop_size[1]):，eval_crop_size[0]为宽，eval_crop_size[1]为高，应该修改为if ori_h != eval_crop_size[1] or ori_w != eval_crop_size[0]:

（2）117行中的im = cv2.imread(image_path, -1)，如果输入为RGB彩色图片，读入的为im为一维图层，并且会在channels = im.shape[2]处报错，应该修改为im = cv2.imread(image_path)，则读取3维RGB图像。

————————————
支持paddle   支持国产


Discussion:
(1)是的，eval_crop_size[0]为宽，eval_crop_size[1]为高，这地方我们修改一下，感谢反馈！
(2)还是得用 cv2.imread(image_path, -1)，因为cv2.imread(image_path)会忽略rgba的alpha通道。这边的问题我们通过另外的方式修复一下，感谢反馈！

Resolving patch:
diff --git a/deploy/python/infer.py b/deploy/python/infer.py
--- a/deploy/python/infer.py
+++ b/deploy/python/infer.py
@@ -107,7 +107,6 @@ def __init__(self, conf_file):
             self.use_pr = deploy_conf["USE_PR"]
 
 
-
 class ImageReader:
     def __init__(self, configs):
         self.config = configs
@@ -117,19 +116,18 @@ def __init__(self, configs):
     def process_worker(self, imgs, idx, use_pr=False):
         image_path = imgs[idx]
         im = cv2.imread(image_path, -1)
-        channels = im.shape[2]
-        ori_h = im.shape[0]
-        ori_w = im.shape[1]
-        if channels == 1:
+        if len(im.shape) == 2:
             im = cv2.cvtColor(im, cv2.COLOR_GRAY2BGR)
-            channels = im.shape[2]
+        channels = im.shape[2]
         if channels != 3 and channels != 4:
             print("Only support rgb(gray) or rgba image.")
             return -1
+        ori_h = im.shape[0]
+        ori_w = im.shape[1]
 
         # resize to eval_crop_size
         eval_crop_size = self.config.eval_crop_size
-        if (ori_h != eval_crop_size[0] or ori_w != eval_crop_size[1]):
+        if (ori_h != eval_crop_size[1] or ori_w != eval_crop_size[0]):
             im = cv2.resize(
                 im, eval_crop_size, fx=0, fy=0, interpolation=cv2.INTER_LINEAR)
 


Test patch:
Repository: PaddlePaddle/PaddleSeg

Issue:
DecoupledSegNet错误
1.环境：（首先安装cpu版本，测试成功）
 
![当前环境](https://user-images.githubusercontent.com/52094265/115170646-aaeba880-a0f3-11eb-8a22-04cd130f4ddb.png)


2.安装GPU版本
命令：python -m pip install paddlepaddle-gpu==2.0.0 -i https://mirror.baidu.com/pypi/simple

3.出现问题
 
![出现问题一](https://user-images.githubusercontent.com/52094265/115170506-62cc8600-a0f3-11eb-8160-fc211569fce5.png)

4.解决方案
（1）env | grep cuda
（2）port LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64
（3） /usr/local/cuda/lib64
（4）ln -s libcusolver.so.10 libcusolver.so

5. 运行 
Python./train.py -config ./configs/decoupled_segnet/decoupledsegnet_resnet50_os8_cityscapes_832x832_80k.yml

6.新问题
![出现问题二](https://user-images.githubusercontent.com/52094265/115170587-91e2f780-a0f3-11eb-81a7-42b22cedd807.png)





Discussion:

Resolving patch:
diff --git a/paddleseg/models/decoupled_segnet.py b/paddleseg/models/decoupled_segnet.py
--- a/paddleseg/models/decoupled_segnet.py
+++ b/paddleseg/models/decoupled_segnet.py
@@ -213,6 +213,7 @@ def forward(self, x):
     def flow_warp(self, input, flow, size):
         input_shape = paddle.shape(input)
         norm = size[::-1].reshape([1, 1, 1, -1])
+        norm.stop_gradient = True
         h_grid = paddle.linspace(-1.0, 1.0, size[0]).reshape([-1, 1])
         h_grid = h_grid.tile([size[1]])
         w_grid = paddle.linspace(-1.0, 1.0, size[1]).reshape([-1, 1])


Test patch:
Repository: PaddlePaddle/PaddleSeg

Issue:
CityscapeSOTA的MscaleOCRNet导出静态图报错

![QQ截图20211113132935](https://user-images.githubusercontent.com/51190264/141607069-ece86232-c716-45c7-b447-b59cb7294260.png)

我已经把CityscapeSOTA目录下的models复制加载到paddleseg.core.models的目录下，但在导出静态图的时候提示backbone输出维度有错误，因为源代码有点复杂，一时半会无法定位和解决问题，希望官方能提供修复帮助。

报错复现地址：https://aistudio.baidu.com/aistudio/projectdetail/2654280?shared=1


Discussion:

Resolving patch:
diff --git a/contrib/CityscapesSOTA/models/backbones/hrnet_nv.py b/contrib/CityscapesSOTA/models/backbones/hrnet_nv.py
--- a/contrib/CityscapesSOTA/models/backbones/hrnet_nv.py
+++ b/contrib/CityscapesSOTA/models/backbones/hrnet_nv.py
@@ -171,17 +171,17 @@ def forward(self, x):
         tr3 = self.tr3(st3)
         st4 = self.st4(tr3)
 
-        x0_h, x0_w = st4[0].shape[2:]
+        x0_hw = paddle.shape(st4[0])[2:]
         x1 = F.interpolate(
-            st4[1], (x0_h, x0_w),
+            st4[1], x0_hw,
             mode='bilinear',
             align_corners=self.align_corners)
         x2 = F.interpolate(
-            st4[2], (x0_h, x0_w),
+            st4[2], x0_hw,
             mode='bilinear',
             align_corners=self.align_corners)
         x3 = F.interpolate(
-            st4[3], (x0_h, x0_w),
+            st4[3], x0_hw,
             mode='bilinear',
             align_corners=self.align_corners)
         x = paddle.concat([st4[0], x1, x2, x3], axis=1)
@@ -606,7 +606,7 @@ def forward(self, x):
         residual_func_idx = 0
         for i in range(self._actual_ch):
             residual = x[i]
-            residual_shape = residual.shape[-2:]
+            residual_shape = paddle.shape(residual)[-2:]
             for j in range(len(self._in_channels)):
                 if j > i:
                     y = self.residual_func_list[residual_func_idx](x[j])
diff --git a/contrib/CityscapesSOTA/models/mscale_ocrnet.py b/contrib/CityscapesSOTA/models/mscale_ocrnet.py
--- a/contrib/CityscapesSOTA/models/mscale_ocrnet.py
+++ b/contrib/CityscapesSOTA/models/mscale_ocrnet.py
@@ -151,7 +151,7 @@ def nscale_forward(self, x_1x, scales):
         return [pred]
 
     def single_scale_forward(self, x):
-        x_size = x.shape[2:]
+        x_size = paddle.shape(x)[2:]
         cls_out, aux_out, ocr_mid_feats = self.ocrnet(x)
         attn = self.scale_attn(ocr_mid_feats)
 
@@ -194,7 +194,7 @@ def scale_as(x, y, align_corners=False):
     '''
     scale x to the same size as y
     '''
-    y_size = y.shape[2], y.shape[3]
+    y_shape = paddle.shape(y)
     x_scaled = nn.functional.interpolate(
-        x, size=y_size, mode='bilinear', align_corners=align_corners)
+        x, size=(y_shape[2], y_shape[3]), mode='bilinear', align_corners=align_corners)
     return x_scaled


Test patch:
Repository: PaddlePaddle/PaddleSeg

Issue:
[Bug] tools/split_dataset_list.py 划分数据集异常
环境信息

 1. PaddleSeg版本：PaddleSeg release/2.5
 2. PaddlePaddle版本：PaddlePaddle 2.2
 3. 操作系统信息：Linux
 4. Python版本号：Python3.7

使用的脚本命令

```bash
export dataset_root=/home/real_data
export images_dir_name=/home/real_data/images
export labels_dir_name=/home/real_data/annotations
python tools/split_dataset_list.py ${dataset_root} ${images_dir_name} ${labels_dir_name} \
    --split 0.7 0.2 0.1
```

报错信息

```plaintext
Traceback (most recent call last):
  File "tools/split_dataset_list.py", line 151, in <module>
    generate_list(args)
  File "tools/split_dataset_list.py", line 82, in generate_list
    raise ValueError("划分比例之和必须为1")
ValueError: 划分比例之和必须为1
```

原因分析

此处对浮点数进行了**不等于**判断

https://github.com/PaddlePaddle/PaddleSeg/blob/03e7cef61431077036acfb112e28eee36d2ae092/tools/split_dataset_list.py#L81-L82

实际上不能直接对浮点数进行等于或不等于判读

```Python
Python 3.7.5 (default, Dec  9 2021, 17:04:37) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 0.7 + 0.2 + 0.1
0.9999999999999999
>>> 
```

修改建议

添加或者使用如下类似的判断

```Python
def float_equal(a: float, b: float) -> bool:
    allowed_error = 1e-8
    return abs(a - b) <= allowed_error
```

```Python
    if not float_equal(sum(args.split), 1.0):
        raise ValueError("划分比例之和必须为1")
```


Discussion:
👍

Resolving patch:
diff --git a/tools/split_dataset_list.py b/tools/split_dataset_list.py
--- a/tools/split_dataset_list.py
+++ b/tools/split_dataset_list.py
@@ -78,7 +78,7 @@ def get_files(path, format, postfix):
 def generate_list(args):
     separator = args.separator
     dataset_root = args.dataset_root
-    if sum(args.split) != 1.0:
+    if abs(sum(args.split) - 1.0) > 1e-8:
         raise ValueError("划分比例之和必须为1")
 
     file_list = os.path.join(dataset_root, 'labels.txt')


Test patch:
Repository: PaddlePaddle/PaddleSeg

Issue:
关于推理部分出现的BUG

![image](https://user-images.githubusercontent.com/83204995/170969692-85d286f3-fc1c-4b6b-9620-6e42b8b39db5.png)
![image](https://user-images.githubusercontent.com/83204995/170969750-17e8d565-8197-42de-998a-18332d86d122.png)



Discussion:
我按照说明文档进行实验，但是不知道在哪测试FPS，遇到了如上的问题。
这是由于校验paddle和onnx模型输出是否存在误差，你可以将如下代码的atol设置大一点，比如1e-2。
![image](https://user-images.githubusercontent.com/52520497/171079378-b8b498d8-9fc1-4a69-ada7-8ce84cffd4d7.png)

将atol设置成1e-2后出现如下问题，如何解决？
![image](https://user-images.githubusercontent.com/83204995/171165309-6fb15659-4d45-4991-b2aa-58fd9a478131.png)

您好，上面的问题是由于tensorrt的版本BUG我已经解决。
![image](https://user-images.githubusercontent.com/83204995/171343264-b3d3b217-d781-4008-a8a3-a4633e3baa4d.png)

然后关于这里的测试结果是平均时延，论文的指标为FPS，如果计算这里的倒数，也与论文PP-LiteSeg-B1 1024X512的195.3相差很多，请问这可能是什么原因造成的？

这个跑出来fps差距有点大，是不是这个显卡也有其他进程在运行？ 
您好，在cityscapes上我的测速达到了论文效果，但是想在camvid数据集上测速时，却遇到了如下问题：
![image](https://user-images.githubusercontent.com/83204995/172371249-cceab91f-d7f3-46b5-9595-7435c5845b06.png)
意思是缺少类别数，请问要在哪里修改。

Resolving patch:
diff --git a/paddleseg/cvlibs/config.py b/paddleseg/cvlibs/config.py
--- a/paddleseg/cvlibs/config.py
+++ b/paddleseg/cvlibs/config.py
@@ -315,17 +315,22 @@ def model(self) -> paddle.nn.Layer:
         model_cfg = self.dic.get('model').copy()
         if not model_cfg:
             raise RuntimeError('No model specified in the configuration file.')
+
         if not 'num_classes' in model_cfg:
             num_classes = None
             try:
                 if self.train_dataset_config:
                     if hasattr(self.train_dataset_class, 'NUM_CLASSES'):
                         num_classes = self.train_dataset_class.NUM_CLASSES
+                    elif 'num_classes' in self.train_dataset_config:
+                        num_classes = self.train_dataset_config['num_classes']
                     elif hasattr(self.train_dataset, 'num_classes'):
                         num_classes = self.train_dataset.num_classes
                 elif self.val_dataset_config:
                     if hasattr(self.val_dataset_class, 'NUM_CLASSES'):
                         num_classes = self.val_dataset_class.NUM_CLASSES
+                    elif 'num_classes' in self.val_dataset_config:
+                        num_classes = self.val_dataset_config['num_classes']
                     elif hasattr(self.val_dataset, 'num_classes'):
                         num_classes = self.val_dataset.num_classes
             except FileNotFoundError:


Test patch:
Repository: PaddlePaddle/PaddleSeg

Issue:
[Bug] Dice loss bug
环境：aistudio tesla v100
paddlepaddle=2.3.0
paddleseg=2.5.0

bug：dice loss 前向传播时，label转换为one-hot编码前，并未对ignore_index进行处理，当ignore_index值大于num_classes（比如ignore index为255，类别为19）时，报错cuda 719。原因为one-hot转换错误。 
代码链接：https://github.com/PaddlePaddle/PaddleSeg/blob/35a4c4d229df2d4a5ca724ad442bf5e0f75b4823/paddleseg/models/losses/dice_loss.py#L46

可将mask部分放到one-hot之前，然后将ignore_index赋值一个小于num_classes的值：
```python
 def forward(self, logits, labels):
        num_class = logits.shape[1]
        if self.weight is not None:
            assert num_class == len(self.weight), \
                "The lenght of weight should be euqal to the num class"
        if logits.shape != labels.shape:
            labels = labels.unsqueeze(axis=1)
            labels = F.interpolate(labels, size=logits.shape[2:], mode='nearest')
            labels = labels.squeeze(axis=1)
        logits = F.softmax(logits, axis=1)
        mask = labels != self.ignore_index
        mask = paddle.cast(paddle.unsqueeze(mask, 1), 'float32')
        labels[labels == self.ignore_index] = 0
        labels_one_hot = F.one_hot(labels, num_class)
        labels_one_hot = paddle.transpose(labels_one_hot, [0, 3, 1, 2])
        
        dice_loss = 0.0
        for i in range(num_class):
            dice_loss_i = dice_loss_helper(logits[:, i], labels_one_hot[:, i],
                                           mask, self.smooth, self.eps)
            if self.weight is not None:
                dice_loss_i *= self.weight[i]
            dice_loss += dice_loss_i
        dice_loss = dice_loss / num_class

        return dice_loss
```



Discussion:
感谢，我们就合入修复pr。

Resolving patch:
diff --git a/paddleseg/models/losses/dice_loss.py b/paddleseg/models/losses/dice_loss.py
--- a/paddleseg/models/losses/dice_loss.py
+++ b/paddleseg/models/losses/dice_loss.py
@@ -42,13 +42,14 @@ def forward(self, logits, labels):
             assert num_class == len(self.weight), \
                 "The lenght of weight should be euqal to the num class"
 
-        logits = F.softmax(logits, axis=1)
-        labels_one_hot = F.one_hot(labels, num_class)
-        labels_one_hot = paddle.transpose(labels_one_hot, [0, 3, 1, 2])
-
         mask = labels != self.ignore_index
         mask = paddle.cast(paddle.unsqueeze(mask, 1), 'float32')
 
+        labels[labels == self.ignore_index] = 0
+        labels_one_hot = F.one_hot(labels, num_class)
+        labels_one_hot = paddle.transpose(labels_one_hot, [0, 3, 1, 2])
+        logits = F.softmax(logits, axis=1)
+
         dice_loss = 0.0
         for i in range(num_class):
             dice_loss_i = dice_loss_helper(logits[:, i], labels_one_hot[:, i],


Test patch:
Repository: PaddlePaddle/PaddleSeg

Issue:
[General Issue] Jeston Xavier NX上TRT部署失败
Thanks for your issue. To help us solve the issue better, please provide following information：
 1. PaddleSeg version: PaddleSeg release/2.6
 2. PaddlePaddle version: PaddlePaddle GPU 2.3.2
 3. Operation system: Ubuntu 18.04
 4. Python version: Python3.6
 5. CUDA/cuDNN version: CUDA10.2，cuDNN 8.2.1 Tensorrt 8.0.1.6 
 6. Additional context: (Add any other context about the problem)

---

欢迎您反馈PaddleSeg使用问题，辛苦您提供以下信息，方便我们快速定位和解决问题：
 1. PaddleSeg版本：PaddleSeg release/2.6
 2. PaddlePaddle版本：PaddlePaddle GPU 2.3.2
 3. 操作系统信息：Ubuntu 18.04
 4. Python版本号：Python3.6
 5. CUDA/cuDNN版本：CUDA10.2，cuDNN 8.2.1 Tensorrt 8.0.1.6
 6. GCC 7.5
 可以用原生GPU运行，PaddleSeg/deploy/cpp/run_seg_gpu.sh运行没有问题。
使用PaddleSeg/deploy/cpp/run_seg_gpu_trt.sh提示
InvalidArgumentError: The input [concat_1.tmp_0] shape of trt subgraph is [-1,256,-1,-1], please enable trt dynamic_shape mode by SetTRTDynamicShapeInfo. (at /home/paddle/data/wangye19/tag_release/remove_paddle/Paddle/paddle/fluid/inference/tensorrt/engine.h:96)
参照PaddleSeg/docs/deployment/inference/cpp_inference_cn.md，使用以下命令
python3 ../python/collect_dynamic_shape.py --config stdc1seg_infer_model/deploy.yaml --image_path ./cityscapes_demo.png --dynamic_shape_path ./dynamic_shape.pbtxt
报以下错误：
![image](https://user-images.githubusercontent.com/29418627/186838808-254d216c-4306-4b98-b20c-aea8a4da6ebb.png)
请问怎样才能用TRT部署分割推理？




Discussion:
您好，这个问题有没有解决呢

> 您好，这个问题有没有解决呢

没
收到，这是一个bug，我们这两天就会修复。  
上一个版本 2.5 应该没有这个bug，如果你们着急，可以先使用上个版本。

Resolving patch:
diff --git a/deploy/python/collect_dynamic_shape.py b/deploy/python/collect_dynamic_shape.py
--- a/deploy/python/collect_dynamic_shape.py
+++ b/deploy/python/collect_dynamic_shape.py
@@ -86,7 +86,8 @@ def collect_dynamic_shape(args):
     # collect
     progbar_val = progbar.Progbar(target=len(img_path_list))
     for idx, img_path in enumerate(img_path_list):
-        data = np.array([cfg.transforms(img_path)[0]])
+        data = {'img': img_path}
+        data = np.array([cfg.transforms(data)['img']])
         input_handle.reshape(data.shape)
         input_handle.copy_from_cpu(data)
 
diff --git a/deploy/python/infer.py b/deploy/python/infer.py
--- a/deploy/python/infer.py
+++ b/deploy/python/infer.py
@@ -176,7 +176,8 @@ def auto_tune(args, imgs, img_nums):
 
     for i in range(0, num):
         if isinstance(imgs[i], str):
-            data = np.array([cfg.transforms(imgs[i])[0]])
+            data = {'img': imgs[i]}
+            data = np.array([cfg.transforms(data)['img']])
         else:
             data = imgs[i]
         input_handle.reshape(data.shape)


Test patch:
Repository: PaddlePaddle/PaddleSeg

Issue:
tool/model/analyze_model.py 分析flops文件问题
### 问题确认 Search before asking

- [X] 我已经查询[历史issue](https://github.com/PaddlePaddle/PaddleSeg/issues)(包括open与closed)，没有发现相似的bug。I have searched the [open and closed issues](https://github.com/PaddlePaddle/PaddleSeg/issues) and found no similar bug report.


### Bug描述 Describe the Bug

在运行tool/model/analyze_model.py出现错误：
AttributeError: 'Config' object has no attribute 'model' 

tool/model/analyze_model.py源码中并没有根据model_cfg实例化出一个具体的model，而在'_dynamic_flops'函数中，
代码不断调用`model.train()`,'model.eval()'等函数

### 复现环境 Environment


platform: Linux-5.10.16.3-microsoft-standard-WSL2-x86_64-with-glibc2.31
Python: 3.9.0 (default, Nov 15 2020, 14:28:56) [GCC 7.3.0]
Paddle compiled with cuda: False
GCC: gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
PaddleSeg: 2.8.0
PaddlePaddle: 2.4.2
OpenCV: 4.5.5

### Bug描述确认 Bug description confirmation

- [X] 我确认已经提供了Bug复现步骤、代码改动说明、以及环境信息，确认问题是可以复现的。I confirm that the bug replication steps, code change instructions, and environment information have been provided, and the problem can be reproduced.


### 是否愿意提交PR？ Are you willing to submit a PR?

- [ ] 我愿意提交PR！I'd like to help by submitting a PR!


Discussion:
这是一个bug，稍后会进行修复，你可以先用更低版本的paddleseg

Resolving patch:
diff --git a/tools/model/analyze_model.py b/tools/model/analyze_model.py
--- a/tools/model/analyze_model.py
+++ b/tools/model/analyze_model.py
@@ -21,14 +21,14 @@
 import os
 import sys
 
-import paddle
 import numpy as np
+import paddle
+from paddle.hapi.dynamic_flops import (count_io_info, count_parameters,
+                                       register_hooks)
+from paddle.hapi.static_flops import Table
 
-from paddleseg.cvlibs import Config
+from paddleseg.cvlibs import Config, SegBuilder
 from paddleseg.utils import get_sys_env, logger, op_flops_funs
-from paddle.hapi.dynamic_flops import (count_parameters, register_hooks,
-                                       count_io_info)
-from paddle.hapi.static_flops import Table
 
 
 def parse_args():
@@ -140,10 +140,11 @@ def analyze(args):
     paddle.set_device('cpu')
 
     cfg = Config(args.config)
+    builder = SegBuilder(cfg)
 
     custom_ops = {paddle.nn.SyncBatchNorm: op_flops_funs.count_syncbn}
     inputs = paddle.randn(args.input_shape)
-    _dynamic_flops(cfg.model, inputs, custom_ops=custom_ops, print_detail=True)
+    _dynamic_flops(builder.model, inputs, custom_ops=custom_ops, print_detail=True)
 
 
 if __name__ == '__main__':


Test patch: