"""
Input:
# Tensor("Placeholder:0", shape=(?, ?, 3), dtype=uint8)
Outputs:
# Tensor("ssd_300_vgg/block4_box/Reshape:0", shape=(1, 38, 38, 4, 4), dtype=float32)
# Tensor("ssd_300_vgg/softmax/Reshape_1:0", shape=(1, 38, 38, 4, 2), dtype=float32)
# Tensor("ssd_300_vgg/block7_box/Reshape:0", shape=(1, 19, 19, 6, 4), dtype=float32)
# Tensor("ssd_300_vgg/softmax_1/Reshape_1:0", shape=(1, 19, 19, 6, 2), dtype=float32)
# Tensor("ssd_300_vgg/block8_box/Reshape:0", shape=(1, 10, 10, 6, 4), dtype=float32)
# Tensor("ssd_300_vgg/softmax_2/Reshape_1:0", shape=(1, 10, 10, 6, 2), dtype=float32)
# Tensor("ssd_300_vgg/block9_box/Reshape:0", shape=(1, 5, 5, 6, 4), dtype=float32)
# Tensor("ssd_300_vgg/softmax_3/Reshape_1:0", shape=(1, 5, 5, 6, 2), dtype=float32)
# Tensor("ssd_300_vgg/block10_box/Reshape:0", shape=(1, 3, 3, 4, 4), dtype=float32)
# Tensor("ssd_300_vgg/softmax_4/Reshape_1:0", shape=(1, 3, 3, 4, 2), dtype=float32)
# Tensor("ssd_300_vgg/block11_box/Reshape:0", shape=(1, 1, 1, 4, 4), dtype=float32)
# Tensor("ssd_300_vgg/softmax_5/Reshape_1:0", shape=(1, 1, 1, 4, 2), dtype=float32)
"""
# python D:\OpenVINO\openvino_2020.4.287\deployment_tools\model_optimizer\mo.py --input_model SSD_300.pb --data_type FP16 --input_shape (300,300,3)

import tensorflow as tf
import matplotlib.pyplot as plt
import cv2
import numpy as np
import time
import random
from collections import namedtuple
from SSD import np_methods

SSDParams = namedtuple('SSDParameters', ['img_shape',
                                         'num_classes',
                                         'no_annotation_label',
                                         'feat_layers',
                                         'feat_shapes',
                                         'anchor_size_bounds',
                                         'anchor_sizes',
                                         'anchor_ratios',
                                         'anchor_steps',
                                         'anchor_offset',
                                         'normalizations',
                                         'prior_scaling'
                                         ])

class SSDNet(object):
    """Implementation of the SSD VGG-based 300 network.

    The default features layers with 300x300 image input are:
      conv4 ==> 38 x 38
      conv7 ==> 19 x 19
      conv8 ==> 10 x 10
      conv9 ==> 5 x 5
      conv10 ==> 3 x 3
      conv11 ==> 1 x 1
    The default image size used to train this network is 300x300.
    """
    default_params = SSDParams(
        img_shape=(300, 300),
        num_classes=2,
        no_annotation_label=2,
        feat_layers=['block4', 'block7', 'block8', 'block9', 'block10', 'block11'],
        feat_shapes=[(38, 38), (19, 19), (10, 10), (5, 5), (3, 3), (1, 1)],
        anchor_size_bounds=[0.15, 0.90],
        # anchor_size_bounds=[0.20, 0.90],
        anchor_sizes=[(21., 45.),
                      (45., 99.),
                      (99., 153.),
                      (153., 207.),
                      (207., 261.),
                      (261., 315.)],
        # anchor_sizes=[(30., 60.),
        #               (60., 111.),
        #               (111., 162.),
        #               (162., 213.),
        #               (213., 264.),
        #               (264., 315.)],
        anchor_ratios=[[2, .5],
                       [2, .5, 3, 1. / 3],
                       [2, .5, 3, 1. / 3],
                       [2, .5, 3, 1. / 3],
                       [2, .5],
                       [2, .5]],
        anchor_steps=[8, 16, 32, 64, 100, 300],
        anchor_offset=0.5,
        normalizations=[20, -1, -1, -1, -1, -1],
        prior_scaling=[0.1, 0.1, 0.2, 0.2]
    )

    def __init__(self, params=None):
        """Init the SSD net with some parameters. Use the default ones
        if none provided.
        """
        if isinstance(params, SSDParams):
            self.params = params
        else:
            self.params = SSDNet.default_params

    def anchors(self, img_shape, dtype=np.float32):
        """Compute the default anchor boxes, given an image shape.
        """
        return np_methods.ssd_anchors_all_layers(img_shape,
                                                 self.params.feat_shapes,
                                                 self.params.anchor_sizes,
                                                 self.params.anchor_ratios,
                                                 self.params.anchor_steps,
                                                 self.params.anchor_offset,
                                                 dtype)

