Retrieved article excerpt
Open article · Retrieved 2026-11-23T22:23:45.968444+00:00
layerpool
# layerpool
### Pool your devices. Train bigger models for free.
One model, split by layers across all your machines. Their memory is pooled, and they train it as one.
[PyPI](https://pypi.org/project/layerpool/) [Python](https://pypi.org/project/layerpool/) [License: MIT](https://github.com/abdallah-swe/layerpool/blob/main/LICENSE)
[A model too big to train on any single machine is split by its layers across a gaming PC, a desktop, a laptop and a cloud GPU, and they train it together. When the laptop drops out, the others take over its layers.](https://raw.githubusercontent.com/abdallah-swe/layerpool/main/docs/demo.webp)
| 💻 Laptop | 🖥️ Desktop | 🎮 Gaming PC | ☁️ Cloud GPU | | ⚡ Your pool |
| --- | --- | --- | --- | --- | --- |
| 16 GB | 24 GB | 12 GB | 16 GB | **=** | **68 GB** |
## Your code doesn't change
```
import layerpool.hf as lp
from transformers import Trainer
model = lp.AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-14B") # spread over all your devices
Trainer(model=model, args=args, train_dataset=data).train() # everything else stays the same
```
## How it works
Your computer runs the training code and keeps the embeddings and the output head. The devices, any number of GPUs, Macs or CPUs, hold consecutive layers. Activations go forward from device to device, the last device's output comes back for the loss, and gradients go back the same way.
- Your computer runs your training code and keeps the parts of the model around its repeated blocks: the embeddings, the
output head, and any image or audio encoder.
- The blocks are split across the devices in order. In each step, activations go from device to device and gradients come back.
- Every device downloads only the weights of its own blocks, and the split follows each device's memory and measured speed.
- Devices keep checkpoints of their part. If one drops out, the others take over its blocks and redo the lost steps from
those checkpoints, so no training is lost.
## Features
- **Any hardware, mixed.** NVIDIA GPUs, Apple Silicon (with MLX or PyTorch) and plain CPUs, on Linux, Windows and macOS, in one model.
- **Full control of each device.** Its memory cap, which of its GPUs to use, how many layers it takes, its place in the chain,
and RAM for layers that do not fit its GPU. Or leave everything to layerpool.
- **Over the internet.** Devices on the same network talk directly; the rest join through a cloudflared tunnel, with a token on
every connection. No port forwarding.
- **Survives disconnects.** If a device drops out, the others take over its layers and training goes on.
- **Balances itself.** Faster devices get more layers, the split adjusts while training runs, and a device that only slows
the run down sits it out.
- **Live dashboard.** Devices, memory, temperature, speed and loss, with every setting in reach.
- **Any model in transformers.** Text, vision-language, speech, embedding, mixture-of-experts and Mamba models: Llama, Qwen,
Gemma, Mistral, Phi, Mixtral, SmolVLM, Whisper, T5, BERT and others. Before the first run of an architecture, layerpool
checks that its split computes the same as the whole model, and stops with a clear message if it does not.
- **Every kind of training.** LoRA, QLoRA, full fine-tuning, training from scratch, DPO, KTO and other preference methods,
reinforcement learning, or your own loss.
## Quickstart
**1. Install and start the pool** on your computer:
```
pip install layerpool
layerpool up
```
The dashboard opens, and your computer joins as the first device.
**2. Add devices.** Click **Add device** and run the command it gives you on each device:
```
pip install -U layerpool
layerpool join http://192.168.1.8:7341 --token inv_...
```
**3. Train.** Run your usual training script on your computer. It finds the pool by itself.
To check first whether a model fits the devices you have, and how it would be split: `layerpool plan Qwen/Qwen3-14B`.
For devices outside your network, start the pool with `layerpool up --tunnel`.
**Requirements.** Python 3.11 or newer on Linux, Windows or an Apple Silicon Mac, with NVIDIA or AMD (ROCm) GPUs, Apple Silicon or
plain CPUs.
- NVIDIA GPU on Windows: install the CUDA build of [PyTorch](https://pytorch.org/get-started/locally/) first.
- AMD GPU: install the ROCm build of [PyTorch](https://pytorch.org/get-started/locally/) first.
- Linux machine without a GPU: `pip install torch --index-url https://download.pytorch.org/whl/cpu` first saves a 3 GB download.
## Use it your way
**Hugging Face Trainer and TRL**
```
import layerpool.hf as lp
from trl import SFTTrainer, SFTConfig
model = lp.AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-8B", lora_r=16)
trainer = SFTTrainer(model=model, args=SFTConfig(output_dir="out"), train_dataset=dataset)
trainer.train()
model.save_pretrained("my-adapter")
```
Works with `transformers.Trainer` and TRL's `SFTTrainer`, `DPOTrainer` and `KTOTrainer`, including gradient accumulation,
evaluation, checkpoints, resuming and `load_best_model_at_end`. Install the extras with `pip install "layerpool[hf]"`.
Every `AutoModel` class works the same way:
```
vision = lp.AutoModelForImageTextToText.from_pretrained("HuggingFaceTB/SmolVLM-256M-Instruct")
speech = lp.AutoModelForSpeechSeq2Seq.from_pretrained("openai/whisper-small")
embedder = lp.AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
```
**Your own PyTorch loop**
```
import torch
import layerpool.hf as lp
model = lp.AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-8B", lora_r=16)
opt = torch.optim.AdamW(model.parameters(), lr=1e-4)
for batch in loader:
loss = model(input_ids=batch["input_ids"], labels=batch["labels"]).loss
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
opt.zero_grad()
```
**Any loss you can write**
Your loss gets the log-probability of every token:
```
import layerpool
from layerpool import losses
pool = layerpool.connect()
run = pool.run("Qwen/Qwen3-8B", rank=16, lr=1e-4)
def my_loss(logprobs, mask, data):
return losses.cross_entropy(logprobs, mask)
for ids, labels in batches:
run.forward_backward(ids, labels, loss=my_loss)
run.optim_step(max_grad_norm=1.0)
run.save("my-adapter")
```
Built in: `cross_entropy`, `dpo`, `ipo`, `simpo`, `orpo`, `policy_gradient`.
**No code at all**
```
layerpool train --model Qwen/Qwen3-8B --data data.jsonl --method sft --epochs 1 --out my-adapter
```
`--method` also takes `cpt`, `dpo`, `ipo`, `simpo` and `orpo`. In Python the same loop is `run.train("data.jsonl", method="sft")`.
## What you can train
| Method | How |
| --- | --- |
| LoRA | `lora_r=16` |
| QLoRA | load a checkpoint already quantized to 4 bits with bitsandbytes, such as unsloth's `...-bnb-4bit` models. Macs train their layers on an MLX 4-bit copy: for unsloth's models they find the `mlx-community` one by themselves, for others add `mlx_model=`. The two 4-bit formats round the frozen weights a little differently |
| Full fine-tuning | `full=True` |
| From scratch | `full=True, random_init=True` |
| Continued pretraining | plain text, or `method="cpt"` |
| DPO, KTO, IPO, SimPO, ORPO | TRL `DPOTrainer` or `KTOTrainer`, or `method="dpo"`, `"ipo"`, `"simpo"`, `"orpo"` |
| Reinforcement learning | `losses.policy_gradient` |
| Classification with a new head | `lp.AutoModelForSequenceClassification.from_pretrained(model, num_labels=3)` |
| Also train modules outside the blocks | `modules_to_save=["embed_tokens"]`, as in PEFT |
| Resume | `trainer.train(resume_from_checkpoint=...)`, or `model.load_adapter(folder)` |
Text, vision, speech and embedding models all work: anything in transformers built from a stack of repeated blocks.
## Settings
Everything has a sensible default, and everything can be changed. Pass these to `from_pretrained` (or to `pool.run`):
| Setting | Default | What it does |
| --- | --- | --- |
| `lora_r`, `lora_alpha` | `16`, `2 × lora_r` | LoRA rank and scale (`rank`, `alpha` in `pool.run`) |
| `target_modules` | every linear layer | the layers LoRA goes on, as in PEFT: `["q_proj", "v_proj"]` |
| `full=True` | off | train every weight instead of LoRA (`mode="full"` in `pool.run`) |
| `modules_to_save` | none | modules around the blocks to train in full in a LoRA run, as in PEFT |
| `dtype` | `"auto"` | how your computer holds its part (embeddings, output head, encoders): `"auto"` uses `bfloat16` when nothing there is trained and a GPU is present, which halves its memory; or `"float32"`, `"bfloat16"`, `"float16"` |
| `codec` | `"fp16"` | how activations travel between devices: `"fp16"`, `"int8"` (half the size, for slow links, but less accurate, most of all on Gemma), or `"fp32"` (exact) |
| `micro` / `micro_batch_size` | `8` / none | how many pieces each batch is cut into, so all devices work at once; or the rows per piece |
| `seq` | `512` | the longest sequence you train on, for planning memory |
| `checkpointing` | `True` | activation checkpointing: devices recompute activations instead of keeping them, for less memory at the cost of recomputing each block's forward pass |
| `ckpt_every` | `4` | steps between the recovery checkpoints devices keep, so a lost device costs at most this many steps |
| `peer_replicas` | `"auto"` | each device also keeps a copy of a neighbour's checkpoint: `"auto"` (devices over the internet), `"always"`, `"never"` |
| `rebalance` | `True` | move layers to faster devices as training runs (it counts each device's compute and its network) |
| `check` | `True` | before the first run of an architecture, split a small copy of it and compare with the whole copy, so a model layerpool cannot split correctly stops with a clear message instead of training wrong |
| `expected_steps` | from the Trainer | how long the run is, so rebalancing knows when a move pays off; the Trainer and the built-in loops tell it themselves |
| `streams` | `3` | parallel connections between neighbouring devices |
| `lr`, `schedule`, `warmup`, `weight_decay` | `1e-4`, `"cosine"`, `0`, `0` | for `pool.run`: the built-in loops follow the schedule; in your own loop pass `lr=run.schedule(step, total)` to `optim_step`; with a Trainer, its own optimizer and scheduler set them |
Each device has its own settings too, in the dashboard, with `layerpool set DEVICE`, or when it joins (`layerpool join URL ...`):
| Setting | What it does |
| --- | --- |
| `--cap-gb 8` | the most memory layerpool may use there: GPU memory on a machine with NVIDIA or AMD GPUs (all the GPUs it trains on together), the shared memory on a Mac, RAM on a computer that trains on its CPU. Default: what it can spare (about 92% of each GPU, 60% of a Mac's memory, half the RAM) |
| `--gpu-cap 0=6,1=10` | on a machine with several GPUs, the most memory of each one, in GB |
| `--gpus 0,2` | on a machine with several GPUs, the ones to train on (default: all) |
| `--ram-cap 12` | on a machine with GPUs, GB of RAM it may also use for layers that do not fit its GPUs; its CPU runs those, more slowly, so layerpool gives it only as many as pay off (default: off) |
| `--layers 8` | how many of the model's layers it takes: a count, a share (`30%`) or a range of counts (`4-10`: between 4 and 10 layers). Default: as many as suit its memory and measured speed |
| `--order 0` | its place in the chain of devices, lower first. Default: layerpool picks |
| `--name laptop` | how it shows up |
| `pause` / `resume` / `remove` | stop using it, use it again, take it out |
When joining only: `--backend torch` or `mlx` on a Mac, `--cpu` to leave its GPU alone, and `--allow-sleep` to let the computer
sleep (by default a device stays awake while it is in a pool, since a sleeping one looks gone; closing a laptop's lid still
sleeps it). While a run trains, `layerpool rebalance off` keeps the split as it is, `on` lets layerpool move layers to faster
devices, and `now` splits again; a setting no split could meet is refused with the reason,