Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 24 additions & 64 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,79 +28,36 @@ This installs the `dengine` package along with its dependencies (PyTorch, torchv

The [`examples/`](./examples) directory contains runnable projects. The simplest is `examples/MNIST`, which trains a small CNN on MNIST over a Barabási–Albert graph using decentralized averaging.

A minimal experiment config looks like this:

```yaml
scenario:
target: This_Will_Be_Overwritten
arguments:
max_communication_rounds: 200

graph:
target: CustomNetworking

dataset:
train:
target: custom_mnist_train
test:
target: custom_mnist_test

partitioning:
target: custom_partitioning
arguments:
validation_percentage: .2

client:
target: CustomClient
training_engine:
target: CustomTrainingEngine
arguments:
epochs: 5
lr: 0.001
optimizer: SGD
training_batch_size: 128
validation_batch_size: 128
local_model:
target: CustomNet

callbacks:
- target: CustomCallback
arguments:
every_n_local_epochs: 5
```

You can also compose an experiment entirely from dEngine's built-in configs in code:

```python
import dengine
from dengine import load_experiment_from_yamls
from dengine import BUILTINS
from dengine.bin.simulation import run_simulation, SimulationArguments, VerbosityLevel
from dengine.config.utils import convert_to_nested_dict

args = SimulationArguments(
gpus=[0],
dataset_directory="datasets/",
output_directory="logs/",
dump_stdout=False,
resume_checkpoints=False,
sanity_check=False,
cfg = dengine.load_experiment_from_yamls(
[
BUILTINS.CORE.GRAPH.BA_SMALL,
BUILTINS.CORE.PARTITIONING.IID,
BUILTINS.CORE.DATASETS.MNIST,
BUILTINS.CORE.CLIENT.CLIENT_DECAVG_ADAM,
BUILTINS.CORE.SCENARIOS.DECENTRALIZED_HOMOGENOUS,
],
experiments_directory_root="logs/",
seed=123,
torch_num_threads=1,
verbosity=VerbosityLevel.info,
)

cfg = load_experiment_from_yamls(
[
dengine.BUILTINS.CORE.GRAPH.BA_SMALL,
dengine.BUILTINS.CORE.PARTITIONING.IID,
dengine.BUILTINS.CORE.DATASETS.MNIST,
dengine.BUILTINS.CORE.SCENARIOS.DECENTRALIZED_HOMOGENOUS,
],
experiments_directory_root=str(args.output_directory),
overrides=convert_to_nested_dict({"client.training_engine.arguments.epochs": 10}),
seed=args.seed,
# Tweak the loaded config directly
cfg.client.local_model.target = "CNNMnist"
cfg.client.training_engine.arguments.update(
epochs=5, training_batch_size=32, validation_batch_size=128,
)

args = SimulationArguments(
gpus=[0], dataset_directory="datasets/", output_directory="logs/",
dump_stdout=False, resume_checkpoints=False, sanity_check=False,
seed=123, torch_num_threads=1, verbosity=VerbosityLevel.info,
)
run_simulation(args, cfg)
```

Expand All @@ -119,6 +76,7 @@ More examples:
- [`examples/Scaffold`](./examples/Scaffold): the SCAFFOLD federated optimization algorithm.
- [`examples/GAN`](./examples/GAN): decentralized training of a generative model.
- [`examples/events`](./examples/events/): advanced events API and distributed runtime
- [`examples/LLMs`](./examples/LLMs): decentralized training of large language models (requires a GPU with at least 80 GB of memory, e.g. an A100 80GB).

## Project structure

Expand Down Expand Up @@ -155,8 +113,10 @@ dEngine ships with ready-to-use configs under [`configs/core`](./configs/core),

## Related projects

- [`dengine-uciml`](https://github.com/DecentralizedLearning/dengine-uciml) — extends dEngine with support for the UCI Machine Learning datasets.
- [`notebooks`](https://github.com/DecentralizedLearning/notebooks) — notebooks for visualizing and analyzing dEngine experiment results.
- [`dengine-uciml`](https://github.com/DecentralizedLearning/dengine-uciml): extends dEngine with support for the UCI Machine Learning Repository datasets.
- [`dengine-timm`](https://github.com/DecentralizedLearning/dengine-timm): extends dEngine with support for [timm](https://huggingface.co/timm) (PyTorch Image Models) architectures.
- [`dengine-vit-pytorch`](https://github.com/DecentralizedLearning/dengine-vit-pytorch): extends dEngine with support for the Vision Transformer models from [vit-pytorch](https://github.com/lucidrains/vit-pytorch).
- [`notebooks`](https://github.com/DecentralizedLearning/notebooks): notebooks for visualizing and analyzing dEngine experiment results.

## License

Expand Down
2 changes: 1 addition & 1 deletion dengine/dataset/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .dataset import SupervisedDataset
from .dataset import SupervisedDataset, NamedSupervisedDatasetCollection
from . import (
mnist,
emnist,
Expand Down
40 changes: 36 additions & 4 deletions dengine/dataset/dataset.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Tuple, Any, List, Optional
from typing import Tuple, Any, List, Optional, Dict
import threading
from dataclasses import dataclass

Expand Down Expand Up @@ -52,7 +52,7 @@ def cache(self):
if self._cache_needs_rebuild:
data, targets = self.data, self.targets
samples = torch.stack([self._process_img(img) for img in data])
labels = [self._process_target(int(t)) for t in targets.tolist()]
labels = [self._process_target(t) for t in targets.tolist()]
self._cache = _Cache(data, targets, samples, labels)
return (self._cache.samples, self._cache.labels)

Expand All @@ -61,7 +61,7 @@ def _process_img(self, img: Tensor) -> Any:
img = self.transform(img)
return img

def _process_target(self, target: int) -> Any:
def _process_target(self, target: Tensor) -> Any:
if self.target_transform is not None:
target = self.target_transform(target)
return target
Expand All @@ -78,7 +78,7 @@ def __getitem__(self, index: int) -> Tuple[Any, Any]:
samples, labels = self.cache
return samples[index], labels[index]

img, target = self.data[index], int(self.targets[index])
img, target = self.data[index], self.targets[index]
return self._process_img(img), self._process_target(target)

def __len__(self) -> int:
Expand All @@ -93,3 +93,35 @@ def __getstate__(self):
def __setstate__(self, state):
self.__dict__.update(state)
self._cache_lock = threading.Lock()


class NamedSupervisedDatasetCollection(SupervisedDataset):
def __init__(
self,
datasets: Dict[str, SupervisedDataset]
):
self._datasets = datasets

def __len__(self) -> int:
return sum([len(x) for x in self._datasets.values()])

def __getitem__(self, index: int) -> Tuple[Any, Any]:
length = len(self)
if index < 0:
index += length
if not 0 <= index < length:
raise IndexError(
f"Index {index} out of range for dataset of length {length}"
)

for dataset in self._datasets.values():
if index < len(dataset):
return dataset[index]
index -= len(dataset)

raise IndexError(index) # unreachable if lengths are consistent

@property
def targets(self) -> Tensor:
lengths = torch.tensor([len(d) for d in self._datasets.values()])
return torch.repeat_interleave(torch.arange(len(lengths)), lengths)
29 changes: 29 additions & 0 deletions examples/LLMs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# LLMs example

Decentralized LoRA fine-tuning of a small LLM (`Qwen/Qwen3-0.6B`) across 5 clients.

| Setting | Value |
|---------------|---------------------------------------------------|
| Model | `Qwen/Qwen3-0.6B` + LoRA (`r=8`, on `q_proj`/`v_proj`) |
| Topology | Barabási–Albert (`n=50`, `m=1`) |
| Aggregation | DecAvg, 200 communication rounds |
| Partitioning | IID (5% validation split) |
| Data | Mix of 10 instruction datasets (finance, medical, SQL, cybersecurity, science) |

Only the LoRA adapter weights are trained and exchanged between clients, so each round shares a few MB per client instead of the full model.

## Running

> Needs a GPU with **at least 80 GB** of memory (e.g. A100 80GB).

Run from this directory (`examples/LLMs`), so dEngine picks up the local `dengine_llm` package:

```bash
pip install -r requirements.txt

TORCH_CUDNN_BENCHMARK=True \
TORCH_CUDNN_DETERMINISTIC=False \
PYTHON_GIL=0 \
HF_TOKEN="<your_token_goes_here>" \
dengine-simulate --config config.yml
```
1 change: 1 addition & 0 deletions examples/LLMs/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .dengine_llm import *
53 changes: 53 additions & 0 deletions examples/LLMs/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
EXPERIMENT_VERSION: '1'
callbacks:
- arguments: null
target: LossDumpCallback
client:
arguments:
include_myself: false
use_weighted_avg: false
local_model:
arguments:
model_name: Qwen/Qwen3-0.6B
target: HF_Transformers_LLM
target: DecAvgClient
training_engine:
arguments:
gradient_accumulation_steps: 2
training_batch_size: 16
validation_batch_size: 16
epochs: 1
lr: 0.0004
target: HF_Transformers_LLM_TrainingEngine
dataset:
postprocessing: null
test:
arguments:
train: false
use_cache: true
tokenizer_pretrained_model_name_or_path: Qwen/Qwen3-0.6B
target: load_domain_instruction_mix_tiny
train:
arguments:
train: true
use_cache: true
tokenizer_pretrained_model_name_or_path: Qwen/Qwen3-0.6B
target: load_domain_instruction_mix_tiny
graph:
arguments:
m: 1
n: 5
nx_class: barabasi_albert_graph
seed: 123
target: NXGraph
partitioning:
arguments:
validation_percentage: 0.05
target: random_iid_balanced
scenario:
arguments:
common_init: true
max_communication_rounds: 200
num_parallel_clients: 5
target: VanillaDecentralizedSynch
seed: 123
3 changes: 3 additions & 0 deletions examples/LLMs/dengine_llm/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .datasets import *
from .training_engine import *
from .models import *
Loading
Loading