Llm finetuning

LLM fine-tuning with SPDL data loading pipeline.

Fine-tunes LLaMA 3.2 1B on Alpaca-style instruction data using LoRA, with SPDL PipelineBuilder for high-performance concurrent tokenization.

SPDL Data Pipeline

The core of this example is the SPDL data loading pipeline:

  1. DistributedRandomSampler – distributes sample indices across ranks with per-epoch reshuffling

  2. pipe(tokenize, concurrency=N) – concurrent Alpaca-format prompt formatting and tokenization

  3. aggregate(batch_size) – groups into batches

  4. pipe(collate) – stacks tensors

  5. add_sink(buffer_size=3) – prefetch buffer for the training loop

Data

Download instruction-following datasets:

# https://github.com/tatsu-lab/stanford_alpaca
python download_alpaca.py --output /tmp/alpaca.jsonl
# https://huggingface.co/datasets/databricks/databricks-dolly-15k
python download_dolly.py --output /tmp/dolly.jsonl

Data format (JSONL with Alpaca-style fields):

{"instruction": "Explain what a linked list is.", "input": "", "output": "A linked list is..."}

Usage

torchrun \
  --nproc_per_node 8 \
  -m spdl.examples.llm_finetune.llm_finetuning \
  --model-path /path/to/Llama-3.2-1B-Instruct \
  --data-path \
    /tmp/alpaca.jsonl \
    /tmp/dolly.jsonl

With the default settings (global batch size 8x32), the training throughput reaches roughly ~570 samples on H100 GPUs.

Source

Source

Click here to see the source.
  1# Copyright (c) Meta Platforms, Inc. and affiliates.
  2# All rights reserved.
  3#
  4# This source code is licensed under the BSD-style license found in the
  5# LICENSE file in the root directory of this source tree.
  6
  7"""LLM fine-tuning with SPDL data loading pipeline.
  8
  9Fine-tunes LLaMA 3.2 1B on Alpaca-style instruction data using LoRA,
 10with SPDL PipelineBuilder for high-performance concurrent tokenization.
 11
 12SPDL Data Pipeline
 13^^^^^^^^^^^^^^^^^^
 14
 15The core of this example is the SPDL data loading pipeline:
 16
 171. ``DistributedRandomSampler`` -- distributes sample indices across ranks
 18   with per-epoch reshuffling
 192. ``pipe(tokenize, concurrency=N)`` -- concurrent Alpaca-format prompt
 20   formatting and tokenization
 213. ``aggregate(batch_size)`` -- groups into batches
 224. ``pipe(collate)`` -- stacks tensors
 235. ``add_sink(buffer_size=3)`` -- prefetch buffer for the training loop
 24
 25Data
 26^^^^
 27
 28Download instruction-following datasets::
 29
 30    # https://github.com/tatsu-lab/stanford_alpaca
 31    python download_alpaca.py --output /tmp/alpaca.jsonl
 32    # https://huggingface.co/datasets/databricks/databricks-dolly-15k
 33    python download_dolly.py --output /tmp/dolly.jsonl
 34
 35Data format (JSONL with Alpaca-style fields)::
 36
 37    {"instruction": "Explain what a linked list is.", "input": "", "output": "A linked list is..."}
 38
 39Usage
 40^^^^^
 41
 42::
 43
 44    torchrun \\
 45      --nproc_per_node 8 \\
 46      -m spdl.examples.llm_finetune.llm_finetuning \\
 47      --model-path /path/to/Llama-3.2-1B-Instruct \\
 48      --data-path \\
 49        /tmp/alpaca.jsonl \\
 50        /tmp/dolly.jsonl
 51
 52With the default settings (global batch size 8x32), the training throughput reaches roughly ~570
 53samples on H100 GPUs.
 54"""
 55
 56from __future__ import annotations
 57
 58__all__ = [
 59    "build_model",
 60    "build_pytorch_dataloader",
 61    "build_spdl_dataloader",
 62    "load_data",
 63    "main",
 64    "train",
 65]
 66
 67
 68import argparse
 69import logging
 70import os
 71import time
 72from collections.abc import Callable
 73from datetime import timedelta
 74from pathlib import Path
 75from typing import TYPE_CHECKING
 76
 77import torch
 78import torch.distributed as dist
 79from torch.nn.parallel import DistributedDataParallel as DDP
 80
 81if TYPE_CHECKING:
 82    from peft import PeftModel
 83
 84try:
 85    from examples.llm_finetune.utils.dataloader import (  # pyre-ignore[21]
 86        build_pytorch_dataloader,
 87    )
 88    from examples.llm_finetune.utils.pipeline import (  # pyre-ignore[21]
 89        build_spdl_dataloader,
 90    )
 91    from examples.llm_finetune.utils.utils import (  # pyre-ignore[21]
 92        load_data,
 93        report_progress,
 94        resolve_model_path,
 95    )
 96except ImportError:
 97    from spdl.examples.llm_finetune.utils.dataloader import (  # type: ignore[import-not-found, no-redef]
 98        build_pytorch_dataloader,
 99    )
