当前位置: 首页 > news >正文

PyTorch Lightning - LightningModule 训练逻辑 (training_step) 异常处理 try-except

欢迎关注我的CSDN:https://spike.blog.csdn.net/
本文地址:https://spike.blog.csdn.net/article/details/133673820

LightningModule

在使用 LightningModule 框架训练模型时,因数据导致的训练错误,严重影响训练稳定性,因此需要使用 try-except 及时捕获错误。即 当错误发生时,在 training_step 异常返回 None,同时,on_before_zero_grad 也需要进行异常处理,处理 training_step 的异常返回 None。

同样的,validation_step 也可以这样处理。

源码如下:

class MyObject(pl.LightningModule):
	def __init__(self, config, args):
		# ...
		
	def training_step_wrapper(self, batch, batch_idx, log_interval=10):
		# train key process
		
	def training_step(self, batch, batch_idx, log_interval=10):
        """
        typically, each step costs 50 seconds
        参考: https://github.com/Lightning-AI/lightning/pull/3566
        """
        try:
            res = self.training_step_wrapper(batch, batch_idx, log_interval)
            return res
        except Exception as e:
            logger.info(f"[CL] training_step, exception: {e}")
            return None
            
	def on_before_zero_grad(self, *args, **kwargs):
        try:
            self.ema.update(self.model)
        except Exception as e:
            # 支持 training_step return None
            logger.info(f"[CL] on_before_zero_grad, exception: {e}")
            return
            
	def validation_step_wrapper(self, batch, batch_idx):
        # val key process

    def validation_step(self, batch, batch_idx):
        try:
            self.validation_step_wrapper(batch, batch_idx)
        except Exception as e:
            logger.info(f"[CL] validation_step, exception: {e}")
            return

常见错误如下

数组越界:

index 0 is out of bounds for dimension 0 with size 0

字典错误字段:

num_res = int(np_example["seq_length"])
KeyError: 'seq_length'

计算输入数值为空:

V, _, W = torch.linalg.svd(C)

free()异常:

free(): invalid next size (fast)

munmap_chunk() 空指针:

munmap_chunk(): invalid pointer

相关文章:

  • Python—Scrapy实践项目
  • objective-c 基础学习
  • 软考 系统架构设计师系列知识点之软件架构风格(5)
  • 2023-2024年华为ICT网络赛道模拟题库
  • 【VUE3 Teleport】
  • redis分布式秒杀锁
  • 【数据结构】二叉树
  • 厌烦了iPhone默认的热点名称?如何更改iPhone上的热点名称
  • 视觉效果绝佳的制作电子宣传册的网站
  • C++交换a和b的方法
  • 导出视频里的字幕
  • ChainForge:衡量Prompt性能和模型稳健性的GUI工具包
  • 面试经典 150 题 4 —(数组 / 字符串)— 80. 删除有序数组中的重复项 II
  • NFTScan | 10.02~10.08 NFT 市场热点汇总
  • 大成者大累,大智者大优,无能者无欲无求
  • Docker搭建MySQL8.0主从复制(一主一从)
  • 【算法与数据结构】--目录
  • RocketMq(五)消息机制
  • [leetcode 单调栈] 901. 股票价格跨度 M
  • 系统架构设计:9 论软件系统架构评估及其应用
  • 《致1999年的自己》:千禧之年的你在哪里?
  • 心相印回应官方旗舰店客服辱骂消费者:正排查
  • 中华人民共和国和俄罗斯联邦关于进一步加强合作维护国际法权威的联合声明
  • 上海优化营商环境十大攻坚突破任务中,为何第一项是实施世行对标改革?
  • 百济首次实现季度营业利润扭亏,泽布替尼销售额近57亿元
  • 专访|李沁云:精神分析不会告诉你“应该怎么做”,但是……