|
| 1 | +# 插件化设计 |
| 2 | + |
| 3 | +考虑到训练性能影响、包大小等因素,自[#780](https://github.com/SwanHubX/SwanLab/issues/780)起,swanlab将云端和本地版分开,在 |
| 4 | +`mode="cloud"` |
| 5 | +时,不再运行本地版服务。本地版服务的主要将交由[SwanLab-Dashboard](https://github.com/SwanHubX/SwanLab-Dashboard)分包处理。 |
| 6 | + |
| 7 | +> NOTE: 由于维护精力问题,本地版服务进入维护模式,不再更新新功能,仅维护bug和适配新版本swanlab的接口变化。 |
| 8 | +> |
| 9 | +> 好消息是,当[#780](https://github.com/SwanHubX/SwanLab/issues/780) |
| 10 | +> 完成的同时,我们将提供私有化部署版,代替[SwanLab-Dashboard](https://github.com/SwanHubX/SwanLab-Dashboard)的绝大多数使用场景。 |
| 11 | +
|
| 12 | +--- |
| 13 | + |
| 14 | +SwanLab-SDK可以被抽象为一个解码器,使用者通过传入不同的数据以及配置,完成不同可视化场景的预处理。 |
| 15 | +以此为基础,swanlab在处理的时候提供了不同的事件,通过事件回调(同步)的方式完成各种需求——因此,所谓的插件本质上是一个事件回调处理器。有关事件的详细信息,可参阅[回调函数](https://github.com/SwanHubX/SwanLab-Toolkit/wiki/第3部分:回调函数) |
| 16 | + |
| 17 | +在swanlab源码当中,有一个继承自[SwanKitCallback](https://github.com/SwanHubX/SwanLab-Toolkit/blob/b914037d471628e2d3194d2d4bb4d9f3f3a7fb9c/swankit/callback/__init__.py#L17C7-L17C22) |
| 18 | +的helper,用于聚合所有的插件回调函数。当某一个事件回调被触发时,helper会按照插件的传入次序依次**同步**调用插件的回调函数。 |
| 19 | + |
| 20 | +> 从上述设计可以看出我们不会再关心回调处理函数的返回值是什么,因为我们认为插件的回调函数是无状态的,不应该有返回值。 |
| 21 | +
|
| 22 | +## 🙋 如何自定义一个插件(回调处理器) |
| 23 | + |
| 24 | +swanlab一切的起点都是`swanlab.init`,此函数允许传入`callbacks`参数,用于向helper注册插件回调函数。我们约定所有的回调处理器都应该继承自 |
| 25 | +`SwanKitCallback`,类似下面这样: |
| 26 | + |
| 27 | +```python |
| 28 | +from swankit.callback import SwanKitCallback |
| 29 | + |
| 30 | + |
| 31 | +class CustomCallback(SwanKitCallback): |
| 32 | + def __str__(self): |
| 33 | + # 用于在swanlab.init的时候打印插件的名称,并作为插件的唯一标识 |
| 34 | + return "CustomCallback" |
| 35 | + |
| 36 | + def on_stop(self, error: str = None): |
| 37 | + print("Experiment stopped.") |
| 38 | +``` |
| 39 | + |
| 40 | +然后在`swanlab.init`的时候传入`callbacks`参数: |
| 41 | + |
| 42 | +```python |
| 43 | +import swanlab |
| 44 | +from swankit.callback import SwanKitCallback |
| 45 | + |
| 46 | + |
| 47 | +class CustomCallback(SwanKitCallback): |
| 48 | + def __str__(self): |
| 49 | + # 用于在swanlab.init的时候打印插件的名称,并作为插件的唯一标识 |
| 50 | + return "CustomCallback" |
| 51 | + |
| 52 | + def on_stop(self, error: str = None): |
| 53 | + print("Experiment stopped.") |
| 54 | + |
| 55 | + |
| 56 | +swanlab.init(callback=CustomCallback()) |
| 57 | +``` |
| 58 | + |
| 59 | +这样,在实验结束后,swanlab会调用`CustomCallback`的`on_stop`方法,在终端打印`Experiment stopped`。 |
| 60 | + |
| 61 | +## ⚠️ 分包后的单元测试 |
| 62 | + |
| 63 | +尽管`swanboard`函数变成一个可选依赖,但是单元测试时依旧需要`swanboard`的支持。即运行单元测试之前,需确保 |
| 64 | +`pip install swanboard` |
0 commit comments