100    from spdl.examples.llm_finetune.utils.pipeline import (  # type: ignore[import-not-found, no-redef]
101        build_spdl_dataloader,
102    )
103    from spdl.examples.llm_finetune.utils.utils import (  # type: ignore[import-not-found, no-redef]
104        load_data,
105        report_progress,
106        resolve_model_path,
107    )
108
109_LG: logging.Logger = logging.getLogger(__name__)
110
111
112# ---------------------------------------------------------------------------
113# Model setup
114# ---------------------------------------------------------------------------
115
116
117def build_model(
118    model_path: str,
119    device: torch.device,
120    lora_r: int,
121    lora_alpha: int,
122    lora_dropout: float,
123) -> "PeftModel":
124    """Load LLaMA model and apply LoRA."""
125    from peft import get_peft_model, LoraConfig, TaskType
126    from transformers import AutoModelForCausalLM
127
128    _LG.info("Loading model from %s", model_path)
129    base_model = AutoModelForCausalLM.from_pretrained(
130        model_path,
131        torch_dtype=torch.bfloat16,
132        attn_implementation="sdpa",
133    )
134
135    lora_config = LoraConfig(
136        task_type=TaskType.CAUSAL_LM,
137        r=lora_r,
138        lora_alpha=lora_alpha,
139        lora_dropout=lora_dropout,
140        target_modules=["q_proj", "v_proj"],
141    )
142    model = get_peft_model(base_model, lora_config)
143    model.print_trainable_parameters()
144
145    model = model.to(device)
146    return model
147
148
149# ---------------------------------------------------------------------------
150# Training
151# ---------------------------------------------------------------------------
152
153
154def train(
155    *,
156    model_path: str,
157    data_path: list[str],
158    output_dir: str,
159    max_seq_len: int,
160    batch_size: int,
161    num_epochs: int,
162    lr: float,
163    weight_decay: float,
164    max_grad_norm: float,
165    log_interval: int,
166    lora_r: int,
167    lora_alpha: int,
168    lora_dropout: float,
169    num_workers: int,
170    dataloader: str = "spdl",
171    mp_context: str = "forkserver",
172    progress_fn: Callable[[int, int], None] | None = None,
173) -> None:
174    """Main training function, called per-rank."""
175    if dist.is_initialized():
176        rank = dist.get_rank()
177        world_size = dist.get_world_size()
178    else:
179        rank = 0
180        world_size = 1
181    local_rank: int = int(os.environ.get("LOCAL_RANK", 0))
182    if torch.cuda.is_available():
183        device = torch.device(f"cuda:{local_rank}")
184        torch.cuda.set_device(device)
185    else:
186        device = torch.device("cpu")
187
188    _LG.info(
189        "Rank %d/%d on device %s (dataloader=%s)",
190        rank,
191        world_size,
192        device,
193        dataloader,
194    )
195
196    # --- Data ---
197    samples = load_data(data_path)
198
199    from transformers import AutoTokenizer
200
201    tokenizer = AutoTokenizer.from_pretrained(model_path)
202    if tokenizer.pad_token is None:
203        tokenizer.pad_token = tokenizer.eos_token
204
205    # --- Model ---
206    model = build_model(
207        model_path,
208        device,
209        lora_r=lora_r,
210        lora_alpha=lora_alpha,
211        lora_dropout=lora_dropout,
212    )
213    ddp_model: torch.nn.Module
214    if dist.is_initialized():
215        ddp_model = DDP(
216            model,
217            device_ids=[local_rank] if torch.cuda.is_available() else None,
218        )
219    else:
220        ddp_model = model
221
222    # --- Optimizer ---
223    optimizer = torch.optim.AdamW(
224        ddp_model.parameters(),
225        lr=lr,
226        weight_decay=weight_decay,
227        foreach=True,
228    )
229
230    num_steps_per_epoch = len(samples) // (batch_size * world_size)
231    total_steps = num_steps_per_epoch * num_epochs
232    if rank == 0:
233        _LG.info(
234            "Training: %d samples, %d epochs, %d steps/epoch, %d total steps",
235            len(samples),
236            num_epochs,
237            num_steps_per_epoch,
238            total_steps,
239        )
240        if progress_fn is not None:
241            progress_fn(0, total_steps)
242
243    scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
244        optimizer,
245        T_max=total_steps,
246        eta_min=lr * 0.1,
247    )
248
249    # --- Build data source ---
250    if dataloader == "pytorch":
251        dl = build_pytorch_dataloader(
252            samples=samples,
253            tokenizer=tokenizer,
254            max_seq_len=max_seq_len,
255            batch_size=batch_size,
256            rank=rank,
257            world_size=world_size,
258            num_workers=num_workers,
259            mp_context=mp_context,
260            device=device,
261        )
262    else:
263        dl = build_spdl_dataloader(
264            samples=samples,
265            tokenizer=tokenizer,
266            max_seq_len=max_seq_len,
267            batch_size=batch_size,
268            rank=rank,
269            world_size=world_size,
270            num_threads=num_workers,
271            mp_context=mp_context,
272        )
273
274    # --- Training loop ---
275    global_step = 0
276    ddp_model.train()
277
278    for epoch in range(num_epochs):
279        _LG.info("Epoch %d/%d", epoch + 1, num_epochs)
280
281        t0 = time.monotonic()
282        epoch_loss = 0.0
283        num_batches = 0
284
285        for batch in dl:
286            outputs = ddp_model(
287                input_ids=batch["input_ids"],
288                attention_mask=batch["attention_mask"],
289                labels=batch["labels"],
290            )
291            loss = outputs.loss
292
293            loss.backward()
294            torch.nn.utils.clip_grad_norm_(ddp_model.parameters(), max_grad_norm)
295            optimizer.step()
296            scheduler.step()
297            optimizer.zero_grad()
298
299            epoch_loss += loss.item()
300            num_batches += 1
301            global_step += 1
302
303            if rank == 0:
304                if progress_fn is not None:
305                    progress_fn(global_step, total_steps)
306                if global_step % log_interval == 0:
307                    avg_loss = epoch_loss / num_batches
308                    elapsed = time.monotonic() - t0
309                    _LG.info(
310                        "Step %d | loss=%.4f | lr=%.2e | %.1f samples/s",
311                        global_step,
312                        avg_loss,
313                        scheduler.get_last_lr()[0],
314                        num_batches * batch_size * world_size / elapsed,
315                    )
316
317        elapsed = time.monotonic() - t0
318        if rank == 0:
319            avg_loss = epoch_loss / max(num_batches, 1)
320            _LG.info(
321                "Epoch %d complete | avg_loss=%.4f | %.1fs | %.1f samples/s",
322                epoch + 1,
323                avg_loss,
324                elapsed,
325                num_batches * batch_size * world_size / elapsed,
326            )
327
328    # --- Save ---
329    if rank == 0 and output_dir:
330        output_path = Path(output_dir)
331        output_path.mkdir(parents=True, exist_ok=True)
332        model.save_pretrained(output_path)  # type: ignore[arg-type]
333        tokenizer.save_pretrained(output_path)
334        _LG.info("Model saved to %s", output_path)
335
336
337def parse_args() -> argparse.Namespace:
338    parser = argparse.ArgumentParser(description=__doc__)
339    # Model
340    parser.add_argument(
341        "--model-path",
342        type=str,
343        required=True,
344        help="Path to pretrained LLaMA model directory",
345    )
346    parser.add_argument(
347        "--output-dir",
348        type=str,
349        default="",
350        help="Directory to save fine-tuned LoRA weights",
351    )
352    # Data
353    parser.add_argument(
354        "--data-path",
355        type=str,
356        nargs="+",
357        required=True,
358        help="One or more paths to Alpaca-format JSONL files (local or manifold://).",
359    )
360    parser.add_argument("--max-seq-len", type=int, default=512)
361    # Training
362    parser.add_argument("--batch-size", type=int, default=4)
363    parser.add_argument("--num-epochs", type=int, default=10)
364    parser.add_argument("--lr", type=float, default=5e-4)
365    parser.add_argument("--weight-decay", type=float, default=0.01)
366    parser.add_argument("--max-grad-norm", type=float, default=1.0)
367    parser.add_argument("--log-interval", type=int, default=10)
368    # LoRA
369    parser.add_argument("--lora-r", type=int, default=8)
370    parser.add_argument("--lora-alpha", type=int, default=16)
371    parser.add_argument("--lora-dropout", type=float, default=0.05)
372    # Pipeline
373    parser.add_argument(
374        "--num-workers",
375        type=int,
376        default=8,
377        help="Concurrent tokenization workers in the data pipeline",
378    )
379    parser.add_argument(
380        "--dataloader",
381        type=str,
382        choices=["spdl", "pytorch"],
383        default="spdl",
384        help="Data loading backend: 'spdl' (default) or 'pytorch' (torch DataLoader)",
385    )
386    parser.add_argument(
387        "--mp-context",
388        type=str,
389        choices=["fork", "spawn", "forkserver"],
390        default="forkserver",
391        help="Multiprocessing context for workers (default: forkserver)",
392    )
393    return parser.parse_args()
394
395
396def init_logging() -> None:
397    """Initialize logging."""
398    rank = os.environ.get("RANK", "?")
399    logging.basicConfig(
400        level=logging.INFO,
401        format=f"%(asctime)s [%(levelname).1s] [Rank{rank}] %(name)s: %(message)s",
402    )
403
404
405def main(args: argparse.Namespace) -> None:
406    use_distributed = "RANK" in os.environ
407    if use_distributed:
408        backend = "nccl" if torch.cuda.is_available() else "gloo"
409        dist.init_process_group(backend=backend, timeout=timedelta(minutes=3))
410    try:
411        train(
412            model_path=resolve_model_path(args.model_path),
413            data_path=args.data_path,
414            output_dir=args.output_dir,
415            max_seq_len=args.max_seq_len,
416            batch_size=args.batch_size,
417            num_epochs=args.num_epochs,
418            lr=args.lr,
419            weight_decay=args.weight_decay,
420            max_grad_norm=args.max_grad_norm,
421            log_interval=args.log_interval,
422            lora_r=args.lora_r,
423            lora_alpha=args.lora_alpha,
424            lora_dropout=args.lora_dropout,
425            num_workers=args.num_workers,
426            dataloader=args.dataloader,
427            mp_context=args.mp_context,
428            progress_fn=report_progress,
429        )
430    finally:
431        if use_distributed:
432            dist.destroy_process_group()
433
434
435if __name__ == "__main__":
436    init_logging()
437    main(parse_args())

