import tempfile
from pathlib import Path
import jammi
import numpy as np
from jammi_cookbook import fixtures
from jammi_cookbook.claims import claim
MODEL = fixtures.model("tiny_bert")
PAIRS = fixtures.url("tiny_pairs.csv")
PROBES = ["quantum error correction methods", "protein folding with transformers",
"graph kernels for chemistry", "solid electrolyte interphase control"]
def engine(local_ranks: int):
"""An embedded engine whose worker runs `local_ranks` ranks, all on the CPU."""
home = Path(tempfile.mkdtemp())
(home / "jammi.toml").write_text(
f"[gpu]\ndevice = -1\n\n[worker]\nlocal_ranks = {local_ranks}\n")
db = jammi.connect(f"file://{home / 'engine'}", config=str(home / "jammi.toml"))
db.add_source("pairs", url=PAIRS, format="csv")
return db
def train(db, world_size: int, batch_size: int):
"""Fine-tune the tiny encoder on the scored pairs; return the loss curve and
the adapted model's embedding of every probe."""
job = db.fine_tune(
source="pairs", base_model=MODEL, columns=["text_a", "text_b", "score"],
method="lora", task="text_embedding", epochs=3, batch_size=batch_size,
lora_dropout=0.0, validation_fraction=0.0, early_stopping_metric="train_loss",
seed=0, world_size=world_size,
)
job.wait()
curve = [point["loss"] for point in job.metrics()["train_loss_curve"]]
vectors = np.asarray([db.encode_query(model=job.output_model_id, query=p) for p in PROBES])
return np.asarray(curve), vectors31 One job, many ranks — distributed training as a gang
Verbs: fine_tune(world_size=…) · [worker] local_ranks · [distributed] max_world_size · [server] peer_bind / peer_advertise · list_workers · Background: data-parallel training — each rank computes gradients on its shard of a global batch and the ranks sum them, so N ranks take the step one process would take over the whole batch (Li et al. 2020) · Checked: measurement (a gang’s training compared with one process’s over the same global batch, loss by loss and vector by vector).
A training job names a world_size: how many ranks train it together. The ranks are a gang — scheduled as one unit, failing as one unit. Every step, the gang splits a global batch of world_size × batch_size rows across its ranks; each rank encodes its shard, the ranks gather each other’s representations so every rank computes the same global loss (a contrastive loss needs every row’s negatives, not only its own shard’s), and the adapter gradients are summed before one shared optimizer step. So a gang is not an approximation of one process: it is one process’s step, computed by N.
This chapter measures exactly that claim. A gang runs where the engine’s worker places it:
- in one process, one rank per accelerator —
[worker] local_ranksranks on[gpu] devices, or every rank on the CPU when the CPU is the only device; - across processes, when a job is wider than one host: the claiming worker becomes rank 0 of a peer gang and assembles the other ranks from its fleet (
[distributed] max_world_sizebounds how wide).
Both run below, over the same rows, and each is measured against one process.
31.1 One process, three rank counts, one global batch
Three runs over the same 30 scored pairs, each with a global batch of six rows: one rank taking six, two ranks taking three each, three ranks taking two each. Dropout is off (lora_dropout = 0): with it on, every rank draws its own dropout mask, which is correct training but not the same arithmetic as one process’s mask.
runs = {}
for world_size, batch_size in [(1, 6), (2, 3), (3, 2)]:
db = engine(local_ranks=world_size)
runs[world_size] = train(db, world_size, batch_size)
db.close()
curve, _ = runs[world_size]
print(f"world_size={world_size} batch_size={batch_size} loss by epoch "
+ " ".join(f"{x:.6f}" for x in curve))
reference_curve, reference_vectors = runs[1]
for world_size in (2, 3):
curve, vectors = runs[world_size]
print(f"{world_size} ranks vs 1: max |Δ loss| {np.abs(curve - reference_curve).max():.2e}"
f" max |Δ embedding| {np.abs(vectors - reference_vectors).max():.2e}")2026-10-03T07:42:12.851004Z WARN jammi_kernels::admission: fused-kernel domain check failed; falling back to the eager composition op="attention_block_fused" predicate="head_dim_is_attention_block_fixed_head_dim"
world_size=1 batch_size=6 loss by epoch 3.620628 3.598928 3.589128
world_size=2 batch_size=3 loss by epoch 3.620628 3.598928 3.589128
world_size=3 batch_size=2 loss by epoch 3.620628 3.598928 3.589128
2 ranks vs 1: max |Δ loss| 1.91e-07 max |Δ embedding| 3.73e-09
3 ranks vs 1: max |Δ loss| 9.54e-08 max |Δ embedding| 7.45e-09
for world_size in (2, 3):
curve, vectors = runs[world_size]
loss_diff = float(np.abs(curve - reference_curve).max())
embedding_diff = float(np.abs(vectors - reference_vectors).max())
claim(f"a gang of {world_size} trains the single process's loss curve and embeddings",
loss_diff < 1e-6 and embedding_diff < 1e-6,
f"largest difference {max(loss_diff, embedding_diff):.1e}")✓ a gang of 2 trains the single process's loss curve and embeddings (largest difference 1.9e-07)
✓ a gang of 3 trains the single process's loss curve and embeddings (largest difference 9.5e-08)
The loss curves and the adapted model’s embeddings agree across rank counts: the gang computes one process’s step. What the ranks buy is capacity — each holds a third, or a half, of the global batch’s activations — not a different optimisation.
31.2 A fleet: servers sharing one catalog
A gang wider than one process needs processes that can find each other, and that is what a shared catalog is: every jammi-server pointed at the same Postgres sees the same queued jobs, and each one that runs the claim loop registers itself as a worker the others can list. (The SQLite catalog the sections above ran on is one process’s by contract.) Postgres comes from pip here, and each server is a real process on its own ports; a result root on the local disk is shared because the fleet is one host — a fleet across hosts roots it in an object store instead.
import socket
import pgserver
from jammi.testing import LiveServer
postgres = pgserver.get_server(tempfile.mkdtemp(), cleanup_mode="stop")
def catalog(name: str) -> str:
"""A fresh database on the chapter's Postgres: the catalog one fleet shares.
pgserver listens on a Unix socket; its URI is libpq's socket form, which the
catalog reads as handed out."""
postgres.psql(f"CREATE DATABASE {name};")
return postgres.get_uri(name)
def free_port() -> int:
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
return probe.getsockname()[1]
def member(catalog_url: str, result_root: str, roles: str, label: str) -> LiveServer:
"""A `jammi-server` of the fleet: the shared catalog and result root, the CPU,
a short lease, and the `roles` that make this process what it is. `label` is
the name `list_workers` reports it under (`JAMMI_WORKER_ID`)."""
home = Path(tempfile.mkdtemp())
(home / "jammi.toml").write_text(f"""
[gpu]
device = -1
[catalog.postgres]
url = "{catalog_url}"
pool_size = 4
[storage]
result_root = "{result_root}"
[lease]
duration_secs = 6
heartbeat_secs = 2
{roles}""")
return LiveServer(home / "engine",
env={"JAMMI_CONFIG": str(home / "jammi.toml"), "JAMMI_WORKER_ID": label})
def workers(db) -> dict:
"""Each worker process's instance id, by its label."""
return {w["label"]: w["instance_id"] for w in db.list_workers()}/__w/jammi-ai/jammi-ai/.venv/lib64/python3.12/site-packages/platformdirs/api.py:459: RuntimeDirWarning: XDG_RUNTIME_DIR is not set, falling back to /tmp/runtime-0
return Path(self.user_runtime_dir)
A job’s listing says where it ran: claimed_by names the instance that holds (or last held) its claim, and ranks the instance that ran each rank of its training attempt, in rank order — the ids list_workers reports.
31.3 Across processes: a peer gang
Two servers, one rank each ([worker] local_ranks = 1), both advertising a gang listener (peer_bind / peer_advertise), and a deployment bound of two ranks ([distributed] max_world_size = 2). A two-rank job fits neither process alone: the server that claims it becomes rank 0 of a peer gang and dials the other for rank 1. The job is submitted over the wire, like any client’s.
peer_catalog = catalog("peer")
peer_root = Path(tempfile.mkdtemp()).as_uri()
def gang_member(label: str) -> LiveServer:
port = free_port()
return member(peer_catalog, peer_root, label=label, roles=f"""
[worker]
enabled = true
kinds = ["fine_tune"]
local_ranks = 1
idle_poll_secs = 1
[distributed]
max_world_size = 2
[server]
peer_bind = "127.0.0.1:{port}"
peer_advertise = "127.0.0.1:{port}"
""")
with (gang_member("first") as first, gang_member("second") as second,
jammi.connect(first.endpoint) as db):
fleet = workers(db)
db.add_source("pairs", url=PAIRS, format="csv")
runs["peer"] = train(db, world_size=2, batch_size=3)
(peer_job,) = db.list_jobs()
label_of = {instance: label for label, instance in fleet.items()}
print(f"{len(fleet)} workers on the shared catalog, one rank each")
print("the job's ranks ran on: "
+ ", ".join(f"rank {r} → {label_of[i]}" for r, i in enumerate(peer_job["ranks"])))
curve, vectors = runs["peer"]
print("peer gang loss by epoch " + " ".join(f"{x:.6f}" for x in curve))
print(f"peer gang vs 1 rank: max |Δ loss| {np.abs(curve - reference_curve).max():.2e}"
f" max |Δ embedding| {np.abs(vectors - reference_vectors).max():.2e}")2 workers on the shared catalog, one rank each
the job's ranks ran on: rank 0 → first, rank 1 → second
peer gang loss by epoch 3.620628 3.598928 3.589128
peer gang vs 1 rank: max |Δ loss| 1.91e-07 max |Δ embedding| 3.73e-09
claim("the gang spans both servers: one rank on each, rank 0 on the claimant",
len(fleet) == 2 and sorted(peer_job["ranks"]) == sorted(fleet.values())
and peer_job["claimed_by"] == peer_job["ranks"][0])
curve, vectors = runs["peer"]
peer_diff = max(float(np.abs(curve - reference_curve).max()),
float(np.abs(vectors - reference_vectors).max()))
claim("and trains what the single process trains", peer_diff < 1e-6,
f"largest difference {peer_diff:.1e}")
postgres.cleanup()✓ the gang spans both servers: one rank on each, rank 0 on the claimant
✓ and trains what the single process trains (largest difference 1.9e-07)
The ranks now live in different processes, and the gradients cross a socket, not shared memory, and the step is still one process’s: two places a gang ran — one process, and two processes dialling each other — and one step computed in each.
31.4 What a gang refuses
Two objectives exist only for one process — GradCache (cached=True), whose second pass runs over the whole batch on one rank, and hard-negative mining, which searches one process’s own index. A gang would not compute them, so the engine refuses the combination at submit rather than training something else. So does a rank count wider than any gang the deployment can form.
from jammi.errors import InvalidArgument
db = engine(local_ranks=2)
refusals = {}
for label, kwargs in [
("GradCache", dict(world_size=2, cached=True)),
("hard-negative mining", dict(world_size=2, mine_hard_negatives=True)),
("three ranks on a two-rank host", dict(world_size=3)),
]:
try:
db.fine_tune(source="pairs", base_model=MODEL, columns=["text_a", "text_b", "score"],
method="lora", task="text_embedding", epochs=1, **kwargs)
refusals[label] = None
except InvalidArgument as refused:
refusals[label] = str(refused)
print(f"{label}: {refusals[label]}")
db.close()GradCache: Configuration error: world_size = 2 cannot be combined with GradCache (`cached`): the cached objective's second pass is over the WHOLE batch on one rank, so a gang would not compute the objective this config asks for
hard-negative mining: Configuration error: world_size = 2 cannot be combined with hard-negative mining (`hard_negatives.mine`): the miner retrieves from this process's own index, so each rank would mine a different negative pool
three ranks on a two-rank host: Configuration error: world_size = 3 exceeds the serveable world of 2 (the wider of [worker] local_ranks and [distributed] max_world_size): raise local_ranks for a gang on this host's devices, max_world_size on every coordinator for a gang across the fleet, or submit a smaller rank count
claim("every layout the hosts cannot serve is refused", all(refusals.values()))
claim("and the refusal names the world the hosts can serve",
"serveable world of 2" in refusals["three ranks on a two-rank host"])✓ every layout the hosts cannot serve is refused
✓ and the refusal names the world the hosts can serve
Each refusal names the knob that would change the answer.