Metadata-Version: 2.4
Name: tzxh-ai-factory-train-metric-log
Version: 0.1.0
Summary: AI训练指标日志工具包
Author-email: YuZhongfei <yuzhongfei@ictnj.ac.cn>
Maintainer-email: YuZhongfei <yuzhongfei@ictnj.ac.cn>
License: MIT
Keywords: ai,training,metrics,logging,machine-learning
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.28.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: isort>=5.12.0; extra == "dev"
Requires-Dist: flake8>=6.0.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Requires-Dist: pre-commit>=3.0.0; extra == "dev"
Provides-Extra: docs
Requires-Dist: sphinx>=5.0.0; extra == "docs"
Requires-Dist: sphinx-rtd-theme>=1.2.0; extra == "docs"
Dynamic: license-file

# tzxh-ai-factory-train-metric-log

[![PyPI version](https://badge.fury.io/py/tzxh-ai-factory-train-metric-log.svg)](https://badge.fury.io/py/tzxh-ai-factory-train-metric-log)
[![Python Versions](https://img.shields.io/pypi/pyversions/tzxh-ai-factory-train-metric-log.svg)](https://pypi.org/project/tzxh-ai-factory-train-metric-log/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

> AI训练指标日志工具包 - 提供类似 SwanLab/WandB 的简洁 API 用于记录和上报训练指标

哼，这是本小姐精心设计的优雅接口，笨蛋们要好好使用！(￣ω￣)ﾉ

---

## ✨ 特性

- 🚀 **简洁易用的 API** - 三行代码即可完成训练指标记录
- 📊 **自动 Step 管理** - 每个指标拥有独立的递增 step 计数器
- 🏷️ **灵活的标签系统** - 支持自定义 tags 方便实验筛选和对比
- 🔒 **线程安全设计** - 多线程环境下也能稳定工作
- 💾 **InfluxDB 风格格式** - 兼容主流时序数据库的数据格式
- ⚡ **零学习成本** - 类似 SwanLab/WandB 的使用体验
- 🎯 **类型注解完整** - 完整的类型提示，IDE 友好

---

## 📦 安装

```bash
pip install tzxh-ai-factory-train-metric-log
```

或者从源码安装：

```bash
git clone https://github.com/yourusername/tzxh-ai-factory-train-metric-log.git
cd tzxh-ai-factory-train-metric-log
pip install -e .
```

---

## 🚀 快速开始

### 最简单的示例

```python
from tzxh_ai_factory_train_metric_log import init, log

# 1. 初始化日志记录器
init(
    domain="https://api.example.com",
    run_name="my-first-experiment"
)

# 2. 记录训练指标
log({"loss": 2.5, "accuracy": 0.25})
# loss_step=0, accuracy_step=0

log({"loss": 2.0, "learning_rate": 0.001})
# loss_step=1, learning_rate_step=0 (accuracy 没有记录，step 保持不变)
```

### 训练循环示例

```python
from tzxh_ai_factory_train_metric_log import init, log

init(
    domain="https://api.example.com",
    run_name="resnet50-cifar10",
    model_name="resnet50",
    dataset="cifar10"
)

for epoch in range(num_epochs):
    for batch_idx in range(batches_per_epoch):
        loss, accuracy = train_one_batch()

        # 记录训练指标（step 自动递增！）
        log({"loss": loss, "accuracy": accuracy})

    # 每个 epoch 结束记录验证集指标
    val_loss, val_acc = validate()
    log({"val_loss": val_loss, "val_accuracy": val_acc})
```

完整示例请查看：[example/training_loop.py](example/training_loop.py)

---

## 📚 核心 API

### `init(domain, run_name, measurement="training_metrics", timeout=30, **extra_tags)`

初始化日志记录器，这是使用本库的第一步（就像魔法仪式前的准备工作一样～）

| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `domain` | `str` | *必需* | API 服务器域名（如 `https://api.example.com`） |
| `run_name` | `str` | *必需* | 运行名称，用于标识此次训练 |
| `measurement` | `str` | `"training_metrics"` | 测量名称 |
| `timeout` | `int` | `30` | HTTP 请求超时时间（秒） |
| `**extra_tags` | `str` | `{}` | 额外的标签键值对，会添加到每次上报的 tags 中 |

```python
init(
    domain="https://api.example.com",
    run_name="exp-001",
    measurement="training_metrics",
    model_type="llama3-8b",     # 自定义 tag
    dataset="wikitext",          # 自定义 tag
    optimizer="adamw"            # 自定义 tag
)
```

---

### `log(metrics, timestamp=None, **extra_fields)`

上报训练指标数据（自动为每个指标分配递增的 step）(￣▽￣)ゞ

| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `metrics` | `Dict[str, Any]` | *必需* | 指标字典（如 `{"loss": 0.45, "accuracy": 0.88}`） |
| `timestamp` | `str \| None` | `None` | 可选的时间戳（ISO 8601 格式），不提供则使用当前时间 |
| `**extra_fields` | `Any` | `{}` | 额外的字段，会合并到 metrics 中 |

**返回值：** `requests.Response` 对象（如果成功），失败时抛出异常

**Step 行为说明：**
- 每个指标都有自己独立的 step 计数器，从 0 开始递增
- 只有在本次记录中出现的指标，其 step 才会递增
- 未记录的指标 step 保持不变

```python
# 第一次记录
log({"loss": 0.45, "accuracy": 0.88})
# loss_step=0, accuracy_step=0

# 第二次记录（accuracy 未记录）
log({"loss": 0.43, "iter": 100})
# loss_step=1, iter_step=0, accuracy_step=0 (不变)

# 第三次记录
log({"loss": 0.40, "iter": 200})
# loss_step=2, iter_step=1
```

**支持的调用风格：**

```python
# 风格 1: 字典参数
log({"loss": 2.5, "accuracy": 0.65})

# 风格 2: 关键字参数
log(loss=2.5, accuracy=0.65)

# 风格 3: 混合使用
log({"loss": 2.5, "accuracy": 0.65}, auc_score=0.72)
```

---

### `get_config()`

获取当前配置信息，方便调试和查看当前状态～ (￣▽￣)ﾉ

**返回值：** 包含当前配置的字典，包括各指标的当前 step 值

```python
config = get_config()
# {
#     "domain": "https://api.example.com",
#     "run_name": "exp-001",
#     "measurement": "training_metrics",
#     "extra_tags": {"model_type": "llama3-8b"},
#     "timeout": 30,
#     "steps": {"loss": 10, "accuracy": 10, "learning_rate": 5},
#     "initialized": true
# }
```

---

## 🎓 高级用法

### 1. 自定义 Tags

使用丰富的 tags 来标记实验，方便后续筛选和分析：

```python
init(
    domain="https://api.example.com",
    run_name="experiment-with-tags",
    model_type="gpt-2",
    model_size="124M",
    dataset="wikitext",
    optimizer="adamw",
    weight_decay="0.01",
    experiment_group="baseline"
)
```

### 2. 混合指标类型

支持记录不同类型的指标：

```python
# 训练指标
log({"loss": 2.5, "accuracy": 0.65, "f1_score": 0.72})

# 进度指标
log({"epoch": 10, "batch": 1250, "samples_processed": 160000})

# 资源指标
log({"gpu_memory_mb": 6400, "cpu_usage_percent": 45.2, "training_time_ms": 235})
```

### 3. Step 独立性

不同频率的指标可以独立记录，step 互不影响：

```python
# 训练指标（高频记录，每个 batch 记录一次）
log({"train_loss": 2.5, "train_acc": 0.30})
log({"train_loss": 2.3, "train_acc": 0.35})
log({"train_loss": 2.1, "train_acc": 0.40})

# 验证指标（低频记录，每个 epoch 记录一次）
log({"val_loss": 2.4, "val_acc": 0.32})

# 测试指标（极低频，整个训练过程记录一次）
log({"test_loss": 2.6, "test_acc": 0.28})
```

### 4. 实验对比

使用不同的 `run_name` 和 tags 来区分不同的实验配置：

```python
# 实验组 A: 基线模型
init(
    domain="https://api.example.com",
    run_name="baseline-exp",
    model_type="resnet18",
    experiment_group="baseline"
)
for i in range(3):
    log({"loss": 2.5 - i * 0.3, "accuracy": 0.5 + i * 0.1})

# 实验组 B: 改进模型
init(
    domain="https://api.example.com",
    run_name="improved-exp",
    model_type="resnet18",
    experiment_group="improved",
    augmentation="advanced"
)
for i in range(3):
    log({"loss": 2.3 - i * 0.4, "accuracy": 0.55 + i * 0.12})
```

更多高级示例请查看：[example/advanced_features.py](example/advanced_features.py)

---

## 📁 示例代码

本小姐为你准备了丰富的示例代码，笨蛋们要好好参考！(￣▽￣)ゞ

| 示例文件 | 说明 |
|----------|------|
| [example/basic_usage.py](example/basic_usage.py) | 基础使用示例 |
| [example/advanced_features.py](example/advanced_features.py) | 高级功能演示 |
| [example/training_loop.py](example/training_loop.py) | 真实训练循环场景 |

运行示例：

```bash
# 运行基础示例
python example/basic_usage.py

# 运行高级示例
python example/advanced_features.py

# 运行训练循环示例
python example/training_loop.py
```

---

## 🛠️ 开发

### 安装开发依赖

```bash
pip install -e ".[dev]"
```

### 运行测试

```bash
pytest
```

### 代码格式化

```bash
# 使用 black 格式化代码
black src tests

# 使用 isort 整理导入
isort src tests
```

### 类型检查

```bash
mypy src
```

---

## 📋 依赖

- Python >= 3.8
- requests >= 2.28.0

---

---

## 📮 联系方式

- 作者：YuZhongfei
- 邮箱：yuzhongfei@ictnj.ac.cn

---

## 📝 更新日志

### 0.1.0 (2025-01-26)
- ✨ 初始版本发布
- 🎉 基础功能实现：init(), log(), get_config()
- 📊 自动 step 管理
- 🔒 线程安全设计
- 🏷️ 灵活的标签系统

---

## 🌟 相关项目

- [SwanLab](https://github.com/SwanLabX/SwanLab) - 开源实验追踪平台
- [WandB](https://github.com/wandb/wandb) - 实验跟踪和可视化工具
- [TensorBoard](https://github.com/tensorflow/tensorboard) - TensorFlow 可视化工具

---