API Reference

Functions

build_model(model_path: str, device: torch.device, lora_r: int, lora_alpha: int, lora_dropout: float) → PeftModel[source]

Load LLaMA model and apply LoRA.

build_pytorch_dataloader(samples: list[dict[str, str]], tokenizer: PreTrainedTokenizerBase, max_seq_len: int, batch_size: int, rank: int, world_size: int, num_workers: int, mp_context: str = 'forkserver', device: torch.device | None = None) → _TDataLoader[source]

Build a reusable PyTorch DataLoader for distributed LLM fine-tuning.

Build once before the training loop and reuse across epochs. The returned wrapper automatically calls DistributedSampler.set_epoch on each iteration, so no manual set_epoch call is needed. Similarly, yielded batches are automatically transferred to the given device, if any, so no manual to(device) call is needed.

build_spdl_dataloader(samples: list[dict[str, str]], tokenizer: PreTrainedTokenizerBase, max_seq_len: int, batch_size: int, rank: int, world_size: int, num_threads: int, mp_context: str = 'forkserver') → _TDataLoader[source]

Build a reusable SPDL data loader with nested pipeline architecture.

Creates two nested pipelines to separate CPU-bound data loading from GPU transfer, reducing the noisy-neighbour effect where data loading threads in the main process compete with the training loop for CPU time, delaying GPU kernel launches.

