Pytorch Lightning 1.5.1 到 Pytorch Lightning 2.0.0 的迁移坑

Pytorch Lightning 1.5.1 到 Pytorch Lightning 2.0.0 的迁移坑

问题描述

  1. 版本兼容报错,可参考函数替代与参数修改节,以及直接根据终端输出修改。
  2. 由 all_step_outputs 迁移修改至分步的 training_step_outputs, validation_step_outputs 和 test_step_outputs。结合官方 github 中迁移说明和 Pytoch Lighning 官方文档修改(😇)。

函数替代与参数修改(部分)

  1. Pytorch Lightning 1.5.1 LightningModule 中的 training_epoch_end( ) 在 Pytorch Lightning 2.0.0 LightningModule 中被替换为 on_train_epoch_end( )。类似的有 validation_epoch_end ( ) 及 test_epoch_end( )。原文参考:github 迁移
  2. pytorch_lightning.trainer.trainer 参数发生以下变化:
    accelerator (Union[str, Accelerator, None]) --> accelerator (Union[str, Accelerator]),不再支持将 strategy 参数在 accelerator 中导入。
    checkpoint_callback (Optional[bool]) 参数被移除,该参数功能被 enable_checkpointing (Optional[bool]) 合并替代。
    flush_logs_every_n_steps (Optional[int]) 和 log_gpu_memory (Optional[str]) 被移除,需用户在相应模块中自定义。

上述参考来源:Pytorch Lightning 1.5.1 官方文档 Trainer

All_step_outputs 的迁移

官方 github 的说明中,给出了函数替代的修改,以及在 _init_ 模块里新增 train_step_outputs 等变量定义,其修改如下:

 class MyLightningModule(L.LightningModule):
+    def __init__(self):
+        super().__init__()
+        self.training_step_outputs = []

     def training_step(self, ...):
         loss = ...
+        self.training_step_outputs.append(loss)
         return loss

#-------------------- 删除部分 ----------------------
#-    def training_epoch_end(self, outputs):
#-        epoch_average = torch.stack([output["loss"] for output in outputs]).mean()
#-------------------- 删除部分 ----------------------

+    def on_train_epoch_end(self):
+        epoch_average = torch.stack(self.training_step_outputs).mean()
         self.log("training_epoch_average", epoch_average)
+        self.training_step_outputs.clear()  # free memory

Pytorch Lightning 2.0.0官方文档 中 给出的 on_train_epoch_end( ) 简单模板:

class MyLightningModule(L.LightningModule):
    def __init__(self):
        super().__init__()
        self.training_step_outputs = []

    def training_step(self):
        loss = ...
        self.training_step_outputs.append(loss)
        return loss


class MyCallback(L.Callback):
    def on_train_epoch_end(self, trainer, pl_module):
        # do something with all training_step outputs, for example:
        epoch_mean = torch.stack(pl_module.training_step_outputs).mean()
        pl_module.log("training_epoch_mean", epoch_mean)
        # free up the memory
        pl_module.training_step_outputs.clear()

在 training_step 的末尾一定要加上 self.xxx.append( ) 操作,在 1.5.1 的版本中,这个操作似乎隐式的完成了,而在新版中如果不 append 在进行 evaluate 等操作时常常会得到空的输出。
validation_step_outputs() 与 test_step_outputs() 类似。
【踩坑ing】

### 关于 `if-else` 语句的练习题与教程 #### C语言中的`if-else`语句应用实例 对于给定的任务——通过输入星期几的第一个字母来判断具体的星期名称,可以采用如下方式实现: ```c #include<stdio.h> int main(){ char ch; printf("请输入星期几的第一个大写字母:"); scanf("%c", &ch); if(ch=='M'){ printf("Monday\n"); } else if(ch=='W'){ printf("Wednesday\n"); } else if(ch=='F'){ printf("Friday\n"); } else{ printf("请输入第二个字母:"); char secondCh; getchar(); // 清除缓冲区 scanf("%c", &secondCh); if(secondCh == 'u' && (ch == 'T')){ printf("Tuesday\n"); } else if(secondCh == 'h' && (ch == 'T')){ printf("Thursday\n"); } else if(secondCh == 'a' && (ch == 'S')){ printf("Saturday\n"); } else if(secondCh == 'u' && (ch == 'S')){ printf("Sunday\n"); } else { printf("无法识别该日期。\n"); } } return 0; } ``` 此程序首先读取用户输入的一个字符作为一周中某天的第一个字母。如果是唯一的首字母(如'M', 'W', 或者 'F'),则直接输出对应的英文单词;如果不是唯一,则进一步请求用户提供第二天的字母以作更精确匹配[^1]。 #### Python 中的 `if-else` 使用案例 当涉及到Python编程时,同样的逻辑可以用更加简洁的方式表达出来: ```python day_map = {"Mo": "Monday", "Tu": "Tuesday", "We": "Wednesday", "Th": "Thursday", "Fr": "Friday", "Sa": "Saturday", "Su": "Sunday"} first_letter = input("Enter the first letter of day: ").strip().capitalize() second_letter = "" if len(first_letter) > 1 or not first_letter.isalpha(): print("Invalid Input.") elif first_letter in ["M", "W", "F"]: print(day_map[first_letter]) else: second_letter = input("Please enter another letter: ").strip().lower() key = f"{first_letter}{second_letter[:1]}" print(f"The full name is {day_map.get(key, 'Not Found')}") ``` 这段脚本同样实现了基于用户输入确定特定日子的功能,并且加入了额外的数据验证措施确保输入的有效性[^3]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值