File size: 4,739 Bytes
f0d6538
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
179
180
181
182
# Getting Started with Abbie

This guide covers integrating Abbie into existing PyTorch distributed training scripts.

## Quick Setup

Initialize the distributed environment and Device Mesh Manager (DMM):

```python
import os
import torch
import torch.distributed as dist
from abbie.device_mesh_manager import DMM

# Standard PyTorch distributed setup
rank = int(os.environ["RANK"])
local_rank = int(os.environ["LOCAL_RANK"])
world_size = int(os.environ["WORLD_SIZE"])

torch.cuda.set_device(local_rank)
dist.init_process_group(backend="nccl", init_method="env://")

# Initialize Abbie's device mesh
DMM.initialize(pp_size=2, ep_size=1, sp_size=1)
```

- `pp_size`: Pipeline parallelism degree (layers split across ranks)
- `ep_size`: Expert parallelism degree (for MoE models)
- `sp_size`: Sequence parallelism degree (sequence split within DP)

## Loading a Model

```python
from abbie.models import load_pretrained_hf_model

model = load_pretrained_hf_model(
    pretrained_path="path/to/hf_model",
    max_batch_size=micro_batch_size * num_chunks,
    max_seq_len=4096,
)
```

Supported models: Qwen2, Qwen3, Qwen3-MoE, Qwen2.5-VL, Qwen3-VL, Qwen3-VL-MoE.

Additional options exist for selective recomputation (`recompute_attn`, `recompute_mlp`), activation offloading, and token dispatch methods.

## Creating an Optimizer

```python
from abbie.gargantua.causal_lm import make_model_optimizer

optimizer = make_model_optimizer(
    model=model,
    num_training_steps=10000,
    num_warmup_steps=500,
    lr=1e-5,
    betas=(0.9, 0.999),
    weight_decay=0.01,
    lr_schedule="cosine",
)
```

For VL models, `visual_lr` allows a separate learning rate for the vision encoder. The optimizer automatically handles parameter grouping for LLM, experts, and visual components.

## Training Loop

Key difference from standard PyTorch: `model.step()` performs both forward and backward passes together. This enables Abbie's overlapped scheduling.

```python
for batch in dataloader:
    input_ids = batch["input_ids"].cuda()
    attention_mask = batch["attention_mask"].cuda()
    position_ids = batch["position_ids"].cuda()
    labels = batch["labels"].cuda()

    optimizer.zero_grad()

    outputs = model.step(
        num_chunks=num_chunks,
        input_ids=input_ids,
        attention_mask=attention_mask,
        position_ids=position_ids,
        labels=labels,
        return_outputs=True,
    )

    optimizer.step()

    if outputs.loss is not None:
        loss = outputs.loss.sum().item()
        print(f"Loss: {loss:.4f}")
```

`num_chunks` is the number of microbatches in one training step. The input tensors should contain `micro_batch_size * num_chunks` samples concatenated together.

## Checkpointing

### Saving

```python
# Save model in HuggingFace format
model.save_pretrained("path/to/checkpoint/hf_model")

# Save optimizer state (sharded per rank)
torch.save(
    optimizer.state_dict(),
    f"path/to/checkpoint/optimizer/{DMM.global_rank}-of-{DMM.world_size}.pt"
)
```

### Resuming

```python
# Load optimizer state
optimizer.load_state_dict(
    torch.load(f"path/to/checkpoint/optimizer/{DMM.global_rank}-of-{DMM.world_size}.pt")
)

# Restore model weights from optimizer's FP32 master weights
for _, base_optimizer in optimizer.optimizers.items():
    base_optimizer.reload_original_from_fp32_param()
```

## Complete Example

```python
import os
import torch
import torch.distributed as dist
from abbie.device_mesh_manager import DMM
from abbie.models import load_pretrained_hf_model
from abbie.gargantua.causal_lm import make_model_optimizer

# Setup
rank = int(os.environ["RANK"])
local_rank = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)
dist.init_process_group(backend="nccl", init_method="env://")
DMM.initialize(pp_size=2, ep_size=1, sp_size=1)

# Model and optimizer
model = load_pretrained_hf_model(
    pretrained_path="Qwen/Qwen2-7B",
    max_batch_size=8,
    max_seq_len=4096,
)

optimizer = make_model_optimizer(
    model=model,
    num_training_steps=10000,
    num_warmup_steps=500,
    lr=1e-5,
)

# Training loop
for step, batch in enumerate(dataloader):
    batch = {k: v.cuda() for k, v in batch.items()}

    optimizer.zero_grad()
    outputs = model.step(
        num_chunks=4,
        input_ids=batch["input_ids"],
        attention_mask=batch["attention_mask"],
        position_ids=batch["position_ids"],
        labels=batch["labels"],
    )
    optimizer.step()

    if DMM.is_global_rank0 and step % 10 == 0:
        loss = outputs.loss.sum().item() if outputs.loss is not None else 0
        DMM.log_rank0(f"Step {step}: loss={loss:.4f}")

# Cleanup
dist.destroy_process_group()
```

Launch with torchrun:

```bash
torchrun --nproc_per_node=8 train.py
```