File size: 4,995 Bytes
4196369
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
## BABILong(QA1 / 32k)数据处理与训练数据流说明

本文档描述当前仓库里 **BABILong QA1(32k.json)** 在训练脚本中的实际处理方式:从原始 JSON,到 tokenizer、padding、labels、DataLoader,再到喂给 `QwenTitansForBABILong` 的整条数据流。

代码入口:

- `examples/train_qwen_titans_babilong.py`

---

## 数据源与样本格式

默认数据路径(可改):

- `TrainingConfig.data_path = /data/yty/BABILong/babilong-train-5k-samples/data/qa1/32k.json`

文件内容为一个 JSON 列表,每条样本大体包含:

- `input`:长上下文(故事/事实)
- `question`:问题
- `target`:答案(短文本)

训练脚本会把它拼成 prompt:

```
{input}

Question: {question}
Answer:
```

并把答案拼接为(答案前加空格):

```
 {target}
```

---

## 关键目标:固定长度样本(FSDP/DDP 必须)

当前实现 **强制每条样本输出固定长度 `config.max_length`(默认 32768)**,原因:

- 模型前向会按 `chunk_size` 把序列分 chunk 循环处理
- 在 FSDP/DDP 下,如果不同 rank 的序列长度不同 → chunk 数不同 → collectives 顺序不一致 → NCCL watchdog 超时

因此数据侧必须固定长度,保证每步每个 rank 的 chunk 次数一致。

相关参数:

- `TrainingConfig.max_length`:固定输出长度(默认 32768)
- `TrainingConfig.answer_reserve_tokens`:给答案预留 token 数(默认 64)

---

## Dataset:`BABILongDataset.__getitem__` 的处理流程

位置:`examples/train_qwen_titans_babilong.py`

### Step 1:tokenize prompt(截断)

- 对 prompt 进行 tokenize
- 最大长度限制为 `max_length - answer_reserve_tokens`
- `add_special_tokens=True`(让 tokenizer 自己加 BOS/EOS 等需要的特殊 token)

### Step 2:tokenize answer(不加特殊 token)

- 对 `" {target}"` tokenize
- `add_special_tokens=False`

### Step 3:拼接并截断到 `max_length`

- 先算 prompt token 数 `len(prompt_ids)`
- answer 只保留剩余可用空间:`available = max_length - len(prompt_ids)`
- `input_ids = concat(prompt_ids, answer_ids[:available])`

### Step 4:构造 `labels`(只监督答案)

- `labels` 初始全为 `-100`
- 只有答案 token 的位置才写入对应 token id
- 这样 loss 只在答案 token 上计算(prompt 与 padding 不参与 loss)

### Step 5:padding 到固定长度 + attention_mask

如果拼接后长度 `< max_length`:

- `input_ids` 右侧 pad 到 `max_length`(pad_id = tokenizer.pad_token_id)
- `labels` pad 的部分保持 `-100`
- `attention_mask`:
  - 真 token 为 1
  - padding 为 0

> 备注:脚本在 `main()` 里如果发现 `tokenizer.pad_token is None`,会设置 `pad_token = eos_token`,确保有 pad_id。

---

## DataLoader 与分布式采样

### DataLoader

- `batch_size = 1`(32k 序列 + chunk streaming,一般只能 1)
- `collate_fn` 只做 stack(Dataset 已固定长度,不做动态 padding)
- `num_workers = 0`(避免多进程复制大张量带来的额外开销/不稳定)

### 训练/验证切分

- `random_split(full_dataset, [train_size, eval_size], generator=manual_seed(config.seed))`
- 默认 `train_ratio=0.9`

### 分布式(torchrun)

当使用 `torchrun` 启动时:

- 训练集:`DistributedSampler(..., shuffle=True, seed=config.seed)`
- 验证集:`DistributedSampler(..., shuffle=False)`
- 每个 epoch 会调用 `train_sampler.set_epoch(epoch)`,保证各 rank shuffle 一致

---

## 喂给模型的数据张量形状

由于固定长度:

- `input_ids`: `[B, max_length]`(默认 `[1, 32768]`)
- `attention_mask`: `[B, max_length]`
- `labels`: `[B, max_length]`

模型内部再按 `chunk_size`(默认 4096)切成 8 个 chunk 进行 streaming。

---

## 训练与日志(跟数据流相关的行为)

- **梯度累积**:`gradient_accumulation_steps=8`
  - 每 8 个 micro-batch 才做一次 optimizer step
- **每 80 个 batch 输出一次**:
  - `--log_every_batches 80`(默认 80)
  - 会自动换算成 `logging_steps = ceil(log_every_batches / gradient_accumulation_steps)`
  - 并在 rank0 额外 `logger.info(...)` 打一行到终端,方便 `tee` 保存

---

## 运行方式(推荐)

### 8 卡 + FSDP

```bash
CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
torchrun --standalone --nproc_per_node=8 \
  examples/train_qwen_titans_babilong.py --fsdp --log_every_batches 80
```

### 快速小跑(2 卡调试)

```bash
CUDA_VISIBLE_DEVICES=0,1 \
torchrun --standalone --nproc_per_node=2 \
  examples/train_qwen_titans_babilong.py --fsdp --max_samples 8 --num_epochs 1 --eval_steps 1000000
```

---

## 训练产物(输出)

默认输出目录:

- `TrainingConfig.output_dir = ./outputs/qwen_titans_babilong`

默认只保存一个 final checkpoint(覆盖写入):

- `final_memory_checkpoint.pt`

内容包括:

- `memory_state_dict`:只包含 `long_term_memory` / `memory_gate` 的参数(体积更小)
- `global_step`