Compare commits
41
Commits
a30e3d5114
...
v1.3.8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bbe6ff2d8f | ||
|
|
db9b39b084 | ||
|
|
849e1e00a3 | ||
|
|
5416c2e8fb | ||
|
|
599a51f4f7 | ||
|
|
17d6eaa2f2 | ||
|
|
2d908639e9 | ||
|
|
c7158418dd | ||
|
|
4d3c9341c1 | ||
|
|
4e508afa2d | ||
|
|
8999ca89b8 | ||
|
|
1adca39cd8 | ||
|
|
204873fa2f | ||
|
|
a5c1de6b1b | ||
|
|
27524ad085 | ||
|
|
27d1921d9c | ||
|
|
70c0e5de90 | ||
|
|
dfb151537b | ||
|
|
500c605fad | ||
|
|
dc9faca3b1 | ||
|
|
aabb0d83e9 | ||
|
|
44579ea6dc | ||
|
|
0f1fcb079f | ||
|
|
84d4769163 | ||
|
|
bf09a35c95 | ||
|
|
6715461a36 | ||
|
|
b4587c5d08 | ||
|
|
88ec63121d | ||
|
|
01d2da2893 | ||
|
|
25d4ea3f91 | ||
|
|
39985840c7 | ||
|
|
b1adc40cfb | ||
|
|
7348bac6ab | ||
|
|
8ab7564d02 | ||
|
|
d096b6e29e | ||
|
|
d88a41f8f1 | ||
|
|
376e9eba80 | ||
|
|
a62c2e11a2 | ||
|
|
a4e5a8c81c | ||
|
|
3e234c46f6 | ||
|
|
7a04b1f8ce |
@@ -1,44 +0,0 @@
|
|||||||
name: Update Badges
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [main]
|
|
||||||
schedule:
|
|
||||||
- cron: "0 0 * * *"
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: write
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
update:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Fetch repo stats
|
|
||||||
id: api
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
run: |
|
|
||||||
mkdir -p badges
|
|
||||||
|
|
||||||
REPO=$(gh repo view --json stargazerCount,forkCount,latestRelease --jq '.')
|
|
||||||
|
|
||||||
STARS=$(echo "$REPO" | jq -r '.stargazerCount')
|
|
||||||
FORKS=$(echo "$REPO" | jq -r '.forkCount')
|
|
||||||
RELEASE=$(echo "$REPO" | jq -r '.latestRelease.tagName // "N/A"')
|
|
||||||
|
|
||||||
echo '{"schemaVersion":1,"label":"release","message":"'"$RELEASE"'","color":"76bad9"}' > badges/release.json
|
|
||||||
echo '{"schemaVersion":1,"label":"stars","message":"'"$STARS"'","color":"76bad9"}' > badges/stars.json
|
|
||||||
echo '{"schemaVersion":1,"label":"forks","message":"'"$FORKS"'","color":"76bad9"}' > badges/forks.json
|
|
||||||
|
|
||||||
- name: Deploy to gh-pages
|
|
||||||
uses: peaceiris/actions-gh-pages@v4
|
|
||||||
with:
|
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
publish_dir: badges
|
|
||||||
destination_dir: badges
|
|
||||||
commit_message: "Sync badges"
|
|
||||||
user_name: "github-actions[bot]"
|
|
||||||
user_email: "github-actions[bot]@users.noreply.github.com"
|
|
||||||
+4
-2
@@ -5,8 +5,10 @@
|
|||||||
!*/
|
!*/
|
||||||
|
|
||||||
# Allow specific file types and root files
|
# Allow specific file types and root files
|
||||||
!*.py
|
!astrai/**/*.py
|
||||||
!*.sh
|
!scripts/**/*.py
|
||||||
|
!scripts/**/*.sh
|
||||||
|
!tests/**/*.py
|
||||||
|
|
||||||
# Allow GitHub files
|
# Allow GitHub files
|
||||||
!/.github/**
|
!/.github/**
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,7 @@ Thank you for your interest in contributing! This document provides step-by-step
|
|||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/your-username/AstrAI.git
|
git clone https://github.com/ViperEkura/AstrAI.git
|
||||||
cd AstrAI
|
cd AstrAI
|
||||||
pip install -e ".[dev]" # install with dev dependencies (pytest, ruff)
|
pip install -e ".[dev]" # install with dev dependencies (pytest, ruff)
|
||||||
```
|
```
|
||||||
|
|||||||
+1
-1
@@ -23,7 +23,7 @@ COPY astrai/ ./astrai/
|
|||||||
COPY pyproject.toml .
|
COPY pyproject.toml .
|
||||||
RUN pip install --no-cache-dir --upgrade pip \
|
RUN pip install --no-cache-dir --upgrade pip \
|
||||||
&& pip install --no-cache-dir . \
|
&& pip install --no-cache-dir . \
|
||||||
--extra-index-url https://download.pytorch.org/whl/cu126
|
--extra-index-url https://download.pytorch.org/whl/cu128
|
||||||
|
|
||||||
# Production stage
|
# Production stage
|
||||||
FROM ubuntu:24.04 AS production
|
FROM ubuntu:24.04 AS production
|
||||||
|
|||||||
@@ -9,9 +9,9 @@
|
|||||||
<div align="center">
|
<div align="center">
|
||||||
<img src="https://img.shields.io/badge/python-3.12+-blue.svg" alt="python">
|
<img src="https://img.shields.io/badge/python-3.12+-blue.svg" alt="python">
|
||||||
<img src="https://img.shields.io/badge/license-GPL--3.0-blue.svg" alt="license">
|
<img src="https://img.shields.io/badge/license-GPL--3.0-blue.svg" alt="license">
|
||||||
<img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/ViperEkura/AstrAI/gh-pages/badges/release.json" alt="release">
|
<img src="https://img.shields.io/github/v/release/ViperEkura/AstrAI?label=Release&color=76bad9" alt="release">
|
||||||
<img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/ViperEkura/AstrAI/gh-pages/badges/stars.json" alt="stars">
|
<img src="https://img.shields.io/github/stars/ViperEkura/AstrAI?style=flat&label=Stars&color=76bad9" alt="stars">
|
||||||
<img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/ViperEkura/AstrAI/gh-pages/badges/forks.json" alt="forks">
|
<img src="https://img.shields.io/github/forks/ViperEkura/AstrAI?style=flat&label=Forks&color=76bad9" alt="forks">
|
||||||
</div>
|
</div>
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
@@ -28,7 +28,8 @@
|
|||||||
## 📖 Table of Contents
|
## 📖 Table of Contents
|
||||||
|
|
||||||
- [Features](#features)
|
- [Features](#features)
|
||||||
- [Quick Start](#quick-start)
|
- [Getting Started](#getting-started)
|
||||||
|
- [Demo](#demo)
|
||||||
- [Documentation](#documentation)
|
- [Documentation](#documentation)
|
||||||
- [Contributing](#contributing)
|
- [Contributing](#contributing)
|
||||||
- [Community](#community)
|
- [Community](#community)
|
||||||
@@ -49,33 +50,43 @@
|
|||||||
- 🤗 **HuggingFace-Style API**: AutoModel/AutoTokenizer APIs inspired by HuggingFace for easy model and tokenizer loading.
|
- 🤗 **HuggingFace-Style API**: AutoModel/AutoTokenizer APIs inspired by HuggingFace for easy model and tokenizer loading.
|
||||||
- 🔌 **Dual API Compatibility**: Supports both OpenAI and Anthropic chat completion APIs out of the box.
|
- 🔌 **Dual API Compatibility**: Supports both OpenAI and Anthropic chat completion APIs out of the box.
|
||||||
|
|
||||||
### Quick Start
|
### Getting Started
|
||||||
|
|
||||||
#### Installation
|
End-to-end walkthrough in 5 steps:
|
||||||
|
|
||||||
|
**1. Install**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/ViperEkura/AstrAI.git
|
git clone https://github.com/ViperEkura/AstrAI.git
|
||||||
cd AstrAI
|
cd AstrAI
|
||||||
pip install -e .
|
pip install -e .
|
||||||
|
# pip install -e ".[dev]" # optional: dev dependencies (pytest, ruff)
|
||||||
```
|
```
|
||||||
|
|
||||||
For development dependencies:
|
**2. Download model**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip install -e ".[dev]"
|
python scripts/demo/download.py # downloads 1B checkpoint to params/
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Download Pre-trained Model
|
**3. Preprocess data**
|
||||||
|
|
||||||
Download pre-trained model weights (1B bilingual checkpoint) to `params/`:
|
Create `pretrain.json` (preprocessing config for `seq` strategy):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"input": {"sections": [{"field": "text", "action": "train"}]},
|
||||||
|
"preprocessing": {"max_seq_len": 2048},
|
||||||
|
"output": {"storage_format": "bin"}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python scripts/demo/download.py
|
python scripts/tools/preprocess.py data/*.jsonl -o output/ -c pretrain.json
|
||||||
```
|
```
|
||||||
|
|
||||||
Or download manually from [HuggingFace](https://huggingface.co/ViperEk/KHAOSZ) into `params/`.
|
**4. Train**
|
||||||
|
|
||||||
#### Train a Model
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
export CUDA_VISIBLE_DEVICES=0,1,2,3
|
export CUDA_VISIBLE_DEVICES=0,1,2,3
|
||||||
@@ -102,15 +113,54 @@ nohup python scripts/tools/train.py \
|
|||||||
> out.log 2> err.log &
|
> out.log 2> err.log &
|
||||||
```
|
```
|
||||||
|
|
||||||
Full reference at [Parameter Guide](assets/docs/params.md).
|
**5. Serve & query**
|
||||||
|
|
||||||
#### Generate Text
|
```bash
|
||||||
|
# Terminal 1: start server
|
||||||
|
python scripts/tools/server.py --param_path ./params --device cuda
|
||||||
|
|
||||||
|
# Terminal 2: query
|
||||||
|
curl http://localhost:8000/v1/chat/completions \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"messages":[{"role":"user","content":"Hello"}],"max_tokens":512}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### Demo
|
||||||
|
|
||||||
|
Check out the demos in the `scripts/demo/` folder:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Download model weights (required before running demos)
|
||||||
|
python scripts/demo/download.py # model → params/
|
||||||
|
|
||||||
|
# Interactive streaming chat (multi-turn, maintains history)
|
||||||
|
python scripts/demo/stream_chat.py
|
||||||
|
# Type your message after >>, type !exit to quit
|
||||||
|
|
||||||
|
# Batch generation (5 hardcoded prompts, non-streaming)
|
||||||
|
python scripts/demo/generate_batch.py
|
||||||
|
|
||||||
|
# Single-prompt autoregressive streaming
|
||||||
|
python scripts/demo/generate_ar.py
|
||||||
|
```
|
||||||
|
|
||||||
|
All generation demos use `temperature=0.8`, `top_p=0.95`, `top_k=50`, `max_tokens=2048` by default and require `params/` to contain model weights (run `download.py` first).
|
||||||
|
|
||||||
|
Watch a video walkthrough on [bilibili](https://www.bilibili.com/video/BV1fuLB6yEj6).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
See [Documentation](#documentation) for full references beyond the examples above.
|
||||||
|
|
||||||
|
#### Text Generation
|
||||||
|
|
||||||
|
Batch generation from a JSONL file:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python scripts/tools/generate.py \
|
python scripts/tools/generate.py \
|
||||||
--param_path /path/to/model \
|
--param_path ./params \
|
||||||
--input_json_file /path/to/input.jsonl \
|
--input_json_file input.jsonl \
|
||||||
--output_json_file /path/to/output.jsonl
|
--output_json_file output.jsonl
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Docker
|
#### Docker
|
||||||
@@ -124,9 +174,6 @@ docker build -t astrai:latest .
|
|||||||
# Run with GPU support
|
# Run with GPU support
|
||||||
docker run --gpus all -it astrai:latest
|
docker run --gpus all -it astrai:latest
|
||||||
|
|
||||||
# Run with specific GPUs
|
|
||||||
docker run --gpus '"device=0,1"' -it astrai:latest
|
|
||||||
|
|
||||||
# Run inference server
|
# Run inference server
|
||||||
docker run --gpus all -p 8000:8000 astrai:latest \
|
docker run --gpus all -p 8000:8000 astrai:latest \
|
||||||
python -m scripts.tools.server --port 8000 --device cuda
|
python -m scripts.tools.server --port 8000 --device cuda
|
||||||
@@ -143,84 +190,37 @@ docker compose --profile cpu up -d
|
|||||||
|
|
||||||
> **Note**: `--gpus all` is required for CUDA support. Without it, `torch.cuda.is_available()` will return `False`.
|
> **Note**: `--gpus all` is required for CUDA support. Without it, `torch.cuda.is_available()` will return `False`.
|
||||||
|
|
||||||
#### Start HTTP Server
|
#### HTTP API Examples
|
||||||
|
|
||||||
Start the inference server with OpenAI and Anthropic-compatible HTTP API:
|
Additional request examples beyond the [Getting Started](#getting-started) flow:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python -m scripts.tools.server --port 8000 --device cuda
|
|
||||||
```
|
|
||||||
|
|
||||||
Make requests:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# OpenAI-compatible
|
|
||||||
curl -X POST http://localhost:8000/v1/chat/completions \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-d '{
|
|
||||||
"messages": [{"role": "user", "content": "Hello"}],
|
|
||||||
"max_tokens": 512
|
|
||||||
}'
|
|
||||||
|
|
||||||
# OpenAI-compatible streaming
|
# OpenAI-compatible streaming
|
||||||
curl -X POST http://localhost:8000/v1/chat/completions \
|
curl -X POST http://localhost:8000/v1/chat/completions \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d '{
|
-d '{"messages":[{"role":"user","content":"Tell a story"}],"stream":true,"max_tokens":500}'
|
||||||
"messages": [{"role": "user", "content": "Tell a story"}],
|
|
||||||
"stream": true,
|
|
||||||
"max_tokens": 500
|
|
||||||
}'
|
|
||||||
|
|
||||||
# Anthropic-compatible
|
# Anthropic-compatible
|
||||||
curl -X POST http://localhost:8000/v1/messages \
|
curl -X POST http://localhost:8000/v1/messages \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d '{
|
-d '{"model":"astrai","system":"You are a helpful assistant.","messages":[{"role":"user","content":"Hello"}],"max_tokens":512}'
|
||||||
"model": "astrai",
|
|
||||||
"system": "You are a helpful assistant.",
|
|
||||||
"messages": [{"role": "user", "content": "Hello"}],
|
|
||||||
"max_tokens": 512
|
|
||||||
}'
|
|
||||||
|
|
||||||
# Anthropic-compatible streaming with stop sequences
|
# Anthropic-compatible streaming with stop sequences
|
||||||
curl -X POST http://localhost:8000/v1/messages \
|
curl -X POST http://localhost:8000/v1/messages \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d '{
|
-d '{"model":"astrai","messages":[{"role":"user","content":"Write a story"}],"max_tokens":500,"stream":true,"stop_sequences":["The end"]}'
|
||||||
"model": "astrai",
|
|
||||||
"messages": [{"role": "user", "content": "Write a story"}],
|
|
||||||
"max_tokens": 500,
|
|
||||||
"stream": true,
|
|
||||||
"stop_sequences": ["The end"]
|
|
||||||
}'
|
|
||||||
|
|
||||||
# Health check
|
# Health check
|
||||||
curl http://localhost:8000/health
|
curl http://localhost:8000/health
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Demo
|
See [Inference Guide](assets/docs/inference.md) for SSE streaming format, error codes, and stats endpoint.
|
||||||
|
|
||||||
Check out the demos in the `scripts/demo/` folder:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Download model weights (required before running demos)
|
|
||||||
python scripts/demo/download.py
|
|
||||||
|
|
||||||
# Interactive streaming chat
|
|
||||||
python scripts/demo/stream_chat.py
|
|
||||||
|
|
||||||
# Batch generation
|
|
||||||
python scripts/demo/generate_batch.py
|
|
||||||
|
|
||||||
# Auto‑regressive generation
|
|
||||||
python scripts/demo/generate_ar.py
|
|
||||||
```
|
|
||||||
|
|
||||||
Watch a video walkthrough on [bilibili](https://www.bilibili.com/video/BV1fuLB6yEj6).
|
|
||||||
|
|
||||||
### Documentation
|
### Documentation
|
||||||
|
|
||||||
| Document | Description |
|
| Document | Description |
|
||||||
|----------|-------------|
|
|----------|-------------|
|
||||||
| [Parameter Guide](./assets/docs/params.md) | Training & inference parameters |
|
| [CLI Reference](./assets/docs/params.md) | Parameters for all CLI tools (train, server, generate, preprocess) |
|
||||||
| [Architecture](./assets/docs/architecture.md) | System architecture, class diagram & design patterns |
|
| [Architecture](./assets/docs/architecture.md) | System architecture, class diagram & design patterns |
|
||||||
| [Training](./assets/docs/training.md) | Training loop, strategies & formulas |
|
| [Training](./assets/docs/training.md) | Training loop, strategies & formulas |
|
||||||
| [Inference](./assets/docs/inference.md) | KVCache, continuous batching, sampling & HTTP API |
|
| [Inference](./assets/docs/inference.md) | KVCache, continuous batching, sampling & HTTP API |
|
||||||
|
|||||||
+75
-75
@@ -15,9 +15,9 @@
|
|||||||
<div align="center">
|
<div align="center">
|
||||||
<img src="https://img.shields.io/badge/python-3.12+-blue.svg" alt="python">
|
<img src="https://img.shields.io/badge/python-3.12+-blue.svg" alt="python">
|
||||||
<img src="https://img.shields.io/badge/license-GPL--3.0-blue.svg" alt="license">
|
<img src="https://img.shields.io/badge/license-GPL--3.0-blue.svg" alt="license">
|
||||||
<img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/ViperEkura/AstrAI/gh-pages/badges/release.json" alt="release">
|
<img src="https://img.shields.io/github/v/release/ViperEkura/AstrAI?label=Release&color=76bad9" alt="release">
|
||||||
<img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/ViperEkura/AstrAI/gh-pages/badges/stars.json" alt="stars">
|
<img src="https://img.shields.io/github/stars/ViperEkura/AstrAI?style=flat&label=Stars&color=76bad9" alt="stars">
|
||||||
<img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/ViperEkura/AstrAI/gh-pages/badges/forks.json" alt="forks">
|
<img src="https://img.shields.io/github/forks/ViperEkura/AstrAI?style=flat&label=Forks&color=76bad9" alt="forks">
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<br>
|
<br>
|
||||||
@@ -34,7 +34,8 @@
|
|||||||
## 📖 目录
|
## 📖 目录
|
||||||
|
|
||||||
- [特性](#特性)
|
- [特性](#特性)
|
||||||
- [快速开始](#快速开始)
|
- [快速上手](#快速上手)
|
||||||
|
- [演示](#演示)
|
||||||
- [文档](#文档)
|
- [文档](#文档)
|
||||||
- [贡献](#贡献)
|
- [贡献](#贡献)
|
||||||
- [社区](#社区)
|
- [社区](#社区)
|
||||||
@@ -55,33 +56,43 @@
|
|||||||
- 🤗 **HuggingFace 风格 API**: 类 HuggingFace 的 AutoModel/AutoTokenizer 接口,方便加载模型和分词器。
|
- 🤗 **HuggingFace 风格 API**: 类 HuggingFace 的 AutoModel/AutoTokenizer 接口,方便加载模型和分词器。
|
||||||
- 🔌 **双 API 兼容**: 同时支持 OpenAI 和 Anthropic 聊天补全 API,开箱即用。
|
- 🔌 **双 API 兼容**: 同时支持 OpenAI 和 Anthropic 聊天补全 API,开箱即用。
|
||||||
|
|
||||||
### 快速开始
|
### 快速上手
|
||||||
|
|
||||||
#### 安装
|
端到端演示,只需 5 步:
|
||||||
|
|
||||||
|
**1. 安装**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/ViperEkura/AstrAI.git
|
git clone https://github.com/ViperEkura/AstrAI.git
|
||||||
cd AstrAI
|
cd AstrAI
|
||||||
pip install -e .
|
pip install -e .
|
||||||
|
# pip install -e ".[dev]" # 可选:开发依赖(pytest, ruff)
|
||||||
```
|
```
|
||||||
|
|
||||||
安装开发依赖:
|
**2. 下载模型**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip install -e ".[dev]"
|
python scripts/demo/download.py # 下载 1B 检查点到 params/
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 下载预训练模型
|
**3. 预处理数据**
|
||||||
|
|
||||||
下载预训练模型权重(1B 双语检查点)到 `params/` 目录:
|
创建 `pretrain.json`(`seq` 策略的预处理配置):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"input": {"sections": [{"field": "text", "action": "train"}]},
|
||||||
|
"preprocessing": {"max_seq_len": 2048},
|
||||||
|
"output": {"storage_format": "bin"}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python scripts/demo/download.py
|
python scripts/tools/preprocess.py data/*.jsonl -o output/ -c pretrain.json
|
||||||
```
|
```
|
||||||
|
|
||||||
或从 [HuggingFace](https://huggingface.co/ViperEk/KHAOSZ) 手动下载放入 `params/`。
|
**4. 训练**
|
||||||
|
|
||||||
#### 训练模型
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
export CUDA_VISIBLE_DEVICES=0,1,2,3
|
export CUDA_VISIBLE_DEVICES=0,1,2,3
|
||||||
@@ -108,15 +119,54 @@ nohup python scripts/tools/train.py \
|
|||||||
> out.log 2> err.log &
|
> out.log 2> err.log &
|
||||||
```
|
```
|
||||||
|
|
||||||
完整参数列表见[参数说明](./params.md)。
|
**5. 启动服务并调用**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 终端 1:启动服务
|
||||||
|
python scripts/tools/server.py --param_path ./params --device cuda
|
||||||
|
|
||||||
|
# 终端 2:发起请求
|
||||||
|
curl http://localhost:8000/v1/chat/completions \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"messages":[{"role":"user","content":"你好"}],"max_tokens":512}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### 演示
|
||||||
|
|
||||||
|
查看 `scripts/demo/` 文件夹中的演示:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 下载模型权重(运行演示前必需)
|
||||||
|
python scripts/demo/download.py # model → params/
|
||||||
|
|
||||||
|
# 交互式流式聊天(多轮对话,保持历史记录)
|
||||||
|
python scripts/demo/stream_chat.py
|
||||||
|
# 在 >> 后输入消息,输入 !exit 退出
|
||||||
|
|
||||||
|
# 批量生成(5 条硬编码提示词,非流式)
|
||||||
|
python scripts/demo/generate_batch.py
|
||||||
|
|
||||||
|
# 单条提示词自回归流式生成
|
||||||
|
python scripts/demo/generate_ar.py
|
||||||
|
```
|
||||||
|
|
||||||
|
所有生成演示默认使用 `temperature=0.8`、`top_p=0.95`、`top_k=50`、`max_tokens=2048`,需要 `params/` 目录包含模型权重(请先运行 `download.py`)。
|
||||||
|
|
||||||
|
观看 [bilibili](https://www.bilibili.com/video/BV1fuLB6yEj6) 上的视频演示。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
更多选项请参考[文档](#文档)。
|
||||||
|
|
||||||
#### 文本生成
|
#### 文本生成
|
||||||
|
|
||||||
|
从 JSONL 文件批量生成:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python scripts/tools/generate.py \
|
python scripts/tools/generate.py \
|
||||||
--param_path /path/to/model \
|
--param_path ./params \
|
||||||
--input_json_file /path/to/input.jsonl \
|
--input_json_file input.jsonl \
|
||||||
--output_json_file /path/to/output.jsonl
|
--output_json_file output.jsonl
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Docker
|
#### Docker
|
||||||
@@ -130,9 +180,6 @@ docker build -t astrai:latest .
|
|||||||
# 启用 GPU 运行
|
# 启用 GPU 运行
|
||||||
docker run --gpus all -it astrai:latest
|
docker run --gpus all -it astrai:latest
|
||||||
|
|
||||||
# 指定特定 GPU
|
|
||||||
docker run --gpus '"device=0,1"' -it astrai:latest
|
|
||||||
|
|
||||||
# 运行推理服务
|
# 运行推理服务
|
||||||
docker run --gpus all -p 8000:8000 astrai:latest \
|
docker run --gpus all -p 8000:8000 astrai:latest \
|
||||||
python -m scripts.tools.server --port 8000 --device cuda
|
python -m scripts.tools.server --port 8000 --device cuda
|
||||||
@@ -149,84 +196,37 @@ docker compose --profile cpu up -d
|
|||||||
|
|
||||||
> **注意**: 必须使用 `--gpus all` 才能启用 CUDA 支持,否则 `torch.cuda.is_available()` 将返回 `False`。
|
> **注意**: 必须使用 `--gpus all` 才能启用 CUDA 支持,否则 `torch.cuda.is_available()` 将返回 `False`。
|
||||||
|
|
||||||
#### 启动 HTTP 服务
|
#### HTTP API 示例
|
||||||
|
|
||||||
启动推理服务器,支持 OpenAI 和 Anthropic 兼容的 HTTP API:
|
除[快速上手](#快速上手)流程外,更多请求示例:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python -m scripts.tools.server --port 8000 --device cuda
|
|
||||||
```
|
|
||||||
|
|
||||||
发起请求:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# OpenAI 兼容
|
|
||||||
curl -X POST http://localhost:8000/v1/chat/completions \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-d '{
|
|
||||||
"messages": [{"role": "user", "content": "你好"}],
|
|
||||||
"max_tokens": 512
|
|
||||||
}'
|
|
||||||
|
|
||||||
# OpenAI 兼容流式
|
# OpenAI 兼容流式
|
||||||
curl -X POST http://localhost:8000/v1/chat/completions \
|
curl -X POST http://localhost:8000/v1/chat/completions \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d '{
|
-d '{"messages":[{"role":"user","content":"讲个故事"}],"stream":true,"max_tokens":500}'
|
||||||
"messages": [{"role": "user", "content": "讲个故事"}],
|
|
||||||
"stream": true,
|
|
||||||
"max_tokens": 500
|
|
||||||
}'
|
|
||||||
|
|
||||||
# Anthropic 兼容
|
# Anthropic 兼容
|
||||||
curl -X POST http://localhost:8000/v1/messages \
|
curl -X POST http://localhost:8000/v1/messages \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d '{
|
-d '{"model":"astrai","system":"你是一个乐于助人的助手。","messages":[{"role":"user","content":"你好"}],"max_tokens":512}'
|
||||||
"model": "astrai",
|
|
||||||
"system": "你是一个乐于助人的助手。",
|
|
||||||
"messages": [{"role": "user", "content": "你好"}],
|
|
||||||
"max_tokens": 512
|
|
||||||
}'
|
|
||||||
|
|
||||||
# Anthropic 兼容流式并设置停止序列
|
# Anthropic 兼容流式并设置停止序列
|
||||||
curl -X POST http://localhost:8000/v1/messages \
|
curl -X POST http://localhost:8000/v1/messages \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d '{
|
-d '{"model":"astrai","messages":[{"role":"user","content":"写个故事"}],"max_tokens":500,"stream":true,"stop_sequences":["结束"]}'
|
||||||
"model": "astrai",
|
|
||||||
"messages": [{"role": "user", "content": "写个故事"}],
|
|
||||||
"max_tokens": 500,
|
|
||||||
"stream": true,
|
|
||||||
"stop_sequences": ["结束"]
|
|
||||||
}'
|
|
||||||
|
|
||||||
# 健康检查
|
# 健康检查
|
||||||
curl http://localhost:8000/health
|
curl http://localhost:8000/health
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 演示
|
SSE 流式格式、错误码和统计端点详见[推理文档](./inference.md)。
|
||||||
|
|
||||||
查看 `scripts/demo/` 文件夹中的演示:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 下载模型权重(运行演示前必需)
|
|
||||||
python scripts/demo/download.py
|
|
||||||
|
|
||||||
# 交互式流式聊天
|
|
||||||
python scripts/demo/stream_chat.py
|
|
||||||
|
|
||||||
# 批量生成
|
|
||||||
python scripts/demo/generate_batch.py
|
|
||||||
|
|
||||||
# 自回归生成
|
|
||||||
python scripts/demo/generate_ar.py
|
|
||||||
```
|
|
||||||
|
|
||||||
观看 [bilibili](https://www.bilibili.com/video/BV1fuLB6yEj6) 上的视频演示。
|
|
||||||
|
|
||||||
### 文档
|
### 文档
|
||||||
|
|
||||||
| 文档 | 说明 |
|
| 文档 | 说明 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| [参数说明](./params.md) | 训练与推理参数配置 |
|
| [CLI 参考](./params.md) | 所有 CLI 工具参数(训练、服务、生成、预处理) |
|
||||||
| [架构文档](./architecture.md) | 系统架构、类图与设计模式 |
|
| [架构文档](./architecture.md) | 系统架构、类图与设计模式 |
|
||||||
| [训练文档](./training.md) | 训练循环、策略与公式 |
|
| [训练文档](./training.md) | 训练循环、策略与公式 |
|
||||||
| [推理文档](./inference.md) | KVCache、连续批处理、采样与 HTTP API |
|
| [推理文档](./inference.md) | KVCache、连续批处理、采样与 HTTP API |
|
||||||
|
|||||||
+68
-56
@@ -1,5 +1,12 @@
|
|||||||
# AstrAI Architecture
|
# AstrAI Architecture
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- [Class Diagram](#class-diagram) — Full Mermaid class diagram across 10+ namespaces
|
||||||
|
- [Module Overview](#module-overview) — Component inventory per module
|
||||||
|
- [Design Patterns](#design-patterns) — 13 documented patterns with classes
|
||||||
|
- [Core Relationships](#core-relationships) — 11 key inter-component relationships
|
||||||
|
|
||||||
## Class Diagram
|
## Class Diagram
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
@@ -8,12 +15,13 @@ classDiagram
|
|||||||
class BaseConfig {
|
class BaseConfig {
|
||||||
+to_dict() Dict
|
+to_dict() Dict
|
||||||
+from_dict(d) Self
|
+from_dict(d) Self
|
||||||
+from_json(path) Self
|
+from_file(path) Self
|
||||||
+to_json(path)
|
+to_file(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
class BaseModelConfig {
|
class BaseModelConfig {
|
||||||
+Optional[str] model_type
|
+Optional[str] model_type
|
||||||
|
+float neftune_alpha
|
||||||
+from_file(config_path) Self
|
+from_file(config_path) Self
|
||||||
+to_file(config_path)
|
+to_file(config_path)
|
||||||
}
|
}
|
||||||
@@ -51,41 +59,44 @@ classDiagram
|
|||||||
+Optional[int] dim_ffn
|
+Optional[int] dim_ffn
|
||||||
+Optional[int] max_len
|
+Optional[int] max_len
|
||||||
+Optional[float] rope_theta
|
+Optional[float] rope_theta
|
||||||
|
+str attn_type
|
||||||
+Optional[int] n_heads
|
+Optional[int] n_heads
|
||||||
+Optional[int] n_kv_heads
|
+Optional[int] n_kv_heads
|
||||||
+Optional[bool] use_qk_norm
|
+Optional[bool] use_qk_norm
|
||||||
+Optional[bool] use_gated_attention
|
+Optional[bool] use_gated_attention
|
||||||
|
+str ffn_type
|
||||||
+Optional[dict] rope_scaling
|
+Optional[dict] rope_scaling
|
||||||
+Optional[str] pooling_type
|
+Optional[str] pooling_type
|
||||||
+Optional[bool] normalize_embeddings
|
+Optional[bool] normalize_embeddings
|
||||||
}
|
}
|
||||||
|
|
||||||
class ConfigFactory {
|
class ConfigFactory {
|
||||||
+Registry _registry
|
+Dict _entries
|
||||||
+register(name) decorator
|
+register(name) decorator
|
||||||
+load(raw) BaseConfig
|
+load(raw) BaseConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
class InputConfig {
|
class InputConfig {
|
||||||
+str type
|
+Optional[List[Dict]] sections
|
||||||
+str messages_key
|
+Optional[Dict[str, Dict]] sources
|
||||||
+str prompt_key
|
|
||||||
+str response_key
|
|
||||||
+str text_key
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class ProcessingConfig {
|
class ProcessingConfig {
|
||||||
+int max_seq_len
|
+int max_seq_len
|
||||||
+int min_chars
|
+int min_chars
|
||||||
+int max_chars
|
+int max_chars
|
||||||
+bool deduplicate
|
|
||||||
+Optional[int] max_items
|
+Optional[int] max_items
|
||||||
|
+str packing_strategy
|
||||||
|
+int max_packed_len
|
||||||
|
+str truncation_mode
|
||||||
}
|
}
|
||||||
|
|
||||||
class OutputConfig {
|
class OutputConfig {
|
||||||
+Optional[str] domain_key
|
+Optional[str] domain_key
|
||||||
+str storage_format
|
+str storage_format
|
||||||
+int max_tokens_per_shard
|
+int max_tokens_per_shard
|
||||||
|
+Dict[str, str] dtype
|
||||||
|
+str position_ids_mode
|
||||||
}
|
}
|
||||||
|
|
||||||
class PipelineConfig {
|
class PipelineConfig {
|
||||||
@@ -110,7 +121,7 @@ classDiagram
|
|||||||
+float max_grad_norm
|
+float max_grad_norm
|
||||||
+list gradient_checkpointing_modules
|
+list gradient_checkpointing_modules
|
||||||
+int start_epoch
|
+int start_epoch
|
||||||
+int start_batch
|
+int start_samples
|
||||||
+str ckpt_dir
|
+str ckpt_dir
|
||||||
+int ckpt_interval
|
+int ckpt_interval
|
||||||
+str log_dir
|
+str log_dir
|
||||||
@@ -128,7 +139,9 @@ classDiagram
|
|||||||
+str start_method
|
+str start_method
|
||||||
+str device_type
|
+str device_type
|
||||||
+Optional[Dataset] val_dataset
|
+Optional[Dataset] val_dataset
|
||||||
|
+Optional[float] val_split
|
||||||
+int val_step
|
+int val_step
|
||||||
|
+float neftune_alpha
|
||||||
+str parallel_mode
|
+str parallel_mode
|
||||||
+dict executor_kwargs
|
+dict executor_kwargs
|
||||||
+dict extra_kwargs
|
+dict extra_kwargs
|
||||||
@@ -190,13 +203,13 @@ classDiagram
|
|||||||
}
|
}
|
||||||
|
|
||||||
class StoreFactory {
|
class StoreFactory {
|
||||||
+Registry _registry
|
+Dict _entries
|
||||||
+register(name) decorator
|
+register(name) decorator
|
||||||
+create(storage_type) Store
|
+create(storage_type) Store
|
||||||
}
|
}
|
||||||
|
|
||||||
class DatasetFactory {
|
class DatasetFactory {
|
||||||
+Registry _registry
|
+Dict _entries
|
||||||
+register(name) decorator
|
+register(name) decorator
|
||||||
+create(train_type, window_size, stride) BaseDataset
|
+create(train_type, window_size, stride) BaseDataset
|
||||||
+load(train_type, load_path, window_size, stride, storage_type) BaseDataset
|
+load(train_type, load_path, window_size, stride, storage_type) BaseDataset
|
||||||
@@ -207,19 +220,20 @@ classDiagram
|
|||||||
class Checkpoint {
|
class Checkpoint {
|
||||||
+dict state_dict
|
+dict state_dict
|
||||||
+int epoch
|
+int epoch
|
||||||
+int iteration
|
+int consumed_samples
|
||||||
+dict extra
|
+dict extra
|
||||||
+dict meta
|
+dict meta
|
||||||
+dict config
|
+dict config
|
||||||
+save(save_dir)
|
+save(save_dir)
|
||||||
+load(save_dir, broadcast) Checkpoint
|
+load(save_dir, broadcast) Checkpoint
|
||||||
|
+load_any(save_dir, broadcast) Optional[Checkpoint]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
namespace model {
|
namespace model {
|
||||||
class AutoModel {
|
class AutoModel {
|
||||||
+BaseModelConfig config
|
+BaseModelConfig config
|
||||||
+Registry _registry
|
+Dict _entries
|
||||||
+register(name) decorator
|
+register(name) decorator
|
||||||
+get_component_class(name) Type
|
+get_component_class(name) Type
|
||||||
+from_pretrained(path, disable_random_init, strict) nn.Module
|
+from_pretrained(path, disable_random_init, strict) nn.Module
|
||||||
@@ -342,7 +356,9 @@ classDiagram
|
|||||||
|
|
||||||
class Embedding {
|
class Embedding {
|
||||||
+Parameter weight
|
+Parameter weight
|
||||||
|
+float neftune_noise_alpha
|
||||||
+forward(x) Tensor
|
+forward(x) Tensor
|
||||||
|
+set_neftune_alpha(alpha)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -395,24 +411,19 @@ classDiagram
|
|||||||
}
|
}
|
||||||
|
|
||||||
namespace factory {
|
namespace factory {
|
||||||
class Registry {
|
|
||||||
+Dict _entries
|
|
||||||
+register(name, component_cls, category, priority)
|
|
||||||
+get(name) Type
|
|
||||||
+list_names() List[str]
|
|
||||||
}
|
|
||||||
|
|
||||||
class BaseFactory {
|
class BaseFactory {
|
||||||
+Registry _registry
|
+Dict _entries
|
||||||
+register(name, category, priority) decorator
|
+register(name) decorator
|
||||||
+create(name, *args, **kwargs) T
|
+create(name, *args, **kwargs) T
|
||||||
|
+get_component_class(name) Type
|
||||||
+list_registered() list
|
+list_registered() list
|
||||||
|
+is_registered(name) bool
|
||||||
}
|
}
|
||||||
|
|
||||||
class MaskBuilderFactory {
|
class MaskBuilderFactory {
|
||||||
+Registry _registry
|
+Dict _entries
|
||||||
+register(name) decorator
|
+register(name) decorator
|
||||||
+create(input_type, config, tokenizer) BaseMaskBuilder
|
+create(name, *args, **kwargs) BaseMaskBuilder
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -435,13 +446,15 @@ classDiagram
|
|||||||
+dict model_config
|
+dict model_config
|
||||||
+BaseExecutor executor
|
+BaseExecutor executor
|
||||||
+int epoch
|
+int epoch
|
||||||
+int iteration
|
+int consumed_samples
|
||||||
+float loss
|
+float loss
|
||||||
|
+float grad_norm
|
||||||
+DataLoader val_dataloader
|
+DataLoader val_dataloader
|
||||||
+float val_loss
|
+float val_loss
|
||||||
+int world_size
|
+int world_size
|
||||||
+int rank
|
+int rank
|
||||||
+dict kwargs
|
+dict kwargs
|
||||||
|
+optimizer_step() int
|
||||||
}
|
}
|
||||||
|
|
||||||
class TrainContextBuilder {
|
class TrainContextBuilder {
|
||||||
@@ -461,7 +474,7 @@ classDiagram
|
|||||||
}
|
}
|
||||||
|
|
||||||
class StrategyFactory {
|
class StrategyFactory {
|
||||||
+Registry _registry
|
+Dict _entries
|
||||||
+register(name) decorator
|
+register(name) decorator
|
||||||
+create(train_type, model, device, **kwargs) BaseStrategy
|
+create(train_type, model, device, **kwargs) BaseStrategy
|
||||||
}
|
}
|
||||||
@@ -502,9 +515,9 @@ classDiagram
|
|||||||
}
|
}
|
||||||
|
|
||||||
class SchedulerFactory {
|
class SchedulerFactory {
|
||||||
+Registry _registry
|
+Dict _entries
|
||||||
+register(name) decorator
|
+register(name) decorator
|
||||||
+create(optimizer, schedule_type, **kwargs) BaseScheduler
|
+create(name, *args, **kwargs) BaseScheduler
|
||||||
}
|
}
|
||||||
|
|
||||||
class CosineScheduler {
|
class CosineScheduler {
|
||||||
@@ -521,6 +534,13 @@ classDiagram
|
|||||||
+int t_mult
|
+int t_mult
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class WSDScheduler {
|
||||||
|
+int warmup_steps
|
||||||
|
+int stable_steps
|
||||||
|
+int decay_steps
|
||||||
|
+float min_rate
|
||||||
|
}
|
||||||
|
|
||||||
class TrainCallback {
|
class TrainCallback {
|
||||||
<<protocol>>
|
<<protocol>>
|
||||||
+on_train_begin(context)
|
+on_train_begin(context)
|
||||||
@@ -581,23 +601,11 @@ classDiagram
|
|||||||
}
|
}
|
||||||
|
|
||||||
class CallbackFactory {
|
class CallbackFactory {
|
||||||
+Registry _registry
|
+Dict _entries
|
||||||
+register(name) decorator
|
+register(name) decorator
|
||||||
+create(name, **kwargs) TrainCallback
|
+create(name, **kwargs) TrainCallback
|
||||||
}
|
}
|
||||||
|
|
||||||
class Muon {
|
|
||||||
+float lr
|
|
||||||
+float momentum
|
|
||||||
+float weight_decay
|
|
||||||
+bool nesterov
|
|
||||||
+int ns_steps
|
|
||||||
+Optional[float] adamw_lr
|
|
||||||
+tuple adamw_betas
|
|
||||||
+float adamw_eps
|
|
||||||
+float adamw_wd
|
|
||||||
+step(closure) Optional[float]
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
namespace inference {
|
namespace inference {
|
||||||
@@ -802,7 +810,9 @@ classDiagram
|
|||||||
|
|
||||||
class ChatMessage {
|
class ChatMessage {
|
||||||
+str role
|
+str role
|
||||||
+str content
|
+Optional[str] content
|
||||||
|
+Optional[List[Dict]] tool_calls
|
||||||
|
+Optional[str] tool_call_id
|
||||||
}
|
}
|
||||||
|
|
||||||
class ChatCompletionRequest {
|
class ChatCompletionRequest {
|
||||||
@@ -819,6 +829,8 @@ classDiagram
|
|||||||
+Optional[float] frequency_penalty
|
+Optional[float] frequency_penalty
|
||||||
+Optional[Dict[int, float]] logit_bias
|
+Optional[Dict[int, float]] logit_bias
|
||||||
+Optional[str] user
|
+Optional[str] user
|
||||||
|
+Optional[List[ToolDef]] tools
|
||||||
|
+Optional[Union[str, Dict]] tool_choice
|
||||||
}
|
}
|
||||||
|
|
||||||
class AnthropicMessage {
|
class AnthropicMessage {
|
||||||
@@ -842,7 +854,7 @@ classDiagram
|
|||||||
<<abstract>>
|
<<abstract>>
|
||||||
+prepare(request, engine) Tuple[str, GenContext, List[str]]
|
+prepare(request, engine) Tuple[str, GenContext, List[str]]
|
||||||
+format_stream_start(ctx) List[str]
|
+format_stream_start(ctx) List[str]
|
||||||
+format_chunk(token) str
|
+format_chunk(token) List[str]
|
||||||
+format_stream_end(ctx, stop) List[str]
|
+format_stream_end(ctx, stop) List[str]
|
||||||
+format_response(ctx, content, stop) Dict
|
+format_response(ctx, content, stop) Dict
|
||||||
}
|
}
|
||||||
@@ -850,7 +862,7 @@ classDiagram
|
|||||||
class OpenAIResponseBuilder {
|
class OpenAIResponseBuilder {
|
||||||
+prepare(request, engine) Tuple
|
+prepare(request, engine) Tuple
|
||||||
+format_stream_start(ctx) List[str]
|
+format_stream_start(ctx) List[str]
|
||||||
+format_chunk(token) str
|
+format_chunk(token) List[str]
|
||||||
+format_stream_end(ctx, stop) List[str]
|
+format_stream_end(ctx, stop) List[str]
|
||||||
+format_response(ctx, content, stop) Dict
|
+format_response(ctx, content, stop) Dict
|
||||||
}
|
}
|
||||||
@@ -858,7 +870,7 @@ classDiagram
|
|||||||
class AnthropicResponseBuilder {
|
class AnthropicResponseBuilder {
|
||||||
+prepare(request, engine) Tuple
|
+prepare(request, engine) Tuple
|
||||||
+format_stream_start(ctx) List[str]
|
+format_stream_start(ctx) List[str]
|
||||||
+format_chunk(token) str
|
+format_chunk(token) List[str]
|
||||||
+format_stream_end(ctx, stop) List[str]
|
+format_stream_end(ctx, stop) List[str]
|
||||||
+format_response(ctx, content, stop) Dict
|
+format_response(ctx, content, stop) Dict
|
||||||
}
|
}
|
||||||
@@ -891,9 +903,9 @@ classDiagram
|
|||||||
+str yielded
|
+str yielded
|
||||||
}
|
}
|
||||||
|
|
||||||
class app {
|
class get_app {
|
||||||
<<singleton>>
|
<<module>>
|
||||||
+FastAPI app
|
+get_app() FastAPI
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -975,7 +987,7 @@ classDiagram
|
|||||||
}
|
}
|
||||||
|
|
||||||
class ExecutorFactory {
|
class ExecutorFactory {
|
||||||
+Registry _registry
|
+Dict _entries
|
||||||
+register(name) decorator
|
+register(name) decorator
|
||||||
+create(parallel_mode, **kwargs) BaseExecutor
|
+create(parallel_mode, **kwargs) BaseExecutor
|
||||||
}
|
}
|
||||||
@@ -1018,6 +1030,7 @@ classDiagram
|
|||||||
BaseStrategy <|-- GRPOStrategy
|
BaseStrategy <|-- GRPOStrategy
|
||||||
BaseScheduler <|-- CosineScheduler
|
BaseScheduler <|-- CosineScheduler
|
||||||
BaseScheduler <|-- SGDRScheduler
|
BaseScheduler <|-- SGDRScheduler
|
||||||
|
BaseScheduler <|-- WSDScheduler
|
||||||
TrainCallback <|-- GradientClippingCallback
|
TrainCallback <|-- GradientClippingCallback
|
||||||
TrainCallback <|-- GradientCheckpointingCallback
|
TrainCallback <|-- GradientCheckpointingCallback
|
||||||
TrainCallback <|-- CheckpointCallback
|
TrainCallback <|-- CheckpointCallback
|
||||||
@@ -1080,7 +1093,6 @@ classDiagram
|
|||||||
DecoderBlock *-- RMSNorm
|
DecoderBlock *-- RMSNorm
|
||||||
ChatCompletionRequest *-- ChatMessage
|
ChatCompletionRequest *-- ChatMessage
|
||||||
MessagesRequest *-- AnthropicMessage
|
MessagesRequest *-- AnthropicMessage
|
||||||
BaseFactory *-- Registry
|
|
||||||
BaseExecutor *-- GradientState
|
BaseExecutor *-- GradientState
|
||||||
AccumOptimizer o-- GradientState
|
AccumOptimizer o-- GradientState
|
||||||
AccumScheduler o-- GradientState
|
AccumScheduler o-- GradientState
|
||||||
@@ -1157,16 +1169,16 @@ classDiagram
|
|||||||
|
|
||||||
| Module | Components | Description |
|
| Module | Components | Description |
|
||||||
|--------|------------|-------------|
|
|--------|------------|-------------|
|
||||||
| **astrai.config** | BaseConfig, BaseModelConfig, AutoRegressiveLMConfig, EncoderConfig, ConfigFactory, TrainConfig, PipelineConfig, InputConfig, ProcessingConfig, OutputConfig | Configuration management (to_dict/from_dict, to_file/from_file, from_json/to_json) |
|
| **astrai.config** | BaseConfig, BaseModelConfig, AutoRegressiveLMConfig, EncoderConfig, ConfigFactory, TrainConfig, PipelineConfig, InputConfig, ProcessingConfig, OutputConfig | Configuration management (to_dict/from_dict, to_file/from_file) |
|
||||||
| **astrai.preprocessing** | BaseMaskBuilder, MaskBuilderFactory, SectionedMaskBuilder, Pipeline, filter_by_length, PackingStrategy, PackingStrategyFactory, PositionIdStrategy, PositionIdStrategyFactory, StoreWriter, StoreWriterFactory | Declarative JSON-driven data preprocessing |
|
| **astrai.preprocessing** | BaseMaskBuilder, MaskBuilderFactory, SectionedMaskBuilder, Pipeline, filter_by_length, PackingStrategy, PackingStrategyFactory, PositionIdStrategy, PositionIdStrategyFactory, StoreWriter, StoreWriterFactory | Declarative JSON-driven data preprocessing |
|
||||||
| **astrai.dataset** | BaseDataset–GRPODataset, Store–MmapStore, StoreFactory, ResumableDistributedSampler, DatasetFactory | Dataset loading and management |
|
| **astrai.dataset** | BaseDataset–GRPODataset, Store–MmapStore, StoreFactory, ResumableDistributedSampler, DatasetFactory | Dataset loading and management |
|
||||||
| **astrai.serialization** | Checkpoint | Model serialization |
|
| **astrai.serialization** | Checkpoint | Model serialization |
|
||||||
| **astrai.model** | AutoModel, AutoRegressiveLM, EmbeddingEncoder, DecoderBlock, GQA, MLA, MLP, DeepSeekMoE, AttnFactory, FFNFactory, RMSNorm, Linear, RotaryEmbedding, Embedding | Neural network model |
|
| **astrai.model** | AutoModel, AutoRegressiveLM, EmbeddingEncoder, DecoderBlock, GQA, MLA, MLP, DeepSeekMoE, AttnFactory, FFNFactory, RMSNorm, Linear, RotaryEmbedding, Embedding | Neural network model |
|
||||||
| **astrai.tokenize** | AutoTokenizer, ChatTemplate | Tokenizer and chat template |
|
| **astrai.tokenize** | AutoTokenizer, ChatTemplate | Tokenizer and chat template |
|
||||||
| **astrai.trainer** | Trainer, TrainContext, TrainContextBuilder, BaseStrategy–GRPOStrategy, StrategyFactory, BaseScheduler–SGDRScheduler, SchedulerFactory, TrainCallback(Protocol)–ValidationCallback, CallbackFactory, Muon | Training workflow |
|
| **astrai.trainer** | Trainer, TrainContext, TrainContextBuilder, BaseStrategy–GRPOStrategy, StrategyFactory, BaseScheduler–WSDScheduler, SchedulerFactory, TrainCallback(Protocol)–ValidationCallback, CallbackFactory | Training workflow |
|
||||||
| **astrai.inference** | InferenceEngine, InferenceScheduler, Executor, KVCache–KvcacheView, Allocator–Storage, Task, TaskManager, TaskStatus, GenerationRequest, GenerateResult, BaseSamplingStrategy–SamplingPipeline, ProtocolHandler, ResponseBuilder, OpenAIResponseBuilder, AnthropicResponseBuilder, StopChecker, GenContext, ChatMessage–MessagesRequest, app | Inference service |
|
| **astrai.inference** | InferenceEngine, InferenceScheduler, Executor, KVCache–KvcacheView, Allocator–Storage, Task, TaskManager, TaskStatus, GenerationRequest, GenerateResult, BaseSamplingStrategy–SamplingPipeline, ProtocolHandler, ResponseBuilder, OpenAIResponseBuilder, AnthropicResponseBuilder, StopChecker, GenContext, ChatMessage–MessagesRequest, app | Inference service |
|
||||||
| **astrai.parallel** | spawn_parallel_fn, setup_parallel, get_rank/get_world_size/get_current_device, only_on_rank, BaseExecutor, ExecutorFactory, NoneExecutor, DDPExecutor, FSDPExecutor, GradientState, AccumOptimizer, AccumScheduler, ParallelModel, RowParallelLinear, ColumnParallelLinear | Distributed parallel & gradient accumulation |
|
| **astrai.parallel** | spawn_parallel_fn, setup_parallel, get_rank/get_world_size/get_current_device, only_on_rank, BaseExecutor, ExecutorFactory, NoneExecutor, DDPExecutor, FSDPExecutor, GradientState, AccumOptimizer, AccumScheduler, ParallelModel, RowParallelLinear, ColumnParallelLinear | Distributed parallel & gradient accumulation |
|
||||||
| **astrai.factory** | Registry, BaseFactory[T] | Component registration |
|
| **astrai.factory** | BaseFactory | Component registration |
|
||||||
| **astrai.protocols** | OptimizerProtocol, SchedulerProtocol | Structural subtyping for optimizer/scheduler wrappers |
|
| **astrai.protocols** | OptimizerProtocol, SchedulerProtocol | Structural subtyping for optimizer/scheduler wrappers |
|
||||||
|
|
||||||
## Design Patterns
|
## Design Patterns
|
||||||
@@ -1174,7 +1186,7 @@ classDiagram
|
|||||||
| Pattern | Classes | Purpose |
|
| Pattern | Classes | Purpose |
|
||||||
|---------|---------|---------|
|
|---------|---------|---------|
|
||||||
| **Factory** | `AttnFactory`, `FFNFactory`, `StrategyFactory`, `DatasetFactory`, `SchedulerFactory`, `CallbackFactory`, `StoreFactory`, `ConfigFactory`, `ExecutorFactory` | Decorator-based component creation |
|
| **Factory** | `AttnFactory`, `FFNFactory`, `StrategyFactory`, `DatasetFactory`, `SchedulerFactory`, `CallbackFactory`, `StoreFactory`, `ConfigFactory`, `ExecutorFactory` | Decorator-based component creation |
|
||||||
| **Registry** | `BaseFactory`, `Registry` | Component registration with category/priority |
|
| **Registry** | `BaseFactory` | Component registration |
|
||||||
| **Strategy** | `SEQStrategy`, `SFTStrategy`, `DPOStrategy`, `GRPOStrategy` | Training strategy switching |
|
| **Strategy** | `SEQStrategy`, `SFTStrategy`, `DPOStrategy`, `GRPOStrategy` | Training strategy switching |
|
||||||
| **Strategy (Sampling)** | `TemperatureStrategy`, `TopKStrategy`, `TopPStrategy`, `SamplingPipeline` | Composable logit transformations |
|
| **Strategy (Sampling)** | `TemperatureStrategy`, `TopKStrategy`, `TopPStrategy`, `SamplingPipeline` | Composable logit transformations |
|
||||||
| **Strategy (API)** | `ResponseBuilder`, `OpenAIResponseBuilder`, `AnthropicResponseBuilder` | HTTP API handler with format hooks |
|
| **Strategy (API)** | `ResponseBuilder`, `OpenAIResponseBuilder`, `AnthropicResponseBuilder` | HTTP API handler with format hooks |
|
||||||
@@ -1197,7 +1209,7 @@ classDiagram
|
|||||||
6. **Distributed**: `spawn_parallel_fn` + `setup_parallel` for multi-process DDP
|
6. **Distributed**: `spawn_parallel_fn` + `setup_parallel` for multi-process DDP
|
||||||
7. **Dataset Loading**: `DatasetFactory` creates datasets, `Store` (H5Store/MmapStore) loads data with explicit `_length` and multi-segment `_data`
|
7. **Dataset Loading**: `DatasetFactory` creates datasets, `Store` (H5Store/MmapStore) loads data with explicit `_length` and multi-segment `_data`
|
||||||
8. **Checkpoint**: `Checkpoint` saves/loads safetensors + metadata (rank-0 only), extra state saved as `{key}.pt`
|
8. **Checkpoint**: `Checkpoint` saves/loads safetensors + metadata (rank-0 only), extra state saved as `{key}.pt`
|
||||||
9. **Scheduler**: `SchedulerFactory` creates `CosineScheduler`/`SGDRScheduler`
|
9. **Scheduler**: `SchedulerFactory` creates `CosineScheduler`/`SGDRScheduler`/`WSDScheduler`
|
||||||
10. **AutoModel**: `from_pretrained()` loads `config.json` + `model.safetensors`, `_disable_random_init` replaces `nn.init.*` with no-ops
|
10. **AutoModel**: `from_pretrained()` loads `config.json` + `model.safetensors`, `_disable_random_init` replaces `nn.init.*` with no-ops
|
||||||
11. **Protocols**: `OptimizerProtocol` / `SchedulerProtocol` — structural subtyping for `AccumOptimizer` / `AccumScheduler` wrappers
|
11. **Protocols**: `OptimizerProtocol` / `SchedulerProtocol` — structural subtyping for `AccumOptimizer` / `AccumScheduler` wrappers
|
||||||
|
|
||||||
|
|||||||
+50
-5
@@ -1,17 +1,58 @@
|
|||||||
# Data Flow
|
# Data Flow
|
||||||
|
|
||||||
This document describes the data pipeline: from raw text to model input tensors.
|
This document describes the data pipeline: from raw text to model input tensors. For creating preprocessing configs, see [Preprocessing Guide](preprocessing.md).
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- [Overview](#overview)
|
||||||
|
- [Data Preparation](#data-preparation) — tokenization, format detection, backends
|
||||||
|
- [Data Keys by Training Type](#data-keys-by-training-type)
|
||||||
|
- [Dataset Architecture](#dataset-architecture)
|
||||||
|
- [Sampler](#sampler)
|
||||||
|
- [DataLoader](#dataloader)
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
```
|
```
|
||||||
Raw Text → AutoTokenizer → Token IDs → .h5/.bin → Store.load() → Store.fetch() → Dataset → Sampler → DataLoader → Training/Inference
|
JSONL Lines → Pipeline (mask builder) → Tokenized Tensors
|
||||||
|
↓
|
||||||
|
.h5 or .bin storage
|
||||||
|
↓
|
||||||
|
Store.load()
|
||||||
|
↓
|
||||||
|
Store.fetch(begin, end, keys)
|
||||||
|
↓
|
||||||
|
BaseDataset.__getitem__(idx)
|
||||||
|
↓
|
||||||
|
Sampler → DataLoader → Training / Inference
|
||||||
```
|
```
|
||||||
|
|
||||||
## Data Preparation
|
## Data Preparation
|
||||||
|
|
||||||
Raw text is tokenized via `AutoTokenizer.encode()` and saved as HDF5 (`.h5`) or binary (`.bin` + `meta.json`) files with keyed tensor groups.
|
Raw text is tokenized via `AutoTokenizer.encode()` and saved as HDF5 (`.h5`) or binary (`.bin` + `meta.json`) files with keyed tensor groups.
|
||||||
|
|
||||||
|
### Tokenization
|
||||||
|
|
||||||
|
The `Pipeline` reads JSONL lines, applies the mask builder (see [Preprocessing](preprocessing.md)), and produces flat token sequences:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Per JSONL line: messages → chat template → token IDs + loss mask
|
||||||
|
tokens = tokenizer.encode(rendered_text) # List[int]
|
||||||
|
loss_mask = [0, 0, 0, 1, 1, 1, 1, 1, 1] # 0=masked, 1=train
|
||||||
|
# Stored as flat tensors, packed with other lines by packing strategy
|
||||||
|
```
|
||||||
|
|
||||||
|
The output `meta.json` records the storage format, key names, dtype, total token count, and tensor shapes for each shard.
|
||||||
|
|
||||||
|
### Format Detection
|
||||||
|
|
||||||
|
`detect_format(load_path)` inspects the path:
|
||||||
|
|
||||||
|
- If `load_path` is a file: checks suffix — `.h5`/`.hdf5` → `"h5"`, unknown suffix raises `ValueError`
|
||||||
|
- If `load_path` is a directory: recursively globs for `*.h5`/`*.hdf5` files → `"h5"`, or `*.bin` + `**/meta.json` → `"bin"`
|
||||||
|
|
||||||
|
### Store Backends
|
||||||
|
|
||||||
Storage format is auto-detected by `detect_format()`; backends are dispatched via registry:
|
Storage format is auto-detected by `detect_format()`; backends are dispatched via registry:
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -19,7 +60,11 @@ StoreFactory.create("h5") → H5Store
|
|||||||
StoreFactory.create("bin") → MmapStore
|
StoreFactory.create("bin") → MmapStore
|
||||||
```
|
```
|
||||||
|
|
||||||
H5 backend supports shared memory via `.share_memory_()`. Bin (mmap) uses OS page-cache sharing natively.
|
**H5Store**: Reads HDF5 files, supports `share_memory_()` for multi-process DataLoader workers (copies tensors to shared memory).
|
||||||
|
|
||||||
|
**MmapStore**: Memory-maps `.bin` files. OS page cache sharing is native — no explicit `share_memory_()` needed. Uses `torch.from_numpy(np.memmap(...))`.
|
||||||
|
|
||||||
|
Both backends normalise tensors into `Store._data[Dict[str, List[Tensor]]]` + `Store._cum[Dict[str, List[int]]]` (cumulative lengths for bisect-based indexing).
|
||||||
|
|
||||||
## Data Keys by Training Type
|
## Data Keys by Training Type
|
||||||
|
|
||||||
@@ -38,7 +83,7 @@ DatasetFactory.load(train_type, load_path, window_size, stride=None, storage_typ
|
|||||||
→ detect_format(load_path)
|
→ detect_format(load_path)
|
||||||
→ StoreFactory.create(storage_type)
|
→ StoreFactory.create(storage_type)
|
||||||
→ Store.load(load_path)
|
→ Store.load(load_path)
|
||||||
→ H5Store._normalize() / MmapStore._normalize()
|
→ _normalize(raw) # base Store, shared by both backends
|
||||||
→ Store._data[Dict[str, List[Tensor]]] + _cum[Dict[str, List[int]]]
|
→ Store._data[Dict[str, List[Tensor]]] + _cum[Dict[str, List[int]]]
|
||||||
→ BaseDataset.__getitem__(idx)
|
→ BaseDataset.__getitem__(idx)
|
||||||
→ get_index(idx) → [begin, end)
|
→ get_index(idx) → [begin, end)
|
||||||
@@ -61,4 +106,4 @@ DatasetFactory.load(train_type, load_path, window_size, stride=None, storage_typ
|
|||||||
|
|
||||||
Standard PyTorch `DataLoader` with configurable `batch_size`, `num_workers`, `pin_memory`, `prefetch_factor`. Sampler produces indices; dataloader fetches tensor batches via `__getitem__`.
|
Standard PyTorch `DataLoader` with configurable `batch_size`, `num_workers`, `pin_memory`, `prefetch_factor`. Sampler produces indices; dataloader fetches tensor batches via `__getitem__`.
|
||||||
|
|
||||||
> Document Update Time: 2026-05-30
|
> Document Update Time: 2026-06-19
|
||||||
|
|||||||
@@ -1,5 +1,16 @@
|
|||||||
# Inference
|
# Inference
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- [KV Cache](#kv-cache)
|
||||||
|
- [KVCache System](#kvcache-system)
|
||||||
|
- [Continuous Batching](#continuous-batching)
|
||||||
|
- [Sampling](#sampling-strategy-pattern)
|
||||||
|
- [Protocol Handlers](#protocol-handlers-strategy-pattern)
|
||||||
|
- [Engine & GenerateResult](#engine--generateresult)
|
||||||
|
- [HTTP API](#http-api) — endpoints, SSE, errors, stats
|
||||||
|
- [Engine API](#engine-api)
|
||||||
|
|
||||||
## KV Cache
|
## KV Cache
|
||||||
|
|
||||||
At decode time, only the last query token matters. All previous K/V are cached to avoid recomputation:
|
At decode time, only the last query token matters. All previous K/V are cached to avoid recomputation:
|
||||||
@@ -12,7 +23,7 @@ RoPE is applied **before** KV cache write, not after — otherwise position enco
|
|||||||
|
|
||||||
## KVCache System
|
## KVCache System
|
||||||
|
|
||||||
Six classes (plus two helpers) working together:
|
Seven classes working together:
|
||||||
|
|
||||||
```
|
```
|
||||||
KVCache (facade)
|
KVCache (facade)
|
||||||
@@ -133,6 +144,84 @@ Supports `stop_sequences` and streaming via `event: content_block_delta`.
|
|||||||
| `max_tokens` | Optional[int] | None | Max generation length |
|
| `max_tokens` | Optional[int] | None | Max generation length |
|
||||||
| `stream` | bool | False | Stream output |
|
| `stream` | bool | False | Stream output |
|
||||||
|
|
||||||
|
### SSE Streaming Format
|
||||||
|
|
||||||
|
**OpenAI** (`/v1/chat/completions`, `stream=true`):
|
||||||
|
|
||||||
|
```
|
||||||
|
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":...,"model":"astrai",
|
||||||
|
"choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}
|
||||||
|
|
||||||
|
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":0,"model":"astrai",
|
||||||
|
"choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}
|
||||||
|
|
||||||
|
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":...,"model":"astrai",
|
||||||
|
"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
|
||||||
|
|
||||||
|
data: {"prompt_tokens":5,"completion_tokens":1,"total_tokens":6}
|
||||||
|
|
||||||
|
data: [DONE]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Anthropic** (`/v1/messages`, `stream=true`):
|
||||||
|
|
||||||
|
```
|
||||||
|
event: message_start
|
||||||
|
data: {"type":"message_start","message":{"id":"msg_...","model":"astrai","role":"assistant",
|
||||||
|
"content":[],"usage":{"input_tokens":0}}}
|
||||||
|
|
||||||
|
event: content_block_start
|
||||||
|
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
|
||||||
|
|
||||||
|
event: content_block_delta
|
||||||
|
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}
|
||||||
|
|
||||||
|
event: content_block_stop
|
||||||
|
data: {"type":"content_block_stop","index":0}
|
||||||
|
|
||||||
|
event: message_delta
|
||||||
|
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{...}}
|
||||||
|
|
||||||
|
event: message_stop
|
||||||
|
data: {"type":"message_stop"}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Error Responses
|
||||||
|
|
||||||
|
The server returns standard HTTP status codes. Pydantic validation errors (e.g. missing required fields)
|
||||||
|
are handled automatically by FastAPI with 422 status. The only application-level error is engine initialization:
|
||||||
|
|
||||||
|
| Status | Meaning |
|
||||||
|
|--------|---------|
|
||||||
|
| 200 | Success |
|
||||||
|
| 422 | Unprocessable entity (Pydantic validation) |
|
||||||
|
| 503 | Service unavailable (model not loaded, engine not ready) |
|
||||||
|
|
||||||
|
Error response body (503):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"detail": "Engine not initialized"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Stats Endpoint
|
||||||
|
|
||||||
|
```
|
||||||
|
GET /stats
|
||||||
|
```
|
||||||
|
|
||||||
|
Response:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"total_tasks": 128,
|
||||||
|
"total_tokens": 10240,
|
||||||
|
"active_tasks": 3,
|
||||||
|
"waiting_queue": 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Engine API
|
## Engine API
|
||||||
|
|
||||||
```python
|
```python
|
||||||
@@ -149,4 +238,4 @@ async for token in engine.generate_async("Hello", ...): # -> AsyncGenerator[s
|
|||||||
print(token)
|
print(token)
|
||||||
```
|
```
|
||||||
|
|
||||||
> Document Update Time: 2026-05-30
|
> Document Update Time: 2026-06-19
|
||||||
|
|||||||
+85
-6
@@ -1,4 +1,11 @@
|
|||||||
# Parameter Documentation
|
# CLI Parameter Reference
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- [Training Parameters](#training-parameters)
|
||||||
|
- [Inference Server](#inference-server-serverpy)
|
||||||
|
- [Generate](#generate-generatepy)
|
||||||
|
- [Preprocess](#preprocess-preprocesspy)
|
||||||
|
|
||||||
## Training Parameters
|
## Training Parameters
|
||||||
|
|
||||||
@@ -46,7 +53,7 @@
|
|||||||
| `--ckpt_interval` | Iterations between checkpoints | 5000 |
|
| `--ckpt_interval` | Iterations between checkpoints | 5000 |
|
||||||
| `--ckpt_dir` | Checkpoint save directory | checkpoint |
|
| `--ckpt_dir` | Checkpoint save directory | checkpoint |
|
||||||
| `--start_epoch` | Resume from epoch (0 = from scratch) | 0 |
|
| `--start_epoch` | Resume from epoch (0 = from scratch) | 0 |
|
||||||
| `--start_batch` | Resume from batch iteration | 0 |
|
| `--start_samples` | Resume from sample count per rank | 0 |
|
||||||
|
|
||||||
### Validation
|
### Validation
|
||||||
|
|
||||||
@@ -60,8 +67,8 @@
|
|||||||
| Parameter | Description | Default |
|
| Parameter | Description | Default |
|
||||||
|-----------|-------------|---------|
|
|-----------|-------------|---------|
|
||||||
| `--log_dir` | Directory for metric logs | checkpoint/logs |
|
| `--log_dir` | Directory for metric logs | checkpoint/logs |
|
||||||
| `--log_interval` | Number of batch iterations between metric logs | 100 |
|
| `--log_interval` | Number of optimizer steps between metric logs | 1 |
|
||||||
| `--metrics` | Metrics to log (e.g. --metrics loss lr val_loss) | ["loss", "lr"] |
|
| `--metrics` | Metrics to log (e.g. --metrics loss lr val_loss) | ["loss", "lr", "grad_norm"] |
|
||||||
|
|
||||||
### Gradient Checkpointing
|
### Gradient Checkpointing
|
||||||
|
|
||||||
@@ -86,11 +93,23 @@
|
|||||||
| Parameter | Description | Default | Used by |
|
| Parameter | Description | Default | Used by |
|
||||||
|-----------|-------------|---------|---------|
|
|-----------|-------------|---------|---------|
|
||||||
| `--dpo_beta` | DPO beta value | 0.1 | `dpo` |
|
| `--dpo_beta` | DPO beta value | 0.1 | `dpo` |
|
||||||
| `--label_smoothing` | Label smoothing for cross-entropy loss | 0.05 | `seq`, `sft` |
|
| `--label_smoothing` | Label smoothing for cross-entropy loss | 0.0 | `seq`, `sft` |
|
||||||
| `--group_size` | GRPO group size | 4 | `grpo` |
|
| `--group_size` | GRPO group size | 4 | `grpo` |
|
||||||
| `--grpo_clip_eps` | GRPO clipping epsilon | 0.2 | `grpo` |
|
| `--grpo_clip_eps` | GRPO clipping epsilon | 0.2 | `grpo` |
|
||||||
| `--grpo_kl_coef` | GRPO KL penalty coefficient | 0.01 | `grpo` |
|
| `--grpo_kl_coef` | GRPO KL penalty coefficient | 0.01 | `grpo` |
|
||||||
| `--grpo_sync_interval` | GRPO ref_model sync interval (steps) | 200 | `grpo` |
|
| `--grpo_sync_interval` | GRPO ref_model sync interval (steps) | 200 | `grpo` |
|
||||||
|
| `--neftune_alpha` | NEFTune noise alpha (0=disabled, typical: 5.0) | 0.0 | `sft` |
|
||||||
|
|
||||||
|
### Scheduler
|
||||||
|
|
||||||
|
| Parameter | Description | Default |
|
||||||
|
|-----------|-------------|---------|
|
||||||
|
| `--schedule_type` | LR scheduler type (`cosine`, `sgdr`, `wsd`) | cosine |
|
||||||
|
| `--min_rate` | Minimum LR as fraction of base LR | None (scheduler default) |
|
||||||
|
| `--cycle_length` | SGDR first cycle length in steps | None (total_steps - warmup_steps) |
|
||||||
|
| `--t_mult` | SGDR cycle length multiplier per restart | 2 |
|
||||||
|
| `--stable_steps` | WSD stable plateau steps | None (required for wsd) |
|
||||||
|
| `--decay_steps` | WSD decay steps | None (total_steps - warmup_steps - stable_steps) |
|
||||||
|
|
||||||
### Usage Example
|
### Usage Example
|
||||||
|
|
||||||
@@ -121,4 +140,64 @@ nohup python scripts/tools/train.py \
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
> Document Update Time: 2026-05-24
|
## Inference Server (`server.py`)
|
||||||
|
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
|-----------|------|---------|-------------|
|
||||||
|
| `--host` | str | `0.0.0.0` | Host address |
|
||||||
|
| `--port` | int | `8000` | Port number |
|
||||||
|
| `--param_path` | path | `project_root/params` | Path to model parameters |
|
||||||
|
| `--device` | str | `cuda` | Device to load model on |
|
||||||
|
| `--dtype` | str | `bfloat16` | Model weights dtype (`bfloat16`, `float16`, `float32`) |
|
||||||
|
| `--max_batch_size` | int | `16` | Maximum batch size for continuous batching |
|
||||||
|
| `--reload` | flag | `False` | Enable auto-reload for development |
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
```bash
|
||||||
|
python scripts/tools/server.py --param_path ./params --device cuda --dtype bfloat16
|
||||||
|
```
|
||||||
|
|
||||||
|
See [Inference Guide](inference.md) for HTTP API documentation.
|
||||||
|
|
||||||
|
## Generate (`generate.py`)
|
||||||
|
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
|-----------|------|---------|-------------|
|
||||||
|
| `--param_path` | str | required | Path to the model directory |
|
||||||
|
| `--input_json_file` | str | required | Path to the input JSONL file |
|
||||||
|
| `--output_json_file` | str | required | Path to the output JSONL file |
|
||||||
|
| `--question_key` | str | `question` | Key for the question in input JSON |
|
||||||
|
| `--response_key` | str | `response` | Key for the response in output JSON |
|
||||||
|
| `--temperature` | float | `0.60` | Sampling temperature |
|
||||||
|
| `--top_k` | int | `30` | Top-k filtering |
|
||||||
|
| `--top_p` | float | `0.95` | Nucleus sampling threshold |
|
||||||
|
| `--batch_size` | int | `1` | Batch size for generation |
|
||||||
|
| `--max_tokens` | int | model config `max_len` | Maximum tokens to generate |
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
```bash
|
||||||
|
python scripts/tools/generate.py \
|
||||||
|
--param_path ./params \
|
||||||
|
--input_json_file input.jsonl \
|
||||||
|
--output_json_file output.jsonl
|
||||||
|
```
|
||||||
|
|
||||||
|
## Preprocess (`preprocess.py`)
|
||||||
|
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
|-----------|------|---------|-------------|
|
||||||
|
| `input_files` | path(s) | required | Input JSONL file(s), supports glob (`data/*.jsonl`) |
|
||||||
|
| `--output_dir`, `-o` | path | required | Output directory for processed data |
|
||||||
|
| `--config`, `-c` | path | required | Preprocessing pipeline config (JSON) |
|
||||||
|
| `--tokenizer_path` | str | `params` | Path to tokenizer directory |
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
```bash
|
||||||
|
python scripts/tools/preprocess.py data/*.jsonl -o output/ -c sft.json
|
||||||
|
```
|
||||||
|
|
||||||
|
See [Preprocessing Guide](preprocessing.md) for config file format and examples.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
> Document Update Time: 2026-06-19
|
||||||
@@ -2,6 +2,17 @@
|
|||||||
|
|
||||||
Declarative JSON-driven data preprocessing. One `SectionedMaskBuilder` handles all formats via `input.sections` (single-output) or `input.sources` (multi-output).
|
Declarative JSON-driven data preprocessing. One `SectionedMaskBuilder` handles all formats via `input.sections` (single-output) or `input.sources` (multi-output).
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- [Philosophy](#philosophy)
|
||||||
|
- [Config Structure](#config-structure)
|
||||||
|
- [Quick Start](#quick-start) — SFT Chat, SFT Instruction, Pretrain, DPO, GRPO examples
|
||||||
|
- [Configuration Reference](#configuration-reference) — all fields
|
||||||
|
- [Mask Algorithm](#mask-algorithm)
|
||||||
|
- [Output Layout](#output-layout)
|
||||||
|
- [CLI](#cli)
|
||||||
|
- [Python API](#python-api)
|
||||||
|
|
||||||
## Philosophy
|
## Philosophy
|
||||||
|
|
||||||
| Component | Responsibility |
|
| Component | Responsibility |
|
||||||
@@ -15,8 +26,9 @@ A single config file captures the entire pipeline, reusable and version-controll
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
|
"version": 1,
|
||||||
"input": {}, // sections (single) or sources (multi)
|
"input": {}, // sections (single) or sources (multi)
|
||||||
"mask": {}, // role → "train" | "mask"
|
"mask": {}, // role -> "train" | "mask"
|
||||||
"mask_default": "mask",
|
"mask_default": "mask",
|
||||||
"preprocessing": {},
|
"preprocessing": {},
|
||||||
"output": {}
|
"output": {}
|
||||||
@@ -209,11 +221,12 @@ Config:
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Output keys: `prompts`, `responses`, `masks`, `rewards` (float32)
|
Output keys: `prompts`, `prompts_mask`, `responses`, `masks`, `rewards` (float32)
|
||||||
|
|
||||||
- `action: "value"` — extract raw values from JSONL without tokenisation
|
- `action: "value"` — extract raw values from JSONL without tokenisation
|
||||||
- `list_field: true` — tokenise each list element independently, then concatenate
|
- `list_field: true` — tokenise each list element independently, then concatenate
|
||||||
- `mask_key: "masks"` — rename the auto-generated mask key (default: `responses_mask`)
|
- `mask_key: "masks"` — rename the auto-generated mask key (default: `responses_mask`)
|
||||||
|
- `prompts_mask` is auto-generated (all masked) and unused by GRPOStrategy
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -255,7 +268,7 @@ When `sources` is set, `sections` is ignored.
|
|||||||
| `storage_format` | str | `"bin"` | `"bin"` (mmap) or `"h5"` |
|
| `storage_format` | str | `"bin"` | `"bin"` (mmap) or `"h5"` |
|
||||||
| `max_tokens_per_shard` | int | `100000000` | Flush threshold in cumulative tokens |
|
| `max_tokens_per_shard` | int | `100000000` | Flush threshold in cumulative tokens |
|
||||||
| `dtype` | dict[str, str] | `{}` | Per-key tensor dtype override (e.g. `{"loss_mask": "bool"}`) |
|
| `dtype` | dict[str, str] | `{}` | Per-key tensor dtype override (e.g. `{"loss_mask": "bool"}`) |
|
||||||
| `position_ids_mode` | str | `"none"` | How to compute position_ids: `"none"`, `"doc_reset"`, `"continuous"` |
|
| `position_ids_mode` | str | `"doc_reset"` | How to compute position_ids: `"none"`, `"doc_reset"`, `"continuous"` |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -263,12 +276,11 @@ When `sources` is set, `sections` is ignored.
|
|||||||
|
|
||||||
### Template mode (`template: true`)
|
### Template mode (`template: true`)
|
||||||
|
|
||||||
For each message in the field's array:
|
|
||||||
|
|
||||||
1. Prepend BOS token (masked)
|
1. Prepend BOS token (masked)
|
||||||
2. Render through `chat_template` for that single message
|
2. For each message in the field's array:
|
||||||
3. Encode rendered text
|
1. Render through `chat_template` for that single message
|
||||||
4. Apply mask rule for the message's role
|
2. Encode rendered text
|
||||||
|
3. Apply mask rule for the message's role
|
||||||
|
|
||||||
### Non-template mode
|
### Non-template mode
|
||||||
|
|
||||||
@@ -276,7 +288,7 @@ Encode the field value as text. Mask value is 1 (train) or 0 (mask) per the sect
|
|||||||
|
|
||||||
### Text config detection
|
### Text config detection
|
||||||
|
|
||||||
When no section uses `template` and all sections have `action: "train"`, the builder skips mask generation entirely — all tokens are trained.
|
When no section uses `template` and all sections have `action: "train"`, the builder omits `loss_mask` from the output — all tokens are trained.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -287,10 +299,12 @@ When no section uses `template` and all sections have `action: "train"`, the bui
|
|||||||
```
|
```
|
||||||
output/
|
output/
|
||||||
__default__/
|
__default__/
|
||||||
|
shard_0000/
|
||||||
meta.json
|
meta.json
|
||||||
sequence.bin
|
sequence.bin
|
||||||
loss_mask.bin
|
loss_mask.bin
|
||||||
wiki/
|
wiki/
|
||||||
|
shard_0000/
|
||||||
meta.json
|
meta.json
|
||||||
sequence.bin
|
sequence.bin
|
||||||
loss_mask.bin
|
loss_mask.bin
|
||||||
@@ -313,7 +327,7 @@ output/
|
|||||||
loss_mask.bin
|
loss_mask.bin
|
||||||
```
|
```
|
||||||
|
|
||||||
`MmapStore` discovers all shards under the domain directory via `rglob("meta.json")`.
|
For `bin` format, `MmapStore` discovers all shards under the domain directory via `rglob("meta.json")`. For `h5` format, `H5Store` discovers `.h5`/`.hdf5` files via recursive glob.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -338,7 +352,7 @@ python scripts/tools/preprocess.py data/grpo/*.jsonl -o output/grpo/ -c configs/
|
|||||||
from astrai.preprocessing.pipeline import Pipeline
|
from astrai.preprocessing.pipeline import Pipeline
|
||||||
from astrai.config.preprocess_config import PipelineConfig
|
from astrai.config.preprocess_config import PipelineConfig
|
||||||
|
|
||||||
config = PipelineConfig.from_json("sft.json")
|
config = PipelineConfig.from_file("sft.json")
|
||||||
Pipeline(
|
Pipeline(
|
||||||
config,
|
config,
|
||||||
["data_part1.jsonl", "data_part2.jsonl"],
|
["data_part1.jsonl", "data_part2.jsonl"],
|
||||||
|
|||||||
+22
-6
@@ -1,5 +1,18 @@
|
|||||||
# Training
|
# Training
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
- [Autoregression](#autoregression)
|
||||||
|
- [Causal Mask](#causal-mask)
|
||||||
|
- [Rotary Position Embedding (RoPE)](#rotary-position-embedding-rope)
|
||||||
|
- [Training Loop](#training-loop)
|
||||||
|
- [Strategies](#strategies) — SEQ, SFT, DPO, GRPO
|
||||||
|
- [LR Schedulers](#lr-schedulers)
|
||||||
|
- [Gradient Checkpointing](#gradient-checkpointing)
|
||||||
|
- [Checkpoint](#checkpoint)
|
||||||
|
- [TrainContextBuilder](#traincontextbuilder-builder-pattern)
|
||||||
|
- [Training CLI](#training-cli)
|
||||||
|
|
||||||
### Autoregression
|
### Autoregression
|
||||||
|
|
||||||
Given a token sequence, the model predicts the probability of the next token. Each generated token is appended to the input and fed back, repeating until an end-of-sequence token or max length.
|
Given a token sequence, the model predicts the probability of the next token. Each generated token is appended to the input and fed back, repeating until an end-of-sequence token or max length.
|
||||||
@@ -45,7 +58,9 @@ on_train_begin
|
|||||||
context.loss = loss.item()
|
context.loss = loss.item()
|
||||||
stand_loss = loss / executor.grad_accum_steps
|
stand_loss = loss / executor.grad_accum_steps
|
||||||
executor.backward(stand_loss)
|
executor.backward(stand_loss)
|
||||||
context.iteration += 1
|
context.consumed_samples += (
|
||||||
|
context.config.batch_per_device * context.world_size
|
||||||
|
)
|
||||||
on_batch_end
|
on_batch_end
|
||||||
|
|
||||||
if executor.sync_gradients:
|
if executor.sync_gradients:
|
||||||
@@ -65,13 +80,13 @@ on_train_end
|
|||||||
| `on_train_begin` | Before training starts | `GradientCheckpointingCallback` |
|
| `on_train_begin` | Before training starts | `GradientCheckpointingCallback` |
|
||||||
| `on_epoch_begin` | Start of each epoch | `ProgressBarCallback` |
|
| `on_epoch_begin` | Start of each epoch | `ProgressBarCallback` |
|
||||||
| `on_batch_begin` | Every batch | — |
|
| `on_batch_begin` | Every batch | — |
|
||||||
| `on_optimizer_step` | Every accumulation window | `GradientClippingCallback`, `ValidationCallback` |
|
| `on_optimizer_step` | Every accumulation window | `GradientClippingCallback`, `MetricLoggerCallback`, `ValidationCallback` |
|
||||||
| `on_batch_end` | Every batch | `CheckpointCallback`, `MetricLoggerCallback`, `ProgressBarCallback` |
|
| `on_batch_end` | Every batch | `CheckpointCallback`, `MetricLoggerCallback`, `ProgressBarCallback` |
|
||||||
| `on_epoch_end` | End of each epoch | `ProgressBarCallback` |
|
| `on_epoch_end` | End of each epoch | `ProgressBarCallback` |
|
||||||
| `on_error` | On exception during training | `CheckpointCallback`, `MetricLoggerCallback` |
|
| `on_error` | On exception during training | `CheckpointCallback`, `MetricLoggerCallback` |
|
||||||
| `on_train_end` | Training ends (always via finally) | `CheckpointCallback`, `MetricLoggerCallback`, `GradientCheckpointingCallback` |
|
| `on_train_end` | Training ends (always via finally) | `CheckpointCallback`, `MetricLoggerCallback`, `GradientCheckpointingCallback` |
|
||||||
|
|
||||||
Default callbacks (in order): `gradient_checkpointing` (activation checkpointing, optional), `checkpoint` (safetensors, rank-0), `metric_logger` (JSONL, rank-0), `progress_bar` (tqdm), `gradient_clipping`, `validation` (periodic validation on val_dataset).
|
Default callbacks (in order): `gradient_checkpointing` (activation checkpointing, optional), `checkpoint` (safetensors, rank-0), `validation` (periodic validation on val_dataset), `metric_logger` (JSONL, rank-0), `progress_bar` (tqdm), `gradient_clipping`.
|
||||||
|
|
||||||
## Strategies
|
## Strategies
|
||||||
|
|
||||||
@@ -127,8 +142,9 @@ Keys: `prompts`, `responses`, `masks`, `rewards`.
|
|||||||
|------|-------|-------------|
|
|------|-------|-------------|
|
||||||
| Cosine | `CosineScheduler` | Linear warmup → cosine decay to `min_rate` |
|
| Cosine | `CosineScheduler` | Linear warmup → cosine decay to `min_rate` |
|
||||||
| SGDR | `SGDRScheduler` | Cosine annealing with warm restarts (`t_mult=2`) |
|
| SGDR | `SGDRScheduler` | Cosine annealing with warm restarts (`t_mult=2`) |
|
||||||
|
| WSD | `WSDScheduler` | Warmup-Stable-Decay with sqrt cooldown |
|
||||||
|
|
||||||
Created by `SchedulerFactory.create(optimizer, schedule_type, **kwargs)`. Valid types: `"cosine"`, `"sgdr"`. Omit to use no scheduler.
|
Created by `SchedulerFactory.create(schedule_type, optimizer, **kwargs)`. Valid types: `"cosine"`, `"sgdr"`, `"wsd"`. Omit to use no scheduler.
|
||||||
|
|
||||||
## Gradient Checkpointing
|
## Gradient Checkpointing
|
||||||
|
|
||||||
@@ -144,8 +160,8 @@ Callback wraps each `DecoderBlock.forward` with `torch.utils.checkpoint.checkpoi
|
|||||||
## Checkpoint
|
## Checkpoint
|
||||||
|
|
||||||
```
|
```
|
||||||
Checkpoint(state_dict, epoch, iteration, extra, meta, config)
|
Checkpoint(state_dict, epoch, consumed_samples, extra, meta, config)
|
||||||
├── save(save_dir) rank-0 only: meta.json (epoch/iteration/timestamp) + config.json (model config) + model.safetensors + optional {key}.pt (optimizer.pt, scheduler.pt)
|
├── save(save_dir) rank-0 only: meta.json (epoch/consumed_samples/timestamp) + config.json (model config) + model.safetensors + optional {key}.pt (optimizer.pt, scheduler.pt)
|
||||||
└── load(save_dir, broadcast=False) loads from local disk; set broadcast=True to broadcast metadata from rank-0
|
└── load(save_dir, broadcast=False) loads from local disk; set broadcast=True to broadcast metadata from rank-0
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
+77
-13
@@ -1,34 +1,98 @@
|
|||||||
__version__ = "1.3.7"
|
__version__ = "1.3.8"
|
||||||
__author__ = "ViperEkura"
|
__author__ = "ViperEkura"
|
||||||
|
|
||||||
from astrai.config import (
|
from astrai.config import (
|
||||||
AutoRegressiveLMConfig,
|
AutoRegressiveLMConfig,
|
||||||
|
BaseModelConfig,
|
||||||
|
ConfigFactory,
|
||||||
EncoderConfig,
|
EncoderConfig,
|
||||||
|
PipelineConfig,
|
||||||
TrainConfig,
|
TrainConfig,
|
||||||
)
|
)
|
||||||
from astrai.dataset import DatasetFactory
|
from astrai.dataset import (
|
||||||
|
BaseDataset,
|
||||||
|
DatasetFactory,
|
||||||
|
ResumableDistributedSampler,
|
||||||
|
Store,
|
||||||
|
StoreFactory,
|
||||||
|
)
|
||||||
from astrai.factory import BaseFactory
|
from astrai.factory import BaseFactory
|
||||||
from astrai.inference import (
|
from astrai.inference import (
|
||||||
GenerationRequest,
|
GenerationRequest,
|
||||||
InferenceEngine,
|
InferenceEngine,
|
||||||
|
ProtocolHandler,
|
||||||
|
SamplingPipeline,
|
||||||
|
get_app,
|
||||||
|
run_server,
|
||||||
|
sample,
|
||||||
|
)
|
||||||
|
from astrai.model import (
|
||||||
|
AutoModel,
|
||||||
|
AutoRegressiveLM,
|
||||||
|
EmbeddingEncoder,
|
||||||
|
LoRAConfig,
|
||||||
|
inject_lora,
|
||||||
|
)
|
||||||
|
from astrai.parallel import (
|
||||||
|
ExecutorFactory,
|
||||||
|
get_rank,
|
||||||
|
get_world_size,
|
||||||
|
only_on_rank,
|
||||||
|
spawn_parallel_fn,
|
||||||
|
)
|
||||||
|
from astrai.preprocessing import Pipeline, filter_by_length
|
||||||
|
from astrai.serialization import Checkpoint
|
||||||
|
from astrai.tokenize import AutoTokenizer, ChatTemplate
|
||||||
|
from astrai.trainer import (
|
||||||
|
BaseScheduler,
|
||||||
|
BaseStrategy,
|
||||||
|
CallbackFactory,
|
||||||
|
SchedulerFactory,
|
||||||
|
StrategyFactory,
|
||||||
|
TrainCallback,
|
||||||
|
Trainer,
|
||||||
)
|
)
|
||||||
from astrai.model import AutoModel, AutoRegressiveLM
|
|
||||||
from astrai.tokenize import AutoTokenizer
|
|
||||||
from astrai.trainer import CallbackFactory, SchedulerFactory, StrategyFactory, Trainer
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"AutoRegressiveLM",
|
"AutoRegressiveLM",
|
||||||
"AutoRegressiveLMConfig",
|
"AutoRegressiveLMConfig",
|
||||||
"EncoderConfig",
|
"AutoModel",
|
||||||
"TrainConfig",
|
|
||||||
"DatasetFactory",
|
|
||||||
"AutoTokenizer",
|
"AutoTokenizer",
|
||||||
|
"BaseDataset",
|
||||||
|
"BaseFactory",
|
||||||
|
"BaseModelConfig",
|
||||||
|
"BaseScheduler",
|
||||||
|
"BaseStrategy",
|
||||||
|
"CallbackFactory",
|
||||||
|
"ChatTemplate",
|
||||||
|
"Checkpoint",
|
||||||
|
"ConfigFactory",
|
||||||
|
"DatasetFactory",
|
||||||
|
"EmbeddingEncoder",
|
||||||
|
"EncoderConfig",
|
||||||
|
"ExecutorFactory",
|
||||||
"GenerationRequest",
|
"GenerationRequest",
|
||||||
"InferenceEngine",
|
"InferenceEngine",
|
||||||
"Trainer",
|
"LoRAConfig",
|
||||||
"CallbackFactory",
|
"Pipeline",
|
||||||
"StrategyFactory",
|
"PipelineConfig",
|
||||||
|
"ProtocolHandler",
|
||||||
|
"ResumableDistributedSampler",
|
||||||
|
"SamplingPipeline",
|
||||||
"SchedulerFactory",
|
"SchedulerFactory",
|
||||||
"BaseFactory",
|
"Store",
|
||||||
"AutoModel",
|
"StoreFactory",
|
||||||
|
"StrategyFactory",
|
||||||
|
"TrainCallback",
|
||||||
|
"TrainConfig",
|
||||||
|
"Trainer",
|
||||||
|
"filter_by_length",
|
||||||
|
"get_app",
|
||||||
|
"get_rank",
|
||||||
|
"get_world_size",
|
||||||
|
"inject_lora",
|
||||||
|
"only_on_rank",
|
||||||
|
"run_server",
|
||||||
|
"sample",
|
||||||
|
"spawn_parallel_fn",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ class BaseModelConfig(BaseConfig):
|
|||||||
"""Base config with ``model_type`` dispatch and file I/O."""
|
"""Base config with ``model_type`` dispatch and file I/O."""
|
||||||
|
|
||||||
model_type: Optional[str] = None
|
model_type: Optional[str] = None
|
||||||
|
neftune_alpha: float = 0.0
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -70,10 +71,12 @@ class EncoderConfig(BaseModelConfig):
|
|||||||
rope_theta: Optional[float] = None
|
rope_theta: Optional[float] = None
|
||||||
rope_scaling: Optional[dict] = None
|
rope_scaling: Optional[dict] = None
|
||||||
|
|
||||||
|
attn_type: str = "gqa"
|
||||||
n_heads: Optional[int] = None
|
n_heads: Optional[int] = None
|
||||||
n_kv_heads: Optional[int] = None
|
n_kv_heads: Optional[int] = None
|
||||||
use_qk_norm: Optional[bool] = None
|
use_qk_norm: Optional[bool] = None
|
||||||
use_gated_attention: Optional[bool] = None
|
use_gated_attention: Optional[bool] = None
|
||||||
|
|
||||||
|
ffn_type: str = "mlp"
|
||||||
pooling_type: Optional[str] = None
|
pooling_type: Optional[str] = None
|
||||||
normalize_embeddings: Optional[bool] = None
|
normalize_embeddings: Optional[bool] = None
|
||||||
|
|||||||
@@ -96,7 +96,7 @@ class OutputConfig(BaseConfig):
|
|||||||
storage_format: str = "bin"
|
storage_format: str = "bin"
|
||||||
max_tokens_per_shard: int = 100_000_000
|
max_tokens_per_shard: int = 100_000_000
|
||||||
dtype: Dict[str, str] = field(default_factory=dict)
|
dtype: Dict[str, str] = field(default_factory=dict)
|
||||||
position_ids_mode: str = "none"
|
position_ids_mode: str = "doc_reset"
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
|
|||||||
@@ -47,14 +47,18 @@ class TrainConfig(BaseConfig):
|
|||||||
|
|
||||||
# checkpoint setting
|
# checkpoint setting
|
||||||
start_epoch: int = field(default=0, metadata={"help": "Start epoch for training."})
|
start_epoch: int = field(default=0, metadata={"help": "Start epoch for training."})
|
||||||
start_batch: int = field(
|
start_samples: int = field(
|
||||||
default=0, metadata={"help": "Start batch iteration for training."}
|
default=0,
|
||||||
|
metadata={
|
||||||
|
"help": "Start samples count (per rank). Superseded by checkpoint consumed_samples."
|
||||||
|
},
|
||||||
)
|
)
|
||||||
ckpt_dir: str = field(
|
ckpt_dir: str = field(
|
||||||
default="./checkpoint", metadata={"help": "Checkpoint directory."}
|
default="./checkpoint", metadata={"help": "Checkpoint directory."}
|
||||||
)
|
)
|
||||||
ckpt_interval: int = field(
|
ckpt_interval: int = field(
|
||||||
default=5000, metadata={"help": "Number of iterations between checkpoints."}
|
default=5000,
|
||||||
|
metadata={"help": "Number of optimizer steps between checkpoints."},
|
||||||
)
|
)
|
||||||
|
|
||||||
# lora setting
|
# lora setting
|
||||||
@@ -67,12 +71,8 @@ class TrainConfig(BaseConfig):
|
|||||||
log_dir: str = field(
|
log_dir: str = field(
|
||||||
default="./checkpoint/logs", metadata={"help": "Directory for metric logs."}
|
default="./checkpoint/logs", metadata={"help": "Directory for metric logs."}
|
||||||
)
|
)
|
||||||
log_interval: int = field(
|
|
||||||
default=100,
|
|
||||||
metadata={"help": "Number of batch iterations between metric logs."},
|
|
||||||
)
|
|
||||||
metrics: List[str] = field(
|
metrics: List[str] = field(
|
||||||
default_factory=lambda: ["loss", "lr"],
|
default_factory=lambda: ["loss", "lr", "grad_norm"],
|
||||||
metadata={"help": "Metrics to record during training."},
|
metadata={"help": "Metrics to record during training."},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -5,10 +5,13 @@ from astrai.dataset.dataset import (
|
|||||||
from astrai.dataset.sampler import ResumableDistributedSampler
|
from astrai.dataset.sampler import ResumableDistributedSampler
|
||||||
from astrai.dataset.storage import (
|
from astrai.dataset.storage import (
|
||||||
H5Store,
|
H5Store,
|
||||||
|
JsonlStore,
|
||||||
MmapStore,
|
MmapStore,
|
||||||
Store,
|
Store,
|
||||||
StoreFactory,
|
StoreFactory,
|
||||||
detect_format,
|
detect_format,
|
||||||
|
)
|
||||||
|
from astrai.serialization import (
|
||||||
load_bin,
|
load_bin,
|
||||||
load_h5,
|
load_h5,
|
||||||
save_bin,
|
save_bin,
|
||||||
@@ -22,6 +25,7 @@ __all__ = [
|
|||||||
"StoreFactory",
|
"StoreFactory",
|
||||||
"H5Store",
|
"H5Store",
|
||||||
"MmapStore",
|
"MmapStore",
|
||||||
|
"JsonlStore",
|
||||||
"detect_format",
|
"detect_format",
|
||||||
"save_h5",
|
"save_h5",
|
||||||
"load_h5",
|
"load_h5",
|
||||||
|
|||||||
@@ -48,24 +48,26 @@ class BaseDataset(Dataset, ABC):
|
|||||||
f"Missing: {missing}"
|
f"Missing: {missing}"
|
||||||
)
|
)
|
||||||
|
|
||||||
def load(self, load_path: str, storage_type: Optional[str] = None):
|
def load(self, load_path: str, storage_type: Optional[str] = None, **kwargs):
|
||||||
"""Load dataset from the given path.
|
"""Load dataset from the given path.
|
||||||
|
|
||||||
Auto-detects the storage format if not specified.
|
Auto-detects the storage format if not specified.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
load_path: Path to the data directory or file
|
load_path: Path to the data directory or file
|
||||||
storage_type: Force a specific storage type ("h5", "bin"),
|
storage_type: Force a specific storage type ("h5", "bin", "jsonl"),
|
||||||
or None for auto-detection
|
or None for auto-detection
|
||||||
|
**kwargs: Extra arguments forwarded to the store constructor and
|
||||||
|
to ``store.load()``.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
KeyError: If the loaded storage is missing required keys.
|
KeyError: If the loaded storage is missing required keys.
|
||||||
"""
|
"""
|
||||||
if storage_type is None:
|
if storage_type is None:
|
||||||
storage_type = detect_format(load_path)
|
storage_type = detect_format(load_path)
|
||||||
self.storage = StoreFactory.create(storage_type)
|
self.storage = StoreFactory.create(storage_type, **kwargs)
|
||||||
self._load_path = load_path
|
self._load_path = load_path
|
||||||
self.storage.load(load_path)
|
self.storage.load(load_path, **kwargs)
|
||||||
self._validate_keys()
|
self._validate_keys()
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@@ -144,6 +146,7 @@ class DatasetFactory(BaseFactory["BaseDataset"]):
|
|||||||
window_size: int,
|
window_size: int,
|
||||||
stride: Optional[int] = None,
|
stride: Optional[int] = None,
|
||||||
storage_type: Optional[str] = None,
|
storage_type: Optional[str] = None,
|
||||||
|
**kwargs,
|
||||||
) -> "BaseDataset":
|
) -> "BaseDataset":
|
||||||
"""Create and load a dataset in one step.
|
"""Create and load a dataset in one step.
|
||||||
|
|
||||||
@@ -152,7 +155,8 @@ class DatasetFactory(BaseFactory["BaseDataset"]):
|
|||||||
load_path: Path to the data file
|
load_path: Path to the data file
|
||||||
window_size: Window size for data sampling
|
window_size: Window size for data sampling
|
||||||
stride: Stride between consecutive samples (default: same as window_size)
|
stride: Stride between consecutive samples (default: same as window_size)
|
||||||
storage_type: Storage type ("h5", "bin") or None for auto-detection
|
storage_type: Storage type ("h5", "bin", "jsonl") or None for auto-detection
|
||||||
|
**kwargs: Extra arguments forwarded to ``dataset.load()``.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Loaded dataset instance
|
Loaded dataset instance
|
||||||
@@ -161,7 +165,7 @@ class DatasetFactory(BaseFactory["BaseDataset"]):
|
|||||||
stride = window_size
|
stride = window_size
|
||||||
|
|
||||||
dataset = cls.create(train_type, window_size, stride)
|
dataset = cls.create(train_type, window_size, stride)
|
||||||
dataset.load(load_path, storage_type=storage_type)
|
dataset.load(load_path, storage_type=storage_type, **kwargs)
|
||||||
|
|
||||||
return dataset
|
return dataset
|
||||||
|
|
||||||
|
|||||||
@@ -74,6 +74,7 @@ class ResumableDistributedSampler(Sampler[int]):
|
|||||||
|
|
||||||
self.epoch += 1
|
self.epoch += 1
|
||||||
self._indices = None
|
self._indices = None
|
||||||
|
self.iter = self.iter % self.num_samples_per_replica
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def _remaining(self):
|
def _remaining(self):
|
||||||
|
|||||||
+111
-65
@@ -20,79 +20,25 @@ Key properties:
|
|||||||
import bisect
|
import bisect
|
||||||
import glob
|
import glob
|
||||||
import json
|
import json
|
||||||
import os
|
import logging
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Dict, List, Union
|
from typing import Dict, List, Union
|
||||||
|
|
||||||
import h5py
|
|
||||||
import numpy as np
|
|
||||||
import torch
|
import torch
|
||||||
from torch import Tensor
|
from torch import Tensor
|
||||||
|
|
||||||
|
from astrai.config.preprocess_config import PipelineConfig
|
||||||
from astrai.factory import BaseFactory
|
from astrai.factory import BaseFactory
|
||||||
|
from astrai.preprocessing.builder import MaskBuilderFactory
|
||||||
|
from astrai.preprocessing.position_id import PositionIdStrategyFactory
|
||||||
def save_h5(file_path: str, file_name: str, tensor_group: Dict[str, List[Tensor]]):
|
from astrai.serialization import (
|
||||||
os.makedirs(file_path, exist_ok=True)
|
load_bin,
|
||||||
full_file_path = os.path.join(file_path, f"{file_name}.h5")
|
load_h5,
|
||||||
with h5py.File(full_file_path, "w") as f:
|
|
||||||
for key, tensors in tensor_group.items():
|
|
||||||
grp = f.create_group(key)
|
|
||||||
for idx, tensor in enumerate(tensors):
|
|
||||||
arr = tensor.cpu().numpy()
|
|
||||||
grp.create_dataset(f"data_{idx}", data=arr)
|
|
||||||
|
|
||||||
|
|
||||||
def load_h5(file_path: str, share_memory=True) -> Dict[str, List[Tensor]]:
|
|
||||||
tensor_group: Dict[str, List[Tensor]] = {}
|
|
||||||
|
|
||||||
root_path = Path(file_path)
|
|
||||||
h5_files = list(root_path.rglob("*.h5")) + list(root_path.rglob("*.hdf5"))
|
|
||||||
|
|
||||||
for h5_file in h5_files:
|
|
||||||
with h5py.File(h5_file, "r") as f:
|
|
||||||
for key in f.keys():
|
|
||||||
grp = f[key]
|
|
||||||
dsets = []
|
|
||||||
for dset_name in grp.keys():
|
|
||||||
dset = grp[dset_name]
|
|
||||||
tensor = torch.from_numpy(dset[:])
|
|
||||||
if share_memory:
|
|
||||||
tensor = tensor.share_memory_()
|
|
||||||
dsets.append(tensor)
|
|
||||||
|
|
||||||
if tensor_group.get(key) is None:
|
|
||||||
tensor_group[key] = []
|
|
||||||
tensor_group[key].extend(dsets)
|
|
||||||
|
|
||||||
return tensor_group
|
|
||||||
|
|
||||||
|
|
||||||
def save_bin(file_path: str, tensor_group: Dict[str, List[Tensor]]):
|
|
||||||
os.makedirs(file_path, exist_ok=True)
|
|
||||||
meta = {}
|
|
||||||
for key, tensors in tensor_group.items():
|
|
||||||
cat = torch.cat(tensors, dim=0)
|
|
||||||
meta[key] = {"shape": list(cat.shape), "dtype": str(cat.dtype).split(".")[-1]}
|
|
||||||
np.asarray(cat.cpu().numpy()).tofile(os.path.join(file_path, f"{key}.bin"))
|
|
||||||
with open(os.path.join(file_path, "meta.json"), "w") as f:
|
|
||||||
json.dump(meta, f)
|
|
||||||
|
|
||||||
|
|
||||||
def load_bin(file_path: str) -> Dict[str, List[Tensor]]:
|
|
||||||
with open(os.path.join(file_path, "meta.json"), "r") as f:
|
|
||||||
meta = json.load(f)
|
|
||||||
segments: Dict[str, List[Tensor]] = {}
|
|
||||||
for key, info in meta.items():
|
|
||||||
arr = np.memmap(
|
|
||||||
os.path.join(file_path, f"{key}.bin"),
|
|
||||||
dtype=info["dtype"],
|
|
||||||
mode="r+",
|
|
||||||
shape=tuple(info["shape"]),
|
|
||||||
)
|
)
|
||||||
segments[key] = [torch.from_numpy(arr)]
|
from astrai.tokenize import AutoTokenizer
|
||||||
return segments
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def detect_format(load_path: str) -> str:
|
def detect_format(load_path: str) -> str:
|
||||||
@@ -102,7 +48,7 @@ def detect_format(load_path: str) -> str:
|
|||||||
load_path: Directory or file path
|
load_path: Directory or file path
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Format string ("h5" or "bin")
|
Format string ("h5", "bin", or "jsonl")
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
FileNotFoundError: If no supported data files are found
|
FileNotFoundError: If no supported data files are found
|
||||||
@@ -112,6 +58,8 @@ def detect_format(load_path: str) -> str:
|
|||||||
suffix = root.suffix.lower()
|
suffix = root.suffix.lower()
|
||||||
if suffix in (".h5", ".hdf5"):
|
if suffix in (".h5", ".hdf5"):
|
||||||
return "h5"
|
return "h5"
|
||||||
|
if suffix == ".jsonl":
|
||||||
|
return "jsonl"
|
||||||
raise ValueError(f"Unsupported file format: {suffix}")
|
raise ValueError(f"Unsupported file format: {suffix}")
|
||||||
|
|
||||||
h5_files = [
|
h5_files = [
|
||||||
@@ -128,6 +76,11 @@ def detect_format(load_path: str) -> str:
|
|||||||
) > 0
|
) > 0
|
||||||
if has_meta:
|
if has_meta:
|
||||||
return "bin"
|
return "bin"
|
||||||
|
jsonl_files = [
|
||||||
|
Path(p) for p in glob.glob(str(root / "**" / "*.jsonl"), recursive=True)
|
||||||
|
]
|
||||||
|
if jsonl_files:
|
||||||
|
return "jsonl"
|
||||||
raise FileNotFoundError(f"No supported data files found at {load_path}")
|
raise FileNotFoundError(f"No supported data files found at {load_path}")
|
||||||
|
|
||||||
|
|
||||||
@@ -264,3 +217,96 @@ class MmapStore(Store):
|
|||||||
self._normalize(all_raw)
|
self._normalize(all_raw)
|
||||||
for tensors in self._data.values():
|
for tensors in self._data.values():
|
||||||
self._mmap_refs.extend(tensors)
|
self._mmap_refs.extend(tensors)
|
||||||
|
|
||||||
|
|
||||||
|
@StoreFactory.register("jsonl")
|
||||||
|
class JsonlStore(Store):
|
||||||
|
"""On-the-fly tokenization store for raw JSONL files.
|
||||||
|
|
||||||
|
A JSONL dataset directory contains ``*.jsonl`` files plus a
|
||||||
|
``dataset_config.json`` file that follows the same schema as
|
||||||
|
:class:`PipelineConfig` with an additional ``tokenizer_path`` field.
|
||||||
|
Records are tokenized when the store is loaded and concatenated into
|
||||||
|
segmented tensors matching the key layout expected by the dataset
|
||||||
|
classes (``sequence``, ``loss_mask``, ``position_ids``, ...).
|
||||||
|
"""
|
||||||
|
|
||||||
|
CONFIG_NAME = "dataset_config.json"
|
||||||
|
|
||||||
|
def load(self, path: str):
|
||||||
|
root = Path(path)
|
||||||
|
config_path = root / self.CONFIG_NAME
|
||||||
|
if not config_path.exists():
|
||||||
|
raise FileNotFoundError(
|
||||||
|
f"JSONL dataset config not found: {config_path}. "
|
||||||
|
f"Expected {self.CONFIG_NAME} alongside *.jsonl files."
|
||||||
|
)
|
||||||
|
|
||||||
|
with open(config_path, "r", encoding="utf-8") as f:
|
||||||
|
raw_config = json.load(f)
|
||||||
|
|
||||||
|
tokenizer_path = raw_config.pop("tokenizer_path", None)
|
||||||
|
if tokenizer_path is None:
|
||||||
|
raise ValueError(
|
||||||
|
f"JSONL dataset config must specify 'tokenizer_path': {config_path}"
|
||||||
|
)
|
||||||
|
|
||||||
|
self.config = PipelineConfig.from_dict(raw_config)
|
||||||
|
tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
|
||||||
|
mask_builder = MaskBuilderFactory.create("sectioned")
|
||||||
|
position_strategy = PositionIdStrategyFactory.create(
|
||||||
|
self.config.output.position_ids_mode
|
||||||
|
)
|
||||||
|
|
||||||
|
raw: Dict[str, List[Tensor]] = {}
|
||||||
|
doc_sequences: List[List[int]] = []
|
||||||
|
|
||||||
|
for jsonl_path in sorted(root.glob("*.jsonl")):
|
||||||
|
with open(jsonl_path, "r", encoding="utf-8") as f:
|
||||||
|
for line in f:
|
||||||
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
item = json.loads(line)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
logger.warning(
|
||||||
|
"Failed to parse JSON line in %s, skipping", jsonl_path
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
result = mask_builder.build(item, self.config, tokenizer)
|
||||||
|
if result is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
result.pop("domain", None)
|
||||||
|
primary_ids = self._primary_ids(result)
|
||||||
|
if not primary_ids:
|
||||||
|
continue
|
||||||
|
|
||||||
|
doc_sequences.append(primary_ids)
|
||||||
|
for key, ids in result.items():
|
||||||
|
if key not in raw:
|
||||||
|
raw[key] = []
|
||||||
|
raw[key].append(torch.tensor(ids, dtype=self._infer_dtype(ids)))
|
||||||
|
|
||||||
|
pos_ids = position_strategy.generate(doc_sequences)
|
||||||
|
if pos_ids:
|
||||||
|
raw["position_ids"] = [torch.tensor(pos_ids, dtype=torch.int32)]
|
||||||
|
|
||||||
|
self._normalize(raw)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _primary_ids(result: dict) -> List[int]:
|
||||||
|
"""Return the first integer list in *result* as the primary id sequence."""
|
||||||
|
for val in result.values():
|
||||||
|
if isinstance(val, list) and val and isinstance(val[0], int):
|
||||||
|
return val
|
||||||
|
return []
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _infer_dtype(ids: List) -> torch.dtype:
|
||||||
|
"""Infer tensor dtype from the first element of a token/value list."""
|
||||||
|
if ids and isinstance(ids[0], float):
|
||||||
|
return torch.float32
|
||||||
|
return torch.int32
|
||||||
|
|||||||
+1
-2
@@ -4,7 +4,6 @@ import inspect
|
|||||||
import sys
|
import sys
|
||||||
from abc import ABC
|
from abc import ABC
|
||||||
from typing import (
|
from typing import (
|
||||||
Any,
|
|
||||||
Callable,
|
Callable,
|
||||||
Dict,
|
Dict,
|
||||||
ForwardRef,
|
ForwardRef,
|
||||||
@@ -38,7 +37,7 @@ def _resolve_type(
|
|||||||
ns = vars(mod)
|
ns = vars(mod)
|
||||||
|
|
||||||
if isinstance(arg, ForwardRef):
|
if isinstance(arg, ForwardRef):
|
||||||
return arg._evaluate(ns, None, frozenset(), recursive_guard=frozenset())
|
return arg._evaluate(ns, None, recursive_guard=frozenset())
|
||||||
|
|
||||||
return ns.get(name)
|
return ns.get(name)
|
||||||
|
|
||||||
|
|||||||
@@ -30,10 +30,14 @@ from astrai.inference.api.openai import OpenAIResponseBuilder
|
|||||||
from astrai.inference.core import (
|
from astrai.inference.core import (
|
||||||
STOP,
|
STOP,
|
||||||
Allocator,
|
Allocator,
|
||||||
|
CacheView,
|
||||||
|
ContiguousCache,
|
||||||
|
ContiguousCacheView,
|
||||||
Executor,
|
Executor,
|
||||||
InferenceScheduler,
|
InferenceScheduler,
|
||||||
KVCache,
|
KVCache,
|
||||||
KvcacheView,
|
PageCache,
|
||||||
|
PageCacheView,
|
||||||
PagePool,
|
PagePool,
|
||||||
PrefixCache,
|
PrefixCache,
|
||||||
Storage,
|
Storage,
|
||||||
@@ -63,8 +67,12 @@ __all__ = [
|
|||||||
"TaskManager",
|
"TaskManager",
|
||||||
"TaskStatus",
|
"TaskStatus",
|
||||||
"Allocator",
|
"Allocator",
|
||||||
|
"CacheView",
|
||||||
"KVCache",
|
"KVCache",
|
||||||
"KvcacheView",
|
"ContiguousCache",
|
||||||
|
"ContiguousCacheView",
|
||||||
|
"PageCache",
|
||||||
|
"PageCacheView",
|
||||||
"PagePool",
|
"PagePool",
|
||||||
"PrefixCache",
|
"PrefixCache",
|
||||||
"Storage",
|
"Storage",
|
||||||
|
|||||||
@@ -2,8 +2,12 @@
|
|||||||
|
|
||||||
from astrai.inference.core.cache import (
|
from astrai.inference.core.cache import (
|
||||||
Allocator,
|
Allocator,
|
||||||
|
CacheView,
|
||||||
|
ContiguousCache,
|
||||||
|
ContiguousCacheView,
|
||||||
KVCache,
|
KVCache,
|
||||||
KvcacheView,
|
PageCache,
|
||||||
|
PageCacheView,
|
||||||
PagePool,
|
PagePool,
|
||||||
PrefixCache,
|
PrefixCache,
|
||||||
Storage,
|
Storage,
|
||||||
@@ -16,8 +20,12 @@ from astrai.inference.core.task import STOP, Task, TaskManager, TaskStatus
|
|||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"Allocator",
|
"Allocator",
|
||||||
|
"CacheView",
|
||||||
"KVCache",
|
"KVCache",
|
||||||
"KvcacheView",
|
"ContiguousCache",
|
||||||
|
"ContiguousCacheView",
|
||||||
|
"PageCache",
|
||||||
|
"PageCacheView",
|
||||||
"PagePool",
|
"PagePool",
|
||||||
"PrefixCache",
|
"PrefixCache",
|
||||||
"Storage",
|
"Storage",
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import threading
|
import threading
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
from typing import Callable, Dict, List, Optional, Tuple
|
from typing import Callable, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
@@ -62,6 +63,7 @@ class Allocator:
|
|||||||
|
|
||||||
def touch(self, idx: int):
|
def touch(self, idx: int):
|
||||||
with self._lock:
|
with self._lock:
|
||||||
|
if idx in self._lru:
|
||||||
self._lru.move_to_end(idx)
|
self._lru.move_to_end(idx)
|
||||||
|
|
||||||
|
|
||||||
@@ -274,7 +276,42 @@ class Storage:
|
|||||||
return k, v
|
return k, v
|
||||||
|
|
||||||
|
|
||||||
class KvcacheView:
|
class CacheView(ABC):
|
||||||
|
"""Abstract view passed to attention layers for KV-cache I/O."""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def write(self, layer_id: int, k: Tensor, v: Tensor): ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def gather(self, layer_id: int) -> Tuple[Tensor, Tensor]: ...
|
||||||
|
|
||||||
|
|
||||||
|
class KVCache(ABC):
|
||||||
|
"""Abstract KV-cache facade for scheduler/executor."""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def task_alloc(self, task_id: str, prompt_ids: List[int]) -> bool: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def task_free(self, task_id: str): ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def task_extend(self, task_id: str, pos: int) -> bool: ...
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def bind_tasks(
|
||||||
|
self, task_ids: List[str], total_len: int, device: torch.device
|
||||||
|
) -> CacheView: ...
|
||||||
|
|
||||||
|
def task_cached(self, task_id: str) -> int:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
def task_record_hashes(
|
||||||
|
self, task_id: str, prompt_ids: List[int], start_logical_page: int = 0
|
||||||
|
): ...
|
||||||
|
|
||||||
|
|
||||||
|
class PageCacheView(CacheView):
|
||||||
"""Bundles Storage + page_table + total_len for attention layers."""
|
"""Bundles Storage + page_table + total_len for attention layers."""
|
||||||
|
|
||||||
def __init__(self, storage: Storage, page_table: Tensor, total_len: int = 0):
|
def __init__(self, storage: Storage, page_table: Tensor, total_len: int = 0):
|
||||||
@@ -290,8 +327,8 @@ class KvcacheView:
|
|||||||
return self._storage.gather(layer_id, self._page_table, self._total_len)
|
return self._storage.gather(layer_id, self._page_table, self._total_len)
|
||||||
|
|
||||||
|
|
||||||
class KVCache:
|
class PageCache(KVCache):
|
||||||
"""Facade: page management + KV-cache I/O for continuous batching."""
|
"""Paged KV-cache with prefix sharing."""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -361,8 +398,102 @@ class KVCache:
|
|||||||
for i in range(start_logical_page, full_pages):
|
for i in range(start_logical_page, full_pages):
|
||||||
self._pool.record(page_table[i], prompt_ids, i)
|
self._pool.record(page_table[i], prompt_ids, i)
|
||||||
|
|
||||||
def make_table_tensor(self, task_ids: List[str], device: torch.device) -> Tensor:
|
def bind_tasks(
|
||||||
return self._table.table_tensor(task_ids, device)
|
self, task_ids: List[str], total_len: int, device: torch.device
|
||||||
|
) -> PageCacheView:
|
||||||
|
page_table = self._table.table_tensor(task_ids, device)
|
||||||
|
return PageCacheView(self._storage, page_table, total_len)
|
||||||
|
|
||||||
def bind(self, page_table: Tensor, total_len: int = 0) -> KvcacheView:
|
|
||||||
return KvcacheView(self._storage, page_table, total_len)
|
class ContiguousCacheView(CacheView):
|
||||||
|
"""Contiguous KV-cache view for attention layers."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self, cache: "ContiguousCache", batch_indices: Tensor, total_len: int = 0
|
||||||
|
):
|
||||||
|
self._cache = cache
|
||||||
|
self._batch_indices = batch_indices
|
||||||
|
self._total_len = total_len
|
||||||
|
|
||||||
|
def write(self, layer_id: int, k: Tensor, v: Tensor):
|
||||||
|
seq_len = k.size(1)
|
||||||
|
start_pos = self._total_len - seq_len
|
||||||
|
indices = self._batch_indices
|
||||||
|
self._cache.k[layer_id, indices, start_pos : start_pos + seq_len] = k
|
||||||
|
self._cache.v[layer_id, indices, start_pos : start_pos + seq_len] = v
|
||||||
|
new_len = start_pos + seq_len
|
||||||
|
for s in indices.tolist():
|
||||||
|
cur = self._cache._slot_len.get(s, 0)
|
||||||
|
if new_len > cur:
|
||||||
|
self._cache._slot_len[s] = new_len
|
||||||
|
|
||||||
|
def gather(self, layer_id: int) -> Tuple[Tensor, Tensor]:
|
||||||
|
max_len = max(
|
||||||
|
self._cache._slot_len.get(int(s), 0) for s in self._batch_indices.tolist()
|
||||||
|
)
|
||||||
|
indices = self._batch_indices
|
||||||
|
k = self._cache.k[layer_id, indices, :max_len]
|
||||||
|
v = self._cache.v[layer_id, indices, :max_len]
|
||||||
|
return k, v
|
||||||
|
|
||||||
|
|
||||||
|
class ContiguousCache(KVCache):
|
||||||
|
"""Contiguous per-slot KV cache (default implementation)."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
n_layers: int,
|
||||||
|
max_batch_size: int,
|
||||||
|
max_seq_len: int,
|
||||||
|
n_kv_heads: int,
|
||||||
|
head_dim: int,
|
||||||
|
device: torch.device,
|
||||||
|
dtype: torch.dtype,
|
||||||
|
):
|
||||||
|
self.max_seq_len = max_seq_len
|
||||||
|
self.k = torch.zeros(
|
||||||
|
n_layers,
|
||||||
|
max_batch_size,
|
||||||
|
max_seq_len,
|
||||||
|
n_kv_heads,
|
||||||
|
head_dim,
|
||||||
|
device=device,
|
||||||
|
dtype=dtype,
|
||||||
|
)
|
||||||
|
self.v = torch.zeros(
|
||||||
|
n_layers,
|
||||||
|
max_batch_size,
|
||||||
|
max_seq_len,
|
||||||
|
n_kv_heads,
|
||||||
|
head_dim,
|
||||||
|
device=device,
|
||||||
|
dtype=dtype,
|
||||||
|
)
|
||||||
|
self._slot_len: Dict[int, int] = {}
|
||||||
|
self._task_slot: Dict[str, int] = {}
|
||||||
|
self._free_slots = list(range(max_batch_size))
|
||||||
|
self._device = device
|
||||||
|
|
||||||
|
def task_alloc(self, task_id: str, prompt_ids: List[int]) -> bool:
|
||||||
|
if not self._free_slots:
|
||||||
|
return False
|
||||||
|
slot = self._free_slots.pop(0)
|
||||||
|
self._task_slot[task_id] = slot
|
||||||
|
self._slot_len[slot] = 0
|
||||||
|
return True
|
||||||
|
|
||||||
|
def task_free(self, task_id: str):
|
||||||
|
slot = self._task_slot.pop(task_id, None)
|
||||||
|
if slot is not None:
|
||||||
|
self._slot_len.pop(slot, None)
|
||||||
|
self._free_slots.append(slot)
|
||||||
|
|
||||||
|
def task_extend(self, task_id: str, pos: int) -> bool:
|
||||||
|
return pos < self.max_seq_len
|
||||||
|
|
||||||
|
def bind_tasks(
|
||||||
|
self, task_ids: List[str], total_len: int, device: torch.device
|
||||||
|
) -> ContiguousCacheView:
|
||||||
|
slots = [self._task_slot[tid] for tid in task_ids]
|
||||||
|
batch_indices = torch.tensor(slots, dtype=torch.long, device=device)
|
||||||
|
return ContiguousCacheView(self, batch_indices, total_len)
|
||||||
|
|||||||
@@ -19,13 +19,13 @@ class Executor:
|
|||||||
self,
|
self,
|
||||||
model: AutoModel,
|
model: AutoModel,
|
||||||
tokenizer: AutoTokenizer,
|
tokenizer: AutoTokenizer,
|
||||||
page_cache: KVCache,
|
kv_cache: KVCache,
|
||||||
device: Optional[str] = None,
|
device: Optional[str] = None,
|
||||||
dtype: Optional[torch.dtype] = None,
|
dtype: Optional[torch.dtype] = None,
|
||||||
):
|
):
|
||||||
self.model = model
|
self.model = model
|
||||||
self.tokenizer = tokenizer
|
self.tokenizer = tokenizer
|
||||||
self.page_cache = page_cache
|
self.kv_cache = kv_cache
|
||||||
self.device = device or next(model.parameters()).device
|
self.device = device or next(model.parameters()).device
|
||||||
self.dtype = dtype or next(model.parameters()).dtype
|
self.dtype = dtype or next(model.parameters()).dtype
|
||||||
|
|
||||||
@@ -43,7 +43,6 @@ class Executor:
|
|||||||
)
|
)
|
||||||
|
|
||||||
task_ids = [t.task_id for t in tasks]
|
task_ids = [t.task_id for t in tasks]
|
||||||
page_tables = self.page_cache.make_table_tensor(task_ids, self.device)
|
|
||||||
|
|
||||||
with torch.inference_mode():
|
with torch.inference_mode():
|
||||||
self.model(
|
self.model(
|
||||||
@@ -53,7 +52,7 @@ class Executor:
|
|||||||
)
|
)
|
||||||
.unsqueeze(0)
|
.unsqueeze(0)
|
||||||
.expand(batch_sz, -1),
|
.expand(batch_sz, -1),
|
||||||
paged_cache=self.page_cache.bind(page_tables, total_len=prompt_len),
|
paged_cache=self.kv_cache.bind_tasks(task_ids, prompt_len, self.device),
|
||||||
)
|
)
|
||||||
|
|
||||||
def execute_decode(self, tasks: List[Task]) -> List[int]:
|
def execute_decode(self, tasks: List[Task]) -> List[int]:
|
||||||
@@ -72,7 +71,6 @@ class Executor:
|
|||||||
total_len = position_ids.max().item() + 1
|
total_len = position_ids.max().item() + 1
|
||||||
|
|
||||||
task_ids = [t.task_id for t in tasks]
|
task_ids = [t.task_id for t in tasks]
|
||||||
page_tables = self.page_cache.make_table_tensor(task_ids, self.device)
|
|
||||||
|
|
||||||
temperatures = torch.tensor([t.temperature for t in tasks], device=self.device)
|
temperatures = torch.tensor([t.temperature for t in tasks], device=self.device)
|
||||||
top_ks = torch.tensor([t.top_k for t in tasks], device=self.device)
|
top_ks = torch.tensor([t.top_k for t in tasks], device=self.device)
|
||||||
@@ -81,7 +79,7 @@ class Executor:
|
|||||||
with torch.inference_mode():
|
with torch.inference_mode():
|
||||||
outputs = self.model(
|
outputs = self.model(
|
||||||
input_ids.unsqueeze(1),
|
input_ids.unsqueeze(1),
|
||||||
paged_cache=self.page_cache.bind(page_tables, total_len=total_len),
|
paged_cache=self.kv_cache.bind_tasks(task_ids, total_len, self.device),
|
||||||
position_ids=position_ids.unsqueeze(1),
|
position_ids=position_ids.unsqueeze(1),
|
||||||
)
|
)
|
||||||
logits = outputs["logits"][:, -1, :]
|
logits = outputs["logits"][:, -1, :]
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from typing import Any, Dict, List, Optional, Tuple
|
|||||||
|
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
from astrai.inference.core.cache import KVCache
|
from astrai.inference.core.cache import ContiguousCache, KVCache
|
||||||
from astrai.inference.core.executor import Executor
|
from astrai.inference.core.executor import Executor
|
||||||
from astrai.inference.core.task import STOP, Task, TaskManager, TaskStatus
|
from astrai.inference.core.task import STOP, Task, TaskManager, TaskStatus
|
||||||
from astrai.model.automodel import AutoModel
|
from astrai.model.automodel import AutoModel
|
||||||
@@ -14,7 +14,7 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
|
|
||||||
class InferenceScheduler:
|
class InferenceScheduler:
|
||||||
"""Four-phase continuous batching loop: cleanup -> refill -> prefill -> decode."""
|
"""Continuous batching loop: cleanup -> refill -> prefill -> decode (all groups)."""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -23,9 +23,9 @@ class InferenceScheduler:
|
|||||||
max_batch_size: int = 16,
|
max_batch_size: int = 16,
|
||||||
max_seq_len: Optional[int] = None,
|
max_seq_len: Optional[int] = None,
|
||||||
max_prompt_len: int = 2048,
|
max_prompt_len: int = 2048,
|
||||||
page_size: int = 64,
|
|
||||||
device: Optional[str] = None,
|
device: Optional[str] = None,
|
||||||
dtype: Optional[torch.dtype] = None,
|
dtype: Optional[torch.dtype] = None,
|
||||||
|
cache: Optional[KVCache] = None,
|
||||||
):
|
):
|
||||||
config = model.config
|
config = model.config
|
||||||
|
|
||||||
@@ -41,16 +41,17 @@ class InferenceScheduler:
|
|||||||
self.device = device or next(model.parameters()).device
|
self.device = device or next(model.parameters()).device
|
||||||
self.dtype = dtype or next(model.parameters()).dtype
|
self.dtype = dtype or next(model.parameters()).dtype
|
||||||
|
|
||||||
n_pages = (
|
head_dim = config.dim // config.n_heads
|
||||||
max_batch_size * (self.max_seq_len + page_size) + page_size - 1
|
|
||||||
) // page_size
|
|
||||||
|
|
||||||
self._page_cache = KVCache(
|
if cache is not None:
|
||||||
|
self._cache = cache
|
||||||
|
else:
|
||||||
|
self._cache = ContiguousCache(
|
||||||
config.n_layers,
|
config.n_layers,
|
||||||
n_pages,
|
max_batch_size,
|
||||||
page_size,
|
self.max_seq_len,
|
||||||
config.n_kv_heads,
|
config.n_kv_heads,
|
||||||
config.dim // config.n_heads,
|
head_dim,
|
||||||
self.device,
|
self.device,
|
||||||
self.dtype,
|
self.dtype,
|
||||||
)
|
)
|
||||||
@@ -65,31 +66,32 @@ class InferenceScheduler:
|
|||||||
self._executor = Executor(
|
self._executor = Executor(
|
||||||
model=model,
|
model=model,
|
||||||
tokenizer=tokenizer,
|
tokenizer=tokenizer,
|
||||||
page_cache=self._page_cache,
|
kv_cache=self._cache,
|
||||||
device=self.device,
|
device=self.device,
|
||||||
dtype=self.dtype,
|
dtype=self.dtype,
|
||||||
)
|
)
|
||||||
|
|
||||||
self._running = False
|
self._stop_event = threading.Event()
|
||||||
self._fatal_error: Optional[Exception] = None
|
self._loop_thread: Optional[threading.Thread] = None
|
||||||
|
|
||||||
def add_task(self, prompt: str, **kwargs) -> str:
|
def add_task(self, prompt: str, **kwargs) -> str:
|
||||||
return self._task_mgr.add_task(prompt, **kwargs)
|
return self._task_mgr.add_task(prompt, **kwargs)
|
||||||
|
|
||||||
def remove_task(self, task_id: str):
|
def remove_task(self, task_id: str):
|
||||||
for task in self._task_mgr.remove_task(task_id):
|
for task in self._task_mgr.remove_task(task_id):
|
||||||
self._page_cache.task_free(task.task_id)
|
self._cache.task_free(task.task_id)
|
||||||
|
|
||||||
def get_stats(self) -> Dict[str, Any]:
|
def get_stats(self) -> Dict[str, Any]:
|
||||||
return self._task_mgr.get_stats()
|
return self._task_mgr.get_stats()
|
||||||
|
|
||||||
def _run_generation_loop(self):
|
def _run_generation_loop(self):
|
||||||
stop_ids = self._task_mgr.tokenizer.stop_ids
|
stop_ids = self._task_mgr.tokenizer.stop_ids
|
||||||
|
cache = self._cache
|
||||||
try:
|
try:
|
||||||
while self._running:
|
while not self._stop_event.is_set():
|
||||||
finished = self._task_mgr.remove_finished_tasks(stop_ids)
|
finished = self._task_mgr.remove_finished_tasks(stop_ids)
|
||||||
for task in finished:
|
for task in finished:
|
||||||
self._page_cache.task_free(task.task_id)
|
cache.task_free(task.task_id)
|
||||||
|
|
||||||
active = self._task_mgr.get_active_tasks()
|
active = self._task_mgr.get_active_tasks()
|
||||||
available = self._task_mgr.max_batch_size - len(active)
|
available = self._task_mgr.max_batch_size - len(active)
|
||||||
@@ -97,7 +99,7 @@ class InferenceScheduler:
|
|||||||
candidates = self._task_mgr.pull_candidates(available)
|
candidates = self._task_mgr.pull_candidates(available)
|
||||||
failed = []
|
failed = []
|
||||||
for task in candidates:
|
for task in candidates:
|
||||||
if self._page_cache.task_alloc(task.task_id, task.prompt_ids):
|
if cache.task_alloc(task.task_id, task.prompt_ids):
|
||||||
self._task_mgr.activate(task)
|
self._task_mgr.activate(task)
|
||||||
else:
|
else:
|
||||||
failed.append(task)
|
failed.append(task)
|
||||||
@@ -112,7 +114,7 @@ class InferenceScheduler:
|
|||||||
t
|
t
|
||||||
for t in self._task_mgr.get_active_tasks()
|
for t in self._task_mgr.get_active_tasks()
|
||||||
if t.output_tokens == 0
|
if t.output_tokens == 0
|
||||||
and self._page_cache.task_cached(t.task_id) < len(t.prompt_ids)
|
and cache.task_cached(t.task_id) < len(t.prompt_ids)
|
||||||
]
|
]
|
||||||
if to_prefill:
|
if to_prefill:
|
||||||
for t in to_prefill:
|
for t in to_prefill:
|
||||||
@@ -122,36 +124,34 @@ class InferenceScheduler:
|
|||||||
for t in to_prefill:
|
for t in to_prefill:
|
||||||
key = (
|
key = (
|
||||||
len(t.prompt_ids),
|
len(t.prompt_ids),
|
||||||
self._page_cache.task_cached(t.task_id),
|
cache.task_cached(t.task_id),
|
||||||
)
|
)
|
||||||
groups.setdefault(key, []).append(t)
|
groups.setdefault(key, []).append(t)
|
||||||
|
|
||||||
for (prompt_len, start_pos), group in groups.items():
|
for (prompt_len, start_pos), group in groups.items():
|
||||||
self._executor.execute_prefill(group, prompt_len, start_pos)
|
self._executor.execute_prefill(group, prompt_len, start_pos)
|
||||||
start_logical_page = start_pos // self._page_cache.page_size
|
start_logical_page = start_pos // getattr(
|
||||||
|
cache, "page_size", 64
|
||||||
|
)
|
||||||
for t in group:
|
for t in group:
|
||||||
self._page_cache.task_record_hashes(
|
cache.task_record_hashes(
|
||||||
t.task_id,
|
t.task_id, t.prompt_ids, start_logical_page
|
||||||
t.prompt_ids,
|
|
||||||
start_logical_page=start_logical_page,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
pos_groups: Dict[int, List[Task]] = {}
|
pos_groups: Dict[int, List[Task]] = {}
|
||||||
for t in self._task_mgr.get_active_tasks():
|
for t in self._task_mgr.get_active_tasks():
|
||||||
pos_groups.setdefault(t.next_pos, []).append(t)
|
pos_groups.setdefault(t.next_pos, []).append(t)
|
||||||
|
|
||||||
if pos_groups:
|
for next_pos in sorted(pos_groups.keys()):
|
||||||
best_key = max(pos_groups, key=lambda k: len(pos_groups[k]))
|
group = sorted(pos_groups[next_pos], key=lambda t: t.task_id)
|
||||||
group = sorted(pos_groups[best_key], key=lambda t: t.task_id)
|
|
||||||
|
|
||||||
valid: List[Task] = []
|
valid: List[Task] = []
|
||||||
for t in group:
|
for t in group:
|
||||||
if self._page_cache.task_extend(t.task_id, t.next_pos):
|
if cache.task_extend(t.task_id, t.next_pos):
|
||||||
valid.append(t)
|
valid.append(t)
|
||||||
else:
|
else:
|
||||||
t.status = TaskStatus.ABORTED
|
t.status = TaskStatus.ABORTED
|
||||||
if t.stream_callback:
|
self._task_mgr.invoke_callback(t.task_id, STOP)
|
||||||
t.stream_callback(STOP)
|
|
||||||
|
|
||||||
if valid:
|
if valid:
|
||||||
next_tokens = self._executor.execute_decode(valid)
|
next_tokens = self._executor.execute_decode(valid)
|
||||||
@@ -159,54 +159,44 @@ class InferenceScheduler:
|
|||||||
for t, ntok in zip(valid, next_tokens):
|
for t, ntok in zip(valid, next_tokens):
|
||||||
t.output_ids.append(ntok)
|
t.output_ids.append(ntok)
|
||||||
t.output_tokens += 1
|
t.output_tokens += 1
|
||||||
pos = t.input_tokens + t.output_tokens
|
self._task_mgr.invoke_callback(
|
||||||
extend_ok = self._page_cache.task_extend(t.task_id, pos)
|
t.task_id,
|
||||||
if t.stream_callback:
|
self._task_mgr.tokenizer.decode([ntok]),
|
||||||
t.stream_callback(
|
|
||||||
self._task_mgr.tokenizer.decode([ntok])
|
|
||||||
)
|
)
|
||||||
if not extend_ok:
|
|
||||||
t.status = TaskStatus.ABORTED
|
|
||||||
if t.stream_callback:
|
|
||||||
t.stream_callback(STOP)
|
|
||||||
|
|
||||||
for t in valid:
|
for t in valid:
|
||||||
if t.is_finished(stop_ids):
|
if t.is_finished(stop_ids):
|
||||||
if t.stream_callback:
|
self._task_mgr.invoke_callback(t.task_id, STOP)
|
||||||
t.stream_callback(STOP)
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self._fatal_error = e
|
self._stop_event.set()
|
||||||
self._running = False
|
|
||||||
logger.error(f"Scheduler loop crashed: {e}", exc_info=True)
|
logger.error(f"Scheduler loop crashed: {e}", exc_info=True)
|
||||||
for task in self._task_mgr.get_active_tasks():
|
for task in self._task_mgr.get_active_tasks():
|
||||||
if task.stream_callback:
|
self._task_mgr.invoke_callback(task.task_id, STOP)
|
||||||
task.stream_callback(STOP)
|
cache.task_free(task.task_id)
|
||||||
self._page_cache.task_free(task.task_id)
|
|
||||||
for task in self._task_mgr.get_waiting_tasks():
|
for task in self._task_mgr.get_waiting_tasks():
|
||||||
if task.stream_callback:
|
self._task_mgr.invoke_callback(task.task_id, STOP)
|
||||||
task.stream_callback(STOP)
|
|
||||||
self._task_mgr.clear_queues()
|
self._task_mgr.clear_queues()
|
||||||
|
|
||||||
def start(self):
|
def start(self):
|
||||||
if not self._running:
|
if self._loop_thread is not None and self._loop_thread.is_alive():
|
||||||
self._running = True
|
return
|
||||||
|
self._stop_event.clear()
|
||||||
t = threading.Thread(target=self._run_generation_loop, daemon=True)
|
t = threading.Thread(target=self._run_generation_loop, daemon=True)
|
||||||
t.start()
|
t.start()
|
||||||
self._loop_thread = t
|
self._loop_thread = t
|
||||||
|
|
||||||
def stop(self):
|
def stop(self):
|
||||||
self._running = False
|
self._stop_event.set()
|
||||||
self._task_mgr.wake()
|
self._task_mgr.wake()
|
||||||
if hasattr(self, "_loop_thread"):
|
if self._loop_thread is not None:
|
||||||
self._loop_thread.join(timeout=2.0)
|
self._loop_thread.join(timeout=2.0)
|
||||||
|
self._loop_thread = None
|
||||||
for task in self._task_mgr.get_active_tasks():
|
for task in self._task_mgr.get_active_tasks():
|
||||||
if task.stream_callback:
|
self._task_mgr.invoke_callback(task.task_id, STOP)
|
||||||
task.stream_callback(STOP)
|
self._cache.task_free(task.task_id)
|
||||||
self._page_cache.task_free(task.task_id)
|
|
||||||
for task in self._task_mgr.get_waiting_tasks():
|
for task in self._task_mgr.get_waiting_tasks():
|
||||||
if task.stream_callback:
|
self._task_mgr.invoke_callback(task.task_id, STOP)
|
||||||
task.stream_callback(STOP)
|
|
||||||
self._task_mgr.clear_queues()
|
self._task_mgr.clear_queues()
|
||||||
if torch.cuda.is_available():
|
if torch.cuda.is_available():
|
||||||
torch.cuda.empty_cache()
|
torch.cuda.empty_cache()
|
||||||
|
|||||||
@@ -33,7 +33,6 @@ class Task:
|
|||||||
temperature: float = 1.0,
|
temperature: float = 1.0,
|
||||||
top_p: float = 1.0,
|
top_p: float = 1.0,
|
||||||
top_k: int = 50,
|
top_k: int = 50,
|
||||||
stream_callback: Optional[Callable[[str], None]] = None,
|
|
||||||
):
|
):
|
||||||
self.task_id = task_id
|
self.task_id = task_id
|
||||||
self.prompt_ids = prompt_ids
|
self.prompt_ids = prompt_ids
|
||||||
@@ -48,7 +47,6 @@ class Task:
|
|||||||
self.output_tokens: int = 0
|
self.output_tokens: int = 0
|
||||||
self.arrival_time = time.time()
|
self.arrival_time = time.time()
|
||||||
self.finish_time: Optional[float] = None
|
self.finish_time: Optional[float] = None
|
||||||
self.stream_callback = stream_callback
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def next_pos(self) -> int:
|
def next_pos(self) -> int:
|
||||||
@@ -79,6 +77,7 @@ class TaskManager:
|
|||||||
|
|
||||||
self.waiting_queue: Deque[Task] = deque()
|
self.waiting_queue: Deque[Task] = deque()
|
||||||
self.active_tasks: List[Task] = []
|
self.active_tasks: List[Task] = []
|
||||||
|
self._callbacks: Dict[str, Callable[[str], None]] = {}
|
||||||
|
|
||||||
self._task_event = threading.Event()
|
self._task_event = threading.Event()
|
||||||
self._lock = threading.Lock()
|
self._lock = threading.Lock()
|
||||||
@@ -117,12 +116,13 @@ class TaskManager:
|
|||||||
temperature=temperature,
|
temperature=temperature,
|
||||||
top_p=top_p,
|
top_p=top_p,
|
||||||
top_k=top_k,
|
top_k=top_k,
|
||||||
stream_callback=stream_callback,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self.waiting_queue.append(task)
|
self.waiting_queue.append(task)
|
||||||
self._total_tasks += 1
|
self._total_tasks += 1
|
||||||
|
if stream_callback:
|
||||||
|
self._callbacks[task_id] = stream_callback
|
||||||
|
|
||||||
self._task_event.set()
|
self._task_event.set()
|
||||||
return task_id
|
return task_id
|
||||||
@@ -134,8 +134,14 @@ class TaskManager:
|
|||||||
t for t in self.waiting_queue if t.task_id != task_id
|
t for t in self.waiting_queue if t.task_id != task_id
|
||||||
)
|
)
|
||||||
self.active_tasks = [t for t in self.active_tasks if t.task_id != task_id]
|
self.active_tasks = [t for t in self.active_tasks if t.task_id != task_id]
|
||||||
|
self._callbacks.pop(task_id, None)
|
||||||
return removed_active
|
return removed_active
|
||||||
|
|
||||||
|
def invoke_callback(self, task_id: str, token: str):
|
||||||
|
cb = self._callbacks.get(task_id)
|
||||||
|
if cb:
|
||||||
|
cb(token)
|
||||||
|
|
||||||
def get_stats(self) -> Dict[str, Any]:
|
def get_stats(self) -> Dict[str, Any]:
|
||||||
return {
|
return {
|
||||||
"total_tasks": self._total_tasks,
|
"total_tasks": self._total_tasks,
|
||||||
@@ -204,6 +210,7 @@ class TaskManager:
|
|||||||
with self._lock:
|
with self._lock:
|
||||||
self.waiting_queue.clear()
|
self.waiting_queue.clear()
|
||||||
self.active_tasks.clear()
|
self.active_tasks.clear()
|
||||||
|
self._callbacks.clear()
|
||||||
|
|
||||||
def wake(self):
|
def wake(self):
|
||||||
self._task_event.set()
|
self._task_event.set()
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ from typing import Any, AsyncGenerator, Dict, Generator, List, Optional, Tuple,
|
|||||||
import torch
|
import torch
|
||||||
import torch.nn as nn
|
import torch.nn as nn
|
||||||
|
|
||||||
|
from astrai.inference.core.cache import KVCache
|
||||||
from astrai.inference.core.scheduler import InferenceScheduler
|
from astrai.inference.core.scheduler import InferenceScheduler
|
||||||
from astrai.inference.core.task import STOP
|
from astrai.inference.core.task import STOP
|
||||||
from astrai.tokenize import AutoTokenizer
|
from astrai.tokenize import AutoTokenizer
|
||||||
@@ -101,6 +102,7 @@ class InferenceEngine:
|
|||||||
max_seq_len: Optional[int] = None,
|
max_seq_len: Optional[int] = None,
|
||||||
max_prompt_len: int = 2048,
|
max_prompt_len: int = 2048,
|
||||||
page_size: int = 128,
|
page_size: int = 128,
|
||||||
|
cache: Optional[KVCache] = None,
|
||||||
):
|
):
|
||||||
self.model = model
|
self.model = model
|
||||||
self.tokenizer = tokenizer
|
self.tokenizer = tokenizer
|
||||||
@@ -110,7 +112,7 @@ class InferenceEngine:
|
|||||||
max_batch_size=max_batch_size,
|
max_batch_size=max_batch_size,
|
||||||
max_seq_len=max_seq_len,
|
max_seq_len=max_seq_len,
|
||||||
max_prompt_len=max_prompt_len,
|
max_prompt_len=max_prompt_len,
|
||||||
page_size=page_size,
|
cache=cache,
|
||||||
)
|
)
|
||||||
|
|
||||||
self.scheduler.start()
|
self.scheduler.start()
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import torch.nn.functional as F
|
|||||||
from torch import Tensor
|
from torch import Tensor
|
||||||
|
|
||||||
from astrai.factory import BaseFactory
|
from astrai.factory import BaseFactory
|
||||||
from astrai.inference.core.cache import KvcacheView
|
from astrai.inference.core.cache import CacheView
|
||||||
from astrai.model.components.linear import Linear
|
from astrai.model.components.linear import Linear
|
||||||
from astrai.model.components.norm import RMSNorm
|
from astrai.model.components.norm import RMSNorm
|
||||||
from astrai.model.components.rope import apply_rotary_emb
|
from astrai.model.components.rope import apply_rotary_emb
|
||||||
@@ -38,6 +38,7 @@ class GQA(nn.Module):
|
|||||||
norm_eps: float,
|
norm_eps: float,
|
||||||
use_gated_attention: bool,
|
use_gated_attention: bool,
|
||||||
layer_id: int,
|
layer_id: int,
|
||||||
|
n_layers: int = 1,
|
||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
assert dim % n_heads == 0
|
assert dim % n_heads == 0
|
||||||
@@ -55,7 +56,7 @@ class GQA(nn.Module):
|
|||||||
self.q_proj = Linear(dim, n_heads * self.head_dim)
|
self.q_proj = Linear(dim, n_heads * self.head_dim)
|
||||||
self.k_proj = Linear(dim, n_kv_heads * self.head_dim)
|
self.k_proj = Linear(dim, n_kv_heads * self.head_dim)
|
||||||
self.v_proj = Linear(dim, n_kv_heads * self.head_dim)
|
self.v_proj = Linear(dim, n_kv_heads * self.head_dim)
|
||||||
self.o_proj = Linear(dim, dim)
|
self.o_proj = Linear(dim, dim, init_std=0.02 / (2 * n_layers) ** 0.5)
|
||||||
|
|
||||||
if self.use_qk_norm:
|
if self.use_qk_norm:
|
||||||
self.q_norm = RMSNorm(self.head_dim, norm_eps)
|
self.q_norm = RMSNorm(self.head_dim, norm_eps)
|
||||||
@@ -74,7 +75,7 @@ class GQA(nn.Module):
|
|||||||
x: Tensor,
|
x: Tensor,
|
||||||
rotary_emb: Tensor,
|
rotary_emb: Tensor,
|
||||||
attn_mask: Tensor = None,
|
attn_mask: Tensor = None,
|
||||||
paged_cache: Optional[KvcacheView] = None,
|
paged_cache: Optional[CacheView] = None,
|
||||||
) -> Tensor:
|
) -> Tensor:
|
||||||
is_causal = attn_mask is None
|
is_causal = attn_mask is None
|
||||||
|
|
||||||
@@ -121,6 +122,7 @@ class MLA(nn.Module):
|
|||||||
use_qk_norm: bool,
|
use_qk_norm: bool,
|
||||||
use_gated_attention: bool,
|
use_gated_attention: bool,
|
||||||
layer_id: int,
|
layer_id: int,
|
||||||
|
n_layers: int = 1,
|
||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.dim = dim
|
self.dim = dim
|
||||||
@@ -148,7 +150,9 @@ class MLA(nn.Module):
|
|||||||
n_kv_heads * (2 * self.head_dim),
|
n_kv_heads * (2 * self.head_dim),
|
||||||
)
|
)
|
||||||
|
|
||||||
self.o_proj = Linear(dim, dim, bias=False)
|
self.o_proj = Linear(
|
||||||
|
dim, dim, bias=False, init_std=0.02 / (2 * n_layers) ** 0.5
|
||||||
|
)
|
||||||
|
|
||||||
if use_gated_attention:
|
if use_gated_attention:
|
||||||
self.gate = Linear(dim, dim, bias=False)
|
self.gate = Linear(dim, dim, bias=False)
|
||||||
@@ -158,7 +162,7 @@ class MLA(nn.Module):
|
|||||||
x: Tensor,
|
x: Tensor,
|
||||||
rotary_emb: Tensor,
|
rotary_emb: Tensor,
|
||||||
attn_mask: Tensor = None,
|
attn_mask: Tensor = None,
|
||||||
paged_cache: Optional[KvcacheView] = None,
|
paged_cache: Optional[CacheView] = None,
|
||||||
) -> Tensor:
|
) -> Tensor:
|
||||||
bsz, seq_len, _ = x.size()
|
bsz, seq_len, _ = x.size()
|
||||||
is_causal = attn_mask is None
|
is_causal = attn_mask is None
|
||||||
|
|||||||
@@ -1,51 +1,31 @@
|
|||||||
|
from dataclasses import asdict
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
import torch.nn as nn
|
import torch.nn as nn
|
||||||
from torch import Tensor
|
from torch import Tensor
|
||||||
|
|
||||||
from astrai.inference.core.cache import KvcacheView
|
from astrai.inference.core.cache import CacheView
|
||||||
from astrai.model.components.attention import AttnFactory
|
from astrai.model.components.attention import AttnFactory
|
||||||
from astrai.model.components.mlp import FFNFactory
|
from astrai.model.components.mlp import FFNFactory
|
||||||
from astrai.model.components.norm import RMSNorm
|
from astrai.model.components.norm import RMSNorm
|
||||||
|
|
||||||
|
|
||||||
class DecoderBlock(nn.Module):
|
class DecoderBlock(nn.Module):
|
||||||
def __init__(
|
def __init__(self, config, layer_id: int):
|
||||||
self,
|
|
||||||
dim: int,
|
|
||||||
n_heads: int,
|
|
||||||
dim_ffn: int,
|
|
||||||
n_kv_heads: int,
|
|
||||||
norm_eps: float,
|
|
||||||
use_qk_norm: bool,
|
|
||||||
use_gated_attention: bool,
|
|
||||||
layer_id: int,
|
|
||||||
attn_type: str = "gqa",
|
|
||||||
ffn_type: str = "mlp",
|
|
||||||
**kwargs,
|
|
||||||
):
|
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.attention = AttnFactory.create(
|
cfg = asdict(config)
|
||||||
attn_type,
|
cfg["down_init_std"] = 0.02 / (2 * config.n_layers) ** 0.5
|
||||||
dim=dim,
|
self.attention = AttnFactory.create(config.attn_type, **cfg, layer_id=layer_id)
|
||||||
n_heads=n_heads,
|
self.input_norm = RMSNorm(config.dim, config.norm_eps)
|
||||||
n_kv_heads=n_kv_heads,
|
self.post_attention_norm = RMSNorm(config.dim, config.norm_eps)
|
||||||
use_qk_norm=use_qk_norm,
|
self.mlp = FFNFactory.create(config.ffn_type, **cfg)
|
||||||
norm_eps=norm_eps,
|
|
||||||
use_gated_attention=use_gated_attention,
|
|
||||||
layer_id=layer_id,
|
|
||||||
**kwargs,
|
|
||||||
)
|
|
||||||
self.input_norm = RMSNorm(dim, norm_eps)
|
|
||||||
self.post_attention_norm = RMSNorm(dim, norm_eps)
|
|
||||||
self.mlp = FFNFactory.create(ffn_type, dim, dim_ffn, **kwargs)
|
|
||||||
|
|
||||||
def forward(
|
def forward(
|
||||||
self,
|
self,
|
||||||
x: Tensor,
|
x: Tensor,
|
||||||
rotary_emb: Tensor,
|
rotary_emb: Tensor,
|
||||||
attention_mask: Optional[Tensor] = None,
|
attention_mask: Optional[Tensor] = None,
|
||||||
paged_cache: Optional[KvcacheView] = None,
|
paged_cache: Optional[CacheView] = None,
|
||||||
) -> Tensor:
|
) -> Tensor:
|
||||||
attn_output = self.attention(
|
attn_output = self.attention(
|
||||||
self.input_norm(x),
|
self.input_norm(x),
|
||||||
|
|||||||
@@ -7,10 +7,13 @@ from torch import Tensor
|
|||||||
|
|
||||||
|
|
||||||
class Embedding(nn.Module):
|
class Embedding(nn.Module):
|
||||||
def __init__(self, vocab_size: int, embedding_dim: int):
|
def __init__(self, vocab_size: int, embedding_dim: int, neftune_alpha: float = 0.0):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.weight = nn.Parameter(torch.empty((vocab_size, embedding_dim)))
|
self.weight = nn.Parameter(torch.empty((vocab_size, embedding_dim)))
|
||||||
self.neftune_noise_alpha = 0.0
|
self.neftune_noise_alpha = neftune_alpha
|
||||||
|
|
||||||
|
def set_neftune_alpha(self, alpha: float):
|
||||||
|
self.neftune_noise_alpha = alpha
|
||||||
|
|
||||||
def reset_parameters(self):
|
def reset_parameters(self):
|
||||||
nn.init.normal_(self.weight, mean=0.0, std=0.02)
|
nn.init.normal_(self.weight, mean=0.0, std=0.02)
|
||||||
|
|||||||
@@ -5,13 +5,16 @@ from torch import Tensor
|
|||||||
|
|
||||||
|
|
||||||
class Linear(nn.Module):
|
class Linear(nn.Module):
|
||||||
def __init__(self, in_dim: int, out_dim: int, bias: bool = False):
|
def __init__(
|
||||||
|
self, in_dim: int, out_dim: int, bias: bool = False, init_std: float = 0.02
|
||||||
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.weight = nn.Parameter(torch.empty((out_dim, in_dim)))
|
self.weight = nn.Parameter(torch.empty((out_dim, in_dim)))
|
||||||
self.bias = nn.Parameter(torch.zeros(out_dim)) if bias else None
|
self.bias = nn.Parameter(torch.zeros(out_dim)) if bias else None
|
||||||
|
self.init_std = init_std
|
||||||
|
|
||||||
def reset_parameters(self):
|
def reset_parameters(self):
|
||||||
nn.init.kaiming_uniform_(self.weight, a=5**0.5)
|
nn.init.normal_(self.weight, mean=0.0, std=self.init_std)
|
||||||
if self.bias is not None:
|
if self.bias is not None:
|
||||||
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight)
|
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight)
|
||||||
bound = 1 / (fan_in**0.5)
|
bound = 1 / (fan_in**0.5)
|
||||||
|
|||||||
@@ -13,11 +13,11 @@ class FFNFactory(BaseFactory[nn.Module]):
|
|||||||
|
|
||||||
@FFNFactory.register("mlp")
|
@FFNFactory.register("mlp")
|
||||||
class MLP(nn.Module):
|
class MLP(nn.Module):
|
||||||
def __init__(self, dim: int, dim_ffn: int):
|
def __init__(self, dim: int, dim_ffn: int, down_init_std: float = 0.02):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.up = Linear(dim, dim_ffn)
|
self.up = Linear(dim, dim_ffn)
|
||||||
self.gate = Linear(dim, dim_ffn)
|
self.gate = Linear(dim, dim_ffn)
|
||||||
self.down = Linear(dim_ffn, dim)
|
self.down = Linear(dim_ffn, dim, init_std=down_init_std)
|
||||||
|
|
||||||
def forward(self, x: Tensor) -> Tensor:
|
def forward(self, x: Tensor) -> Tensor:
|
||||||
gated = self.up(x) * F.silu(self.gate(x))
|
gated = self.up(x) * F.silu(self.gate(x))
|
||||||
@@ -35,6 +35,7 @@ class DeepSeekMoE(nn.Module):
|
|||||||
n_shared_experts: int = 1,
|
n_shared_experts: int = 1,
|
||||||
n_activated_experts: int = 2,
|
n_activated_experts: int = 2,
|
||||||
topk_method: str = "greedy",
|
topk_method: str = "greedy",
|
||||||
|
n_layers: int = 1,
|
||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.dim = dim
|
self.dim = dim
|
||||||
@@ -44,12 +45,20 @@ class DeepSeekMoE(nn.Module):
|
|||||||
self.topk_method = topk_method
|
self.topk_method = topk_method
|
||||||
|
|
||||||
self.router = Linear(dim, n_routed_experts, bias=False)
|
self.router = Linear(dim, n_routed_experts, bias=False)
|
||||||
|
moe_scale = 1 / max(n_shared_experts, 1) + 1 / n_activated_experts
|
||||||
|
down_init_std = 0.02 / (2 * n_layers * moe_scale) ** 0.5
|
||||||
|
|
||||||
self.shared_experts = nn.ModuleList(
|
self.shared_experts = nn.ModuleList(
|
||||||
[MLP(dim, dim_ffn) for _ in range(n_shared_experts)]
|
[
|
||||||
|
MLP(dim, dim_ffn, down_init_std=down_init_std)
|
||||||
|
for _ in range(n_shared_experts)
|
||||||
|
]
|
||||||
)
|
)
|
||||||
self.routed_experts = nn.ModuleList(
|
self.routed_experts = nn.ModuleList(
|
||||||
[MLP(dim, dim_ffn) for _ in range(n_routed_experts)]
|
[
|
||||||
|
MLP(dim, dim_ffn, down_init_std=down_init_std)
|
||||||
|
for _ in range(n_routed_experts)
|
||||||
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
def forward(self, x: Tensor) -> Tensor:
|
def forward(self, x: Tensor) -> Tensor:
|
||||||
|
|||||||
+4
-14
@@ -23,22 +23,12 @@ class EmbeddingEncoder(AutoModel):
|
|||||||
self.rotary_embedding = RotaryEmbedding(
|
self.rotary_embedding = RotaryEmbedding(
|
||||||
rope_dim, config.max_len, rope_base, rope_scaling=config.rope_scaling
|
rope_dim, config.max_len, rope_base, rope_scaling=config.rope_scaling
|
||||||
)
|
)
|
||||||
self.embed_tokens = Embedding(config.vocab_size, config.dim)
|
self.embed_tokens = Embedding(
|
||||||
|
config.vocab_size, config.dim, neftune_alpha=config.neftune_alpha
|
||||||
|
)
|
||||||
|
|
||||||
self.layers = nn.ModuleList(
|
self.layers = nn.ModuleList(
|
||||||
[
|
[DecoderBlock(config, layer_id) for layer_id in range(config.n_layers)]
|
||||||
DecoderBlock(
|
|
||||||
config.dim,
|
|
||||||
config.n_heads,
|
|
||||||
config.dim_ffn,
|
|
||||||
config.n_kv_heads,
|
|
||||||
config.norm_eps,
|
|
||||||
config.use_qk_norm,
|
|
||||||
config.use_gated_attention,
|
|
||||||
layer_id,
|
|
||||||
)
|
|
||||||
for layer_id in range(config.n_layers)
|
|
||||||
]
|
|
||||||
)
|
)
|
||||||
|
|
||||||
self.norm = RMSNorm(config.dim, config.norm_eps)
|
self.norm = RMSNorm(config.dim, config.norm_eps)
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import torch.nn as nn
|
|||||||
from torch import Tensor
|
from torch import Tensor
|
||||||
|
|
||||||
from astrai.config.model_config import AutoRegressiveLMConfig
|
from astrai.config.model_config import AutoRegressiveLMConfig
|
||||||
from astrai.inference.core.cache import KvcacheView
|
from astrai.inference.core.cache import CacheView
|
||||||
from astrai.model.automodel import AutoModel
|
from astrai.model.automodel import AutoModel
|
||||||
from astrai.model.components.decoder_block import DecoderBlock
|
from astrai.model.components.decoder_block import DecoderBlock
|
||||||
from astrai.model.components.embedding import Embedding
|
from astrai.model.components.embedding import Embedding
|
||||||
@@ -59,31 +59,12 @@ class AutoRegressiveLM(AutoModel):
|
|||||||
self.rotary_embedding = RotaryEmbedding(
|
self.rotary_embedding = RotaryEmbedding(
|
||||||
rope_dim, config.max_len, rope_base, rope_scaling=config.rope_scaling
|
rope_dim, config.max_len, rope_base, rope_scaling=config.rope_scaling
|
||||||
)
|
)
|
||||||
self.embed_tokens = Embedding(config.vocab_size, config.dim)
|
self.embed_tokens = Embedding(
|
||||||
|
config.vocab_size, config.dim, neftune_alpha=config.neftune_alpha
|
||||||
|
)
|
||||||
|
|
||||||
self.layers = nn.ModuleList(
|
self.layers = nn.ModuleList(
|
||||||
[
|
[DecoderBlock(config, layer_id) for layer_id in range(config.n_layers)]
|
||||||
DecoderBlock(
|
|
||||||
config.dim,
|
|
||||||
config.n_heads,
|
|
||||||
config.dim_ffn,
|
|
||||||
config.n_kv_heads,
|
|
||||||
config.norm_eps,
|
|
||||||
config.use_qk_norm,
|
|
||||||
config.use_gated_attention,
|
|
||||||
layer_id,
|
|
||||||
attn_type=config.attn_type,
|
|
||||||
ffn_type=config.ffn_type,
|
|
||||||
n_routed_experts=config.n_routed_experts,
|
|
||||||
n_shared_experts=config.n_shared_experts,
|
|
||||||
n_activated_experts=config.n_activated_experts,
|
|
||||||
topk_method=config.topk_method,
|
|
||||||
kv_lora_rank=config.kv_lora_rank,
|
|
||||||
qk_nope_head_dim=config.qk_nope_head_dim,
|
|
||||||
qk_rope_head_dim=config.qk_rope_head_dim,
|
|
||||||
)
|
|
||||||
for layer_id in range(config.n_layers)
|
|
||||||
]
|
|
||||||
)
|
)
|
||||||
|
|
||||||
self.norm = RMSNorm(config.dim, config.norm_eps)
|
self.norm = RMSNorm(config.dim, config.norm_eps)
|
||||||
@@ -131,7 +112,7 @@ class AutoRegressiveLM(AutoModel):
|
|||||||
self,
|
self,
|
||||||
input_ids: Tensor,
|
input_ids: Tensor,
|
||||||
input_mask: Optional[Tensor] = None,
|
input_mask: Optional[Tensor] = None,
|
||||||
paged_cache: Optional[KvcacheView] = None,
|
paged_cache: Optional[CacheView] = None,
|
||||||
position_ids: Optional[Tensor] = None,
|
position_ids: Optional[Tensor] = None,
|
||||||
) -> Dict[str, Tensor]:
|
) -> Dict[str, Tensor]:
|
||||||
assert input_ids.ndim == 2
|
assert input_ids.ndim == 2
|
||||||
|
|||||||
@@ -132,6 +132,12 @@ class BaseExecutor:
|
|||||||
def grad_accum_steps(self) -> int:
|
def grad_accum_steps(self) -> int:
|
||||||
return self.gradient_state.num_steps
|
return self.gradient_state.num_steps
|
||||||
|
|
||||||
|
def clip_grad_norm(self, model: nn.Module, max_norm: float) -> float:
|
||||||
|
total_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm)
|
||||||
|
if isinstance(total_norm, torch.Tensor):
|
||||||
|
return total_norm.item()
|
||||||
|
return total_norm
|
||||||
|
|
||||||
|
|
||||||
class ExecutorFactory(BaseFactory[BaseExecutor]):
|
class ExecutorFactory(BaseFactory[BaseExecutor]):
|
||||||
pass
|
pass
|
||||||
@@ -260,6 +266,14 @@ class FSDPExecutor(BaseExecutor):
|
|||||||
return model.no_sync()
|
return model.no_sync()
|
||||||
return contextlib.nullcontext()
|
return contextlib.nullcontext()
|
||||||
|
|
||||||
|
def clip_grad_norm(self, model: nn.Module, max_norm: float) -> float:
|
||||||
|
if isinstance(model, FSDP) and self.use_distributed:
|
||||||
|
total_norm = model.clip_grad_norm_(max_norm)
|
||||||
|
if isinstance(total_norm, torch.Tensor):
|
||||||
|
return total_norm.item()
|
||||||
|
return total_norm
|
||||||
|
return super().clip_grad_norm(model, max_norm)
|
||||||
|
|
||||||
def unwrap_model(self, model: nn.Module):
|
def unwrap_model(self, model: nn.Module):
|
||||||
if isinstance(model, FSDP) and self.use_distributed:
|
if isinstance(model, FSDP) and self.use_distributed:
|
||||||
with FSDP.state_dict_type(
|
with FSDP.state_dict_type(
|
||||||
|
|||||||
@@ -58,9 +58,11 @@ def setup_parallel(
|
|||||||
os.environ["WORLD_SIZE"] = str(world_size)
|
os.environ["WORLD_SIZE"] = str(world_size)
|
||||||
os.environ["LOCAL_DEVICE"] = str(device_id)
|
os.environ["LOCAL_DEVICE"] = str(device_id)
|
||||||
|
|
||||||
dist.init_process_group(
|
pg_kwargs = dict(rank=rank, world_size=world_size, backend=backend)
|
||||||
rank=rank, world_size=world_size, backend=backend, device_id=device_id
|
if backend in ("nccl", "ccl"):
|
||||||
)
|
pg_kwargs["device_id"] = device_id
|
||||||
|
|
||||||
|
dist.init_process_group(**pg_kwargs)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if backend == "nccl" and torch.cuda.is_available():
|
if backend == "nccl" and torch.cuda.is_available():
|
||||||
|
|||||||
@@ -6,8 +6,7 @@ pipeline later flattens the result into contiguous tensors.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from collections import defaultdict
|
from typing import Dict, List
|
||||||
from typing import Dict, List, Tuple
|
|
||||||
|
|
||||||
from astrai.factory import BaseFactory
|
from astrai.factory import BaseFactory
|
||||||
|
|
||||||
@@ -53,6 +52,15 @@ class SimplePacking(PackingStrategy):
|
|||||||
|
|
||||||
@PackingStrategyFactory.register("bfd")
|
@PackingStrategyFactory.register("bfd")
|
||||||
class BFDPacking(PackingStrategy):
|
class BFDPacking(PackingStrategy):
|
||||||
|
"""Best-Fit Decreasing bin packing.
|
||||||
|
|
||||||
|
Assigns sequences to bins using a best-fit heuristic (sorted by
|
||||||
|
decreasing length) and concatenates sequences within each bin into
|
||||||
|
a single packed sequence. Packed sequences are truncated to
|
||||||
|
*max_packed_len* so that each packed bin fits within one context
|
||||||
|
window during training.
|
||||||
|
"""
|
||||||
|
|
||||||
def apply(
|
def apply(
|
||||||
self,
|
self,
|
||||||
keys: Dict[str, List[List[int]]],
|
keys: Dict[str, List[List[int]]],
|
||||||
@@ -62,24 +70,40 @@ class BFDPacking(PackingStrategy):
|
|||||||
sequences = keys.get("sequence", [])
|
sequences = keys.get("sequence", [])
|
||||||
if not sequences:
|
if not sequences:
|
||||||
return keys
|
return keys
|
||||||
plan = self._plan(sequences, max_packed_len)
|
bins = self._plan(sequences, max_packed_len, truncation_mode)
|
||||||
reordered: dict = defaultdict(list)
|
|
||||||
for orig_idx, _ in plan:
|
packed: Dict[str, List[List[int]]] = {}
|
||||||
for k, vals in keys.items():
|
for k, vals in keys.items():
|
||||||
reordered[k].append(
|
packed[k] = [
|
||||||
_truncate(vals[orig_idx], max_packed_len, truncation_mode)
|
_truncate(
|
||||||
|
self._concat_bin(vals, bin_indices),
|
||||||
|
max_packed_len,
|
||||||
|
truncation_mode,
|
||||||
)
|
)
|
||||||
return dict(reordered)
|
for bin_indices in bins
|
||||||
|
]
|
||||||
|
return packed
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _plan(sequences: List[List[int]], max_packed_len: int) -> List[Tuple[int, int]]:
|
def _concat_bin(vals: List[List[int]], indices: List[int]) -> List[int]:
|
||||||
|
result: List[int] = []
|
||||||
|
for i in indices:
|
||||||
|
result.extend(vals[i])
|
||||||
|
return result
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _plan(
|
||||||
|
sequences: List[List[int]], max_packed_len: int, truncation_mode: str
|
||||||
|
) -> List[List[int]]:
|
||||||
n = len(sequences)
|
n = len(sequences)
|
||||||
order = sorted(range(n), key=lambda i: len(sequences[i]), reverse=True)
|
order = sorted(range(n), key=lambda i: len(sequences[i]), reverse=True)
|
||||||
bins: List[List[int]] = []
|
bins: List[List[int]] = []
|
||||||
bin_lengths: List[int] = []
|
bin_lengths: List[int] = []
|
||||||
|
|
||||||
for orig_idx in order:
|
for orig_idx in order:
|
||||||
seq_len = min(len(sequences[orig_idx]), max_packed_len)
|
seq_len = len(
|
||||||
|
_truncate(sequences[orig_idx], max_packed_len, truncation_mode)
|
||||||
|
)
|
||||||
best_bin = None
|
best_bin = None
|
||||||
best_remain = max_packed_len + 1
|
best_remain = max_packed_len + 1
|
||||||
for i, bl in enumerate(bin_lengths):
|
for i, bl in enumerate(bin_lengths):
|
||||||
@@ -94,8 +118,4 @@ class BFDPacking(PackingStrategy):
|
|||||||
bins.append([orig_idx])
|
bins.append([orig_idx])
|
||||||
bin_lengths.append(seq_len)
|
bin_lengths.append(seq_len)
|
||||||
|
|
||||||
plan: List[Tuple[int, int]] = []
|
return bins
|
||||||
for bin_indices in bins:
|
|
||||||
for orig_idx in bin_indices:
|
|
||||||
plan.append((orig_idx, min(len(sequences[orig_idx]), max_packed_len)))
|
|
||||||
return plan
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ dispatched by configuration keys.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import logging
|
||||||
import os
|
import os
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from itertools import chain
|
from itertools import chain
|
||||||
@@ -22,6 +23,8 @@ from astrai.preprocessing.position_id import PositionIdStrategyFactory
|
|||||||
from astrai.preprocessing.writer import StoreWriterFactory
|
from astrai.preprocessing.writer import StoreWriterFactory
|
||||||
from astrai.tokenize import AutoTokenizer
|
from astrai.tokenize import AutoTokenizer
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
_STR_TO_DTYPE: dict[str, torch.dtype] = {
|
_STR_TO_DTYPE: dict[str, torch.dtype] = {
|
||||||
"bool": torch.bool,
|
"bool": torch.bool,
|
||||||
"uint8": torch.uint8,
|
"uint8": torch.uint8,
|
||||||
@@ -88,7 +91,13 @@ class Pipeline:
|
|||||||
if pp.max_items and count >= pp.max_items:
|
if pp.max_items and count >= pp.max_items:
|
||||||
break
|
break
|
||||||
|
|
||||||
|
try:
|
||||||
result = self.transform(item)
|
result = self.transform(item)
|
||||||
|
except Exception:
|
||||||
|
logger.warning(
|
||||||
|
"Failed to process item #%d, skipping", count + 1, exc_info=True
|
||||||
|
)
|
||||||
|
continue
|
||||||
if result is None:
|
if result is None:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -105,7 +114,7 @@ class Pipeline:
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
bucket = domains[domain]
|
bucket = domains[domain]
|
||||||
self._align_bucket(bucket, result, ids, is_multi)
|
self._align_bucket(bucket, result, ids)
|
||||||
for key, val in result.items():
|
for key, val in result.items():
|
||||||
bucket[key].append(val)
|
bucket[key].append(val)
|
||||||
|
|
||||||
@@ -130,16 +139,12 @@ class Pipeline:
|
|||||||
return []
|
return []
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _align_bucket(bucket: dict, result: dict, ids: list, is_multi: bool):
|
def _align_bucket(bucket: dict, result: dict, ids: list):
|
||||||
"""Pad previously-accumulated keys that are missing from *result*."""
|
"""Pad previously-accumulated keys that are missing from *result*."""
|
||||||
for key in list(bucket.keys()):
|
for key in list(bucket.keys()):
|
||||||
if key in result:
|
if key in result:
|
||||||
continue
|
continue
|
||||||
if is_multi:
|
bucket[key].append([0] * len(ids))
|
||||||
pad = bucket[key][-1] if bucket[key] else [1] * len(ids)
|
|
||||||
bucket[key].append(pad)
|
|
||||||
else:
|
|
||||||
bucket[key].append([1] * len(ids))
|
|
||||||
|
|
||||||
def _iter_items(self):
|
def _iter_items(self):
|
||||||
for path in self.paths:
|
for path in self.paths:
|
||||||
@@ -155,6 +160,12 @@ class Pipeline:
|
|||||||
idx = shard_idx[domain]
|
idx = shard_idx[domain]
|
||||||
|
|
||||||
pp = self.config.preprocessing
|
pp = self.config.preprocessing
|
||||||
|
original_sequences = keys.get("sequence", [])
|
||||||
|
mode = self.config.output.position_ids_mode
|
||||||
|
|
||||||
|
if mode == "doc_reset" and original_sequences:
|
||||||
|
keys["position_ids"] = [list(range(len(s))) for s in original_sequences]
|
||||||
|
|
||||||
keys = self._packer.apply(dict(keys), pp.max_packed_len, pp.truncation_mode)
|
keys = self._packer.apply(dict(keys), pp.max_packed_len, pp.truncation_mode)
|
||||||
|
|
||||||
tensors: Dict[str, List[torch.Tensor]] = {}
|
tensors: Dict[str, List[torch.Tensor]] = {}
|
||||||
@@ -166,6 +177,7 @@ class Pipeline:
|
|||||||
torch.tensor(list(chain.from_iterable(ids_list)), dtype=dt)
|
torch.tensor(list(chain.from_iterable(ids_list)), dtype=dt)
|
||||||
]
|
]
|
||||||
|
|
||||||
|
if mode == "continuous" and original_sequences:
|
||||||
pos_ids = self._position_id.generate(keys.get("sequence", []))
|
pos_ids = self._position_id.generate(keys.get("sequence", []))
|
||||||
if pos_ids:
|
if pos_ids:
|
||||||
tensors["position_ids"] = [torch.tensor(pos_ids, dtype=torch.int32)]
|
tensors["position_ids"] = [torch.tensor(pos_ids, dtype=torch.int32)]
|
||||||
|
|||||||
@@ -6,14 +6,18 @@ List[Tensor]}`` dict and delegates the write to the writer selected
|
|||||||
by ``output.storage_format``.
|
by ``output.storage_format``.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import shutil
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from typing import Dict, List
|
from typing import Dict, List
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
from astrai.dataset.storage import save_bin, save_h5
|
|
||||||
from astrai.factory import BaseFactory
|
from astrai.factory import BaseFactory
|
||||||
|
from astrai.serialization import save_bin, save_h5
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class StoreWriter(ABC):
|
class StoreWriter(ABC):
|
||||||
@@ -37,11 +41,35 @@ class StoreWriterFactory(BaseFactory["StoreWriter"]):
|
|||||||
class BinWriter(StoreWriter):
|
class BinWriter(StoreWriter):
|
||||||
def save(self, output_dir, domain, shard_idx, tensors):
|
def save(self, output_dir, domain, shard_idx, tensors):
|
||||||
shard_path = os.path.join(output_dir, domain, f"shard_{shard_idx:04d}")
|
shard_path = os.path.join(output_dir, domain, f"shard_{shard_idx:04d}")
|
||||||
|
try:
|
||||||
save_bin(shard_path, tensors)
|
save_bin(shard_path, tensors)
|
||||||
|
except Exception:
|
||||||
|
if os.path.exists(shard_path):
|
||||||
|
shutil.rmtree(shard_path, ignore_errors=True)
|
||||||
|
logger.error(
|
||||||
|
"Failed to write shard %s/%s_%04d, cleaned up partial output",
|
||||||
|
domain,
|
||||||
|
"shard",
|
||||||
|
shard_idx,
|
||||||
|
exc_info=True,
|
||||||
|
)
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
@StoreWriterFactory.register("h5")
|
@StoreWriterFactory.register("h5")
|
||||||
class H5Writer(StoreWriter):
|
class H5Writer(StoreWriter):
|
||||||
def save(self, output_dir, domain, shard_idx, tensors):
|
def save(self, output_dir, domain, shard_idx, tensors):
|
||||||
chunk_dir = os.path.join(output_dir, domain)
|
chunk_dir = os.path.join(output_dir, domain)
|
||||||
|
file_path = os.path.join(chunk_dir, f"data_{shard_idx:04d}.h5")
|
||||||
|
try:
|
||||||
save_h5(chunk_dir, f"data_{shard_idx:04d}", tensors)
|
save_h5(chunk_dir, f"data_{shard_idx:04d}", tensors)
|
||||||
|
except Exception:
|
||||||
|
if os.path.exists(file_path):
|
||||||
|
os.remove(file_path)
|
||||||
|
logger.error(
|
||||||
|
"Failed to write shard %s/data_%04d.h5, cleaned up partial output",
|
||||||
|
domain,
|
||||||
|
shard_idx,
|
||||||
|
exc_info=True,
|
||||||
|
)
|
||||||
|
raise
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"""Serialization utilities for models and datasets.
|
||||||
|
|
||||||
|
This package re-exports checkpoint helpers and dataset storage helpers so
|
||||||
|
that existing imports from ``astrai.serialization`` continue to work.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from astrai.serialization.checkpoint import (
|
||||||
|
Checkpoint,
|
||||||
|
load_json,
|
||||||
|
load_model_config,
|
||||||
|
load_model_weights,
|
||||||
|
load_safetensors,
|
||||||
|
load_state_dict,
|
||||||
|
load_torch,
|
||||||
|
save_json,
|
||||||
|
save_model,
|
||||||
|
save_safetensors,
|
||||||
|
save_torch,
|
||||||
|
)
|
||||||
|
from astrai.serialization.dataset import (
|
||||||
|
load_bin,
|
||||||
|
load_h5,
|
||||||
|
save_bin,
|
||||||
|
save_h5,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"Checkpoint",
|
||||||
|
"load_json",
|
||||||
|
"load_model_config",
|
||||||
|
"load_model_weights",
|
||||||
|
"load_safetensors",
|
||||||
|
"load_state_dict",
|
||||||
|
"load_torch",
|
||||||
|
"save_json",
|
||||||
|
"save_model",
|
||||||
|
"save_safetensors",
|
||||||
|
"save_torch",
|
||||||
|
"load_bin",
|
||||||
|
"load_h5",
|
||||||
|
"save_bin",
|
||||||
|
"save_h5",
|
||||||
|
]
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
|
"""Model checkpoint serialization helpers."""
|
||||||
|
|
||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
|
import os
|
||||||
import time
|
import time
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -136,7 +139,7 @@ def load_state_dict(path: Union[str, Path], broadcast: bool = False) -> dict:
|
|||||||
class Checkpoint:
|
class Checkpoint:
|
||||||
state_dict: Dict[str, Any] = field(default_factory=dict)
|
state_dict: Dict[str, Any] = field(default_factory=dict)
|
||||||
epoch: int = 0
|
epoch: int = 0
|
||||||
iteration: int = 0
|
consumed_samples: int = 0
|
||||||
extra: Dict[str, Any] = field(default_factory=dict)
|
extra: Dict[str, Any] = field(default_factory=dict)
|
||||||
meta: Dict[str, Any] = field(default_factory=dict)
|
meta: Dict[str, Any] = field(default_factory=dict)
|
||||||
config: Dict[str, Any] = field(default_factory=dict)
|
config: Dict[str, Any] = field(default_factory=dict)
|
||||||
@@ -150,7 +153,7 @@ class Checkpoint:
|
|||||||
|
|
||||||
meta = {
|
meta = {
|
||||||
"epoch": self.epoch,
|
"epoch": self.epoch,
|
||||||
"iteration": self.iteration,
|
"consumed_samples": self.consumed_samples,
|
||||||
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
||||||
**self.meta,
|
**self.meta,
|
||||||
}
|
}
|
||||||
@@ -176,7 +179,7 @@ class Checkpoint:
|
|||||||
return cls(
|
return cls(
|
||||||
state_dict=state_dict,
|
state_dict=state_dict,
|
||||||
epoch=meta.get("epoch", 0),
|
epoch=meta.get("epoch", 0),
|
||||||
iteration=meta.get("iteration", 0),
|
consumed_samples=meta.get("consumed_samples", 0),
|
||||||
extra=extra,
|
extra=extra,
|
||||||
config=config,
|
config=config,
|
||||||
)
|
)
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
"""Dataset storage serialization helpers (HDF5 / memory-mapped binary)."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
|
import h5py
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
from torch import Tensor
|
||||||
|
|
||||||
|
|
||||||
|
def save_h5(file_path: str, file_name: str, tensor_group: Dict[str, List[Tensor]]):
|
||||||
|
os.makedirs(file_path, exist_ok=True)
|
||||||
|
full_file_path = os.path.join(file_path, f"{file_name}.h5")
|
||||||
|
with h5py.File(full_file_path, "w") as f:
|
||||||
|
for key, tensors in tensor_group.items():
|
||||||
|
grp = f.create_group(key)
|
||||||
|
for idx, tensor in enumerate(tensors):
|
||||||
|
arr = tensor.cpu().numpy()
|
||||||
|
grp.create_dataset(f"data_{idx}", data=arr)
|
||||||
|
|
||||||
|
|
||||||
|
def load_h5(file_path: str, share_memory=True) -> Dict[str, List[Tensor]]:
|
||||||
|
tensor_group: Dict[str, List[Tensor]] = {}
|
||||||
|
|
||||||
|
root_path = Path(file_path)
|
||||||
|
h5_files = list(root_path.rglob("*.h5")) + list(root_path.rglob("*.hdf5"))
|
||||||
|
|
||||||
|
for h5_file in h5_files:
|
||||||
|
with h5py.File(h5_file, "r") as f:
|
||||||
|
for key in f.keys():
|
||||||
|
grp = f[key]
|
||||||
|
dsets = []
|
||||||
|
for dset_name in grp.keys():
|
||||||
|
dset = grp[dset_name]
|
||||||
|
tensor = torch.from_numpy(dset[:])
|
||||||
|
if share_memory:
|
||||||
|
tensor = tensor.share_memory_()
|
||||||
|
dsets.append(tensor)
|
||||||
|
|
||||||
|
if tensor_group.get(key) is None:
|
||||||
|
tensor_group[key] = []
|
||||||
|
tensor_group[key].extend(dsets)
|
||||||
|
|
||||||
|
return tensor_group
|
||||||
|
|
||||||
|
|
||||||
|
def save_bin(file_path: str, tensor_group: Dict[str, List[Tensor]]):
|
||||||
|
os.makedirs(file_path, exist_ok=True)
|
||||||
|
meta = {}
|
||||||
|
for key, tensors in tensor_group.items():
|
||||||
|
cat = torch.cat(tensors, dim=0)
|
||||||
|
meta[key] = {"shape": list(cat.shape), "dtype": str(cat.dtype).split(".")[-1]}
|
||||||
|
np.asarray(cat.cpu().numpy()).tofile(os.path.join(file_path, f"{key}.bin"))
|
||||||
|
with open(os.path.join(file_path, "meta.json"), "w") as f:
|
||||||
|
json.dump(meta, f)
|
||||||
|
|
||||||
|
|
||||||
|
def load_bin(file_path: str) -> Dict[str, List[Tensor]]:
|
||||||
|
with open(os.path.join(file_path, "meta.json"), "r") as f:
|
||||||
|
meta = json.load(f)
|
||||||
|
segments: Dict[str, List[Tensor]] = {}
|
||||||
|
for key, info in meta.items():
|
||||||
|
arr = np.memmap(
|
||||||
|
os.path.join(file_path, f"{key}.bin"),
|
||||||
|
dtype=info["dtype"],
|
||||||
|
mode="r+",
|
||||||
|
shape=tuple(info["shape"]),
|
||||||
|
)
|
||||||
|
segments[key] = [torch.from_numpy(arr)]
|
||||||
|
return segments
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
from astrai.trainer.optim import Muon
|
|
||||||
from astrai.trainer.schedule import BaseScheduler, SchedulerFactory
|
from astrai.trainer.schedule import BaseScheduler, SchedulerFactory
|
||||||
from astrai.trainer.strategy import BaseStrategy, StrategyFactory
|
from astrai.trainer.strategy import BaseStrategy, StrategyFactory
|
||||||
from astrai.trainer.train_callback import (
|
from astrai.trainer.train_callback import (
|
||||||
@@ -10,8 +9,6 @@ from astrai.trainer.trainer import Trainer
|
|||||||
__all__ = [
|
__all__ = [
|
||||||
# Main trainer
|
# Main trainer
|
||||||
"Trainer",
|
"Trainer",
|
||||||
# Optimizer
|
|
||||||
"Muon",
|
|
||||||
# Strategy factory
|
# Strategy factory
|
||||||
"StrategyFactory",
|
"StrategyFactory",
|
||||||
"BaseStrategy",
|
"BaseStrategy",
|
||||||
|
|||||||
@@ -1,42 +1,25 @@
|
|||||||
from typing import Any, Callable, Dict
|
from typing import Dict
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
import torch.nn as nn
|
import torch.nn as nn
|
||||||
|
|
||||||
|
|
||||||
def _grad_stat(
|
def grad_norm(model: nn.Module, per_param: bool = False) -> float | Dict[str, float]:
|
||||||
model: nn.Module, fn: Callable[[torch.Tensor], Any], default: Any
|
grads = [p.grad.detach() for p in model.parameters() if p.grad is not None]
|
||||||
) -> dict:
|
if not grads:
|
||||||
results = {}
|
return 0.0
|
||||||
|
|
||||||
|
total_sq = torch.stack([g.pow(2).sum() for g in grads]).sum()
|
||||||
|
if per_param:
|
||||||
|
norms = {}
|
||||||
for name, param in model.named_parameters():
|
for name, param in model.named_parameters():
|
||||||
results[name] = default
|
|
||||||
if param.grad is not None:
|
if param.grad is not None:
|
||||||
results[name] = fn(param.grad.data)
|
norms[name] = param.grad.norm(2).item()
|
||||||
return results
|
else:
|
||||||
|
norms[name] = 0.0
|
||||||
|
norms["total"] = total_sq.sqrt().item()
|
||||||
def grad_norm(model: nn.Module, norm_type: int = 2) -> Dict[str, float]:
|
return norms
|
||||||
return _grad_stat(model, lambda g: g.norm(norm_type).item(), 0.0)
|
return total_sq.sqrt().item()
|
||||||
|
|
||||||
|
|
||||||
def grad_std(model: nn.Module) -> Dict[str, float]:
|
|
||||||
return _grad_stat(model, lambda g: g.std().item(), 0.0)
|
|
||||||
|
|
||||||
|
|
||||||
def grad_max(model: nn.Module) -> Dict[str, float]:
|
|
||||||
return _grad_stat(model, lambda g: g.max().item(), -float("inf"))
|
|
||||||
|
|
||||||
|
|
||||||
def grad_min(model: nn.Module) -> Dict[str, float]:
|
|
||||||
return _grad_stat(model, lambda g: g.min().item(), float("inf"))
|
|
||||||
|
|
||||||
|
|
||||||
def grad_mean(model: nn.Module) -> Dict[str, float]:
|
|
||||||
return _grad_stat(model, lambda g: g.mean().item(), 0.0)
|
|
||||||
|
|
||||||
|
|
||||||
def grad_nan_num(model: nn.Module) -> Dict[str, int]:
|
|
||||||
return _grad_stat(model, lambda g: g.isnan().sum().item(), 0)
|
|
||||||
|
|
||||||
|
|
||||||
def ctx_get_loss(ctx):
|
def ctx_get_loss(ctx):
|
||||||
@@ -52,24 +35,4 @@ def ctx_get_val_loss(ctx):
|
|||||||
|
|
||||||
|
|
||||||
def ctx_get_grad_norm(ctx):
|
def ctx_get_grad_norm(ctx):
|
||||||
return grad_norm(ctx.model)
|
return ctx.grad_norm
|
||||||
|
|
||||||
|
|
||||||
def ctx_get_grad_std(ctx):
|
|
||||||
return grad_std(ctx.model)
|
|
||||||
|
|
||||||
|
|
||||||
def ctx_get_grad_max(ctx):
|
|
||||||
return grad_max(ctx.model)
|
|
||||||
|
|
||||||
|
|
||||||
def ctx_get_grad_min(ctx):
|
|
||||||
return grad_min(ctx.model)
|
|
||||||
|
|
||||||
|
|
||||||
def ctx_get_grad_mean(ctx):
|
|
||||||
return grad_mean(ctx.model)
|
|
||||||
|
|
||||||
|
|
||||||
def ctx_get_grad_nan_num(ctx):
|
|
||||||
return grad_nan_num(ctx.model)
|
|
||||||
|
|||||||
@@ -1,143 +0,0 @@
|
|||||||
import torch
|
|
||||||
from torch.optim import Optimizer
|
|
||||||
|
|
||||||
|
|
||||||
def _zeropower_via_newtonschulz(G: torch.Tensor, steps: int = 5):
|
|
||||||
assert G.ndim == 2
|
|
||||||
X = G
|
|
||||||
scale = max(1, G.size(0) / G.size(1)) ** 0.5
|
|
||||||
X = X / (X.norm() + 1e-7) * scale
|
|
||||||
if steps == 0:
|
|
||||||
return X
|
|
||||||
a, b, c = (3.4445, -4.7750, 2.0315)
|
|
||||||
for _ in range(steps):
|
|
||||||
A = X @ X.T
|
|
||||||
B = A @ X
|
|
||||||
X = a * X + b * B + c * (A @ B)
|
|
||||||
return X
|
|
||||||
|
|
||||||
|
|
||||||
class Muon(Optimizer):
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
params,
|
|
||||||
lr: float = 2e-3,
|
|
||||||
momentum: float = 0.95,
|
|
||||||
weight_decay: float = 0.0,
|
|
||||||
nesterov: bool = True,
|
|
||||||
ns_steps: int = 5,
|
|
||||||
adamw_lr: float = None,
|
|
||||||
adamw_betas: tuple = (0.9, 0.95),
|
|
||||||
adamw_eps: float = 1e-8,
|
|
||||||
adamw_wd: float = 0.0,
|
|
||||||
):
|
|
||||||
defaults = dict(
|
|
||||||
lr=lr,
|
|
||||||
momentum=momentum,
|
|
||||||
weight_decay=weight_decay,
|
|
||||||
nesterov=nesterov,
|
|
||||||
ns_steps=ns_steps,
|
|
||||||
adamw_lr=adamw_lr if adamw_lr is not None else lr * 0.1,
|
|
||||||
adamw_betas=adamw_betas,
|
|
||||||
adamw_eps=adamw_eps,
|
|
||||||
adamw_wd=adamw_wd,
|
|
||||||
)
|
|
||||||
super().__init__(params, defaults)
|
|
||||||
|
|
||||||
@torch.no_grad()
|
|
||||||
def step(self, closure=None):
|
|
||||||
loss = None
|
|
||||||
if closure is not None:
|
|
||||||
with torch.enable_grad():
|
|
||||||
loss = closure()
|
|
||||||
|
|
||||||
for group in self.param_groups:
|
|
||||||
params_2d, params_1d = [], []
|
|
||||||
grads_2d, grads_1d = [], []
|
|
||||||
|
|
||||||
for p in group["params"]:
|
|
||||||
if p.grad is None:
|
|
||||||
continue
|
|
||||||
if p.grad.is_sparse:
|
|
||||||
raise RuntimeError("Muon does not support sparse gradients")
|
|
||||||
if p.ndim >= 2:
|
|
||||||
params_2d.append(p)
|
|
||||||
grads_2d.append(p.grad)
|
|
||||||
else:
|
|
||||||
params_1d.append(p)
|
|
||||||
grads_1d.append(p.grad)
|
|
||||||
|
|
||||||
if params_2d:
|
|
||||||
self._muon_update_foreach(params_2d, grads_2d, group)
|
|
||||||
if params_1d:
|
|
||||||
self._adamw_update_foreach(params_1d, grads_1d, group)
|
|
||||||
|
|
||||||
return loss
|
|
||||||
|
|
||||||
def _muon_update_foreach(self, params_2d, grads_2d, group):
|
|
||||||
lr = group["lr"]
|
|
||||||
momentum = group["momentum"]
|
|
||||||
wd = group["weight_decay"]
|
|
||||||
nesterov = group["nesterov"]
|
|
||||||
ns_steps = group["ns_steps"]
|
|
||||||
|
|
||||||
if wd != 0:
|
|
||||||
torch._foreach_mul_(params_2d, 1 - lr * wd)
|
|
||||||
|
|
||||||
if nesterov:
|
|
||||||
grads_2d = torch._foreach_add(grads_2d, params_2d, alpha=wd)
|
|
||||||
|
|
||||||
bufs = []
|
|
||||||
for p, grad in zip(params_2d, grads_2d):
|
|
||||||
state = self.state[p]
|
|
||||||
if "momentum_buffer" not in state:
|
|
||||||
state["momentum_buffer"] = torch.zeros_like(grad)
|
|
||||||
bufs.append(state["momentum_buffer"])
|
|
||||||
|
|
||||||
torch._foreach_lerp_(bufs, grads_2d, 1 - momentum)
|
|
||||||
|
|
||||||
for p, buf in zip(params_2d, bufs):
|
|
||||||
update = _zeropower_via_newtonschulz(buf, steps=ns_steps)
|
|
||||||
scale = max(1, p.size(0) / p.size(1)) ** 0.5
|
|
||||||
p.add_(update, alpha=-lr * scale)
|
|
||||||
|
|
||||||
def _adamw_update_foreach(self, params_1d, grads_1d, group):
|
|
||||||
lr = group["adamw_lr"]
|
|
||||||
betas = group["adamw_betas"]
|
|
||||||
eps = group["adamw_eps"]
|
|
||||||
wd = group["adamw_wd"]
|
|
||||||
|
|
||||||
steps: list[int] = []
|
|
||||||
exp_avgs, exp_avg_sqs = [], []
|
|
||||||
has_state = []
|
|
||||||
for p in params_1d:
|
|
||||||
state = self.state[p]
|
|
||||||
if not state:
|
|
||||||
state["step"] = 0
|
|
||||||
state["exp_avg"] = torch.zeros_like(p)
|
|
||||||
state["exp_avg_sq"] = torch.zeros_like(p)
|
|
||||||
has_state.append(False)
|
|
||||||
else:
|
|
||||||
has_state.append(True)
|
|
||||||
state["step"] += 1
|
|
||||||
steps.append(state["step"])
|
|
||||||
exp_avgs.append(state["exp_avg"])
|
|
||||||
exp_avg_sqs.append(state["exp_avg_sq"])
|
|
||||||
|
|
||||||
beta1, beta2 = betas
|
|
||||||
|
|
||||||
torch._foreach_lerp_(exp_avgs, grads_1d, 1 - beta1)
|
|
||||||
grads_sq = torch._foreach_mul(grads_1d, grads_1d)
|
|
||||||
torch._foreach_lerp_(exp_avg_sqs, grads_sq, 1 - beta2)
|
|
||||||
|
|
||||||
bias_correction1 = [1 - beta1**s for s in steps]
|
|
||||||
bias_correction2 = [1 - beta2**s for s in steps]
|
|
||||||
|
|
||||||
if wd != 0:
|
|
||||||
torch._foreach_mul_(params_1d, 1 - lr * wd)
|
|
||||||
|
|
||||||
exp_avg_corrected = torch._foreach_div(exp_avgs, bias_correction1)
|
|
||||||
denom = torch._foreach_div(exp_avg_sqs, bias_correction2)
|
|
||||||
denom = torch._foreach_sqrt(denom)
|
|
||||||
torch._foreach_add_(denom, eps)
|
|
||||||
torch._foreach_addcdiv_(params_1d, exp_avg_corrected, denom, value=-lr)
|
|
||||||
@@ -53,7 +53,7 @@ class CosineScheduler(BaseScheduler):
|
|||||||
optimizer,
|
optimizer,
|
||||||
warmup_steps: int,
|
warmup_steps: int,
|
||||||
lr_decay_steps: int,
|
lr_decay_steps: int,
|
||||||
min_rate: float = 0.05,
|
min_rate: float = 0.01,
|
||||||
last_epoch: int = -1,
|
last_epoch: int = -1,
|
||||||
):
|
):
|
||||||
self.warmup_steps = warmup_steps
|
self.warmup_steps = warmup_steps
|
||||||
@@ -65,11 +65,15 @@ class CosineScheduler(BaseScheduler):
|
|||||||
def get_lr(self) -> List[float]:
|
def get_lr(self) -> List[float]:
|
||||||
# warmup
|
# warmup
|
||||||
if self.last_epoch < self.warmup_steps:
|
if self.last_epoch < self.warmup_steps:
|
||||||
warmup_factor = max(self.min_rate, self.last_epoch / self.warmup_steps)
|
warmup_factor = max(
|
||||||
|
self.min_rate, self.last_epoch / max(self.warmup_steps, 1)
|
||||||
|
)
|
||||||
return [base_lr * warmup_factor for base_lr in self.base_lrs]
|
return [base_lr * warmup_factor for base_lr in self.base_lrs]
|
||||||
|
|
||||||
# cosine decay
|
# cosine decay
|
||||||
decay_progress = (self.last_epoch - self.warmup_steps) / self.lr_decay_steps
|
decay_progress = (self.last_epoch - self.warmup_steps) / max(
|
||||||
|
self.lr_decay_steps, 1
|
||||||
|
)
|
||||||
decay_progress = min(decay_progress, 1.0)
|
decay_progress = min(decay_progress, 1.0)
|
||||||
cosine_decay = 0.5 * (1.0 + math.cos(math.pi * decay_progress))
|
cosine_decay = 0.5 * (1.0 + math.cos(math.pi * decay_progress))
|
||||||
decay_factor = max(self.min_rate, cosine_decay)
|
decay_factor = max(self.min_rate, cosine_decay)
|
||||||
@@ -104,7 +108,7 @@ class SGDRScheduler(BaseScheduler):
|
|||||||
optimizer,
|
optimizer,
|
||||||
warmup_steps: int,
|
warmup_steps: int,
|
||||||
cycle_length: int,
|
cycle_length: int,
|
||||||
min_rate: float = 0.05,
|
min_rate: float = 0.01,
|
||||||
t_mult: int = 2,
|
t_mult: int = 2,
|
||||||
last_epoch: int = -1,
|
last_epoch: int = -1,
|
||||||
):
|
):
|
||||||
@@ -118,7 +122,9 @@ class SGDRScheduler(BaseScheduler):
|
|||||||
def get_lr(self):
|
def get_lr(self):
|
||||||
# warmup
|
# warmup
|
||||||
if self.last_epoch < self.warmup_steps:
|
if self.last_epoch < self.warmup_steps:
|
||||||
warmup_factor = max(self.min_rate, self.last_epoch / self.warmup_steps)
|
warmup_factor = max(
|
||||||
|
self.min_rate, self.last_epoch / max(self.warmup_steps, 1)
|
||||||
|
)
|
||||||
return [base_lr * warmup_factor for base_lr in self.base_lrs]
|
return [base_lr * warmup_factor for base_lr in self.base_lrs]
|
||||||
|
|
||||||
# SGDR
|
# SGDR
|
||||||
@@ -164,3 +170,66 @@ class SGDRScheduler(BaseScheduler):
|
|||||||
self.min_rate = state_dict.pop("min_rate")
|
self.min_rate = state_dict.pop("min_rate")
|
||||||
self.t_mult = state_dict.pop("t_mult")
|
self.t_mult = state_dict.pop("t_mult")
|
||||||
super().load_state_dict(state_dict)
|
super().load_state_dict(state_dict)
|
||||||
|
|
||||||
|
|
||||||
|
@SchedulerFactory.register("wsd")
|
||||||
|
class WSDScheduler(BaseScheduler):
|
||||||
|
"""WSD (Warmup-Stable-Decay) scheduler with sqrt cooldown.
|
||||||
|
|
||||||
|
warmup_steps: linear warmup from min_rate to 1.0
|
||||||
|
stable_steps: constant at base_lr
|
||||||
|
decay_steps: sqrt decay from base_lr to min_rate
|
||||||
|
min_rate: minimum lr as fraction of base_lr (default 0.0)
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
optimizer,
|
||||||
|
warmup_steps: int,
|
||||||
|
stable_steps: int,
|
||||||
|
decay_steps: int,
|
||||||
|
min_rate: float = 0.01,
|
||||||
|
last_epoch: int = -1,
|
||||||
|
):
|
||||||
|
self.warmup_steps = warmup_steps
|
||||||
|
self.stable_steps = stable_steps
|
||||||
|
self.decay_steps = decay_steps
|
||||||
|
self.min_rate = min_rate
|
||||||
|
self.total_steps = warmup_steps + stable_steps + decay_steps
|
||||||
|
super().__init__(optimizer, last_epoch)
|
||||||
|
|
||||||
|
def get_lr(self) -> List[float]:
|
||||||
|
if self.last_epoch < self.warmup_steps:
|
||||||
|
factor = max(self.min_rate, self.last_epoch / max(self.warmup_steps, 1))
|
||||||
|
return [base_lr * factor for base_lr in self.base_lrs]
|
||||||
|
|
||||||
|
offset = self.last_epoch - self.warmup_steps
|
||||||
|
|
||||||
|
if offset < self.stable_steps:
|
||||||
|
return list(self.base_lrs)
|
||||||
|
|
||||||
|
decay_ratio = (offset - self.stable_steps) / max(self.decay_steps, 1)
|
||||||
|
decay_ratio = min(decay_ratio, 1.0)
|
||||||
|
factor = (1.0 - self.min_rate) * (1.0 - decay_ratio) ** 2 + self.min_rate
|
||||||
|
return [base_lr * factor for base_lr in self.base_lrs]
|
||||||
|
|
||||||
|
def state_dict(self):
|
||||||
|
state = super().state_dict()
|
||||||
|
state.update(
|
||||||
|
{
|
||||||
|
"warmup_steps": self.warmup_steps,
|
||||||
|
"stable_steps": self.stable_steps,
|
||||||
|
"decay_steps": self.decay_steps,
|
||||||
|
"min_rate": self.min_rate,
|
||||||
|
"total_steps": self.total_steps,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return state
|
||||||
|
|
||||||
|
def load_state_dict(self, state_dict):
|
||||||
|
self.warmup_steps = state_dict.pop("warmup_steps")
|
||||||
|
self.stable_steps = state_dict.pop("stable_steps")
|
||||||
|
self.decay_steps = state_dict.pop("decay_steps")
|
||||||
|
self.min_rate = state_dict.pop("min_rate")
|
||||||
|
self.total_steps = state_dict.pop("total_steps")
|
||||||
|
super().load_state_dict(state_dict)
|
||||||
|
|||||||
@@ -196,7 +196,7 @@ class SFTStrategy(BaseStrategy):
|
|||||||
|
|
||||||
ignore_index = -100
|
ignore_index = -100
|
||||||
input_mask = make_doc_boundary_mask(position_ids)
|
input_mask = make_doc_boundary_mask(position_ids)
|
||||||
target_ids = target_ids.masked_fill(loss_mask == 0, ignore_index)
|
target_ids = target_ids.masked_fill(~loss_mask, ignore_index)
|
||||||
logits = self.model(
|
logits = self.model(
|
||||||
input_ids=input_ids, position_ids=position_ids, input_mask=input_mask
|
input_ids=input_ids, position_ids=position_ids, input_mask=input_mask
|
||||||
)["logits"]
|
)["logits"]
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ from typing import IO, Callable, List, Optional, Protocol, runtime_checkable
|
|||||||
import torch
|
import torch
|
||||||
import torch.distributed as dist
|
import torch.distributed as dist
|
||||||
import torch.nn as nn
|
import torch.nn as nn
|
||||||
from torch.nn.utils import clip_grad_norm_
|
|
||||||
from torch.utils.checkpoint import checkpoint as torch_checkpoint
|
from torch.utils.checkpoint import checkpoint as torch_checkpoint
|
||||||
from tqdm import tqdm
|
from tqdm import tqdm
|
||||||
|
|
||||||
@@ -18,12 +17,7 @@ from astrai.parallel import only_on_rank
|
|||||||
from astrai.parallel.setup import get_current_device, get_rank
|
from astrai.parallel.setup import get_current_device, get_rank
|
||||||
from astrai.serialization import Checkpoint
|
from astrai.serialization import Checkpoint
|
||||||
from astrai.trainer.metric_util import (
|
from astrai.trainer.metric_util import (
|
||||||
ctx_get_grad_max,
|
|
||||||
ctx_get_grad_mean,
|
|
||||||
ctx_get_grad_min,
|
|
||||||
ctx_get_grad_nan_num,
|
|
||||||
ctx_get_grad_norm,
|
ctx_get_grad_norm,
|
||||||
ctx_get_grad_std,
|
|
||||||
ctx_get_loss,
|
ctx_get_loss,
|
||||||
ctx_get_lr,
|
ctx_get_lr,
|
||||||
ctx_get_val_loss,
|
ctx_get_val_loss,
|
||||||
@@ -86,7 +80,9 @@ class GradientClippingCallback(TrainCallback):
|
|||||||
self.max_grad_norm = max_grad_norm
|
self.max_grad_norm = max_grad_norm
|
||||||
|
|
||||||
def on_optimizer_step(self, context: TrainContext):
|
def on_optimizer_step(self, context: TrainContext):
|
||||||
clip_grad_norm_(context.model.parameters(), self.max_grad_norm)
|
context.grad_norm = context.executor.clip_grad_norm(
|
||||||
|
context.model, self.max_grad_norm
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@CallbackFactory.register("gradient_checkpointing")
|
@CallbackFactory.register("gradient_checkpointing")
|
||||||
@@ -143,34 +139,35 @@ class CheckpointCallback(TrainCallback):
|
|||||||
self.interval = interval
|
self.interval = interval
|
||||||
self.weight_only = weight_only
|
self.weight_only = weight_only
|
||||||
self.save_extra_fn = save_extra_fn or CheckpointCallback.save_extra
|
self.save_extra_fn = save_extra_fn or CheckpointCallback.save_extra
|
||||||
self.last_ckpt_iter = 0
|
self.last_ckpt_step = 0
|
||||||
|
|
||||||
def _save_checkpoint(self, context: TrainContext):
|
def _save_checkpoint(self, context: TrainContext):
|
||||||
state_dict = context.executor.unwrap_model(context.model)
|
state_dict = context.executor.unwrap_model(context.model)
|
||||||
self.last_ckpt_iter = context.iteration
|
self.last_ckpt_step = context.optimizer_step
|
||||||
|
|
||||||
if get_rank() == 0:
|
if get_rank() == 0:
|
||||||
save_path = os.path.join(
|
save_path = os.path.join(
|
||||||
self.save_dir, f"epoch_{context.epoch}_iter_{context.iteration}"
|
self.save_dir,
|
||||||
|
f"epoch_{context.epoch}_step_{context.optimizer_step}",
|
||||||
)
|
)
|
||||||
extra = self.save_extra_fn(context)
|
extra = self.save_extra_fn(context)
|
||||||
meta = context.config.to_dict()
|
meta = context.config.to_dict()
|
||||||
context.checkpoint = Checkpoint(
|
context.checkpoint = Checkpoint(
|
||||||
state_dict=state_dict,
|
state_dict=state_dict,
|
||||||
epoch=context.epoch,
|
epoch=context.epoch,
|
||||||
iteration=context.iteration,
|
consumed_samples=context.consumed_samples,
|
||||||
|
config=context.model_config,
|
||||||
extra=extra,
|
extra=extra,
|
||||||
meta=meta,
|
meta=meta,
|
||||||
config=context.model_config,
|
|
||||||
)
|
)
|
||||||
context.checkpoint.save(save_path)
|
context.checkpoint.save(save_path)
|
||||||
|
|
||||||
def on_batch_end(self, context: TrainContext):
|
def on_batch_end(self, context: TrainContext):
|
||||||
if context.iteration - self.last_ckpt_iter >= self.interval:
|
if context.optimizer_step - self.last_ckpt_step >= self.interval:
|
||||||
self._save_checkpoint(context)
|
self._save_checkpoint(context)
|
||||||
|
|
||||||
def on_train_end(self, context: TrainContext):
|
def on_train_end(self, context: TrainContext):
|
||||||
if context.iteration != self.last_ckpt_iter:
|
if context.optimizer_step != self.last_ckpt_step:
|
||||||
self._save_checkpoint(context)
|
self._save_checkpoint(context)
|
||||||
|
|
||||||
def on_error(self, context: TrainContext):
|
def on_error(self, context: TrainContext):
|
||||||
@@ -202,23 +199,27 @@ class ProgressBarCallback(TrainCallback):
|
|||||||
|
|
||||||
@only_on_rank(0)
|
@only_on_rank(0)
|
||||||
def on_epoch_begin(self, context: TrainContext):
|
def on_epoch_begin(self, context: TrainContext):
|
||||||
|
total_steps = len(context.dataloader) // context.executor.grad_accum_steps
|
||||||
self.progress_bar = tqdm(
|
self.progress_bar = tqdm(
|
||||||
context.dataloader,
|
total=total_steps,
|
||||||
desc=f"Epoch {context.epoch + 1}/{self.num_epoch}",
|
desc=f"Epoch {context.epoch + 1}/{self.num_epoch}",
|
||||||
dynamic_ncols=True,
|
dynamic_ncols=True,
|
||||||
file=self.file or sys.stdout,
|
file=self.file or sys.stdout,
|
||||||
)
|
)
|
||||||
|
|
||||||
@only_on_rank(0)
|
@only_on_rank(0)
|
||||||
def on_batch_end(self, context: TrainContext):
|
def on_optimizer_step(self, context: TrainContext):
|
||||||
|
self.progress_bar.update(1)
|
||||||
postfix = {
|
postfix = {
|
||||||
|
"step": context.optimizer_step,
|
||||||
"loss": f"{context.loss:.4f}",
|
"loss": f"{context.loss:.4f}",
|
||||||
"lr": f"{context.optimizer.param_groups[-1]['lr']:.2e}",
|
"lr": f"{context.optimizer.param_groups[-1]['lr']:.2e}",
|
||||||
}
|
}
|
||||||
|
if context.grad_norm is not None:
|
||||||
|
postfix["grad_norm"] = f"{context.grad_norm:.2f}"
|
||||||
if context.val_loss is not None:
|
if context.val_loss is not None:
|
||||||
postfix["val_loss"] = f"{context.val_loss:.4f}"
|
postfix["val_loss"] = f"{context.val_loss:.4f}"
|
||||||
self.progress_bar.set_postfix(postfix)
|
self.progress_bar.set_postfix(postfix)
|
||||||
self.progress_bar.update(1)
|
|
||||||
|
|
||||||
@only_on_rank(0)
|
@only_on_rank(0)
|
||||||
def on_epoch_end(self, context: TrainContext):
|
def on_epoch_end(self, context: TrainContext):
|
||||||
@@ -227,19 +228,20 @@ class ProgressBarCallback(TrainCallback):
|
|||||||
self.progress_bar.close()
|
self.progress_bar.close()
|
||||||
|
|
||||||
|
|
||||||
@CallbackFactory.register("metric_logger")
|
@CallbackFactory.register("metric")
|
||||||
class MetricLoggerCallback(TrainCallback):
|
class MetricCallback(TrainCallback):
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
log_dir: str,
|
log_dir: str,
|
||||||
save_interval: int,
|
save_interval: int,
|
||||||
log_interval: int = 10,
|
|
||||||
metrics: List[str] = None,
|
metrics: List[str] = None,
|
||||||
|
val_step: int = 0,
|
||||||
):
|
):
|
||||||
self.last_log_iter = 0
|
self.last_log_flush_step = 0
|
||||||
self.save_interval = save_interval
|
self.save_interval = save_interval
|
||||||
self.log_interval = log_interval
|
|
||||||
self.metrics = metrics or ["loss", "lr"]
|
self.metrics = metrics or ["loss", "lr"]
|
||||||
|
self.val_step = val_step
|
||||||
|
self._next_val_step = 0
|
||||||
|
|
||||||
self.log_dir = Path(log_dir) if log_dir else Path.cwd() / "logs"
|
self.log_dir = Path(log_dir) if log_dir else Path.cwd() / "logs"
|
||||||
self.log_dir.mkdir(parents=True, exist_ok=True)
|
self.log_dir.mkdir(parents=True, exist_ok=True)
|
||||||
@@ -251,58 +253,28 @@ class MetricLoggerCallback(TrainCallback):
|
|||||||
"lr": ctx_get_lr,
|
"lr": ctx_get_lr,
|
||||||
"val_loss": ctx_get_val_loss,
|
"val_loss": ctx_get_val_loss,
|
||||||
"grad_norm": ctx_get_grad_norm,
|
"grad_norm": ctx_get_grad_norm,
|
||||||
"grad_std": ctx_get_grad_std,
|
|
||||||
"grad_max": ctx_get_grad_max,
|
|
||||||
"grad_min": ctx_get_grad_min,
|
|
||||||
"grad_mean": ctx_get_grad_mean,
|
|
||||||
"grad_nan_num": ctx_get_grad_nan_num,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
def _get_log_data(self, context: TrainContext):
|
def _metrics(self, context: TrainContext, names):
|
||||||
data = {
|
return {
|
||||||
|
m: self._metric_funcs[m](context)
|
||||||
|
for m in names
|
||||||
|
if self._metric_funcs[m](context) is not None
|
||||||
|
}
|
||||||
|
|
||||||
|
@only_on_rank(0)
|
||||||
|
def _append(self, event_type: str, context: TrainContext, **extra):
|
||||||
|
entry = {
|
||||||
|
"type": event_type,
|
||||||
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
||||||
"epoch": context.epoch,
|
"epoch": context.epoch,
|
||||||
"iter": context.iteration,
|
"step": context.optimizer_step,
|
||||||
|
"consumed_samples": context.consumed_samples,
|
||||||
|
**extra,
|
||||||
}
|
}
|
||||||
for m in self.metrics:
|
self.log_cache.append(entry)
|
||||||
val = self._metric_funcs[m](context)
|
|
||||||
if val is not None:
|
|
||||||
data[m] = val
|
|
||||||
return data
|
|
||||||
|
|
||||||
@only_on_rank(0)
|
def _run_validation(self, context: TrainContext) -> float:
|
||||||
def _add_log(self, log_data):
|
|
||||||
self.log_cache.append(log_data)
|
|
||||||
|
|
||||||
@only_on_rank(0)
|
|
||||||
def _save_log(self, epoch, iter):
|
|
||||||
log_file = self.log_dir / f"epoch_{epoch}_iter_{iter}_metric.jsonl"
|
|
||||||
log_file.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
|
|
||||||
with open(log_file, "w") as f:
|
|
||||||
for log in self.log_cache:
|
|
||||||
f.write(json.dumps(log) + "\n")
|
|
||||||
|
|
||||||
def on_batch_end(self, context):
|
|
||||||
if context.iteration % self.log_interval == 0:
|
|
||||||
log_data = self._get_log_data(context)
|
|
||||||
self._add_log(log_data)
|
|
||||||
|
|
||||||
if context.iteration - self.last_log_iter >= self.save_interval:
|
|
||||||
self._save_log(context.epoch, context.iteration)
|
|
||||||
self.last_log_iter = context.iteration
|
|
||||||
|
|
||||||
def on_train_end(self, context):
|
|
||||||
if context.iteration != self.last_log_iter:
|
|
||||||
self._save_log(context.epoch, context.iteration)
|
|
||||||
|
|
||||||
def on_error(self, context):
|
|
||||||
self._save_log(context.epoch, context.iteration)
|
|
||||||
|
|
||||||
|
|
||||||
@CallbackFactory.register("validation")
|
|
||||||
class ValidationCallback(TrainCallback):
|
|
||||||
def _run_validation(self, context: TrainContext):
|
|
||||||
context.model.eval()
|
context.model.eval()
|
||||||
|
|
||||||
total_loss = 0.0
|
total_loss = 0.0
|
||||||
@@ -314,27 +286,49 @@ class ValidationCallback(TrainCallback):
|
|||||||
total_loss += loss.item()
|
total_loss += loss.item()
|
||||||
num_batches += 1
|
num_batches += 1
|
||||||
|
|
||||||
|
if context.world_size > 1 and dist.is_initialized():
|
||||||
|
stats = torch.tensor(
|
||||||
|
[total_loss, float(num_batches)], device=get_current_device()
|
||||||
|
)
|
||||||
|
dist.all_reduce(stats, op=dist.ReduceOp.SUM)
|
||||||
|
avg_loss = (stats[0] / stats[1]).item()
|
||||||
|
else:
|
||||||
avg_loss = total_loss / max(num_batches, 1)
|
avg_loss = total_loss / max(num_batches, 1)
|
||||||
|
|
||||||
if context.world_size > 1 and dist.is_initialized():
|
|
||||||
loss_tensor = torch.tensor([avg_loss], device=get_current_device())
|
|
||||||
dist.all_reduce(loss_tensor, op=dist.ReduceOp.AVG)
|
|
||||||
avg_loss = loss_tensor.item()
|
|
||||||
|
|
||||||
context.val_loss = avg_loss
|
|
||||||
context.model.train()
|
context.model.train()
|
||||||
|
return avg_loss
|
||||||
|
|
||||||
step_count = context.iteration // context.config.grad_accum_steps
|
@only_on_rank(0)
|
||||||
logger.info(
|
def _flush(self, epoch, step):
|
||||||
f"Epoch {context.epoch + 1}, Step {step_count}, Val Loss: {avg_loss:.4f}"
|
log_file = self.log_dir / f"epoch_{epoch}_step_{step}_metric.jsonl"
|
||||||
)
|
log_file.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with open(log_file, "w") as f:
|
||||||
|
for log in self.log_cache:
|
||||||
|
f.write(json.dumps(log) + "\n")
|
||||||
|
|
||||||
def on_optimizer_step(self, context: TrainContext):
|
def on_optimizer_step(self, context):
|
||||||
if context.val_dataloader is None:
|
if (
|
||||||
return
|
context.val_dataloader is not None
|
||||||
cfg = context.config
|
and self.val_step > 0
|
||||||
if cfg.val_step <= 0:
|
and context.optimizer_step >= self._next_val_step
|
||||||
return
|
):
|
||||||
step_count = context.iteration // cfg.grad_accum_steps
|
context.val_loss = self._run_validation(context)
|
||||||
if step_count % cfg.val_step == 0:
|
self._next_val_step = context.optimizer_step + self.val_step
|
||||||
self._run_validation(context)
|
self._append("validation", context, val_loss=context.val_loss)
|
||||||
|
|
||||||
|
step_metrics = [m for m in self.metrics if m != "val_loss"]
|
||||||
|
self._append("step", context, **self._metrics(context, step_metrics))
|
||||||
|
|
||||||
|
if context.optimizer_step - self.last_log_flush_step >= self.save_interval:
|
||||||
|
self._flush(context.epoch, context.optimizer_step)
|
||||||
|
self.last_log_flush_step = context.optimizer_step
|
||||||
|
|
||||||
|
def on_epoch_end(self, context):
|
||||||
|
self._append("epoch", context)
|
||||||
|
|
||||||
|
def on_train_end(self, context):
|
||||||
|
if context.optimizer_step != self.last_log_flush_step:
|
||||||
|
self._flush(context.epoch, context.optimizer_step)
|
||||||
|
|
||||||
|
def on_error(self, context):
|
||||||
|
self._flush(context.epoch, context.optimizer_step)
|
||||||
|
|||||||
@@ -29,8 +29,9 @@ class TrainContext:
|
|||||||
executor: BaseExecutor = field(default=None)
|
executor: BaseExecutor = field(default=None)
|
||||||
|
|
||||||
epoch: int = field(default=0)
|
epoch: int = field(default=0)
|
||||||
iteration: int = field(default=0)
|
consumed_samples: int = field(default=0)
|
||||||
loss: float = field(default=0.0)
|
loss: float = field(default=0.0)
|
||||||
|
grad_norm: Optional[float] = field(default=None)
|
||||||
val_dataloader: Optional[DataLoader] = field(default=None)
|
val_dataloader: Optional[DataLoader] = field(default=None)
|
||||||
val_loss: Optional[float] = field(default=None)
|
val_loss: Optional[float] = field(default=None)
|
||||||
|
|
||||||
@@ -38,6 +39,14 @@ class TrainContext:
|
|||||||
rank: int = field(default=0)
|
rank: int = field(default=0)
|
||||||
kwargs: Dict[str, Any] = field(default_factory=dict)
|
kwargs: Dict[str, Any] = field(default_factory=dict)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def optimizer_step(self) -> int:
|
||||||
|
return self.consumed_samples // (
|
||||||
|
self.config.batch_per_device
|
||||||
|
* self.world_size
|
||||||
|
* self.config.grad_accum_steps
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class TrainContextBuilder:
|
class TrainContextBuilder:
|
||||||
def __init__(
|
def __init__(
|
||||||
@@ -63,7 +72,6 @@ class TrainContextBuilder:
|
|||||||
|
|
||||||
model = cfg.model_fn()
|
model = cfg.model_fn()
|
||||||
model = model.to(device=device)
|
model = model.to(device=device)
|
||||||
model.embed_tokens.neftune_noise_alpha = cfg.neftune_alpha
|
|
||||||
|
|
||||||
model_config = {}
|
model_config = {}
|
||||||
if self._resume_dir:
|
if self._resume_dir:
|
||||||
@@ -90,7 +98,10 @@ class TrainContextBuilder:
|
|||||||
if checkpoint.config:
|
if checkpoint.config:
|
||||||
context.model_config = checkpoint.config
|
context.model_config = checkpoint.config
|
||||||
context.epoch = checkpoint.epoch or cfg.start_epoch
|
context.epoch = checkpoint.epoch or cfg.start_epoch
|
||||||
context.iteration = checkpoint.iteration or cfg.start_batch
|
if checkpoint.consumed_samples > 0:
|
||||||
|
context.consumed_samples = checkpoint.consumed_samples
|
||||||
|
else:
|
||||||
|
context.consumed_samples = cfg.start_samples * context.world_size
|
||||||
context.checkpoint = checkpoint
|
context.checkpoint = checkpoint
|
||||||
|
|
||||||
if cfg.lora is not None:
|
if cfg.lora is not None:
|
||||||
@@ -116,7 +127,7 @@ class TrainContextBuilder:
|
|||||||
cfg.dataset, [n_train, n_val], generator=generator
|
cfg.dataset, [n_train, n_val], generator=generator
|
||||||
)
|
)
|
||||||
|
|
||||||
sampler_offset = context.iteration * cfg.batch_per_device
|
sampler_offset = context.consumed_samples // context.world_size
|
||||||
sampler = ResumableDistributedSampler(
|
sampler = ResumableDistributedSampler(
|
||||||
data_source=train_dataset,
|
data_source=train_dataset,
|
||||||
start_epoch=context.epoch,
|
start_epoch=context.epoch,
|
||||||
|
|||||||
@@ -35,15 +35,14 @@ class Trainer:
|
|||||||
cfg.ckpt_interval,
|
cfg.ckpt_interval,
|
||||||
),
|
),
|
||||||
CallbackFactory.create(
|
CallbackFactory.create(
|
||||||
"metric_logger",
|
"metric",
|
||||||
log_dir=cfg.log_dir,
|
log_dir=cfg.log_dir,
|
||||||
save_interval=cfg.ckpt_interval,
|
save_interval=cfg.ckpt_interval,
|
||||||
log_interval=cfg.log_interval,
|
|
||||||
metrics=cfg.metrics,
|
metrics=cfg.metrics,
|
||||||
|
val_step=cfg.val_step,
|
||||||
),
|
),
|
||||||
CallbackFactory.create("progress_bar", cfg.n_epoch),
|
CallbackFactory.create("progress_bar", cfg.n_epoch),
|
||||||
CallbackFactory.create("gradient_clipping", cfg.max_grad_norm),
|
CallbackFactory.create("gradient_clipping", cfg.max_grad_norm),
|
||||||
CallbackFactory.create("validation"),
|
|
||||||
]
|
]
|
||||||
return callbacks
|
return callbacks
|
||||||
|
|
||||||
@@ -74,7 +73,9 @@ class Trainer:
|
|||||||
context.loss = loss.item()
|
context.loss = loss.item()
|
||||||
stand_loss = loss / executor.grad_accum_steps
|
stand_loss = loss / executor.grad_accum_steps
|
||||||
executor.backward(stand_loss)
|
executor.backward(stand_loss)
|
||||||
context.iteration += 1
|
context.consumed_samples += (
|
||||||
|
context.config.batch_per_device * context.world_size
|
||||||
|
)
|
||||||
self._call_callbacks("on_batch_end", context)
|
self._call_callbacks("on_batch_end", context)
|
||||||
|
|
||||||
if executor.sync_gradients:
|
if executor.sync_gradients:
|
||||||
|
|||||||
+3
-3
@@ -9,8 +9,8 @@ readme = "README.md"
|
|||||||
requires-python = ">=3.12"
|
requires-python = ">=3.12"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"h5py==3.15.1",
|
"h5py==3.15.1",
|
||||||
"numpy==2.3.2",
|
"numpy==2.4.4",
|
||||||
"torch==2.7.1",
|
"torch==2.11.0",
|
||||||
"tokenizers==0.21.4",
|
"tokenizers==0.21.4",
|
||||||
"tqdm==4.67.1",
|
"tqdm==4.67.1",
|
||||||
"safetensors==0.5.3",
|
"safetensors==0.5.3",
|
||||||
@@ -37,7 +37,7 @@ dev = ["pytest==9.0.2", "ruff"]
|
|||||||
where = ["."]
|
where = ["."]
|
||||||
|
|
||||||
[tool.pip]
|
[tool.pip]
|
||||||
extra-index-url = "https://download.pytorch.org/whl/cu126"
|
extra-index-url = "https://download.pytorch.org/whl/cu128"
|
||||||
|
|
||||||
[tool.setuptools.dynamic]
|
[tool.setuptools.dynamic]
|
||||||
version = { attr = "astrai.__version__" }
|
version = { attr = "astrai.__version__" }
|
||||||
|
|||||||
+53
-12
@@ -1,3 +1,4 @@
|
|||||||
|
from argparse import ArgumentParser
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
@@ -7,42 +8,82 @@ from astrai.model import AutoModel
|
|||||||
from astrai.tokenize import AutoTokenizer
|
from astrai.tokenize import AutoTokenizer
|
||||||
|
|
||||||
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
||||||
PARAMETER_ROOT = Path(PROJECT_ROOT, "params")
|
|
||||||
|
|
||||||
|
def parse_args():
|
||||||
|
parser = ArgumentParser(description="Interactive streaming chat")
|
||||||
|
parser.add_argument(
|
||||||
|
"--model_path",
|
||||||
|
type=Path,
|
||||||
|
default=PROJECT_ROOT / "params",
|
||||||
|
help="Path to model weights (params/ or checkpoint/epoch_N_step_M/)",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--temperature",
|
||||||
|
type=float,
|
||||||
|
default=0.8,
|
||||||
|
help="Sampling temperature (default: 0.8)",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--top_p",
|
||||||
|
type=float,
|
||||||
|
default=0.95,
|
||||||
|
help="Top-p sampling threshold",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--top_k",
|
||||||
|
type=int,
|
||||||
|
default=50,
|
||||||
|
help="Top-k sampling threshold",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--max_tokens",
|
||||||
|
type=int,
|
||||||
|
default=2048,
|
||||||
|
help="Maximum tokens to generate",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--system_prompt",
|
||||||
|
type=str,
|
||||||
|
default="You are a helpful assistant.",
|
||||||
|
help="Optional system prompt",
|
||||||
|
)
|
||||||
|
return parser.parse_args()
|
||||||
|
|
||||||
|
|
||||||
def chat():
|
def chat():
|
||||||
model = AutoModel.from_pretrained(PARAMETER_ROOT)
|
args = parse_args()
|
||||||
tokenizer = AutoTokenizer.from_pretrained(PARAMETER_ROOT)
|
model_path = args.model_path
|
||||||
model.to(device="cuda", dtype=torch.bfloat16)
|
|
||||||
|
|
||||||
messages = [{"role": "system", "content": "You are a helpful assistant."}]
|
model = AutoModel.from_pretrained(model_path)
|
||||||
|
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
||||||
|
model.to(device="cuda", dtype=torch.bfloat16)
|
||||||
engine = InferenceEngine(model=model, tokenizer=tokenizer)
|
engine = InferenceEngine(model=model, tokenizer=tokenizer)
|
||||||
|
|
||||||
|
messages = [{"role": "system", "content": args.system_prompt}]
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
query = input(">> ")
|
query = input(">> ")
|
||||||
if query == "!exit":
|
if query == "!exit":
|
||||||
break
|
break
|
||||||
|
|
||||||
# Add user message
|
|
||||||
messages.append({"role": "user", "content": query})
|
messages.append({"role": "user", "content": query})
|
||||||
|
|
||||||
# Generate response
|
|
||||||
full_response = ""
|
full_response = ""
|
||||||
prompt = tokenizer.apply_chat_template(messages, tokenize=False)
|
prompt = tokenizer.apply_chat_template(messages, tokenize=False)
|
||||||
|
|
||||||
for token in engine.generate(
|
for token in engine.generate(
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
stream=True,
|
stream=True,
|
||||||
max_tokens=2048,
|
max_tokens=args.max_tokens,
|
||||||
temperature=0.8,
|
temperature=args.temperature,
|
||||||
top_p=0.95,
|
top_p=args.top_p,
|
||||||
top_k=50,
|
top_k=args.top_k,
|
||||||
):
|
):
|
||||||
print(token, end="", flush=True)
|
print(token, end="", flush=True)
|
||||||
full_response += token
|
full_response += token
|
||||||
|
|
||||||
print()
|
print()
|
||||||
# Add assistant response to messages
|
|
||||||
messages.append({"role": "assistant", "content": full_response.strip()})
|
messages.append({"role": "assistant", "content": full_response.strip()})
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,307 @@
|
|||||||
|
"""SVD effective rank & weight statistics analysis for model checkpoints."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import safetensors.torch
|
||||||
|
import torch
|
||||||
|
|
||||||
|
|
||||||
|
def effective_rank_metrics(w: torch.Tensor) -> dict:
|
||||||
|
if w.ndim == 1:
|
||||||
|
return {"shape": tuple(w.shape), "is_1d": True}
|
||||||
|
|
||||||
|
w = w.float()
|
||||||
|
s = torch.linalg.svdvals(w)
|
||||||
|
s_sq = s**2
|
||||||
|
total = s_sq.sum()
|
||||||
|
cumsum = torch.cumsum(s_sq, dim=0) / total
|
||||||
|
|
||||||
|
min_dim = min(w.shape[0], w.shape[1])
|
||||||
|
er_90 = (cumsum < 0.90).sum().item() + 1
|
||||||
|
er_95 = (cumsum < 0.95).sum().item() + 1
|
||||||
|
er_99 = (cumsum < 0.99).sum().item() + 1
|
||||||
|
|
||||||
|
p = s_sq / total
|
||||||
|
p = p[p > 1e-30]
|
||||||
|
entropy = -(p * torch.log(p)).sum()
|
||||||
|
entropic_rank = torch.exp(entropy).item()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"shape": tuple(w.shape),
|
||||||
|
"min_dim": min_dim,
|
||||||
|
"er_90": er_90,
|
||||||
|
"er_95": er_95,
|
||||||
|
"er_99": er_99,
|
||||||
|
"er_99_norm": er_99 / min_dim,
|
||||||
|
"er_95_norm": er_95 / min_dim,
|
||||||
|
"entropic_rank": entropic_rank,
|
||||||
|
"entropic_rank_norm": entropic_rank / min_dim,
|
||||||
|
"top1_ratio": s[0].item() / s.sum().item(),
|
||||||
|
"top5_ratio": s[:5].sum().item() / s.sum().item(),
|
||||||
|
"decay_ratio": s[-1].item() / s[0].item(),
|
||||||
|
"condition_number": s[0].item() / s[-1].item(),
|
||||||
|
"mean": w.mean().item(),
|
||||||
|
"std": w.std().item(),
|
||||||
|
"min": w.min().item(),
|
||||||
|
"max": w.max().item(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def format_header(headers: list[str], widths: list[int]) -> str:
|
||||||
|
return "".join(h.ljust(w) for h, w in zip(headers, widths))
|
||||||
|
|
||||||
|
|
||||||
|
def format_row(values: list[str], widths: list[int]) -> str:
|
||||||
|
return "".join(v.ljust(w) for v, w in zip(values, widths))
|
||||||
|
|
||||||
|
|
||||||
|
def group_by_component(results: dict[str, dict]) -> dict[str, list[dict]]:
|
||||||
|
groups: dict[str, list[dict]] = {}
|
||||||
|
for key, r in results.items():
|
||||||
|
parts = key.split(".")
|
||||||
|
if parts[0] == "layers" and len(parts) >= 3:
|
||||||
|
sub = parts[2:]
|
||||||
|
if sub[0] == "attention":
|
||||||
|
comp = f"attn.{sub[1]}"
|
||||||
|
elif sub[0] == "mlp":
|
||||||
|
comp = f"mlp.{sub[1]}"
|
||||||
|
elif sub[0] == "input_norm":
|
||||||
|
comp = "input_norm"
|
||||||
|
elif sub[0] == "post_attention_norm":
|
||||||
|
comp = "post_attn_norm"
|
||||||
|
else:
|
||||||
|
comp = ".".join(sub)
|
||||||
|
else:
|
||||||
|
comp = key
|
||||||
|
groups.setdefault(comp, []).append(r)
|
||||||
|
return groups
|
||||||
|
|
||||||
|
|
||||||
|
def print_component_summary(results: dict[str, dict], title: str):
|
||||||
|
groups = group_by_component(results)
|
||||||
|
matrix_groups = {
|
||||||
|
k: [v for v in vs if not v.get("is_1d")]
|
||||||
|
for k, vs in groups.items()
|
||||||
|
if any(not v.get("is_1d") for v in vs)
|
||||||
|
}
|
||||||
|
|
||||||
|
widths = [20, 12, 12, 12, 12, 12]
|
||||||
|
print(f"\n{title}")
|
||||||
|
print(
|
||||||
|
format_header(
|
||||||
|
["Component", "N", "ER@99%", "EntRank%", "Top1 σ(%)", "Cond. Num"], widths
|
||||||
|
)
|
||||||
|
)
|
||||||
|
print("-" * sum(widths))
|
||||||
|
|
||||||
|
for name in sorted(matrix_groups.keys()):
|
||||||
|
items = matrix_groups[name]
|
||||||
|
n = len(items)
|
||||||
|
print(
|
||||||
|
format_row(
|
||||||
|
[
|
||||||
|
name,
|
||||||
|
str(n),
|
||||||
|
f"{sum(r['er_99_norm'] for r in items) / n:.4f}",
|
||||||
|
f"{sum(r['entropic_rank_norm'] for r in items) / n:.4f}",
|
||||||
|
f"{sum(r['top1_ratio'] for r in items) / n:.4f}",
|
||||||
|
f"{sum(r['condition_number'] for r in items) / n:.1f}",
|
||||||
|
],
|
||||||
|
widths,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
all_er = [
|
||||||
|
r["er_99_norm"]
|
||||||
|
for vs in matrix_groups.values()
|
||||||
|
for r in vs
|
||||||
|
if "_norm" not in r or not r.get("is_1d")
|
||||||
|
]
|
||||||
|
if all_er:
|
||||||
|
m = sum(all_er) / len(all_er)
|
||||||
|
print(f"\n Overall Mean ER@99: {m:.4f} ({m * 100:.1f}% of dimension)")
|
||||||
|
if m > 0.85:
|
||||||
|
print(" → HIGH utilization: model near capacity → need more params")
|
||||||
|
elif m > 0.5:
|
||||||
|
print(" → MODERATE utilization: some headroom left")
|
||||||
|
else:
|
||||||
|
print(" → LOW utilization: significant unused capacity")
|
||||||
|
|
||||||
|
|
||||||
|
def print_layer_grid(results: dict[str, dict]):
|
||||||
|
comps = [
|
||||||
|
"attn.q_proj",
|
||||||
|
"attn.k_proj",
|
||||||
|
"attn.v_proj",
|
||||||
|
"attn.o_proj",
|
||||||
|
"mlp.up",
|
||||||
|
"mlp.gate",
|
||||||
|
"mlp.down",
|
||||||
|
]
|
||||||
|
widths = [6] + [10] * len(comps)
|
||||||
|
metric = "er_99_norm"
|
||||||
|
|
||||||
|
print(f"\n--- Per-Layer Effective Rank (99% energy) ---")
|
||||||
|
print(format_header(["Layer"] + comps, widths))
|
||||||
|
print("-" * sum(widths))
|
||||||
|
|
||||||
|
layer_data: dict[int, dict[str, dict]] = {}
|
||||||
|
for key, r in results.items():
|
||||||
|
parts = key.split(".")
|
||||||
|
if parts[0] != "layers":
|
||||||
|
continue
|
||||||
|
li = int(parts[1])
|
||||||
|
sub = parts[2:]
|
||||||
|
if sub[0] == "attention":
|
||||||
|
cname = f"attn.{sub[1]}"
|
||||||
|
elif sub[0] == "mlp":
|
||||||
|
cname = f"mlp.{sub[1]}"
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
layer_data.setdefault(li, {})[cname] = r
|
||||||
|
|
||||||
|
for li in sorted(layer_data):
|
||||||
|
values = [str(li)]
|
||||||
|
for c in comps:
|
||||||
|
v = layer_data[li].get(c, {}).get(metric, 0)
|
||||||
|
values.append(f"{v:.4f}")
|
||||||
|
print(format_row(values, widths))
|
||||||
|
|
||||||
|
|
||||||
|
def print_weight_stats(results: dict[str, dict]):
|
||||||
|
groups = group_by_component(results)
|
||||||
|
widths = [20, 12, 12, 12, 12]
|
||||||
|
print(f"\n--- Weight Value Statistics ---")
|
||||||
|
print(format_header(["Component", "Mean", "Std", "Min", "Max"], widths))
|
||||||
|
print("-" * sum(widths))
|
||||||
|
|
||||||
|
for name in sorted(groups.keys()):
|
||||||
|
items = groups[name]
|
||||||
|
means = [r.get("mean", 0) for r in items]
|
||||||
|
stds = [r.get("std", 0) for r in items]
|
||||||
|
mins = [r.get("min", 0) for r in items]
|
||||||
|
maxs = [r.get("max", 0) for r in items]
|
||||||
|
g_mean = sum(means) / len(means)
|
||||||
|
g_std = sum(stds) / len(stds)
|
||||||
|
g_min = min(mins)
|
||||||
|
g_max = max(maxs)
|
||||||
|
print(
|
||||||
|
format_row(
|
||||||
|
[
|
||||||
|
name,
|
||||||
|
f"{g_mean:.6f}",
|
||||||
|
f"{g_std:.6f}",
|
||||||
|
f"{g_min:.6f}",
|
||||||
|
f"{g_max:.6f}",
|
||||||
|
],
|
||||||
|
widths,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def print_params_summary(results: dict[str, dict]):
|
||||||
|
total_2d = sum(
|
||||||
|
r["shape"][0] * r["shape"][1] for r in results.values() if not r.get("is_1d")
|
||||||
|
)
|
||||||
|
total_1d = sum(r["shape"][0] for r in results.values() if r.get("is_1d"))
|
||||||
|
print(f"\n Total 2D params: {total_2d:,}")
|
||||||
|
print(f" Total 1D params: {total_1d:,}")
|
||||||
|
print(f" Total params: {total_2d + total_1d:,}")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="SVD effective rank & weight statistics of a model checkpoint."
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--ckpt_dir",
|
||||||
|
type=str,
|
||||||
|
required=True,
|
||||||
|
help="Path to checkpoint directory (containing model.safetensors + config.json).",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--compare",
|
||||||
|
type=str,
|
||||||
|
nargs="*",
|
||||||
|
help="Additional checkpoint directories to compare against.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--no_svd",
|
||||||
|
action="store_true",
|
||||||
|
help="Skip SVD analysis, only show weight statistics (mean/std/min/max).",
|
||||||
|
)
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
def analyze_one(ckpt_dir: str, label: str):
|
||||||
|
ckpt_dir = Path(ckpt_dir)
|
||||||
|
weights_path = ckpt_dir / "model.safetensors"
|
||||||
|
if not weights_path.exists():
|
||||||
|
print(f"ERROR: {weights_path} not found")
|
||||||
|
return {}
|
||||||
|
|
||||||
|
meta = {}
|
||||||
|
meta_path = ckpt_dir / "meta.json"
|
||||||
|
if meta_path.exists():
|
||||||
|
with open(meta_path) as f:
|
||||||
|
meta = json.load(f)
|
||||||
|
|
||||||
|
print(f"\n{'=' * 70}")
|
||||||
|
print(f" {label}: {ckpt_dir}")
|
||||||
|
if meta:
|
||||||
|
print(
|
||||||
|
f" Iteration: {meta.get('iteration', '?')}, "
|
||||||
|
f"Strategy: {meta.get('strategy', '?')}, "
|
||||||
|
f"nprocs={meta.get('nprocs', '?')}"
|
||||||
|
)
|
||||||
|
print(f"{'=' * 70}")
|
||||||
|
|
||||||
|
print(f"Loading weights...")
|
||||||
|
sd = safetensors.torch.load_file(str(weights_path))
|
||||||
|
print(f" {len(sd)} keys loaded")
|
||||||
|
|
||||||
|
weight_keys = [
|
||||||
|
k
|
||||||
|
for k in sd
|
||||||
|
if ".weight" in k and "rotary_embedding" not in k and "freqs_cis" not in k
|
||||||
|
]
|
||||||
|
|
||||||
|
results = {}
|
||||||
|
if not args.no_svd:
|
||||||
|
print(f"Computing SVD on {len(weight_keys)} tensors...")
|
||||||
|
for i, k in enumerate(sorted(weight_keys)):
|
||||||
|
print(f" [{i + 1}/{len(weight_keys)}] {k:<60s}", end="\r")
|
||||||
|
results[k] = effective_rank_metrics(sd[k])
|
||||||
|
print()
|
||||||
|
else:
|
||||||
|
print(f"Computing stats on {len(weight_keys)} tensors (no SVD)...")
|
||||||
|
for i, k in enumerate(sorted(weight_keys)):
|
||||||
|
t = sd[k]
|
||||||
|
results[k] = {
|
||||||
|
"shape": tuple(t.shape),
|
||||||
|
"is_1d": t.ndim == 1,
|
||||||
|
"mean": t.float().mean().item(),
|
||||||
|
"std": t.float().std().item(),
|
||||||
|
"min": t.float().min().item(),
|
||||||
|
"max": t.float().max().item(),
|
||||||
|
}
|
||||||
|
|
||||||
|
print_params_summary(results)
|
||||||
|
if not args.no_svd:
|
||||||
|
print_component_summary(
|
||||||
|
results, "\n=== SVD Effective Rank by Component ==="
|
||||||
|
)
|
||||||
|
print_layer_grid(results)
|
||||||
|
print_weight_stats(results)
|
||||||
|
return results
|
||||||
|
|
||||||
|
analyze_one(args.ckpt_dir, "Primary")
|
||||||
|
|
||||||
|
if args.compare:
|
||||||
|
for cdir in args.compare:
|
||||||
|
analyze_one(cdir, "Compare")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+271
-212
@@ -1,22 +1,22 @@
|
|||||||
"""HumanEval code generation benchmark.
|
"""HumanEval benchmark — functional pipeline design.
|
||||||
|
|
||||||
Generates n completions per problem, extracts function bodies, executes
|
Pipeline:
|
||||||
against hidden tests, and computes pass@k.
|
load -> generate -> extract -> test -> score -> report
|
||||||
|
|
||||||
Usage::
|
Each stage is a pure function (except GPU/CPU-bound I/O stages).
|
||||||
|
Config is a single dataclass; side effects are isolated at pipeline boundaries.
|
||||||
python scripts/tools/evaluate_humaneval.py --param_path ./params \
|
|
||||||
--data_path HumanEval.jsonl.gz --output results.json \
|
|
||||||
--num_samples 200 --temperature 0.8 --max_tokens 512
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
|
import itertools
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from dataclasses import dataclass
|
||||||
from math import prod
|
from math import prod
|
||||||
from multiprocessing import Process, Queue
|
from typing import Dict, Iterator, List, Optional, Sequence, Tuple
|
||||||
from typing import Dict, List, Optional, Tuple
|
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
@@ -26,11 +26,15 @@ from astrai.inference import InferenceEngine
|
|||||||
from astrai.model import AutoModel
|
from astrai.model import AutoModel
|
||||||
from astrai.tokenize import AutoTokenizer
|
from astrai.tokenize import AutoTokenizer
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Config
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
HUMANEVAL_URL = (
|
HUMANEVAL_URL = (
|
||||||
"https://github.com/openai/human-eval/raw/master/data/HumanEval.jsonl.gz"
|
"https://github.com/openai/human-eval/raw/master/data/HumanEval.jsonl.gz"
|
||||||
)
|
)
|
||||||
|
|
||||||
_STOP_SEQUENCES = [
|
STOP_SEQUENCES = [
|
||||||
"\nclass ",
|
"\nclass ",
|
||||||
"\ndef ",
|
"\ndef ",
|
||||||
"\n# ",
|
"\n# ",
|
||||||
@@ -40,43 +44,85 @@ _STOP_SEQUENCES = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
def _download_humaneval(data_path: str):
|
@dataclass
|
||||||
if os.path.exists(data_path):
|
class EvalConfig:
|
||||||
|
param_path: str = "./params"
|
||||||
|
data_path: str = "./humaneval/HumanEval.jsonl"
|
||||||
|
output: Optional[str] = None
|
||||||
|
|
||||||
|
test_only: Optional[str] = None
|
||||||
|
generate_only: bool = False
|
||||||
|
|
||||||
|
num_samples: int = 200
|
||||||
|
max_tokens: int = 512
|
||||||
|
temperature: float = 0.8
|
||||||
|
top_p: float = 0.95
|
||||||
|
top_k: int = 50
|
||||||
|
batch_size: int = 32
|
||||||
|
test_timeout: float = 3.0
|
||||||
|
test_workers: int = 8
|
||||||
|
k_values: Tuple[int, ...] = (1, 10, 100)
|
||||||
|
problem_indices: Optional[List[int]] = None
|
||||||
|
|
||||||
|
|
||||||
|
def download(url: str, path: str):
|
||||||
|
if os.path.exists(path):
|
||||||
return
|
return
|
||||||
import gzip
|
import gzip
|
||||||
import urllib.request
|
import urllib.request
|
||||||
|
|
||||||
os.makedirs(os.path.dirname(data_path) or ".", exist_ok=True)
|
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
||||||
print(f"Downloading HumanEval from {HUMANEVAL_URL} ...")
|
print(f"Downloading {url} ...")
|
||||||
tmp = data_path + ".tmp"
|
tmp = path + ".tmp"
|
||||||
urllib.request.urlretrieve(HUMANEVAL_URL, tmp)
|
urllib.request.urlretrieve(url, tmp)
|
||||||
with gzip.open(tmp, "rb") as f_in:
|
with gzip.open(tmp, "rb") as f_in:
|
||||||
with open(data_path, "wb") as f_out:
|
with open(path, "wb") as f_out:
|
||||||
f_out.write(f_in.read())
|
f_out.write(f_in.read())
|
||||||
os.remove(tmp)
|
os.remove(tmp)
|
||||||
print(f" saved to {data_path}")
|
print(f" saved to {path}")
|
||||||
|
|
||||||
|
|
||||||
def _load_problems(data_path: str) -> List[dict]:
|
def load_jsonl(path: str) -> List[dict]:
|
||||||
problems = []
|
rows = []
|
||||||
with open(data_path, "r", encoding="utf-8") as f:
|
with open(path, encoding="utf-8") as f:
|
||||||
for line in f:
|
for line in f:
|
||||||
line = line.strip()
|
line = line.strip()
|
||||||
if line:
|
if line:
|
||||||
problems.append(json.loads(line))
|
rows.append(json.loads(line))
|
||||||
return problems
|
return rows
|
||||||
|
|
||||||
|
|
||||||
def _extract_function_body(code: str, entry_point: str) -> Optional[str]:
|
def save_json(path: str, data):
|
||||||
"""Extract the function body from a completion."""
|
with open(path, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||||
|
|
||||||
|
|
||||||
|
def create_engine(param_path: str, batch_size: int) -> InferenceEngine:
|
||||||
|
model = AutoModel.from_pretrained(param_path)
|
||||||
|
tokenizer = AutoTokenizer.from_pretrained(param_path)
|
||||||
|
model.to(device="cuda", dtype=torch.bfloat16)
|
||||||
|
return InferenceEngine(
|
||||||
|
model=model,
|
||||||
|
tokenizer=tokenizer,
|
||||||
|
max_batch_size=batch_size,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def trim_stop(text: str) -> str:
|
||||||
|
for stop in STOP_SEQUENCES:
|
||||||
|
idx = text.find(stop)
|
||||||
|
if idx != -1:
|
||||||
|
text = text[:idx]
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def extract_body(code: str, entry_point: str) -> Optional[str]:
|
||||||
pattern = rf"def\s+{re.escape(entry_point)}\b[^:]*:"
|
pattern = rf"def\s+{re.escape(entry_point)}\b[^:]*:"
|
||||||
match = re.search(pattern, code)
|
match = re.search(pattern, code)
|
||||||
if not match:
|
if not match:
|
||||||
# Use the full code as-is if we can't find the function
|
|
||||||
return code
|
return code
|
||||||
|
|
||||||
body_start = match.end()
|
lines = code[match.end() :].split("\n")
|
||||||
lines = code[body_start:].split("\n")
|
|
||||||
body_lines = []
|
body_lines = []
|
||||||
started = False
|
started = False
|
||||||
|
|
||||||
@@ -94,240 +140,253 @@ def _extract_function_body(code: str, entry_point: str) -> Optional[str]:
|
|||||||
body_lines.append(stripped)
|
body_lines.append(stripped)
|
||||||
|
|
||||||
body = "\n".join(body_lines)
|
body = "\n".join(body_lines)
|
||||||
if not body.strip():
|
return body if body.strip() else None
|
||||||
return None
|
|
||||||
return body
|
|
||||||
|
|
||||||
|
|
||||||
def _trim_stop_sequences(text: str) -> str:
|
def deduplicate(seq: Sequence[str]) -> List[str]:
|
||||||
for stop in _STOP_SEQUENCES:
|
|
||||||
idx = text.find(stop)
|
|
||||||
if idx != -1:
|
|
||||||
text = text[:idx]
|
|
||||||
return text
|
|
||||||
|
|
||||||
|
|
||||||
def _execute_code(problem: dict, completion: str, timeout: float = 3.0) -> bool:
|
|
||||||
"""Run the completion against hidden tests in a subprocess."""
|
|
||||||
|
|
||||||
def _worker(queue, full_code):
|
|
||||||
try:
|
|
||||||
namespace = {}
|
|
||||||
exec(full_code, namespace)
|
|
||||||
check = namespace.get("check")
|
|
||||||
if check is None:
|
|
||||||
queue.put(False)
|
|
||||||
return
|
|
||||||
check(namespace.get(problem["entry_point"]))
|
|
||||||
queue.put(True)
|
|
||||||
except Exception:
|
|
||||||
queue.put(False)
|
|
||||||
|
|
||||||
full_code = problem["prompt"] + completion + "\n" + problem["test"]
|
|
||||||
|
|
||||||
queue: Queue = Queue()
|
|
||||||
proc = Process(target=_worker, args=(queue, full_code))
|
|
||||||
proc.start()
|
|
||||||
proc.join(timeout)
|
|
||||||
|
|
||||||
if proc.is_alive():
|
|
||||||
proc.terminate()
|
|
||||||
proc.join()
|
|
||||||
return False
|
|
||||||
|
|
||||||
try:
|
|
||||||
return queue.get_nowait()
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _pass_at_k(n: int, c: int, k: int) -> float:
|
|
||||||
"""Unbiased estimator of pass@k."""
|
|
||||||
if n - c < k:
|
|
||||||
return 1.0
|
|
||||||
return 1.0 - float(prod(1.0 - k / np.arange(n - c + 1, n + 1)))
|
|
||||||
|
|
||||||
|
|
||||||
def _deduplicate(completions: List[str]) -> List[str]:
|
|
||||||
seen = set()
|
seen = set()
|
||||||
unique = []
|
return [x for x in seq if not (x in seen or seen.add(x))]
|
||||||
for c in completions:
|
|
||||||
if c not in seen:
|
|
||||||
seen.add(c)
|
|
||||||
unique.append(c)
|
|
||||||
return unique
|
|
||||||
|
|
||||||
|
|
||||||
def _generate(
|
def generate_batch(
|
||||||
engine: InferenceEngine,
|
engine: InferenceEngine,
|
||||||
prompt: str,
|
prompt: str,
|
||||||
num_samples: int,
|
n: int,
|
||||||
|
batch_size: int,
|
||||||
max_tokens: int,
|
max_tokens: int,
|
||||||
temperature: float,
|
temperature: float,
|
||||||
top_p: float,
|
top_p: float,
|
||||||
top_k: int,
|
top_k: int,
|
||||||
batch_size: int,
|
|
||||||
) -> List[str]:
|
) -> List[str]:
|
||||||
batches = [prompt] * min(batch_size, num_samples)
|
|
||||||
completions = []
|
completions = []
|
||||||
remaining = num_samples
|
remaining = n
|
||||||
|
|
||||||
while remaining > 0:
|
while remaining > 0:
|
||||||
current = min(batch_size, remaining)
|
current = min(batch_size, remaining)
|
||||||
batch_prompts = batches[:current]
|
|
||||||
outputs = engine.generate(
|
outputs = engine.generate(
|
||||||
prompt=batch_prompts,
|
prompt=[prompt] * current,
|
||||||
stream=False,
|
stream=False,
|
||||||
max_tokens=max_tokens,
|
max_tokens=max_tokens,
|
||||||
temperature=temperature,
|
temperature=temperature,
|
||||||
top_p=top_p,
|
top_p=top_p,
|
||||||
top_k=top_k,
|
top_k=top_k,
|
||||||
)
|
)
|
||||||
if isinstance(outputs, str):
|
completions.extend(outputs if isinstance(outputs, list) else [outputs])
|
||||||
outputs = [outputs]
|
|
||||||
completions.extend(outputs)
|
|
||||||
remaining -= current
|
remaining -= current
|
||||||
|
return deduplicate(completions)
|
||||||
return _deduplicate(completions)
|
|
||||||
|
|
||||||
|
|
||||||
def evaluate(
|
def extract_completions(
|
||||||
engine: InferenceEngine,
|
raw: Sequence[str],
|
||||||
problems: List[dict],
|
entry_point: str,
|
||||||
num_samples: int,
|
) -> List[str]:
|
||||||
max_tokens: int,
|
bodies = []
|
||||||
temperature: float,
|
for r in raw:
|
||||||
top_p: float,
|
t = trim_stop(r)
|
||||||
top_k: int,
|
body = extract_body(t, entry_point)
|
||||||
batch_size: int,
|
|
||||||
k_values: Tuple[int, ...] = (1, 10, 100),
|
|
||||||
) -> Dict:
|
|
||||||
results = {}
|
|
||||||
all_pass_at_k = {k: [] for k in k_values}
|
|
||||||
|
|
||||||
for problem in tqdm.tqdm(problems, desc="HumanEval", unit="problem"):
|
|
||||||
task_id = problem["task_id"]
|
|
||||||
prompt = problem["prompt"]
|
|
||||||
entry_point = problem["entry_point"]
|
|
||||||
|
|
||||||
raw_completions = _generate(
|
|
||||||
engine,
|
|
||||||
prompt,
|
|
||||||
num_samples,
|
|
||||||
max_tokens,
|
|
||||||
temperature,
|
|
||||||
top_p,
|
|
||||||
top_k,
|
|
||||||
batch_size,
|
|
||||||
)
|
|
||||||
|
|
||||||
completions = []
|
|
||||||
for raw in raw_completions:
|
|
||||||
trimmed = _trim_stop_sequences(raw)
|
|
||||||
body = _extract_function_body(trimmed, entry_point)
|
|
||||||
if body:
|
if body:
|
||||||
completions.append(body)
|
bodies.append(body)
|
||||||
|
return bodies
|
||||||
|
|
||||||
passed = 0
|
|
||||||
for comp in completions:
|
|
||||||
if _execute_code(problem, comp):
|
|
||||||
passed += 1
|
|
||||||
|
|
||||||
n = len(completions)
|
|
||||||
c = passed
|
|
||||||
result = {"task_id": task_id, "n": n, "passed": c}
|
|
||||||
for k in k_values:
|
|
||||||
result[f"pass@{k}"] = round(_pass_at_k(n, c, k), 4)
|
|
||||||
all_pass_at_k[k].append(_pass_at_k(n, c, k))
|
|
||||||
results[task_id] = result
|
|
||||||
|
|
||||||
summary = {}
|
|
||||||
for k in k_values:
|
|
||||||
vals = all_pass_at_k[k]
|
|
||||||
summary[f"pass@{k}"] = round(float(np.mean(vals)), 4)
|
|
||||||
results["_summary"] = summary
|
|
||||||
|
|
||||||
|
def generate_all(
|
||||||
|
engine: InferenceEngine,
|
||||||
|
problems: Sequence[dict],
|
||||||
|
cfg: EvalConfig,
|
||||||
|
) -> List[dict]:
|
||||||
|
results = []
|
||||||
|
for problem in tqdm.tqdm(problems, desc="Generating", unit="problem"):
|
||||||
|
raw = generate_batch(
|
||||||
|
engine,
|
||||||
|
problem["prompt"],
|
||||||
|
cfg.num_samples,
|
||||||
|
cfg.batch_size,
|
||||||
|
cfg.max_tokens,
|
||||||
|
cfg.temperature,
|
||||||
|
cfg.top_p,
|
||||||
|
cfg.top_k,
|
||||||
|
)
|
||||||
|
bodies = extract_completions(raw, problem["entry_point"])
|
||||||
|
results.append(
|
||||||
|
dict(
|
||||||
|
task_id=problem["task_id"],
|
||||||
|
entry_point=problem["entry_point"],
|
||||||
|
prompt=problem["prompt"],
|
||||||
|
test=problem["test"],
|
||||||
|
completions=bodies,
|
||||||
|
)
|
||||||
|
)
|
||||||
return results
|
return results
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def execute_one(args: tuple) -> bool:
|
||||||
parser = argparse.ArgumentParser(description="HumanEval benchmark")
|
full_code, entry_point, timeout = args
|
||||||
parser.add_argument(
|
try:
|
||||||
"--param_path", type=str, default="./params", help="Model directory"
|
r = subprocess.run(
|
||||||
|
[sys.executable, "-c", full_code],
|
||||||
|
capture_output=True,
|
||||||
|
timeout=timeout,
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
return r.returncode == 0
|
||||||
"--data_path",
|
except subprocess.TimeoutExpired:
|
||||||
|
return False
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def test_one(item: dict, cfg: EvalConfig) -> Tuple[str, int, int]:
|
||||||
|
from concurrent.futures import ProcessPoolExecutor
|
||||||
|
|
||||||
|
task_id = item["task_id"]
|
||||||
|
completions = item["completions"]
|
||||||
|
codes = [
|
||||||
|
(
|
||||||
|
item["prompt"] + c + "\n" + item["test"],
|
||||||
|
item["entry_point"],
|
||||||
|
cfg.test_timeout,
|
||||||
|
)
|
||||||
|
for c in completions
|
||||||
|
]
|
||||||
|
n = len(codes)
|
||||||
|
passed = 0
|
||||||
|
with ProcessPoolExecutor(max_workers=cfg.test_workers) as pool:
|
||||||
|
for ok in pool.map(execute_one, codes):
|
||||||
|
if ok:
|
||||||
|
passed += 1
|
||||||
|
return task_id, n, passed
|
||||||
|
|
||||||
|
|
||||||
|
def test_all(
|
||||||
|
items: Sequence[dict],
|
||||||
|
cfg: EvalConfig,
|
||||||
|
) -> Iterator[Tuple[str, int, int]]:
|
||||||
|
for item in tqdm.tqdm(items, desc="Testing", unit="problem"):
|
||||||
|
yield test_one(item, cfg)
|
||||||
|
|
||||||
|
|
||||||
|
def pass_at_k(n: int, c: int, k: int) -> float:
|
||||||
|
if n - c < k:
|
||||||
|
return 1.0
|
||||||
|
return 1.0 - float(prod(1.0 - k / np.arange(n - c + 1, n + 1)))
|
||||||
|
|
||||||
|
|
||||||
|
def score_results(
|
||||||
|
results: Iterator[Tuple[str, int, int]],
|
||||||
|
k_values: Tuple[int, ...],
|
||||||
|
) -> Dict:
|
||||||
|
# filter to k <= n (peek first result to get n)
|
||||||
|
first = next(results)
|
||||||
|
results = itertools.chain([first], results)
|
||||||
|
n = first[1]
|
||||||
|
k_values = tuple(k for k in k_values if k <= n)
|
||||||
|
|
||||||
|
scores = {k: [] for k in k_values}
|
||||||
|
output = {}
|
||||||
|
for task_id, n, passed in results:
|
||||||
|
entry = {"task_id": task_id, "n": n, "passed": passed}
|
||||||
|
for k in k_values:
|
||||||
|
pk = round(pass_at_k(n, passed, k), 4)
|
||||||
|
entry[f"pass@{k}"] = pk
|
||||||
|
scores[k].append(pk)
|
||||||
|
output[task_id] = entry
|
||||||
|
|
||||||
|
summary = {}
|
||||||
|
for k in k_values:
|
||||||
|
vals = scores[k]
|
||||||
|
summary[f"pass@{k}"] = round(float(np.mean(vals)), 4)
|
||||||
|
output["_summary"] = summary
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
def run_pipeline(cfg: EvalConfig) -> Dict:
|
||||||
|
if cfg.test_only:
|
||||||
|
with open(cfg.test_only, encoding="utf-8") as f:
|
||||||
|
generated = json.load(f)
|
||||||
|
else:
|
||||||
|
download(HUMANEVAL_URL, cfg.data_path)
|
||||||
|
|
||||||
|
problems = load_jsonl(cfg.data_path)
|
||||||
|
if cfg.problem_indices:
|
||||||
|
problems = [problems[i] for i in cfg.problem_indices if i < len(problems)]
|
||||||
|
|
||||||
|
engine = create_engine(cfg.param_path, cfg.batch_size)
|
||||||
|
|
||||||
|
try:
|
||||||
|
generated = generate_all(engine, problems, cfg)
|
||||||
|
finally:
|
||||||
|
engine.shutdown()
|
||||||
|
|
||||||
|
if cfg.output:
|
||||||
|
mid = cfg.output.replace(".json", "_completions.json")
|
||||||
|
save_json(mid, generated)
|
||||||
|
print(f"Completions saved to {mid}")
|
||||||
|
|
||||||
|
if cfg.generate_only:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
results = test_all(generated, cfg)
|
||||||
|
scored = score_results(results, cfg.k_values)
|
||||||
|
return scored
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args(argv: Optional[List[str]] = None) -> EvalConfig:
|
||||||
|
p = argparse.ArgumentParser(description="HumanEval benchmark")
|
||||||
|
p.add_argument("--param_path", type=str, default="./params")
|
||||||
|
p.add_argument("--data_path", type=str, default="./humaneval/HumanEval.jsonl")
|
||||||
|
p.add_argument("--output", type=str, default=None)
|
||||||
|
p.add_argument(
|
||||||
|
"--test_only",
|
||||||
type=str,
|
type=str,
|
||||||
default="./humaneval/HumanEval.jsonl",
|
|
||||||
help="HumanEval JSONL file (auto-download if missing)",
|
|
||||||
)
|
|
||||||
parser.add_argument("--output", type=str, default=None, help="Output JSON path")
|
|
||||||
parser.add_argument(
|
|
||||||
"--num_samples",
|
|
||||||
type=int,
|
|
||||||
default=200,
|
|
||||||
help="Completions per problem",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--max_tokens", type=int, default=512, help="Max generation tokens"
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--temperature", type=float, default=0.8, help="Sampling temperature"
|
|
||||||
)
|
|
||||||
parser.add_argument("--top_p", type=float, default=0.95, help="Top-p sampling")
|
|
||||||
parser.add_argument("--top_k", type=int, default=50, help="Top-k sampling")
|
|
||||||
parser.add_argument(
|
|
||||||
"--batch_size", type=int, default=1, help="Inference batch size"
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--problems",
|
|
||||||
type=int,
|
|
||||||
nargs="+",
|
|
||||||
default=None,
|
default=None,
|
||||||
help="Specific problem indices (0-based)",
|
help="Skip generation, test existing completions JSON",
|
||||||
)
|
)
|
||||||
args = parser.parse_args()
|
p.add_argument(
|
||||||
|
"--generate_only", action="store_true", help="Only generate, skip testing"
|
||||||
_download_humaneval(args.data_path)
|
|
||||||
problems = _load_problems(args.data_path)
|
|
||||||
if args.problems:
|
|
||||||
problems = [problems[i] for i in args.problems if i < len(problems)]
|
|
||||||
|
|
||||||
model = AutoModel.from_pretrained(args.param_path)
|
|
||||||
tokenizer = AutoTokenizer.from_pretrained(args.param_path)
|
|
||||||
model.to(device="cuda", dtype=torch.bfloat16)
|
|
||||||
|
|
||||||
engine = InferenceEngine(
|
|
||||||
model=model,
|
|
||||||
tokenizer=tokenizer,
|
|
||||||
max_batch_size=args.batch_size,
|
|
||||||
)
|
)
|
||||||
|
p.add_argument("--num_samples", type=int, default=200)
|
||||||
|
p.add_argument("--max_tokens", type=int, default=512)
|
||||||
|
p.add_argument("--temperature", type=float, default=0.8)
|
||||||
|
p.add_argument("--top_p", type=float, default=0.95)
|
||||||
|
p.add_argument("--top_k", type=int, default=50)
|
||||||
|
p.add_argument("--batch_size", type=int, default=32)
|
||||||
|
p.add_argument("--test_workers", type=int, default=8)
|
||||||
|
p.add_argument("--test_timeout", type=float, default=3.0)
|
||||||
|
p.add_argument("--problems", type=int, nargs="+", default=None)
|
||||||
|
args = p.parse_args(argv)
|
||||||
|
|
||||||
results = evaluate(
|
return EvalConfig(
|
||||||
engine=engine,
|
param_path=args.param_path,
|
||||||
problems=problems,
|
data_path=args.data_path,
|
||||||
|
output=args.output,
|
||||||
|
test_only=args.test_only,
|
||||||
|
generate_only=args.generate_only,
|
||||||
num_samples=args.num_samples,
|
num_samples=args.num_samples,
|
||||||
max_tokens=args.max_tokens,
|
max_tokens=args.max_tokens,
|
||||||
temperature=args.temperature,
|
temperature=args.temperature,
|
||||||
top_p=args.top_p,
|
top_p=args.top_p,
|
||||||
top_k=args.top_k,
|
top_k=args.top_k,
|
||||||
batch_size=args.batch_size,
|
batch_size=args.batch_size,
|
||||||
k_values=(1, 10, 100),
|
test_workers=args.test_workers,
|
||||||
|
test_timeout=args.test_timeout,
|
||||||
|
problem_indices=args.problems,
|
||||||
)
|
)
|
||||||
|
|
||||||
summary = results.pop("_summary")
|
|
||||||
|
def report(scored: Dict):
|
||||||
|
summary = scored.pop("_summary", {})
|
||||||
print(f"\n{'=' * 60}")
|
print(f"\n{'=' * 60}")
|
||||||
for k, v in summary.items():
|
for k, v in summary.items():
|
||||||
print(f" {k}: {v:.2%}")
|
print(f" {k}: {v:.2%}")
|
||||||
print(f"{'=' * 60}")
|
print(f"{'=' * 60}")
|
||||||
|
scored["_summary"] = summary
|
||||||
|
|
||||||
if args.output:
|
|
||||||
results["_summary"] = summary
|
|
||||||
with open(args.output, "w", encoding="utf-8") as f:
|
|
||||||
json.dump(results, f, indent=2, ensure_ascii=False)
|
|
||||||
print(f"Results saved to {args.output}")
|
|
||||||
|
|
||||||
engine.shutdown()
|
def main():
|
||||||
|
cfg = parse_args()
|
||||||
|
scored = run_pipeline(cfg)
|
||||||
|
report(scored)
|
||||||
|
if cfg.output:
|
||||||
|
save_json(cfg.output, scored)
|
||||||
|
print(f"Results saved to {cfg.output}")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
+383
-92
@@ -1,24 +1,23 @@
|
|||||||
"""IFD (Instruction Following Difficulty) data quality scoring.
|
"""IFD (Instruction Following Difficulty) data quality scoring.
|
||||||
|
|
||||||
Computes IFD scores for instruction-response pairs to guide data selection.
|
IFD = conditional_NLL / unconditional_NLL
|
||||||
IFD = conditional_NLL / unconditional_NLL, where:
|
|
||||||
|
|
||||||
- conditional_NLL: average CE loss on response tokens given instruction context
|
- Messages format: plain text concatenation (no chat template)
|
||||||
- unconditional_NLL: average CE loss on response tokens alone
|
- Plain format: raw instr_key + resp_key fields
|
||||||
|
|
||||||
Higher IFD (close to 1) = instruction provides less help = harder sample.
|
v2 changelog:
|
||||||
Lower IFD (close to 0) = instruction provides strong guidance = easy sample.
|
- Same token set: unconditional pass prefixes resp with a plain-text sentinel
|
||||||
IFD > 1 = instruction misleads the model = likely low-quality data.
|
(default ``\\n``; use ``--sentinel_text ""`` for bos/pad fallback).
|
||||||
|
Both branches predict the identical N resp tokens.
|
||||||
Usage::
|
Single-token answers (rl=1) are now supported.
|
||||||
|
- ctx_len tracked in output
|
||||||
python scripts/eval/ifd.py --param_path ./params \
|
- skip_reason for None samples (no more silent None)
|
||||||
--input data.jsonl --output data_with_ifd.jsonl \
|
- --per_token for per-token IFD breakdown
|
||||||
--instr_key instruction --resp_key response
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import json
|
import json
|
||||||
|
import statistics
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
import torch.nn.functional as F
|
import torch.nn.functional as F
|
||||||
@@ -28,120 +27,396 @@ from astrai.model import AutoModel
|
|||||||
from astrai.tokenize import AutoTokenizer
|
from astrai.tokenize import AutoTokenizer
|
||||||
|
|
||||||
|
|
||||||
def compute_ifd(
|
def _pack_bins(pairs, max_len):
|
||||||
|
"""BFD bin packing: pack (c+r) into bins of max total length."""
|
||||||
|
indexed = sorted(enumerate(pairs), key=lambda x: -(len(x[1][0]) + len(x[1][1])))
|
||||||
|
bins = []
|
||||||
|
lengths = []
|
||||||
|
for orig_idx, (c, r) in indexed:
|
||||||
|
size = len(c) + len(r)
|
||||||
|
best_bin = -1
|
||||||
|
for bi, rem in enumerate(lengths):
|
||||||
|
if rem >= size:
|
||||||
|
if best_bin < 0 or rem < lengths[best_bin]:
|
||||||
|
best_bin = bi
|
||||||
|
if best_bin >= 0:
|
||||||
|
bins[best_bin].append((orig_idx, c, r))
|
||||||
|
lengths[best_bin] -= size
|
||||||
|
else:
|
||||||
|
bins.append([(orig_idx, c, r)])
|
||||||
|
lengths.append(max_len - size)
|
||||||
|
return bins
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_sentinel_ids(tokenizer, sentinel_text):
|
||||||
|
"""Tokenize the sentinel text for the unconditional pass prefix.
|
||||||
|
|
||||||
|
Falls back to bos/pad_token_id when sentinel_text is empty or
|
||||||
|
cannot be encoded.
|
||||||
|
"""
|
||||||
|
if sentinel_text:
|
||||||
|
ids = tokenizer.encode(sentinel_text, add_special_tokens=False)
|
||||||
|
if ids:
|
||||||
|
return ids
|
||||||
|
for attr in ("bos_token_id", "pad_token_id", "eos_token_id"):
|
||||||
|
tid = getattr(tokenizer, attr, None)
|
||||||
|
if tid is not None:
|
||||||
|
return [tid]
|
||||||
|
return [0]
|
||||||
|
|
||||||
|
|
||||||
|
@torch.inference_mode()
|
||||||
|
def _score_batch(
|
||||||
|
pairs, model, device, max_len=2048, sentinel_ids=None, per_token=False
|
||||||
|
):
|
||||||
|
"""BFD-packed IFD with text-sentinel-anchored unconditional pass.
|
||||||
|
|
||||||
|
Conditional: (ctx + resp[0..i-1]) → resp[i], i = 0..N-1
|
||||||
|
Unconditional: (<sentinel> + resp[0..i-1]) → resp[i], i = 0..N-1
|
||||||
|
|
||||||
|
Both branches predict the identical N response tokens. A short
|
||||||
|
plain-text sentinel gives the unconditional pass a prefix so that
|
||||||
|
every response token can be predicted. Single-token answers (rl=1)
|
||||||
|
are supported.
|
||||||
|
"""
|
||||||
|
if not pairs:
|
||||||
|
return []
|
||||||
|
|
||||||
|
if sentinel_ids is None:
|
||||||
|
sentinel_ids = [0]
|
||||||
|
|
||||||
|
bins = _pack_bins(pairs, max_len)
|
||||||
|
result = [None] * len(pairs)
|
||||||
|
|
||||||
|
# ---- conditional pass (packed, per-document position IDs) ----
|
||||||
|
for bin_items in bins:
|
||||||
|
seq_ids = []
|
||||||
|
global_pos = []
|
||||||
|
doc_ids = []
|
||||||
|
doc_offsets = []
|
||||||
|
|
||||||
|
for di, (orig_idx, c, r) in enumerate(bin_items):
|
||||||
|
ctx_len = len(c)
|
||||||
|
start = len(seq_ids)
|
||||||
|
item_len = len(c) + len(r)
|
||||||
|
seq_ids.extend(c)
|
||||||
|
seq_ids.extend(r)
|
||||||
|
end = len(seq_ids)
|
||||||
|
global_pos.extend(range(item_len))
|
||||||
|
doc_ids.extend([di] * item_len)
|
||||||
|
doc_offsets.append((start, end, orig_idx, ctx_len))
|
||||||
|
|
||||||
|
full_ids = torch.tensor([seq_ids], device=device, dtype=torch.long)
|
||||||
|
pos_ids = torch.tensor([global_pos], device=device, dtype=torch.long)
|
||||||
|
seq_len = len(seq_ids)
|
||||||
|
causal = torch.tril(
|
||||||
|
torch.ones(seq_len, seq_len, dtype=torch.bool, device=device)
|
||||||
|
)
|
||||||
|
doc_t = torch.tensor([doc_ids], device=device)
|
||||||
|
doc_mask = doc_t.unsqueeze(-1) == doc_t.unsqueeze(-2)
|
||||||
|
attn_mask = (causal & doc_mask[0]).unsqueeze(0).unsqueeze(0)
|
||||||
|
logits_full = model(full_ids, position_ids=pos_ids, input_mask=attn_mask)[
|
||||||
|
"logits"
|
||||||
|
][0]
|
||||||
|
|
||||||
|
for start, end, orig_idx, ctx_len in doc_offsets:
|
||||||
|
rl = end - start - ctx_len
|
||||||
|
resp_start = start + ctx_len - 1
|
||||||
|
resp_logits = logits_full[resp_start : end - 1]
|
||||||
|
resp_targets = torch.tensor(
|
||||||
|
seq_ids[start + ctx_len : end], device=device, dtype=torch.long
|
||||||
|
)
|
||||||
|
cond_losses = F.cross_entropy(
|
||||||
|
resp_logits, resp_targets, reduction="none"
|
||||||
|
).cpu()
|
||||||
|
result[orig_idx] = {
|
||||||
|
"_cond_losses": cond_losses,
|
||||||
|
"_rl": rl,
|
||||||
|
"_ctx_len": ctx_len,
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---- unconditional pass (sentinel-prefixed, batched 2D) ----
|
||||||
|
valid_items = [
|
||||||
|
(
|
||||||
|
i,
|
||||||
|
result[i]["_rl"],
|
||||||
|
result[i]["_ctx_len"],
|
||||||
|
result[i]["_cond_losses"],
|
||||||
|
pairs[i][1],
|
||||||
|
)
|
||||||
|
for i in range(len(pairs))
|
||||||
|
if result[i] is not None and "_cond_losses" in result[i]
|
||||||
|
]
|
||||||
|
if not valid_items:
|
||||||
|
return result
|
||||||
|
|
||||||
|
valid_items.sort(key=lambda x: -x[1])
|
||||||
|
prefix_len = len(sentinel_ids)
|
||||||
|
max_rl = prefix_len + max(rl for _, rl, _, _, _ in valid_items)
|
||||||
|
bsz = len(valid_items)
|
||||||
|
|
||||||
|
u_batch = torch.zeros(bsz, max_rl, dtype=torch.long, device=device)
|
||||||
|
for ri, (_, rl, _, _, r_ids) in enumerate(valid_items):
|
||||||
|
u_batch[ri, :prefix_len] = torch.tensor(sentinel_ids, dtype=torch.long)
|
||||||
|
u_batch[ri, prefix_len : prefix_len + rl] = torch.tensor(
|
||||||
|
r_ids, dtype=torch.long
|
||||||
|
)
|
||||||
|
|
||||||
|
logits_resp = model(u_batch)["logits"]
|
||||||
|
|
||||||
|
for ri, (orig_idx, rl, ctx_len, cond_losses, _) in enumerate(valid_items):
|
||||||
|
unp_logits = logits_resp[ri, prefix_len - 1 : prefix_len - 1 + rl]
|
||||||
|
unp_targets = u_batch[ri, prefix_len : prefix_len + rl]
|
||||||
|
uncond_losses = F.cross_entropy(unp_logits, unp_targets, reduction="none").cpu()
|
||||||
|
|
||||||
|
L_cond = cond_losses.mean().item()
|
||||||
|
L_uncond = uncond_losses.mean().item()
|
||||||
|
ifd = L_cond / L_uncond if L_uncond > 0 else None
|
||||||
|
|
||||||
|
out = {
|
||||||
|
"L_cond": round(L_cond, 6),
|
||||||
|
"L_uncond": round(L_uncond, 6),
|
||||||
|
"ifd": round(ifd, 6) if ifd is not None else None,
|
||||||
|
"ctx_len": ctx_len,
|
||||||
|
"resp_len": rl,
|
||||||
|
}
|
||||||
|
if per_token:
|
||||||
|
per = [
|
||||||
|
(round(c.item() / u.item(), 6) if u.item() > 0 else None)
|
||||||
|
for c, u in zip(cond_losses, uncond_losses)
|
||||||
|
]
|
||||||
|
out["ifd_per_token"] = per
|
||||||
|
result[orig_idx] = out
|
||||||
|
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _trim(context_ids, resp_ids, max_len):
|
||||||
|
"""Truncate to fit max_len, keeping response intact if possible."""
|
||||||
|
if len(resp_ids) > max_len // 2:
|
||||||
|
resp_ids = resp_ids[: max_len // 2]
|
||||||
|
full_ids = context_ids + resp_ids
|
||||||
|
if len(full_ids) <= max_len:
|
||||||
|
return context_ids, resp_ids
|
||||||
|
overflow = len(full_ids) - max_len
|
||||||
|
if overflow >= len(context_ids):
|
||||||
|
return [], resp_ids[:max_len]
|
||||||
|
return context_ids[overflow:], resp_ids
|
||||||
|
|
||||||
|
|
||||||
|
def score_plain(
|
||||||
model,
|
model,
|
||||||
tokenizer,
|
tokenizer,
|
||||||
instruction: str,
|
instruction,
|
||||||
response: str,
|
response,
|
||||||
device: str,
|
device,
|
||||||
max_len: int = 2048,
|
max_len=2048,
|
||||||
) -> dict:
|
sentinel_ids=None,
|
||||||
instr_ids = tokenizer.encode(instruction)
|
per_token=False,
|
||||||
resp_ids = tokenizer.encode(response)
|
):
|
||||||
|
"""Compute IFD for a single instruction-response pair (plain format)."""
|
||||||
if not resp_ids:
|
ctx_ids = tokenizer.encode(instruction, add_special_tokens=False)
|
||||||
|
resp_ids = tokenizer.encode(response, add_special_tokens=False)
|
||||||
|
ctx_ids, resp_ids = _trim(ctx_ids, resp_ids, max_len)
|
||||||
|
if not ctx_ids or not resp_ids:
|
||||||
return {
|
return {
|
||||||
"L_cond": None,
|
"L_cond": None,
|
||||||
"L_uncond": None,
|
"L_uncond": None,
|
||||||
"ifd": None,
|
"ifd": None,
|
||||||
"error": "empty response",
|
"skip_reason": "empty ctx or resp",
|
||||||
}
|
}
|
||||||
|
return _score_batch(
|
||||||
|
[(ctx_ids, resp_ids)],
|
||||||
|
model,
|
||||||
|
device,
|
||||||
|
max_len,
|
||||||
|
sentinel_ids=sentinel_ids,
|
||||||
|
per_token=per_token,
|
||||||
|
)[0]
|
||||||
|
|
||||||
# Truncate instruction if total length exceeds max_len
|
|
||||||
qa_len = len(instr_ids) + len(resp_ids)
|
|
||||||
if qa_len > max_len:
|
|
||||||
overflow = qa_len - max_len
|
|
||||||
instr_ids = instr_ids[overflow:]
|
|
||||||
|
|
||||||
instr_len = len(instr_ids)
|
|
||||||
resp_len = len(resp_ids)
|
|
||||||
|
|
||||||
# Conditional: instruction + response
|
|
||||||
qa_ids = instr_ids + resp_ids
|
|
||||||
qa_tensor = torch.tensor([qa_ids], device=device, dtype=torch.long)
|
|
||||||
|
|
||||||
with torch.inference_mode():
|
|
||||||
logits_qa = model(qa_tensor)["logits"][0] # [qa_len, vocab]
|
|
||||||
|
|
||||||
resp_logits = logits_qa[instr_len - 1 : -1] # predict response tokens
|
|
||||||
resp_targets = torch.tensor(resp_ids, device=device, dtype=torch.long)
|
|
||||||
L_cond = F.cross_entropy(resp_logits, resp_targets, reduction="mean").item()
|
|
||||||
|
|
||||||
# Unconditional: response alone
|
|
||||||
resp_tensor = torch.tensor([resp_ids], device=device, dtype=torch.long)
|
|
||||||
|
|
||||||
with torch.inference_mode():
|
|
||||||
logits_resp = model(resp_tensor)["logits"][0] # [resp_len, vocab]
|
|
||||||
|
|
||||||
unp_logits = logits_resp[:-1] # causal shift
|
|
||||||
unp_targets = resp_tensor[0, 1:]
|
|
||||||
L_uncond = F.cross_entropy(unp_logits, unp_targets, reduction="mean").item()
|
|
||||||
|
|
||||||
ifd = L_cond / L_uncond if L_uncond > 0 else None
|
|
||||||
|
|
||||||
|
def score_messages(
|
||||||
|
model, tokenizer, messages, device, max_len=2048, sentinel_ids=None, per_token=False
|
||||||
|
):
|
||||||
|
"""Compute IFD for each assistant turn in a messages array."""
|
||||||
|
turns = []
|
||||||
|
for i, msg in enumerate(messages):
|
||||||
|
if msg.get("role") != "assistant":
|
||||||
|
continue
|
||||||
|
ctx_text = "\n\n".join(m["content"] for m in messages[:i])
|
||||||
|
ctx_ids = tokenizer.encode(ctx_text)
|
||||||
|
resp_ids = tokenizer.encode(msg["content"], add_special_tokens=False)
|
||||||
|
ctx_ids, resp_ids = _trim(ctx_ids, resp_ids, max_len)
|
||||||
|
if ctx_ids and resp_ids:
|
||||||
|
turns.append((ctx_ids, resp_ids))
|
||||||
|
if not turns:
|
||||||
|
return None
|
||||||
|
raw_scores = _score_batch(
|
||||||
|
turns, model, device, max_len, sentinel_ids=sentinel_ids, per_token=per_token
|
||||||
|
)
|
||||||
|
valid = [s for s in raw_scores if s is not None and s.get("ifd") is not None]
|
||||||
|
if not valid:
|
||||||
|
return {"ifd": None, "ifd_turns": raw_scores}
|
||||||
|
avg = sum(s["ifd"] for s in valid) / len(valid)
|
||||||
return {
|
return {
|
||||||
"L_cond": round(L_cond, 6),
|
"ifd": avg,
|
||||||
"L_uncond": round(L_uncond, 6),
|
"ifd_detail": valid[0] if len(valid) == 1 else None,
|
||||||
"ifd": round(ifd, 6) if ifd is not None else None,
|
"ifd_turns": raw_scores,
|
||||||
"instr_len": instr_len,
|
|
||||||
"resp_len": resp_len,
|
|
||||||
"error": None,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def process_file(
|
def process_file(
|
||||||
param_path: str,
|
param_path,
|
||||||
input_file: str,
|
input_file,
|
||||||
output_file: str,
|
output_file,
|
||||||
instr_key: str,
|
instr_key,
|
||||||
resp_key: str,
|
resp_key,
|
||||||
max_len: int,
|
max_len=2048,
|
||||||
|
data_format="plain",
|
||||||
|
batch_size=1,
|
||||||
|
device=None,
|
||||||
|
sentinel_text="\n",
|
||||||
|
per_token=False,
|
||||||
):
|
):
|
||||||
|
if device is None:
|
||||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||||
dtype = torch.bfloat16 if device == "cuda" else torch.float32
|
dtype = torch.bfloat16 if "cuda" in device else torch.float32
|
||||||
|
|
||||||
model = AutoModel.from_pretrained(param_path)
|
model = AutoModel.from_pretrained(param_path)
|
||||||
tokenizer = AutoTokenizer.from_pretrained(param_path)
|
tokenizer = AutoTokenizer.from_pretrained(param_path)
|
||||||
model.to(device=device, dtype=dtype)
|
model.to(device=device, dtype=dtype)
|
||||||
model.eval()
|
model.eval()
|
||||||
|
|
||||||
with open(input_file, "r", encoding="utf-8") as f:
|
sentinel_ids = _resolve_sentinel_ids(tokenizer, sentinel_text)
|
||||||
|
|
||||||
|
with open(input_file, encoding="utf-8") as f:
|
||||||
data = [json.loads(line) for line in f if line.strip()]
|
data = [json.loads(line) for line in f if line.strip()]
|
||||||
|
|
||||||
results = []
|
results = []
|
||||||
ifd_values = []
|
all_ifds = []
|
||||||
|
buffer = []
|
||||||
|
|
||||||
with torch.inference_mode():
|
|
||||||
for item in tqdm.tqdm(data, desc="Computing IFD", unit="sample"):
|
for item in tqdm.tqdm(data, desc="Computing IFD", unit="sample"):
|
||||||
instruction = item[instr_key]
|
if data_format == "messages":
|
||||||
response = item[resp_key]
|
turns = []
|
||||||
scores = compute_ifd(
|
for i, msg in enumerate(item.get("messages", [])):
|
||||||
model, tokenizer, instruction, response, device, max_len
|
if msg.get("role") != "assistant":
|
||||||
|
continue
|
||||||
|
ctx_text = "\n\n".join(m["content"] for m in item["messages"][:i])
|
||||||
|
ctx_ids = tokenizer.encode(ctx_text)
|
||||||
|
resp_ids = tokenizer.encode(msg["content"], add_special_tokens=False)
|
||||||
|
ctx_ids, resp_ids = _trim(ctx_ids, resp_ids, max_len)
|
||||||
|
if ctx_ids and resp_ids:
|
||||||
|
turns.append((ctx_ids, resp_ids))
|
||||||
|
if not turns:
|
||||||
|
results.append(
|
||||||
|
{
|
||||||
|
**item,
|
||||||
|
"ifd": None,
|
||||||
|
"skip_reason": "no valid assistant turns",
|
||||||
|
"ifd_turns": [],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
buffer.append((item, turns, "messages"))
|
||||||
|
else:
|
||||||
|
ctx_ids = tokenizer.encode(item[instr_key], add_special_tokens=False)
|
||||||
|
resp_ids = tokenizer.encode(item[resp_key], add_special_tokens=False)
|
||||||
|
ctx_ids, resp_ids = _trim(ctx_ids, resp_ids, max_len)
|
||||||
|
if not ctx_ids or not resp_ids:
|
||||||
|
results.append(
|
||||||
|
{
|
||||||
|
**item,
|
||||||
|
"ifd": None,
|
||||||
|
"ifd_detail": {"skip_reason": "empty ctx or resp"},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
buffer.append((item, [(ctx_ids, resp_ids)], "plain"))
|
||||||
|
|
||||||
|
if len(buffer) >= batch_size:
|
||||||
|
_flush_buffer(
|
||||||
|
buffer,
|
||||||
|
results,
|
||||||
|
all_ifds,
|
||||||
|
model,
|
||||||
|
device,
|
||||||
|
max_len,
|
||||||
|
sentinel_ids,
|
||||||
|
per_token,
|
||||||
|
)
|
||||||
|
|
||||||
|
if buffer:
|
||||||
|
_flush_buffer(
|
||||||
|
buffer, results, all_ifds, model, device, max_len, sentinel_ids, per_token
|
||||||
)
|
)
|
||||||
ifd_values.append(scores["ifd"])
|
|
||||||
results.append({**item, "ifd": scores["ifd"], "ifd_detail": scores})
|
|
||||||
|
|
||||||
with open(output_file, "w", encoding="utf-8") as f:
|
with open(output_file, "w", encoding="utf-8") as f:
|
||||||
for item in results:
|
for item in results:
|
||||||
f.write(json.dumps(item, ensure_ascii=False) + "\n")
|
f.write(json.dumps(item, ensure_ascii=False) + "\n")
|
||||||
|
|
||||||
valid_ifd = [v for v in ifd_values if v is not None]
|
valid_ifd = [v for v in all_ifds if v is not None]
|
||||||
if valid_ifd:
|
if valid_ifd:
|
||||||
import statistics
|
|
||||||
|
|
||||||
print(f"\n{'=' * 50}")
|
print(f"\n{'=' * 50}")
|
||||||
print(f" Samples: {len(data)}")
|
print(f" Samples: {len(data)}")
|
||||||
print(f" Valid IFD: {len(valid_ifd)}")
|
print(f" Valid IFD: {len(valid_ifd)}")
|
||||||
|
print(f" Skipped: {len(data) - len(valid_ifd)}")
|
||||||
print(f" Mean IFD: {statistics.mean(valid_ifd):.4f}")
|
print(f" Mean IFD: {statistics.mean(valid_ifd):.4f}")
|
||||||
print(f" Median IFD: {statistics.median(valid_ifd):.4f}")
|
print(f" Median IFD: {statistics.median(valid_ifd):.4f}")
|
||||||
|
if len(valid_ifd) > 1:
|
||||||
print(f" Stdev IFD: {statistics.stdev(valid_ifd):.4f}")
|
print(f" Stdev IFD: {statistics.stdev(valid_ifd):.4f}")
|
||||||
print(f" Min IFD: {min(valid_ifd):.4f}")
|
print(f" Min IFD: {min(valid_ifd):.4f}")
|
||||||
print(f" Max IFD: {max(valid_ifd):.4f}")
|
print(f" Max IFD: {max(valid_ifd):.4f}")
|
||||||
print(f"{'=' * 50}")
|
print(f"{'=' * 50}")
|
||||||
|
|
||||||
print(f"Results saved to {output_file}")
|
print(f"Results saved to {output_file}")
|
||||||
|
|
||||||
|
|
||||||
|
def _flush_buffer(
|
||||||
|
buffer, results, all_ifds, model, device, max_len, sentinel_ids, per_token
|
||||||
|
):
|
||||||
|
all_pairs = []
|
||||||
|
indices = []
|
||||||
|
for item, turns, fmt in buffer:
|
||||||
|
start = len(all_pairs)
|
||||||
|
all_pairs.extend(turns)
|
||||||
|
indices.append((item, turns, fmt, start, len(all_pairs)))
|
||||||
|
|
||||||
|
raw = _score_batch(
|
||||||
|
all_pairs,
|
||||||
|
model,
|
||||||
|
device,
|
||||||
|
max_len,
|
||||||
|
sentinel_ids=sentinel_ids,
|
||||||
|
per_token=per_token,
|
||||||
|
)
|
||||||
|
|
||||||
|
for item, turns, fmt, start, end in indices:
|
||||||
|
turn_scores = raw[start:end]
|
||||||
|
if fmt == "messages":
|
||||||
|
valid = [
|
||||||
|
s for s in turn_scores if s is not None and s.get("ifd") is not None
|
||||||
|
]
|
||||||
|
if not valid:
|
||||||
|
results.append({**item, "ifd": None, "ifd_turns": turn_scores})
|
||||||
|
else:
|
||||||
|
avg = sum(s["ifd"] for s in valid) / len(valid)
|
||||||
|
all_ifds.append(avg)
|
||||||
|
results.append(
|
||||||
|
{
|
||||||
|
**item,
|
||||||
|
"ifd": avg,
|
||||||
|
"ifd_detail": valid[0] if len(valid) == 1 else None,
|
||||||
|
"ifd_turns": turn_scores,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
score = turn_scores[0]
|
||||||
|
all_ifds.append(score.get("ifd"))
|
||||||
|
results.append({**item, "ifd": score.get("ifd"), "ifd_detail": score})
|
||||||
|
|
||||||
|
buffer.clear()
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser(
|
||||||
description="Compute IFD scores for instruction-response data"
|
description="Compute IFD scores for instruction-response data"
|
||||||
@@ -149,23 +424,34 @@ def main():
|
|||||||
parser.add_argument("--param_path", type=str, required=True, help="Model directory")
|
parser.add_argument("--param_path", type=str, required=True, help="Model directory")
|
||||||
parser.add_argument("--input", type=str, required=True, help="Input JSONL file")
|
parser.add_argument("--input", type=str, required=True, help="Input JSONL file")
|
||||||
parser.add_argument("--output", type=str, required=True, help="Output JSONL file")
|
parser.add_argument("--output", type=str, required=True, help="Output JSONL file")
|
||||||
|
parser.add_argument("--max_len", type=int, default=2048, help="Max token length")
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--instr_key",
|
"--format",
|
||||||
type=str,
|
type=str,
|
||||||
default="instruction",
|
default="plain",
|
||||||
help="Key for instruction field",
|
choices=["plain", "messages"],
|
||||||
|
help="Input format",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--resp_key",
|
"--instr_key", type=str, default="instruction", help="Key for instruction field"
|
||||||
type=str,
|
|
||||||
default="response",
|
|
||||||
help="Key for response field",
|
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--max_len",
|
"--resp_key", type=str, default="response", help="Key for response field"
|
||||||
type=int,
|
)
|
||||||
default=2048,
|
parser.add_argument(
|
||||||
help="Max token length (instruction truncated to fit)",
|
"--batch_size", type=int, default=8, help="Batch size for model forward passes"
|
||||||
|
)
|
||||||
|
parser.add_argument("--device", type=str, default=None, help="Device (e.g. cuda:0)")
|
||||||
|
parser.add_argument(
|
||||||
|
"--sentinel_text",
|
||||||
|
type=str,
|
||||||
|
default="\n",
|
||||||
|
help='Plain-text prefix for unconditional pass (default: "\\n"). Use "" for bos/pad fallback.',
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--per_token",
|
||||||
|
action="store_true",
|
||||||
|
help="Include per-token IFD breakdown in output",
|
||||||
)
|
)
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
@@ -176,6 +462,11 @@ def main():
|
|||||||
args.instr_key,
|
args.instr_key,
|
||||||
args.resp_key,
|
args.resp_key,
|
||||||
args.max_len,
|
args.max_len,
|
||||||
|
data_format=args.format,
|
||||||
|
batch_size=args.batch_size,
|
||||||
|
device=args.device,
|
||||||
|
sentinel_text=args.sentinel_text,
|
||||||
|
per_token=args.per_token,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -343,14 +343,20 @@ def verify_response(response: str, instruction_id: str, kwargs: dict) -> Optiona
|
|||||||
|
|
||||||
def generate_one(
|
def generate_one(
|
||||||
engine: InferenceEngine,
|
engine: InferenceEngine,
|
||||||
|
tokenizer: AutoTokenizer,
|
||||||
prompt: str,
|
prompt: str,
|
||||||
max_tokens: int,
|
max_tokens: int,
|
||||||
temperature: float,
|
temperature: float,
|
||||||
top_p: float,
|
top_p: float,
|
||||||
top_k: int,
|
top_k: int,
|
||||||
) -> str:
|
) -> str:
|
||||||
|
formatted = tokenizer.apply_chat_template(
|
||||||
|
[{"role": "user", "content": prompt}],
|
||||||
|
tokenize=False,
|
||||||
|
add_generation_prompt=True,
|
||||||
|
)
|
||||||
output = engine.generate(
|
output = engine.generate(
|
||||||
prompt=prompt,
|
prompt=formatted,
|
||||||
stream=False,
|
stream=False,
|
||||||
max_tokens=max_tokens,
|
max_tokens=max_tokens,
|
||||||
temperature=temperature,
|
temperature=temperature,
|
||||||
@@ -364,6 +370,7 @@ def generate_one(
|
|||||||
|
|
||||||
def evaluate(
|
def evaluate(
|
||||||
engine: InferenceEngine,
|
engine: InferenceEngine,
|
||||||
|
tokenizer: AutoTokenizer,
|
||||||
problems: List[dict],
|
problems: List[dict],
|
||||||
max_tokens: int,
|
max_tokens: int,
|
||||||
temperature: float,
|
temperature: float,
|
||||||
@@ -385,7 +392,7 @@ def evaluate(
|
|||||||
samples = []
|
samples = []
|
||||||
for _ in range(num_samples):
|
for _ in range(num_samples):
|
||||||
response = generate_one(
|
response = generate_one(
|
||||||
engine, prompt, max_tokens, temperature, top_p, top_k
|
engine, tokenizer, prompt, max_tokens, temperature, top_p, top_k
|
||||||
)
|
)
|
||||||
samples.append(response)
|
samples.append(response)
|
||||||
|
|
||||||
@@ -536,6 +543,7 @@ def main():
|
|||||||
model = AutoModel.from_pretrained(args.param_path)
|
model = AutoModel.from_pretrained(args.param_path)
|
||||||
tokenizer = AutoTokenizer.from_pretrained(args.param_path)
|
tokenizer = AutoTokenizer.from_pretrained(args.param_path)
|
||||||
model.to(device="cuda", dtype=torch.bfloat16)
|
model.to(device="cuda", dtype=torch.bfloat16)
|
||||||
|
model.eval()
|
||||||
|
|
||||||
engine = InferenceEngine(
|
engine = InferenceEngine(
|
||||||
model=model,
|
model=model,
|
||||||
@@ -545,6 +553,7 @@ def main():
|
|||||||
|
|
||||||
results = evaluate(
|
results = evaluate(
|
||||||
engine=engine,
|
engine=engine,
|
||||||
|
tokenizer=tokenizer,
|
||||||
problems=problems,
|
problems=problems,
|
||||||
max_tokens=args.max_tokens,
|
max_tokens=args.max_tokens,
|
||||||
temperature=args.temperature,
|
temperature=args.temperature,
|
||||||
@@ -562,7 +571,7 @@ def main():
|
|||||||
print(f" Unsupported: {summary['unsupported_constraints']}")
|
print(f" Unsupported: {summary['unsupported_constraints']}")
|
||||||
print(f"{'=' * 60}")
|
print(f"{'=' * 60}")
|
||||||
|
|
||||||
print(f"\nPer-type accuracy:")
|
print("\nPer-type accuracy:")
|
||||||
for inst_id, stats in sorted(summary["per_type_accuracy"].items()):
|
for inst_id, stats in sorted(summary["per_type_accuracy"].items()):
|
||||||
print(
|
print(
|
||||||
f" {inst_id:50s} {stats['accuracy']:.2%} "
|
f" {inst_id:50s} {stats['accuracy']:.2%} "
|
||||||
|
|||||||
@@ -86,7 +86,7 @@ def process_file(
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
parser = argparse.ArgumentParser(description="Run perplexity with a Khaosz model.")
|
parser = argparse.ArgumentParser(description="Perplexity evaluation on JSONL text.")
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--param_path", type=str, required=True, help="Path to the model directory."
|
"--param_path", type=str, required=True, help="Path to the model directory."
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,153 @@
|
|||||||
|
"""ROUGE evaluation (manual implementation, no external deps).
|
||||||
|
|
||||||
|
Computes ROUGE-1, ROUGE-2, ROUGE-L precision, recall, and F1.
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
# Batch evaluation from JSONL (each line: {"reference": ..., "candidate": ...})
|
||||||
|
python scripts/eval/evaluate_rouge.py --data_path preds.jsonl --output results.json
|
||||||
|
|
||||||
|
# As a library
|
||||||
|
from scripts.eval.evaluate_rouge import compute_rouge
|
||||||
|
scores = compute_rouge("the cat sat on the mat", "the cat sat")
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
from collections import Counter
|
||||||
|
from typing import Dict, List, Tuple
|
||||||
|
|
||||||
|
|
||||||
|
def _tokenize(text: str) -> List[str]:
|
||||||
|
return text.split()
|
||||||
|
|
||||||
|
|
||||||
|
def _ngrams(tokens: List[str], n: int) -> Counter:
|
||||||
|
return Counter(zip(*[tokens[i:] for i in range(n)]))
|
||||||
|
|
||||||
|
|
||||||
|
def _lcs(x: List[str], y: List[str]) -> int:
|
||||||
|
m, n = len(x), len(y)
|
||||||
|
dp = [[0] * (n + 1) for _ in range(m + 1)]
|
||||||
|
for i in range(1, m + 1):
|
||||||
|
xi = x[i - 1]
|
||||||
|
dpi = dp[i]
|
||||||
|
dpi_1 = dp[i - 1]
|
||||||
|
for j in range(1, n + 1):
|
||||||
|
if xi == y[j - 1]:
|
||||||
|
dpi[j] = dpi_1[j - 1] + 1
|
||||||
|
else:
|
||||||
|
dpi[j] = dpi_1[j] if dpi_1[j] > dpi[j - 1] else dpi[j - 1]
|
||||||
|
return dp[m][n]
|
||||||
|
|
||||||
|
|
||||||
|
def _f1(precision: float, recall: float) -> float:
|
||||||
|
if precision + recall == 0:
|
||||||
|
return 0.0
|
||||||
|
return 2 * precision * recall / (precision + recall)
|
||||||
|
|
||||||
|
|
||||||
|
def _rouge_n(ref_tokens: List[str], cand_tokens: List[str], n: int) -> Dict[str, float]:
|
||||||
|
ref_ngrams = _ngrams(ref_tokens, n)
|
||||||
|
cand_ngrams = _ngrams(cand_tokens, n)
|
||||||
|
|
||||||
|
overlap = sum((cand_ngrams & ref_ngrams).values())
|
||||||
|
cand_total = sum(cand_ngrams.values())
|
||||||
|
ref_total = sum(ref_ngrams.values())
|
||||||
|
|
||||||
|
precision = overlap / cand_total if cand_total > 0 else 0.0
|
||||||
|
recall = overlap / ref_total if ref_total > 0 else 0.0
|
||||||
|
f1 = _f1(precision, recall)
|
||||||
|
|
||||||
|
return {"precision": precision, "recall": recall, "f1": f1}
|
||||||
|
|
||||||
|
|
||||||
|
def _rouge_l(ref_tokens: List[str], cand_tokens: List[str]) -> Dict[str, float]:
|
||||||
|
lcs_len = _lcs(ref_tokens, cand_tokens)
|
||||||
|
ref_len = len(ref_tokens)
|
||||||
|
cand_len = len(cand_tokens)
|
||||||
|
|
||||||
|
recall = lcs_len / ref_len if ref_len > 0 else 0.0
|
||||||
|
precision = lcs_len / cand_len if cand_len > 0 else 0.0
|
||||||
|
f1 = _f1(precision, recall)
|
||||||
|
|
||||||
|
return {"precision": precision, "recall": recall, "f1": f1}
|
||||||
|
|
||||||
|
|
||||||
|
def compute_rouge(
|
||||||
|
reference: str, candidate: str, n: int = 2
|
||||||
|
) -> Dict[str, Dict[str, float]]:
|
||||||
|
"""Compute ROUGE-N (1..n) and ROUGE-L scores.
|
||||||
|
|
||||||
|
Returns::
|
||||||
|
|
||||||
|
{
|
||||||
|
"rouge-1": {"precision": ..., "recall": ..., "f1": ...},
|
||||||
|
"rouge-2": {"precision": ..., "recall": ..., "f1": ...},
|
||||||
|
"rouge-l": {"precision": ..., "recall": ..., "f1": ...},
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
ref_tokens = _tokenize(reference)
|
||||||
|
cand_tokens = _tokenize(candidate)
|
||||||
|
|
||||||
|
results = {}
|
||||||
|
for i in range(1, n + 1):
|
||||||
|
results[f"rouge-{i}"] = _rouge_n(ref_tokens, cand_tokens, i)
|
||||||
|
results["rouge-l"] = _rouge_l(ref_tokens, cand_tokens)
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate_file(data_path: str) -> Dict:
|
||||||
|
with open(data_path, "r", encoding="utf-8") as f:
|
||||||
|
pairs = [json.loads(line) for line in f if line.strip()]
|
||||||
|
|
||||||
|
agg = {
|
||||||
|
k: {"precision": 0.0, "recall": 0.0, "f1": 0.0}
|
||||||
|
for k in ("rouge-1", "rouge-2", "rouge-l")
|
||||||
|
}
|
||||||
|
per_item = []
|
||||||
|
|
||||||
|
for item in pairs:
|
||||||
|
ref = item["reference"]
|
||||||
|
cand = item["candidate"]
|
||||||
|
scores = compute_rouge(ref, cand)
|
||||||
|
per_item.append({**item, "scores": scores})
|
||||||
|
for k, v in scores.items():
|
||||||
|
agg[k]["precision"] += v["precision"]
|
||||||
|
agg[k]["recall"] += v["recall"]
|
||||||
|
agg[k]["f1"] += v["f1"]
|
||||||
|
|
||||||
|
n = len(pairs)
|
||||||
|
for k in agg:
|
||||||
|
agg[k] = {m: v / n for m, v in agg[k].items()}
|
||||||
|
|
||||||
|
return {"num_samples": n, "aggregate": agg, "per_item": per_item}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description="ROUGE evaluation")
|
||||||
|
parser.add_argument(
|
||||||
|
"--data_path", required=True, help="JSONL with reference/candidate per line"
|
||||||
|
)
|
||||||
|
parser.add_argument("--output", type=str, default=None, help="Output JSON path")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
results = evaluate_file(args.data_path)
|
||||||
|
agg = results["aggregate"]
|
||||||
|
|
||||||
|
print(f"Samples: {results['num_samples']}")
|
||||||
|
print()
|
||||||
|
for metric in ("rouge-1", "rouge-2", "rouge-l"):
|
||||||
|
s = agg[metric]
|
||||||
|
print(
|
||||||
|
f" {metric:8s} P={s['precision']:.4f} R={s['recall']:.4f} F1={s['f1']:.4f}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if args.output:
|
||||||
|
with open(args.output, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(results, f, indent=2, ensure_ascii=False)
|
||||||
|
print(f"\nSaved to {args.output}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import argparse
|
import argparse
|
||||||
import json
|
import json
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
@@ -17,7 +18,7 @@ def processor(
|
|||||||
top_p: float,
|
top_p: float,
|
||||||
question_key: str,
|
question_key: str,
|
||||||
response_key: str,
|
response_key: str,
|
||||||
max_tokens: int,
|
max_tokens: Optional[int],
|
||||||
batch_size: int,
|
batch_size: int,
|
||||||
):
|
):
|
||||||
# Load model and tokenizer
|
# Load model and tokenizer
|
||||||
@@ -72,7 +73,7 @@ def processor(
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
parser = argparse.ArgumentParser(description="Run generate with a Khaosz model.")
|
parser = argparse.ArgumentParser(description="Batch generation from JSONL file.")
|
||||||
|
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--param_path", type=str, required=True, help="Path to the model directory."
|
"--param_path", type=str, required=True, help="Path to the model directory."
|
||||||
@@ -93,36 +94,42 @@ if __name__ == "__main__":
|
|||||||
"--question_key",
|
"--question_key",
|
||||||
type=str,
|
type=str,
|
||||||
default="question",
|
default="question",
|
||||||
help="Key for the question in the input JSON.",
|
help="Key for the question in the input JSON (default: question).",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--response_key",
|
"--response_key",
|
||||||
type=str,
|
type=str,
|
||||||
default="response",
|
default="response",
|
||||||
help="Key for the response in the output JSON.",
|
help="Key for the response in the output JSON (default: response).",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--temperature",
|
"--temperature",
|
||||||
type=float,
|
type=float,
|
||||||
default=0.60,
|
default=0.60,
|
||||||
help="Temperature for generating responses.",
|
help="Temperature for generating responses (default: 0.60).",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--top_k", type=int, default=30, help="Top-k value for generating responses."
|
"--top_k",
|
||||||
|
type=int,
|
||||||
|
default=30,
|
||||||
|
help="Top-k value for generating responses (default: 30).",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--top_p",
|
"--top_p",
|
||||||
type=float,
|
type=float,
|
||||||
default=0.95,
|
default=0.95,
|
||||||
help="Top-p value for generating responses.",
|
help="Top-p value for generating responses (default: 0.95).",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--batch_size", type=int, default=1, help="Batch size for generating responses."
|
"--batch_size",
|
||||||
|
type=int,
|
||||||
|
default=1,
|
||||||
|
help="Batch size for generating responses (default: 1).",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--max_tokens",
|
"--max_tokens",
|
||||||
type=int,
|
type=int,
|
||||||
default=2048,
|
default=None,
|
||||||
help="Maximum tokens to generate (default: model config max_len).",
|
help="Maximum tokens to generate (default: model config max_len).",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+88
-19
@@ -150,8 +150,8 @@ def parse_args() -> argparse.Namespace:
|
|||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--metrics",
|
"--metrics",
|
||||||
nargs="*",
|
nargs="*",
|
||||||
default=["loss", "lr"],
|
default=["loss", "lr", "grad_norm"],
|
||||||
help="Metrics to log (e.g. --metrics loss lr val_loss). Default: loss lr.",
|
help="Metrics to log (e.g. --metrics loss lr val_loss). Default: loss lr grad_norm.",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--log_dir",
|
"--log_dir",
|
||||||
@@ -159,12 +159,6 @@ def parse_args() -> argparse.Namespace:
|
|||||||
default="checkpoint/logs",
|
default="checkpoint/logs",
|
||||||
help="Directory for metric logs.",
|
help="Directory for metric logs.",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
|
||||||
"--log_interval",
|
|
||||||
type=int,
|
|
||||||
default=100,
|
|
||||||
help="Number of batch iterations between metric logs.",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--grpo_sync_interval",
|
"--grpo_sync_interval",
|
||||||
type=int,
|
type=int,
|
||||||
@@ -175,7 +169,10 @@ def parse_args() -> argparse.Namespace:
|
|||||||
"--start_epoch", type=int, default=0, help="Start epoch for training."
|
"--start_epoch", type=int, default=0, help="Start epoch for training."
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--start_batch", type=int, default=0, help="Start batch for training."
|
"--start_samples",
|
||||||
|
type=int,
|
||||||
|
default=0,
|
||||||
|
help="Start samples (per rank) for training.",
|
||||||
)
|
)
|
||||||
|
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
@@ -221,6 +218,44 @@ def parse_args() -> argparse.Namespace:
|
|||||||
help="NEFTune noise alpha (0=disabled, typical: 5.0).",
|
help="NEFTune noise alpha (0=disabled, typical: 5.0).",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"--schedule_type",
|
||||||
|
type=str,
|
||||||
|
default="cosine",
|
||||||
|
choices=["cosine", "sgdr", "wsd"],
|
||||||
|
help="Learning rate scheduler type.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--min_rate",
|
||||||
|
type=float,
|
||||||
|
default=None,
|
||||||
|
help="Minimum LR as fraction of base LR. Uses scheduler default if not set (cosine/sgdr: 0.05, wsd: 0.0).",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--cycle_length",
|
||||||
|
type=int,
|
||||||
|
default=None,
|
||||||
|
help="SGDR first cycle length in steps. Defaults to total_steps - warmup_steps.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--t_mult",
|
||||||
|
type=int,
|
||||||
|
default=2,
|
||||||
|
help="SGDR cycle length multiplier per restart.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--stable_steps",
|
||||||
|
type=int,
|
||||||
|
default=None,
|
||||||
|
help="WSD stable plateau steps. Required when --schedule_type wsd.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--decay_steps",
|
||||||
|
type=int,
|
||||||
|
default=None,
|
||||||
|
help="WSD decay steps. Defaults to total_steps - warmup_steps - stable_steps.",
|
||||||
|
)
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
return args
|
return args
|
||||||
@@ -231,7 +266,20 @@ def create_model(config):
|
|||||||
|
|
||||||
|
|
||||||
def create_optimizer(model, **kwargs) -> optim.Optimizer:
|
def create_optimizer(model, **kwargs) -> optim.Optimizer:
|
||||||
return optim.AdamW(model.parameters(), fused=True, **kwargs)
|
decay_params = []
|
||||||
|
no_decay_params = []
|
||||||
|
for name, param in model.named_parameters():
|
||||||
|
if not param.requires_grad:
|
||||||
|
continue
|
||||||
|
if param.dim() < 2 or "norm" in name or "bias" in name:
|
||||||
|
no_decay_params.append(param)
|
||||||
|
else:
|
||||||
|
decay_params.append(param)
|
||||||
|
param_groups = [
|
||||||
|
{"params": decay_params, "weight_decay": kwargs.pop("weight_decay", 0.01)},
|
||||||
|
{"params": no_decay_params, "weight_decay": 0.0},
|
||||||
|
]
|
||||||
|
return optim.AdamW(param_groups, fused=True, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
def create_scheduler(
|
def create_scheduler(
|
||||||
@@ -266,7 +314,7 @@ def train(
|
|||||||
n_epoch: int,
|
n_epoch: int,
|
||||||
batch_per_device: int,
|
batch_per_device: int,
|
||||||
start_epoch: int,
|
start_epoch: int,
|
||||||
start_batch: int,
|
start_samples: int,
|
||||||
grad_accum_steps: int,
|
grad_accum_steps: int,
|
||||||
warmup_ratio: float,
|
warmup_ratio: float,
|
||||||
ckpt_interval: int,
|
ckpt_interval: int,
|
||||||
@@ -275,7 +323,6 @@ def train(
|
|||||||
val_step: int,
|
val_step: int,
|
||||||
metrics: list[str],
|
metrics: list[str],
|
||||||
log_dir: str,
|
log_dir: str,
|
||||||
log_interval: int,
|
|
||||||
dpo_beta: float,
|
dpo_beta: float,
|
||||||
grpo_clip_eps: float,
|
grpo_clip_eps: float,
|
||||||
grpo_kl_coef: float,
|
grpo_kl_coef: float,
|
||||||
@@ -300,6 +347,12 @@ def train(
|
|||||||
master_port: str,
|
master_port: str,
|
||||||
start_method: str,
|
start_method: str,
|
||||||
neftune_alpha: float,
|
neftune_alpha: float,
|
||||||
|
schedule_type: str,
|
||||||
|
min_rate: float,
|
||||||
|
cycle_length: int,
|
||||||
|
t_mult: int,
|
||||||
|
stable_steps: int,
|
||||||
|
decay_steps: int,
|
||||||
):
|
):
|
||||||
assert train_type in ["seq", "sft", "dpo", "grpo"]
|
assert train_type in ["seq", "sft", "dpo", "grpo"]
|
||||||
assert os.path.exists(param_path)
|
assert os.path.exists(param_path)
|
||||||
@@ -309,6 +362,7 @@ def train(
|
|||||||
# Load config
|
# Load config
|
||||||
config_path = os.path.join(param_path, "config.json")
|
config_path = os.path.join(param_path, "config.json")
|
||||||
config = AutoRegressiveLMConfig.from_file(config_path)
|
config = AutoRegressiveLMConfig.from_file(config_path)
|
||||||
|
config.neftune_alpha = neftune_alpha
|
||||||
|
|
||||||
if window_size is None:
|
if window_size is None:
|
||||||
window_size = config.max_len
|
window_size = config.max_len
|
||||||
@@ -348,14 +402,30 @@ def train(
|
|||||||
len(dataset), n_epoch, batch_per_device, nprocs, grad_accum_steps
|
len(dataset), n_epoch, batch_per_device, nprocs, grad_accum_steps
|
||||||
)
|
)
|
||||||
warmup_steps = int(warmup_ratio * total_steps)
|
warmup_steps = int(warmup_ratio * total_steps)
|
||||||
|
warmup_steps = min(warmup_steps, total_steps)
|
||||||
|
|
||||||
|
scheduler_kwargs = {"warmup_steps": warmup_steps}
|
||||||
|
|
||||||
|
if schedule_type == "cosine":
|
||||||
|
scheduler_kwargs["lr_decay_steps"] = total_steps - warmup_steps
|
||||||
|
elif schedule_type == "sgdr":
|
||||||
|
scheduler_kwargs["cycle_length"] = cycle_length or (total_steps - warmup_steps)
|
||||||
|
scheduler_kwargs["t_mult"] = t_mult
|
||||||
|
elif schedule_type == "wsd":
|
||||||
|
remaining = total_steps - warmup_steps
|
||||||
|
stable_steps_ = stable_steps or max(1, int(remaining * 0.8))
|
||||||
|
scheduler_kwargs["stable_steps"] = stable_steps_
|
||||||
|
scheduler_kwargs["decay_steps"] = max(
|
||||||
|
1, decay_steps or (remaining - stable_steps_)
|
||||||
|
)
|
||||||
|
|
||||||
|
if min_rate is not None:
|
||||||
|
scheduler_kwargs["min_rate"] = min_rate
|
||||||
|
|
||||||
scheduler_fn = partial(
|
scheduler_fn = partial(
|
||||||
create_scheduler,
|
create_scheduler,
|
||||||
**{
|
schedule_type=schedule_type,
|
||||||
"schedule_type": "cosine",
|
**scheduler_kwargs,
|
||||||
"warmup_steps": min(warmup_steps, total_steps),
|
|
||||||
"lr_decay_steps": total_steps - min(warmup_steps, total_steps),
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
|
|
||||||
grad_ckpt_modules = [DecoderBlock] if gradient_checkpointing else []
|
grad_ckpt_modules = [DecoderBlock] if gradient_checkpointing else []
|
||||||
@@ -370,7 +440,7 @@ def train(
|
|||||||
n_epoch=n_epoch,
|
n_epoch=n_epoch,
|
||||||
batch_per_device=batch_per_device,
|
batch_per_device=batch_per_device,
|
||||||
start_epoch=start_epoch,
|
start_epoch=start_epoch,
|
||||||
start_batch=start_batch,
|
start_samples=start_samples,
|
||||||
ckpt_interval=ckpt_interval,
|
ckpt_interval=ckpt_interval,
|
||||||
grad_accum_steps=grad_accum_steps,
|
grad_accum_steps=grad_accum_steps,
|
||||||
max_grad_norm=max_grad_norm,
|
max_grad_norm=max_grad_norm,
|
||||||
@@ -388,7 +458,6 @@ def train(
|
|||||||
val_step=val_step,
|
val_step=val_step,
|
||||||
metrics=metrics,
|
metrics=metrics,
|
||||||
log_dir=log_dir,
|
log_dir=log_dir,
|
||||||
log_interval=log_interval,
|
|
||||||
gradient_checkpointing_modules=grad_ckpt_modules,
|
gradient_checkpointing_modules=grad_ckpt_modules,
|
||||||
executor_kwargs=executor_kwargs,
|
executor_kwargs=executor_kwargs,
|
||||||
extra_kwargs=strategy_kwargs,
|
extra_kwargs=strategy_kwargs,
|
||||||
|
|||||||
+1
-1
@@ -75,7 +75,7 @@ class MultiTurnDataset(Dataset):
|
|||||||
|
|
||||||
|
|
||||||
class EarlyStoppingDataset(Dataset):
|
class EarlyStoppingDataset(Dataset):
|
||||||
"""Dataset that triggers early stopping after a specified number of iterations."""
|
"""Dataset that triggers early stopping after consuming a specified number of samples."""
|
||||||
|
|
||||||
def __init__(self, length=10, stop_after=5):
|
def __init__(self, length=10, stop_after=5):
|
||||||
self.length = length
|
self.length = length
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
import tempfile
|
import tempfile
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -8,6 +10,7 @@ from astrai.config.preprocess_config import (
|
|||||||
PipelineConfig,
|
PipelineConfig,
|
||||||
ProcessingConfig,
|
ProcessingConfig,
|
||||||
)
|
)
|
||||||
|
from astrai.preprocessing.builder import SectionedMaskBuilder
|
||||||
from astrai.tokenize import AutoTokenizer
|
from astrai.tokenize import AutoTokenizer
|
||||||
|
|
||||||
_SPECIAL_TOKENS_CONFIG = {
|
_SPECIAL_TOKENS_CONFIG = {
|
||||||
@@ -200,3 +203,33 @@ def make_grpo_no_template_config():
|
|||||||
mask_default="mask",
|
mask_default="mask",
|
||||||
preprocessing=ProcessingConfig(max_seq_len=2048),
|
preprocessing=ProcessingConfig(max_seq_len=2048),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def builder():
|
||||||
|
return SectionedMaskBuilder()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def tokenizer_dir(temp_dir, test_tokenizer):
|
||||||
|
d = os.path.join(temp_dir, "tok")
|
||||||
|
os.makedirs(d, exist_ok=True)
|
||||||
|
test_tokenizer._tokenizer.save(os.path.join(d, "tokenizer.json"))
|
||||||
|
with open(os.path.join(d, "tokenizer_config.json"), "w") as f:
|
||||||
|
json.dump(
|
||||||
|
{"special_tokens": {"pad_token": "<|_pad_|>", "unk_token": "<|_unk_|>"}}, f
|
||||||
|
)
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def chat_tokenizer_dir(temp_dir, chat_tokenizer):
|
||||||
|
d = os.path.join(temp_dir, "tok")
|
||||||
|
os.makedirs(d, exist_ok=True)
|
||||||
|
chat_tokenizer._tokenizer.save(os.path.join(d, "tokenizer.json"))
|
||||||
|
with open(os.path.join(d, "tokenizer_config.json"), "w") as f:
|
||||||
|
json.dump(
|
||||||
|
{"special_tokens": _SPECIAL_TOKENS_CONFIG, "chat_template": _CHAT_TEMPLATE},
|
||||||
|
f,
|
||||||
|
)
|
||||||
|
return d
|
||||||
|
|||||||
@@ -25,7 +25,9 @@ def test_single_process():
|
|||||||
|
|
||||||
scheduler.step()
|
scheduler.step()
|
||||||
|
|
||||||
checkpoint = Checkpoint(state_dict=model.state_dict(), epoch=3, iteration=30)
|
checkpoint = Checkpoint(
|
||||||
|
state_dict=model.state_dict(), epoch=3, consumed_samples=120
|
||||||
|
)
|
||||||
|
|
||||||
with tempfile.TemporaryDirectory() as tmpdir:
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
checkpoint.save(tmpdir)
|
checkpoint.save(tmpdir)
|
||||||
@@ -33,7 +35,7 @@ def test_single_process():
|
|||||||
loaded_checkpoint = Checkpoint.load(tmpdir)
|
loaded_checkpoint = Checkpoint.load(tmpdir)
|
||||||
|
|
||||||
assert loaded_checkpoint.epoch == 3
|
assert loaded_checkpoint.epoch == 3
|
||||||
assert loaded_checkpoint.iteration == 30
|
assert loaded_checkpoint.consumed_samples == 120
|
||||||
|
|
||||||
|
|
||||||
def test_checkpoint_with_extra():
|
def test_checkpoint_with_extra():
|
||||||
@@ -46,7 +48,10 @@ def test_checkpoint_with_extra():
|
|||||||
"scheduler": {"last_epoch": 5},
|
"scheduler": {"last_epoch": 5},
|
||||||
}
|
}
|
||||||
checkpoint = Checkpoint(
|
checkpoint = Checkpoint(
|
||||||
state_dict=model.state_dict(), epoch=1, iteration=10, extra=extra
|
state_dict=model.state_dict(),
|
||||||
|
epoch=1,
|
||||||
|
consumed_samples=40,
|
||||||
|
extra=extra,
|
||||||
)
|
)
|
||||||
|
|
||||||
with tempfile.TemporaryDirectory() as tmpdir:
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
@@ -77,7 +82,7 @@ def simple_training():
|
|||||||
checkpoint = Checkpoint(
|
checkpoint = Checkpoint(
|
||||||
state_dict=model.state_dict(),
|
state_dict=model.state_dict(),
|
||||||
epoch=2,
|
epoch=2,
|
||||||
iteration=10,
|
consumed_samples=40,
|
||||||
)
|
)
|
||||||
|
|
||||||
rank = get_rank()
|
rank = get_rank()
|
||||||
|
|||||||
+195
-125
@@ -1,42 +1,85 @@
|
|||||||
|
import json
|
||||||
import os
|
import os
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pytest
|
import pytest
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
|
from astrai.config.preprocess_config import PipelineConfig
|
||||||
from astrai.dataset.dataset import DatasetFactory, SEQDataset
|
from astrai.dataset.dataset import DatasetFactory, SEQDataset
|
||||||
from astrai.dataset.storage import (
|
from astrai.dataset.storage import (
|
||||||
H5Store,
|
H5Store,
|
||||||
StoreFactory,
|
StoreFactory,
|
||||||
detect_format,
|
detect_format,
|
||||||
|
)
|
||||||
|
from astrai.serialization import (
|
||||||
load_bin,
|
load_bin,
|
||||||
save_bin,
|
save_bin,
|
||||||
save_h5,
|
save_h5,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _rand_seq(length, vocab=1000):
|
||||||
|
return torch.randint(0, vocab, (length,), dtype=torch.int64)
|
||||||
|
|
||||||
|
|
||||||
|
def _save_test_tokenizer(test_dir, tokenizer):
|
||||||
|
tokenizer_path = os.path.join(test_dir, "tokenizer")
|
||||||
|
os.makedirs(tokenizer_path, exist_ok=True)
|
||||||
|
tokenizer.save_pretrained(tokenizer_path)
|
||||||
|
return tokenizer_path
|
||||||
|
|
||||||
|
|
||||||
|
def _write_jsonl_dataset(test_dir, tokenizer_path, records, config_overrides=None):
|
||||||
|
data_dir = os.path.join(test_dir, "jsonl_data")
|
||||||
|
os.makedirs(data_dir, exist_ok=True)
|
||||||
|
|
||||||
|
with open(os.path.join(data_dir, "data.jsonl"), "w", encoding="utf-8") as f:
|
||||||
|
for record in records:
|
||||||
|
f.write(json.dumps(record, ensure_ascii=False) + "\n")
|
||||||
|
|
||||||
|
config = {
|
||||||
|
"tokenizer_path": tokenizer_path,
|
||||||
|
"version": 1,
|
||||||
|
"input": {"sections": [{"field": "text", "action": "train"}]},
|
||||||
|
"preprocessing": {"max_seq_len": 128},
|
||||||
|
"output": {"position_ids_mode": "continuous"},
|
||||||
|
}
|
||||||
|
if config_overrides:
|
||||||
|
config.update(config_overrides)
|
||||||
|
|
||||||
|
with open(
|
||||||
|
os.path.join(data_dir, "dataset_config.json"), "w", encoding="utf-8"
|
||||||
|
) as f:
|
||||||
|
json.dump(config, f, ensure_ascii=False, indent=2)
|
||||||
|
|
||||||
|
return data_dir
|
||||||
|
|
||||||
|
|
||||||
|
def _make_seq_dataset(
|
||||||
|
test_dir, name="data", seq_length=200, train_type="seq", data=None, **load_kwargs
|
||||||
|
):
|
||||||
|
if data is None:
|
||||||
|
data = {"sequence": [_rand_seq(seq_length)]}
|
||||||
|
save_h5(test_dir, name, data)
|
||||||
|
return DatasetFactory.load(
|
||||||
|
train_type,
|
||||||
|
test_dir,
|
||||||
|
window_size=load_kwargs.pop("window_size", 64),
|
||||||
|
**load_kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_dataset_loader_random_paths(base_test_env):
|
def test_dataset_loader_random_paths(base_test_env):
|
||||||
"""Test dataset loader with multiple random paths"""
|
"""Test dataset loader with multiple random paths"""
|
||||||
test_dir = base_test_env["test_dir"]
|
test_dir = base_test_env["test_dir"]
|
||||||
|
|
||||||
# Create multiple mmap dataset directories with random data
|
|
||||||
num_files = np.random.randint(2, 5)
|
num_files = np.random.randint(2, 5)
|
||||||
|
|
||||||
for i in range(num_files):
|
for i in range(num_files):
|
||||||
seq_length = np.random.randint(200, 400)
|
seq_length = np.random.randint(200, 400)
|
||||||
dummy_data = {
|
dummy_data = {"sequence": [_rand_seq(seq_length) for _ in range(10)]}
|
||||||
"sequence": [
|
loaded_dataset = _make_seq_dataset(
|
||||||
torch.randint(0, 1000, (seq_length,), dtype=torch.int64)
|
test_dir, f"data_{i}", seq_length, data=dummy_data
|
||||||
for _ in range(10)
|
|
||||||
],
|
|
||||||
}
|
|
||||||
save_h5(test_dir, f"data_{i}", dummy_data)
|
|
||||||
|
|
||||||
# Test loading with multiple paths
|
|
||||||
loaded_dataset = DatasetFactory.load(
|
|
||||||
train_type="seq",
|
|
||||||
load_path=test_dir,
|
|
||||||
window_size=64,
|
|
||||||
)
|
)
|
||||||
assert loaded_dataset is not None
|
assert loaded_dataset is not None
|
||||||
assert len(loaded_dataset) > 0
|
assert len(loaded_dataset) > 0
|
||||||
@@ -54,23 +97,15 @@ def test_dpo_strategy_with_random_data(base_test_env):
|
|||||||
"""Test DPO strategy with randomized preference data"""
|
"""Test DPO strategy with randomized preference data"""
|
||||||
test_dir = base_test_env["test_dir"]
|
test_dir = base_test_env["test_dir"]
|
||||||
|
|
||||||
# Create DPO-style data with memory mapping format
|
|
||||||
seq_length = np.random.randint(100, 200)
|
seq_length = np.random.randint(100, 200)
|
||||||
|
|
||||||
dummy_data = {
|
dummy_data = {
|
||||||
"chosen": [torch.randint(0, 1000, (seq_length,), dtype=torch.int64)],
|
"chosen": [_rand_seq(seq_length)],
|
||||||
"rejected": [torch.randint(0, 1000, (seq_length,), dtype=torch.int64)],
|
"rejected": [_rand_seq(seq_length)],
|
||||||
"chosen_mask": [torch.ones(seq_length, dtype=torch.bool)],
|
"chosen_mask": [torch.ones(seq_length, dtype=torch.bool)],
|
||||||
"rejected_mask": [torch.ones(seq_length, dtype=torch.bool)],
|
"rejected_mask": [torch.ones(seq_length, dtype=torch.bool)],
|
||||||
}
|
}
|
||||||
|
dpo_dataset = _make_seq_dataset(
|
||||||
save_h5(test_dir, "dpo_data", dummy_data)
|
test_dir, "dpo_data", seq_length, train_type="dpo", data=dummy_data
|
||||||
|
|
||||||
# Load DPO dataset
|
|
||||||
dpo_dataset = DatasetFactory.load(
|
|
||||||
train_type="dpo",
|
|
||||||
load_path=test_dir,
|
|
||||||
window_size=64,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
assert dpo_dataset is not None
|
assert dpo_dataset is not None
|
||||||
@@ -92,22 +127,14 @@ def test_sft_dataset_with_random_data(base_test_env):
|
|||||||
"""Test SFT dataset with random data"""
|
"""Test SFT dataset with random data"""
|
||||||
test_dir = base_test_env["test_dir"]
|
test_dir = base_test_env["test_dir"]
|
||||||
|
|
||||||
# Create SFT-style data with memory mapping format
|
|
||||||
seq_length = np.random.randint(100, 200)
|
seq_length = np.random.randint(100, 200)
|
||||||
|
|
||||||
dummy_data = {
|
dummy_data = {
|
||||||
"sequence": [torch.randint(0, 1000, (seq_length,), dtype=torch.int64)],
|
"sequence": [_rand_seq(seq_length)],
|
||||||
"loss_mask": [torch.ones(seq_length, dtype=torch.bool)],
|
"loss_mask": [torch.ones(seq_length, dtype=torch.bool)],
|
||||||
"position_ids": [torch.arange(seq_length, dtype=torch.int32)],
|
"position_ids": [torch.arange(seq_length, dtype=torch.int32)],
|
||||||
}
|
}
|
||||||
|
sft_dataset = _make_seq_dataset(
|
||||||
save_h5(test_dir, "sft_data", dummy_data)
|
test_dir, "sft_data", seq_length, train_type="sft", data=dummy_data
|
||||||
|
|
||||||
# Load SFT dataset
|
|
||||||
sft_dataset = DatasetFactory.load(
|
|
||||||
train_type="sft",
|
|
||||||
load_path=test_dir,
|
|
||||||
window_size=64,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
assert sft_dataset is not None
|
assert sft_dataset is not None
|
||||||
@@ -128,25 +155,11 @@ def test_dataset_with_custom_stride(base_test_env):
|
|||||||
"""Test dataset with custom stride parameter"""
|
"""Test dataset with custom stride parameter"""
|
||||||
test_dir = base_test_env["test_dir"]
|
test_dir = base_test_env["test_dir"]
|
||||||
|
|
||||||
# Create test data
|
|
||||||
seq_length = 200
|
|
||||||
dummy_data = {
|
|
||||||
"sequence": [torch.randint(0, 1000, (seq_length,), dtype=torch.int64)],
|
|
||||||
}
|
|
||||||
|
|
||||||
save_h5(test_dir, "stride_test_data", dummy_data)
|
|
||||||
|
|
||||||
# Test with custom stride
|
|
||||||
custom_stride = 32
|
custom_stride = 32
|
||||||
dataset = DatasetFactory.load(
|
dataset = _make_seq_dataset(test_dir, "stride_test_data", stride=custom_stride)
|
||||||
train_type="seq", load_path=test_dir, window_size=64, stride=custom_stride
|
|
||||||
)
|
|
||||||
|
|
||||||
assert dataset is not None
|
assert dataset is not None
|
||||||
assert len(dataset) > 0
|
assert len(dataset) > 0
|
||||||
|
|
||||||
# With stride 32 and window 64 on 200 length data, we should get more samples
|
|
||||||
# than with default stride (which equals window size)
|
|
||||||
default_stride_dataset = DatasetFactory.load(
|
default_stride_dataset = DatasetFactory.load(
|
||||||
train_type="seq",
|
train_type="seq",
|
||||||
load_path=test_dir,
|
load_path=test_dir,
|
||||||
@@ -157,25 +170,11 @@ def test_dataset_with_custom_stride(base_test_env):
|
|||||||
|
|
||||||
|
|
||||||
def test_dataset_count_property(base_test_env):
|
def test_dataset_count_property(base_test_env):
|
||||||
"""Test the count property returns correct raw token count"""
|
|
||||||
test_dir = base_test_env["test_dir"]
|
test_dir = base_test_env["test_dir"]
|
||||||
|
dataset = _make_seq_dataset(test_dir, "count_test_data")
|
||||||
seq_length = 200
|
assert dataset.count == 200
|
||||||
dummy_data = {
|
assert dataset.count > len(dataset)
|
||||||
"sequence": [torch.randint(0, 1000, (seq_length,), dtype=torch.int64)],
|
assert len(dataset) == (200 - 1 - 64) // 64 + 1
|
||||||
}
|
|
||||||
|
|
||||||
save_h5(test_dir, "count_test_data", dummy_data)
|
|
||||||
|
|
||||||
dataset = DatasetFactory.load(
|
|
||||||
train_type="seq",
|
|
||||||
load_path=test_dir,
|
|
||||||
window_size=64,
|
|
||||||
)
|
|
||||||
|
|
||||||
assert dataset.count == seq_length
|
|
||||||
assert dataset.count > len(dataset) # raw tokens > windows
|
|
||||||
assert len(dataset) == (seq_length - 1 - 64) // 64 + 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_empty_dataset_count():
|
def test_empty_dataset_count():
|
||||||
@@ -186,17 +185,10 @@ def test_empty_dataset_count():
|
|||||||
|
|
||||||
|
|
||||||
def test_dataset_too_short_for_window(base_test_env):
|
def test_dataset_too_short_for_window(base_test_env):
|
||||||
"""Dataset shorter than window_size returns __len__ == 0"""
|
|
||||||
test_dir = base_test_env["test_dir"]
|
test_dir = base_test_env["test_dir"]
|
||||||
seq_length = 30
|
dataset = _make_seq_dataset(test_dir, "short", seq_length=30)
|
||||||
save_h5(
|
|
||||||
test_dir,
|
|
||||||
"short",
|
|
||||||
{"sequence": [torch.randint(0, 1000, (seq_length,), dtype=torch.int64)]},
|
|
||||||
)
|
|
||||||
dataset = DatasetFactory.load("seq", test_dir, window_size=64)
|
|
||||||
assert len(dataset) == 0
|
assert len(dataset) == 0
|
||||||
assert dataset.count == seq_length
|
assert dataset.count == 30
|
||||||
|
|
||||||
|
|
||||||
def test_unloaded_dataset_getitem_raises():
|
def test_unloaded_dataset_getitem_raises():
|
||||||
@@ -220,12 +212,8 @@ def test_store_unloaded_len():
|
|||||||
|
|
||||||
|
|
||||||
def test_store_fetch_begin_equals_end(base_test_env):
|
def test_store_fetch_begin_equals_end(base_test_env):
|
||||||
"""Store.fetch with begin == end returns empty tensor"""
|
|
||||||
test_dir = base_test_env["test_dir"]
|
test_dir = base_test_env["test_dir"]
|
||||||
dummy = {"sequence": [torch.randint(0, 1000, (100,), dtype=torch.int64)]}
|
dataset = _make_seq_dataset(test_dir, "empty_fetch", seq_length=100, window_size=32)
|
||||||
save_h5(test_dir, "empty_fetch", dummy)
|
|
||||||
|
|
||||||
dataset = DatasetFactory.load("seq", test_dir, window_size=32)
|
|
||||||
result = dataset.storage.fetch(10, 10, "sequence")
|
result = dataset.storage.fetch(10, 10, "sequence")
|
||||||
assert result.numel() == 0
|
assert result.numel() == 0
|
||||||
|
|
||||||
@@ -299,12 +287,8 @@ def test_save_load_bin_roundtrip(base_test_env):
|
|||||||
|
|
||||||
|
|
||||||
def test_mmap_store_load_and_fetch(base_test_env):
|
def test_mmap_store_load_and_fetch(base_test_env):
|
||||||
"""MmapStore loads bin data and fetches correctly"""
|
|
||||||
test_dir = base_test_env["test_dir"]
|
test_dir = base_test_env["test_dir"]
|
||||||
|
data = {"sequence": [_rand_seq(200)]}
|
||||||
data = {
|
|
||||||
"sequence": [torch.randint(0, 1000, (200,), dtype=torch.int64)],
|
|
||||||
}
|
|
||||||
save_bin(test_dir, data)
|
save_bin(test_dir, data)
|
||||||
|
|
||||||
store = StoreFactory.create("bin")
|
store = StoreFactory.create("bin")
|
||||||
@@ -317,14 +301,9 @@ def test_mmap_store_load_and_fetch(base_test_env):
|
|||||||
|
|
||||||
|
|
||||||
def test_mmap_dataset_load(base_test_env):
|
def test_mmap_dataset_load(base_test_env):
|
||||||
"""DatasetFactory.load auto-detects bin format"""
|
|
||||||
test_dir = base_test_env["test_dir"]
|
test_dir = base_test_env["test_dir"]
|
||||||
|
data = {"sequence": [_rand_seq(200)]}
|
||||||
data = {
|
|
||||||
"sequence": [torch.randint(0, 1000, (200,), dtype=torch.int64)],
|
|
||||||
}
|
|
||||||
save_bin(test_dir, data)
|
save_bin(test_dir, data)
|
||||||
|
|
||||||
dataset = DatasetFactory.load("seq", test_dir, window_size=64)
|
dataset = DatasetFactory.load("seq", test_dir, window_size=64)
|
||||||
assert len(dataset) > 0
|
assert len(dataset) > 0
|
||||||
assert dataset.count == 200
|
assert dataset.count == 200
|
||||||
@@ -348,19 +327,16 @@ def test_normalize_mixed_empty_key():
|
|||||||
|
|
||||||
|
|
||||||
def test_grpo_dataset_dtype(base_test_env):
|
def test_grpo_dataset_dtype(base_test_env):
|
||||||
"""GRPODataset returns correct dtypes"""
|
|
||||||
test_dir = base_test_env["test_dir"]
|
test_dir = base_test_env["test_dir"]
|
||||||
|
dummy_data = {
|
||||||
seq_len = 100
|
"prompts": [torch.randint(0, 100, (100,), dtype=torch.int32)],
|
||||||
data = {
|
"responses": [torch.randint(0, 100, (100,), dtype=torch.int32)],
|
||||||
"prompts": [torch.randint(0, 100, (seq_len,), dtype=torch.int32)],
|
"masks": [torch.ones(100, dtype=torch.int32)],
|
||||||
"responses": [torch.randint(0, 100, (seq_len,), dtype=torch.int32)],
|
"rewards": [torch.ones(100, dtype=torch.float32)],
|
||||||
"masks": [torch.ones(seq_len, dtype=torch.int32)],
|
|
||||||
"rewards": [torch.ones(seq_len, dtype=torch.float32)],
|
|
||||||
}
|
}
|
||||||
save_h5(test_dir, "grpo_dtype", data)
|
dataset = _make_seq_dataset(
|
||||||
|
test_dir, "grpo_dtype", train_type="grpo", data=dummy_data, window_size=32
|
||||||
dataset = DatasetFactory.load("grpo", test_dir, window_size=32)
|
)
|
||||||
item = dataset[0]
|
item = dataset[0]
|
||||||
|
|
||||||
assert item["prompts"].dtype == torch.long
|
assert item["prompts"].dtype == torch.long
|
||||||
@@ -370,18 +346,16 @@ def test_grpo_dataset_dtype(base_test_env):
|
|||||||
|
|
||||||
|
|
||||||
def test_grpo_dataset_load(base_test_env):
|
def test_grpo_dataset_load(base_test_env):
|
||||||
"""GRPODataset loads and returns correct keys"""
|
|
||||||
test_dir = base_test_env["test_dir"]
|
test_dir = base_test_env["test_dir"]
|
||||||
seq_len = 200
|
dummy_data = {
|
||||||
data = {
|
"prompts": [_rand_seq(200)],
|
||||||
"prompts": [torch.randint(0, 1000, (seq_len,), dtype=torch.int64)],
|
"responses": [_rand_seq(200)],
|
||||||
"responses": [torch.randint(0, 1000, (seq_len,), dtype=torch.int64)],
|
"masks": [torch.ones(200, dtype=torch.int64)],
|
||||||
"masks": [torch.ones(seq_len, dtype=torch.int64)],
|
"rewards": [torch.rand(200, dtype=torch.float32)],
|
||||||
"rewards": [torch.rand(seq_len, dtype=torch.float32)],
|
|
||||||
}
|
}
|
||||||
save_h5(test_dir, "grpo_test", data)
|
dataset = _make_seq_dataset(
|
||||||
|
test_dir, "grpo_test", train_type="grpo", data=dummy_data
|
||||||
dataset = DatasetFactory.load("grpo", test_dir, window_size=64)
|
)
|
||||||
assert len(dataset) > 0
|
assert len(dataset) > 0
|
||||||
item = dataset[0]
|
item = dataset[0]
|
||||||
assert "prompts" in item
|
assert "prompts" in item
|
||||||
@@ -400,7 +374,6 @@ def test_detect_format_bin_dir(base_test_env):
|
|||||||
|
|
||||||
|
|
||||||
def test_store_fetch_multi_key(base_test_env):
|
def test_store_fetch_multi_key(base_test_env):
|
||||||
"""Store.fetch with List[str] returns Dict[str, Tensor]"""
|
|
||||||
test_dir = base_test_env["test_dir"]
|
test_dir = base_test_env["test_dir"]
|
||||||
save_h5(
|
save_h5(
|
||||||
test_dir,
|
test_dir,
|
||||||
@@ -410,7 +383,6 @@ def test_store_fetch_multi_key(base_test_env):
|
|||||||
"loss_mask": [torch.ones(100, dtype=torch.int64)],
|
"loss_mask": [torch.ones(100, dtype=torch.int64)],
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
store = StoreFactory.create("h5")
|
store = StoreFactory.create("h5")
|
||||||
store.load(test_dir)
|
store.load(test_dir)
|
||||||
result = store.fetch(10, 20, ["sequence", "loss_mask"])
|
result = store.fetch(10, 20, ["sequence", "loss_mask"])
|
||||||
@@ -420,10 +392,8 @@ def test_store_fetch_multi_key(base_test_env):
|
|||||||
|
|
||||||
|
|
||||||
def test_store_fetch_out_of_bounds(base_test_env):
|
def test_store_fetch_out_of_bounds(base_test_env):
|
||||||
"""Store.fetch raises ValueError for out-of-bounds indices"""
|
|
||||||
test_dir = base_test_env["test_dir"]
|
test_dir = base_test_env["test_dir"]
|
||||||
save_h5(test_dir, "bounds", {"sequence": [torch.randint(0, 100, (50,))]})
|
save_h5(test_dir, "bounds", {"sequence": [torch.randint(0, 100, (50,))]})
|
||||||
|
|
||||||
store = StoreFactory.create("h5")
|
store = StoreFactory.create("h5")
|
||||||
store.load(test_dir)
|
store.load(test_dir)
|
||||||
with pytest.raises(ValueError, match="out of bounds"):
|
with pytest.raises(ValueError, match="out of bounds"):
|
||||||
@@ -435,10 +405,110 @@ def test_store_fetch_out_of_bounds(base_test_env):
|
|||||||
|
|
||||||
|
|
||||||
def test_dataset_load_explicit_storage_type(base_test_env):
|
def test_dataset_load_explicit_storage_type(base_test_env):
|
||||||
"""DatasetFactory.load with explicit storage_type bypasses auto-detect"""
|
|
||||||
test_dir = base_test_env["test_dir"]
|
test_dir = base_test_env["test_dir"]
|
||||||
save_h5(test_dir, "explicit", {"sequence": [torch.randint(0, 100, (200,))]})
|
dataset = _make_seq_dataset(test_dir, "explicit", storage_type="h5")
|
||||||
|
|
||||||
dataset = DatasetFactory.load("seq", test_dir, window_size=64, storage_type="h5")
|
|
||||||
assert len(dataset) > 0
|
assert len(dataset) > 0
|
||||||
assert dataset.count == 200
|
assert dataset.count == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_detect_format_jsonl_dir(base_test_env):
|
||||||
|
test_dir = base_test_env["test_dir"]
|
||||||
|
tokenizer_path = _save_test_tokenizer(test_dir, base_test_env["tokenizer"])
|
||||||
|
data_dir = _write_jsonl_dataset(
|
||||||
|
test_dir,
|
||||||
|
tokenizer_path,
|
||||||
|
[{"text": "hello world"}, {"text": "foo bar baz"}],
|
||||||
|
)
|
||||||
|
assert detect_format(data_dir) == "jsonl"
|
||||||
|
|
||||||
|
|
||||||
|
def test_jsonl_store_seq(base_test_env):
|
||||||
|
test_dir = base_test_env["test_dir"]
|
||||||
|
tokenizer_path = _save_test_tokenizer(test_dir, base_test_env["tokenizer"])
|
||||||
|
data_dir = _write_jsonl_dataset(
|
||||||
|
test_dir,
|
||||||
|
tokenizer_path,
|
||||||
|
[{"text": "hello world"}, {"text": "foo bar baz qux"}],
|
||||||
|
config_overrides={"preprocessing": {"max_seq_len": 128, "min_chars": 0}},
|
||||||
|
)
|
||||||
|
|
||||||
|
store = StoreFactory.create("jsonl")
|
||||||
|
store.load(data_dir)
|
||||||
|
assert len(store) > 0
|
||||||
|
assert "sequence" in store.keys
|
||||||
|
|
||||||
|
dataset = DatasetFactory.load("seq", data_dir, window_size=8)
|
||||||
|
assert len(dataset) > 0
|
||||||
|
item = dataset[0]
|
||||||
|
assert "input_ids" in item
|
||||||
|
assert "target_ids" in item
|
||||||
|
assert item["input_ids"].dtype == torch.long
|
||||||
|
|
||||||
|
|
||||||
|
def test_jsonl_store_sft(base_test_env):
|
||||||
|
test_dir = base_test_env["test_dir"]
|
||||||
|
tokenizer = base_test_env["tokenizer"]
|
||||||
|
tokenizer.set_chat_template(
|
||||||
|
"{% for message in messages %}{{ message['role'] }}:{{ message['content'] }}\n{% endfor %}"
|
||||||
|
)
|
||||||
|
tokenizer_path = _save_test_tokenizer(test_dir, tokenizer)
|
||||||
|
data_dir = _write_jsonl_dataset(
|
||||||
|
test_dir,
|
||||||
|
tokenizer_path,
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"messages": [
|
||||||
|
{"role": "system", "content": "sys"},
|
||||||
|
{"role": "user", "content": "hi"},
|
||||||
|
{"role": "assistant", "content": "hello"},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
config_overrides={
|
||||||
|
"input": {
|
||||||
|
"sections": [{"field": "messages", "action": "$role", "template": True}]
|
||||||
|
},
|
||||||
|
"mask": {"system": "mask", "user": "mask", "assistant": "train"},
|
||||||
|
"mask_default": "mask",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
store = StoreFactory.create("jsonl")
|
||||||
|
store.load(data_dir)
|
||||||
|
assert "sequence" in store.keys
|
||||||
|
assert "loss_mask" in store.keys
|
||||||
|
assert "position_ids" in store.keys
|
||||||
|
|
||||||
|
dataset = DatasetFactory.load("sft", data_dir, window_size=8)
|
||||||
|
item = dataset[0]
|
||||||
|
assert "input_ids" in item
|
||||||
|
assert "target_ids" in item
|
||||||
|
assert "loss_mask" in item
|
||||||
|
assert "position_ids" in item
|
||||||
|
assert item["loss_mask"].dtype == torch.bool
|
||||||
|
|
||||||
|
|
||||||
|
def test_jsonl_store_pipeline_config_roundtrip(base_test_env):
|
||||||
|
test_dir = base_test_env["test_dir"]
|
||||||
|
config_path = os.path.join(test_dir, "dataset_config.json")
|
||||||
|
with open(config_path, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(
|
||||||
|
{
|
||||||
|
"tokenizer_path": os.path.join(test_dir, "tokenizer"),
|
||||||
|
"version": 1,
|
||||||
|
"input": {"sections": [{"field": "text", "action": "train"}]},
|
||||||
|
"mask": {"assistant": "train"},
|
||||||
|
"preprocessing": {"max_seq_len": 64},
|
||||||
|
"output": {"position_ids_mode": "doc_reset"},
|
||||||
|
},
|
||||||
|
f,
|
||||||
|
ensure_ascii=False,
|
||||||
|
indent=2,
|
||||||
|
)
|
||||||
|
|
||||||
|
with open(config_path, "r", encoding="utf-8") as f:
|
||||||
|
raw = json.load(f)
|
||||||
|
raw.pop("tokenizer_path")
|
||||||
|
config = PipelineConfig.from_dict(raw)
|
||||||
|
assert config.output.position_ids_mode == "doc_reset"
|
||||||
|
assert config.preprocessing.max_seq_len == 64
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
from astrai.config.preprocess_config import (
|
from astrai.config.preprocess_config import (
|
||||||
InputConfig,
|
InputConfig,
|
||||||
OutputConfig,
|
OutputConfig,
|
||||||
@@ -20,9 +22,8 @@ from tests.data.conftest import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_chat_simple(chat_tokenizer):
|
def test_chat_simple(chat_tokenizer, builder):
|
||||||
config = make_chat_config()
|
config = make_chat_config()
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {
|
item = {
|
||||||
"messages": [
|
"messages": [
|
||||||
{"role": "system", "content": "You are helpful."},
|
{"role": "system", "content": "You are helpful."},
|
||||||
@@ -46,9 +47,8 @@ def test_chat_simple(chat_tokenizer):
|
|||||||
assert trained < total
|
assert trained < total
|
||||||
|
|
||||||
|
|
||||||
def test_chat_mask_only_assistant(chat_tokenizer):
|
def test_chat_mask_only_assistant(chat_tokenizer, builder):
|
||||||
config = make_chat_config()
|
config = make_chat_config()
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {
|
item = {
|
||||||
"messages": [
|
"messages": [
|
||||||
{"role": "user", "content": "What is 2+2?"},
|
{"role": "user", "content": "What is 2+2?"},
|
||||||
@@ -66,14 +66,22 @@ def test_chat_mask_only_assistant(chat_tokenizer):
|
|||||||
assert len(masked) > 0
|
assert len(masked) > 0
|
||||||
|
|
||||||
|
|
||||||
def test_chat_all_masked(chat_tokenizer):
|
@pytest.mark.parametrize(
|
||||||
|
"mask_rules,mask_default,expect_nonzero",
|
||||||
|
[
|
||||||
|
({"system": "mask", "user": "mask", "assistant": "mask"}, "mask", False),
|
||||||
|
({}, "train", True),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_chat_uniform_masking(
|
||||||
|
mask_rules, mask_default, expect_nonzero, chat_tokenizer, builder
|
||||||
|
):
|
||||||
config = PipelineConfig(
|
config = PipelineConfig(
|
||||||
input=InputConfig(sections=_CHAT_SECTIONS),
|
input=InputConfig(sections=_CHAT_SECTIONS),
|
||||||
mask={"system": "mask", "user": "mask", "assistant": "mask"},
|
mask=mask_rules,
|
||||||
mask_default="mask",
|
mask_default=mask_default,
|
||||||
preprocessing=ProcessingConfig(max_seq_len=2048),
|
preprocessing=ProcessingConfig(max_seq_len=2048),
|
||||||
)
|
)
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {
|
item = {
|
||||||
"messages": [
|
"messages": [
|
||||||
{"role": "system", "content": "You are helpful."},
|
{"role": "system", "content": "You are helpful."},
|
||||||
@@ -81,35 +89,20 @@ def test_chat_all_masked(chat_tokenizer):
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
result = builder.build(item, config, chat_tokenizer)
|
result = builder.build(item, config, chat_tokenizer)
|
||||||
assert sum(result["loss_mask"]) == 0
|
masked_count = sum(result["loss_mask"])
|
||||||
|
if expect_nonzero:
|
||||||
|
assert masked_count > 0
|
||||||
|
else:
|
||||||
|
assert masked_count == 0
|
||||||
|
|
||||||
|
|
||||||
def test_chat_all_trained(chat_tokenizer):
|
def test_chat_empty_messages(chat_tokenizer, builder):
|
||||||
config = PipelineConfig(
|
|
||||||
input=InputConfig(sections=_CHAT_SECTIONS),
|
|
||||||
mask={},
|
|
||||||
mask_default="train",
|
|
||||||
preprocessing=ProcessingConfig(max_seq_len=2048),
|
|
||||||
)
|
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {
|
|
||||||
"messages": [
|
|
||||||
{"role": "system", "content": "You are helpful."},
|
|
||||||
{"role": "assistant", "content": "Hi there!"},
|
|
||||||
]
|
|
||||||
}
|
|
||||||
result = builder.build(item, config, chat_tokenizer)
|
|
||||||
assert sum(result["loss_mask"]) == len(result["sequence"]) - 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_chat_empty_messages(chat_tokenizer):
|
|
||||||
config = make_chat_config()
|
config = make_chat_config()
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
assert builder.build({"messages": []}, config, chat_tokenizer) is None
|
assert builder.build({"messages": []}, config, chat_tokenizer) is None
|
||||||
assert builder.build({}, config, chat_tokenizer) is None
|
assert builder.build({}, config, chat_tokenizer) is None
|
||||||
|
|
||||||
|
|
||||||
def test_chat_domain_extraction(chat_tokenizer):
|
def test_chat_domain_extraction(chat_tokenizer, builder):
|
||||||
config = PipelineConfig(
|
config = PipelineConfig(
|
||||||
input=InputConfig(sections=_CHAT_SECTIONS),
|
input=InputConfig(sections=_CHAT_SECTIONS),
|
||||||
mask={"assistant": "train"},
|
mask={"assistant": "train"},
|
||||||
@@ -117,7 +110,6 @@ def test_chat_domain_extraction(chat_tokenizer):
|
|||||||
preprocessing=ProcessingConfig(max_seq_len=2048),
|
preprocessing=ProcessingConfig(max_seq_len=2048),
|
||||||
output=OutputConfig(domain_key="source"),
|
output=OutputConfig(domain_key="source"),
|
||||||
)
|
)
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {
|
item = {
|
||||||
"messages": [
|
"messages": [
|
||||||
{"role": "user", "content": "Hi"},
|
{"role": "user", "content": "Hi"},
|
||||||
@@ -129,14 +121,13 @@ def test_chat_domain_extraction(chat_tokenizer):
|
|||||||
assert result["domain"] == "wiki"
|
assert result["domain"] == "wiki"
|
||||||
|
|
||||||
|
|
||||||
def test_chat_truncation(chat_tokenizer):
|
def test_chat_truncation(chat_tokenizer, builder):
|
||||||
config = PipelineConfig(
|
config = PipelineConfig(
|
||||||
input=InputConfig(sections=_CHAT_SECTIONS),
|
input=InputConfig(sections=_CHAT_SECTIONS),
|
||||||
mask={"assistant": "train"},
|
mask={"assistant": "train"},
|
||||||
mask_default="mask",
|
mask_default="mask",
|
||||||
preprocessing=ProcessingConfig(max_seq_len=10),
|
preprocessing=ProcessingConfig(max_seq_len=10),
|
||||||
)
|
)
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {
|
item = {
|
||||||
"messages": [
|
"messages": [
|
||||||
{
|
{
|
||||||
@@ -151,18 +142,16 @@ def test_chat_truncation(chat_tokenizer):
|
|||||||
assert len(result["loss_mask"]) == len(result["sequence"])
|
assert len(result["loss_mask"]) == len(result["sequence"])
|
||||||
|
|
||||||
|
|
||||||
def test_instruction_basic(test_tokenizer):
|
def test_instruction_basic(test_tokenizer, builder):
|
||||||
config = make_instruction_config()
|
config = make_instruction_config()
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {"prompt": "Translate to French: Hello", "response": "Bonjour"}
|
item = {"prompt": "Translate to French: Hello", "response": "Bonjour"}
|
||||||
result = builder.build(item, config, test_tokenizer)
|
result = builder.build(item, config, test_tokenizer)
|
||||||
assert result is not None
|
assert result is not None
|
||||||
assert len(result["sequence"]) == len(result["loss_mask"])
|
assert len(result["sequence"]) == len(result["loss_mask"])
|
||||||
|
|
||||||
|
|
||||||
def test_instruction_prompt_masked(test_tokenizer):
|
def test_instruction_prompt_masked(test_tokenizer, builder):
|
||||||
config = make_instruction_config()
|
config = make_instruction_config()
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {"prompt": "hello", "response": "world"}
|
item = {"prompt": "hello", "response": "world"}
|
||||||
result = builder.build(item, config, test_tokenizer)
|
result = builder.build(item, config, test_tokenizer)
|
||||||
mask = result["loss_mask"]
|
mask = result["loss_mask"]
|
||||||
@@ -175,7 +164,7 @@ def test_instruction_prompt_masked(test_tokenizer):
|
|||||||
assert all(m == 1 for m in mask[p_len:])
|
assert all(m == 1 for m in mask[p_len:])
|
||||||
|
|
||||||
|
|
||||||
def test_instruction_train_on_prompt(test_tokenizer):
|
def test_instruction_train_on_prompt(test_tokenizer, builder):
|
||||||
config = PipelineConfig(
|
config = PipelineConfig(
|
||||||
input=InputConfig(
|
input=InputConfig(
|
||||||
sections=[
|
sections=[
|
||||||
@@ -185,7 +174,6 @@ def test_instruction_train_on_prompt(test_tokenizer):
|
|||||||
),
|
),
|
||||||
preprocessing=ProcessingConfig(max_seq_len=2048),
|
preprocessing=ProcessingConfig(max_seq_len=2048),
|
||||||
)
|
)
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {"prompt": "hello", "response": "world"}
|
item = {"prompt": "hello", "response": "world"}
|
||||||
result = builder.build(item, config, test_tokenizer)
|
result = builder.build(item, config, test_tokenizer)
|
||||||
mask = result["loss_mask"]
|
mask = result["loss_mask"]
|
||||||
@@ -196,9 +184,8 @@ def test_instruction_train_on_prompt(test_tokenizer):
|
|||||||
assert all(m == 1 for m in mask[:p_len])
|
assert all(m == 1 for m in mask[:p_len])
|
||||||
|
|
||||||
|
|
||||||
def test_text_basic(test_tokenizer):
|
def test_text_basic(test_tokenizer, builder):
|
||||||
config = make_text_config()
|
config = make_text_config()
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {"text": "Hello world. This is a test document."}
|
item = {"text": "Hello world. This is a test document."}
|
||||||
result = builder.build(item, config, test_tokenizer)
|
result = builder.build(item, config, test_tokenizer)
|
||||||
assert result is not None
|
assert result is not None
|
||||||
@@ -207,41 +194,37 @@ def test_text_basic(test_tokenizer):
|
|||||||
assert "loss_mask" not in result
|
assert "loss_mask" not in result
|
||||||
|
|
||||||
|
|
||||||
def test_text_empty(test_tokenizer):
|
def test_text_empty(test_tokenizer, builder):
|
||||||
config = make_text_config()
|
config = make_text_config()
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
assert builder.build({"text": ""}, config, test_tokenizer) is None
|
assert builder.build({"text": ""}, config, test_tokenizer) is None
|
||||||
assert builder.build({"text": " "}, config, test_tokenizer) is None
|
assert builder.build({"text": " "}, config, test_tokenizer) is None
|
||||||
|
|
||||||
|
|
||||||
def test_text_too_short(test_tokenizer):
|
def test_text_too_short(test_tokenizer, builder):
|
||||||
config = PipelineConfig(
|
config = PipelineConfig(
|
||||||
input=InputConfig(sections=_TEXT_SECTIONS),
|
input=InputConfig(sections=_TEXT_SECTIONS),
|
||||||
preprocessing=ProcessingConfig(min_chars=100),
|
preprocessing=ProcessingConfig(min_chars=100),
|
||||||
)
|
)
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
assert builder.build({"text": "short"}, config, test_tokenizer) is None
|
assert builder.build({"text": "short"}, config, test_tokenizer) is None
|
||||||
|
|
||||||
|
|
||||||
def test_text_truncation(test_tokenizer):
|
def test_text_truncation(test_tokenizer, builder):
|
||||||
config = PipelineConfig(
|
config = PipelineConfig(
|
||||||
input=InputConfig(sections=_TEXT_SECTIONS),
|
input=InputConfig(sections=_TEXT_SECTIONS),
|
||||||
preprocessing=ProcessingConfig(max_seq_len=3, min_chars=1),
|
preprocessing=ProcessingConfig(max_seq_len=3, min_chars=1),
|
||||||
)
|
)
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {"text": "This is a very long text that should be truncated"}
|
item = {"text": "This is a very long text that should be truncated"}
|
||||||
result = builder.build(item, config, test_tokenizer)
|
result = builder.build(item, config, test_tokenizer)
|
||||||
assert len(result["sequence"]) <= 3
|
assert len(result["sequence"]) <= 3
|
||||||
|
|
||||||
|
|
||||||
def test_sectioned_chat(chat_tokenizer):
|
def test_sectioned_chat(chat_tokenizer, builder):
|
||||||
config = PipelineConfig(
|
config = PipelineConfig(
|
||||||
input=InputConfig(sections=_CHAT_SECTIONS),
|
input=InputConfig(sections=_CHAT_SECTIONS),
|
||||||
mask={"system": "mask", "user": "mask", "assistant": "train"},
|
mask={"system": "mask", "user": "mask", "assistant": "train"},
|
||||||
mask_default="mask",
|
mask_default="mask",
|
||||||
preprocessing=ProcessingConfig(max_seq_len=2048),
|
preprocessing=ProcessingConfig(max_seq_len=2048),
|
||||||
)
|
)
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {
|
item = {
|
||||||
"messages": [
|
"messages": [
|
||||||
{"role": "user", "content": "What is 2+2?"},
|
{"role": "user", "content": "What is 2+2?"},
|
||||||
@@ -255,12 +238,11 @@ def test_sectioned_chat(chat_tokenizer):
|
|||||||
assert 0 in result["loss_mask"]
|
assert 0 in result["loss_mask"]
|
||||||
|
|
||||||
|
|
||||||
def test_sectioned_instruction(test_tokenizer):
|
def test_sectioned_instruction(test_tokenizer, builder):
|
||||||
config = PipelineConfig(
|
config = PipelineConfig(
|
||||||
input=InputConfig(sections=_INSTRUCTION_SECTIONS),
|
input=InputConfig(sections=_INSTRUCTION_SECTIONS),
|
||||||
preprocessing=ProcessingConfig(max_seq_len=2048, min_chars=0),
|
preprocessing=ProcessingConfig(max_seq_len=2048, min_chars=0),
|
||||||
)
|
)
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {"prompt": "Q: Why?", "response": "A: Because."}
|
item = {"prompt": "Q: Why?", "response": "A: Because."}
|
||||||
result = builder.build(item, config, test_tokenizer)
|
result = builder.build(item, config, test_tokenizer)
|
||||||
assert result is not None
|
assert result is not None
|
||||||
@@ -269,24 +251,22 @@ def test_sectioned_instruction(test_tokenizer):
|
|||||||
assert mask[-1] == 1
|
assert mask[-1] == 1
|
||||||
|
|
||||||
|
|
||||||
def test_sectioned_text(test_tokenizer):
|
def test_sectioned_text(test_tokenizer, builder):
|
||||||
config = PipelineConfig(
|
config = PipelineConfig(
|
||||||
input=InputConfig(sections=_TEXT_SECTIONS),
|
input=InputConfig(sections=_TEXT_SECTIONS),
|
||||||
preprocessing=ProcessingConfig(max_seq_len=2048, min_chars=1),
|
preprocessing=ProcessingConfig(max_seq_len=2048, min_chars=1),
|
||||||
)
|
)
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {"text": "Hello world, this is a test."}
|
item = {"text": "Hello world, this is a test."}
|
||||||
result = builder.build(item, config, test_tokenizer)
|
result = builder.build(item, config, test_tokenizer)
|
||||||
assert result is not None
|
assert result is not None
|
||||||
assert "loss_mask" not in result
|
assert "loss_mask" not in result
|
||||||
|
|
||||||
|
|
||||||
def test_sectioned_text_too_short(test_tokenizer):
|
def test_sectioned_text_too_short(test_tokenizer, builder):
|
||||||
config = PipelineConfig(
|
config = PipelineConfig(
|
||||||
input=InputConfig(sections=_TEXT_SECTIONS),
|
input=InputConfig(sections=_TEXT_SECTIONS),
|
||||||
preprocessing=ProcessingConfig(max_seq_len=2048, min_chars=100),
|
preprocessing=ProcessingConfig(max_seq_len=2048, min_chars=100),
|
||||||
)
|
)
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
assert builder.build({"text": "short"}, config, test_tokenizer) is None
|
assert builder.build({"text": "short"}, config, test_tokenizer) is None
|
||||||
|
|
||||||
|
|
||||||
@@ -296,13 +276,12 @@ def test_factory_registered():
|
|||||||
|
|
||||||
|
|
||||||
def test_factory_create():
|
def test_factory_create():
|
||||||
builder = MaskBuilderFactory.create("sectioned")
|
builder_obj = MaskBuilderFactory.create("sectioned")
|
||||||
assert isinstance(builder, SectionedMaskBuilder)
|
assert isinstance(builder_obj, SectionedMaskBuilder)
|
||||||
|
|
||||||
|
|
||||||
def test_dpo_chat_basic(chat_tokenizer):
|
def test_dpo_chat_basic(chat_tokenizer, builder):
|
||||||
config = make_dpo_chat_config()
|
config = make_dpo_chat_config()
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {
|
item = {
|
||||||
"chosen": [
|
"chosen": [
|
||||||
{"role": "user", "content": "What is 2+2?"},
|
{"role": "user", "content": "What is 2+2?"},
|
||||||
@@ -319,16 +298,14 @@ def test_dpo_chat_basic(chat_tokenizer):
|
|||||||
assert "rejected" in result
|
assert "rejected" in result
|
||||||
assert "chosen_mask" in result
|
assert "chosen_mask" in result
|
||||||
assert "rejected_mask" in result
|
assert "rejected_mask" in result
|
||||||
assert "domain" in result
|
|
||||||
assert len(result["chosen"]) == len(result["chosen_mask"])
|
assert len(result["chosen"]) == len(result["chosen_mask"])
|
||||||
assert len(result["rejected"]) == len(result["rejected_mask"])
|
assert len(result["rejected"]) == len(result["rejected_mask"])
|
||||||
assert sum(result["chosen_mask"]) > 0
|
assert sum(result["chosen_mask"]) > 0
|
||||||
assert sum(result["rejected_mask"]) > 0
|
assert sum(result["rejected_mask"]) > 0
|
||||||
|
|
||||||
|
|
||||||
def test_dpo_chosen_only_trained(chat_tokenizer):
|
def test_dpo_chosen_only_trained(chat_tokenizer, builder):
|
||||||
config = make_dpo_chat_config()
|
config = make_dpo_chat_config()
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {
|
item = {
|
||||||
"chosen": [
|
"chosen": [
|
||||||
{"role": "user", "content": "Hi"},
|
{"role": "user", "content": "Hi"},
|
||||||
@@ -346,15 +323,13 @@ def test_dpo_chosen_only_trained(chat_tokenizer):
|
|||||||
assert 1 in result["rejected_mask"]
|
assert 1 in result["rejected_mask"]
|
||||||
|
|
||||||
|
|
||||||
def test_dpo_missing_field_is_none(chat_tokenizer):
|
def test_dpo_missing_field_is_none(chat_tokenizer, builder):
|
||||||
config = make_dpo_chat_config()
|
config = make_dpo_chat_config()
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
assert builder.build({"chosen": [], "rejected": []}, config, chat_tokenizer) is None
|
assert builder.build({"chosen": [], "rejected": []}, config, chat_tokenizer) is None
|
||||||
|
|
||||||
|
|
||||||
def test_grpo_basic(chat_tokenizer):
|
def test_grpo_basic(chat_tokenizer, builder):
|
||||||
config = make_grpo_config()
|
config = make_grpo_config()
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {
|
item = {
|
||||||
"prompt": [{"role": "user", "content": "What is 2+2?"}],
|
"prompt": [{"role": "user", "content": "What is 2+2?"}],
|
||||||
"responses": ["4", "The answer is four", "Four", "2+2=4"],
|
"responses": ["4", "The answer is four", "Four", "2+2=4"],
|
||||||
@@ -370,9 +345,8 @@ def test_grpo_basic(chat_tokenizer):
|
|||||||
assert result["rewards"] == [1.0, 0.5, 0.8, 0.2]
|
assert result["rewards"] == [1.0, 0.5, 0.8, 0.2]
|
||||||
|
|
||||||
|
|
||||||
def test_grpo_response_tokens_all_trained(chat_tokenizer):
|
def test_grpo_response_tokens_all_trained(chat_tokenizer, builder):
|
||||||
config = make_grpo_config()
|
config = make_grpo_config()
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {
|
item = {
|
||||||
"prompt": [{"role": "user", "content": "Q"}],
|
"prompt": [{"role": "user", "content": "Q"}],
|
||||||
"responses": ["A", "B"],
|
"responses": ["A", "B"],
|
||||||
@@ -384,9 +358,8 @@ def test_grpo_response_tokens_all_trained(chat_tokenizer):
|
|||||||
assert len(masks) == len(result["responses"])
|
assert len(masks) == len(result["responses"])
|
||||||
|
|
||||||
|
|
||||||
def test_grpo_single_reward(chat_tokenizer):
|
def test_grpo_single_reward(chat_tokenizer, builder):
|
||||||
config = make_grpo_config()
|
config = make_grpo_config()
|
||||||
builder = SectionedMaskBuilder()
|
|
||||||
item = {
|
item = {
|
||||||
"prompt": [{"role": "user", "content": "Q"}],
|
"prompt": [{"role": "user", "content": "Q"}],
|
||||||
"responses": ["A"],
|
"responses": ["A"],
|
||||||
|
|||||||
@@ -10,9 +10,7 @@ from astrai.config.preprocess_config import (
|
|||||||
from astrai.preprocessing.pipeline import Pipeline, filter_by_length
|
from astrai.preprocessing.pipeline import Pipeline, filter_by_length
|
||||||
from tests.data.conftest import (
|
from tests.data.conftest import (
|
||||||
_CHAT_SECTIONS,
|
_CHAT_SECTIONS,
|
||||||
_CHAT_TEMPLATE,
|
|
||||||
_INSTRUCTION_SECTIONS,
|
_INSTRUCTION_SECTIONS,
|
||||||
_SPECIAL_TOKENS_CONFIG,
|
|
||||||
_TEXT_SECTIONS,
|
_TEXT_SECTIONS,
|
||||||
make_dpo_chat_config,
|
make_dpo_chat_config,
|
||||||
make_grpo_no_template_config,
|
make_grpo_no_template_config,
|
||||||
@@ -26,19 +24,7 @@ def test_filter_by_length():
|
|||||||
assert filter_by_length("just right", min_len=5, max_len=20)
|
assert filter_by_length("just right", min_len=5, max_len=20)
|
||||||
|
|
||||||
|
|
||||||
def test_full_chat_pipeline(temp_dir, chat_tokenizer):
|
def test_full_chat_pipeline(temp_dir, chat_tokenizer_dir):
|
||||||
tokenizer_dir = os.path.join(temp_dir, "tok")
|
|
||||||
os.makedirs(tokenizer_dir, exist_ok=True)
|
|
||||||
chat_tokenizer._tokenizer.save(os.path.join(tokenizer_dir, "tokenizer.json"))
|
|
||||||
with open(os.path.join(tokenizer_dir, "tokenizer_config.json"), "w") as f:
|
|
||||||
json.dump(
|
|
||||||
{
|
|
||||||
"special_tokens": _SPECIAL_TOKENS_CONFIG,
|
|
||||||
"chat_template": _CHAT_TEMPLATE,
|
|
||||||
},
|
|
||||||
f,
|
|
||||||
)
|
|
||||||
|
|
||||||
jsonl_path = os.path.join(temp_dir, "chat.jsonl")
|
jsonl_path = os.path.join(temp_dir, "chat.jsonl")
|
||||||
with open(jsonl_path, "w", encoding="utf-8") as f:
|
with open(jsonl_path, "w", encoding="utf-8") as f:
|
||||||
f.write(
|
f.write(
|
||||||
@@ -78,7 +64,7 @@ def test_full_chat_pipeline(temp_dir, chat_tokenizer):
|
|||||||
config=config,
|
config=config,
|
||||||
input_paths=[jsonl_path],
|
input_paths=[jsonl_path],
|
||||||
output_dir=out_dir,
|
output_dir=out_dir,
|
||||||
tokenizer_path=tokenizer_dir,
|
tokenizer_path=chat_tokenizer_dir,
|
||||||
).run()
|
).run()
|
||||||
|
|
||||||
meta_path = os.path.join(out_dir, "__default__", "shard_0000", "meta.json")
|
meta_path = os.path.join(out_dir, "__default__", "shard_0000", "meta.json")
|
||||||
@@ -91,21 +77,7 @@ def test_full_chat_pipeline(temp_dir, chat_tokenizer):
|
|||||||
assert meta["loss_mask"]["dtype"] == "int32"
|
assert meta["loss_mask"]["dtype"] == "int32"
|
||||||
|
|
||||||
|
|
||||||
def test_full_text_pipeline(temp_dir, test_tokenizer):
|
def test_full_text_pipeline(temp_dir, tokenizer_dir):
|
||||||
tokenizer_dir = os.path.join(temp_dir, "tok")
|
|
||||||
os.makedirs(tokenizer_dir, exist_ok=True)
|
|
||||||
test_tokenizer._tokenizer.save(os.path.join(tokenizer_dir, "tokenizer.json"))
|
|
||||||
with open(os.path.join(tokenizer_dir, "tokenizer_config.json"), "w") as f:
|
|
||||||
json.dump(
|
|
||||||
{
|
|
||||||
"special_tokens": {
|
|
||||||
"pad_token": "<|_pad_|>",
|
|
||||||
"unk_token": "<|_unk_|>",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
f,
|
|
||||||
)
|
|
||||||
|
|
||||||
jsonl_path = os.path.join(temp_dir, "text.jsonl")
|
jsonl_path = os.path.join(temp_dir, "text.jsonl")
|
||||||
with open(jsonl_path, "w", encoding="utf-8") as f:
|
with open(jsonl_path, "w", encoding="utf-8") as f:
|
||||||
f.write(
|
f.write(
|
||||||
@@ -145,24 +117,9 @@ def test_full_text_pipeline(temp_dir, test_tokenizer):
|
|||||||
meta = json.load(f)
|
meta = json.load(f)
|
||||||
assert "sequence" in meta
|
assert "sequence" in meta
|
||||||
assert "loss_mask" not in meta
|
assert "loss_mask" not in meta
|
||||||
assert meta["sequence"]["dtype"] == "int32"
|
|
||||||
|
|
||||||
|
|
||||||
def test_full_instruction_pipeline(temp_dir, test_tokenizer):
|
def test_full_instruction_pipeline(temp_dir, tokenizer_dir):
|
||||||
tokenizer_dir = os.path.join(temp_dir, "tok")
|
|
||||||
os.makedirs(tokenizer_dir, exist_ok=True)
|
|
||||||
test_tokenizer._tokenizer.save(os.path.join(tokenizer_dir, "tokenizer.json"))
|
|
||||||
with open(os.path.join(tokenizer_dir, "tokenizer_config.json"), "w") as f:
|
|
||||||
json.dump(
|
|
||||||
{
|
|
||||||
"special_tokens": {
|
|
||||||
"pad_token": "<|_pad_|>",
|
|
||||||
"unk_token": "<|_unk_|>",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
f,
|
|
||||||
)
|
|
||||||
|
|
||||||
jsonl_path = os.path.join(temp_dir, "instruct.jsonl")
|
jsonl_path = os.path.join(temp_dir, "instruct.jsonl")
|
||||||
with open(jsonl_path, "w", encoding="utf-8") as f:
|
with open(jsonl_path, "w", encoding="utf-8") as f:
|
||||||
f.write(
|
f.write(
|
||||||
@@ -206,25 +163,9 @@ def test_full_instruction_pipeline(temp_dir, test_tokenizer):
|
|||||||
meta = json.load(f)
|
meta = json.load(f)
|
||||||
assert "sequence" in meta
|
assert "sequence" in meta
|
||||||
assert "loss_mask" in meta
|
assert "loss_mask" in meta
|
||||||
assert meta["sequence"]["dtype"] == "int32"
|
|
||||||
assert meta["loss_mask"]["dtype"] == "int32"
|
|
||||||
|
|
||||||
|
|
||||||
def test_dtype_override(temp_dir, test_tokenizer):
|
def test_dtype_override(temp_dir, tokenizer_dir):
|
||||||
tokenizer_dir = os.path.join(temp_dir, "tok")
|
|
||||||
os.makedirs(tokenizer_dir, exist_ok=True)
|
|
||||||
test_tokenizer._tokenizer.save(os.path.join(tokenizer_dir, "tokenizer.json"))
|
|
||||||
with open(os.path.join(tokenizer_dir, "tokenizer_config.json"), "w") as f:
|
|
||||||
json.dump(
|
|
||||||
{
|
|
||||||
"special_tokens": {
|
|
||||||
"pad_token": "<|_pad_|>",
|
|
||||||
"unk_token": "<|_unk_|>",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
f,
|
|
||||||
)
|
|
||||||
|
|
||||||
jsonl_path = os.path.join(temp_dir, "data.jsonl")
|
jsonl_path = os.path.join(temp_dir, "data.jsonl")
|
||||||
with open(jsonl_path, "w", encoding="utf-8") as f:
|
with open(jsonl_path, "w", encoding="utf-8") as f:
|
||||||
f.write(json.dumps({"prompt": "Q", "response": "A"}) + "\n")
|
f.write(json.dumps({"prompt": "Q", "response": "A"}) + "\n")
|
||||||
@@ -252,19 +193,7 @@ def test_dtype_override(temp_dir, test_tokenizer):
|
|||||||
assert meta["loss_mask"]["dtype"] == "bool"
|
assert meta["loss_mask"]["dtype"] == "bool"
|
||||||
|
|
||||||
|
|
||||||
def test_dpo_pipeline(temp_dir, chat_tokenizer):
|
def test_dpo_pipeline(temp_dir, chat_tokenizer_dir):
|
||||||
tokenizer_dir = os.path.join(temp_dir, "tok")
|
|
||||||
os.makedirs(tokenizer_dir, exist_ok=True)
|
|
||||||
chat_tokenizer._tokenizer.save(os.path.join(tokenizer_dir, "tokenizer.json"))
|
|
||||||
with open(os.path.join(tokenizer_dir, "tokenizer_config.json"), "w") as f:
|
|
||||||
json.dump(
|
|
||||||
{
|
|
||||||
"special_tokens": _SPECIAL_TOKENS_CONFIG,
|
|
||||||
"chat_template": _CHAT_TEMPLATE,
|
|
||||||
},
|
|
||||||
f,
|
|
||||||
)
|
|
||||||
|
|
||||||
jsonl_path = os.path.join(temp_dir, "dpo.jsonl")
|
jsonl_path = os.path.join(temp_dir, "dpo.jsonl")
|
||||||
with open(jsonl_path, "w", encoding="utf-8") as f:
|
with open(jsonl_path, "w", encoding="utf-8") as f:
|
||||||
f.write(
|
f.write(
|
||||||
@@ -288,7 +217,7 @@ def test_dpo_pipeline(temp_dir, chat_tokenizer):
|
|||||||
config=make_dpo_chat_config(),
|
config=make_dpo_chat_config(),
|
||||||
input_paths=[jsonl_path],
|
input_paths=[jsonl_path],
|
||||||
output_dir=out_dir,
|
output_dir=out_dir,
|
||||||
tokenizer_path=tokenizer_dir,
|
tokenizer_path=chat_tokenizer_dir,
|
||||||
).run()
|
).run()
|
||||||
|
|
||||||
meta_path = os.path.join(out_dir, "__default__", "shard_0000", "meta.json")
|
meta_path = os.path.join(out_dir, "__default__", "shard_0000", "meta.json")
|
||||||
@@ -302,21 +231,7 @@ def test_dpo_pipeline(temp_dir, chat_tokenizer):
|
|||||||
assert "sequence" not in meta
|
assert "sequence" not in meta
|
||||||
|
|
||||||
|
|
||||||
def test_grpo_pipeline(temp_dir, test_tokenizer):
|
def test_grpo_pipeline(temp_dir, tokenizer_dir):
|
||||||
tokenizer_dir = os.path.join(temp_dir, "tok")
|
|
||||||
os.makedirs(tokenizer_dir, exist_ok=True)
|
|
||||||
test_tokenizer._tokenizer.save(os.path.join(tokenizer_dir, "tokenizer.json"))
|
|
||||||
with open(os.path.join(tokenizer_dir, "tokenizer_config.json"), "w") as f:
|
|
||||||
json.dump(
|
|
||||||
{
|
|
||||||
"special_tokens": {
|
|
||||||
"pad_token": "<|_pad_|>",
|
|
||||||
"unk_token": "<|_unk_|>",
|
|
||||||
}
|
|
||||||
},
|
|
||||||
f,
|
|
||||||
)
|
|
||||||
|
|
||||||
jsonl_path = os.path.join(temp_dir, "grpo.jsonl")
|
jsonl_path = os.path.join(temp_dir, "grpo.jsonl")
|
||||||
with open(jsonl_path, "w", encoding="utf-8") as f:
|
with open(jsonl_path, "w", encoding="utf-8") as f:
|
||||||
f.write(
|
f.write(
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import torch
|
|||||||
|
|
||||||
from astrai.inference import (
|
from astrai.inference import (
|
||||||
Allocator,
|
Allocator,
|
||||||
KVCache,
|
PageCache,
|
||||||
PagePool,
|
PagePool,
|
||||||
PrefixCache,
|
PrefixCache,
|
||||||
Storage,
|
Storage,
|
||||||
@@ -161,7 +161,7 @@ def test_task_table_pop():
|
|||||||
|
|
||||||
|
|
||||||
def test_kv_cache_task_extend_allocates():
|
def test_kv_cache_task_extend_allocates():
|
||||||
cache = KVCache(
|
cache = PageCache(
|
||||||
n_layers=1,
|
n_layers=1,
|
||||||
n_pages=8,
|
n_pages=8,
|
||||||
page_size=64,
|
page_size=64,
|
||||||
@@ -177,7 +177,7 @@ def test_kv_cache_task_extend_allocates():
|
|||||||
|
|
||||||
|
|
||||||
def test_kv_cache_task_extend_fails_when_pool_full():
|
def test_kv_cache_task_extend_fails_when_pool_full():
|
||||||
cache = KVCache(
|
cache = PageCache(
|
||||||
n_layers=1,
|
n_layers=1,
|
||||||
n_pages=2,
|
n_pages=2,
|
||||||
page_size=64,
|
page_size=64,
|
||||||
|
|||||||
@@ -13,67 +13,28 @@ from astrai.inference.api.tool_parser import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_scan_complete_simple():
|
@pytest.mark.parametrize(
|
||||||
end, complete = _scan_json('{"key": "value"}', 0)
|
"text,expected_complete,check_end_eq_len",
|
||||||
assert complete is True
|
[
|
||||||
assert end == len('{"key": "value"}')
|
('{"key": "value"}', True, True),
|
||||||
|
('{"outer": {"inner": 1}}', True, True),
|
||||||
|
('{"key": "value"', False, False),
|
||||||
def test_scan_complete_nested():
|
('{"outer": {"inner": 1}', False, False),
|
||||||
text = '{"outer": {"inner": 1}}'
|
('{"key": "a{b}c"} extra', True, False),
|
||||||
|
(r'{"key": "a\"b"}', True, False),
|
||||||
|
('{"a": {"b": {"c": {"d": {"e": 5}}}}}', True, True),
|
||||||
|
('{"items": [{"x": 1}, {"x": 2}]}', True, True),
|
||||||
|
('{"fn": "function() { return 1; }"}', True, False),
|
||||||
|
('{"key": "\u5317\u4eac"}', True, False),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_scan_json(text, expected_complete, check_end_eq_len):
|
||||||
end, complete = _scan_json(text, 0)
|
end, complete = _scan_json(text, 0)
|
||||||
assert complete is True
|
assert complete is expected_complete
|
||||||
|
if check_end_eq_len:
|
||||||
assert end == len(text)
|
assert end == len(text)
|
||||||
|
|
||||||
|
|
||||||
def test_scan_incomplete_unclosed():
|
|
||||||
end, complete = _scan_json('{"key": "value"', 0)
|
|
||||||
assert complete is False
|
|
||||||
|
|
||||||
|
|
||||||
def test_scan_incomplete_nested():
|
|
||||||
end, complete = _scan_json('{"outer": {"inner": 1}', 0)
|
|
||||||
assert complete is False
|
|
||||||
|
|
||||||
|
|
||||||
def test_scan_string_braces_ignored():
|
|
||||||
text = '{"key": "a{b}c"} extra'
|
|
||||||
end, complete = _scan_json(text, 0)
|
|
||||||
assert complete is True
|
|
||||||
|
|
||||||
|
|
||||||
def test_scan_escaped_quote_ignored():
|
|
||||||
text = r'{"key": "a\"b"}'
|
|
||||||
end, complete = _scan_json(text, 0)
|
|
||||||
assert complete is True
|
|
||||||
|
|
||||||
|
|
||||||
def test_scan_deeply_nested():
|
|
||||||
text = '{"a": {"b": {"c": {"d": {"e": 5}}}}}'
|
|
||||||
end, complete = _scan_json(text, 0)
|
|
||||||
assert complete is True
|
|
||||||
assert end == len(text)
|
|
||||||
|
|
||||||
|
|
||||||
def test_scan_array_with_braces():
|
|
||||||
text = '{"items": [{"x": 1}, {"x": 2}]}'
|
|
||||||
end, complete = _scan_json(text, 0)
|
|
||||||
assert complete is True
|
|
||||||
assert end == len(text)
|
|
||||||
|
|
||||||
|
|
||||||
def test_scan_code_in_string():
|
|
||||||
text = '{"fn": "function() { return 1; }"}'
|
|
||||||
end, complete = _scan_json(text, 0)
|
|
||||||
assert complete is True
|
|
||||||
|
|
||||||
|
|
||||||
def test_scan_unicode_chars():
|
|
||||||
text = '{"key": "\u5317\u4eac"}'
|
|
||||||
end, complete = _scan_json(text, 0)
|
|
||||||
assert complete is True
|
|
||||||
|
|
||||||
|
|
||||||
def test_find_single_tool_call():
|
def test_find_single_tool_call():
|
||||||
text = '{"name": "get_weather", "arguments": {"city": "Beijing"}}'
|
text = '{"name": "get_weather", "arguments": {"city": "Beijing"}}'
|
||||||
results = _find_tool_calls(text)
|
results = _find_tool_calls(text)
|
||||||
@@ -141,10 +102,7 @@ def test_find_arguments_with_array():
|
|||||||
|
|
||||||
|
|
||||||
def test_find_arguments_with_nested_array_of_objects():
|
def test_find_arguments_with_nested_array_of_objects():
|
||||||
text = (
|
text = '{"name": "batch", "arguments": {"rows": [{"id": 1, "val": "a"}, {"id": 2, "val": "b"}]}}'
|
||||||
'{"name": "batch", '
|
|
||||||
'"arguments": {"rows": [{"id": 1, "val": "a"}, {"id": 2, "val": "b"}]}}'
|
|
||||||
)
|
|
||||||
results = _find_tool_calls(text)
|
results = _find_tool_calls(text)
|
||||||
assert len(results) == 1
|
assert len(results) == 1
|
||||||
assert '"rows"' in results[0]["args"]
|
assert '"rows"' in results[0]["args"]
|
||||||
@@ -206,38 +164,26 @@ def test_find_extracts_correct_arg_start_position():
|
|||||||
assert json_str == text
|
assert json_str == text
|
||||||
|
|
||||||
|
|
||||||
def test_partial_with_name():
|
@pytest.mark.parametrize(
|
||||||
result = _find_partial_tool_call('{"name": "func", "arguments": {"city"')
|
"text,expected_name,expected_complete",
|
||||||
|
[
|
||||||
|
('{"name": "func", "arguments": {"city"', "func", False),
|
||||||
|
('{"name": "func", "arguments": {"city": "BJ"}}', "func", None),
|
||||||
|
("plain text", None, None),
|
||||||
|
('{"nam', None, None),
|
||||||
|
('{"name": "deep", "arguments": {"a": {"b": {"c": ', "deep", None),
|
||||||
|
('{"name": "batch", "arguments": {"items": [1, 2, ', "batch", None),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_find_partial_tool_call(text, expected_name, expected_complete):
|
||||||
|
result = _find_partial_tool_call(text)
|
||||||
|
if expected_name is None:
|
||||||
|
assert result is None
|
||||||
|
else:
|
||||||
assert result is not None
|
assert result is not None
|
||||||
assert result["name"] == "func"
|
assert result["name"] == expected_name
|
||||||
assert result["complete"] is False
|
if expected_complete is not None:
|
||||||
|
assert result["complete"] is expected_complete
|
||||||
|
|
||||||
def test_partial_with_full_args():
|
|
||||||
result = _find_partial_tool_call('{"name": "func", "arguments": {"city": "BJ"}}')
|
|
||||||
assert result is not None
|
|
||||||
assert result["name"] == "func"
|
|
||||||
|
|
||||||
|
|
||||||
def test_partial_no_match():
|
|
||||||
assert _find_partial_tool_call("plain text") is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_partial_no_name_yet():
|
|
||||||
assert _find_partial_tool_call('{"nam') is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_partial_deeply_nested():
|
|
||||||
result = _find_partial_tool_call('{"name": "deep", "arguments": {"a": {"b": {"c": ')
|
|
||||||
assert result is not None
|
|
||||||
assert result["name"] == "deep"
|
|
||||||
assert '"a"' in result["args"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_partial_array_incomplete():
|
|
||||||
result = _find_partial_tool_call('{"name": "batch", "arguments": {"items": [1, 2, ')
|
|
||||||
assert result is not None
|
|
||||||
assert result["name"] == "batch"
|
|
||||||
|
|
||||||
|
|
||||||
def test_feed_plain_text():
|
def test_feed_plain_text():
|
||||||
@@ -269,7 +215,6 @@ def test_feed_tool_call_args_streaming():
|
|||||||
parser = SimpleJsonToolParser()
|
parser = SimpleJsonToolParser()
|
||||||
d1 = parser.feed('{"name": "f", "arguments": {"x":')
|
d1 = parser.feed('{"name": "f", "arguments": {"x":')
|
||||||
d2 = parser.feed('{"name": "f", "arguments": {"x": "1"}}')
|
d2 = parser.feed('{"name": "f", "arguments": {"x": "1"}}')
|
||||||
|
|
||||||
args_deltas = [
|
args_deltas = [
|
||||||
d
|
d
|
||||||
for batch in (d1, d2)
|
for batch in (d1, d2)
|
||||||
@@ -332,17 +277,6 @@ def test_feed_content_after_tool_call_is_not_emitted():
|
|||||||
assert parser.has_tool_calls
|
assert parser.has_tool_calls
|
||||||
|
|
||||||
|
|
||||||
def _collect_args_deltas(parser):
|
|
||||||
args_parts = []
|
|
||||||
for d in parser.feed(parser._text_buffer):
|
|
||||||
if "tool_calls" in d:
|
|
||||||
for tc in d["tool_calls"]:
|
|
||||||
fn = tc.get("function", {})
|
|
||||||
if "arguments" in fn and fn["arguments"]:
|
|
||||||
args_parts.append(fn["arguments"])
|
|
||||||
return args_parts
|
|
||||||
|
|
||||||
|
|
||||||
def _simulate_streaming(parser, text):
|
def _simulate_streaming(parser, text):
|
||||||
all_delta_names = []
|
all_delta_names = []
|
||||||
all_args_chunks = []
|
all_args_chunks = []
|
||||||
@@ -447,7 +381,6 @@ def test_streaming_args_diff_only_emits_new_bytes():
|
|||||||
parser = SimpleJsonToolParser()
|
parser = SimpleJsonToolParser()
|
||||||
step1 = parser.feed('{"name": "f", "arguments": {"city": "Bei')
|
step1 = parser.feed('{"name": "f", "arguments": {"city": "Bei')
|
||||||
step2 = parser.feed('{"name": "f", "arguments": {"city": "Beijing"}}')
|
step2 = parser.feed('{"name": "f", "arguments": {"city": "Beijing"}}')
|
||||||
|
|
||||||
all_args = []
|
all_args = []
|
||||||
for step in (step1, step2):
|
for step in (step1, step2):
|
||||||
for d in step:
|
for d in step:
|
||||||
@@ -500,31 +433,21 @@ def test_parse_complete_with_content():
|
|||||||
|
|
||||||
def test_parse_complete_multiple_tool_calls():
|
def test_parse_complete_multiple_tool_calls():
|
||||||
parser = SimpleJsonToolParser()
|
parser = SimpleJsonToolParser()
|
||||||
body = (
|
body = '{"name": "get_weather", "arguments": {"city": "Beijing"}}{"name": "get_time", "arguments": {"tz": "Asia/Shanghai"}}'
|
||||||
'{"name": "get_weather", "arguments": {"city": "Beijing"}}'
|
|
||||||
'{"name": "get_time", "arguments": {"tz": "Asia/Shanghai"}}'
|
|
||||||
)
|
|
||||||
result = parser.parse_complete(body)
|
result = parser.parse_complete(body)
|
||||||
assert result is not None
|
assert result is not None
|
||||||
assert len(result["tool_calls"]) == 2
|
assert len(result["tool_calls"]) == 2
|
||||||
assert result["tool_calls"][0]["function"]["name"] == "get_weather"
|
assert result["tool_calls"][0]["function"]["name"] == "get_weather"
|
||||||
assert result["tool_calls"][1]["function"]["name"] == "get_time"
|
assert result["tool_calls"][1]["function"]["name"] == "get_time"
|
||||||
assert "Beijing" in result["tool_calls"][0]["function"]["arguments"]
|
|
||||||
assert "Asia/Shanghai" in result["tool_calls"][1]["function"]["arguments"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_complete_complex_real_world():
|
def test_parse_complete_complex_real_world():
|
||||||
parser = SimpleJsonToolParser()
|
parser = SimpleJsonToolParser()
|
||||||
body = (
|
body = (
|
||||||
'{"name": "send_email", '
|
'{"name": "send_email", "arguments": {'
|
||||||
'"arguments": {'
|
'"to": ["a@b.com", "c@d.com"], "cc": null, '
|
||||||
'"to": ["a@b.com", "c@d.com"], '
|
'"subject": "Hello World", "body": "This is a test email.", '
|
||||||
'"cc": null, '
|
'"priority": 1, "attachments": false}}'
|
||||||
'"subject": "Hello World", '
|
|
||||||
'"body": "This is a test email.", '
|
|
||||||
'"priority": 1, '
|
|
||||||
'"attachments": false'
|
|
||||||
"}}"
|
|
||||||
)
|
)
|
||||||
result = parser.parse_complete(body)
|
result = parser.parse_complete(body)
|
||||||
assert result is not None
|
assert result is not None
|
||||||
@@ -539,11 +462,7 @@ def test_parse_complete_complex_real_world():
|
|||||||
|
|
||||||
def test_parse_complete_content_with_multiple_tool_calls():
|
def test_parse_complete_content_with_multiple_tool_calls():
|
||||||
parser = SimpleJsonToolParser()
|
parser = SimpleJsonToolParser()
|
||||||
body = (
|
body = 'I will do two things. {"name": "f1", "arguments": {"a": 1}}{"name": "f2", "arguments": {"b": 2}}'
|
||||||
"I will do two things. "
|
|
||||||
'{"name": "f1", "arguments": {"a": 1}}'
|
|
||||||
'{"name": "f2", "arguments": {"b": 2}}'
|
|
||||||
)
|
|
||||||
result = parser.parse_complete(body)
|
result = parser.parse_complete(body)
|
||||||
assert result is not None
|
assert result is not None
|
||||||
assert result["content"] == "I will do two things."
|
assert result["content"] == "I will do two things."
|
||||||
@@ -588,30 +507,29 @@ def test_feed_then_parse_complete_same_instance():
|
|||||||
assert parser.has_tool_calls
|
assert parser.has_tool_calls
|
||||||
|
|
||||||
|
|
||||||
def test_pattern_matches_basic():
|
@pytest.mark.parametrize(
|
||||||
assert _TOOL_CALL_HEAD_RE.search('{"name": "f"}')
|
"text,matches",
|
||||||
|
[
|
||||||
|
('{"name": "f"}', True),
|
||||||
def test_pattern_matches_with_whitespace():
|
('{ "name" : "f"}', True),
|
||||||
assert _TOOL_CALL_HEAD_RE.search('{ "name" : "f"}')
|
('{"other": 1}', False),
|
||||||
|
('prefix {"name": "f", "args": {}}', True),
|
||||||
|
('{"name": "f"}', True), # match at start
|
||||||
def test_pattern_no_match_without_name():
|
(' {"name": "f"}', True),
|
||||||
assert _TOOL_CALL_HEAD_RE.search('{"other": 1}') is None
|
],
|
||||||
|
)
|
||||||
|
def test_pattern_regex(text, matches):
|
||||||
def test_pattern_match_mid_text():
|
result = _TOOL_CALL_HEAD_RE.search(text)
|
||||||
assert _TOOL_CALL_HEAD_RE.search('prefix {"name": "f", "args": {}}') is not None
|
if matches:
|
||||||
|
assert result is not None
|
||||||
|
else:
|
||||||
|
assert result is None
|
||||||
|
|
||||||
|
|
||||||
def test_pattern_name_at_start():
|
def test_pattern_name_at_start():
|
||||||
assert _TOOL_CALL_HEAD_RE.match('{"name": "f"}')
|
assert _TOOL_CALL_HEAD_RE.match('{"name": "f"}')
|
||||||
|
|
||||||
|
|
||||||
def test_pattern_leading_whitespace():
|
|
||||||
assert _TOOL_CALL_HEAD_RE.search(' {"name": "f"}') is not None
|
|
||||||
|
|
||||||
|
|
||||||
def test_factory_register_and_create():
|
def test_factory_register_and_create():
|
||||||
parser = ToolParserFactory.create("simple_json")
|
parser = ToolParserFactory.create("simple_json")
|
||||||
assert isinstance(parser, BaseToolParser)
|
assert isinstance(parser, BaseToolParser)
|
||||||
@@ -661,7 +579,6 @@ def test_feed_token_ids_do_not_affect_parsing():
|
|||||||
text, current_token_ids=[1, 2, 3], delta_token_ids=[3]
|
text, current_token_ids=[1, 2, 3], delta_token_ids=[3]
|
||||||
)
|
)
|
||||||
assert len(result_no) == len(result_with)
|
assert len(result_no) == len(result_with)
|
||||||
assert len(result_no) > 0
|
|
||||||
assert (
|
assert (
|
||||||
result_no[0]["tool_calls"][0]["function"]["name"]
|
result_no[0]["tool_calls"][0]["function"]["name"]
|
||||||
== result_with[0]["tool_calls"][0]["function"]["name"]
|
== result_with[0]["tool_calls"][0]["function"]["name"]
|
||||||
|
|||||||
@@ -1,6 +1,13 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
import safetensors.torch as st
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
from astrai.config.model_config import EncoderConfig
|
from astrai.config.model_config import EncoderConfig
|
||||||
|
from astrai.model.automodel import AutoModel
|
||||||
from astrai.model.encoder import EmbeddingEncoder
|
from astrai.model.encoder import EmbeddingEncoder
|
||||||
|
|
||||||
TINY_CONFIG = dict(
|
TINY_CONFIG = dict(
|
||||||
@@ -14,92 +21,56 @@ TINY_CONFIG = dict(
|
|||||||
norm_eps=1e-5,
|
norm_eps=1e-5,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
_device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||||
|
|
||||||
def test_encoder_forward_mean():
|
|
||||||
config = EncoderConfig(**TINY_CONFIG)
|
def _make_model(**kwargs):
|
||||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
config = EncoderConfig(**{**TINY_CONFIG, **kwargs})
|
||||||
model = EmbeddingEncoder(config).to(device=device)
|
return EmbeddingEncoder(config).to(device=_device)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("pooling_type", ["mean", "cls", "last"])
|
||||||
|
def test_encoder_forward_pooling(pooling_type):
|
||||||
|
model = _make_model(pooling_type=pooling_type)
|
||||||
model.eval()
|
model.eval()
|
||||||
|
|
||||||
batch_size, seq_len = 2, 8
|
batch_size, seq_len = 2, 8
|
||||||
input_ids = torch.randint(
|
input_ids = torch.randint(
|
||||||
0, config.vocab_size, (batch_size, seq_len), device=device
|
0, TINY_CONFIG["vocab_size"], (batch_size, seq_len), device=_device
|
||||||
)
|
)
|
||||||
|
|
||||||
with torch.no_grad():
|
with torch.no_grad():
|
||||||
output = model(input_ids)
|
output = model(input_ids)
|
||||||
|
|
||||||
assert output.shape == (batch_size, config.dim)
|
assert output.shape == (batch_size, TINY_CONFIG["dim"])
|
||||||
assert not torch.isnan(output).any()
|
|
||||||
|
|
||||||
|
|
||||||
def test_encoder_forward_cls():
|
|
||||||
config = EncoderConfig(**{**TINY_CONFIG, "pooling_type": "cls"})
|
|
||||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
||||||
model = EmbeddingEncoder(config).to(device=device)
|
|
||||||
model.eval()
|
|
||||||
|
|
||||||
batch_size, seq_len = 2, 8
|
|
||||||
input_ids = torch.randint(
|
|
||||||
0, config.vocab_size, (batch_size, seq_len), device=device
|
|
||||||
)
|
|
||||||
|
|
||||||
with torch.no_grad():
|
|
||||||
output = model(input_ids)
|
|
||||||
|
|
||||||
assert output.shape == (batch_size, config.dim)
|
|
||||||
assert not torch.isnan(output).any()
|
|
||||||
|
|
||||||
|
|
||||||
def test_encoder_forward_last():
|
|
||||||
config = EncoderConfig(**{**TINY_CONFIG, "pooling_type": "last"})
|
|
||||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
||||||
model = EmbeddingEncoder(config).to(device=device)
|
|
||||||
model.eval()
|
|
||||||
|
|
||||||
batch_size, seq_len = 2, 8
|
|
||||||
input_ids = torch.randint(
|
|
||||||
0, config.vocab_size, (batch_size, seq_len), device=device
|
|
||||||
)
|
|
||||||
|
|
||||||
with torch.no_grad():
|
|
||||||
output = model(input_ids)
|
|
||||||
|
|
||||||
assert output.shape == (batch_size, config.dim)
|
|
||||||
assert not torch.isnan(output).any()
|
assert not torch.isnan(output).any()
|
||||||
|
|
||||||
|
|
||||||
def test_encoder_forward_with_padding():
|
def test_encoder_forward_with_padding():
|
||||||
config = EncoderConfig(**TINY_CONFIG)
|
model = _make_model()
|
||||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
||||||
model = EmbeddingEncoder(config).to(device=device)
|
|
||||||
model.eval()
|
model.eval()
|
||||||
|
|
||||||
batch_size, seq_len = 2, 8
|
batch_size, seq_len = 2, 8
|
||||||
input_ids = torch.randint(
|
input_ids = torch.randint(
|
||||||
0, config.vocab_size, (batch_size, seq_len), device=device
|
0, TINY_CONFIG["vocab_size"], (batch_size, seq_len), device=_device
|
||||||
)
|
)
|
||||||
input_mask = torch.ones(batch_size, seq_len, dtype=torch.bool, device=device)
|
input_mask = torch.ones(batch_size, seq_len, dtype=torch.bool, device=_device)
|
||||||
input_mask[:, 4:] = False
|
input_mask[:, 4:] = False
|
||||||
|
|
||||||
with torch.no_grad():
|
with torch.no_grad():
|
||||||
output = model(input_ids, input_mask=input_mask)
|
output = model(input_ids, input_mask=input_mask)
|
||||||
|
|
||||||
assert output.shape == (batch_size, config.dim)
|
assert output.shape == (batch_size, TINY_CONFIG["dim"])
|
||||||
assert not torch.isnan(output).any()
|
assert not torch.isnan(output).any()
|
||||||
|
|
||||||
|
|
||||||
def test_encoder_normalize():
|
def test_encoder_normalize():
|
||||||
config = EncoderConfig(
|
model = _make_model(pooling_type="mean", normalize_embeddings=True)
|
||||||
**{**TINY_CONFIG, "pooling_type": "mean", "normalize_embeddings": True}
|
|
||||||
)
|
|
||||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
||||||
model = EmbeddingEncoder(config).to(device=device)
|
|
||||||
model.eval()
|
model.eval()
|
||||||
|
|
||||||
batch_size, seq_len = 2, 8
|
batch_size, seq_len = 2, 8
|
||||||
input_ids = torch.randint(
|
input_ids = torch.randint(
|
||||||
0, config.vocab_size, (batch_size, seq_len), device=device
|
0, TINY_CONFIG["vocab_size"], (batch_size, seq_len), device=_device
|
||||||
)
|
)
|
||||||
|
|
||||||
with torch.no_grad():
|
with torch.no_grad():
|
||||||
@@ -110,24 +81,19 @@ def test_encoder_normalize():
|
|||||||
|
|
||||||
|
|
||||||
def test_encoder_register():
|
def test_encoder_register():
|
||||||
from astrai.model.automodel import AutoModel
|
|
||||||
|
|
||||||
assert AutoModel.is_registered("embedding")
|
assert AutoModel.is_registered("embedding")
|
||||||
cls = AutoModel.get_component_class("embedding")
|
cls = AutoModel.get_component_class("embedding")
|
||||||
assert cls is EmbeddingEncoder
|
assert cls is EmbeddingEncoder
|
||||||
|
|
||||||
|
|
||||||
def test_encoder_from_transformer_checkpoint():
|
def test_encoder_from_transformer_checkpoint():
|
||||||
config = EncoderConfig(**TINY_CONFIG)
|
model = _make_model()
|
||||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
||||||
model = EmbeddingEncoder(config).to(device=device)
|
|
||||||
|
|
||||||
state_dict = model.state_dict()
|
state_dict = model.state_dict()
|
||||||
state_dict["lm_head.weight"] = torch.randn(
|
state_dict["lm_head.weight"] = torch.randn(
|
||||||
config.vocab_size, config.dim, device=device
|
TINY_CONFIG["vocab_size"], TINY_CONFIG["dim"], device=_device
|
||||||
)
|
)
|
||||||
|
|
||||||
new_model = EmbeddingEncoder(config).to(device=device)
|
new_model = _make_model()
|
||||||
new_model.load_state_dict(state_dict, strict=True)
|
new_model.load_state_dict(state_dict, strict=True)
|
||||||
|
|
||||||
for key in model.state_dict():
|
for key in model.state_dict():
|
||||||
@@ -135,12 +101,6 @@ def test_encoder_from_transformer_checkpoint():
|
|||||||
|
|
||||||
|
|
||||||
def test_encoder_save_load():
|
def test_encoder_save_load():
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import tempfile
|
|
||||||
|
|
||||||
import safetensors.torch as st
|
|
||||||
|
|
||||||
test_dir = tempfile.mkdtemp(prefix="encoder_test_")
|
test_dir = tempfile.mkdtemp(prefix="encoder_test_")
|
||||||
config_path = os.path.join(test_dir, "config.json")
|
config_path = os.path.join(test_dir, "config.json")
|
||||||
weights_path = os.path.join(test_dir, "model.safetensors")
|
weights_path = os.path.join(test_dir, "model.safetensors")
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ def create_train_config(
|
|||||||
batch_per_device: Batch size per device (default: 2)
|
batch_per_device: Batch size per device (default: 2)
|
||||||
grad_accum_steps: Gradient accumulation steps (default: 1)
|
grad_accum_steps: Gradient accumulation steps (default: 1)
|
||||||
max_grad_norm: Maximum gradient norm for clipping (default: 1.0)
|
max_grad_norm: Maximum gradient norm for clipping (default: 1.0)
|
||||||
ckpt_interval: Checkpoint save interval in iterations (default: 5)
|
ckpt_interval: Checkpoint save interval in optimizer steps (default: 5)
|
||||||
random_seed: Random seed for reproducibility (default: 42)
|
random_seed: Random seed for reproducibility (default: 42)
|
||||||
**kwargs: Additional arguments passed to TrainConfig
|
**kwargs: Additional arguments passed to TrainConfig
|
||||||
|
|
||||||
|
|||||||
@@ -44,14 +44,14 @@ def test_early_stopping_simulation(base_test_env, early_stopping_dataset):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
# Resume from latest checkpoint
|
# Resume from latest checkpoint
|
||||||
load_dir = os.path.join(base_test_env["test_dir"], "epoch_0_iter_2")
|
load_dir = os.path.join(base_test_env["test_dir"], "epoch_0_step_1")
|
||||||
trainer = Trainer(train_config)
|
trainer = Trainer(train_config)
|
||||||
trainer.train(resume_dir=load_dir)
|
trainer.train(resume_dir=load_dir)
|
||||||
|
|
||||||
# Verify checkpoint was saved at expected iteration
|
# Verify checkpoint was saved at expected step
|
||||||
load_dir = os.path.join(base_test_env["test_dir"], "epoch_1_iter_10")
|
load_dir = os.path.join(base_test_env["test_dir"], "epoch_1_step_5")
|
||||||
import json
|
import json
|
||||||
|
|
||||||
with open(os.path.join(load_dir, "meta.json")) as f:
|
with open(os.path.join(load_dir, "meta.json")) as f:
|
||||||
meta = json.load(f)
|
meta = json.load(f)
|
||||||
assert meta["iteration"] == 10
|
assert meta["consumed_samples"] == 20
|
||||||
|
|||||||
Reference in New Issue
Block a user