Inner pipeline (runs in a subprocess):

Sampling → lookup → tokenize (concurrent) → aggregate → collate. All CPU work runs in a dedicated subprocess with its own thread pool, completely isolating it from the training process. The subprocess is created once and reused across epochs — each for ... in call rebuilds the pipeline inside the same subprocess.

Outer pipeline (runs in the main process):

Receives CPU batches from the subprocess via IPC queue and transfers them to GPU using transfer_tensor_h2d with a dedicated single-thread executor. This ensures GPU transfer uses a consistent CUDA stream and overlaps with training computation.

Build once before the training loop and iterate each epoch:

dataloader = build_spdl_dataloader(samples, tokenizer, ...)
for epoch in range(num_epochs):
    for batch in dataloader:
        train(batch)
load_data(paths: Sequence[str]) → list[dict[str, str]][source]

Load and concatenate data from one or more JSONL files.

main(args: Namespace) → None[source]
train(*, model_path: str, data_path: list[str], output_dir: str, max_seq_len: int, batch_size: int, num_epochs: int, lr: float, weight_decay: float, max_grad_norm: float, log_interval: int, lora_r: int, lora_alpha: int, lora_dropout: float, num_workers: int, dataloader: str = 'spdl', mp_context: str = 'forkserver', progress_fn: Callable[[int, int], None] | None = None) → None[source]

Main training function, called per-rank.