def draw(image, boxes, classes):
    image_h, image_w, _ = image.shape
    colors = [255, 0, 0]
    for i in range(classes.shape[0]):
        cls_id = int(classes[i])
        if cls_id >= 0:
            boxes[i, 0] = int(boxes[i, 0] * image_h)
            boxes[i, 1] = int(boxes[i, 1] * image_w)
            boxes[i, 2] = int(boxes[i, 2] * image_h)
            boxes[i, 3] = int(boxes[i, 3] * image_w)
    for box in boxes:
        x0, y0, x1, y1 = box
        left = max(0, np.floor(x0 + 0.5).astype(int))
        top = max(0, np.floor(y0 + 0.5).astype(int))
        right = min(image.shape[1], np.floor(x1 + 0.5).astype(int))
        bottom = min(image.shape[0], np.floor(y1 + 0.5).astype(int))
        bbox_thick = 1
        cv2.rectangle(image, (left, top), (right, bottom), colors, bbox_thick)
    return image

if __name__ == '__main__':
    input_shape = (300, 300)
    ssd_net = SSDNet()
    ssd_anchors = ssd_net.anchors(input_shape)

    with tf.gfile.GFile('./SSD_300.pb', "rb") as pb:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(pb.read())

    # We load the graph_def in the default graph
    with tf.Graph().as_default() as graph:
        tf.import_graph_def(
            graph_def,
            name="",  # name可以自定义，修改name之后记得在下面的代码中也要改过来
        )

    # 打印网络结构
    for op in graph.get_operations():
        print(op.name, op.values())

    nodein = graph.get_tensor_by_name('Placeholder:0')
    output = ["ssd_300_vgg/block4_box/Reshape:0", "ssd_300_vgg/softmax/Reshape_1:0",
              "ssd_300_vgg/block7_box/Reshape:0", "ssd_300_vgg/softmax_1/Reshape_1:0",
              "ssd_300_vgg/block8_box/Reshape:0", "ssd_300_vgg/softmax_2/Reshape_1:0",
              "ssd_300_vgg/block9_box/Reshape:0", "ssd_300_vgg/softmax_3/Reshape_1:0",
              "ssd_300_vgg/block10_box/Reshape:0", "ssd_300_vgg/softmax_4/Reshape_1:0",
              "ssd_300_vgg/block11_box/Reshape:0", "ssd_300_vgg/softmax_5/Reshape_1:0"]
    prediction = []
    location = []
    prediction.append(graph.get_tensor_by_name(output[1]))
    prediction.append(graph.get_tensor_by_name(output[3]))
    prediction.append(graph.get_tensor_by_name(output[5]))
    prediction.append(graph.get_tensor_by_name(output[7]))
    prediction.append(graph.get_tensor_by_name(output[9]))
    prediction.append(graph.get_tensor_by_name(output[11]))
    location.append(graph.get_tensor_by_name(output[0]))
    location.append(graph.get_tensor_by_name(output[2]))
    location.append(graph.get_tensor_by_name(output[4]))
    location.append(graph.get_tensor_by_name(output[6]))
    location.append(graph.get_tensor_by_name(output[8]))
    location.append(graph.get_tensor_by_name(output[10]))

    with tf.Session(graph=graph) as sess:
        cam = cv2.VideoCapture(0)
        ifsuccess, frame_origin = cam.read()
        assert ifsuccess is True, 'camera error'

        while 1:
            ifsuccess, frame_origin = cam.read()
            frame_origin = cv2.resize(frame_origin, input_shape, interpolation=cv2.INTER_CUBIC)
            time_start = time.time()  # start
            rprediction, rlocation = sess.run([prediction, location], feed_dict={nodein: frame_origin})
            time_stop = time.time()  # stop
            cost_time = time_stop - time_start
            print('fps: ', 1 / cost_time)

            rclasses, rscores, rbboxes = np_methods.ssd_bboxes_select(
                rprediction, rlocation, ssd_anchors,
                select_threshold=0.55, img_shape=input_shape, num_classes=2, decode=True)

            # 检测有没有超出检测边缘
            rbbox_img = [0, 0, 1, 1]
            rbboxes = np_methods.bboxes_clip(rbbox_img, rbboxes)
            rclasses, rscores, rbboxes = np_methods.bboxes_sort(rclasses, rscores, rbboxes, top_k=400)
            # 去重，将重复检测到的目标去掉
            rclasses, rscores, rbboxes = np_methods.bboxes_nms(rclasses, rscores, rbboxes, nms_threshold=0.01)
            # 将box的坐标重新映射到原图上（上文所有的坐标都进行了归一化，所以要逆操作一次）
            rbboxes = np_methods.bboxes_resize(rbbox_img, rbboxes)

            frame_origin = draw(frame_origin, rbboxes, rclasses)
            frame_origin = cv2.putText(frame_origin, 'Model: SSD_300', (10, 25),
                                       cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 23, 255), 1)
            frame_origin = cv2.putText(frame_origin, 'Device: GPU', (10, 50),
                                       cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 23, 255), 1)
            frame_origin = cv2.putText(frame_origin, 'Cost: {:2.2f} ms'.format(cost_time),
                                       (10, 75), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 23, 255), 1)
            frame_origin = cv2.putText(frame_origin,
                                       'FPS: {:2.2f}'.format(1 / cost_time) if cost_time > 0 else 'FPS: --',
                                       (10, 100), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 23, 255), 1)
            cv2.imshow("capture", frame_origin)

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

        cam.release()
        cv2.destroyAllWindows()
        sess.close()


import json
import math
import os
import random
import re

import numpy as np
import torch
import torch.cuda
from sklearn.utils import shuffle
from torch.cuda.amp import autocast, GradScaler
from torch.nn import DataParallel
from transformers import AdamW
from transformers import get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, \
    get_linear_schedule_with_warmup

from easy_bert import logger
from easy_bert.adversarial import FGM, PGD
from easy_bert.base.base_trainer import BaseTrainer
from easy_bert.bert4classification.classification_model import ClassificationModel
from easy_bert.vocab import Vocab

class ClassificationTrainer(BaseTrainer):
    def __init__(self, pretrained_model_dir, model_dir, learning_rate=5e-5, ckpt_name='bert_model.bin',
                 vocab_name='vocab.json', enable_parallel=False, adversarial=None, dropout_rate=0.5,
                 loss_type='cross_entropy_loss', focal_loss_gamma=2, focal_loss_alpha=None, random_seed=0,
                 warmup_type=None, warmup_step_num=10, enable_fp16=False,
                 add_on=None, rnn_hidden=256, rnn_lr=1e-3,
                 load_last_ckpt=False, layer_wise_lr_decay=False, lr_decay_rate=0.95):
        # 设置目录
        self.pretrained_model_dir, self.model_dir = pretrained_model_dir, model_dir
        self.ckpt_name, self.vocab_name = ckpt_name, vocab_name

        self.enable_parallel = enable_parallel

        self.load_last_ckpt = load_last_ckpt  # 是否加载上次模型

        # 设置随机种子
        self.random_seed = random_seed
        self._set_random_seed(random_seed)

        # 对抗训练配置
        self.adversarial = adversarial
        assert adversarial in (None, 'fgm', 'pgd')

        # loss配置
        self.loss_type = loss_type
        self.focal_loss_gamma = focal_loss_gamma
        self.focal_loss_alpha = focal_loss_alpha

        # 自动获取当前设备
        self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

        self.dropout_rate = dropout_rate
        self.learning_rate = learning_rate
        self.batch_size = None
        self.epoch = None

        # 混合精度配置
        if enable_fp16:
            self.grad_scaler = GradScaler()  # 设置梯度缩放
        self.enable_fp16 = enable_fp16

        # warmup配置
        assert warmup_type in ('constant', 'cosine', 'linear', None)
        assert type(warmup_step_num) in (int, float)
        self.warmup_type = warmup_type
        self.warmup_step_num = warmup_step_num

        # 附加层配置（add-on）
        self.add_on = add_on
        self.rnn_hidden, self.rnn_lr = rnn_hidden, rnn_lr

        # llrd配置
        self.layer_wise_lr_decay = layer_wise_lr_decay
        self.lr_decay_rate = lr_decay_rate

        self.vocab = Vocab()

    def _set_random_seed(self, seed):
        """针对torch torch.cuda numpy random分别设定随机种子"""
        torch.manual_seed(seed)
        torch.cuda.manual_seed_all(seed)
        np.random.seed(seed)
        random.seed(seed)

    def _build_model(self):
        """构建bert模型"""
        # 实例化ClassificationModel模型
        self.model = ClassificationModel(
            self.pretrained_model_dir, self.vocab.label_size, dropout_rate=self.dropout_rate,
            loss_type=self.loss_type, focal_loss_alpha=self.focal_loss_alpha, focal_loss_gamma=self.focal_loss_gamma,
            add_on=self.add_on, rnn_hidden=self.rnn_hidden
        )

        # 如果启用增量训练，预加载之前训练好的模型
        if self.load_last_ckpt and os.path.exists('{}/{}'.format(self.model_dir, self.ckpt_name)):
            self.model.load_state_dict(
                torch.load('{}/{}'.format(self.model_dir, self.ckpt_name), map_location=self.device)
            )
            logger.info('load last ckpt {}/{} success'.format(self.model_dir, self.ckpt_name))

        # 设置AdamW优化器
        no_decay = ["bias", "LayerNorm.weight"]  # bias和LayerNorm不使用正则化
        # 参数分组
        embedding_parameters, encoder_parameters = [], {}
        linear_parameters, rnn_parameters = [], []
        for name, param in self.model.named_parameters():
            if 'rnn' in name:
                rnn_parameters.append((name, param))
            elif 'embeddings' in name:
                embedding_parameters.append((name, param))
            elif 'encoder.layer' in name:
                layer_no = int(re.search('encoder\.layer\.(\d+)', name).group(1))
                if layer_no not in encoder_parameters:
                    encoder_parameters[layer_no] = []
                encoder_parameters[layer_no].append((name, param))
            else:
                linear_parameters.append((name, param))
        # 为不同参数组设置不同的lr
        num_hidden_layers = self.model.bert_model.config.num_hidden_layers
        optimizer_grouped_parameters = [
            {'params': [p for n, p in embedding_parameters if not any(nd in n for nd in no_decay)],
             'weight_decay': 0.01,
             'lr': self.learning_rate * self.lr_decay_rate ** num_hidden_layers if self.layer_wise_lr_decay else self.learning_rate},
            {'params': [p for n, p in embedding_parameters if any(nd in n for nd in no_decay)],
             'weight_decay': 0.0,
             'lr': self.learning_rate * self.lr_decay_rate ** num_hidden_layers if self.layer_wise_lr_decay else self.learning_rate},
        ]
        for layer_no in range(num_hidden_layers):
            optimizer_grouped_parameters.extend([
                {'params': [p for n, p in encoder_parameters[layer_no] if not any(nd in n for nd in no_decay)],
                 'weight_decay': 0.01,
                 'lr': self.learning_rate * self.lr_decay_rate ** (
                         num_hidden_layers - layer_no - 1) if self.layer_wise_lr_decay else self.learning_rate},
                {'params': [p for n, p in encoder_parameters[layer_no] if any(nd in n for nd in no_decay)],
                 'weight_decay': 0.0,
                 'lr': self.learning_rate * self.lr_decay_rate ** (
                         num_hidden_layers - layer_no - 1) if self.layer_wise_lr_decay else self.learning_rate},
            ])
        optimizer_grouped_parameters.extend([
            {'params': [p for n, p in linear_parameters], 'lr': self.learning_rate},
            {'params': [p for n, p in rnn_parameters], 'lr': self.rnn_lr}  # rnn layer设置自己的lr
        ])
        self.optimizer = AdamW(optimizer_grouped_parameters, lr=self.learning_rate)

        # 使用bert的vocab更新Vocab对象
        self.vocab.set_vocab2id(self.model.get_bert_tokenizer().vocab)
        self.vocab.set_id2vocab({_id: char for char, _id in self.vocab.vocab2id.items()})
        self.vocab.set_unk_vocab_id(self.vocab.vocab2id['[UNK]'])
        self.vocab.set_pad_vocab_id(self.vocab.vocab2id['[PAD]'])

        # 启用并行，使用DataParallel封装model
        if self.enable_parallel:
            self.model = DataParallel(self.model, device_ids=list(range(torch.cuda.device_count())))

        # 将模型拷贝到当前设备
        self.model.to(self.device)

    def _save_config(self):
        """保存训练参数配置为json文件"""
        config = {
            'vocab_size': self.vocab.vocab_size,
            'label_size': self.vocab.label_size,
            'learning_rate': self.learning_rate,
            'batch_size': self.batch_size,
            'dropout_rate': self.dropout_rate,
            'epoch': self.epoch,
            'ckpt_name': self.ckpt_name,
            'vocab_name': self.vocab_name,
            'enable_parallel': self.enable_parallel,
            'enable_fp16': self.enable_fp16,
            'adversarial': self.adversarial,
            'loss_type': self.loss_type,
            'focal_loss_gamma': self.focal_loss_gamma,
            'focal_loss_alpha': self.focal_loss_alpha,
            'pretrained_model': os.path.basename(self.pretrained_model_dir),
            'add_on': self.add_on,
            'rnn_hidden': self.rnn_hidden,
            'rnn_lr': self.rnn_lr,
            'random_seed': self.random_seed,
            'layer_wise_lr_decay': self.layer_wise_lr_decay,
            'lr_decay_rate': self.lr_decay_rate,
        }
        with open('{}/train_config.json'.format(self.model_dir), 'w') as f:
            f.write(json.dumps(config, indent=4))

    def _transform_batch(self, batch_texts, batch_labels, max_length=512):
        """将batch的文本及labels转换为bert的输入tensor形式"""
        batch_input_ids, batch_att_mask, batch_label_ids = [], [], []
        for text, label in zip(batch_texts, batch_labels):  # 迭代每条样本
            assert isinstance(text, str)
            # 根据是否并行，获取bert_tokenizer
            bert_tokenizer = self.model.bert_tokenizer if not self.enable_parallel else self.model.module.bert_tokenizer
            encoded_dict = bert_tokenizer.encode_plus(text, max_length=max_length, padding='max_length',
                                                      return_tensors='pt', truncation=True)
            batch_input_ids.append(encoded_dict['input_ids'])
            batch_att_mask.append(encoded_dict['attention_mask'])
            batch_label_ids.append(self.vocab.tag2id[label])
        batch_input_ids, batch_att_mask, batch_label_ids = \
            torch.cat(batch_input_ids), torch.cat(batch_att_mask), torch.LongTensor(batch_label_ids)

        # 将数据拷贝到当前设备
        batch_input_ids, batch_att_mask, batch_label_ids = \
            batch_input_ids.to(self.device), batch_att_mask.to(self.device), batch_label_ids.to(self.device)

        return batch_input_ids, batch_att_mask, batch_label_ids

    def train(self, train_texts, train_labels, validate_texts, validate_labels,
              batch_size=30, epoch=10, max_loss_num=10, warning_max_len=True):
        """训练
        Args:
            train_texts: list[str] 训练集样本
            train_labels: list[str] 训练集标签
            validate_texts: list[str] 验证集样本
            validate_labels: list[str] 验证集标签
            batch_size: int
            epoch: int
            max_loss_num: int 连续max_loss_num个validate loss平均，根据其保存模型
            warning_max_len: bool 是否警告max_len超过512（普通bert不能处理超过512，除了一些变体如longformer）
        """
        self.batch_size = batch_size
        self.epoch = epoch

        # 构建词库表（只构建label id映射，词库bert已有）、构建模型
        self.vocab.build_vocab(labels=train_labels, build_texts=False, with_build_in_tag_id=False)
        self._build_model()
        # 保存词库、保存训练config
        self.vocab.save_vocab('{}/{}'.format(self.model_dir, self.vocab_name))
        self._save_config()

        logger.info('train samples: {}, validate samples: {}'.format(len(train_texts), len(validate_texts)))

        best_loss = float("inf")  # 当前最小的loss
        loss_buff = []  # 保存最近max_loss_num的个valid loss

        step = 0

        # 根据对抗配置，实例化不同的对抗实例
        if self.adversarial:
            logger.info('enable adversarial training')
            adv_class = {'fgm': FGM, 'pgd': PGD}[self.adversarial]
            adv = adv_class(self.model, grad_scaler=self.grad_scaler if self.enable_fp16 else None)

        # 根据warmup配置，设置warmup
        if self.warmup_type:
            total_steps = len(train_texts) // batch_size * epoch
            num_warmup_steps = self.warmup_step_num if isinstance(self.warmup_step_num, int) else \
                int(total_steps * self.warmup_step_num)
            assert num_warmup_steps <= total_steps, \
                'num_warmup_steps {} is too large, more than total_steps {}'.format(num_warmup_steps, total_steps)
            if self.warmup_type == 'linear':
                warmup_scheduler = get_linear_schedule_with_warmup(self.optimizer, num_warmup_steps, total_steps)
            elif self.warmup_type == 'cosine':
                warmup_scheduler = get_cosine_schedule_with_warmup(self.optimizer, num_warmup_steps, total_steps)
            else:
                warmup_scheduler = get_constant_schedule_with_warmup(self.optimizer, num_warmup_steps)

        for epoch in range(epoch):
            for batch_idx in range(math.ceil(len(train_texts) / batch_size)):
                text_batch = train_texts[batch_size * batch_idx: batch_size * (batch_idx + 1)]
                labels_batch = train_labels[batch_size * batch_idx: batch_size * (batch_idx + 1)]

                step += 1
                self.model.train()  # 设置为train模式
                self.model.zero_grad()  # 清空梯度

                # 训练
                batch_max_len = max([len(text) for text in text_batch]) + 2  # 长度得加上[CLS]和[SEP]
                if warning_max_len and batch_max_len > 512:
                    logger.warning(
                        'current batch max_len is {}, > 512, which may not be processed by bert!'.format(batch_max_len)
                    )
                batch_input_ids, batch_att_mask, batch_label_ids = self._transform_batch(text_batch,
                                                                                labels_batch,
                                                                                max_length=batch_max_len)
                if self.enable_fp16:  # 如果启用混合精度训练，用autocast封装
                    with autocast():
                        best_paths, loss = self.model(batch_input_ids, batch_att_mask, labels=batch_label_ids)
                else:  # 不启用混合精度，正常训练
                    best_paths, loss = self.model(batch_input_ids, batch_att_mask, labels=batch_label_ids)

                # 如果启用并行，需将多张卡返回的sub-batch loss平均
                if self.enable_parallel:
                    loss = loss.mean()

                # 反向传播（混合精度需要放大loss再反传）
                loss.backward() if not self.enable_fp16 else self.grad_scaler.scale(loss).backward()

                # 对抗训练
                if self.adversarial:
                    adv.train(batch_input_ids, batch_att_mask, labels=batch_label_ids)

                # 更新参数
                if self.enable_fp16:
                    self.grad_scaler.step(self.optimizer)
                    self.grad_scaler.update()
                else:
                    self.optimizer.step()

                # 如果启用warmup，更新lr
                if self.warmup_type:
                    warmup_scheduler.step()

                # 计算train acc、valid acc
                train_acc = self._get_acc_one_step(best_paths, batch_label_ids)
                valid_acc, valid_loss = self.validate(validate_texts, validate_labels, batch_size, warning_max_len)

                # 计算连续max_loss_num个平均valid_loss
                loss_buff.append(valid_loss)
                if len(loss_buff) > max_loss_num:
                    loss_buff = loss_buff[-max_loss_num:]
                avg_loss = sum(loss_buff) / len(loss_buff) if len(loss_buff) == max_loss_num else None

                logger.info(
                    'epoch %d, step %d, train loss %.4f, train acc %.4f, valid loss %.4f valid acc %.4f, '
                    'last %d avg valid loss %s' % (
                        epoch, step, loss, train_acc, valid_loss, valid_acc, max_loss_num,
                        '%.4f' % avg_loss if avg_loss else avg_loss
                    )
                )

                # 如果avg_loss在降，保存模型
                if avg_loss and avg_loss < best_loss:
                    best_loss = avg_loss
                    # 根据是否启用并行，获得state_dict
                    state_dict = self.model.state_dict() if not self.enable_parallel else self.model.module.state_dict()
                    torch.save(state_dict, '{}/{}'.format(self.model_dir, self.ckpt_name))
                    logger.info("model saved")

        logger.info("finished")

    def validate(self, validate_texts, validate_labels, sample_size=100, warning_max_len=True):
        """验证
        Args:
            validate_texts: list[str]
            validate_labels: list[str]
            sample_size: int 采样大小(使用全量验证集较慢，这里每次随机采样sample_size个样本做验证)
            warning_max_len: bool 是否警告max_len超过512（普通bert不能处理超过512，除了一些变体如longformer）
        Returns:
            float 验证集上acc, loss
        """
        # 设置为evaluate模式
        self.model.eval()

        # 随机采样sample_size个样本
        batch_texts, batch_labels = [
            return_val[:sample_size] for return_val in shuffle(validate_texts, validate_labels)
        ]

        # 计算valid acc, valid loss
        batch_max_len = max([len(text) for text in batch_texts]) + 2
        if warning_max_len and batch_max_len > 512:
            logger.warning(
                'current batch max_len is {}, > 512, which may not be processed by bert!'.format(batch_max_len)
            )
        with torch.no_grad():  # eval时不计算梯度
            batch_input_ids, batch_att_mask, batch_label_ids = self._transform_batch(batch_texts,
                                                                                batch_labels,
                                                                                max_length=batch_max_len)
            # 如果启用混合精度训练，用autocast封装，并使用grad_scaler放大loss
            if self.enable_fp16:
                with autocast():
                    best_paths, loss = self.model(batch_input_ids, batch_att_mask, labels=batch_label_ids)
            else:
                best_paths, loss = self.model(batch_input_ids, batch_att_mask, labels=batch_label_ids)

            # 如果启用并行，需将多张卡返回的sub-batch loss平均
            if self.enable_parallel:
                loss = loss.mean()

            acc = self._get_acc_one_step(best_paths, batch_label_ids)
            return acc, loss

    def _get_acc_one_step(self, labels_predict_batch, labels_batch):
        """计算一个batch的acc, correct_label_num / total_label_num"""
        acc = (labels_predict_batch == labels_batch).sum().item() / labels_batch.shape[0]
        return float(acc)